目录

libuv Usage and Cases

About This Document

This document describes how to correctly use libuv APIs and locate faults by checking the code when a problem occurs. It covers the following aspects:

libuv Usage Rules

This section describes the usage specifications of requests and handles in libuv to ensure that developers can correctly use libuv APIs and avoid application stability issues. For details about the libuv principles, see libuv.

[h2]Request Usage Specifications in libuv

In the libuv library, a request is a temporary request and will not be held by an event loop for a long time. After the request task is executed, the mission of the request on the event loop ends. If you want to send the next request, you must call the related API again. In the official libuv documentation, requests are classified into the following types:

typedef struct uv_req_s uv_req_t;
typedef struct uv_getaddrinfo_s uv_getaddrinfo_t;
typedef struct uv_getnameinfo_s uv_getnameinfo_t;
typedef struct uv_shutdown_s uv_shutdown_t;
typedef struct uv_write_s uv_write_t;
typedef struct uv_connect_s uv_connect_t;
typedef struct uv_udp_send_s uv_udp_send_t;
typedef struct uv_fs_s uv_fs_t;
typedef struct uv_work_s uv_work_t;
typedef struct uv_random_s uv_random_t;

However, only the following threads pass through the asynchronous thread pool:

typedef struct uv_getaddrinfo_s uv_getaddrinfo_t;
typedef struct uv_getnameinfo_s uv_getnameinfo_t;
typedef struct uv_fs_s uv_fs_t;
typedef struct uv_work_s uv_work_t;
typedef struct uv_random_s uv_random_t;

In HarmonyOS, the data structure with the highest frequency of use is uv_work_t, which is mainly used to customize asynchronous task requests. The corresponding API is uv_queue_work, which is defined as follows:

UV_EXTERN int uv_queue_work(uv_loop_t* loop,
                            uv_work_t* req,
                            uv_work_cb work_cb,
                            uv_after_work_cb after_work_cb);

loop indicates the event loop where the request is located, work_cb indicates the asynchronous task executed in the asynchronous thread pool, and after_work_cb indicates the callback for processing the execution result of the asynchronous task in the event loop. In HarmonyOS, the entire processing of uv_queue_work is as follows:

  1. Call uv_queue_work.
  2. work_cb is encapsulated into the function uv__queue_work, and after_work_cb is encapsulated into uv__queue_done.
  3. The asynchronous thread pool (ffrt) executes uv__queue_work and then executes the real work_cb.
  4. Then, the processing is performed separately based on whether the thread is the main thread.
    1. If the thread is the main thread, uv__queue_done is inserted into the event handler task queue of the main thread based on the priority and waits to be executed.
    2. If the thread is another TS thread or the event loop thread created by the developer, uv__queue_done is placed in the wq queue, and uv_async_send is called to trigger the fd to wait for the event loop to process the wq queue.

After understanding the execution principle of uv_queue_work, you can use this API in the following scenarios.

The asynchronous task is deleted after being executed once.

Pseudocode 1:

Context* context = new Context; // context is a user-defined object.
uv_work_t* work = new uv_work_t;
work->data = (void*)context;
uv_queue_work(loop, work, [](uv_work_t*){
    Context *ctx = (Context*)work->data;
    // Service logic.
}, [uv_work_t* work, int status] {
    Context *ctx = (Context*)work->data;
    // Service logic.
    delete ctx; // Whether to delete the context is determined by the developer.
    delete work;
});

Pseudocode 2:

class Context {
public:
    uv_work_t work; // The lifetime of this work is the same as that of the context.
}

Context* context = new Context; // context is a user-defined object.
context->work.data = (void*)context;
uv_queue_work(loop, &context->work, [](uv_work_t*){
    Context *ctx = (Context*)work->data;
    // Service logic.
}, [uv_work_t* work, int status] {
    Context *ctx = (Context*)work->data;
    // Service logic.
    delete ctx; // Whether to delete the context is determined by the developer.
});

The preceding code complies with the following basic principle: For the calling mode of uv_queue_work, ensure that the deallocation of memory is completed in after_work_cb. Developers should avoid managing the lifecycle of asynchronous tasks, because it is impossible to determine when the tasks will be completed. This principle also applies to asynchronous requests executed in other thread pools.

Multiple request tasks share the same structure.

In this scenario, if the expected asynchronous task is to use the same structure to execute the same request task after the previous asynchronous request is completed, you can use the following code:

uv_loop_t* loop;

bool g_done = false;
uv_work_t *work = new uv_work_t;
void ExecuteCB(uv_work_t *work) {
    // Business Logic
}


void CompleteCB(uv_work_t *work, int status) {
    // Business Logic
    if (!g_done) {
        uv_queue_work(work->loop, work, ExecuteCB, CompleteCB);
    } else {
        delete work;
    }
}
    uv_queue_work(loop, work, ExecuteCB, CompleteCB);

This reduces the frequent allocation and release of objects and lowers the overhead.

If you are not sure whether the lifecycle of the created object needs to be consistent with that of the libuv request object, the best practice is to create the custom object and the request object separately and place the custom object in the data field of the request object. This ensures that the two objects do not affect each other. Even if there is a problem with the lifecycle management of the custom object, the normal execution of the system library will not be affected. If a crash occurs, the crash stack will be displayed in the specific service logic instead of the system library, facilitating fault locating.

[h2]Handle Usage Specifications in libuv

In the libuv development guide, a handle represents a persistent request that can be held by the event loop for a long time. If you do not call the uv_close function, the created handle will be permanently stored in the event loop, affecting the normal exit of the event loop. In the official documentation, handles are classified into the following types:

/* Handle types. */
typedef struct uv_loop_s uv_loop_t;
typedef struct uv_handle_s uv_handle_t;
typedef struct uv_dir_s uv_dir_t;
typedef struct uv_stream_s uv_stream_t;
typedef struct uv_tcp_s uv_tcp_t;
typedef struct uv_udp_s uv_udp_t;
typedef struct uv_pipe_s uv_pipe_t;
typedef struct uv_tty_s uv_tty_t;
typedef struct uv_poll_s uv_poll_t;
typedef struct uv_timer_s uv_timer_t;
typedef struct uv_prepare_s uv_prepare_t;
typedef struct uv_check_s uv_check_t;
typedef struct uv_idle_s uv_idle_t;
typedef struct uv_async_s uv_async_t;
typedef struct uv_process_s uv_process_t;
typedef struct uv_fs_event_s uv_fs_event_t;
typedef struct uv_fs_poll_s uv_fs_poll_t;
typedef struct uv_signal_s uv_signal_t;

However, the common handles in HarmonyOS are as follows:

/* Handle representing an event loop */
typedef struct uv_loop_s uv_loop_t;
/* The parent structure of all handles */
typedef struct uv_handle_s uv_handle_t;
/* Handle used to represent timer tasks */
typedef struct uv_timer_s uv_timer_t;
/* Handle used to represent communication between threads */
typedef struct uv_async_s uv_async_t;

