[Rule] When argv in napi_get_cb_info is not nullptr, the length of argv must be greater than or equal to argc.
If argv is not nullptr, the arguments actually passed by JS will be copied to argv in napi_get_cb_info based on the value of argc. If there are more arguments than the provided count, only the requested number of arguments are copied. If there are fewer arguments provided than the claimed, the rest of argv is filled with values that represent undefined.
Incorrect example
static napi_value IncorrectDemo1(napi_env env, napi_callback_info info) {
// The `argc` is not properly initialized, resulting in an indeterminate random value, which may cause the length of `argv` to be less than the number declared by `argc`, leading to data overrun.
size_t argc;
napi_value argv[10] = {nullptr};
napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
return nullptr;
}
static napi_value IncorrectDemo2(napi_env env, napi_callback_info info) {
// The number of declared argc exceeds the actual length initialized by argv, causing the napi_get_cb_info interface to write out-of-bounds data when writing to argv.
size_t argc = 5;
napi_value argv[3] = {nullptr};
napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
return nullptr;
} Correct example:
static napi_value GetArgvDemo1(napi_env env, napi_callback_info info) {
size_t argc = 0;
// Argv passes null ptr to obtain the true number of parameters passed in
napi_get_cb_info(env, info, &argc, nullptr, nullptr, nullptr);
// JS input parameter is 0, do not execute subsequent logic
if (argc == 0) {
return nullptr;
}
// Create an array to retrieve the parameters passed in JS
napi_value *argv = new napi_value[argc];
napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
// Business code
// ... ...
// The object created by argv for new is manually released after use
delete[] argv;
return nullptr;
}
static napi_value GetArgvDemo2(napi_env env, napi_callback_info info) {
size_t argc = 2;
napi_value argv[2] = {nullptr};
// Napi_get_cf_info will write argc JS parameters or undefined to argv
napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
// Business code
// ... ...
return nullptr;
} [Rule] Properly use napi_open_handle_scope and napi_close_handle_scope to minimize the lifecycle of napi_value and avoid memory leaks.
Each napi_value has a specific HandleScope. HandleScope is opened through napi_open_handle_scope and closed through napi_close_handle_scope. After HandleScope is closed, napi_value is automatically released.
Correct example:
static void OpenHandleScope(napi_env env, napi_callback_info info) {
/**
* When frequently calling the Napi interface to create JS objects in a for loop, handle_scope should be added to
* promptly release resources that are no longer in use.
* In the following example, at the end of each loop, the lifecycle of the local variable res has ended.
* Therefore, adding scope to release its held JS objects in a timely manner to prevent memory leakage.
*/
for (int i = 0; i < 100000; i++) {
napi_handle_scope scope = nullptr;
napi_status status = napi_open_handle_scope(env, &scope);
if (status != napi_ok) {
return;
}
napi_value res;
napi_create_object(env, &res);
napi_close_handle_scope(env, scope);
}
} [Rule] Do not use Node-API to access JS objects across engine instances.
An engine instance is an independent running environment. Operations such as creating and accessing a JS object must be performed in the same engine instance. If an object is operated in different JSVM instances, the app may crash. An engine instance is represented as a value of napi_env in APIs.
Incorrect example:
// Thread 1 executes, creating a string object in env1 with the value "bar".
napi_create_string_utf8(env1, "bar", NAPI_AUTO_LENGTH, &string);
// Thread 2 executes, creates an object in env2, and sets the aforementioned string object into the object.
napi_status status = napi_create_object(env2, &object);
if (status != napi_ok) {
napi_throw_error(env, ...);
return;
}
status = napi_set_named_property(env2, object, "foo", string);
if (status != napi_ok) {
napi_throw_error(env, ...);
return;
} JS objects belong to a specific napi_env. Therefore, you cannot set an object of env1 to an object of env2. If the object of env1 is accessed in env2, the app may crash.
[Suggestion] Any exception occurred in a Node-API call should be handled in a timely manner. Otherwise, unexpected behavior may occur.
Correct example:
static void ErroHandle(napi_env env, napi_callback_info info) {
napi_value object, string;
// 1.create object
napi_status status = napi_create_object(env, &object);
if (status != napi_ok) {
napi_throw_error(env, "ERROR: ", "...");
return;
}
// 2.Create attribute values
status = napi_create_string_utf8(env, "bar", NAPI_AUTO_LENGTH, &string);
if (status != napi_ok) {
napi_throw_error(env, "ERROR: ", "...");
return;
}
// 3.Set the result of step 2 to the value of the object property foo
status = napi_set_named_property(env, object, "foo", string);
if (status != napi_ok) {
napi_throw_error(env, "ERROR: ", "...");
return;
}
} In this example, if an exception occurs in step 1 or step 2, step 3 will not be performed. Step 3 will be performed only when napi_ok is returned in steps 1 and 2.
[Rule] When the uv_queue_work method is called to throw a work to a JS thread for execution, use napi_handle_scope to manage the lifecycle of napi_value created by the JS callback.
The Node-API framework will not be used when the uv_queue_work method is called. In this case, you must use napi_handle_scope to manage the lifecycle of napi_value.
Correct example:
void callbackTest(CallbackContext* context)
{
uv_loop_s* loop = nullptr;
napi_get_uv_event_loop(context->env, &loop);
uv_work_t* work = new uv_work_t;
context->retData = 1;
work->data = (void*)context;
uv_queue_work(
loop, work,
// Please note that uv_queue-work will create a thread and execute the callback function. If developers only
// want to throw tasks to JS threads, it is not recommended to use uv_queue-work to avoid redundant thread
// creation
[](uv_work_t* work) {
// Execute some business logic
},
// This callback will be executed on the JS thread where the loop is located
[](uv_work_t* work, int status) {
CallbackContext* context = (CallbackContext*)work->data;
napi_handle_scope scope = nullptr;
napi_status scope_status = napi_open_handle_scope(context->env, &scope);
if (scope_status != napi_ok) {
if (work != nullptr) {
delete work;
}
return;
}
napi_value callback = nullptr;
napi_get_reference_value(context->env, context->callbackRef, &callback);
napi_value retArg;
napi_create_int32(context->env, context->retData, &retArg);
napi_value ret;
napi_call_function(context->env, nullptr, callback, 1, &retArg, &ret);
napi_delete_reference(context->env, context->callbackRef);
napi_close_handle_scope(context->env, scope);
if (work != nullptr) {
delete work;
}
delete context;
}
);
} [Rule] If the value of the last parameter result is not nullptr in napi_wrap(), use napi_remove_wrap() at a proper time to delete the created napi_ref.
The napi_wrap interface is defined as follows:
napi_wrap(napi_env env, napi_value js_object, void* native_object, napi_finalize finalize_cb, void* finalize_hint, napi_ref* result)
When the last parameter result is not null, the Node-API framework creates an napi_ref object pointing to js_object. You need to manage the lifecycle of js_object. Specifically, use napi_remove_wrap to delete napi_ref at a proper time so that the garbage collector (GC) can release js_object and trigger the destructor finalize_cb bound to the C++ object native_object.
You can directly pass in nullptr for the last parameter result.
Correct example:
void NapiWrapTest(napi_env env, napi_callback_info info) {
napi_value jsobject, nativeObject;
napi_finalize cb;
// Usage 1: Napi_rap does not need to receive the created napi_ref, and the last parameter is passed as nulliptr.
// The created napi_ref is a weak reference, managed by the system, and does not require manual release by the user
napi_wrap(env, jsobject, nativeObject, cb, nullptr, nullptr);
// Usage 2: napi_rap needs to receive the created napi_ref, the last parameter is not null ptr, and the returned
// napi_ref is a strong reference that needs to be manually released by the user, otherwise it will cause memory
// leakage
napi_ref result;
napi_wrap(env, jsobject, nativeObject, cb, nullptr, &result);
// When js_order and result are no longer used in the future, promptly call napi_remove-wrap to release result
void *nativeObjectResult = nullptr;
napi_remove_wrap(env, jsobject, &nativeObjectResult);
} [Suggestion] Use ArrayBuffer instead of JSArray to store value-type data for higher performance.
JSArray is used as a container to store data and supports almost all JS data types.
When napi_set_element is used to store value-type data (such as int32) in JSArray, interaction with the runtime is involved, which causes unnecessary overhead.
The operations on ArrayBuffer are performed in the buffer, which delivers higher performance than using napi_set_element to operate JSArray.
You are advised to use the ArrayBuffer object created by napi_create_arraybuffer in this scenario.
Example:
// The following code uses a regular JSArray as a container, but it only stores data of type int32.
// But because it is a JS object, it can only be modified using the napi method, resulting in lower performance.
static napi_value ArrayDemo(napi_env env, napi_callback_info info)
{
constexpr size_t arrSize = 1000;
napi_value jsArr = nullptr;
napi_create_array(env, &jsArr);
for (int i = 0; i < arrSize; i++) {
napi_value arrValue = nullptr;
napi_create_int32(env, i, &arrValue);
// Conventional JSArray uses napi method to read and write arrays, which results in poor performance.
napi_set_element(env, jsArr, i, arrValue);
}
return jsArr;
}
// Recommended writing style:
// Taking int32 type data as an example, but the following code uses an ArrayBuffer as the container.
// Therefore, C/C++methods can be used to directly modify the buffer.
static napi_value ArrayBufferDemo(napi_env env, napi_callback_info info)
{
constexpr size_t arrSize = 1000;
napi_value arrBuffer = nullptr;
void* data = nullptr;
napi_create_arraybuffer(env, arrSize * sizeof(int32_t), &data, &arrBuffer);
// Data is a null pointer, cancel writing to data
if (data == nullptr) {
return arrBuffer;
}
int32_t* i32Buffer = reinterpret_cast<int32_t*>(data);
for (int i = 0; i < arrSize; i++) {
// ArrayBuffer directly modifies the buffer, skipping runtime,
// Equivalent in performance to manipulating C/C++objects
i32Buffer[i] = i;
}
return arrBuffer;
} napi_create_arraybuffer is equivalent to newArrayBuffer(size) in JS. The object generated cannot be directly read in TS/JS. It can be read or written only after being encapsulated into a TypedArray or DataView object.
Benchmark performance test result:
The following data is the accumulated data written in thousands of cycles. To more clearly reflect the difference, the core frequency of the device has been limited.
Container Types | Benchmark Data (us) |
|---|---|
JSArray | 1566.174 |
ArrayBuffer | 3.609 |
[Suggestion] Minimize the number of data conversions and avoid unnecessary replication.
Rules
Add "static" to the function corresponding to nm_register_func to prevent conflicts with symbols in other .so files.
The module registration entry, that is, the name of the function decorated by __attribute__((constructor)) must be different from that of other modules.
The .nm_modname field must completely match the module name and is case sensitive.
Incorrect example:
In the following incorrect example, the module name is nativerender.
EXTERN_C_START
napi_value Init(napi_env env, napi_value exports)
{
// ...
return exports;
}
EXTERN_C_END
static napi_module nativeModule = {
.nm_version = 1,
.nm_flags = 0,
.nm_filename = nullptr,
// The function corresponding to nm_register_func was not marked as static.
.nm_register_func = Init,
// In the module implementation, if the.nm_modname field does not fully match the module name, it may cause module loading failures in multi-threaded scenarios.
.nm_modname = "entry",
.nm_priv = nullptr,
.reserved = { 0 },
};
// The entry function name for module registration is RegisterModule, which is prone to conflict with other modules.
extern "C" __attribute__((constructor)) void RegisterModule()
{
napi_module_register(&nativeModule);
} Correct example:
In the following correct example, the module name is nativerender.
EXTERN_C_START
static napi_value Init(napi_env env, napi_value exports)
{
// ...
return exports;
}
EXTERN_C_END
static napi_module demoModule = {
.nm_version = 1,
.nm_flags = 0,
.nm_filename = nullptr,
.nm_register_func = Init,
.nm_modname = "nativerender",
.nm_priv = ((void*)0),
.reserved = { 0 },
};
extern "C" __attribute__((constructor)) void RegisterNativerenderModule(void)
{
napi_module_register(&demoModule);
} [Rule] The JS object created by napi_create_external APIs can be passed and used only in the calling thread. If it is passed across threads (for example, using post_message of the worker interface), the app may crash. If a JS object bound with a native object needs to be passed across threads, use napi_coerce_to_native_binding_object.
Incorrect example:
static void MyFinalizeCB(napi_env env, void *finalize_data, void *finalize_hint) { return; };
static napi_value CreateMyExternal(napi_env env, napi_callback_info info) {
napi_value result = nullptr;
napi_create_external(env, nullptr, MyFinalizeCB, nullptr, &result);
return result;
}
// The code for module registration has been omitted here; you may need to register the CreateMyExternal method yourself. // index.d.ts
export const createMyExternal: () => Object;
// Application Code
import testNapi from 'libentry.so';
import { worker } from '@kit.ArkTS';
const mWorker = new worker.ThreadWorker('../workers/Worker');
{
const mExternalObj = testNapi.createMyExternal();
mWorker.postMessage(mExternalObj);
}
// Close the worker thread.
// The application may crash at this step or during subsequent garbage collection by the engine.
mWorker.terminate();
// The implementation of Worker is a default template, omitted here. [Rule] The parameter data in certain APIs, such as napi_get_arraybuffer_info, cannot be released manually. Its lifecycle is managed by the engine.
The following uses napi_get_arraybuffer_info as an example to describe the interface definition:
napi_get_arraybuffer_info(napi_env env, napi_value arraybuffer, void** data, size_t* byte_length)
The parameter data specifies the buffer header pointer to ArrayBuffer. This buffer can be read and written in the given range but cannot be released. The buffer memory is managed by the ArrayBuffer Allocator in the engine and is automatically released with the lifecycle of the JS object ArrayBuffer.
Incorrect example:
void* arrayBufferPtr = nullptr; napi_value arrayBuffer = nullptr; size_t createBufferSize = ARRAY_BUFFER_SIZE; napi_status verification = napi_create_arraybuffer(env, createBufferSize, &arrayBufferPtr, &arrayBuffer); size_t arrayBufferSize; napi_status result = napi_get_arraybuffer_info(env, arrayBuffer, &arrayBufferPtr, &arrayBufferSize); delete arrayBufferPtr; // This step is prohibited. The lifecycle of the created arrayBufferPtr is managed by the engine, and users are not allowed to delete it themselves. Otherwise, it may lead to double free.
Applicable APIs |
|---|
napi_create_arraybuffer |
napi_create_sendable_arraybuffer |
napi_get_arraybuffer_info |
napi_create_buffer |
napi_get_buffer_info |
napi_get_typedarray_info |
napi_get_dataview_info |
[Suggestion] Properly use napi_object_freeze and napi_object_seal.
napi_object_freeze is equivalent to Object.freeze. After an object is frozen, its properties cannot be changed. napi_object_seal is equivalent to Object.seal. After an object is sealed, no properties can be added or deleted, but the property values can still be modified. The main difference is that the property values can be modified after an object is sealed, but not after it is frozen.
When using the preceding semantics, ensure that the constraints meet the requirements. If the semantics are violated in strict mode (default), an error will be thrown.