Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

node-api: run finalizers directly from GC #42651

Closed
wants to merge 10 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions doc/api/n-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -5428,6 +5428,42 @@ invocation. If it is deleted before then, then the finalize callback may never
be invoked. Therefore, when obtaining a reference a finalize callback is also
required in order to enable correct disposal of the reference.

#### `node_api_post_finalizer`

<!-- YAML
added: REPLACEME
-->

> Stability: 1 - Experimental

```c
napi_status node_api_post_finalizer(napi_env env,
napi_finalize finalize_cb,
void* finalize_data,
void* finalize_hint);
```

* `[in] env`: The environment that the API is invoked under.
* `[in] finalize_cb`: Native callback that will be used to free the
native data when the JavaScript object has been garbage-collected.
[`napi_finalize`][] provides more details.
* `[in] finalize_data`: Optional data to be passed to `finalize_cb`.
* `[in] finalize_hint`: Optional contextual hint that is passed to the
finalize callback.

Returns `napi_ok` if the API succeeded.

Schedules a `napi_finalize` callback to be called asynchronously in the
event loop.

Normally, finalizers are called while the GC (garbage collector) collects
objects. At that point calling any Node-API that may cause changes in the GC
state will be disabled and will crash Node.js.

`node_api_post_finalizer` helps to work around this limitation by allowing the
add-on to defer calls to such Node-APIs to a point in time outside of the GC
finalization.

## Simple asynchronous operations

Addon modules often need to leverage async helpers from libuv as part of their
Expand Down
10 changes: 10 additions & 0 deletions src/js_native_api.h
Original file line number Diff line number Diff line change
Expand Up @@ -517,6 +517,16 @@ NAPI_EXTERN napi_status NAPI_CDECL napi_add_finalizer(napi_env env,

#endif // NAPI_VERSION >= 5

#ifdef NAPI_EXPERIMENTAL

NAPI_EXTERN napi_status NAPI_CDECL
node_api_post_finalizer(napi_env env,
napi_finalize finalize_cb,
void* finalize_data,
void* finalize_hint);

#endif // NAPI_EXPERIMENTAL

#if NAPI_VERSION >= 6

// BigInt
Expand Down
Loading