No serious problem occurs when uv_loop_t is used. When using the event loop, you need to correctly release the resources in the event loop when the event loop exits. This prevents resource leakage caused by the event loop failing to exit. If you are not clear about how the upper-layer service uses the created event loop, you can call uv_walk to traverse the handles in the event loop and call uv_close in the callback to remove the handles from the event loop. Then, execute uv_run to ensure that the asynchronous task is executed. This ensures that the event loop exits normally, provided that no other services add tasks to the event loop during this process. For details, see the Event Loops in libuv.

When using handles in libuv, ensure that uv_close is called when the handles are not used, and that the call is made in the thread where the event loop is located. This prevents data contention between multiple threads. If you need to operate handles in a multi-thread environment, see the section Using libuv Timers in the libuv development guide.

Pay special attention to the use of uv_close, which does not synchronously remove the handle from the event loop. Before explaining the running logic of uv_close, you need to understand the following background knowledge:

  1. Call uv_close to remove uv_async_t from loop->async_handles, and then mount the node of uv_async_t to loop->closing_handles, indicating that the node is being closed and setting some flags.
  2. The event loop continues to execute the next step in this iteration until the uv__run_closing_handles function is executed.
  3. In the function in step 2, the handle_queue in uv_async_t is removed from loop->handle_queue, and then the close_cb callback of the node is executed. The close_cb is the parameter passed by the developer when calling uv_close.

    Therefore, the developer should avoid releasing the handle after calling uv_close and before the event loop executes the uv__run_closing_handles function.

Crash Cases Related to libuv

This section describes crash cases caused by the application calling the uv API.

Case 1: An application incorrectly uses uv_close.

Problem description: When an application calls the libuv API at the native layer, the application occasionally crashes due to improper use. The crash stack is located in libuv. The crash stack is as follows:

Pid:44250
Uid:20020034
Process name:crasher_cpp
Process life time:8s
Reason:Signal:SIGSEGV(SEGV MAPERR)0000000000000000000 probably caused by NULL pointer dereference
Fault thread info:
Tid:44250, Name:crasher_cpp
#00 pc 0000000000018528 /system/lib64/platformsdk/libuv.so(uv_run+724)(1616669436a9c6d4bcaf8ae1f5989855)
#01 pc 0000000000083518 /system/lib64/platformsdk/libruntime.z.so(OHOS::AbilityRuntime::OHOSLoopHandler::OnTriggered()+268)(d061df412ec8b3260629e85ba1a6344b)
#02 pc 00000000000833dc /system/lib64/platformsdk/libruntime.z.so(OHOS::AbilityRuntime::OHOSLoopHandler::OnReadable(int)+244) (dO61df412ec8b3260629e85ba1a6344b)
#03 pc 0000000000016710 /system/lib64/chipset-pub-sdk/libeventhandler.z.so(std:: __h::_ function::_ func<OHOS::AppExecFwk::EpollIoWaiter::HandleFileDescriptorEvent(i
#04 pc 000000000001aOdO /system/lib64/chipset-pub-sdk/libeventhandler.z.so(OHOS::AppExecFwk::EventHandler::DistributeEvent(std:: hocunique ptr<OHOS::AppExecFwk::Ir 
#05 pc 0000000000028418 /system/lib64/chipset-pub-sdk/libeventhandler.z.so(OHOS::AppExecFwk::(anonymous namespace)::EventRunnerImpl::ExecuteEventHandler(std::_ hoste
#06 pc 0000000000027cbc /system/lib64/chipset-pub-sdk/libeventhandler.z.so(OHOS::AppExecFwk::(anonymous namespace)::EventRunnerImpl::Run()+880)(a83d7f5ebf4fe67105b5 
#07 pc 000000000002a9d0 /system/lib64/chipset-pub-sdk/libeventhandler.z.so(OHOS::AppExecFwk::EventRunner::Run()+320)(a83d7f5ebf4fe67105b53501f28aa078)
#08 pc 00000000000ba48c /system/lib64/platformsdk/libappkit_native.z.so(OHOS::AppExecFwk::MainThread::Start()+872)(8f59740ee20585693a5c2814e1e9f6dd)
#09 pc 0000000000004ac4 /system/lib64/appspawn/appspawn/libappspawn_ace.z.so(RunChildProcessor(AppSpawnContent*, AppSpawnClient*)+216)(c368de983182514a8ea3Odaa3ba41
#10 pc 0000000000008688 /system/bin/appspawn(AppSpawnChild+436)(8e25bd745a01ef608e0816fd1eabcce2)	
#11 pc 0000000000008368 /system/bin/appspawn(AppSpawnProcessMsg+564)(8e25bd745a01ef608e0816fd1eabcce2)	
#12 pc 000000000000ff28 /system/bin/appspawn(OnReceiveRequest+676)(8e25bd745a01ef608e0816fd1eabcce2)
#13 pc 0000000000017af8 /system/lib64/chipset-pub-sdk/libbegetutil.z.so(HandleRecvMsg_+260)(fcd62c07eOd7d3c70d75c3c61180bc55)
#14 pc 0000000000017618 /system/lib64/chipset-pub-sdk/libbegetutil.z.so(HandleStreamEvent_+168)(fcd62c07eOd7d3c70d75c3c61180bc55)

Cause analysis: The following call chain is obtained by decompiling and de-stacking:

uv_run->uv__run_closing_handles->uv__finish_close->uv__queue_remove

uv__queue_remove indicates that a node is removed from the event loop queue. The crash occurs in this function, and the null pointer is dereferenced. In this case, you only need to enable ASan and reproduce the crash by referring to ASan: Detecting Memory Errors. Then, you can obtain the specific crash stack. Locate the specific code line through de-stacking. In this example, the error code is as follows:

class NapiTaskRunner : public AbstractTaskRunner {
public:
    NapiTaskRunner (
        napi env env,
        ExceptionHandler exceptionHandler = defaultExceptionHandler);
    ~NapiTaskRunner() override;
    NapiTaskRunner(const NapiTaskRunner&) = delete;
    NapiTaskRunner& operator=(const NapiTaskRunner&) = delete;
    void runAsyncTask(Task&& task) override;
    void runSyncTask(Task&& task) override;
    bool isOnCurrentThread() const override;
    void setExceptionHandler (ExceptionHandler handler) override;
private:
    napi env env;
    uv_loop_t* getLoop() const;
    uv_async_t	asyncHandle;
    std::mutex tasksMutex;
    std::queue<Task> tasksQueue;
    std::thread::id threadId;
    std::condition_variable cv;
    std::shared_ptr<std::atomic_bool> running = std::make_shared<std::atomic_bool>(true);
    ExceptionHandler exceptionHandler;
};

// Code of the constructor
NapiTaskRunner::NapiTaskRunner (napi_env env, ExceptionHandler exceptionHandler)
    : env(env), exceptionHandler(std::move (exceptionHandler)) {
    threadId = std::this_thread::get id();
    auto loop = getLoop() ;
    asyncHandle.data = static_cast<void*>(this);
    uv_async_init(loop, &asyncHandle, [](auto handle) {});
}

