Skip to content

Commit 1bffb4d

Browse files
vmorozalexfernandez
authored andcommitted
node-api: run finalizers directly from GC
PR-URL: nodejs#42651 Reviewed-By: Gabriel Schulhof <gabrielschulhof@gmail.com> Reviewed-By: Michael Dawson <midawson@redhat.com>
1 parent 6813c3e commit 1bffb4d

10 files changed

+477
-40
lines changed

doc/api/n-api.md

+36
Original file line numberDiff line numberDiff line change
@@ -5428,6 +5428,42 @@ invocation. If it is deleted before then, then the finalize callback may never
54285428
be invoked. Therefore, when obtaining a reference a finalize callback is also
54295429
required in order to enable correct disposal of the reference.
54305430

5431+
#### `node_api_post_finalizer`
5432+
5433+
<!-- YAML
5434+
added: REPLACEME
5435+
-->
5436+
5437+
> Stability: 1 - Experimental
5438+
5439+
```c
5440+
napi_status node_api_post_finalizer(napi_env env,
5441+
napi_finalize finalize_cb,
5442+
void* finalize_data,
5443+
void* finalize_hint);
5444+
```
5445+
5446+
* `[in] env`: The environment that the API is invoked under.
5447+
* `[in] finalize_cb`: Native callback that will be used to free the
5448+
native data when the JavaScript object has been garbage-collected.
5449+
[`napi_finalize`][] provides more details.
5450+
* `[in] finalize_data`: Optional data to be passed to `finalize_cb`.
5451+
* `[in] finalize_hint`: Optional contextual hint that is passed to the
5452+
finalize callback.
5453+
5454+
Returns `napi_ok` if the API succeeded.
5455+
5456+
Schedules a `napi_finalize` callback to be called asynchronously in the
5457+
event loop.
5458+
5459+
Normally, finalizers are called while the GC (garbage collector) collects
5460+
objects. At that point calling any Node-API that may cause changes in the GC
5461+
state will be disabled and will crash Node.js.
5462+
5463+
`node_api_post_finalizer` helps to work around this limitation by allowing the
5464+
add-on to defer calls to such Node-APIs to a point in time outside of the GC
5465+
finalization.
5466+
54315467
## Simple asynchronous operations
54325468

54335469
Addon modules often need to leverage async helpers from libuv as part of their

src/js_native_api.h

+10
Original file line numberDiff line numberDiff line change
@@ -517,6 +517,16 @@ NAPI_EXTERN napi_status NAPI_CDECL napi_add_finalizer(napi_env env,
517517

518518
#endif // NAPI_VERSION >= 5
519519

520+
#ifdef NAPI_EXPERIMENTAL
521+
522+
NAPI_EXTERN napi_status NAPI_CDECL
523+
node_api_post_finalizer(napi_env env,
524+
napi_finalize finalize_cb,
525+
void* finalize_data,
526+
void* finalize_hint);
527+
528+
#endif // NAPI_EXPERIMENTAL
529+
520530
#if NAPI_VERSION >= 6
521531

522532
// BigInt

0 commit comments

Comments
 (0)