Memory problem detection method and electronic equipment
By performing static analysis and runtime scanning in the Swift language to generate warning logs and weak reference graphs, the problem of lag and inaccuracy of manual tool analysis is solved, achieving efficient and accurate memory leak detection and repair.
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2025-12-12
- Publication Date
- 2026-04-07
AI Technical Summary
In existing technologies, relying on manual tool analysis and human review to locate and fix memory leaks in the Swift language suffers from lag and insufficient accuracy, making it difficult to meet development needs.
Static analysis is performed during the code compilation phase to generate early warning logs and inject monitoring code. At runtime, target object instances are scanned and a weak reference graph is constructed to generate a leak detection report, achieving automated and high-precision memory leak detection.
By identifying potential leaks early, we can reduce debugging costs for developers, improve memory security and application stability, reduce runtime overhead, and achieve accurate location and repair of memory leaks.
Smart Images

Figure CN121807376A_ABST
Abstract
Description
Technical Field
[0001] This application relates to the field of computer technology, and more specifically, to a method for detecting memory problems and an electronic device. Background Technology
[0002] In the field of mobile application development, the Swift language greatly simplifies memory management with its Automatic Reference Counting (ARC) mechanism, eliminating the need for developers to manually allocate and release memory. However, ARC cannot completely eliminate memory safety risks and still has problems such as circular strong references, indirect leaks under value type semantics, and dangling pointers. These problems directly affect application stability and performance.
[0003] In existing technologies, the solution to these problems mainly relies on manual tool analysis and manual review to locate and repair circular references, which suffers from lag and insufficient accuracy. Summary of the Invention
[0004] The purpose of this application is to provide a memory problem detection method and electronic device to address the shortcomings of the prior art, thereby solving the problems of lag and insufficient accuracy in the prior art that relies on manual tools for analysis and manual review to locate and repair circular references.
[0005] To achieve the above objectives, the technical solution adopted in this application is as follows: Firstly, this application provides a method for detecting memory problems, the method comprising: During the code compilation phase, static analysis is performed on the initial source code and configuration information to generate an early warning log. The early warning log is used to describe at least one potential leakage point, the code location corresponding to each potential leakage point, and the risk level of each potential leakage point. Based on the warning log, monitoring code is generated and injected into the initial source code to obtain the target source code; A target object instance is created based on the target source code. When the target object instance is running, the target object instance is scanned at a preset period to determine whether the target object instance has been leaked. If so, then traverse the memory layout of the target object instance and extract the leak information of the target object instance. The leak information includes: the leaked object of the target object instance and the strong reference list of the leaked object. A weak reference graph is constructed based on the leaked information. The weak reference graph is used to indicate the leak path from the referenced object to the formation of a loop. A leak detection report is generated based on the warning log and the weak reference graph.
[0006] Optionally, the step of performing static analysis on the initial source code and configuration information to generate an early warning log includes: Static analysis is performed on the initial source code and configuration information to obtain at least one potential leakage point, the code location corresponding to each potential leakage point, and the risk level of each potential leakage point. The potential leakage points, the corresponding code locations, and the risk levels of each potential leakage point are written into a log file to obtain the warning log.
[0007] Optionally, the static analysis of the initial source code and configuration information to obtain at least one potential leakage point, the code location corresponding to each potential leakage point, and the risk level of each potential leakage point includes: The initial source code is transformed into an abstract syntax tree, and the node identification of the abstract syntax tree is performed to obtain multiple key nodes, including: closure expression nodes, struct nodes, and class declaration nodes. Using the structure node and class declaration node as context information, semantic analysis is performed on each closure expression node to obtain a capture list, which includes: the capture variables and capture modes of the closure expression node; Based on the capture list, closure escape detection is performed on each of the closure expression nodes to obtain the risk level of each of the closure expression nodes; Based on the risk level of each closure expression node and a preset risk level threshold, at least one potential leakage point is identified in each closure expression node, and the code location corresponding to each potential leakage point and the risk level of each potential leakage point are recorded.
[0008] Optionally, the step of performing closure escape detection on each of the closure expression nodes according to the capture list to obtain the risk level of each of the closure expression nodes includes: If the capture mode of the closure expression node is strong capture mode, and the closure escape detection result of the closure expression node meets the preset closure escape condition, then the risk level of the closure expression node is determined to be the first risk level. If the capture mode of the closure expression node is strong capture mode, and the closure escape detection result of the closure expression node does not meet the preset closure escape condition, then the risk level of the closure expression node is determined to be the second risk level. The risk corresponding to the first risk level is higher than the risk corresponding to the second risk level.
[0009] Optionally, injecting the monitoring code into the initial source code to obtain the target source code includes: By using pre-defined injection code or compiler front-end hook functions, the monitoring code is injected into the code locations corresponding to each potential leak point in the initial source code, thereby obtaining the target source code.
[0010] Optionally, the target source code creates a target object instance. During runtime of the target object instance, the target object instance is scanned at a preset period to determine whether the target object instance has been leaked, including: Create a weak reference table for all currently running target object instances; The system iterates through each target object instance in the weak reference table according to a preset period. If the current target object instance is alive and has not entered the release phase, then the current target object instance is determined to have been leaked.
[0011] Optionally, traversing the memory layout of the target object instance and extracting the leaked information of the target object instance includes: Traverse the memory layout of the target object instance to obtain the metadata of the leaked object of the target object instance. The metadata of the leaked object includes: strong reference attributes and a list of closure attributes. Based on the metadata of the leaked object, at least one reference object of the leaked object and the reference object of each reference object are determined; A strong reference list of the leaked object is generated based on the leaked object, at least one referenced object of the leaked object, and referenced objects of each referenced object.
[0012] Optionally, constructing a weak reference graph based on the leaked information includes: Create the root node corresponding to the leaked object, and recursively traverse the memory reference relationship between the leaked object and its associated objects based on the strong reference list, generating the child nodes corresponding to the root node layer by layer to obtain the weak reference graph.
[0013] Optionally, generating a leakage detection report based on the early warning log and the weak reference graph includes: Match the leakage location of the leaked object in the warning log with the leakage path of the leaked object in the weak reference graph to identify at least one leaked object; Based on the aforementioned warning log, potential leakage targets are identified, and alert messages are generated for each potential leakage target. The leakage detection report is generated based on the leaked objects, each of the potential leaked objects, the prompt information of each of the potential leaked objects, and the preset report template.
[0014] Secondly, embodiments of this application also provide an electronic device, including: a processor, a storage medium, and a bus, wherein the storage medium stores machine-readable instructions executable by the processor, and when the electronic device is running, the processor communicates with the storage medium via the bus, and the processor executes the machine-readable instructions to perform the steps of a memory problem detection method as described in any one of the first aspects.
[0015] The beneficial effects of this application are: Early identification of potential leak points through compile-time static analysis enables early detection of memory safety issues, preventing them from being exposed only at runtime or in production environments. Non-intrusive monitoring code is injected without affecting the original code's functionality. Runtime scanning of target object instances at preset intervals, combined with memory layout traversal and strong reference list extraction, allows for more accurate leak identification. A weak reference graph is constructed based on leak information, clearly revealing the leak path. Finally, the alert logs and graph are integrated to generate a report, thus clarifying the leak location and remediation direction. The overall process achieves automated, high-precision detection, significantly reducing developer debugging costs, solving the problems of outdated technology and ambiguous location in existing methods, and has low runtime overhead, thereby effectively ensuring application memory safety and performance.
[0016] To make the above-mentioned objectives, features and advantages of this application more apparent and understandable, preferred embodiments are described below in detail with reference to the accompanying drawings. Attached Figure Description
[0017] To more clearly illustrate the technical solutions of the embodiments of this application, the accompanying drawings used in the embodiments will be briefly introduced below. It should be understood that the following drawings only show some embodiments of this application and should not be regarded as a limitation of the scope. For those skilled in the art, other related drawings can be obtained based on these drawings without creative effort.
[0018] Figure 1 A flowchart of a memory problem detection method provided in an embodiment of this application is shown; Figure 2 This application provides a flowchart for generating an early warning log. Figure 3 A flowchart illustrating a static analysis method provided in an embodiment of this application is shown; Figure 4 This document illustrates a flowchart of a leak monitoring process during runtime, as provided in an embodiment of this application. Figure 5 This document illustrates a flowchart of a method for generating a strong reference list, as provided in an embodiment of this application. Figure 6 This document illustrates a flowchart of a method for generating a leak detection report, as provided in an embodiment of this application. Figure 7 This paper presents an overall flowchart of a memory problem detection method provided in an embodiment of this application. Figure 8 This paper shows a schematic diagram of the structure of a memory problem detection device provided in an embodiment of this application; Figure 9 A schematic diagram of the structure of an electronic device provided in an embodiment of this application is shown. Detailed Implementation
[0019] To make the objectives, technical solutions, and advantages of the embodiments of this application clearer, the technical solutions of the embodiments of this application will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some embodiments of this application, and not all embodiments. The components of the embodiments of this application described and shown in the accompanying drawings can generally be arranged and designed in various different configurations. Therefore, the following detailed description of the embodiments of this application provided in the accompanying drawings is not intended to limit the scope of the claimed application, but merely represents selected embodiments of this application. All other embodiments obtained by those skilled in the art based on the embodiments of this application without inventive effort are within the scope of protection of this application.
[0020] It should be noted that the term "comprising" will be used in the embodiments of this application to indicate the presence of the features declared thereafter, but does not exclude the addition of other features.
[0021] In mobile application development, Swift's ARC mechanism simplifies memory management, but memory safety issues such as circular strong references, value type indirection leaks, and dangling pointers still exist. Existing solutions include manual analysis and review using the Instruments tool. However, Instruments requires manual execution and has vague positioning, while traditional static analysis only stays at the syntax level and lacks sufficient support for Swift's closure escape properties. Manual review is inefficient and fails to meet development needs.
[0022] Specifically, existing analysis methods suffer from several drawbacks: first, they are time-consuming, often revealing problems only at runtime or in production environments; second, they lack accuracy, failing to pinpoint precise lines of code and reference paths; and third, they lack coverage, with insufficient support for Swift-specific language features, resulting in a high false negative rate. These issues lead to high costs for fixing memory safety problems, impacting application stability and development efficiency.
[0023] Based on this, this application proposes a memory problem detection method. By performing static code analysis at compile time to obtain warning logs and identify potential leakage points, a leakage path is traced by constructing a graph during code runtime. Finally, a leakage detection report is generated by combining the warning logs and the constructed graph, thereby achieving accurate identification and precise location of leakage.
[0024] Figure 1 This is a flowchart illustrating a memory problem detection method provided in an embodiment of this application. The execution subject of this method can be an electronic device. Figure 1 The method includes: S101. During the code compilation phase, static analysis is performed on the initial source code and configuration information to generate warning logs.
[0025] Optionally, the alert log is used to describe at least one potential leak point, the code location corresponding to each potential leak point, and the risk level of each potential leak point. A potential leak point can be a code location identified in static analysis that may lead to a memory leak, such as a scenario where closure capture is not used with `[weakself]`. The code location corresponding to a potential leak point can be the file name and line number within that file.
[0026] Optionally, the initial source code refers to the original application code written by the developer in Swift that has not been processed by this memory safety verification framework and is used for memory management. Configuration information refers to the set of parameters used to customize static analysis, runtime monitoring, and report generation processes during Swift memory problem detection.
[0027] The risk level indicates the probability of a potential leak occurring at a potential leak point, and includes high risk and potential risk.
[0028] Optionally, based on the concept of memory safety left shift, memory problem detection can be brought forward to the compilation stage, avoiding problems from being exposed at runtime or in the production environment. Static analysis refers to analyzing the syntactic structure and semantic logic of the initial source code without executing the code, thereby identifying memory safety risks. For example, an Abstract Syntax Tree (AST) can be used to traverse and parse the code's syntactic structure, combined with data flow analysis to understand the semantic logic and identify memory risks specific to Swift.
[0029] For example, during the code compilation phase, the initial source code and configuration information can be converted into an abstract syntax tree, and static analysis can be performed based on the abstract syntax tree. This allows for the analysis of the semantic logic in the code without executing the code, resulting in potential leakage points, the code locations corresponding to each potential leakage point, and the risk level of each potential leakage point. Warning logs are then recorded.
[0030] S102. Generate monitoring code based on the warning log and inject the monitoring code into the initial source code to obtain the target source code.
[0031] The monitoring code can be lightweight code embedded in the target code, such as a customized base class or a deinit (deinitialization hook). The target source code can be the code obtained after the monitoring code is injected; the target source code and the initial source code have the same functionality.
[0032] Based on the risk locations identified by the early warning logs, non-intrusive monitoring code is injected to ensure that the original code functionality is not affected, while providing a foundation for runtime tracing.
[0033] In one possible implementation, monitoring code containing customized base class inheritance declarations and deinit hooks can be generated based on potential leak points in the alert logs. Then, using a compiler front-end hook or a customized code generation tool, the monitoring code is injected into the corresponding location in the initial source code, resulting in the target source code.
[0034] S103. Create a target object instance based on the target source code. When the target object instance is running, scan the target object instance according to a preset period to determine whether the target object instance has been leaked.
[0035] The preset period can be a fixed time interval for scanning leaks, controlled by a timer. The timer thread can be a different thread than the code execution thread.
[0036] Optionally, a global tracer can be used to monitor the lifecycle of the target object instance during code runtime, and determine whether the target object instance has been leaked by judging its liveness and release status.
[0037] In this context, a target object instance leak refers to a situation where, during the runtime of a Swift application, the memory resources of a target object instance should have been released by the automatic reference counting mechanism, but due to the existence of strong references that have not been broken, ARC is unable to reduce its reference count to zero. As a result, the object instance continues to occupy memory and cannot be reclaimed, and it cannot enter the release phase of its lifecycle normally, ultimately causing memory waste, application performance degradation, or even crashes.
[0038] In one possible implementation, all target object instances that need to be monitored can be registered in a weak reference table when the target source code is running. Then, a global tracker can traverse each target object instance in the weak reference table to identify any leaked target object instances.
[0039] S104. If so, traverse the memory layout of the target object instance and extract the leaked information of the target object instance.
[0040] The leaked information includes: the leaked objects in the target object instance and a list of strong references to the leaked objects.
[0041] Optionally, after determining that a target object instance has leaked, the memory layout of the target object instance can be traversed, the referenced instance objects can be extracted by memory offset, and the associated references of each referenced object can be recursively searched to generate a strong reference list containing the leaked object, the directly referenced object, and the indirectly referenced object.
[0042] The target object instance is all object instances created by the target source code that need to be monitored, including all objects involved in memory monitoring during application runtime. A leaked object refers to an object within the target object instance that is determined to have a memory leak through runtime scanning; it is a selected subset of abnormal objects from the full set of objects.
[0043] S105. Construct a weak reference graph based on the leaked information. The weak reference graph is used to indicate the leak path from the referenced object to the formation of a loop.
[0044] A weak reference graph can be a tree-like structure that represents the reference relationships of leaked objects, used to show the complete path from external objects to leaked objects that form a cycle.
[0045] Optionally, the leaked object can be used as the root node, and child nodes can be generated for each referenced object based on the strong reference list, with the reference type marked. Then, the reference relationship of the associated objects can be traversed recursively layer by layer until a reference loop is found, thus obtaining a weak reference graph.
[0046] S106. Generate a leak detection report based on the warning log and weak reference graph.
[0047] A leak detection report can be a final output document that integrates compile-time warnings and runtime graphs, including the location of the leak, the reference path, and remediation suggestions.
[0048] This application's embodiments identify potential leak points in advance through compile-time static analysis, enabling early detection of memory safety issues and preventing them from being exposed only at runtime or in the production environment. By injecting non-intrusive monitoring code, it does not affect the original code's functionality. At runtime, it scans target object instances at preset intervals, combining memory layout traversal and strong reference list extraction to more accurately determine leaks. Based on the leak information, it constructs a weak reference graph, clearly showing the leak path. Finally, it integrates warning logs and the graph to generate a report, thereby clarifying the leak location and remediation direction. The overall process achieves automated, high-precision detection, significantly reducing developer debugging costs, solving the problems of lagging technology and ambiguous location in existing technologies, and has low runtime overhead, thus effectively ensuring application memory security and performance.
[0049] The following is a further explanation of the static analysis performed on the initial source code and configuration information to generate warning logs, such as... Figure 2 As shown, the above step S101 includes: S201. Perform static analysis on the initial source code and configuration information to obtain at least one potential leakage point, the code location corresponding to each potential leakage point, and the risk level of each potential leakage point.
[0050] Optionally, the initial source code can be transformed into an abstract syntax tree, and semantic analysis can be performed on the abstract syntax tree and configuration information to obtain at least one potential leakage point and the risk level of the potential leakage point, and the code location corresponding to the potential leakage point can be recorded.
[0051] S202. Write each potential leak point, the corresponding code location, and the risk level of each potential leak point into a log file to obtain an early warning log.
[0052] Log files can be files that store static analysis results, used to record potential leak points, code locations, and risk levels in a structured manner.
[0053] For example, a log file format can be defined, and the results of static analysis can be written to the log file one by one according to the preset format to obtain the warning log.
[0054] In this embodiment, static analysis is used to deeply identify potential leakage points unique to Swift, accurately record code locations and risk levels, and then store them in a structured log format. This enables early detection and marking of memory security issues, providing accurate evidence for subsequent code injection, ensuring targeted embedding of monitoring logic, avoiding the lag issues of existing technologies, reducing subsequent repair costs, and improving detection and development efficiency.
[0055] The following is a further explanation of the static analysis performed on the initial source code and configuration information, which revealed at least one potential leak point, the corresponding code location of each potential leak point, and the risk level of each potential leak point. Figure 3 As shown, the above step S201 includes: S301. Transform the initial source code into an abstract syntax tree, and perform node identification on the abstract syntax tree to obtain multiple key nodes.
[0056] Key nodes include: closure expression nodes, struct nodes, and class declaration nodes.
[0057] The Abstract Syntax Tree (AST) refers to the tree-like structure formed during the compilation of source code. It represents the syntactic logic and semantic relationships of the code and is the core data carrier for static analysis. Key nodes can be node types with specific semantics in the AST, including closure expression nodes, struct nodes, and class declaration nodes, and are the objects of memory risk analysis.
[0058] Abstract Syntax Tree (AST) is a structured representation of source code semantics. By transforming AST, we can analyze syntax logic and reference relationships directly, without going beyond the code text. Key nodes are high-frequency associated nodes of memory leaks in the Swift language.
[0059] For example, the initial source code can be parsed into an abstract syntax tree using a compiler front-end tool, preserving information such as the syntax type, code location, and relationships of the nodes. Then, all nodes of the abstract syntax tree can be traversed, and closure expression nodes can be filtered out by matching node types. The struct nodes and class declaration nodes associated with the closure expression nodes can also be used as key nodes.
[0060] S302. Using the struct node and class declaration node as context information, perform semantic analysis on each closure expression node to obtain a capture list.
[0061] The capture list includes: the capture variables and capture modes of the closure expression node.
[0062] Context information refers to information such as scope, property definitions, and inheritance relationships contained in struct nodes and class declaration nodes, which is used to help understand the capture logic and reference scenarios of closure expression nodes.
[0063] Optionally, the struct node to which the closure expression node belongs and the class declaration node can be used as context information to determine the scope and accessible variables of the closure, and the syntax structure of the closure expression node can be parsed to extract captured variables, identify the capturing mode of the captured variables, and distinguish between strong reference mode, weak reference mode, and unowned reference mode to form a capture list.
[0064] S303. Perform closure escape detection on each closure expression node according to the capture list to obtain the risk level of each closure expression node.
[0065] Optionally, closure escape detection refers to determining whether a closure will exceed its defined lifespan. The escape nature of a closure directly determines the probability of a strongly captured variable causing a circular reference. Escaped closures have longer lifespans and a higher risk of forming a closed loop with external objects. Classifying the risk level accordingly can improve detection accuracy.
[0066] In one possible implementation, the use case of the closure expression node can be analyzed to determine whether it meets the escape condition, and the risk level of the closure expression node can be obtained by combining the capture patterns in the capture list.
[0067] S304. Based on the risk level of each closure expression node and the preset risk level threshold, identify at least one potential leakage point in each closure expression node, and record the code location corresponding to each potential leakage point and the risk level of each potential leakage point.
[0068] Among them, the risk level threshold is a preset risk judgment standard used to distinguish the risk level boundaries that need to be marked as "potential leakage points".
[0069] By filtering high-priority risk nodes using risk level thresholds, information redundancy caused by indiscriminate labeling can be avoided. Recording code locations enables precise problem localization and reduces repair costs.
[0070] Optionally, the risk level threshold in the configuration information can be read, and all closure expression nodes can be traversed. Nodes whose risk level meets the threshold requirements can be marked as potential leakage points. The code location corresponding to the potential leakage point can be extracted, and the code location, risk level and potential leakage point can be associated to form a structured analysis result.
[0071] In this embodiment, the core analysis is focused through AST transformation and key node identification. The capture list is accurately extracted by combining contextual semantic analysis. Then, the risk level is divided by escape detection. Finally, potential leakage points are screened according to the threshold and their locations are recorded. This achieves deep and accurate identification of memory risks unique to Swift, solving the problems of high false negative rate and shallow semantic understanding in traditional static analysis. High-risk points are identified in advance, providing accurate basis for subsequent processing.
[0072] The following is a further explanation of the above-mentioned closure escape detection performed on each closure expression node based on the capture list to obtain the risk level of each closure expression node. The above-mentioned step S303 includes: If the capture mode of the closure expression node is strong capture mode, and the closure escape detection result of the closure expression node meets the preset closure escape condition, then the risk level of the closure expression node is determined to be the first risk level.
[0073] If the capture mode of the closure expression node is strong capture mode, and the closure escape detection result of the closure expression node does not meet the preset closure escape condition, then the risk level of the closure expression node is determined to be the second risk level.
[0074] The risk level corresponding to the first risk level is higher than that corresponding to the second risk level. For example, the first risk level is a high risk level, corresponding to a scenario where the closure strongly captures variables and meets the escape condition, while the second risk level is a potential risk level, corresponding to a scenario where the closure strongly captures variables but does not meet the escape condition.
[0075] It should be understood that the strong capture pattern creates a strong reference association between the closure and the captured variable, while the lifecycle of the escaping closure is not limited by its defined scope. The combination of these two inevitably leads to a reference count that cannot reach zero, forming a stable circular reference, thus it is judged as the highest risk. Although the strong capture pattern also has a reference association, the lifecycle of the non-escaping closure is limited to its defined scope, and the probability of forming a closed loop with the external object is low. However, subsequent code modifications may change the closure's lifecycle, posing a potential risk of leakage, therefore it is judged as the second highest risk.
[0076] Alternatively, strong capture mode is the default variable capture method for Swift closures. The closure holds a strong reference to the captured variable, which increases the variable's reference count. If a reference loop is formed, the variable cannot be released by ARC, which is the core cause of memory leaks.
[0077] Closure escape detection determines whether a closure's lifecycle extends beyond its defined scope. The core checks include whether the closure is assigned to a stored property, passed to the `@escaping` parameter, or used in an asynchronous task. Optionally, closure escape conditions refer to predefined criteria in the configuration information for determining if a closure is an escaped closure, such as assigning the closure to a class's stored property or passing the closure as an `@escaping` parameter. The `@escaping` parameter is a keyword in Swift used to modify function type parameters, indicating that the parameter's lifecycle extends beyond the scope of its enclosing function; it is not immediately destroyed when the function finishes execution but continues to exist and may be invoked at some later time.
[0078] Optionally, the capture mode can be extracted from the capture list of the closure expression node to determine whether it is a strong capture, and the usage conditions of the closure can be analyzed to check whether the preset escape conditions are met. If both the strong capture mode and the escape conditions are met, the closure expression node is marked as the first risk level.
[0079] If the capture mode of the closure expression node is confirmed to be strong capture, and the closure escape detection confirms that the closure does not meet the preset escape condition, then the closure expression node is marked as the second risk level.
[0080] In this embodiment, by distinguishing the escape state of closures under strong capture mode, different risk levels are accurately classified and risk priorities are clarified, enabling developers to prioritize the first risk level problem with a high probability of leakage, while also paying attention to potential risks. This solves the problem of traditional analysis failing to differentiate risks and lacking focus, and improves the targeting and repair efficiency of memory security detection.
[0081] The following is a further explanation of how the monitoring code was injected into the initial source code to obtain the target source code, including: By injecting pre-defined injection code or compiler front-end hook functions, monitoring code is injected into the code locations corresponding to potential leak points in the initial source code, thereby obtaining the target source code.
[0082] The target source code and the initial source code have the same functionality when run.
[0083] Optionally, the injected code can be a predefined lightweight monitoring logic code snippet, including inherited custom base class declarations, deinit hook associations, etc., used to embed the initial source code to achieve runtime tracing. Compiler front-end hook functions are custom functions embedded in the compiler front-end flow, which can intercept syntax analysis results during code compilation and trigger monitoring code injection operations.
[0084] In one possible implementation, an injection code library can be pre-built, containing monitoring code templates for different potential leakage scenarios. The compiler front-end hook can intercept alert logs generated by static analysis, extract the code locations of potential leakage points, and then match the corresponding pre-defined injection code according to the leakage scenario. The hook function then embeds the monitoring code into the target location of the initial source code and generates the target source code.
[0085] It should be noted that the monitoring code only adds auxiliary logic such as lifecycle tracking and status marking, and does not interfere with the business logic execution flow of the original source code, ensuring the non-intrusiveness of the injection operation and avoiding impact on the original functionality of the application.
[0086] The following is a further explanation of how to create a target object instance from the aforementioned target source code, and how to scan the target object instance at a preset periodic interval during runtime to determine whether the target object instance has been leaked. Figure 4 As shown, the above step S103 includes: S401. Create a weak reference table for all currently running target object instances.
[0087] The weak reference table is a thread-safe data structure that stores weak references to the currently running target object instance. The key is the object's unique identifier, and the value is a weak reference wrapper. It is used to safely track the object's state without preventing ARC from releasing it.
[0088] When the target object instance is initialized, it can be automatically registered to the weak reference table. When the target object instance is released, it can be removed from the weak reference table to ensure that only the currently running object instance is retained in the weak reference table.
[0089] S402. Traverse each target object instance in the weak reference table according to the preset period. For the current target object instance that is traversed, if the current target object instance is alive and has not entered the release phase, then it is determined that the current target object instance has been leaked.
[0090] Optionally, a timer can be started through a global tracker and each target object instance in the weak reference table can be traversed according to a preset period. During the traversal, attempts can be made to upgrade weak references in the weak reference table to strong references. If the upgrade is successful, it means that the target object instance is alive. At this time, it can be detected whether the live object has entered the release phase. If the target object instance is alive and has not entered the release phase, it can be determined that the current target object instance has been leaked.
[0091] Specifically, the thread that traverses the weak reference table for the global tracker is a different thread from the thread that unregisters the target object instance from the weak reference table, in order to ensure thread safety.
[0092] This application embodiment uses a weak reference table to securely track runtime target object instances. By combining preset periodic traversal with dual determination of liveness and release status, it achieves automated and accurate leak detection. The weak reference table design does not interfere with ARC release, ensuring runtime performance, avoiding the inefficiency of manually triggering detection, timely detection of memory leaks, and improving detection reliability and development efficiency.
[0093] The following is a further explanation of the memory layout of the target object instance and the extraction of leaked information from the target object instance, such as... Figure 5 As shown, step S104 above includes: S501. Traverse the memory layout of the target object instance to obtain the metadata of the leaked object of the target object instance.
[0094] The metadata of a leaked object describes its structural characteristics and is used to trace the reference chain. The metadata of a leaked object includes: strong reference attributes and a list of closure attributes.
[0095] Strong reference properties are properties declared with strong references within an object, which increase the reference count of the referenced object. Closure property lists are closure-type properties declared within an object. Closures can capture external variables, forming strong references, and are a frequent cause of memory leaks in Swift. The memory layout of a target object instance refers to its storage structure in memory, including the memory allocation methods and offsets of properties, methods, metadata, and other information.
[0096] In one possible implementation, the Swift Runtime API can be used to access the memory layout of the leaked object, obtain information such as property types and memory offsets, filter out strong reference properties and closure properties, and organize the metadata of the leaked object in the target object instance.
[0097] S502. Based on the metadata of the leaked object, determine at least one reference object of the leaked object and the reference object of each reference object.
[0098] The metadata of a leaked object is directly associated with its strong reference targets. The reference chain can be traced layer by layer through the metadata until the reference loop is found, thereby identifying the leaked reference object.
[0099] S503. Generate a strong reference list of the leaked object based on the leaked object, at least one referenced object of the leaked object, and referenced objects of each referenced object.
[0100] In one possible implementation, the corresponding reference object instance can be accessed via memory offset based on the strong reference attribute in the metadata. The metadata extraction operation is repeated for each reference object instance to continue finding the next level object strongly referenced by the reference object. The depth of the recursive search is pre-limited, and a strong reference list is generated based on the found leaked objects and reference objects.
[0101] When generating a strong reference list, the leaked object can be used as the starting point. The class name, object identifier, and reference type of each object are recorded in the hierarchical order of the leaked object, the directly referenced object, and the indirectly referenced object. The closing points in the reference chain are marked, such as the referenced object referencing the leaked object in reverse. Finally, the above information is stored in a structured form to form a strong reference list.
[0102] The process of constructing a weak reference graph based on the leaked information includes: Create the root node corresponding to the leaked object, and recursively traverse the memory reference relationships of the leaked object and its associated objects based on the strong reference list, generating the child nodes corresponding to the root node layer by layer to obtain the weak reference graph.
[0103] Optionally, information such as the class name, object identifier, and code location of the leaked object can be extracted to create a root node, and the node type can be marked as a leaked object. Then, strong reference objects are read, and starting from the leaked object, the memory reference relationships of all related objects in the strong reference list are traced layer by layer until all related reference chains are traversed or the traversal method with a preset depth limit is reached. Corresponding child nodes are generated for each related object, and information such as the class name, reference type, and code location of the child nodes are marked. The association relationship between the child nodes and the root node and between the child nodes is established. After the traversal is completed, the root node, child nodes, and association relationships are integrated to obtain a weak reference graph.
[0104] This application's embodiments anchor the leaked object by creating a root node, recursively traversing associated objects based on a strong reference list and generating child nodes to construct a complete weak reference graph. This visually presents the leakage path and closed loop, solving the problem that traditional technologies cannot clearly define the reference chain. Furthermore, it provides developers with clear evidence for leak tracing, significantly reducing the difficulty of leak location and repair, and improving debugging efficiency.
[0105] The following is a further explanation of the process of generating a leak detection report based on the warning logs and weak reference graphs, such as... Figure 6 As shown, step S106 above includes: S601. Match the leakage location of the leaked object in the warning log with the leakage path of the leaked object in the weak reference graph to identify at least one leaked object.
[0106] Warning logs can provide risk locations identified at compile time, while weak reference graphs can provide the actual leakage paths at runtime. Matching the two allows for cross-verification, eliminating false alarms, and thus accurately locating the objects that have actually leaked.
[0107] In one possible implementation, the code location and associated object information of each potential leak point in the warning log can be extracted, and the class name, reference path and associated code location of the leaked object in the weak reference graph can be extracted. The object class name and code location are then matched. If the potential leak point in the warning log and the actual leak path in the graph point to the same object and location, then it is determined to be a leaked object.
[0108] S602. Identify potential leak targets based on the early warning log and generate alert messages for each potential leak target.
[0109] Optionally, potential leakage points in the warning log that do not match the weak reference graph leakage path can be filtered, marked as potential leakage objects, and prompt information can be generated based on the risk level and judgment criteria in the warning log. The prompt information includes risk level, code location, description of leakage risks and remediation suggestions.
[0110] S603. Generate a leak detection report based on the leaked objects, each potential leaked object, the prompt information of each potential leaked object, and the preset report template.
[0111] The preset report template can be a predefined structured report format, which includes details of the leaked objects, potential risk warnings, and remediation solutions.
[0112] This application embodiment accurately identifies leaked objects by matching early warning logs and weak reference graphs, extracts potential leaked objects and generates prompt information, and integrates them according to a preset template to generate a structured report, achieving dual verification and comprehensive presentation of leakage issues. The information is complete and logically clear, and it can also focus on potential risks, greatly improving debugging and repair efficiency.
[0113] like Figure 7 The diagram shown is an overall flowchart of a memory problem detection method. The following section will combine... Figure 7 The overall process of the method is described. The compile-time analyzer, code injector, runtime tracer, and report generator are processing modules within the electronic device.
[0114] The user provides the initial source code and configuration information to the compile-time analyzer. The analyzer first transforms the initial source code into an abstract syntax tree and identifies key nodes. Through semantic analysis and closure escape detection, it identifies potential leakage points and their risk levels, generating an alert log containing the leakage locations. Based on this alert log, the code injector injects monitoring code into the corresponding location in the initial source code, thus obtaining the target source code.
[0115] After the user compiles and runs the target source code, the target object instance is automatically registered to the weak reference table of the runtime tracker during initialization. The runtime tracker traverses the weak reference table at a preset period. If the target object instance is alive and has not entered the release phase, it is determined to be a leaked object. Then, it traverses its memory layout to extract metadata, traces the referenced objects to generate a strong reference list, and constructs a weak reference graph based on the leaked object as the root node and the strong reference list.
[0116] The report generator matches the leak location in the warning log with the leak path in the weak reference graph to identify the leaked objects; at the same time, it extracts potential leaked objects from the warning log and generates prompt information. Finally, it integrates the leaked objects, potential leaked objects, and prompt information according to a preset template, outputs the final memory detection report, and provides feedback to the user.
[0117] Based on the same inventive concept, this application also provides a memory problem detection device corresponding to the memory problem detection method. Since the principle of the device in this application is similar to the memory problem detection method described above in this application, the implementation of the device can refer to the implementation of the method, and the repeated parts will not be described again.
[0118] Figure 8 A schematic diagram of a memory problem detection device provided in an embodiment of this application is shown. The device includes: a static analysis module 801, a code injection module 802, an instance scanning module 803, an information extraction module 804, a graph construction module 805, and a report generation module 806.
[0119] The static analysis module 801 is used to perform static analysis on the initial source code and configuration information during the code compilation stage, and generate warning logs. The warning logs are used to describe at least one potential leakage point, the code location corresponding to each potential leakage point, and the risk level of each potential leakage point. The code injection module 802 is used to generate monitoring code based on the warning log and inject the monitoring code into the initial source code to obtain the target source code; The instance scanning module 803 is used to create a target object instance based on the target source code, and scan the target object instance at a preset period during the runtime of the target object instance to determine whether the target object instance has been leaked. The information extraction module 804 is used to traverse the memory layout of the target object instance and extract the leaked information of the target object instance. The leaked information includes: the leaked object of the target object instance and the list of strong references to the leaked object. The graph construction module 805 is used to construct a weak reference graph based on the leaked information. The weak reference graph is used to indicate the leaked path from the referenced object to the formation of a loop. The report generation module 806 is used to generate a leak detection report based on the warning log and weak reference graph.
[0120] Optionally, the static analysis module 801 is specifically used for: Static analysis was performed on the initial source code and configuration information to identify at least one potential leak point, the code location corresponding to each potential leak point, and the risk level of each potential leak point. Each potential leak point, its corresponding code location, and its risk level are written to a log file to generate an early warning log.
[0121] Optionally, the static analysis module 801 is specifically used for: The initial source code is transformed into an abstract syntax tree, and node identification is performed on the abstract syntax tree to obtain multiple key nodes, including: closure expression nodes, struct nodes, and class declaration nodes. Using struct nodes and class declaration nodes as context information, semantic analysis is performed on each closure expression node to obtain a capture list, which includes: the capture variables and capture modes of the closure expression node; Based on the capture list, closure escape detection is performed on each closure expression node to obtain the risk level of each closure expression node; Based on the risk level of each closure expression node and the preset risk level threshold, at least one potential leakage point is identified in each closure expression node, and the code location corresponding to each potential leakage point and the risk level of each potential leakage point are recorded.
[0122] Optionally, the static analysis module 801 is specifically used for: If the capture mode of the closure expression node is strong capture mode, and the closure escape detection result of the closure expression node meets the preset closure escape condition, then the risk level of the closure expression node is determined to be the first risk level. If the capture mode of the closure expression node is strong capture mode, and the closure escape detection result of the closure expression node does not meet the preset closure escape condition, then the risk level of the closure expression node is determined to be the second risk level. The risk level corresponding to the first risk level is higher than that corresponding to the second risk level.
[0123] Optionally, the code injection module 802 is specifically used for: By injecting pre-defined injection code or compiler front-end hook functions, monitoring code is injected into the code locations corresponding to potential leak points in the initial source code, thereby obtaining the target source code.
[0124] Optionally, the instance scanning module 803 is specifically used for: Create a weak reference table for all currently running target object instances; The system iterates through each target object instance in the weak reference table according to a preset period. If the current target object instance is alive and has not entered the release phase, then the current target object instance is determined to have been leaked.
[0125] Optionally, the information extraction module 804 is specifically used for: Traverse the memory layout of the target object instance to obtain the metadata of the leaked object of the target object instance. The metadata of the leaked object includes: strong reference properties and a list of closure properties. Based on the metadata of the leaked object, identify at least one referenced object of the leaked object and the referenced objects of each referenced object; Generate a list of strong references to the leaked object based on the leaked object, at least one referenced object of the leaked object, and referenced objects of each referenced object.
[0126] Optionally, the map construction module 805 is specifically used for: Create the root node corresponding to the leaked object, and recursively traverse the memory reference relationships of the leaked object and its associated objects based on the strong reference list, generating the child nodes corresponding to the root node layer by layer to obtain the weak reference graph.
[0127] Optionally, the report generation module 806 is specifically used for: Match the leakage location of the leaked object in the warning log with the leakage path of the leaked object in the weak reference graph to identify at least one leaked object; Based on the warning logs, identify potential targets for leakage and generate alert messages for each potential target. Based on the already leaked objects, each potential leaked object, the prompts for each potential leaked object, and the preset report template, a leak detection report is generated.
[0128] This application's embodiments identify potential leak points in advance through compile-time static analysis, enabling early detection of memory safety issues and preventing them from being exposed only at runtime or in the production environment. By injecting non-intrusive monitoring code, it does not affect the original code's functionality. At runtime, it scans target object instances at preset intervals, combining memory layout traversal and strong reference list extraction to more accurately determine leaks. Based on the leak information, it constructs a weak reference graph, clearly showing the leak path. Finally, it integrates warning logs and the graph to generate a report, thereby clarifying the leak location and remediation direction. The overall process achieves automated, high-precision detection, significantly reducing developer debugging costs, solving the problems of lagging technology and ambiguous location in existing technologies, and has low runtime overhead, thus effectively ensuring application memory security and performance.
[0129] Figure 9 This illustration shows a schematic diagram of an electronic device provided in an embodiment of this application, including: a processor 901, a storage medium 902, and a bus 903. The storage medium 902 stores machine-readable instructions executable by the processor 901. When the electronic device runs a memory problem detection method as described in the embodiment, the processor 901 communicates with the storage medium 902 via the bus 903. The processor 901 executes the machine-readable instructions, and the preamble of the method item of the processor 901 performs the steps in the above-described memory problem detection method.
[0130] This application also provides a computer-readable storage medium storing a computer program that is executed by a processor, wherein the processor performs the steps in the memory problem detection method described above.
[0131] In this embodiment, the computer program, when run by the processor, can also execute other machine-readable instructions to perform other methods as described in the embodiments. For details on the specific execution steps and principles, please refer to the description of the embodiments, which will not be repeated here.
[0132] In the embodiments provided in this application, it should be understood that the disclosed apparatus and methods can be implemented in other ways. The apparatus embodiments described above are merely illustrative. For example, the division of units is only a logical functional division, and in actual implementation, there may be other division methods. Furthermore, multiple units or components may be combined or integrated into another system, or some features may be ignored or not executed. Additionally, the displayed or discussed mutual couplings, direct couplings, or communication connections may be through some communication interfaces; indirect couplings or communication connections between devices or units may be electrical, mechanical, or other forms.
[0133] The units described as separate components may or may not be physically separate. The components shown as units may or may not be physical units; that is, they may be located in one place or distributed across multiple network units. Some or all of the units can be selected to achieve the purpose of this embodiment according to actual needs.
[0134] In addition, the functional units in the embodiments provided in this application can be integrated into one processing unit, or each unit can exist physically separately, or two or more units can be integrated into one unit.
[0135] If the aforementioned functions are implemented as software functional units and sold or used as independent products, they can be stored in a computer-readable storage medium. Based on this understanding, the technical solution of this application, in essence, or the part that contributes to the prior art, or a portion of the technical solution, can be embodied in the form of a software product. This computer software product is stored in a storage medium and includes several instructions to cause a computer device (which may be a personal computer, server, or network device, etc.) to execute all or part of the steps of the methods described in the various embodiments of this application. The aforementioned storage medium includes various media capable of storing program code, such as USB flash drives, portable hard drives, read-only memory (ROM), random access memory (RAM), magnetic disks, or optical disks.
[0136] It should be noted that similar labels and letters in the following figures indicate similar items. Therefore, once an item is defined in one figure, it does not need to be further defined and explained in subsequent figures. In addition, the terms "first", "second", "third", etc. are used only to distinguish descriptions and should not be construed as indicating or implying relative importance.
[0137] Finally, it should be noted that the above-described embodiments are merely specific implementations of this application, used to illustrate the technical solutions of this application, and not to limit them. The protection scope of this application is not limited thereto. Although this application has been described in detail with reference to the foregoing embodiments, those skilled in the art should understand that any person skilled in the art can still modify or easily conceive of changes to the technical solutions described in the foregoing embodiments, or make equivalent substitutions for some of the technical features, within the scope of the technology disclosed in this application; and these modifications, changes, or substitutions do not cause the essence of the corresponding technical solutions to deviate from the spirit and scope of the technical solutions of the embodiments of this application. All should be covered within the protection scope of this application. Therefore, the protection scope of this application should be determined by the protection scope of the claims.
Claims
1. A method for detecting memory problems, characterized in that, include: During the code compilation phase, static analysis is performed on the initial source code and configuration information to generate an early warning log. The early warning log is used to describe at least one potential leakage point, the code location corresponding to each potential leakage point, and the risk level of each potential leakage point. Based on the warning log, monitoring code is generated and injected into the initial source code to obtain the target source code; A target object instance is created based on the target source code. When the target object instance is running, the target object instance is scanned at a preset period to determine whether the target object instance has been leaked. If so, then traverse the memory layout of the target object instance and extract the leak information of the target object instance. The leak information includes: the leaked object of the target object instance and the strong reference list of the leaked object. A weak reference graph is constructed based on the leaked information. The weak reference graph is used to indicate the leak path from the referenced object to the formation of a loop. A leak detection report is generated based on the warning log and the weak reference graph.
2. The method according to claim 1, characterized in that, The static analysis of the initial source code and configuration information to generate warning logs includes: Static analysis is performed on the initial source code and configuration information to obtain at least one potential leakage point, the code location corresponding to each potential leakage point, and the risk level of each potential leakage point. The potential leakage points, the corresponding code locations, and the risk levels of each potential leakage point are written into a log file to obtain the warning log.
3. The method according to claim 2, characterized in that, The static analysis of the initial source code and configuration information to obtain at least one potential leakage point, the code location corresponding to each potential leakage point, and the risk level of each potential leakage point includes: The initial source code is transformed into an abstract syntax tree, and the node identification of the abstract syntax tree is performed to obtain multiple key nodes, including: closure expression nodes, struct nodes, and class declaration nodes. Using the structure node and class declaration node as context information, semantic analysis is performed on each closure expression node to obtain a capture list, which includes: the capture variables and capture modes of the closure expression node; Based on the capture list, closure escape detection is performed on each of the closure expression nodes to obtain the risk level of each of the closure expression nodes; Based on the risk level of each closure expression node and a preset risk level threshold, at least one potential leakage point is identified in each closure expression node, and the code location corresponding to each potential leakage point and the risk level of each potential leakage point are recorded.
4. The method according to claim 3, characterized in that, The step of performing closure escape detection on each of the closure expression nodes according to the capture list to obtain the risk level of each of the closure expression nodes includes: If the capture mode of the closure expression node is strong capture mode, and the closure escape detection result of the closure expression node meets the preset closure escape condition, then the risk level of the closure expression node is determined to be the first risk level. If the capture mode of the closure expression node is strong capture mode, and the closure escape detection result of the closure expression node does not meet the preset closure escape condition, then the risk level of the closure expression node is determined to be the second risk level. The risk corresponding to the first risk level is higher than the risk corresponding to the second risk level.
5. The method according to claim 1, characterized in that, The step of injecting the monitoring code into the initial source code to obtain the target source code includes: By using pre-defined injection code or compiler front-end hook functions, the monitoring code is injected into the code locations corresponding to each potential leak point in the initial source code, thereby obtaining the target source code.
6. The method according to claim 1, characterized in that, The target source code creates a target object instance. When the target object instance runs, it is scanned at a preset period to determine whether the target object instance has been leaked, including: Create a weak reference table for all currently running target object instances; The system iterates through each target object instance in the weak reference table according to a preset period. If the current target object instance is alive and has not entered the release phase, then the current target object instance is determined to have been leaked.
7. The method according to claim 1, characterized in that, The step of traversing the memory layout of the target object instance and extracting the leaked information of the target object instance includes: Traverse the memory layout of the target object instance to obtain the metadata of the leaked object of the target object instance. The metadata of the leaked object includes: strong reference attributes and a list of closure attributes. Based on the metadata of the leaked object, at least one reference object of the leaked object and the reference object of each reference object are determined; A strong reference list of the leaked object is generated based on the leaked object, at least one referenced object of the leaked object, and referenced objects of each referenced object.
8. The method according to claim 1, characterized in that, The step of constructing a weak reference graph based on the leaked information includes: Create the root node corresponding to the leaked object, and recursively traverse the memory reference relationship between the leaked object and its associated objects based on the strong reference list, generating the child nodes corresponding to the root node layer by layer to obtain the weak reference graph.
9. The method according to claim 1, characterized in that, The step of generating a leak detection report based on the warning log and the weak reference graph includes: Match the leakage location of the leaked object in the warning log with the leakage path of the leaked object in the weak reference graph to identify at least one leaked object; Based on the warning log, at least one potential leak target is identified, and a prompt message is generated for each potential leak target; The leakage detection report is generated based on the leaked objects, each of the potential leaked objects, the prompt information of each of the potential leaked objects, and the preset report template.
10. An electronic device, characterized in that, include: The device includes a processor, a storage medium, and a bus, wherein the storage medium stores machine-readable instructions executable by the processor, and when the electronic device is running, the processor communicates with the storage medium via the bus, and the processor executes the machine-readable instructions to perform the steps of a memory problem detection method as described in any one of claims 1 to 9.