// Code of the destructor
NapiTaskRunner::~NapiTaskRunner() {
    running->store(false);
    cv.notify_all();
    uv_close(reinterpret_cast<uv_handle_t*>(&asyncHandle), nullptr);
}

It is a good practice to perform memory operations in the destructor. However, the developer may not fully understand the calling sequence of uv_close. When uv_async_t is used as a common member variable of NapiTaskRunner, the lifecycle of asyncHandle is the same as that of NapiTaskRunner. The destructor calls uv_close to remove the handle from the event loop. However, since uv_close is an asynchronous operation, the entire removal process cannot be completed immediately after the call. Therefore, after the destructor is executed, asyncHandle is released. If the event loop then attempts to operate on this node, a crash will occur.

The cause of the crash is as follows:

Solution:

If you need to place asyncHandle in a custom object, you can place it in NapiTaskRunner as a pointer. In the constructor, use new to create asyncHandle, and call uv_close in the destructor. In this way, NapiTaskRunner and asyncHandle can be independent of each other.

class NapiTaskRunner : public AbstractTaskRunner {
public:
    NapiTaskRunner (
        napi_env env,
        ExceptionHandler exceptionHandler = defaultExceptionHandler);
    ~NapiTaskRunner() override;
    NapiTaskRunner(const NapiTaskRunner&) = delete;
    NapiTaskRunner& operator=(const NapiTaskRunner&) = delete;
    void runAsyncTask(Task&& task) override;
    void runSyncTask(Task&& task) override;
    bool isOnCurrentThread() const override;
    void setExceptionHandler (ExceptionHandler handler) override;
private:
    napi_env env;
    uv_loop_t* getLoop() const;
    uv_async_t*    asyncHandle;
    std::mutex tasksMutex;
    std::queue<Task> tasksQueue;
    std::thread::id threadId;
    std::condition_variable cv;
    std::shared_ptr<std::atomic_bool> running = std::make_shared<std::atomic_bool>(true);
    ExceptionHandler exceptionHandler;
};


//Constructor code section
NapiTaskRunner::NapiTaskRunner (napi_env env, ExceptionHandler exceptionHandler)
    : env(env), exceptionHandler(std::move (exceptionHandler)) {
    threadId = std::this_thread::get_id();
    auto loop = getLoop() ;
    asyncHandle = new uv_async_t;
    asyncHandle->data = static_cast<void*>(this);
    uv_async_init(loop, asyncHandle, [](auto handle) {});
}


//Destructor section code
NapiTaskRunner::~NapiTaskRunner() {
    running->store(false);
    cv.notify_all();
    uv_close(reinterpret_cast<uv_handle_t*>(asyncHandle), [](uv_handle_t* handle) {
        delete (uv_async_t*)handle;
    });
}

Case 2: Crash during asynchronous task execution

If a crash occurs during asynchronous task execution, the possible scenarios are as follows:

Scenario 1

Problem description: Before the after_work_cb function is executed in the main thread, the function address is corrupted, causing the crash. The partial call stack is as follows:

Pid:13724
Uid:20020032
Process name:crasher_cpp
Reason:Signal:SIGBUS(BUS_ADRALN)@0xddde2ddf82f7dddd
Process life time:24s
Fault thread info:
Tid:13724, Name:crasher_cpp
#00 pc ddde2ddf82f7dddd Not mapped
#01 pc 000000000007c2fc /system/lib64/platformsdk/libruntime.z.so	(430e3acd9544f1f7ca5b27a4cecc0195)
#02 pc 000000000001ad94 /system/lib64/chipset-pub-sdk/libeventhandler.z.so(OHOS: :AppExecFwk::EventHandler::DistributeEvent(std::_h::unique ptr<OHOS::AppExecFwk::InnerEvent, void (*)(OHOS::AppExecFwk::InnerEvent*)> con=
#03 pc 000000000002bcf4 /system/lib64/chipset-pub-sdk/libeventhandler.z.so(OHOS::AppExecFwk::(anonymous namespace):EventRunnerImpl::ExecuteEventHandler(std::__h::unique ptr<OHOS::AppExecFwk::InnerEvent, void (*)(OHOS:
#04 pc 000000000002b5cc /system/lib64/chipset-pub-sdk/libeventhandler.z.so(OHOS::AppExecFwk::(anonymous namespace)::EventRunnerImpl::Run()+880)(b89cf5c314801ffd0e29111078d34982)
#05 pc 000000000002e96c /system/lib64/chipset-pub-sdk/libeventhandler.z.so(OHOS::AppExecFwk::EventRunner::Run()+524)(b89cf5c314801ffd0e29111078d34982)
#06 pc 00000000000b3fb4 /system/lib64/platformsdk/libappkit_native.z.so(OHOS::AppExecFwk::MainThread::Start()+616)(e9ba1356486e1df571afbc78c5f9d693)
#07 pc 0000000000004e28 /system/lib64/appspawn/appspawn/libappspawn_ace.z.so(RunChildProcessor(AppSpawnContent*, AppSpawnClient*)+568)(9f5d8e5303d934ad8210339181dca305)
#08 pc 000000000000b308 /system/bin/appspawn(AppSpawnChild+576)(ea1fc238c52f4e7577605cb35a5238b7)
#09 pc 000000000000af9c /system/bin/appspawn(AppSpawnProcessMsg+712)(ea1fc238c52f4e7577605cb35a5238b7)
#10 pc 00000000000138e0 /system/bin/appspawn(ProcessSpawnReqMsg+228)(ea1fc238c52f4e7577605cb35a5238b7)

Analysis:

According to the crash stack, the 0th frame is Notmapped, indicating that the address of after_work_cb is ddde2ddf82f7dddd. This address is not a normal PC address, and the ddd and the last ddd indicate that the memory block has been released. Therefore, it can be determined that the crash is caused by use-after-free (UAF). For such problems, developers can find some onsite information based on the register information in the crash stack. However, the crash of asynchronous tasks is usually far away from the problem site. Therefore, HarmonyOS also provides the ASan detection tool. By using this tool to reproduce the problem, you can easily find the problem site. The following is the onsite information captured by the tool:

The call stack of the first allocation is as follows:

The call stack of the first release is as follows:

After the decompilation by the related developers, the code is as follows:

Conclusion: When the function related to uv_work_t is called, the memory release must be performed in after_work_cb. If the developer cannot control the lifecycle of the custom object, the memory deallocation of uv_work_t can be performed in after_work_cb, and the memory of the custom object can be managed by the developer.

Scenario 2

Description: An error occurs in the lifecycle management of asynchronous tasks, causing the application to crash during uv__queue_done. The crash stack is as follows:

