目录

Memory Leaks Caused by Oversized Stack Memory

Introduction

Oversized stack memory of an app is one of the level-2 root causes of RSS memory leaks. This topic describes the possible root causes of oversized stack memory and provides case studies to help you analyze problems in the development and O&M states.

Root Cause

As the basic memory area for program running, the stack memory is typically used to store information such as local variables, function call chains, and return addresses. Generally, the stack memory is automatically managed by the system and is automatically released when a function returns. It is believed in the industry that stack memory does not leak. However, in the actual development and O&M of HarmonyOS, oversized stack memory can also lead to severe memory leak issues.

Memory leak caused by oversized stack memory is rooted in unbalanced thread lifecycle management, which is typically manifested in two types of issues:

Problem Analysis

[h2]Problem Analysis in the O&M State

You can analyze the lightweight smaps maintenance and debugging logs based on the basic log analysis method. If the memory usage of the stack category is the largest, you can narrow down the RSS memory leak issue to a stack memory leak issue. To further analyze the leak point, you can obtain the memory stack logs by referring to the method of obtaining memory stack logs, import the logs to DevEco Studio, and analyze the call stack based on the memory stack log analysis method to locate the leak point.

The speed of memory leaks has a great impact on the validity of the application memory stack. If the speed is too fast or too slow, the memory call stack may fail to hit the leak point. For fast memory leaks, you are advised to subscribe to resource leak events by referring to Subscribing to Resource Leak Events (ArkTS). In addition, use the configEventPolicy() method to subscribe to app page switching information to analyze the leak scenario and reproduce and locate the leak issue in the development state.

[h2]Problem Analysis in the Development State

If an RSS memory leak occurs in your app, you can reproduce the issue based on the scenario and use the Allocation feature of the Profiler tool in DevEco Studio to locate the stack memory leak issue by referring to Analysis approach in the development state.

Case Analysis

To clearly demonstrate how to locate memory leaks caused by oversized stack memory, the following describes the analysis process in the development and O&M states based on a negative case where memory leaks occur due to excessive thread requests.

[h2]Case: Memory Leak Caused by Excessive Thread Requests

In this negative case, the app requests a large number of threads but does not release them, resulting in excessive stack memory usage. After detecting an RSS memory leak in the app, the system manages and controls the app in the foreground. As a result, the app crashes.

Analysis approach in the O&M state

If you encounter this issue in the O&M state, perform the following steps for analysis:

  1. By subscribing to resource leak events, you can receive the fault log /data/storage/el2/log/resourcelimit/RESOURCE_OVERLIMIT_XXXX_XXXX.log in the sandbox.
  2. Find the keyword LOGGER_MEMCHECK_SAMPLIFY_SMAPS_INFO in the fault log and read the data as follows:

    LOGGER_MEMCHECK_SAMPLIFY_SMAPS_INFO
           Size         Rss        Swap                Category      Counts    Name
            512           0          52       arkts-static heap           2    [anon:ArkTs Static Object Space]
           1028          12           0                    stack          1    [anon:stack:55575]
           1028          12           0                    stack          1    [anon:stack:55576]
           1028          12           0                    stack          1    [anon:stack:55577]
           1028          12           0                    stack          1    [anon:stack:55578]
    ......

  3. Analyze the smaps maintenance and debugging logs, perform clustering based on the Category column, and sum up the values in the Rss and Swap columns for each type to obtain the total amount of memory requested for each type. After sorting, it is found that the total amount of memory for the stack type is the largest. Therefore, it can be preliminarily determined that the current RSS memory leak is caused by stack memory leak.
  4. After obtaining the Profiler logs using the method for obtaining memory stack logs, use the Profiler tool in DevEco Studio to import the memory stack logs and further analyze the leak point based on the memory stack log analysis method.

    1. In the following figure, open the Profiler component in DevEco Studio and click the position 1 to import the obtained memory stack logs.
    2. Click the Threads lane under System Resources, as shown in position 2.
    3. Click Call Trees in position 3 to view the memory allocation call stack.
    4. Click Created & Existing in position 4 to filter the memory that is allocated but not released and its call stack.
    5. Filter out the threads whose number of allocations is abnormal and their call stacks, as shown in position 5.

  5. Analyze the code snippet pointed to by the call stack. It is found that the app repeatedly allocates threads, and the threads are always running and not released. As a result, an RSS memory leak occurs.

