node-api: segregate nogc APIs from rest via type system

We define a new type called `node_api_nogc_env` as the `const` version
of `napi_env` and `node_api_nogc_finalize` as a variant of
`napi_finalize` that accepts a `node_api_nogc_env` as its first
argument.

We then modify those APIs which do not affect GC state as accepting a
`node_api_nogc_env`. APIs accepting finalizer callbacks are modified to
accept `node_api_nogc_finalize` callbacks. Thus, the only way to attach
a `napi_finalize` callback, wherein Node-APIs affecting GC state may be
called is to call `node_api_post_finalizer` from a
`node_api_nogc_finalize` callback.

In keeping with the process of introducing new Node-APIs, this feature
is guarded by `NAPI_EXPERIMENTAL`. Since this feature modifies APIs
already marked as stable, it is additionally guared by
`NODE_API_EXPERIMENTAL_NOGC_ENV`, so as to provide a further buffer to
adoption. Nevertheless, both guards must be removed upon releasing a
new version of Node-API.

PR-URL: https://github.com/nodejs/node/pull/50060
Reviewed-By: Chengzhong Wu <legendecas@gmail.com>
Reviewed-By: Vladimir Morozov <vmorozov@microsoft.com>
Reviewed-By: Michael Dawson <midawson@redhat.com>
This commit is contained in:
Gabriel Schulhof authored and RafaelGSS committed 2024-01-02 15:05:23 -03:00
1 parent c96ef6533c
commit b2135ae7dc
16 files changed
+368 -146

No files matched your search

@@ -4,12 +4,12 @@
static uint32_t finalizeCount = 0;
static void FreeData(napi_env env, void* data, void* hint) {
NODE_API_ASSERT_RETURN_VOID(env, data != NULL, "Expects non-NULL data.");
static void FreeData(node_api_nogc_env env, void* data, void* hint) {
NODE_API_NOGC_ASSERT_RETURN_VOID(data != NULL, "Expects non-NULL data.");
free(data);
}
static void Finalize(napi_env env, void* data, void* hint) {
static void Finalize(node_api_nogc_env env, void* data, void* hint) {
++finalizeCount;
}
@@ -61,7 +61,7 @@ static napi_value ToUInt32Value(napi_env env, uint32_t value) {
static napi_status InitRefArray(napi_env env) {
// valueRefs array has one entry per napi_valuetype
napi_ref* valueRefs = malloc(sizeof(napi_ref) * ((int)napi_bigint + 1));
return napi_set_instance_data(env, valueRefs, &FreeData, NULL);
return napi_set_instance_data(env, valueRefs, (napi_finalize)&FreeData, NULL);
}
static napi_value CreateExternal(napi_env env, napi_callback_info info) {