Pid:26268
uid:20020114
Process name:crasher_cpp
Process life time:18s
Reason:Signal:SIGSEGV(SEGV MAPERR)@0x0000007400650073
Fault thread info:
Tid:26268, Name:crasher_cpp
#00 pc 00000000000112fc /system/lib64/platformsdk/libuv.so(uv_queue_done+8)(a90636dbbfd39960db73e29590075d11)
#01 pc 000000000007c28c /system/lib64/platformsdk/libruntime.z.so(92caabbc4aec7feb10ce78ccb2755b86)
#02 pc 000000000001ad8c /system/lib64/chipset-pub-sdk/libeventhandler.z.so(OHOS::AppExecFwk::EventHandler::DistributeEvent (std::h:unique ptr<OHOS::AppExecFwk::InnerEvent, void (*)
#03 pc 000000000002b580 /system/lib64/chipset-pub-sdk/libeventhandler.z.so(OHOS::AppExecFwk::(anonymous namespace)::EventRunnerImpl::ExecuteEventHandler (std:: h::unique ptr<OHOS::Apr
#04 pc 000000000002ae58 /system/lib64/chipset-pub-sdk/libeventhandler.z.so(OHOS::AppExecFwk::(anonymous namespace)::EventRunnerImpl::Run()+880)(6394acafle4743acfbb25998ee37297b)
#05	pc 000000000002e1£8 /system/lib64/chipset-pub-sdk/libeventhandler.z.so(OHOS::AppExecFwk::EventRunner::Run ()+524)(6394acaf1e4743acfbb25998ee37297b)
#06	pc 00000000000b4408 /system/lib64/platformsdk/libappkit_native.z.so(OHOS::AppExecFwk::MainThread::Start()+408)(7771dOfba84d0fcd69£48428a264274a)
#07	pc 0000000000004d18 /system/lib64/appspawn/appspawn/libappspawn_ace.z.so (RunChildProcessor(AppSpawnContent*, AppSpawnClient*)+560)(e33c30d195115715c46ece122£278d5£)
#08	pc 000000000000a4a4 /system/bin/appspawn(AppSpawnChild+484)(f60d4361d8bc8fe7e6b3a73529a98031)
#09	pc 000000000000a194 /system/bin/appspawn(AppSpawnProcessMsg+688)(f60d4361d8bc8fe7e6b3a73529a98031)
#10	pc 0000000000011c18 /system/bin/appspawn(ProcessSpawnReqMsg+228)(f60d4361d8bc8fe7e6b3a73529a98031)
#11	pc 0000000000011238 /system/bin/appspawn(OnReceiveRequest+172)(£60d4361d8bc8fe7e6b3a73529a98031)
#12	pc 0000000000016058 /system/lib64/chipset-pub-sdk/libbegetutil.z.so(HandleRecvMsg_+292)(bc25e5f0f7a71£78a286£419d13c202£)
#13	pc 0000000000015b58 /system/lib64/chipset-pub-sdk/libbegetutil.z.so(HandleStreamEvent_+172) (bc25e5f0f7a71£78a286£419d13c202f)
#14	pc 0000000000013230 /system/lib64/chipset-pub-sdk/libbegetutil.z.so(ProcessEvent+108)(bc25e5f0f7a71£78a286£419d13c202f)
#15	pc 0000000000012df0 /system/lib64/chipset-pub-sdk/libbegetutil.z.so(RunLoop_+356)(bc25e5f0f7a71f78a286£419d13c202f)
#16	pc 000000000000£3c0 /system/bin/appspawn(AppSpawnRun+136)(f60d4361d8bc8fe7e6b3a73529a98031)
#17	pc 000000000000cd4c /system/bin/appspawn(main+744)(£60d4361d8bc8fe7e6b3a73529a98031)
#18	pc 00000000000a05£4 /system/lib/ld-musl-aarch64.so.1(1ibc start main stage2+64)(73£87e7c2e4e0d3e8e0510b97431a820)

Analysis:

This type of problem is usually caused by the crash due to improper management of the lifecycle of the uv_work_t object. However, how to trace the source of the problem has always been a challenge. This case introduces a special method, that is, using the register information in the crash file to speculate the problem scene.

First, after decompilation, you can see the specific code line and assembly instruction, as shown in the following figure.

The meaning of the assembly instruction in the red box in the preceding figure is as follows:

112fc: indicates that the value of the x8 register plus 32 in decimal is used as the address, and then the content at the address is obtained and stored in the w9 register. (Actually, w9 is x9. One is 32-bit, and the other is 64-bit.) w9 = [x8+32]

112f8: indicates that the value of the x0 register minus 24 in decimal is used as the address, and then the content at the address is stored in the x8 register. x8 = [x0 - 24] . [] indicates that the content is obtained.

The following describes the content stored in the preceding two registers. A basic knowledge is that in a C++ function, the x0 register corresponds to the first formal parameter of the function. Therefore, the x0 register stores the address of the formal parameter w. According to the instruction 112f8, the content of the x8 register is 24 bytes before the address corresponding to x0. The content represented by x8 can be inferred from the following structure:

struct uv_work_s {
  UV_REQ_FIELDS
  uv_loop_t* loop;                     //x0 -24
  uv_work_cb work_cb;                  //x0 -16
  uv_after_work_cb after_work_cb;      //x0 -8
  struct uv__work work_req;            //x0
};

According to the preceding memory layout, the x8 register stores the address of loop. The current error occurs on the x8 register, which verifies the preceding conclusion and indicates that this is a UAF problem of an asynchronous task.

Next, by analyzing the uv_work_s structure, you can find that the structure contains the first parameter w of uv__queue_done and the after_work_cb function pointer.

after_work_cb is a function pointer passed by the developer. It is usually defined in the code file written by the developer and finally compiled into the dynamic library (.so). The crash file on HarmonyOS contains the address range of the .so file mapped to the current application process. Therefore, you can find the corresponding .so file in the crash file based on the address of after_work_cb, and locate the specific code line based on the start address. Check whether the x0 register still retains the after_work_cb information.

x0 contains the address of after_work_cb. Determine the address range of the .so file where the address is located, and then subtract the start address of the .so file from the address to obtain the offset address. You can find the specific code line through decompilation.

The specific code is as follows:

void DataShareUvQueue::LambdaForWork(uv_work_t *work, int uvstatus)
{
    if (work == nullptr || work->data == nullptr) {
        LOG_ERROR("invalid work or work->data.");
        return;
    }
    auto *entry = static_cast<UvEntry*>(work->data);
    {
        // The error is reported in this line, and the lock fails to be obtained.
        std::unique_lock<std::mutex> lock(entry->mutex);
        if (entry->func) {
            entry->func();
        }
        entry->done = true;
        if (!entry->purge) {
            entry->condition.notify_all();
            return;
        }
    }
    DataShareUvQueue::Purge(work);
}

