1# Node-API FAQs 2 3## What should I do when "undefined/not callable" or specific error message is reported for xxx after "import xxx from libxxx.so" is executed? 4 51. Check whether the module name in the .cpp file used in module registration is the same as that in the .so file name. 6 If the module name is **entry**, the .so file name must be **libentry.so**, and the **nm_modname** field in **napi_module** must be **entry**. The module names must be of the same case. 7 82. Check whether the .so file is successfully loaded. 9 Check the logs related to module loading during the application startup. Search for the keyword "dlopen" and check for error information. Generally, a loading failure is caused when the file to be loaded does not exist or is in a blocklist or the application does not have the required permission. In multi-thread scenarios (such as worker threads and taskpool), check whether **nm_modname** is the same as the module name. The module names must be of the same case. 10 113. Check whether the dependency .so files are successfully loaded. 12 Check that all the dependency .so files are packaged into the application and the application has the permission to open them. 13 144. Check whether the module import mode matches the .so file path. 15 If the module is imported by using **import xxx from '\@ohos.yyy.zzz'**, you may find **libzzz.z.so** or **libzzz_napi.z.so** in **/system/lib/module/yyy** (for a 32-bit system) or **/system/lib64/module/yyy** (for a 64-bit system). If the .so file does not exist or the file names do not match, an error containing the keyword "dlopen" will be reported. 16 17 18 19| **Error Log**| **Solution**| 20| -------- | -------- | 21| module $SO is not allowed to load in restricted runtime. | The module, identified by **$SO**, is not allowed for the worker thread running in a restricted environment and cannot be loaded. You are advised to delete the module.| 22| module $SO is in blocklist, loading prohibited. | The module, identified by **$SO**, is in the blocklist due to the control of the widget or Extension, and cannot be loaded. You are advised to delete the module.| 23| load module failed. $ERRMSG. | The dynamic library fails to be loaded. **$ERRMSG** indicates the cause of the loading failure. Possible causes include the following:<br>- The .so file to be loaded does not exist.<br>- The dependency .so file does not exist. <br>- Undefined symbol is found. <br>Locate the cause based on the error message.| 24| try to load abc file from $FILEPATH failed. | You can load either a dynamic library or an .abc file. If this log information is displayed when you attempt to load a dynamic library, ignore this message. If it is displayed when you attempt to load an .abc file, the .abc file does not exist. **$FILEPATH** indicates the module path.| 25 265. If specific error message is reported, identify the fault based on the error message. 27 28| **Error message** | **Fault Analysis & Solution**| 29| -------- | -------- | 30| First attempt: $ERRMSG. | Loading the .so file with the module name of "xxx" fails. *$ERRMSG* indicates the error information.| 31| Second attempt: $ERRMSG. | Loading the .so file with the module name of "xxx_napi" fails. *$ERRMSG* indicates the error information.| 32| try to load abc file from xxx failed. | Loading the .abc file fails. *xxx* indicates the name of the .abc file.| 33| module xxx is not allowed to load in restricted runtime. | This module cannot be used in restricted runtime. *xxx* indicates the module name. You are advised to delete the module.| 34| module xxx is in blocklist, loading prohibited. | The module cannot be used in the current extension. *xxx* indicates the module name. You are advised to delete the module.| 35 36## What should I do when an unexpected value is returned by an API and "occur exception need return" is reported? 37 38Before the call is complete, some Node-API interfaces are checked for JavaScript (JS) exceptions in the VM. If an exception is detected, "occur exception need return" will be reported, with the line number of the code and the Node-API interface name. 39 40You can solve this problem as follows: 41 42- If the exception does not matter, clear the exception. 43 Call **napi_get_and_clear_last_exception** before "occur exception need return" is printed to clear the exception. 44 45- Throw the exception to the ArkTS layer for capture. 46 Throw the exception directly to the ArkTS layer without going through the native logic. 47 48## What are the differences between the lifecycle of napi_value and napi_ref? 49 50- **native_value** is managed by **HandleScope**. Generally, you do not need to add **HandleScope** for **native_value** (except for **complete callback** of **uv_queue_work**). 51 52- **napi_ref** must be deleted manually. 53 54## How do I locate the fault if the return value of a Node-API interface is not "napi_ok"? 55 56When a Node-API interface is successfully executed, **napi_ok** is returned. If the return value is not **napi_ok**, locate the fault as follows: 57 58- Check the result of the input parameter null check, which is performed first before a Node-API interface is executed. The code is as follows: 59 60 ```cpp 61 CHECK_ENV: null check for env. 62 CHECK_ARG: null check for other input parameters. 63 ``` 64 65- Check the result of the input parameter type check, which is performed for certain Node-API interfaces. For example, **napi_get_value_double** is used to obtain a C double value from a JS number, and the type of the JS value passed in must be number. The parameter type check is as follows: 66 67 ```cpp 68 RETURN_STATUS_IF_FALSE(env, nativeValue->TypeOf() == NATIVE_NUMBER, napi_number_expected); 69 ``` 70 71- Check the return value, which contains the verification result of certain interfaces. For example, **napi_call_function** is used to execute a JS function. If an exception occurs in the JS function, Node-API returns **napi_pending_exception**. 72 73 ```cpp 74 auto resultValue = engine->CallFunction(nativeRecv, nativeFunc, nativeArgv, argc); 75 RETURN_STATUS_IF_FALSE(env, resultValue != nullptr, napi_pending_exception) 76 ``` 77 78- Determine the status value returned, and analyze the situation in which the status value is returned. 79 80## What should I do if memory leaks when napi_threadsafe_function is used? 81 82When **napi_threadsafe_function** (**tsfn** for short) is used, **napi_acquire_threadsafe_function** is often called to change the reference count of **tsfn** to ensure that **tsfn** is not released unexpectedly. When all the **tsfn** calls are complete, **napi_release_threadsafe_function** should be called in **napi_tsfn_release** mode in a timely manner to ensure that the reference count returns to the value before **napi_acquire_threadsafe_function** is called. **tsfn** can be correctly released only when the reference count is **0**. 83 84When **env** is about to exit but the reference count of **tsfn** is not **0**, **napi_release_threadsafe_function** should be called in **napi_tsfn_abort** mode to ensure that **tsfn** is not held or used by **env** after **env** is released. If **env** continues to hold and use **tsfn** after exiting, the application may crash. 85 86The following code shows how to register **env_cleanup** to ensure that **tsfn** is no longer held by **env** after **env** exits. 87 88```cpp 89//napi_init.cpp 90#include <hilog/log.h> // To output logs, link libhilog_ndk.z.so. 91#include <thread> // Include the thread module to create and manage threads. 92#include <unistd.h> // Include unistd.h to suspend the execution of the calling thread. 93 94// Define the log domain and tag. 95#undef LOG_DOMAIN 96#undef LOG_TAG 97#define LOG_DOMAIN 0x2342 98#define LOG_TAG "MY_TSFN_DEMO" 99 100/* 101 To construct a scenario in which the env lifecycle is shorter than the native lifecycle, 102 the following uses worker, taskpool, and napi_create_ark_runtime 103 to create an ArkTS running environment for a worker thread and manually stop the thread in advance. 104*/ 105 106 107// Define a struct to simulate the scenario where tsfn is stored. 108class MyTsfnContext { 109public: 110// MyTsfnContext is constructed only in a JS thread because Node-API is used. 111MyTsfnContext(napi_env env, napi_value workName) { 112 // Register the env_cleanup_hook function. 113 napi_add_env_cleanup_hook(env, Cleanup, this); 114 // Create a thread-safe function. 115 if (napi_create_threadsafe_function(env, nullptr, nullptr, workName, 1, 1, this, 116 TsfnFinalize, this, TsfnCallJs, &tsfn_) != napi_ok) { 117 OH_LOG_INFO(LOG_APP, "tsfn is created failed"); 118 return; 119 }; 120}; 121 122~MyTsfnContext() { OH_LOG_INFO(LOG_APP, "MyTsfnContext is deconstructed"); }; 123 124napi_threadsafe_function GetTsfn() { 125 std::unique_lock<std::mutex> lock(mutex_); 126 return tsfn_; 127} 128 129bool Acquire() { 130 if (GetTsfn() == nullptr) { 131 return false; 132 }; 133 return (napi_acquire_threadsafe_function(GetTsfn()) == napi_ok); 134}; 135 136bool Release() { 137 if (GetTsfn() == nullptr) { 138 return false; 139 }; 140 return (napi_release_threadsafe_function(GetTsfn(), napi_tsfn_release) == napi_ok); 141}; 142 143bool Call(void *data) { 144 if (GetTsfn() == nullptr) { 145 return false; 146 }; 147 return (napi_call_threadsafe_function(GetTsfn(), data, napi_tsfn_blocking) == napi_ok); 148}; 149 150private: 151// Ensure correct read and write of tsfn by multiple threads. 152std::mutex mutex_; 153napi_threadsafe_function tsfn_ = nullptr; 154 155// Call napi_add_env_cleanup_hook. 156static void Cleanup(void *data) { 157 MyTsfnContext *that = reinterpret_cast<MyTsfnContext *>(data); 158 napi_threadsafe_function tsfn = that->GetTsfn(); 159 std::unique_lock<std::mutex> lock(that->mutex_); 160 that->tsfn_ = nullptr; 161 lock.unlock(); 162 OH_LOG_WARN(LOG_APP, "cleanup is called"); 163 napi_release_threadsafe_function(tsfn, napi_tsfn_abort); 164}; 165 166// Callback to be invoked when tsfn is released. 167static void TsfnFinalize(napi_env env, void *data, void *hint) { 168 MyTsfnContext *ctx = reinterpret_cast<MyTsfnContext *>(data); 169 OH_LOG_INFO(LOG_APP, "tsfn is released"); 170 napi_remove_env_cleanup_hook(env, MyTsfnContext::Cleanup, ctx); 171 // Cleanup releases the thread-safe function in advance. To avoid UAF, enable the caller to trigger the release. 172 if (ctx->GetTsfn() != nullptr) { 173 OH_LOG_INFO(LOG_APP, "ctx is released"); 174 delete ctx; 175 } 176}; 177 178// Callback sent by tsfn to the JS thread for execution. 179static void TsfnCallJs(napi_env env, napi_value func, void *context, void *data) { 180 MyTsfnContext *ctx = reinterpret_cast<MyTsfnContext *>(context); 181 char *str = reinterpret_cast<char *>(data); 182 OH_LOG_INFO(LOG_APP, "tsfn is called, data is: \"%{public}s\"", str); 183 // The service logic is omitted here. 184}; 185}; 186 187// Register the myTsfnDemo method with the module Index.d.ts. The myTsfnDemo method is defined as follows: 188// export const myTsfnDemo: () => void; 189napi_value MyTsfnDemo(napi_env env, napi_callback_info info) { 190 OH_LOG_ERROR(LOG_APP, "MyTsfnDemo is called"); 191 napi_value workName = nullptr; 192 napi_create_string_utf8(env, "MyTsfnWork", NAPI_AUTO_LENGTH, &workName); 193 MyTsfnContext *myContext = new MyTsfnContext(env, workName); 194 if (myContext->GetTsfn() == nullptr) { 195 OH_LOG_ERROR(LOG_APP, "failed to create tsfn"); 196 delete myContext; 197 return nullptr; 198 }; 199 char *data0 = new char[]{"Im call in ArkTS Thread"}; 200 if (!myContext->Call(data0)) { 201 OH_LOG_INFO(LOG_APP, "call tsfn failed"); 202 }; 203 204 // Create a thread to simulate an asynchronous operation. 205 std::thread( 206 [](MyTsfnContext *myCtx) { 207 if (!myCtx->Acquire()) { 208 OH_LOG_ERROR(LOG_APP, "acquire tsfn failed"); 209 return; 210 }; 211 char *data1 = new char[]{"Im call in std::thread"}; 212 // This operation is optional and used only to check whether the asynchronous tsfn is still valid. 213 if (!myCtx->Call(data1)) { 214 OH_LOG_ERROR(LOG_APP, "call tsfn failed"); 215 }; 216 // Suspend the thread for 5 seconds to simulate a time-consuming operation, which is not complete when env exits. 217 sleep(5); 218 // When the asynchronous operation is complete, tsfn has been released and set to nullptr. 219 char *data2 = new char[]{"Im call after work"}; 220 if (!myCtx->Call(data2) && !myCtx->Release()) { 221 OH_LOG_ERROR(LOG_APP, "call and release tsfn failed"); 222 delete myCtx; 223 } 224 }, 225 myContext) 226 .detach(); 227 return nullptr; 228}; 229``` 230 231The following is the main thread logic, which creates worker threads and instruct workers to execute tasks. 232 233```ts 234// Main thread Index.ets 235import worker, { MessageEvents } from '@ohos.worker'; 236 237const mWorker = new worker.ThreadWorker('../workers/Worker'); 238mWorker.onmessage = (e: MessageEvents) => { 239 const action: string | undefined = e.data?.action; 240 if (action === 'kill') { 241 mWorker.terminate(); 242 } 243} 244 245// The registration of the triggering mode is omitted. 246mWorker.postMessage({action: 'tsfn-demo'}); 247 248``` 249 250The following is the worker thread logic, which triggers native tasks. 251 252```ts 253// worker.ets 254import worker, { ThreadWorkerGlobalScope, MessageEvents, ErrorEvent } from '@ohos.worker'; 255import napiModule from 'libentry.so'; // libentry.so is the module name of the Node-API library. 256 257const workerPort: ThreadWorkerGlobalScope = worker.workerPort; 258 259workerPort.onmessage = (e: MessageEvents) => { 260 const action: string | undefined = e.data?.action; 261 if (action === 'tsfn-demo') { 262 // Trigger the tsfn demo in C++. 263 napiModule.myTsfnDemo(); 264 // Instruct the main thread to terminate the worker. 265 workerPort.postMessage({action: 'kill'}); 266 }; 267} 268``` 269 270## napi_get_uv_event_loop Error Codes 271 272Additional parameter verification is added to prevent use of invalid **napi_env** in **napi_get_uv_event_loop**. The return value indicates the verification result. The return values of this API are as follows: 273 2741. If **env** and/or **loop** are **nullptr**, **napi_invalid_arg** is returned. 2752. If **env** is a valid **napi_env** and **loop** is a valid pointer, **napi_ok** is returned. 2763. If **env** is not a valid **napi_env** (for example, a released **env**), **napi_generic_failure** is returned. 277 278Example: 279 280```c++ 281napi_value NapiInvalidArg(napi_env env, napi_callback_info) 282{ 283 napi_status status = napi_ok; 284 status = napi_get_uv_event_loop(env, nullptr); // loop is nullptr, napi_invalid_arg. 285 if (status == napi_ok) { 286 // do something 287 } 288 289 uv_loop_s* loop = nullptr; 290 status = napi_get_uv_event_loop(nullptr, &loop); // env is nullptr, napi_invalid_arg. 291 if (status == napi_ok) { 292 // do something 293 } 294 295 status = napi_get_uv_event_loop(nullptr, nullptr); // Both env and loop are nullptr, napi_invalid_arg. 296 if (status == napi_ok) { 297 // do something 298 } 299 300 return nullptr; 301} 302 303napi_value NapiGenericFailure(napi_env env, napi_callback_info) 304{ 305 std::thread([]() { 306 napi_env env = nullptr; 307 napi_create_ark_runtime (&env); // Generally, the return value needs to be checked. 308 // napi_destroy_ark_runtime sets the pointer to null. Copy the pointer to simulate the problem. 309 napi_env copiedEnv = env; 310 napi_destroy_ark_runtime(&env); 311 uv_loop_s* loop = nullptr; 312 napi_status status = napi_get_uv_event_loop(copiedEnv, &loop); // env is invalid. napi_generic_failure will be returned. 313 if (status == napi_ok) { 314 // do something 315 } 316 }).detach();; 317} 318``` 319