Analysis approach in the development state

For problems in the development state, you can roughly infer the scenario where the RSS memory leak occurs. You can perform the following steps to check whether the problem is caused by thread stack leak and locate the fault:

  1. Run the hidumper --mem-smaps pid command to obtain the memory usage details of the specified process by referring to the method of analyzing problems in the development state. If the command output contains a large number of stack memories in the Category column, a thread leak occurs.

    # hidumper --mem-smaps 43709
    
    -------------------------------[memory]-------------------------------
    
                                        Shared      Shared      Private     Private
    Size        Rss         Pss         Clean       Dirty       Clean       Dirty       Swap        SwapPss     Counts      Category                         Name
    ......
    28          0           0           0           0           0           0           0           0           1           stack                            [anon:signal_stack:43766]
    28          0           0           0           0           0           0           0           0           1           stack                            [anon:signal_stack:43767]
    28          0           0           0           0           0           0           0           0           1           stack                            [anon:signal_stack:43768]
    28          0           0           0           0           0           0           0           0           1           stack                            [anon:signal_stack:43770]
    28          0           0           0           0           0           0           0           0           1           stack                            [anon:signal_stack:43802]
    28          0           0           0           0           0           0           0           0           1           stack                            [anon:signal_stack:43817]
    28          0           0           0           0           0           0           0           0           1           stack                            [anon:signal_stack:43878]
    28          0           0           0           0           0           0           0           0           1           stack                            [anon:signal_stack:654]
    ......
    1028        12          12          0           0           12          0           0           0           1           stack                            [anon:stack:43766]
    1028        12          12          0           0           12          0           0           0           1           stack                            [anon:stack:43767]
    1028        16          16          0           0           16          0           0           0           1           stack                            [anon:stack:43768]
    8196        24          24          0           0           24          0           0           0           1           stack                            [anon:stack:43816]
    1028        28          28          0           0           28          0           0           0           1           stack                            [anon:stack:43817]
    1028        8           8           0           0           8           0           0           0           1           stack                            [anon:stack:43878]
    ......

  2. Try to reproduce this scenario and use the Allocation feature of the Profiler tool in DevEco Studio to capture the abnormal increase points of memory.
  3. After the recording is complete, click the Threads lane under System Resources. It is found that the number of threads increases abnormally.
  4. Click the Call Trees button in position 1 shown in the following figure, and then click Created & Existing in position 2 to find the abnormal thread allocation call stack in position 3.

  5. Analyze the code snippet pointed to by the call stack. It is found that the app is repeatedly allocating threads, and the threads are always running and not released. As a result, an RSS memory leak occurs.

Rectification Suggestions

  1. Standardized thread lifecycle management
    • For all threads created using new Thread(), explicitly call join() to wait for the thread to finish or call detach() to set the thread to the detached state after the thread is started. This ensures that the system automatically reclaims resources when the thread exits.
    • Use a thread pool for unified management to avoid missing resource reclamation logic.
  2. Completeness of loop exit conditions
    • All infinite loops, such as while(true) and for(;;), must contain an explicit exit path, such as based on a counter threshold, timestamp expiration, or an external cancellation flag.
    • The loop body must check the thread interruption status and be able to respond to external interruption requests.
  3. Lock acquisition timeout and fairness
    • Avoid nested locks. If nesting is necessary, ensure that all threads acquire locks in the same sequence to eliminate the necessary conditions for deadlocks.