void DataShareUvQueue::SyncCall(NapiVoidFunc func, NapiBoolFunc retFunc)
{
    // Dynamically apply for uv_work_t.
    uv_work_t* work = new (std::nothrow) uv_work_t;
    if (work == nullptr) {
        LOG_ERROR("invalid work.");
        return;
    }
    // Allocate a UvEntry and assign it to work->data.
    work->data = new UvEntry {env_, std::move(func), false, false, {}, {}, std::move(retFunc)};
    if (work->data == nullptr) {
        delete work;
        LOG_ERROR("invalid uvEntry.");
        return;
    }

    bool noNeedPurge = false;
    auto *uvEntry = static_cast<UvEntry*>(work->data);
    {
        std::unique_lock<std::mutex> lock(uvEntry->mutex);
        // Throw an asynchronous task. Everything is normal.
        auto status = uv_queue_work(
            loop_, work, [](uv_work_t *work) {}, LambdaForWork);
        if (status != napi_ok) {
            LOG_ERROR("queue work failed");
            DataShareUvQueue::Purge(work);
            return;
        }
        // Asynchronous-to-synchronous conversion. Actually, it is fine as long as the tasks are not in the same thread. However, the code implementation is not elegant.
        if (uvEntry->condition.wait_for(lock, std::chrono::seconds(WAIT_TIME), [uvEntry] { return uvEntry->done; })) {
            auto time = static_cast<uint64_t>(duration_cast<milliseconds>(
                system_clock::now().time_since_epoch()).count());
            LOG_INFO("function ended successfully. times %{public}" PRIu64 ".", time);
        }
        // Here, the problem starts. This is essentially about handling exceptions. That is, when all tasks cannot be executed, you need to call uv_cancel to cancel the task. Then, execute Purge to perform the cleanup operation.
        if (!uvEntry->done && uv_cancel((uv_req_t*)work) != napi_ok) {
            LOG_ERROR("uv_cancel failed.");
            uvEntry->purge = true;
            noNeedPurge = true;
        }
    }

    CheckFuncAndExec(uvEntry->retFunc);
    if (!noNeedPurge) {
        // Purge is used to perform the cleanup operation, including deleting uv_work_t and uvEntry.
        DataShareUvQueue::Purge(work);
    }
}

The reason for the error in the preceding code is that the developer is not familiar with the uv_cancel function. The running logic of the uv_cancel function is as follows:

  1. First, it determines whether the task can be canceled based on the status of the asynchronous task work_cb in uv_work_t. If the task cannot be canceled, the function returns.
  2. Then, work_cb is set to uv__cancelled. The asynchronous process continues to be executed, and status is set to UV_ECANCELED and passed to after_work_cb.
  3. Finally, after_work_cb is executed.

    uv_cancel does not actually cancel the asynchronous task, nor does it prevent the execution of the after_work_cb callback. If the developer calls uv_cancel but does not check whether status is equal to UV_ECANCELED in the callback, the code will not be executed as expected. This may cause the cleanup to be incomplete, which may lead to double free or UAF problems.

Conclusion: Ensure that the memory of the asynchronous task object is released in after_work_cb.

Scenario 3

Problem description: An application calls an asynchronous task, and the application crashes before work_cb is executed in the asynchronous thread pool. The crash stack is as follows:

Thread name:OS_FFRT
#00 pc 0000000000000000 Not mapped
#01 pc 0000000000012790/system/lib64/platformsdk/libuv.so(uv_ffrt_work+56)(e51f7fcef979b717a8cfda493466e715)
#02 pc 00000000000647bc/system/lib64/ndk/libffrt.so(ffrt:CPUWorker:Run(ffrt_executor_task*, int)+488)(2922cbbd7fc6ad47a9cdddf7480a607e)
#03 pc 0000000000064fe8 /system/lib64/ndk/libffrt.so(ffrt:CPUWorker::RunTask(ffrt_executor_task*, ffrt::CPUWorker*)+124)(2922cbbd7fc6ad47a9cdddf7480a607e)
#04 pc 000000000006553c/system/lib64/ndk/libffrt.so(ffrt:CPUWorker:WorkerLooperDefault(ffrt::WorkerThread*)+588)(2922cbbd7fc6ad47a9cdddf7480a607e)
#05 pc 0000000000064e84/system/lib64/ndk/libffrt.so(ffrt:CPUWorker:Dispatch(ffrt:CPUWorker*)+144)(2922cbbd7fc6ad47a9cdddf7480a607e)
#06 pc 0000000000064ddc/system/lib64/ndk/libffrt.so(ffrt:CPUWorker:WrapDispatch(void*)+28)(2922cbbd7fc6ad47a9cdddf7480a607e)	
#07 pc 00000000001bc964 /system/lib/ld-musl-aarch64.so.1(start+236)(9df691eca4c7c964a4d25c8af1c7a550)

Analysis:

It is extremely difficult to reproduce this issue, and only big data can be used to reproduce it. Therefore, the tool is not very useful. In the end, the code needs to be checked. The code in pseudocode 2 is separated from the code in pseudocode 1, and the custom object and UV object are created separately. After the modification, this issue does not recur. After modification:

Conclusion: Refer to scenario 1. If you are not sure whether the lifecycle management of the custom object and the UV asynchronous task object is synchronous, you are advised to separate the two objects and manage them independently.

Context* context = new Context;// context is a custom object.
uv_work_t* work = new uv_work_t;
work->data = (void*)context;
uv_queue_work(loop, work, [](uv_work_t*){
    Context *ctx = (Context*)work->data;
    // Service logic
}, [uv_work_t* work, int status] {
    Context *ctx = (Context*)work->data;
    // Service logic
    delete ctx; // Whether to delete the object is determined by the developer.
    delete work;
});

Freeze Cases Related to libuv

As a framework, libuv provides some asynchronous I/O capabilities for developers. It itself does not cause deadlocks. If the freeze stack shows that the libuv-related APIs are on the top of the stack, the cause is that the developer calls some blocking APIs of libuv in the main thread (UI thread). In this case, the developer should avoid calling blocking APIs of libuv in the main thread, such as the synchronous file reading API. In addition, improper use of libuv APIs by the developer may also cause the event loop framework to be suspended. This will be described later.

Case 1: The main thread calls a blocking UV API.

Problem description: An application calls the synchronous API of the file module in the main thread. The underlying TS API uses the underlying capabilities of libuv. As a result, when sendfile is called, the main thread is blocked and frozen.

