Memory leak detection method, electronic device and storage medium
By traversing the Android source code, determining the reference count of the Handler class, the problem of memory leak detection false positives caused by the Handler class in the prior art is solved, and the accuracy of detection is improved.
Patent Information
- Application Number
- CN202411803195.3
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2024-12-10
- Publication Date
- 2025-05-13
- Estimated Expiration
- 2044-12-10
AI Technical Summary
The prior art detects memory leaks caused by the Handler class in the Android messaging mechanism, which reduces the accuracy of memory leak detection.
By obtaining the source code to be detected, traversing the target message processing class, determining its corresponding target message processing object, and generating memory leakage detection results based on the reference count of these objects.
It improves the accuracy of memory leak detection, can accurately identify message processing objects with memory leaks, and reduces false alarms and missed reports.
Smart Images

Figure CN119396697B_ABST
Abstract
Description
Technical Field
[0001] The present application relates to the field of memory management technology, and in particular to a memory leak detection method, an electronic device, and a storage medium. Background Art
[0002] In the Android message passing mechanism, the Handler object is used for inter-thread communication. The Handler object is instantiated from the Handler class. The Handler object is associated with a message queue, which is used to store messages for inter-thread communication. If the messages in the message queue associated with the Handler object are not completely cleared, the Handler object cannot be released, and the Handler class corresponding to the Handler object still holds a reference to an external class (for example, the Activity class), which in turn causes the Garbage Collection (GC) thread to be unable to recycle the external class, resulting in a memory leak.
[0003] In the related art, detection is performed on the Handler class, which can only locate the Handler class and directly report the hidden danger of memory leakage, resulting in a large number of false alarms and reducing the accuracy of memory leakage detection. Summary of the invention
[0004] The purpose of the embodiments of the present application is to provide a memory leak detection method, an electronic device, and a storage medium, which can detect a message processing object with a memory leak and improve the accuracy of memory leak detection. The specific technical solution is as follows:
[0005] In a first aspect, in order to achieve the above-mentioned purpose, an embodiment of the present application provides a memory leak detection method, which is applied to an electronic device and includes:
[0006] Get the source code to be tested;
[0007] Traversing the source code to be detected, and determining a target message processing class in the source code to be detected;
[0008] For each target message processing class, determining a target message processing object corresponding to the target message processing class; wherein the target message processing object is used to process messages transmitted between two threads;
[0009] Based on the calling relationship of each target message processing object, determining the reference count of each target message processing object; wherein the reference count of a target message processing object indicates the number of times the target message processing object is referenced;
[0010] Based on the reference count of each target message processing object, a memory leak detection result is generated; wherein the detection result includes: a message processing object with a memory leak.
[0011] As can be seen from the above, the technical solution provided in this embodiment can determine the target message processing object corresponding to the target message processing class, and determine the reference count representing the number of times the target message processing object is referenced. Furthermore, based on the reference count of the target message processing object, the message processing object with memory leak is determined, thereby improving the accuracy of memory leak detection.
[0012] In one embodiment of the present application, the generation of a memory leak detection result based on the reference count of each target message processing object includes:
[0013] For each target message processing object, if the reference count of the target message processing object is 0, it is determined that there is no memory leak in the target message processing object;
[0014] If the reference count of the target message processing object is not 0, it is determined that the target message processing object has a memory leak.
[0015] As can be seen from the above, in the technical solution provided by this embodiment, the reference count of the target message processing object indicates the number of times the target message processing object is referenced. When the reference counts of the target message processing object for each message are all 0, it is determined that there is no memory leak in the target message processing object. When the reference count of the target message processing object for any message is not 0, it is determined that there is a memory leak in the target message processing object, which can improve the accuracy of memory leak detection.
[0016] In one embodiment of the present application, traversing the source code to be detected to determine the target message processing class in the source code to be detected includes:
[0017] Traversing the source code to be detected to obtain various types of message processing classes in the source code to be detected;
[0018] For each message processing class, if the message processing class is a static class, determine the message processing class as the message processing class to be filtered;
[0019] If the message processing class is not a static class and the message processing class satisfies the filtering condition, the message processing class is determined to be the message processing class to be filtered; wherein the filtering condition is satisfied including: the message processing class holds a weak reference, the message processing class inherits from a parent class holding a weak reference, and the constructor of the message processing class contains a specified parameter;
[0020] From the message processing classes, other message processing classes except the message processing class to be filtered are determined to obtain a target message processing class.
[0021] As can be seen from the above, the technical solution provided by this embodiment is that the message processing class holding weak references will not cause memory leaks, and the message processing class inherited from the message processing class holding weak references will not cause memory leaks. The message processing class that holds weak references is diffused and identified, and the message processing class that inherits from the message processing class holding weak references is determined, which can prevent false alarms. In addition, by filtering out the message processing classes of static classes, the message processing classes holding weak references, the message processing classes that inherit from the message processing classes holding weak references, and the message processing classes whose constructors contain specified parameters, the message processing classes that will not cause memory leaks can be filtered out. Subsequently, only the target message processing classes that may cause memory leaks are detected, which reduces the false alarm rate and improves the accuracy of memory leak detection.
[0022] In one embodiment of the present application, for each target message processing class, determining a target message processing object corresponding to the target message processing class includes:
[0023] For each target message processing class, determining a first message processing object obtained by instantiating the target message processing class, and determining a second message processing object generated in a preset manner based on the first message processing object;
[0024] The first message processing object and the second message processing object are obtained to obtain the target message processing object corresponding to the target message processing class.
[0025] From the above, it can be seen that the technical solution provided in this embodiment, after determining the first message processing object instantiated by the target message processing class, also performs handle expansion identification on the first message processing object, determines the second message processing object, and obtains the target message processing object. This can avoid missed detection caused by failure to identify the second message processing object, reduce the missed alarm rate, and further improve the accuracy of memory leak detection.
[0026] In one embodiment of the present application, the second message processing object includes at least one of the following:
[0027] Assigning the first message processing object to the newly created message processing object to obtain a second message processing object;
[0028] A second message processing object is obtained by declaring a variable of a newly created message processing object; the newly created message processing object is initialized and assigned a value to the first message processing object;
[0029] Inserting a new item into the container to obtain a second message processing object; the new item is the first message processing object;
[0030] a second message processing object for accessing the first message processing object in a container;
[0031] A second message processing object for accessing the first message processing object in an iterator;
[0032] Used to return a second message processing object defined by a function; the function definition includes the first message processing object;
[0033] A second message processing object used for transferring function parameters; the function parameters include the first message processing object.
[0034] In one embodiment of the present application, determining the reference count of each target message processing object based on the calling relationship of each target message processing object includes:
[0035] Traversing the called methods in the source code to be detected, and determining that the caller is a method of the target message processing object;
[0036] For each target message processing object, based on the control flow information and the parent node of the method called by the target message processing object, the calling information of the target message processing object is generated; wherein the calling information includes: the external class that calls the target message processing object, and the method called by the target message processing object;
[0037] Based on the call information of the target message processing object, a reference count of the target message processing object is calculated.
[0038] As can be seen from the above, the technical solution provided by this embodiment can determine the reference count of the target message processing object, and subsequently generate memory leak detection results based on the reference counts of each target message processing object, thereby further improving the accuracy of memory leak detection.
[0039] In one embodiment of the present application, the step of calculating a reference count of the target message processing object based on the call information of the target message processing object includes:
[0040] If the method called by the target message processing object includes the method of sending a delayed message, the reference count of the target message processing object is increased by 1;
[0041] If the method called by the target message processing object includes the method of sending a blank delayed message, the reference count of the target message processing object is increased by 1;
[0042] If the method called by the target message processing object includes a clear message method, the reference count of the target message processing object is reduced by 1;
[0043] If the method called by the target message processing object includes a publishing delay method, the reference count of the target message processing object is increased by 1;
[0044] If the method called by the target message processing object includes a clear callback method, the reference count of the target message processing object is reduced by 1;
[0045] If the method called by the target message processing object includes a clear callback and a message method, the reference count of the target message processing object is 0.
[0046] In one embodiment of the present application, the target message processing class is a Handler class; and the target message processing object is a Handler object.
[0047] As can be seen from the above, the technical solution provided in this embodiment can determine the target Handler object corresponding to the target Handler class, and determine the reference count representing the number of times the target Handler object is referenced. Then, based on the reference count of the target Handler object, the Handler object with memory leak is determined, thereby improving the accuracy of memory leak detection.
[0048] In a second aspect, an embodiment of the present application further provides an electronic device, including:
[0049] one or more processors and memory;
[0050] The memory is coupled to the one or more processors, and the memory is used to store computer program codes, wherein the computer program codes include computer instructions, and the one or more processors call the computer instructions to enable the electronic device to execute any of the above-mentioned memory leak detection methods.
[0051] In a third aspect, an embodiment of the present application further provides a computer-readable storage medium, comprising a computer program, which, when executed on an electronic device, enables the electronic device to execute any of the above-described memory leak detection methods.
[0052] In a fourth aspect, an embodiment of the present application further provides a computer program product, which includes executable instructions. When the executable instructions are executed on an electronic device, the electronic device executes any of the above-mentioned memory leak detection methods.
[0053] In a fifth aspect, an embodiment of the present application further provides a chip system, which is applied to an electronic device, and the chip system includes one or more processors, and the processor is used to call computer instructions so that the electronic device inputs data into the chip system, and executes any of the above-mentioned memory leakage detection methods to process the data and output the processing results.
[0054] The beneficial effects of the solutions provided by the embodiments in the second, third, fourth and fifth aspects can refer to the beneficial effects of the solutions provided by the embodiments in the first aspect. BRIEF DESCRIPTION OF THE DRAWINGS
[0055] In order to more clearly illustrate the technical solutions of the embodiments of the present application, the drawings required for use in the embodiments will be briefly introduced below. Obviously, the drawings described below are only some embodiments of the present application. For ordinary technicians in this field, other drawings can be obtained based on these drawings without paying creative labor.
[0056] Figure 1 A structural diagram of an electronic device provided in an embodiment of the present application;
[0057] Figure 2 A software structure block diagram of an electronic device provided in an embodiment of the present application;
[0058] Figure 3 A flowchart of a first memory leak detection method provided in an embodiment of the present application;
[0059] Figure 4 A flowchart of a second memory leak detection method provided in an embodiment of the present application;
[0060] Figure 5 A flowchart of a first method for determining a target Handler class provided in an embodiment of the present application;
[0061] Figure 6 A flowchart of a second method for determining a target Handler class provided in an embodiment of the present application;
[0062] Figure 7 A flowchart of a third memory leak detection method provided in an embodiment of the present application;
[0063] Figure 8 A flowchart of a fourth memory leak detection method provided in an embodiment of the present application;
[0064] Fig. 9 A call graph of a target Handler object provided in an embodiment of the present application;
[0065] Fig.10 A flowchart of a method for generating a call graph of a target Handler object provided in an embodiment of the present application;
[0066] Fig.11 A flowchart of a fifth memory leak detection method provided in an embodiment of the present application;
[0067] Fig.12A flowchart of a sixth memory leak detection method provided in an embodiment of the present application;
[0068] Fig.13 A flowchart of a seventh memory leak detection method provided in an embodiment of the present application;
[0069] Fig.14 A flowchart of an eighth memory leak detection method provided in an embodiment of the present application;
[0070] Fig.15 A structural diagram of a chip system provided in an embodiment of the present application. DETAILED DESCRIPTION
[0071] In order to better understand the technical solution of the present application, the embodiments of the present application are described in detail below with reference to the accompanying drawings.
[0072] In order to facilitate the clear description of the technical solutions of the embodiments of the present application, in the embodiments of the present application, the words "first" and "second" are used to distinguish the same items or similar items with substantially the same functions and effects. For example, the first instruction and the second instruction are to distinguish different user instructions, and their order is not limited. Those skilled in the art can understand that the words "first" and "second" do not limit the quantity and execution order, and the words "first" and "second" do not necessarily limit them to be different.
[0073] It should be noted that, in this application, words such as "exemplarily" or "for example" are used to indicate examples, illustrations or explanations. Any embodiment or design described as "exemplarily" or "for example" in this application should not be interpreted as being more preferred or more advantageous than other embodiments or designs. Specifically, the use of words such as "exemplarily" or "for example" is intended to present related concepts in a specific way.
[0074] The memory leak detection method provided in the embodiment of the present application is applied to electronic devices. The above electronic devices can be mobile phones, tablet computers, personal digital assistants (PDAs), smart watches, wearable electronic devices, augmented reality (AR) devices, virtual reality (VR) devices, robots, smart glasses, etc., so that the electronic devices can detect the Handler object with memory leak in the source code to be detected according to the method provided in the embodiment of the present application, thereby improving the accuracy of memory leak detection.
[0075] For example, Figure 1The structure diagram of the electronic device 100 is shown. The electronic device 100 may include a processor 110, a display screen 120, a camera 130, an internal memory 140, a Subscriber Identification Module (SIM) card interface 150, a Universal Serial Bus (USB) interface 160, a charging management module 170, a battery management module 171, a battery 172 with a cell and a battery protection device, a sensor module 180, a mobile communication module 190, a wireless communication module 200, an antenna 1 and an antenna 2, etc. The sensor module 180 may include a pressure sensor 180A, a fingerprint sensor 180B, a touch sensor 180C, an ambient light sensor 180D, etc.
[0076] It is to be understood that the structure illustrated in the embodiment of the present application does not constitute a specific limitation on the electronic device 100. In other embodiments of the present application, the electronic device 100 may include more or fewer components than shown in the figure, or combine some components, or split some components, or arrange the components differently. The components shown in the figure may be implemented in hardware, software, or a combination of software and hardware.
[0077] The processor 110 may include one or more processing units, for example: the processor 110 may include a central processing unit (CPU), an application processor (AP), a modem processor, a graphics processing unit (GPU), an image signal processor (ISP), a controller, a video codec, a digital signal processor (DSP), a baseband processor, and / or a neural network processor (NPU), etc. Among them, different processing units may be independent components or integrated into one or more processors. In some embodiments, the electronic device 100 may also include one or more processors 110. Among them, the controller may generate an operation control signal according to the instruction opcode and the timing signal to complete the control of fetching and executing instructions. In some other embodiments, a memory may also be provided in the processor 110 for storing instructions and data. Exemplarily, the memory in the processor 110 may be a high-speed cache memory. The memory may store instructions or data that the processor 110 has just used or circulated. If the processor 110 needs to use the instruction or data again, it may be directly called from the memory. This avoids repeated accesses, reduces the waiting time of the processor 110, and thus improves the efficiency of the electronic device 100 in processing data or executing instructions.
[0078] In some embodiments, the processor 110 may include one or more interfaces. The interface may include an Inter-Integrated Circuit (I2C) interface, an Inter-Integrated Circuit Sound (I2S) interface, a Pulse Code Modulation (PCM) interface, a Universal Asynchronous Receiver / Transmitter (UART) interface, a Mobile Industry Processor Interface (MIPI), a General-Purpose Input / Output (GPIO) interface, a SIM card interface and / or a USB interface, etc. Among them, the USB interface 160 is an interface that complies with the USB standard specification, and specifically can be a Mini USB interface, a Micro USB interface, a USB Type C interface, etc. The USB interface 160 can be used to connect a charger to charge the electronic device 100, and can also be used to transmit data between the electronic device 100 and a peripheral device. The USB interface 160 can also be used to connect headphones to play audio through the headphones.
[0079] It is understandable that the interface connection relationship between the modules illustrated in the embodiment of the present application is for illustrative purposes only and does not constitute a structural limitation on the electronic device 100. In other embodiments of the present application, the electronic device 100 may also adopt different interface connection methods in the above embodiments, or a combination of multiple interface connection methods.
[0080] The wireless communication function of the electronic device 100 can be implemented through the antenna 1, the antenna 2, the mobile communication module 190, the wireless communication module 200, the modem processor, the baseband processor, and the like.
[0081] Antenna 1 and antenna 2 are used to transmit and receive electromagnetic wave signals. Each antenna in electronic device 100 can be used to cover a single or multiple communication frequency bands. Different antennas can also be reused to improve the utilization of antennas. For example, antenna 1 can be reused as a diversity antenna for a wireless local area network. In some other embodiments, the antenna can be used in combination with a tuning switch.
[0082] The electronic device 100 implements the display function through a GPU, a display screen 120, and an application processor. The GPU is a microprocessor for image processing, which connects the display screen 120 and the application processor. The GPU is used to perform mathematical and geometric calculations for graphics rendering. The processor 110 may include one or more GPUs, which execute program instructions to generate or change display information.
[0083] The display screen 120 is used to display images, videos, etc. The display screen 120 includes a display panel. The display panel may be a liquid crystal display (LCD), an organic light-emitting diode (OLED), an active-matrix organic light-emitting diode or an active-matrix organic light-emitting diode (AMOLED), a flexible light-emitting diode (FLED), Miniled, MicroLed, Micro-oLed, a quantum dot light-emitting diode (QLED), etc. In some embodiments, the electronic device 100 may include one or more display screens 120.
[0084] In some embodiments of the present application, when the display panel is made of materials such as OLED, AMOLED, FLED, etc., the above Figure 1 The display screen 120 in the embodiment can be bent. Here, the display screen 120 can be bent means that the display screen can be bent to any angle at any position and can be kept at the angle, for example, the display screen 120 can be folded in half from the middle to the left or right. It can also be folded in half from the middle to the top or bottom.
[0085] The display screen 120 of the electronic device 100 can be a flexible screen. At present, flexible screens have attracted much attention for their unique characteristics and huge potential. Compared with traditional screens, flexible screens have the characteristics of strong flexibility and bendability, which can provide users with a new interaction method based on bendable characteristics, and can meet users' more needs for electronic devices. For electronic devices equipped with a foldable display, the foldable display on the electronic device can be switched between a small screen in a folded form and a large screen in an unfolded form at any time. Therefore, users use the split-screen function on electronic devices equipped with a foldable display more and more frequently.
[0086] The electronic device 100 can realize the shooting function through the ISP, the camera 130, the video codec, the GPU, the display screen 120 and the application processor, etc., wherein the camera 130 includes a front camera and a rear camera.
[0087] The ISP is used to process the data fed back by the camera 130. For example, when shooting, the shutter is opened, and light is transmitted to the camera photosensitive element through the lens. The light signal is converted into an electrical signal, and the camera photosensitive element transmits the electrical signal to the ISP for processing and converts it into an image visible to the naked eye. The ISP can perform algorithm optimization on the noise, brightness and color of the image. The ISP can also optimize the exposure and color temperature of the shooting scene and other parameters. In some embodiments, the ISP can be set in the camera 130.
[0088] The camera 130 is used to take photos or videos. The object generates an optical image through the lens and projects it onto the photosensitive element. The photosensitive element can be a charge coupled device (CCD) or a complementary metal oxide semiconductor (CMOS) phototransistor. The photosensitive element converts the optical signal into an electrical signal, and then transmits the electrical signal to the ISP to be converted into a digital image signal. The ISP outputs the digital image signal to the DSP for processing. The DSP converts the digital image signal into an image signal in a standard red green blue (RGB), YUV or other format. In some embodiments, the electronic device 100 may include 1 or N cameras 130, where N is a positive integer greater than 1.
[0089] The digital signal processor is used to process digital signals, and can process not only digital image signals but also other digital signals. For example, when the electronic device 100 is selecting a frequency point, the digital signal processor is used to perform Fourier transform on the frequency point energy.
[0090] Video codecs are used to compress or decompress digital videos. The electronic device 100 may support one or more video codecs. Thus, the electronic device 100 may play or record videos in a variety of coding formats, such as Moving Picture Experts Group (MPEG) 1, MPEG2, MPEG3, and MPEG4.
[0091] NPU is a neural network (NN) computing processor. By drawing on the structure of biological neural networks, such as the transmission mode between neurons in the human brain, it can quickly process input information and can also continuously self-learn. NPU can realize applications such as intelligent cognition of electronic device 100, such as image recognition, face recognition, voice recognition, text understanding, etc.
[0092] The internal memory 140 can be used to store one or more computer programs, which include instructions. The processor 110 can execute the above instructions stored in the internal memory 140, so that the electronic device 100 performs the image generation method provided in some embodiments of the present application, as well as various applications and data processing. The internal memory 140 may include a program storage area and a data storage area. Among them, the program storage area can store an operating system; the program storage area can also store one or more applications (such as a gallery, contacts, etc.). The data storage area can store data (such as photos, contacts, etc.) created during the use of the electronic device 100. In addition, the internal memory 140 may include a high-speed random access memory, and may also include a non-volatile memory, such as one or more disk storage components, flash memory components, universal flash storage (Universal Flash Storage, UFS), etc. In some embodiments, the processor 110 can execute the memory leak detection method provided in the embodiment of the present application, as well as other applications and data processing by running the instructions stored in the internal memory 140 and / or the instructions stored in the memory provided in the processor 110.
[0093] The internal memory 140 can be used to store the relevant programs of the memory leak detection method provided in the embodiment of the present application, and the processor 110 can be used to call the relevant programs of the memory leak detection method stored in the internal memory 140 when displaying information to execute the memory leak detection method of the embodiment of the present application.
[0094] The sensor module 180 may include a pressure sensor 180A, a fingerprint sensor 180B, a touch sensor 180C, an ambient light sensor 180D, and the like.
[0095] The pressure sensor 180A is used to sense the pressure signal and can convert the pressure signal into an electrical signal. In some embodiments, the pressure sensor 180A can be set on the display screen 120. There are many types of pressure sensors 180A, for example, they can be resistive pressure sensors, inductive pressure sensors or capacitive pressure sensors. The capacitive pressure sensor can be a parallel plate including at least two conductive materials. When the force acts on the pressure sensor 180A, the capacitance between the electrodes changes, and the electronic device 100 determines the intensity of the pressure according to the change in capacitance. When the touch operation acts on the display screen 120, the electronic device 100 detects the touch operation according to the pressure sensor 180A. The electronic device 100 can also calculate the position of the touch according to the detection signal of the pressure sensor 180A. In some embodiments, touch operations acting on the same touch position but with different touch operation intensities can correspond to different operation instructions. For example: when a touch operation with a touch operation intensity less than the first pressure threshold acts on a short message application icon, an instruction to view the short message is executed; when a touch operation with a touch operation intensity greater than or equal to the first pressure threshold acts on a short message application icon, an instruction to create a new short message is executed.
[0096] The fingerprint sensor 180B is used to collect fingerprints. The electronic device 100 can use the collected fingerprint characteristics to realize functions such as unlocking, accessing application locks, taking photos, and answering calls.
[0097] The touch sensor 180C is also called a touch control device. The touch sensor 180C can be arranged on the display screen 120, and the touch sensor 180C and the display screen 120 form a touch screen, which is also called a touch control screen. The touch sensor 180C is used to detect a touch operation acting on or near it. The touch sensor 180C can pass the detected touch operation to the application processor to determine the type of touch event. A visual output related to the touch operation can be provided through the display screen 120. In other embodiments, the touch sensor 180C can also be arranged on the surface of the electronic device 100, and is arranged at a different position from the display screen 120.
[0098] The ambient light sensor 180D is used to sense the brightness of the ambient light. The electronic device 100 can adaptively adjust the brightness of the display screen 120 according to the perceived brightness of the ambient light. The ambient light sensor 180D can also be used to automatically adjust the white balance when shooting. The ambient light sensor 180D can also transmit the environmental information of the device to the GPU.
[0099] The ambient light sensor 180D is also used to obtain the brightness, light ratio, color temperature, etc. of the environment in which the camera 130 captures images.
[0100] Figure 2A software structure block diagram of an electronic device applicable to an embodiment of the present application. The software system of the electronic device can adopt a layered architecture, an event-driven architecture, a micro-core architecture, a micro-service architecture, or a cloud architecture. The layered architecture divides the software system of the electronic device into several layers, each with a clear role and division of labor. The layers communicate with each other through software interfaces. In some embodiments, the software system can be divided into three layers, namely, an application layer (applications), an application framework layer (application framework), and a driver layer (hardware abstract layer, HAL).
[0101] The application layer can include a series of application packages. The application layer runs applications by calling the application programming interface (API) provided by the application framework layer. Figure 2 As shown, the application package may include multiple applications, such as camera, clock, browser, music, etc. It can be understood that the port of each of the above applications can be used to receive data.
[0102] The application framework layer provides API and programming framework for the applications in the application layer. The application framework layer includes some predefined functions. Figure 2 As shown, the application framework layer may include a window manager, a content provider, a view system, a resource manager, a notification manager, and a Dynamic Host Configuration Protocol (DHCP) module.
[0103] The driver layer is a layer between hardware and software, used to drive the hardware to make it work. The driver layer can be installed with multiple drivers for driving the hardware to work. For example, camera drivers, display drivers, audio drivers, and sensor drivers.
[0104] In addition, the electronic device also includes a hardware layer, which may include a camera, a speaker, a display screen, a battery, etc. The hardware layer is connected to the driver layer.
[0105] The following describes the application scenarios of the memory leak detection method provided in the embodiments of the present application.
[0106] The memory leak detection method provided in the embodiment of the present application detects memory leaks caused by message processing objects, and the message processing objects are instantiated from message processing classes. The following is an example of the Android operating system. The message processing object in the Android operating system is a Handler object, and the message processing class is a Handler class.
[0107] In the Android message passing mechanism, when threads need to communicate, the Handler class can be instantiated to obtain a Handler object, which is used to send and process messages between threads. For example, when the main thread of an application communicates with a child thread, some time-consuming operations (such as updating the user interface (UI)) will be performed in the child thread. After the operation is completed, the Handler object is called to send a message to the main thread to notify the main thread to perform the corresponding operation.
[0108] The Handler object is associated with a message queue, which is used to store messages for communication between threads. For Handler classes that are non-static inner classes or anonymous inner classes, they hold references to external classes (for example, activities, servers, broadcast receivers, etc.) by default. If the messages in the message queue associated with the Handler object are not completely cleared, the Handler object cannot be released, and the Handler class corresponding to the Handler object still holds a reference to the external class, which in turn makes it impossible for the GC thread to recycle the external class, resulting in memory leaks.
[0109] In the related art, detection on the Handler class can only locate the Handler class and directly report the hidden danger of memory leak. However, there are a large number of complex problems in actual development scenarios, such as a single module calling multiple Handler objects with different names, a single module having multiple different types of Handler classes, a single module having multiple Handler classes of the same type instantiating multiple Handler objects with different names, and multiple different modules calling their own Handler objects with the same name, etc. Some of the multiple Handler objects call the message clearing method, while some Handler objects do not call the message status method. For the Handler class detection, it is impossible to detect whether the Handler object instantiated by the Handler class is released. In addition, the code patterns of different types (such as static inner classes, anonymous classes, etc.) are different and complex. Detecting memory leaks only for the Handler class will lead to a large number of false positives, reducing the accuracy of memory leak detection.
[0110] The following is an explanation of the source code example with memory leaks.
[0111] Example 1:
[0112] public class HandlerTest extends AppCompatActivity{
[0113] / / Non-static inner class
[0114] private class ThreadHandler extends Handler{
[0115] @Override
[0116] public void handleMessage(Message msg){
[0117] }
[0118] }
[0119] @Override
[0120] protected void onCreate(Bundle savedlnstanceState){
[0121] ThreadHandler threadHandler=new ThreadHandler(); / / Create a ThreadHandler instance
[0122] threadHandler.sendEmptyMessageDelayed(1,1000); / / Send delayed message
[0123] super.onCreate(savedlnstanceState);
[0124] }
[0125] @Override
[0126] protected void onDestroy(){
[0127] super.onDestroy(); / / Close external class
[0128] }
[0129] }
[0130] The Handler class (ThreadHandler) in the above example 1 is a non-static inner class. ThreadHandler is instantiated to obtain a Handler object (threadHandler). The method called by threadHandler is sendEmptyMessageDelayed(1,1000).
[0131] In the above example 1, the external class (ie, Activity) is closed by calling the onDestroy method, but the threadHandler message clearing operation is not performed. In this case, there may still be messages in the threadHandler message queue, resulting in the Handler object (ie, threadHandler) being unable to be released, which in turn causes a memory leak.
[0132] Example 2:
[0133] public class HandlerTest5 extends AppCompatActivity{
[0134] @Override
[0135] protected void onCreate(Bundle savedlnstanceState){
[0136] / / Anonymous class
[0137] Handler threadHandler=new Handler() / / Create an anonymous Handler instance
[0138] @Override
[0139] public void handleMessage(Message msg){
[0140] }
[0141] }
[0142] threadHandler.sendEmptyMessageDelayed(1,1000); / / Send delayed message
[0143] super.onCreate(savedlnstanceState);
[0144] }
[0145] @Override
[0146] protected void onDestroy(){
[0147] super.onDestroy(); / / Close external class
[0148] }
[0149] }
[0150] The Handler class (i.e., Handler) in the above example 2 is an anonymous class. The Handler is instantiated to obtain a Handler object (i.e., threadHandler). The method called by threadHandler is sendEmptyMessageDelayed(1,1000).
[0151] In the above example 2, the external class (ie, Activity) is closed by calling the onDestroy method, but the threadHandler message clearing operation is not performed. In this case, there may still be messages in the threadHandler message queue, resulting in the Handler object (ie, threadHandler) being unable to be released, which in turn causes a memory leak.
[0152] In order to solve the above problems, the memory leak detection method provided in the embodiment of the present application adopts a context-sensitive hybrid static analysis method to detect the source code to be detected. It can perform more accurate detection on complex memory leak problems of multiple modules, multiple types and multiple instances, and directly locate the Handler object with memory leaks, which can greatly reduce false alarms and missed alarms, improve the detection effect of memory leaks, and thus improve the code quality.
[0153] Compared with the prior art, the memory leak detection method provided in the embodiment of the present application has been enhanced in multiple dimensions to determine the Handler object with memory leaks and improve the accuracy of memory leak detection. For example, feature recognition is performed on the Handler class to determine the Handler class holding weak references, the Handler class whose constructor contains Looper parameters, etc., to reduce the false alarm rate. In addition, based on context-sensitive Handler object handle recognition and handle propagation analysis, that is, on the basis of identifying the Handler object instantiated by the Handler class (i.e., the first Handler object), the handle propagation analysis is performed on the first Handler object to identify the Handler object obtained by the first Handler object (i.e., the second Handler object), to avoid the situation where the Handler object is missed and reduce the missed alarm rate. And reference counting analysis is performed based on the calling relationship of the Handler object to locate the Handler object with memory leaks and reduce the false alarm rate.
[0154] Next, the memory leak detection method provided in the embodiment of the present application is described in detail through specific examples.
[0155] In one embodiment of the present application, see Figure 3 , Figure 3 A flowchart of a memory leak detection method provided in an embodiment of the present application, the method is applied to an electronic device, and the method may include the following steps:
[0156] S301: Obtain source code to be detected.
[0157] S302: Traverse the source code to be detected and determine the target message processing class in the source code to be detected.
[0158] S303: For each target message processing class, determine a target message processing object corresponding to the target message processing class.
[0159] The target message processing object is used to process the messages transmitted between two threads.
[0160] S304: Determine the reference count of each target message processing object based on the calling relationship of each target message processing object.
[0161] The reference count of a target message processing object indicates the number of times the target message processing object is referenced.
[0162] S305: Generate a memory leak detection result based on the reference count of each target message processing object.
[0163] The detection results include: a message processing object with a memory leak.
[0164] As can be seen from the above, the technical solution provided in this embodiment can determine the target message processing object corresponding to the target message processing class, and determine the reference count representing the number of times the target message processing object is referenced. Furthermore, based on the reference count of the target message processing object, the message processing object with memory leak is determined, thereby improving the accuracy of memory leak detection.
[0165] For step S301 and step S302, the source code to be detected may be a source code that has been developed but has not yet been put into operation. The following description is made by taking the message processing class as the Handler class and the message processing object as the Handler object as an example.
[0166] If a Handler class is defined in the source code to be detected, the source code to be detected can be traversed to determine the Handler class in the source code to be detected, and then the target Handler class (i.e., the target message processing class) can be determined.
[0167] In some embodiments, Figure 3 Based on Figure 4 , step S302 may include the following steps:
[0168] S3021: Traverse the source code to be detected to obtain various types of message processing classes in the source code to be detected.
[0169] S3022: For each message processing class, if the message processing class is a static class, determine that the message processing class is a message processing class to be filtered.
[0170] S3023: If the message processing class is not a static class and the message processing class meets the filtering condition, determine that the message processing class is the message processing class to be filtered.
[0171] The filtering conditions are satisfied as follows: the message processing class holds a weak reference, the message processing class inherits from a parent class that holds a weak reference, and the constructor of the message processing class contains specified parameters.
[0172] S3024: Determine other message processing classes except the message processing class to be filtered from the message processing classes, and obtain a target message processing class.
[0173] If the source code to be tested is developed according to the Abstract Syntax Tree (AST), then the source code to be tested is traversed according to the AST structure to obtain various types of Handler classes in the source code to be tested. The types of Handler classes include: static anonymous class, non-static anonymous class, static non-anonymous class, non-static non-anonymous class, static inner class, non-static inner class, anonymous inner class, non-anonymous inner class, etc.
[0174] Some of the above types of Handler classes may cause memory leaks, while others may not. Therefore, it is necessary to determine the Handler class that may cause memory leaks from the above types of Handler classes and obtain the target Handler class.
[0175] The Handler class of a static class (i.e., static anonymous class, static non-anonymous class, and static inner class) will not cause memory leaks. For each Handler class, if the Handler class is a static class, it is determined that the Handler class will not cause memory leaks, and the Handler class is determined to be the Handler class to be filtered. If the Handler class is not a static class, the Handler class may cause memory leaks, and based on the characteristics of the Handler class, a step is performed to detect whether the Handler class will cause memory leaks.
[0176] Read characteristic fields from the definition of the Handler class, including: a field that records whether the Handler class holds a weak reference, a field that records whether the Handler class contains a specified parameter, and a field that records whether the Handler class inherits from a parent class that holds a weak reference. The specified parameter is a Looper parameter.
[0177] Determine whether the characteristics of the Handler class meet the filtering conditions. If the characteristics of the Handler class meet any of the following filtering conditions, it is determined that the Handler class will not cause memory leaks, and the Handler class is determined to be the Handler class to be filtered. The Handler class meets the filtering conditions including: the Handler class holds a weak reference, the Handler class inherits from a parent Handler class that holds a weak reference, and the constructor of the Handler class contains a Looper parameter.
[0178] A weak reference is a reference that cannot ensure that the object it refers to will not be reclaimed by the garbage collection thread. If an object is only referenced by a weak reference, it is considered inaccessible (or weakly accessible) and may be reclaimed at any time. Therefore, a Handler class that holds a weak reference will not cause memory leaks.
[0179] Then, the Handler class that will not cause memory leaks (ie, the Handler class to be filtered) is filtered out to obtain the target Handler class.
[0180] See also Figure 5 , Figure 5 A flowchart of a method for determining a target Handler class provided in an embodiment of the present application. In this embodiment, the target message processing class is the target Handler class, and the target message processing object is the target Handler object. The method includes the following steps:
[0181] S501: SourceCodeSCanner (source code scanner).
[0182] S502: Get all Handler classes.
[0183] S503: Filter static classes.
[0184] S504: Collect the Handler classes that hold WeakReference (weak reference) and add them to the WeakReferenceHandlerSet (weak reference operator determination) set.
[0185] S505: Non-inner classes are put into the candidateWeakRefHandlers (candidates for weak reference operator classes) collection.
[0186] S506: Filter special cases related to constructor Looper parameters.
[0187] S507: Collect Handler classes of anonymous classes and non-anonymous inner classes.
[0188] SourceCodeSCanner is an open source source code detection tool that is used to traverse the source code to be detected and obtain all Handler definition source points (i.e. Handler classes) in the source code to be detected, that is, to obtain all Handler classes. After determining the Handler class in the source code to be detected, the type of the Handler class can be obtained according to the definition of the Handler class, and the static class Handler class that will not cause memory leaks can be filtered out.
[0189] Then, the Handler classes holding WeakReference are collected and added to the WeakReferenceHandlerSet collection. The WeakReferenceHandlerSet collection is used to record the Handler classes holding WeakReference, and the Handler classes in the WeakReferenceHandlerSet collection are subsequently filtered out.
[0190] It is determined that among the Handler classes of non-inner classes, there may be Handler classes (i.e., subclasses) that inherit from the parent class holding WeakReference. This type of Handler class will not cause memory leaks. In this case, the Handler class of the non-inner class is put into the candidateWeakRefHandlers collection, and the Handler classes in the candidateWeakRefHandlers collection are further filtered later.
[0191] In addition, the Handler classes whose constructors contain Looper parameters are filtered out, and the Handler classes of anonymous classes and non-anonymous inner classes are collected to obtain the target Handler class.
[0192] See also Figure 6 , Figure 6 A flowchart of a method for determining a target Handler class provided in an embodiment of the present application. In this embodiment, the target message processing class is the target Handler class, and the target message processing object is the target Handler object. The method may include the following steps:
[0193] S601: WeakReferenceHandlerSet (weak reference handler set) expansion.
[0194] S602: Find the subclass inherited from WeakReferenceHandlerSet from candidateWeakRefHandlers (candidates of weak reference operator class).
[0195] S603: Weak reference filtering WeakReferenceHandlerSet.
[0196] exist Figure 5 Based on the method, the WeakReferenceHandlerSet collection is expanded, that is, from the Handler classes in the candidateWeakRefHandlers collection, the subclasses (i.e. Handler classes) inherited from the WeakReferenceHandlerSet are determined and added to the WeakReferenceHandlerSet collection. Then, the Handler classes in the WeakReferenceHandlerSet collection are filtered out to obtain the target Handler class.
[0197] As can be seen from the above, the technical solution provided by this embodiment is that the Handler class holding a weak reference (referred to as the RefHandler class) will not cause memory leaks, and the Handler class inherited from the RefHandler class will not cause memory leaks. The RefHandler class is diffused and identified to determine the Handler class inherited from the RefHandler class, which can prevent false alarms. In addition, by filtering out the Handler class of the static class, the Handler class holding a weak reference, the Handler class inherited from the RefHandler class, and the Handler class whose constructor contains the Looper parameter, the Handler class that will not cause memory leaks can be filtered out. Subsequently, only the target Handler class that may cause memory leaks is detected, which reduces the false alarm rate and improves the accuracy of memory leak detection.
[0198] For step S303, if the target Handler class is a Handler class that may cause memory leaks, the target Handler object (ie, the target message processing object) corresponding to the target Handler class may also cause memory leaks. After determining the target Handler class, the target Handler object corresponding to the target Handler class is further determined.
[0199] In some embodiments, Figure 3 Based on Figure 7 , step S303 may include the following steps:
[0200] S3031: For each target message processing class, determine a first message processing object obtained by instantiating the target message processing class, and determine a second message processing object generated in a preset manner based on the first message processing object.
[0201] S3032: Acquire the first message processing object and the second message processing object to obtain the target message processing object corresponding to the target message processing class.
[0202] The following description is made by taking the target message processing class as the target Handler class and the target message processing object as the target Handler object as an example. The target Handler object corresponding to the target Handler class includes: a first Handler object instantiated from the target Handler class and a second Handler object obtained from the first Handler object.
[0203] For each target Handler class, first determine the first Handler object instantiated by the target Handler class. For example, the following handler1 and handler2 are two instances (ie, instantiated Handler objects) of myHandler (ie, Handler class).
[0204] Handler handler1 = new myHandler(); / / Create myHandler instance handler1
[0205] Handler handler2 = new myHandler(); / / Create myHandler instance handler2
[0206] The Handler object can also be called a Handler handle. There are other objects that call the Handler handle in the source code to be detected. This type of object may also cause memory leaks. Therefore, based on the data flow dependency in the source code to be detected, handle propagation analysis is performed, and handle expansion identification is performed for the first Handler object, that is, the second Handler object generated in a preset manner based on the first Handler object is determined. For example, the first Handler object (i.e., the Handler handle) can be handle expanded and identified according to the expansion identification rules shown in Table 1 to obtain the second Handler object. Then, by obtaining the first Handler object and the second Handler object, the target Handler object corresponding to the target Handler class can be obtained.
[0207] Refer to Table 1, which is a handle expansion identification rule table provided in an embodiment of the present application. In this embodiment, the target message processing class is the target Handler class, and the target message processing object is the target Handler object.
[0208] Table 1
[0209]
[0210] Accordingly, according to the handle expansion identification rules shown in Table 1 above, identifying the second Handler object (i.e., the second message processing object) obtained based on the first Handler object (i.e., the first message processing object) includes at least one of the following:
[0211] The second Handler object is obtained by assigning the first Handler object to the newly created Handler object. For example, in the above Table 1, handler1 is the first Handler object obtained by instantiating the Handler, and handler1 is assigned to handler2, and handler2 is the second Handler object.
[0212] A second Handler object is obtained by declaring a variable for the newly created Handler object; the newly created Handler object is initialized and assigned the value of the first Handler object.
[0213] The second Handler object is obtained by inserting a new item into the container; the new item is the first Handler object. For example, the container in Table 1 above is an array represented by Handler[5], which contains 5 elements. Handler1 (the first Handler object) is inserted into the array as the first element of the array (i.e., handlerList[0]) to obtain the second Handler object.
[0214] The second Handler object used to access the first Handler object in the container. For example, in Table 1 above, the second Handler object used to access the first element in the array (i.e., handlerList[0]). The first element in the array (i.e., handlerList[0]) is the first Handler object.
[0215] The second Handler object used to access the first Handler object in the iterator. For example, in Table 1 above, the second Handler object used to access the handler (i.e., the first Handler object) in the iterator (i.e., iterator).
[0216] Used to return the second Handler object of the function definition; the function definition includes the first Handler object. For example, in the above Table 1, the second Handler object of the function definition including the first Handler object (ie, handler) is returned.
[0217] The second Handler object used to transfer function parameters; the function parameters include the first Handler object. For example, in the above Table 1, the second Handler object of the first Handler object (ie, handler) is transferred as the function parameter.
[0218] From the above, it can be seen that the technical solution provided in this embodiment, after determining the first Handler object instantiated by the target Handler class, also performs handle expansion identification on the first Handler object, determines the second Handler object, and obtains the target Handler object, which can avoid missed detection caused by failure to identify the second Handler object, reduce the missed alarm rate, and further improve the accuracy of memory leak detection.
[0219] For step S304, a target message processing object (such as a target Handler object) is associated with a message queue, which is used to store messages for corresponding inter-thread communication. When the external class held by the target Handler class ends, if there are still unprocessed messages in the message queue associated with the target Handler object corresponding to the target Handler class, the external class held by the target Handler class will cause a memory leak. Therefore, after determining the target Handler object, it is necessary to perform a reference count on the message queue associated with the target Handler object (i.e., determine the reference count of the target Handler object). When the target Handler object has no reference count (i.e., the reference count is 0), there are no messages in the message queue associated with the target Handler object, and it can be determined that there is no risk of memory leak. When the target Handler object has a reference count (i.e., the reference count is not 0), there are messages in the message queue associated with the target Handler object, and it can be determined that there is a risk of memory leak. The call relationship refers to the external class that calls the target Handler object, and the internal method called by the target Handler object, etc.
[0220] In some embodiments, Figure 3 Based on Figure 8 , step S304 may include the following steps:
[0221] S3041: Traverse the called methods in the source code to be detected and determine that the caller is a method of the target message processing object.
[0222] S3042: For each target message processing object, based on the control flow information and parent node of the method called by the target message processing object, generate calling information of the target message processing object.
[0223] The calling information includes: the external class that calls the target message processing object, and the internal method that the target message processing object calls.
[0224] S3043: Calculate the reference count of the target message processing object based on the calling information of the target message processing object.
[0225] The following example takes the target message processing class as the target Handler class and the target message processing object as the target Handler object. Multiple methods are defined in the source code to be tested, some of which are called and some are not. The uncalled methods will not be called by the target Handler object, which will not cause memory leaks. Therefore, first traverse the called methods in the source code to be tested, and determine the methods whose callers are the target Handler object, that is, determine the methods called by the target Handler object.
[0226] Then, the control flow information of the method called by the target Handler object is obtained. The control flow information refers to the calling mode from the external class that calls the target Handler object to the method called by the target Handler object. For example, if-else statements, try-catch-finally statements, switch statements, loop statements, etc.
[0227] For example, in an if-else statement, the if statement is a call from the external class of the target Handler object to the method called by the target Handler object, or the else statement is a call from the external class of the target Handler object to the method called by the target Handler object.
[0228] And get the parent node of the method called by the target Handler object. The parent node refers to the upper-level method of the method called by the target Handler object. You can also get the call chain of the target Handler object, and then get the call information of the target Handler object.
[0229] The call information of the target Handler object may be represented in the form of a call graph or a call table.
[0230] Exemplarily, the calling information of mHandler2 is as follows, which can be represented by the calling table shown in Table 2, or by Fig. 9 The call graph shown.
[0231] TestActivity.onCreate→ TestActivity.doSomething→mHandler2.sendMessageDelay(A)
[0232] See Table 2. Table 2 is a call table of a target Handler object provided in an embodiment of the present application. In this embodiment, the target message processing class is the target Handler class, and the target message processing object is the target Handler object.
[0233] Table 2
[0234]
[0235] For example, see Fig. 9 , Fig. 9 A call graph of a target Handler object provided in an embodiment of the present application. Fig. 9 The call graph in is a directed graph, and the arrows point to indicate the call relationship.
[0236] Table 2 and Fig. 9 The target Handler object in the call information is mHandler2. The method called by the target Handler object is sendMessageDelay(A), which is an internal method of mHandler2. The method called by the target Handler object is doSomething, which is an external method of mHandler2. The external class called by the target Handler object is Activity.
[0237] See also Fig.10 , Fig.10 A flowchart of a method for generating a call graph of a target Handler object provided in an embodiment of the present application. In this embodiment, the target message processing class is the target Handler class, and the target message processing object is the target Handler object. The method may include the following steps:
[0238] S1001: Record the Handler instance name and type.
[0239] S1002: Traverse method call nodes.
[0240] S1003: Determine whether the method caller is a Handler instance, if yes, execute step S1004, if no, execute step S1002.
[0241] S1004: Obtain control flow information.
[0242] S1005: Get the parent node of the current method and generate a call chain.
[0243] S1006: Save the control flow information and the call chain, and generate a call graph.
[0244] A Handler instance refers to a target Handler object. The instance name is the ID (identity identifier) of the target Handler object, and the type is the type of the target Handler class that instantiates the target Handler object.
[0245] The method call node refers to the method called in the source code to be detected, that is, to determine each method called in the source code to be detected, and for each method called in the source code to be detected, determine whether the caller of the method is a Handler instance (i.e., a Handler object). If the caller of the method is not a Handler instance, it will not cause memory leaks, and then return to step S1002 to continue to determine whether the caller of the next method is a Handler instance. If the caller of the method is a Handler instance, obtain the control flow information of the Handler instance, and obtain the parent node of the method to generate a call chain. Then, save the control flow information and the call chain to generate a call graph (i.e., call information) of the Handler instance. Control flow information, parent node, call chain reference Figure 8 Related introduction of implementation examples.
[0246] After the call information of the target Handler object is obtained, based on the method called by the target Handler object recorded in the call information, the reference count of the target Handler object can be calculated according to the reference count determination rule shown in Table 3.
[0247] Refer to Table 3, which is a reference count determination rule table provided in an embodiment of the present application. In this embodiment, the target message processing class is the target Handler class, and the target message processing object is the target Handler object.
[0248] Table 3
[0249]
[0250] Whether the above table 3 depends on the ID refers to whether the method operates on the message of the specific ID. For example, the sendMessageDelay method depends on the ID. In the above table 2, mHandler2 calls the sendMessageDelay method, which means that mHandler2 sends the delayed message A. The removeCallbacksAndMessages method does not depend on the ID. Calling the removeCallbacksAndMessages method can clear all messages in the message queue without relying on the ID.
[0251] Accordingly, according to the reference count determination rule shown in Table 3, the method of calculating the reference count of the target Handler object (ie, the target message processing object) includes:
[0252] If the method called by the target Handler object includes a method for sending a delayed message (e.g., sendMessageDelay), the reference count of the target Handler object for the sent message is increased by 1;
[0253] If the method called by the target Handler object includes a method for sending a blank delayed message (e.g., sendEmptyMessageDelayed), the reference count of the target Handler object for the sent message is increased by 1;
[0254] If the method called by the target Handler object includes a message clearing method (such as removeMessages), the reference count of the target Handler object for the cleared message is reduced by 1;
[0255] If the method called by the target Handler object includes a publishing delay method (such as postDelayed), the reference count of the target Handler object for the published message is increased by 1;
[0256] If the method called by the target Handler object includes a clear callback method (such as removeCallbacks), the reference count of the target Handler object for the cleared message is reduced by 1;
[0257] If the method called by the target Handler object includes a method for clearing callbacks and messages (for example, removeCallbacksAndMessages), the reference count of the target Handler object for all messages is 0.
[0258] As can be seen from the above, the technical solution provided in this embodiment can determine the reference count of the target Handler object, and subsequently generate memory leak detection results based on the reference counts of each target Handler object, thereby further improving the accuracy of memory leak detection.
[0259] For step S305, the reference count of a target message processing object for different messages includes: the number of times the target message processing object is referenced by different methods. The number of references can indicate whether there are unprocessed messages in the message queue associated with the target message processing object, that is, whether the target message processing object will cause a memory leak.
[0260] Correspondingly, based on the reference count of each target message processing object, the message processing object with memory leak can be determined, and the detection result of the memory leak can be obtained.
[0261] In some embodiments, Figure 3 Based on Fig.11 , step S305 may include the following steps:
[0262] S3051: For each target message processing object, if the reference count of the target message processing object is 0, it is determined that there is no memory leak in the target message processing object.
[0263] S3052: If the reference count of the target message processing object is not 0, it is determined that a memory leak exists in the target message processing object.
[0264] The following is an example in which the target message processing class is the target Handler class and the target message processing object is the target Handler object. For each target Handler object, if the reference count of each message of the target Handler object is 0, it means that there is no unprocessed message in the message queue associated with the target Handler object, then the target Handler class corresponding to the target Handler object can be released, and further, the external class held by the target Handler class can also be released, which will not cause memory leaks, and it is determined that the target Handler object does not have a memory leak.
[0265] If the reference count of the target Handler object for any message is not 0, it means that there are unprocessed messages in the message queue associated with the target Handler object. Then the target Handler class corresponding to the target Handler object cannot be released. Furthermore, the external class held by the target Handler class cannot be released, which will cause a memory leak. It is determined that the target Handler object has a memory leak.
[0266] The following is an example of determining the reference count of the target Handler object and determining the memory leak detection result, where true (correct) means there is no memory leak risk, and false (error) means there is a memory leak risk:
[0267] Path1: Handler1.sendMessageDelay(A)-> Handler1.removeMessages(A) true
[0268] The information in the above call chain (Path) 1 indicates that Handler1 calls the method sendMessageDelay to send the delayed message A, and Handler1 also calls the method removeMessages to clear the delayed message A. Then, Handler1 first increases the reference count of message A by 1 and then decreases by 1, that is, the reference count of Handler1 is 0, and there is no risk of memory leakage.
[0269] Path2: Handler1.sendMessageDelay(A)-> Handler2.removeMessages(A)false
[0270] The information in Path2 above indicates that: Handler1 calls the sendMessageDelay method to send a delayed message A, and Handler2 calls the removeMessages method to clear the delayed message A. Then, Handler1 first increases the reference count of message A by 1, and Handler2 decreases the reference count of message A by 1. That is, the reference counts of Handler1 and Handler2 are not 0, and there is a risk of memory leakage.
[0271] Path3: Handler1.sendMessageDelay(A)-> Handler1.removeCallbacksAndMessages() true
[0272] The information in Path3 above indicates that Handler1 calls the sendMessageDelay method to send a delayed message A, and Handler1 calls the removeCallbacksAndMessages method to clear the message queue, that is, to clear all messages in the message queue. Then, the reference count of each message in Handler1 is cleared to zero, that is, the reference count of Handler1 is 0, and there is no risk of memory leakage.
[0273] Path4: Handler1.sendMessageDelay(A) -> Handler1.removeMessages(B)false
[0274] The information in Path4 above indicates that Handler1 calls the sendMessageDelay method to send a delayed message A, and Handler1 calls the removeMessages method to clear message B. Then Handler1's reference count for message A is increased by 1, and the reference count for message B is decreased by 1, that is, the reference count of Handler1 is not 0, and there is a risk of memory leakage.
[0275] Path5: Handler1.sendMessageDelay(A) -> Handler1.removeMessages(B)->Handler1.removeCallbacksAndMessages() true
[0276] The information in the above Path5 indicates that: Handler1 calls the sendMessageDelay method to send the delayed message A, and Handler1 calls the removeMessages method to clear the message B, and Handler1 calls the removeCallbacksAndMessages method to clear the message queue. Then, Handler1 adds 1 to the reference count of message A and decrements 1 to the reference count of message B. Then, the reference count of Handler1 is cleared, that is, the reference count of Handler1 is 0, and there is no risk of memory leakage.
[0277] After determining the detection result of the memory leak, a detection report containing the detection result can also be generated and displayed to the developer. Accordingly, the developer can optimize the source code to be detected based on the detection report to avoid memory leaks and thus improve the code quality.
[0278] The following is an example of a test report for a source code to be tested:
[0279] The Handler class of a non-static inner class or anonymous inner class holds a reference to the outer class, which may cause memory leaks.
[0280] Modification suggestion: Although the removeMessages method may have been called to perform fixed-point message clearing, it cannot be completely guaranteed that there will be no messages in the message queue when the external class is closed. Therefore, it is recommended to call the removeCallbacksAndMessages method at the end position of the corresponding external class closure (such as the onDestroy method of the Activity) to completely clear the message queue.
[0281] The above test report indicates that the Handler class of the source code to be tested has the risk of memory leakage. In addition, modification suggestions for the source code to be tested are also given. For example, although the removeMessages method may have been called to clear messages in the source code to be tested, since removeMessages is applicable to clearing messages with a specified ID, there may be messages that have not called the removeMessages method and still exist in the message queue. Therefore, it is recommended to call the removeCallbacksAndMessages method to completely clear the message queue to avoid unprocessed messages in the message queue and avoid memory leakage. In addition, the Handler object that is at risk of memory leakage can also be prompted in the above test report.
[0282] As can be seen from the above, in the technical solution provided by this embodiment, the reference count of the target Handler object indicates the number of times the target Handler object is referenced. When the reference count of the target Handler object for each message is 0, it is determined that there is no memory leak in the target Handler object. When the reference count of the target Handler object for any message is not 0, it is determined that there is a memory leak in the target Handler object, which can improve the accuracy of memory leak detection.
[0283] See also Fig.12 , Fig.12 A flowchart of a memory leak detection method provided in an embodiment of the present application. In this embodiment, the target message processing class is the target Handler class, and the target message processing object is the target Handler object.
[0284] S1201: Generate a call graph based on handles.
[0285] S1202: Perform reference count analysis based on the call graph.
[0286] S1203: Determine whether the reference count is cleared to 0, if so, execute step S1205, if not, execute step S1204.
[0287] S1204: Generate a problem report.
[0288] S1205: End.
[0289] The handle refers to the target Handler object in the above embodiment, and the call graph is a specific representation of the call information in the above embodiment. Generating a call graph based on the handle means generating a call graph of the target Handler object for each target Handler object in the source code to be detected.
[0290] Then, reference count analysis is performed according to the call graph of the target Handler object, and the reference counts of the target Handler object for different messages are calculated. Then, it is determined whether the reference count of the target Handler object for each message is 0. If the reference count of the target Handler object for each message is 0, it is determined that there is no risk of memory leakage, and the detection process ends. If the reference count of the target Handler object for each message is not 0, it is determined that there is a risk of memory leakage, and a problem report (i.e., the detection report in the aforementioned embodiment) is generated, and the detection process ends.
[0291] See also Fig.13 , Fig.13 A flowchart of a memory leak detection method provided in an embodiment of the present application. In this embodiment, the target message processing class is the target Handler class, and the target message processing object is the target Handler object.
[0292] S1301: Based on AST Parse, the traversed Handler defines source point preprocessing.
[0293] In this step, the Handler definition source point is the Handler class in the above embodiment. That is, after obtaining the source code to be detected, a syntax analysis (Parse) is performed based on the AST of the source code to be detected to obtain the Handler definition source point in the source code to be detected. Fig.14 In step 1 of the above, the project source code (i.e. the source code to be detected) is obtained, and in step 2, the Handler definition source point preprocessing based on AST traversal is performed. The Handler definition source point preprocessing based on AST traversal includes: firstly identifying the Handler definition source point based on AST traversal, obtaining the Handler source point (Handler Source), and performing feature extraction. Feature extraction includes: anonymous class feature extraction, anonymous class binding variable and non-static inner class feature extraction.
[0294] S1302: Handler weak reference source filtering based on dependency analysis.
[0295] In this step, the Handler weak reference source is the Handler class that holds the weak reference. If the Handler weak reference source does not cause memory leaks, the Handler weak reference source is filtered out. Fig.14 In step 3, Handler weak reference source points are filtered based on dependency analysis to obtain Handler Source\kill weakRef, which is the Handler definition source point after filtering weak references. In addition, based on the features of each type of Handler definition source point extracted by feature extraction in step 2, the Handler definition source points of static classes, Handler definition source points inherited from parent classes holding weak references, and Handler definition source points whose constructors contain Looper parameters are filtered to obtain the final Handler definition source point (i.e., the target Handler class).
[0296] S1303: Context-sensitive Handler strong reference handle analysis and handle propagation analysis.
[0297] In this step, the Handler strong reference point handle refers to the handle that holds a strong reference (i.e., the Handler object). That is, after determining the final Handler definition source point, first determine the Handler object instantiated by the final Handler definition source point, and perform handle propagation analysis on the determined Handler object to obtain the corresponding Handler object. Combining the above two determined Handler objects, obtain the target Handler object, and obtain the call information of the target Handler object.
[0298] like Fig.14 In step 4, based on context-sensitive Handler strong reference handle identification and handle propagation analysis, the target Handler object is obtained and the call chain of the Handler instance (i.e., the target Handler object) is generated. Then, the call graph of the Handler instance is generated.
[0299] S1304: Handler reference count analysis based on function call graph analysis.
[0300] In this step, the function call graph is the call graph of the Handler instance, such as Fig.14Step 5 in the above code analyzes the Handler reference count based on the function call graph analysis to obtain the Handler object reference count flow graph. The circles in the reference count flow graph represent Handler instances (Handler Object) with a reference count of 0, and the dots represent Handler instances with a reference count that is not 0. The dots in the reference count flow graph are partially enlarged. In the partially enlarged graph, the reference count of the Handler instance is determined based on the method called by the Handler instance. That is, the reference count input (in) of the Handler instance is +1, or the reference count output IDx (outIDx) of the Handler instance is -1. When the reference count of the Handler instance is -1, it is necessary to calculate the reference count based on the ID of the message targeted by the Handler instance (such as Fig.14 The IDx in the table is used for the calculation.
[0301] S1305: Handler memory leak interception based on reference counting directed graph analysis.
[0302] In this step, based on the reference count directed graph analysis, that is, based on the reference count of the Handler instance, it is determined whether the Handler instance has the risk of memory leakage and a detection report is generated. Fig.14 In step 6, the Handler memory leak is intercepted based on directed graph analysis to obtain a detection report.
[0303] As can be seen from the above, the technical solution provided by this embodiment has enhanced the memory leak detection method in multiple dimensions, determined the Handler object with memory leak, and improved the accuracy of memory leak detection. For example, feature recognition is performed on the Handler class to determine the Handler class holding weak references, the Handler class whose constructor contains Looper parameters, etc., to reduce the false alarm rate. In addition, based on context-sensitive Handler object handle recognition and handle propagation analysis, that is, on the basis of identifying the Handler object instantiated by the Handler class (i.e., the first Handler object), the handle propagation analysis is performed on the first Handler object to identify the Handler object obtained by the first Handler object (i.e., the second Handler object), to avoid the situation where the Handler object is missed, and to reduce the missed alarm rate. And reference counting analysis is performed based on the calling relationship of the Handler object to locate the Handler object with memory leaks and reduce the false alarm rate.
[0304] In a specific implementation, the present application also provides an electronic device, which includes one or more processors and a memory; the memory is coupled to the one or more processors, the memory is used to store computer program code, the computer program code includes computer instructions, and the one or more processors call the computer instructions to enable the electronic device to perform some or all of the steps in the above method embodiments.
[0305] The present application also provides a computer-readable storage medium, including a computer program, which, when executed on an electronic device, enables the electronic device to perform some or all of the steps in the above method embodiment. The above storage medium may be a magnetic disk, an optical disk, a read-only memory (ROM) or a random access memory (RAM), etc.
[0306] In a specific implementation, an embodiment of the present application further provides a computer program product, which includes executable instructions. When the executable instructions are executed on an electronic device, the electronic device executes part or all of the steps in the above method embodiment.
[0307] like Fig.15 As shown, the present application also provides a chip system, which is applied to electronic devices. The chip system includes one or more processors 1501. The processor 1501 is used to call computer instructions so that the electronic device inputs the data to be processed into the chip system. The chip system processes the data based on the memory leakage detection method provided in the embodiment of the present application and outputs the processing result.
[0308] In a possible implementation, the chip system also includes input and output interfaces for inputting and outputting data.
[0309] The various embodiments of the mechanism disclosed in the present application can be implemented in hardware, software, firmware or a combination of these implementation methods. The embodiments of the present application can be implemented as a computer program or program code executed on a programmable system, which includes at least one processor, a storage system (including volatile and non-volatile memory and / or storage elements), at least one input device and at least one output device.
[0310] Program code may be applied to input instructions to perform the functions described herein and to generate output information. The output information may be applied to one or more output devices in a known manner. For purposes of this application, a processing system includes any system having a processor such as, for example, a digital signal processor (DSP), a microcontroller, an application specific integrated circuit (ASIC), or a microprocessor.
[0311] Program code can be implemented with high-level programming language or object-oriented programming language to communicate with the processing system. When necessary, program code can also be implemented with assembly language or machine language. In fact, the mechanism described in this application is not limited to the scope of any specific programming language. In either case, the language can be a compiled language or an interpreted language.
[0312] In some cases, the disclosed embodiments may be implemented in hardware, firmware, software, or any combination thereof. The disclosed embodiments may also be implemented as instructions carried or stored on one or more temporary or non-temporary machine-readable (e.g., computer-readable) storage media, which may be read and executed by one or more processors. For example, the instructions may be distributed over a network or through other computer-readable media. Therefore, a machine-readable medium may include any mechanism for storing or transmitting information in a machine (e.g., computer) readable form, including but not limited to floppy disks, optical disks, optical disks, compact disc read-only memories (Compact Disc Read Only Memory, CD-ROMs), magneto-optical disks, read-only memories, random access memories, erasable programmable read-only memories (Erasable Programmable Read Only Memory, EPROM), electrically erasable programmable read-only memories (Electrically Erasable Programmable Read Only Memory, EEPROM), magnetic or optical cards, flash memory, or a tangible machine-readable memory for transmitting information (e.g., carrier waves, infrared signals, digital signals, etc.) using the Internet in electrical, optical, acoustic, or other forms of propagation signals. Accordingly, machine-readable media include any type of machine-readable media suitable for storing or transmitting electronic instructions or information in a form readable by a machine (eg, a computer).
[0313] In the accompanying drawings, some structural or method features may be shown in a specific arrangement and / or order. However, it should be understood that such a specific arrangement and / or order may not be required. Instead, in some embodiments, these features may be arranged in a manner and / or order different from that shown in the accompanying drawings of the specification. In addition, the inclusion of structural or method features in a particular figure does not mean that such features are required in all embodiments, and in some embodiments, these features may not be included or may be combined with other features.
[0314] It should be noted that the units / modules mentioned in the various device embodiments of the present application are all logical units / modules. Physically, a logical unit / module can be a physical unit / module, or a part of a physical unit / module, or can be implemented as a combination of multiple physical units / modules. The physical implementation method of these logical units / modules themselves is not the most important. The combination of functions implemented by these logical units / modules is the key to solving the technical problems proposed by the present application. In addition, in order to highlight the innovative part of the present application, the above-mentioned device embodiments of the present application do not introduce units / modules that are not closely related to solving the technical problems proposed by the present application, which does not mean that there are no other units / modules in the above-mentioned device embodiments.
[0315] It should be noted that in the examples and description of this patent, relational terms such as first and second, etc. are only used to distinguish one entity or operation from another entity or operation, and do not necessarily require or imply any such actual relationship or order between these entities or operations. Moreover, the terms "include", "comprise" or any other variants thereof are intended to cover non-exclusive inclusion, so that a process, method, article or device including a series of elements includes not only those elements, but also other elements not explicitly listed, or also includes elements inherent to such process, method, article or device. In the absence of further restrictions, the elements defined by the sentence "including one" do not exclude the existence of other identical elements in the process, method, article or device including the elements.
[0316] Although the present application has been illustrated and described with reference to certain preferred embodiments thereof, it will be apparent to those skilled in the art that various changes in form and details may be made therein without departing from the spirit and scope of the present application.
Claims
1. A memory leak detection method, characterized in that: The method is applied to an electronic device, and the method comprises: Get the source code to be tested; Traversing the source code to be detected, and determining a target message processing class in the source code to be detected; For each target message processing class, determine a target message processing object corresponding to the target message processing class; wherein the target message processing object is used to process messages transmitted between two threads, the target message processing class is an operator Handler class; the target message processing object is a Handler object; Based on the calling relationship of each target message processing object, determining the reference count of each target message processing object; wherein the reference count of a target message processing object indicates the number of times the target message processing object is referenced; Generate a memory leak detection result based on the reference count of each target message processing object; wherein the detection result includes: a message processing object with a memory leak; The step of determining the reference count of each target message processing object based on the calling relationship of each target message processing object includes: Traversing the called methods in the source code to be detected, and determining that the caller is a method of the target message processing object; For each target message processing object, based on the control flow information and the parent node of the method called by the target message processing object, the calling information of the target message processing object is generated; wherein the calling information includes: the external class that calls the target message processing object, and the method called by the target message processing object; Calculate the reference count of the target message processing object based on the call information of the target message processing object; The calculating the reference count of the target message processing object based on the call information of the target message processing object includes: If the method called by the target message processing object includes the method of sending a delayed message, the reference count of the target message processing object is increased by 1; If the method called by the target message processing object includes the method of sending a blank delayed message, the reference count of the target message processing object is increased by 1; If the method called by the target message processing object includes a clear message method, the reference count of the target message processing object is reduced by 1; If the method called by the target message processing object includes a publishing delay method, the reference count of the target message processing object is increased by 1; If the method called by the target message processing object includes a clear callback method, the reference count of the target message processing object is reduced by 1; If the method called by the target message processing object includes a clear callback and a message method, the reference count of the target message processing object is 0; The traversing the source code to be detected to determine the target message processing class in the source code to be detected includes: Traversing the source code to be detected to obtain various types of message processing classes in the source code to be detected; For each message processing class, if the message processing class is a static class, determine the message processing class as the message processing class to be filtered; If the message processing class is not a static class and the message processing class satisfies the filtering condition, the message processing class is determined to be the message processing class to be filtered; wherein the filtering condition is satisfied including: the message processing class holds a weak reference, the message processing class inherits from a parent class holding a weak reference, and the constructor of the message processing class contains a specified parameter; From each message processing class, determine other message processing classes except the message processing class to be filtered, and obtain a target message processing class; The step of determining, for each target message processing class, a target message processing object corresponding to the target message processing class includes: For each target message processing class, determine a first message processing object obtained by instantiating the target message processing class, perform handle propagation analysis based on data flow dependencies in the source code to be detected, perform handle expansion identification on the first message processing object, and obtain a second message processing object; Acquire the first message processing object and the second message processing object to obtain the target message processing object corresponding to the target message processing class; The call information of the target message processing object is represented in the form of a call graph. The call information of the target message processing object is generated based on the control flow information and the parent node of the method called by the target message processing object, including: Record the Handler instance name and type; traverse the method call node; determine whether the method caller is a Handler instance. If not, execute the steps of traversing the method call node. If yes, obtain the control flow information, obtain the parent node of the current method, generate a call chain, save the control flow information and call chain, and generate a call graph.
2. The method according to claim 1, characterized in that The memory leak detection result is generated based on the reference count of each target message processing object, including: For each target message processing object, if the reference count of the target message processing object is 0, it is determined that there is no memory leak in the target message processing object; If the reference count of the target message processing object is not 0, it is determined that the target message processing object has a memory leak.
3. The method according to claim 1, characterized in that The second message processing object includes at least one of the following: Assigning the first message processing object to the newly created message processing object to obtain a second message processing object; A second message processing object is obtained by declaring a variable of a newly created message processing object; the newly created message processing object is initialized and assigned a value to the first message processing object; Inserting a new item into the container to obtain a second message processing object; the new item is the first message processing object; a second message processing object for accessing the first message processing object in a container; A second message processing object for accessing the first message processing object in an iterator; Used to return a second message processing object defined by a function; the function definition includes the first message processing object; A second message processing object used for transferring function parameters; the function parameters include the first message processing object.
4. An electronic device, characterized in that: include: one or more processors and memory; The memory is coupled to the one or more processors, and the memory is used to store computer program codes, wherein the computer program codes include computer instructions, and the one or more processors call the computer instructions to enable the electronic device to execute the method according to any one of claims 1 to 3.
5. A computer-readable storage medium, characterized in that: The invention comprises a computer program, which, when being executed on an electronic device, enables the electronic device to execute the method according to any one of claims 1 to 3.
6. A computer program product, characterized in that The computer program product comprises executable instructions, and when the executable instructions are executed on an electronic device, the electronic device is caused to execute the method according to any one of claims 1 to 3.
7. A chip system, characterized in that: The chip system is applied to an electronic device, and the chip system includes one or more processors, and the processor is used to call computer instructions so that the electronic device inputs data into the chip system, and executes the method described in any one of claims 1-3 to process the data and then output the processing results.
Citation Information
Patent Citations
Memory leak detection method and device
CN108664390A
Method and device for monitoring memory leak and electronic equipment
CN118708427A