目录

Using the Memory Leak Customization Capability

Overview

Memory leak issues in third-party apps are often difficult to locate, and traditional analysis methods are inefficient. To improve the troubleshooting efficiency, HarmonyOS provides the MallocDispatchTable mechanism, which allows you to customize the hook behavior of memory allocation functions and flexibly insert custom monitoring logic. This enables precise tracking of memory allocation behavior and proactive capture of memory leak scenarios. With this capability, you can customize hook policies as needed, such as recording call stacks, collecting allocation frequency statistics, and setting threshold alarms. This significantly enhances the capability of customized analysis for memory leak issues.

Note: Hook is a hooking technique in computer programming that allows you to intercept, modify, or extend functions. By using hooks, you can inject custom code to modify the behavior of a program when a specific event occurs.

This document describes the following content:

How to Implement

[h2]Overview of MallocDispatchTable

MallocDispatchTable, also known as the memory allocation table, provides the hook capability for memory operation functions such as malloc, calloc, realloc, and free in the libc standard library of HarmonyOS. This capability can be used to trace the memory allocation and freeing information of an app, helping quickly demarcate and locate memory leak issues.

Note: For details about memory basics, see Basic Concepts.

[h2]Hook Process of MallocDispatchTable

As shown in the following figure, you can use custom functions to replace the standard library functions. When an app calls the standard library functions, the custom functions are actually executed. By using the function pointers in MallocDispatchTable, the standard library functions can be redirected to the custom functions when they are called. The main capability of MallocDispatchTable is to decouple the implementation of the standard library functions from the custom functions.

You can use the OH_HiDebug_SetMallocDispatchTable() API to set the MallocDispatchTable used in the libc standard library and use the OH_HiDebug_GetDefaultMallocDispatchTable() API to obtain the default MallocDispatchTable in libc.

Scenario Case

[h2]When to Use

If you observe that the anonymous memory size of a program keeps increasing, you need to record the information (including the allocated memory size and address) about the program's calls to the mmap and munmap functions in the standard library. This helps you calculate the size of the memory that is allocated using mmap but not freed (no record of using munmap to free the corresponding memory address).

[h2]How to Develop

  1. Add the header file dependencies.

    #include "hidebug/hidebug.h"
    #include "hidebug/hidebug_type.h"

    First, reference the header file related to MallocDispatchTable.

  2. Create custom mmap and munmap methods.

    static void* MyMmap(void* addr, size_t len, int prot, int flags, int fd, off_t offset)
    {
        HiDebug_MallocDispatch* original = (HiDebug_MallocDispatch*)OH_HiDebug_GetDefaultMallocDispatchTable();
        void* returnAddr = original->mmap(addr, len, prot, flags, fd, offset);
        OH_LOG_INFO(LOG_APP, "test MyMmap with len:%{public}d and addr:%{public}p", len, returnAddr);
        return returnAddr;
    }
    
    static int MyMunmap(void* addr, size_t len)
    {
        HiDebug_MallocDispatch* original = (HiDebug_MallocDispatch*)OH_HiDebug_GetDefaultMallocDispatchTable();
        OH_LOG_INFO(LOG_APP, "test MyMunmap with len:%{public}d and addr:%{public}p", len, addr);
        return original->munmap(addr, len);
    }

    In the custom function, the memory address (function parameter addr) and memory range size (function parameter len) are printed in logs.

  3. Create an allocation table of the HiDebug_MallocDispatch type.

    //Obtain default MallocDispatchTable that can allocate memory directly.
    HiDebug_MallocDispatch* original = (HiDebug_MallocDispatch*)OH_HiDebug_GetDefaultMallocDispatchTable();
    //Create a MallocDispatchTable struct called current.
    HiDebug_MallocDispatch* current = (HiDebug_MallocDispatch*)original->malloc(sizeof(HiDebug_MallocDispatch));
    memset(current, 0, sizeof(HiDebug_MallocDispatch));
    //replace function pointers of current, from which self-defined functions can be redirected.
    current->mmap = MyMmap;
    current->munmap = MyMunmap;

    Create a HiDebug_MallocDispatch structure current and allocate the heap memory occupied by it through OH_HiDebug_GetDefaultMallocDispatchTable(). Modify the function pointers in the structure to point to the previously defined MyMmap and MyMunmap functions.

  4. Enable the custom MallocDispatchTable.

    OH_HiDebug_SetMallocDispatchTable(current);

    Replace the MallocDispatchTable used in the libc standard library with the custom allocation table.

  5. Call the mmap function in the libc standard library.

    char* mapPtr = nullptr;
    const size_t bufferSize = 100;  // 100 : the size of memory
    mapPtr = (char*)mmap(nullptr, bufferSize, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
    if (mapPtr == MAP_FAILED) {
        printf("mmap failed\n");
        return;
    }
    munmap(mapPtr, bufferSize);

    When the mmap function of the basic library is executed, it is automatically redirected to the previously defined MyMmap function to complete the service customization.

  6. Disable the custom MallocDispatchTable.

    //release memory of self-defined MallocDispatchTable struct.
    HiDebug_MallocDispatch* original = (HiDebug_MallocDispatch*)OH_HiDebug_GetDefaultMallocDispatchTable();
    original->free(current);
    //reset MallocDispatchTable strut that libc uses.
    OH_HiDebug_RestoreMallocDispatchTable();

    Call the OH_HiDebug_RestoreMallocDispatchTable() API to restore the default MallocDispatchTable of the standard library.

  7. Add the following dependencies to the CMakeLists.txt file:

    add_library(entry SHARED napi_init.cpp test_backtrace.cpp test_malloc_dispatch.cpp)
    target_link_libraries(entry PUBLIC libace_napi.z.so libhilog_ndk.z.so libohhidebug.so)

If a custom MallocDispatchTable is set for the app, it is mutually exclusive with some mechanisms provided by HarmonyOS. Pay attention to this after enabling the custom MallocDispatchTable in step 4.

The constraints are as follows:

  1. Out-of-bounds memory access cannot be detected using the GWP-ASan function. For details about the working principles of GWP-ASan, see GWP-ASan Detection Principles.
  2. The function call stack of the app cannot be captured using the nativehook plugin.
  1. Do not call the memory operation functions (malloc, free, mmap, and munmap) of the libc standard library in custom methods. Otherwise, an infinite loop will occur.
  2. Do not use hilog to print logs in the custom malloc method. Otherwise, a deadlock occurs.

Sample Code