Tid:19473, Name:app_name
#00 pc 00000000000a457c /system/lib/ld-musl-aarch64.so.1(fbb1eb526bb54f59c5dc4f2521b68e52)
#01 pc 0000000000019f88 /system/lib64/platformsdk/libuv.so(uv__fs_work+2956)(afecd0c8f506e5fc1661ef2cb46dea9d)
#02 pc 000000000001c048 /system/lib64/platformsdk/libuv.so(uv_fs_sendfile+148)(afecd0c8f506e5fc1661ef2cb46dea9d)
#03 pc 000000000011d27c /system/lib64/module/file/libfs.z.so(OHOS::FileManagement::ModuleFileIO::OpenFile(OHOS::FileManagement::ModuleFileIO::FileInfo&, OHOS::FileManagement::ModuleFileIO::FileInfo&)+732)(c8dbb978ac2472548e07ccb7f6f9eb18)
#04 pc 000000000011c99c /system/lib64/module/file/libfs.z.so(OHOS::FileManagement::ModuleFileIO::CopyFile::Sync(napi_env__*, napi_callback_info__*) (.cfi)+756)(c8dbb978ac2472548e07ccb7f6f9eb18)
#05 pc 000000000003dec8 /system/lib64/platformsdk/libace_napi.z.so(panda::JSValueRef ArkNativeFunctionCallBack<true>(panda::JsiRuntimeCallInfo*)+216)(e9eee6ffeb9040c06af8fe2188c7ee8e)
#06 pc 00000000003f3b6c /system/lib64/module/arkcompiler/stub.an(RTStub_PushCallArgsAndDispatchNative+40)
#07 at handleSendVideo (entry|feat_chat|1.0.0|src/main/ets/viewmodel/ChatViewModel.ts:874:1)
#08 pc 00000000003a1500 /system/lib64/platformsdk/libark_jsruntime.so(panda::ecmascript::InterpreterAssembly::GeneratorReEnterInterpreter(panda::ecmascript::JSThread*, panda::ecmascript::JSHandle<panda::ecmascript::GeneratorContext>)+104)(77423abf0869226a2e04e046a4b743b7)
#09 pc 00000000003db234 /system/lib64/platformsdk/libark_jsruntime.so(panda::ecmascript::EcmaInterpreter::GeneratorReEnterInterpreter(panda::ecmascript::JSThread*, panda::ecmascript::JSHandle<panda::ecmascript::GeneratorContext>)+144)(77423abf0869226a2e04e046a4b743b7)
#10 pc 000000000038fc34 /system/lib64/platformsdk/libark_jsruntime.so(panda::ecmascript::GeneratorHelper::Next(panda::ecmascript::JSThread*, panda::ecmascript::JSHandle<panda::ecmascript::GeneratorContext> const&, panda::ecmascript::JSTaggedValue)+156)(77423abf0869226a2e04e046a4b743b7)
#11 pc 000000000046c6c0 /system/lib64/platformsdk/libark_jsruntime.so(77423abf0869226a2e04e046a4b743b7)
#12 pc 00000000002757ac /system/lib64/platformsdk/libark_jsruntime.so(panda::ecmascript::builtins::BuiltinsPromiseHandler::AsyncAwaitFulfilled(panda::ecmascript::EcmaRuntimeCallInfo*)+112)(77423abf0869226a2e04e046a4b743b7)
#13 pc 00000000003f37b0 /system/lib64/module/arkcompiler/stub.an(RTStub_AsmInterpreterEntry+208)
#14 pc 00000000003a12b8 /system/lib64/platformsdk/libark_jsruntime.so(panda::ecmascript::InterpreterAssembly::Execute(panda::ecmascript::EcmaRuntimeCallInfo*)+216)(77423abf0869226a2e04e046a4b743b7)
#15 pc 0000000000277568 /system/lib64/platformsdk/libark_jsruntime.so(panda::ecmascript::builtins::BuiltinsPromiseJob::PromiseReactionJob(panda::ecmascript::EcmaRuntimeCallInfo*)+344)(77423abf0869226a2e04e046a4b743b7)
#16 pc 00000000003f37b0 /system/lib64/module/arkcompiler/stub.an(RTStub_AsmInterpreterEntry+208)
#17 pc 00000000003a12b8 /system/lib64/platformsdk/libark_jsruntime.so(panda::ecmascript::InterpreterAssembly::Execute(panda::ecmascript::EcmaRuntimeCallInfo*)+216)(77423abf0869226a2e04e046a4b743b7)
#18 pc 0000000000408d18 /system/lib64/platformsdk/libark_jsruntime.so(panda::ecmascript::job::MicroJobQueue::ExecutePendingJob(panda::ecmascript::JSThread*, panda::ecmascript::JSHandle<panda::ecmascript::job::MicroJobQueue>)+552)(77423abf0869226a2e04e046a4b743b7)
#19 pc 0000000000367d78 /system/lib64/platformsdk/libark_jsruntime.so(panda::ecmascript::EcmaContext::ExecutePromisePendingJob()+92)(77423abf0869226a2e04e046a4b743b7)
#20 pc 000000000058ebcc /system/lib64/platformsdk/libark_jsruntime.so(panda::PromiseCapabilityRef::Resolve(panda::ecmascript::EcmaVM const*, unsigned long)+256)(77423abf0869226a2e04e046a4b743b7)
#21 pc 0000000000060c28 /system/lib64/platformsdk/libace_napi.z.so(napi_resolve_deferred+120)(e9eee6ffeb9040c06af8fe2188c7ee8e)
#22 pc 00000000005455c0 /system/lib64/libmedialibrary_nutils.z.so(OHOS::Media::MediaLibraryNapiUtils::InvokeJSAsyncMethod(napi_env__*, napi_deferred__*, napi_ref__*, napi_async_work__*, OHOS::Media::JSAsyncContextOutput const&) (.cfi)+264)(c9ee202598f64bfbd76934922ac5a1e8)
#23 pc 00000000004729d0 /system/lib64/libmedialibrary_nutils.z.so(OHOS::Media::JSGetThumbnailCompleteCallback(napi_env__*, napi_status, OHOS::Media::FileAssetAsyncContext*) (.cfi)+504)(c9ee202598f64bfbd76934922ac5a1e8)
#24 pc 000000000006652c /system/lib64/platformsdk/libace_napi.z.so(NativeAsyncWork::AsyncAfterWorkCallback(uv_work_s*, int)+524)(e9eee6ffeb9040c06af8fe2188c7ee8e)
#25 pc 000000000007c9c0 /system/lib64/platformsdk/libruntime.z.so(929be9ac71f5f1b8c50d931718342ac3)
#26 pc 000000000001bdb4 /system/lib64/chipset-pub-sdk/libeventhandler.z.so(OHOS::AppExecFwk::EventHandler::DistributeEvent(std::__h::unique_ptr<OHOS::AppExecFwk::InnerEvent, void (*)(OHOS::AppExecFwk::InnerEvent*)> const&)+1140)(ea7c9b930d7b542607af81677dd531e7)
#27 pc 000000000002d6a8 /system/lib64/chipset-pub-sdk/libeventhandler.z.so(OHOS::AppExecFwk::(anonymous namespace)::EventRunnerImpl::ExecuteEventHandler(std::__h::unique_ptr<OHOS::AppExecFwk::InnerEvent, void (*)(OHOS::AppExecFwk::InnerEvent*)>&)+348)(ea7c9b930d7b542607af81677dd531e7)
#28 pc 000000000002cf64 /system/lib64/chipset-pub-sdk/libeventhandler.z.so(OHOS::AppExecFwk::(anonymous namespace)::EventRunnerImpl::Run()+908)(ea7c9b930d7b542607af81677dd531e7)
#29 pc 0000000000030308 /system/lib64/chipset-pub-sdk/libeventhandler.z.so(OHOS::AppExecFwk::EventRunner::Run()+528)(ea7c9b930d7b542607af81677dd531e7)
#30 pc 00000000000b19ac /system/lib64/platformsdk/libappkit_native.z.so(OHOS::AppExecFwk::MainThread::Start()+400)(fe61820fe652b04577747dfc89270211)
#31 pc 0000000000004e34 /system/lib64/appspawn/appspawn/libappspawn_ace.z.so(RunChildProcessor(AppSpawnContent*, AppSpawnClient*)+568)(7c113fbf97a325774d8a727348d15388)
#32 pc 000000000000ba7c /system/bin/appspawn(AppSpawnChild+576)(3d47202f3e52b59a2a29815389a567f0)
#33 pc 0000000000015320 /system/bin/appspawn(ProcessSpawnReqMsg+3180)(3d47202f3e52b59a2a29815389a567f0)
#34 pc 00000000000134b8 /system/bin/appspawn(OnReceiveRequest+132)(3d47202f3e52b59a2a29815389a567f0)
#35 pc 0000000000016cf8 /system/lib64/chipset-pub-sdk/libbegetutil.z.so(HandleRecvMsg_+344)(3e5c25bc70c753fec6381de8070a97e0)
#36 pc 00000000000167cc /system/lib64/chipset-pub-sdk/libbegetutil.z.so(HandleStreamEvent_+192)(3e5c25bc70c753fec6381de8070a97e0)
#37 pc 0000000000013eac /system/lib64/chipset-pub-sdk/libbegetutil.z.so(ProcessEvent+88)(3e5c25bc70c753fec6381de8070a97e0)
#38 pc 0000000000013a68 /system/lib64/chipset-pub-sdk/libbegetutil.z.so(RunLoop_+308)(3e5c25bc70c753fec6381de8070a97e0)
#39 pc 00000000000113b4 /system/bin/appspawn(AppSpawnRun+212)(3d47202f3e52b59a2a29815389a567f0)
#40 pc 000000000000ecd4 /system/bin/appspawn(main+764)(3d47202f3e52b59a2a29815389a567f0)
#41 pc 00000000000a12c0 /system/lib/ld-musl-aarch64.so.1(libc_start_main_stage2+64)(fbb1eb526bb54f59c5dc4f2521b68e52)

Conclusion

When using the file synchronization API, do not call it in the main thread. You are advised to call it in the worker thread or taskpool.

Case 2: PDF freezing occurs in the event loop.

Symptom: When an application calls the .so API of another SDK in the taskpool scenario, the application is suspended on libuv.

Tid:61139, Name:example.pdftest
#00 pc 0000000000018044 /system/lib64/platformsdk/libuv.so(uv async_io+360)(fe4a9f2630458fa5b8b7b0e4dacc5f9a)
#01 pc 0000000000017720 /system/lib64/platformsdk/libuv.so(uv_io_poll+1268)(fe4a9f2630458fa5b8b7b0e4dacc5f9a)
#02 pc 0000000000018540 /system/lib64/platformsdk/libuv.so(uv_run+376)(fe4a9f2630458fa5b8b7b0e4dacc5f9a)
#03 pc 00000000000768b4 /system/lib64/platformsdk/libruntime.z.so(OHOS::AbilityRuntime::OHOSLoopHandler:OnTriggered()+148)(09902ebffe1260cecd7be3e24ad58df5)
#04 pc 00000000000195b8 /system/lib64/chipset-pub-sdk/libeventhandler.z.so(96fe4d4a21391569c237423eae1d16df)
#05 pc 0000000000015324 /system/lib64/chipset-pub-sdk/libeventhandler.z.so(OHOS::AppExecFwk::EventHandler:DistributeEvent(std: h:unique ptrOHOS::AppExecFwk:In
#06 pc 0000000000023f78 /system/lib64/chipset-pub-sdk/libeventhandler.z.so(OHOS::AppExecFwk:(anonymous namespace):EventRunnerImpl:ExecuteEventHandler(std:: hu
#07 pc 0000000000023850 /system/lib64/chipset-pub-sdk/libeventhandler.z.so(OHOS::AppExecFwk::(anonymous namespace)::EventRunnerImpl:Run()+872)(96fe4d4a2139156S
#08 pc 0000000000026628/system/lib64/chipset-pub-sdk/libeventhandler.z.so(OHOS::AppExecFwk::EventRunner:Run()+284)(96fe4d4a21391569c237423eae1d16df)
#09 pc 00000000000a5bb4 /system/lib64/platformsdk/libappkit_native.z.so(OHOS::AppExecFwk:MainThread::Start()+764)(b926a67fe9460965838f4a20dbd3a020)
#10 pc 0000000000004880 /system/lib64/appspawn/appspawn/libappspawn_ace.z.so(RunChildProcessor(AppSpawnContent*, AppSpawnClient*)+216)(1f4858241fab18c5ee268
#11 pc 0000000000008788 /system/bin/appspawn(AppSpawnChild+404)(3d1b41c7794e59721bc566882e35a530)
#12 pc 00000000000084c8 /system/bin/appspawn(AppSpawnProcessMsg+636)(3d1b41c7794e59721bc566882e35a530)
#13 pc 000000000000f974 /system/bin/appspawn(ProcessSpawnReqMsg+228)(3d1b41c7794e59721bc566882e35a530)
#14 pc 000000000000f224 /system/bin/appspawn(OnReceiveRequest+172)(3d1b41c7794e59721bc566882e35a530)
#15 pc 0000000000017c9c /system/lib64/chipset-pub-sdk/libbegetutil.z.so(HandleRecvMsg_+260)(6725d8c1610eb726305c093a8f27148c)
#16 pc 00000000000177bc /system/lib64/chipset-pub-sdk/libbegetutil.z.so(HandleStreamEvent_+168)(6725d8c1610eb726305c093a8f27148c)
#17 pc 0000000000014ee0/system/lib64/chipset-pub-sdk/libbegetutil.z.so(ProcessEvent+108)(6725d8c1610eb726305c093a8f27148c)
#18 pc 0000000000014aa0/system/lib64/chipset-pub-sdk/libbegetutil.z.so(RunLoop_+356)(6725d8c1610eb726305c093a8f27148c)
#19 pc 000000000000d3bc /system/bin/appspawn(AppSpawnRun+136)(3d1b41c7794e59721bc566882e35a530)
#20 pc 000000000000ad20 /system/bin/appspawn(main+708)(3d1b41c7794e59721bc566882e35a530)
#21 pc 000000000009eac0 /system/lib/ld-musl-aarch64.so.1(libc start main stage2+64)(82429be6ea2851745621f83dce721120)

Analysis:

First, decompile the code to check which line is suspended:

The logic of this code is to traverse the queue on the loop in sequence and check whether the internal pending has been modified. If it has been modified, the callback function is executed.

The freeze occurs in this loop, and the loop is always in an infinite loop. There are two main reasons for this phenomenon.

The first case is less likely. According to the log verification, this is not the cause of the problem. For the second case, use GDB to debug and simulate the linked list operation process when the system is suspended:

The figure shows that when the system is suspended, the async_handles queue on the loop is traversed, and the previously obtained node is mounted to the current queue again. As a result, an infinite loop occurs. This phenomenon may be caused by the fact that the same handle is initialized in two event loops, causing two linked lists to be intertwined. To verify this inference, we add logs again to reproduce the problem. The logs are as follows:

The log proves that the same handle is initialized in the loop of the main thread and the TaskWorker thread of the task pool.

Then, check the .so code in the SDK. The code is as follows:

The code saves a common uv_async_t object in a static object, but does not perform call_once processing. As a result, the object is initialized each time the component is imported, and the same handle is initialized multiple times in different event loops.

Conclusion: Developers should use call_once to process the singleton to avoid initializing the same handle in different event loops. Otherwise, an infinite loop will occur in the event loop. If this occurs in the main thread, the system may be frozen. In addition, if a handle is initialized twice in an event loop, the previously initialized node will be lost, causing the function to fail. If you have created multiple napi_threadsafe_function or uv_async_t handles and the callback is not executed when these handles are triggered, you can consider the preceding problem.

libuv Crash Caused by Double Close

Double close details

Description: libuv is an asynchronous I/O event scheduling framework, and its core logic is driven by file descriptors (fd). The internal code terminates the program if it detects that the errno is not as expected after calling the system call related to fd. In HarmonyOS, the event loop continues to use this method, but more information is obtained before the program is terminated. The following is the crash stack when the fd is abnormal:

Process life time:569s
Reason:Signal:SIGABRT(SI_TKILL)@0x01317b430000996b from:39275:20020035
LastFatalMessage:errno is 9, loop addr is 385399404800, fd is 315 (../../../third_party/libuv/src/unix/async.c:uv_async_send:170)
Fault thread info:
Tid:39304, Name:OS TaskManager
#00 pc 0000000000197420./system/lib/ld-musl-aarch64.so.1 (raise+228)(b168£10a179c£6050a309242262e6a17)
#01 pc 0000000000145760 /system/lib/ld-musl-aarch64.so.1(abort+20)(b168f10a179cf6050a309242262e6a17)
#02 pc 0000000000017814 /system/lib64/platformsdk/libuv.so(uv_async_send+360)(23ffblfca6d55d23fe917788b2334b12)
#03 pc 000000000001bb3c /system/lib64/module/libtaskpool.z.so(Commonlibrary::Concurrent:: TaskPoolModule::TaskManager:: TryExpand ()+60)
#04 pc 0000000000017be0 /system/lib64/platformsdk/libuv.so(uvasync_io+352)(23ffb1fca6d55d23fe917788b2334b12)
#05 pc 0000000000017258 /system/lib64/platformsdk/libuv.so(uvio poll+956)(23ffblfca6d55d23fe917788b2334b12)
#06 pc 00000000000180e4 /system/lib64/platformsdk/libuv.so(uv _run+376)(23ffblfca6d55d23fe917788b2334b12)
#07 pc 000000000001cc88./system/lib64/module/libtaskpool.z.so(Commonlibrary::Concurrent::TaskPoolModule:: TaskManager:: RunTaskManager ()+172)
#08 pc 000000000001e058 /system/lib64/module/libtaskpool.z.so(e18ade536547e34d8ef7a614e073£74a)
#09 pc 00000000001b87ac /system/lib/ld-musl-aarch64.so.1(start+236)(b168£10a179c£6050a309242262e6a17)

The preceding crash stack is only one of the causes of abnormal termination of libuv. Other stacks are similar to the preceding crash stack, and all of them contain the LastFatalMessage information. In addition, the 0th and 1st frames are raise and abort of the musl library, and the 2nd frame is the code of libuv. The LastFatalMessage field indicates the fd that is operated, the returned errno, and the event loop to which the fd belongs. (One ArkTS thread corresponds to one event loop, and the uv_loop_t created by the developer is also an event loop.)

Analysis:

According to the preceding crash stack, the errno is 9, indicating that the problem is a double close problem. If the errno is 22, it is also a double close problem. The double close model is as follows:

Three modules A, B, and C are executed in sequence.

  1. A requests an fd, for example, fd 100, and shares it with B.
  2. After using the fd, B closes the fd whose value is 100.
  3. C requests the fd. If the kernel allocates fd 100 to C, C performs operations on the fd.
  4. A does not know that the fd whose value is 100 has been closed by B. When A closes the fd, A calls the close operation once.
  5. C crashes when using the fd.

According to a large number of tests, double close may cause the following three types of impacts:

  1. If the fd created by A is closed by B and the fd is not allocated to another module, the error "errno = 9" will be reported when the fd is used.
  2. If the fd created by A is closed by B and the fd has been allocated to another module, but the type of the fd is different from that of the previous fd (for example, the old fd is of the eventfd type, and the newly created fd is of the file type), the error "errno = 22" will be reported.
  3. If the fd created by A is closed by B and the fd has been allocated to another module with the same type, a file conflict occurs. For example, an A thread has an event loop, and to trigger a callback, characters need to be written to the fd of A. If the event loop created by the B thread obtains the fd, all the callbacks that should be triggered to the A thread cannot be executed normally. Instead, the callbacks are triggered to the event loop of the B thread.

Troubleshooting Method

  1. If the application process contains native code and involves file operations, the fd must be released by the one who requests it. If there are special service requirements, such as transparent transmission of the fd, the following must be specified: The transparent transmission party shall not perform the close operation on the fd for transparent transmission. Ensure that each fd is created and closed only once.
  2. If the ArkTS layer does not use the TS API and a specific fd number is returned, the fd must be operated in the first method. In addition, the fd starts from 0. Therefore, you must ensure that the variable is set to –1 instead of 0 after the fd is closed.

Case 1: An application crashes occasionally after a user logs out and restarts the application.

Problem description: The app occasionally crashes due to double close. The reproduction procedure is as follows: Log out of the account and then click the app. A crash occurs. The crash stack is the same as that in the first figure in the article. The crash stack is mainly concentrated in the worker thread or the thread related to the task pool (TaskManager thread and TaskWorker thread).

Analysis:

Check the code of the app. The code is as follows:

In the preceding code, rawFileDescriptor is the management object of the file descriptor obtained by the resource management subsystem through rawFilePath.

The comment (out) part indicates that the first close operation is performed by using the close API of the file management subsystem. The second close operation is performed by using the closeRawFd API of the resource management subsystem, with the rawFilePath file path being passed. The two close operations correspond to the two call stacks captured by the plugin.

Solution:

Delete the redundant close operation according to the comment (out) in the code in the preceding figure.

Sample Code