Embedded code instrumentation dynamic monitoring method

Through the embedded code insert dynamic monitoring method, central analysis and topological evolution technology are used to identify key paths and optimize resource allocation, the problems of uneven monitoring resources and high false alarm rates in the existing technology are solved, and efficient anomaly detection and system stability are achieved.

CN120596352APending Publication Date: 2025-09-05NANJING XINLIAN ELECTRONICS CO LTD +1
View PDF 0 Cites 2 Cited by

Patent Information

Application Number
CN202510750875.1
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2025-06-06
Publication Date
2025-09-05

Smart Images

  • Figure CN120596352A_ABST
    Figure CN120596352A_ABST
Patent Text Reader

Abstract

The invention discloses an embedded code instrumentation dynamic monitoring method, which comprises the following steps of: analyzing a source code, and generating a structure description file and initial instrumentation configuration; performing centrality analysis based on the structure description file, constructing a topological relation, and outputting an execution topological graph and a node mapping table; performing compression and time sequence attenuation on the execution topological graph to generate a compression execution graph and a multi-level mapping relation; deploying a three-level layered buffer area according to the compression execution graph, and collecting execution data to form track original data; and analyzing the original data of the track through topological evolution, identifying an abnormal path, and obtaining a feature vector and a monitoring strategy updating instruction. According to the method, topology perception and anti-fact comparative analysis are applied, the anomaly detection accuracy is remarkably improved, the early warning time is remarkably shortened, and meanwhile resource consumption is reduced.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] The present invention relates to embedded software related technologies, in particular to an embedded code plug-in dynamic monitoring method. Background Art

[0002] Embedded systems play a core role in key sectors such as aerospace, medical devices, smart grids, and industrial control. The reliability and security of their code execution directly impact the stable operation of the entire system. As embedded devices become increasingly complex and their code size continues to expand, hidden defects and abnormal execution paths are becoming increasingly difficult to identify and locate. Therefore, developing efficient dynamic code execution monitoring technology that can capture abnormal execution behavior in real time during system operation is crucial for improving embedded system reliability, shortening fault location time, and reducing maintenance costs.

[0003] Currently, embedded system code monitoring primarily employs three methods: count-based statistical monitoring, trace-based execution recording, and sampling-based performance analysis. Count-based statistical monitoring collects execution frequency data by inserting counters at key code locations, but struggles to capture complex execution path relationships. Trajectory-based execution recording records the execution direction at each branch point. While this method can reproduce the complete execution sequence, it faces data explosion issues during long-term operation. Sampling-based performance analysis achieves low-overhead monitoring by periodically interrupting program execution and sampling the current program counter and call stack state. However, the granularity of monitoring is limited, making it difficult to capture transient anomalies. For resource-constrained embedded environments, the industry has also proposed various lightweight solutions, such as using ring buffers to manage historical data, setting up conditionally triggered recording mechanisms, and using compression encoding to reduce storage requirements.

[0004] However, existing technologies still face several key problems in embedded environments, including: a lack of systematic analysis of code execution topology, difficulty in identifying and prioritizing monitoring of critical execution paths, resulting in uneven distribution of monitoring resources, either focusing on too many insignificant code areas, or ignoring critical but infrequently executed functional modules. Summary of the Invention

[0005] The purpose of the invention is to provide an embedded code instrumentation dynamic monitoring method, in order to solve at least one technical problem existing in the prior art.

[0006] Technical solution: an embedded code instrumentation dynamic monitoring method, including: Parse the source code, generate the structure description file and the initial instrumentation configuration; Perform centrality analysis based on the structure description file and initial instrumentation configuration, build topology relationships, and output execution topology graphs and node mapping tables; Compress and time-decay the execution topology graph and node mapping table to generate a compressed execution graph and multi-level mapping relationship; Deploy a three-level hierarchical buffer based on the compressed execution graph and multi-level mapping relationship to collect execution data and form trajectory raw data; The original trajectory data is analyzed through topological evolution to identify abnormal paths and generate monitoring strategy update instructions accordingly.

[0007] According to one aspect of the present application, identifying an abnormal execution path includes: Based on the original trajectory data, we construct execution subgraphs of multiple time windows, calculate the topological feature parameters to form a feature matrix of the temporal topology, and extract the time-varying pattern of the topological structure from it to establish a topological evolution model. The topological features of the current trajectory data are compared with the evolution model. Through execution path causal chain analysis and counterfactual comparison, abnormal change points are identified and a set of topological anomaly indicators is generated. Based on this, the abnormal execution path is located, the severity is evaluated, and an abnormal path report is obtained.

[0008] According to one aspect of the present application, generating a topology anomaly indicator set includes: Extract the conditional expression status and trigger conditions of the execution path from the feature matrix of the temporal topology, establish a mapping relationship between input conditions and path selection, and form an execution path causal model; Combining the original trace data with the execution path causal model, the semantic boundary points of function execution are identified, the execution flow is divided into semantically coherent segments of variable length, and a non-uniform execution profile is generated. Compare the current non-uniform execution profile with the execution path causal model, build a counterfactual model of the expected execution path, calculate the difference between the actual execution path and the expected path, distinguish between normal condition changes and abnormal path selection, and generate a set of topological anomaly indicators.

[0009] According to one aspect of the present application, extracting the conditional expression state and trigger condition of the execution path includes: Extract the conditional expression status and input parameters of each execution path from the timing topology feature matrix, record the specific condition values ​​that trigger each path, and generate a path selection condition table; Analyze the path selection condition table, build a conditional decision tree model, identify the association pattern between condition combinations and path selection, establish a mapping relationship between input conditions and path selection, and form a condition-path mapping diagram; Integrate the condition-path mapping diagram with execution frequency data, calculate the probability distribution of path selection under different condition combinations, distinguish between inevitable and possible triggering paths, and generate an execution path causal model.

[0010] According to one aspect of the present application, the execution flow is divided into semantically coherent segments of variable length to generate a non-uniform execution profile, including: Read the original trace data and the execution path causal model, analyze the control flow transition points, data dependency change points, and function call boundaries in the code execution sequence, identify the start and end positions of execution units with semantic integrity, and form a semantic boundary marker set; Based on the semantic boundary marker set, the continuous execution flow is divided into variable-length semantic segments according to the principle of functional integrity, ensuring that each segment contains a complete functional execution unit, and generating a semantic execution segment set; For each fragment in the semantic execution fragment set, its execution environment context, trigger condition status and resource consumption characteristics are extracted, the path selection pattern and state transition characteristics within the fragment are calculated, and a non-uniform execution profile reflecting functional integrity is constructed.

[0011] According to one aspect of the present application, it further includes: After obtaining the abnormal path report, the topology evolution feature vector is updated, the instrumentation strategy and buffer resource allocation are adjusted accordingly, and the monitoring strategy update instruction is generated. The monitoring strategy update instructions are composed of an instrumentation density adjustment plan, a buffer resource reallocation plan, and preventive monitoring enhancement instructions.

[0012] According to one aspect of the present application, adjusting the instrumentation strategy and buffer resource allocation and generating a monitoring strategy update instruction include: Generate a monitoring demand assessment table based on the location and impact range of the abnormal path report and the topology evolution feature vector abnormal area in the execution topology, and calculate the optimal instrumentation density adjustment strategy based on this table to form an instrumentation density adjustment plan; Analyze the current hierarchical buffer status, reallocate the resource ratio of the three-level buffer according to the instrumentation density adjustment plan, and obtain the buffer resource reallocation plan; Based on the trend information in the topology evolution feature vector, potential problem areas are predicted, the monitoring density is enhanced in advance, and preventive monitoring enhancement instructions are generated.

[0013] According to one aspect of the present application, a three-level hierarchical buffer is deployed to collect execution data and form raw trace data, including: Convert the monitoring point information in the compressed execution graph into actual instrumentation instructions to generate an instrumentation instruction set; Initialize hierarchical buffers at the micro, meso, and macro time scales based on the instrumented instruction set and system resource status; Collect the trigger data of the instrumentation points during code execution in real time, record the node access sequence and state changes, store them in the micro buffer, and generate the real-time execution sequence; Regularly analyze the real-time execution sequence, and store the critical path information and state transition data into the meso-buffer and macro-buffer according to the node importance evaluation results to form the execution trajectory raw data.

[0014] According to one aspect of the present application, generating a compressed execution graph and a multi-level mapping relationship includes: Apply the community detection algorithm to the initial execution topology graph to form a node community partition table; Based on the node community partition table and node mapping table, hierarchical graph compression is performed to retain key nodes and generate a multi-level compression model; Apply the temporal weight decay function to make the edge weights in the multi-level compression model decay over time and establish a temporal weight mapping table; Integrate the multi-level compression model and timing weight mapping table to generate a compressed execution graph and multi-level node mapping relationship.

[0015] According to one aspect of the present application, performing centrality analysis and constructing topological relationships includes: Parse the code structure description file, extract the calling relationship and execution order dependency between nodes, and build an execution dependency matrix; Convert the execution dependency matrix into a directed graph structure, where nodes represent code blocks and edges represent execution flows, forming an initial execution topology graph. Based on the initial execution topology graph, degree centrality, betweenness centrality and execution breakpoint sensitivity are calculated to obtain a set of topological centrality indicators, including the integrated degree centrality table, betweenness centrality table, influence indicator table and breakpoint sensitivity table.

[0016] According to one aspect of the present application, obtaining a topological centrality index set includes: Calculate the degree centrality index of each node in the initial execution topology, including the in-degree and out-degree that reflect the frequency of the node being called and calling other nodes, and generate a degree centrality table; Identify the key nodes at the intersection of multiple execution paths in the initial execution topology graph and obtain the betweenness centrality table; Analyze the directional characteristics of code execution and the frequency of node execution, calculate the influence of each node in the overall execution flow, and generate an influence index table; By simulating the removal of a single node, the impact on the connectivity of the overall execution graph is evaluated, key execution breakpoints are identified, and a breakpoint sensitivity table is formed.

[0017] According to one aspect of the present application, generating a structure description file and an initial instrumentation configuration includes: Read the source code file and use the compiler front-end to parse and generate an abstract syntax tree; Traverse the abstract syntax tree, mark key execution nodes including function entry, branch points, and loop structures, and generate a code node index table; Analyze the static characteristics of each node in the code node index table, including complexity and functional attributes, assign an initial importance weight to each node, and form a node importance table; According to the node importance table, the instrumentation location and initial sampling frequency are determined, and the initial instrumentation configuration and code structure description file are generated.

[0018] To achieve beneficial results, the system uses centrality analysis and topological evolution analysis to identify key nodes and execution paths, assessing the importance of each code module. It then maintains high-precision monitoring of key nodes and appropriately consolidates non-critical areas, achieving intelligent allocation of monitoring resources. For example, it uses high-frequency sampling (per execution) for key nodes, while setting a minimum weight guarantee (0.3) for low-frequency but important functional modules to ensure they are not overlooked. This improves anomaly detection accuracy to 92.5%, while keeping memory usage below 256KB. BRIEF DESCRIPTION OF THE DRAWINGS

[0019] Figure 1 It is a flow chart of the present invention.

[0020] Figure 2 It is a flow chart of the present invention for identifying abnormal execution paths.

[0021] Figure 3 This is a flow chart of the present invention for generating a topology anomaly indicator set.

[0022] Figure 4 It is a flow chart of the conditional expression state and trigger conditions of the execution path extracted by the present invention. DETAILED DESCRIPTION

[0023] like Figure 1-Figure 4 As shown, in order to solve the above problems existing in the prior art, a dynamic monitoring method for embedded code instrumentation is provided. The overall data flow is as follows: S1. Obtain the source code file and apply abstract syntax tree parsing technology to perform code structure analysis, identify function entry points, branch points, and execution flow relationships, assign initial importance weights to each node, and finally generate a code structure description file and initial instrumentation configuration as the basis for subsequent topology analysis.

[0024] S2. Read the code structure description file and the initial instrumentation configuration, build a topological relationship model for code execution, apply the centrality analysis algorithm to calculate the importance of nodes in the execution flow, identify key execution paths and bridge nodes, and output the initial execution topology diagram and key node mapping table to support accurate monitoring of resource allocation.

[0025] S3. Process the initial execution topology graph and key node mapping table, apply the multi-scale topology compression algorithm and temporal weight decay mechanism, merge similar nodes in non-critical areas while retaining the accurate representation of key nodes, establish a time-sensitive edge weight management system, generate a compressed execution graph and multi-level node mapping relationship to solve the problem of out-of-control graph complexity in long-term monitoring.

[0026] S4. Based on the compressed execution graph and multi-level node mapping relationship, a hierarchical buffer structure with three time scales is deployed in the target system. Code execution data is collected in real time and selectively stored according to node importance. Buffer resource allocation is adaptively managed, and execution trajectory raw data is continuously generated as the data basis for anomaly detection.

[0027] S5. Analyze the original execution trajectory data, build a temporal topology feature model, apply the topology evolution analysis algorithm to compare the deviation between the current execution graph and the expected pattern, identify abnormal topology changes and track and locate the specific abnormal execution path, output the topology evolution feature vector and abnormal path report, and generate monitoring strategy update instructions to feed back to the data collection link to form a closed-loop monitoring system.

[0028] Research has uncovered several issues. Traditional fixed-time window analysis methods artificially fragment the continuous execution process, making it difficult to understand the complete functional semantics and anomaly root causes. This leads to high false positive rates, particularly in complex execution environments with strong state dependencies. Furthermore, existing monitoring methods focus more on "what was executed" rather than "why it was executed," lacking in-depth exploration of the causal relationship between execution path selection and triggering conditions. This makes it difficult to distinguish between normal condition triggering changes and actual execution anomalies in environments with frequently changing conditions, severely limiting the accuracy and timeliness of anomaly detection. To address this, the following detailed solutions are proposed.

[0029] S1. Obtain the source code file, use the abstract syntax tree parser to perform code analysis, identify the code structure and execution flow, and generate a code structure description file and initial instrumentation configuration.

[0030] S11. Read the source code file and use the GCC compiler front-end to parse and generate an abstract syntax tree.

[0031] S12. Traverse the abstract syntax tree, mark key execution nodes such as function entry, branch points, loop structures, and generate a code node index table.

[0032] S13. Analyze the static characteristics (such as complexity and functional attributes) of each node in the code node index table, assign an initial importance weight to each node, and form a node importance table.

[0033] S14. Determine the insertion position and initial sampling frequency according to the node importance table, and generate an initial insertion configuration and code structure description file.

[0034] S2. Read the code structure description file, build a topology map, analyze the topological relationship of the code execution path, and generate an initial execution topology map and a key node mapping table.

[0035] S21. Parse the code structure description file, extract the calling relationship and execution order dependency between nodes, and build an execution dependency matrix.

[0036] S22. Convert the execution dependency matrix into a directed graph structure, where nodes represent code blocks and edges represent execution flows, to form an initial execution topology graph.

[0037] S23. Apply centrality analysis algorithms (degree centrality, betweenness centrality) to process the initial execution topology graph, calculate the topological importance score of each node, and generate a set of topological centrality indicators.

[0038] S24. Combine the node importance table and the topological centrality index set to calculate the comprehensive importance score, identify the key paths and key nodes, and output the key node mapping table.

[0039] S3. Process the initial execution topology graph, apply the multi-scale compression algorithm and temporal weight decay mechanism, optimize the graph structure complexity, and generate a compressed execution graph and multi-level node mapping relationship.

[0040] S31. Apply a community detection algorithm to the initial execution topology graph to identify highly correlated node clusters and form a node community partition table.

[0041] S32. Based on the node community partition table and the key node mapping table, perform hierarchical graph compression to ensure that key nodes retain details and non-key areas are appropriately merged to generate a multi-level compression model.

[0042] S33. Design and apply a temporal weight decay function to make the edge weights in the multi-level compression model decay according to time, and establish a temporal weight mapping table.

[0043] S34. Integrate the multi-level compression model and the timing weight mapping table to generate the final compression execution graph and the complete multi-level node mapping relationship.

[0044] S4. Configure the monitoring environment based on the compressed execution graph and multi-level node mapping relationship, collect code execution data in real time, manage the data buffer, and generate execution trajectory raw data.

[0045] S41 , converting the monitoring point information in the compressed execution graph into actual instrumentation instructions to generate an instrumentation instruction set.

[0046] S42. When the target system starts, initialize the hierarchical buffer of three time scales according to the instrumentation instruction set: micro buffer (high frequency fine granularity, covering the recent 5-10 minutes), meso buffer (medium frequency sampling, covering 2-4 hours) and macro buffer (low frequency summary, covering the entire operation cycle).

[0047] S43. Collect the trigger data of the insertion points during the code execution process in real time, record the node access sequence and state changes, store them in the micro buffer, and generate a real-time execution sequence.

[0048] S44. Regularly analyze the real-time execution sequence, extract the critical path information and state transition data, and selectively store them in the meso-buffer and macro-buffer according to the node importance evaluation results to comprehensively form the execution trajectory raw data.

[0049] S5. Process the execution trajectory raw data, apply the topology evolution analysis algorithm, identify abnormal execution patterns and key change points, and output the topology evolution feature vector and abnormal path report.

[0050] S51. Based on the original execution trajectory data, construct execution subgraphs of different time windows, calculate topological feature parameters (such as node degree distribution, path characteristics, clustering coefficient), and generate a temporal topological feature matrix.

[0051] S52. Apply time series analysis to the temporal topological feature matrix to extract the time-varying pattern of topological structure and establish a topological evolution model.

[0052] S53. Design and apply a topology change significance detection algorithm to compare the deviation between the current topology features and the predicted values ​​of the topology evolution model, identify abnormal change points, and generate a set of topology anomaly indicators.

[0053] S54. Based on the topology anomaly indicator set, locate the specific abnormal execution path through reverse tracing, evaluate the severity of the anomaly, output the abnormal path report and warning information, and update the topology evolution feature vector for subsequent analysis.

[0054] S55. Based on the abnormal path report and topology evolution feature vector, dynamically adjust the instrumentation strategy and buffer resource allocation, enhance the monitoring of potential problem areas, and generate monitoring strategy update instructions to feed back to the data collection process.

[0055] By constructing a comprehensive representation of code execution patterns over time, this approach overcomes the limitations of traditional methods that focus solely on static execution states. This enables the system to distinguish between changes in execution frequency and changes in the execution path structure, enabling early identification of anomalies. In one example, a battery temperature sensor anomaly was detected 5.8 seconds in advance, whereas traditional methods could only detect the failure after it occurred.

[0056] According to one aspect of the present application, S53, designing and applying a topology change significance detection algorithm, specifically: S531 , reading the time series topology feature matrix and the topology evolution model, calculating the deviation measure between the topology feature vector of the current time window and the model prediction value, and generating a topology deviation vector.

[0057] S532. Apply an adaptive threshold mechanism to process the topology deviation vector, establish a multi-dimensional deviation threshold based on the historical operating status of the system, consider the importance weights of different topological features, and generate a weighted deviation index.

[0058] S533. Apply statistical anomaly detection algorithm to the weighted deviation index, combined with Mahalanobis distance and local outlier factor analysis, to identify topological changes that exceed the normal fluctuation range and form an anomaly candidate set.

[0059] S534. Read the anomaly candidate set, screen out persistent anomalies and critical anomaly patterns through time correlation analysis, reduce the false alarm rate of random fluctuations, and output a topological anomaly indicator set.

[0060] In another embodiment of the present application, step S53, designing and applying a topology change significance detection algorithm, may also be: S531 , read the timing topology feature matrix, record the conditional expression status and input parameters of each execution path, and generate a path selection condition table.

[0061] Analyze the path selection condition table, build a conditional decision tree model, establish a mapping relationship between input conditions and path selection, and form a condition-path mapping diagram.

[0062] Integrate the condition-path mapping graph with execution frequency data, calculate the path selection probability distribution of the condition combination, and output the execution path causal model.

[0063] S532: Read the execution trace raw data and the execution path causal model, detect the semantic boundary points of function execution (transaction start / end, function call completion, state transition point), and form a semantic boundary marker set.

[0064] Based on the semantic boundary marker set, the execution flow is divided into semantically coherent segments of variable length, namely non-uniform semantic segmentation, to generate a set of semantic execution segments.

[0065] For each set of semantic execution fragments, the path selection pattern, triggering state and resource consumption characteristics are calculated to output a non-uniform execution profile.

[0066] S533. Read the current non-uniform execution profile and the historical execution path causal model, build a counterfactual model of the expected execution path based on the recorded input conditions, and generate an expected execution model.

[0067] The actual execution path is compared with the expected execution model, and the structural difference, conditional response deviation and transition probability abnormality are calculated to form a counterfactual difference matrix.

[0068] Analyze the counterfactual difference matrix, distinguish path conversion caused by normal condition changes from abnormal path selection, locate the trigger condition anomaly point, and output the topology anomaly indicator set.

[0069] By mapping input conditions to selected paths, a deeper understanding of "why" is achieved rather than simply focusing on "what" was executed is achieved, addressing the high false alarm rate of traditional methods in complex environments. This technology extracts the conditional expression states and trigger conditions from the temporal topology feature matrix, constructs a conditional decision tree model, and calculates the probability distribution of path selection under different condition combinations. In a battery management implementation, the correlation between "Battery.Temperature>45°C" and the overheat protection path was found to be as high as 28.67, clearly indicating that temperature is the primary cause of protection triggering. This enables the system to accurately distinguish between sensor faults and actual overheating conditions, increasing the recognition rate of condition-triggered anomalies from 61% to 93%. In particular, traditional methods misidentify a temperature sensor offset of +10°C as normal overheat protection, while causal chain analysis correctly identifies the sensor anomaly, avoiding unnecessary power restrictions and ensuring system performance and battery safety.

[0070] By building an expected model of "what should happen if conditions are normal" and comparing it with the actual execution path, the system can accurately distinguish between abnormal paths and normal condition variations. This technology combines the path selection condition table with a non-uniform execution profile to construct a counterfactual model of the expected execution path. It then calculates the structural differences between the actual and expected paths, the condition response deviation, and the degree of abnormal transition probability. In the case of temperature sensor excursion, the system discovered that under the same input conditions (displayed temperature 48°C), the expected path 27→42→43→51→27 was actually executed, while the actual path 27→42→43→51→63 was executed. This resulted in a mismatch in the terminal error handling node and an anomaly significance score of 0.784. This comparison enables the system to distinguish between true overheating (conditions matching the expected path) and sensor anomalies (conditions inconsistent with the selected path), improving anomaly detection sensitivity by 124%. In particular, in the case of multiple combined triggering conditions, the coverage of complex condition anomaly detection increased from 35% to 87%.

[0071] According to one aspect of the present application, S54, abnormal execution path location and root cause analysis, specifically: S541. Read the topology anomaly indicator set and the execution path causal model, trace back the execution conditions of the anomaly path, establish the diffusion path of the anomaly from the trigger point to the detection point, identify the initial anomaly source, and generate the anomaly propagation chain model.

[0072] Analyze the anomaly propagation chain model, evaluate the impact of anomalies on downstream modules and system functions, calculate the risk of functional impairment, and output an anomaly impact assessment report.

[0073] Compare the anomaly propagation chain model with historical anomaly patterns, identify anomaly types and root cause categories, record newly discovered anomaly patterns, and form preliminary results of anomaly diagnosis.

[0074] S542: Read the preliminary abnormality diagnosis results and the condition-path mapping diagram, determine the minimum condition set that triggers the abnormality, identify the key triggering factors, and output the root cause candidate set.

[0075] For each candidate in the root cause candidate set, a counterfactual verification model is constructed to simulate the scenario of "no such root cause", calculate the confidence level, and generate the root cause verification result.

[0076] The root cause verification results and anomaly impact assessment reports are integrated and sorted by confidence and severity to generate an anomaly path report.

[0077] According to one aspect of the present application, S55, dynamically adjusting the instrumentation strategy and monitoring resource allocation, specifically: S551. Read the abnormal path report and the topology abnormality indicator set, analyze the system resource status and monitoring requirements, calculate the optimal resource allocation solution, and generate a monitoring resource allocation plan.

[0078] Based on the monitoring resource allocation plan, the capacity allocation ratio of the three-level buffer is adjusted, more storage space is allocated to the abnormal area, and the buffer reconfiguration instruction is output.

[0079] Integrate buffer reconfiguration instructions and system load status, optimize data collection strategies, and form a monitoring efficiency optimization plan.

[0080] S552. Analyze the exception path report and the execution path causal model, identify the code areas and conditional judgment points that require key monitoring, determine the minimum necessary instrumentation point set, and generate an instrumentation density adjustment plan.

[0081] Based on the instrumentation density adjustment plan, the sampling frequency is increased for abnormal areas and trigger condition points, and the frequency is reduced for stable areas, and the instrumentation frequency configuration table is output.

[0082] Combined with the instrumentation frequency configuration table and the monitoring efficiency optimization plan, the instrumentation instruction update is generated, a feedback evaluation mechanism is established, and the instrumentation strategy update instruction is formed.

[0083] S553. Read the execution path causal model and topology evolution feature vector, analyze the evolution direction of system behavior, identify potential problem areas, predict possible abnormal code modules, and generate a risk prediction map.

[0084] Based on the risk prediction map, design forward-looking monitoring strategies, enhance monitoring density in high-risk areas, arrange preventive data collection, and output preventive monitoring strategies.

[0085] Integrate the instrumentation strategy update instructions and preventive monitoring strategies to form monitoring strategy update instructions, which are fed back into the data collection process.

[0086] By establishing a closed-loop feedback loop between topology analysis and monitoring resources, the system achieves a technological leap from passive monitoring to proactive early warning. Based on anomaly path reports and topology evolution feature vectors, this technology increases sampling frequency in anomaly-related areas, reduces it in stable areas, and reallocates the proportion of tertiary buffer resources. Furthermore, based on trend predictions, the system proactively enhances monitoring of potential problem areas. In the case of a temperature sensor anomaly, the system increased the instrumentation density of sensor-related nodes from 0.2 to 0.8, increasing memory allocation from 5% to 15%. Meanwhile, the instrumentation density in the stable power control area was reduced to 0.2, resulting in a 215% increase in data capture density in critical areas without increasing overall resource consumption. This intelligent adjustment resulted in a monitoring efficiency gain of 0.31 (significantly higher than the 0.12 of traditional static allocation), an improvement in the anomaly detection metric (AMD) from 0.52 to 1.38, and a 68% increase in system resource utilization. In particular, when subtle changes in voltage monitoring functionality were predicted to potentially escalate into issues, the system proactively enhanced monitoring, successfully identifying and resolving potential vulnerabilities before they escalated.

[0087] According to one aspect of the present application, S53: the code executes a critical path mutation detection algorithm, which may also be: S53a: Extract the complete causal chain from the temporal topology feature matrix, including not only the relationships between nodes and edges, but also the execution order and triggering conditions. Using the conditional trigger analysis method, record the status of the conditional expression selected for each execution path. Establish a "path selection decision tree" to map the relationship between input conditions and execution path selection; generate an execution path causal model that includes the complete link from condition → path → result; S53b: Automatically identify execution boundaries (e.g., transaction start / end, function call completion) based on functional completeness; implement semantically coherent execution profiles rather than simple time slices; and create non-uniform execution profiles based on functional completeness. S53c: Introduce "counterfactual reasoning" into code execution analysis; for each detected path change, construct an "expected execution counterfactual model": the execution path the system should take under the same input conditions; calculate the structural differences and transition probability differences between the actual execution path and the counterfactual model; evaluate abnormalities based on the degree of difference and generate a counterfactual difference map.

[0088] According to one aspect of the present application, S32, performing hierarchical graph compression based on the node community partition table and the key node mapping table, specifically: S321. Read the node community division table and the key node mapping table, build a hierarchical compression decision matrix, set compression ratio targets for different communities, and generate a community compression plan.

[0089] S322. Based on the community compression scheme, an importance-aware node merging algorithm is applied to each community. Key nodes maintain their original granularity, and non-key nodes are grouped and merged according to their connection patterns and functional similarities to form a first-level compression graph.

[0090] S323. Process the first-level compressed graph and apply edge filtering technology to retain high-frequency or key function conversion edges, delete low-frequency repeated execution paths, establish a compression mapping relationship of the edges, and output an edge simplification model.

[0091] S324. Integrate the first-level compression graph and edge simplification model, establish a multi-level abstract view, design an inter-level navigation index, ensure bidirectional mapping of information between different abstract levels, and generate a multi-level compression model and a complete hierarchical mapping relationship table.

[0092] According to one aspect of the present application, S42, initializing a hierarchical buffer of three time scales, specifically: S421. Read the compressed execution graph and system resource status information, calculate the available monitoring resource quota, and allocate it to the micro, meso, and macro buffers in a ratio of 5:3:2 to generate an initial buffer configuration.

[0093] S422. Based on the initial buffer configuration, create a micro-buffer data structure, configure high-frequency sampling parameters (100ms interval), set a loop overwrite strategy, optimize the memory layout for fast writing, establish a time index, and complete the micro-layer monitoring initialization.

[0094] S423. Read the initial buffer configuration, create the meso-level buffer data structure, set the selective recording strategy and intermediate frequency sampling parameters (5-minute interval), configure the data retention rules based on importance, and complete the meso-level monitoring initialization.

[0095] S424. Read the initial buffer configuration, create the macro buffer data structure, set the low-frequency summary recording parameters (30-minute interval), configure the trigger recording mechanism based on state transition, realize efficient storage of long-term execution mode, and complete the macro layer monitoring initialization.

[0096] S425. Integrate the micro-layer monitoring initialization, meso-layer monitoring initialization, and macro-layer monitoring initialization information, establish data flow rules and interactive interfaces among the three-level buffers, and generate a unified hierarchical buffer manager.

[0097] This embodiment solves the contradiction between fine-grained monitoring and storage limitations in embedded systems. The structure allocates resources in a 5:3:2 ratio and adopts differentiated storage strategies for execution data of different importance, thus achieving long-term monitoring under limited resource conditions. Compared with the traditional single buffer, this technology extends the data retention time from 3 days to 7 days under the same 256KB memory usage, while ensuring a critical event capture rate of 99.8%. Especially in the battery abnormality scenario, the micro buffer captures temperature fluctuations every 100ms, the meso buffer retains the state transitions of a 5-minute period, and the macro buffer records the system state evolution at a 30-minute granularity, fully presenting the entire process from normal state to abnormality.

[0098] According to one aspect of the present application, S33, designing and applying a temporal weight decay function, specifically: S331. Analyze the edge weight distribution characteristics in the multi-level compression model, combine with code execution frequency statistics, identify the timing sensitivity of different types of edges, and establish an edge type classification table.

[0099] S332. Based on the edge type classification table, differentiated timing attenuation functions are designed for different types of edges: a slowly decaying exponential function is used for key function conversion edges, a linear attenuation function is used for regular execution edges, and a fast attenuation function is used for low-value loop edges, thereby generating a family of attenuation functions.

[0100] S333. Construct a dual time window mechanism, apply the decay function family to the short-term behavior window (24 hours) and the long-term pattern window (7 days), calculate the time-sensitive edge weight values, and output the time-series weight matrix.

[0101] S334. Design an importance protection mechanism to identify critical but low-frequency execution paths in the timing weight matrix, apply a minimum weight protection strategy to prevent important edges from being excessively attenuated due to low frequency, and generate the final timing weight mapping table.

[0102] According to one aspect of the present application, S23, applying a centrality analysis algorithm to process the initial execution topology graph, specifically: S231 , read the initial execution topology graph, calculate the degree centrality index of each node, including in-degree (frequency of being called) and out-degree (frequency of calling other nodes), and generate a degree centrality table.

[0103] S232. Apply the improved betweenness centrality algorithm to process the initial execution topology graph, identify key nodes located at the intersection of multiple execution paths, which play a bridging role in information flow, and output the betweenness centrality table.

[0104] S233. Design and apply a specialized PageRank algorithm, taking into account the directional nature of code execution and the frequency of node execution, calculate the influence of each node in the overall execution flow, and generate an influence index table.

[0105] S234. Develop an "execution breakpoint sensitivity" analysis method to simulate the impact of removing a single node on the connectivity of the entire execution graph, identify key execution breakpoints, and form a breakpoint sensitivity table.

[0106] S235, integrate the degree centrality table, betweenness centrality table, influence index table and breakpoint sensitivity table, and apply the multidimensional weighted fusion algorithm to generate a unified topological centrality index set.

[0107] According to one aspect of the present application, S55, dynamically adjusting the instrumentation strategy and buffer resource allocation, may also be: S551. Read the abnormal path report and topology evolution feature vector, analyze the location and impact range of the abnormal area in the execution topology, evaluate the monitoring enhancement needs, and generate a monitoring needs assessment table.

[0108] S552. Based on the monitoring needs assessment table, calculate the optimal insertion density adjustment strategy, increase the sampling frequency for abnormal related areas, and appropriately reduce the sampling frequency for stable areas to form an insertion density adjustment plan.

[0109] S553: ​​Analyze the current hierarchical buffer manager state, reallocate the resource ratio of the three-level buffer according to the instrumentation density adjustment plan, allocate more storage space to the abnormality-related area, and output the buffer resource reallocation plan.

[0110] S554. Design a forward-looking monitoring enhancement strategy to predict potential problem areas based on the trend information in the topological evolution feature vector, enhance the monitoring density of these areas in advance, and generate preventive monitoring enhancement instructions.

[0111] S555: Integrate the instrumentation density adjustment plan, buffer resource reallocation plan, and preventive monitoring enhancement instructions to form a complete monitoring strategy update instruction, which is fed back to the data collection process to achieve closed-loop adaptive monitoring.

[0112] According to one aspect of the present application, S22, converting the execution dependency matrix into a directed graph structure, specifically: S221. Read the execution dependency matrix, analyze the matrix structure characteristics, identify strong dependencies and weak dependencies, set the dependency strength threshold, and generate a dependency strength classification table.

[0113] S222. Based on the dependency strength classification table, construct an initial directed graph skeleton, where nodes represent code blocks, strong dependencies form directed edges, establish a basic graph structure, and output the graph structure skeleton.

[0114] S223. Analyze the conditional execution relationship in the execution dependency matrix, add conditional attributes and trigger probabilities to the edges in the graph structure skeleton, represent the path selection characteristics under different execution conditions, and form a conditional execution edge table.

[0115] S224. Integrate the graph structure skeleton and the conditional execution edge table, add edge weight information such as execution frequency and resource consumption, establish a complete directed graph representation, and generate the final initial execution topology graph.

[0116] According to one aspect of the present application, S51, constructing execution subgraphs of different time windows, specifically: S511 , read the original execution trajectory data, segment it according to multiple time window scales (5 minutes, 30 minutes, 4 hours, 24 hours), extract the execution path data within each time window, and form a time window data set.

[0117] S512: Apply a graph reconstruction algorithm to each time window data set to restore the execution topology within the time window, retain the timing information and execution frequency, and generate a series of timing execution subgraphs.

[0118] S513. Calculate the topological characteristic parameters of each sequential execution subgraph, including node degree distribution, clustering coefficient, path length distribution, centrality index, etc., to form a multidimensional feature vector, and output a topological feature vector set.

[0119] S514. Apply a time series arrangement algorithm to the topological feature vector set, organize the multi-dimensional feature data in chronological order, establish a feature evolution trajectory, and generate a complete time series topological feature matrix.

[0120] In another embodiment of the present application, updating the topology evolution feature vector includes: First, the system obtains a set of topological anomaly indicators from step S53, which includes the degree, location, and nature of the anomaly change. Through a reverse tracing algorithm, these anomaly indicators are mapped to specific code execution paths to establish an anomaly-path association graph. Compare the newly discovered anomaly patterns with the existing feature vectors: for known anomaly types, update their frequency of occurrence, most recent triggering time, and related conditions; for new anomalies, add new feature dimensions to record their first occurrence, triggering conditions, and impact range.

[0121] A time decay function is applied to the historical anomalies in the feature vector to reduce the weight of abnormal patterns that have not reappeared for a long time; and to increase the weight of repeated abnormal patterns to indicate their continued relevance.

[0122] Update the dynamic characteristics of each node and edge in the code execution topology; record the changing trends of key node behaviors over time; update the usage frequency and conditional triggering patterns of common execution paths; Adjust the parameters of the topology evolution prediction model based on new anomaly data; update the anomaly detection threshold to adapt it to the current operating state of the system; adjust the weights of each topological feature dimension to increase sensitivity to important anomaly patterns.

[0123] The updated topology evolution feature vector contains the following key dimensions: Path frequency distribution: records the relative usage frequency of each execution path and its rate of change; conditional trigger pattern: records the correlation strength between specific input conditions and path selection; node centrality dynamics: tracks the changing trend of key node centrality indicators over time; abnormal pattern fingerprint: stores the identified abnormal pattern characteristics and their recent occurrence; timing correlation index: captures the time series correlation between execution paths; resource consumption characteristics: records the resource usage patterns of different execution paths; change rate metadata: saves the change rate of each dimension of the topology structure.

[0124] Example 1: Dynamic Monitoring of the Power Management Subsystem of an Embedded Device This example demonstrates the implementation of a topology-aware multi-scale critical path monitoring method using an embedded device power management subsystem as the target. The power management subsystem includes functional modules such as voltage regulation, battery charge and discharge management, and low-power mode switching.

[0125] Parse the source code and generate the structure description file and initial instrumentation configuration, specifically including: Step S11: Read the source code file and use the compiler front-end to parse and generate an abstract syntax tree The power management subsystem C source code file, power_mgmt.c, contains 1500 lines of code, 12 functions, 35 branch structures, and 8 loop structures. A modified version of the GCC compiler front-end was used to parse the source code and generate an abstract syntax tree (AST). The AST contains 247 nodes, covering all function definitions, conditional branches, loop structures, and variable declarations.

[0126] Step S12: traverse the abstract syntax tree, mark key execution nodes, and generate a code node index table Traverse the AST generated by S11 and mark the following key node types: 12 function entry nodes; 35 branch point nodes; 8 loop structure nodes; 7 error handling nodes; 15 resource access nodes. Generate a code node index table CNT, containing 77 node records. Each record format is: CNT(i) = {NodeID, NodeType, LineNum, ParentNode, ChildNodes[]}; For example, the voltage regulation function entry node record is: CNT(23) = {23, FUNC_ENTRY, 352, null, [24, 25, 31]}.

[0127] Step S13: Analyze the code node index table and assign an initial importance weight to each node For each node i in CNT, the initial importance weight W_init(i) = α·C(i) + β·F(i) +γ·R(i) is calculated; where: C(i) is the cyclomatic complexity of node i, calculated as the number of branches + 1; F(i) is the functional attribute score of node i, ranging from 1 to 10; R(i) is the resource relevance of node i, ranging from 0 to 5; α is the complexity weight coefficient, with a value of 0.4; β is the functional importance weight coefficient, with a value of 0.4; γ is the resource relevance weight coefficient, with a value of 0.2; i is the node index, ranging from 1 to 77.

[0128] For example, the initial importance weight calculation of the battery charging control function is: node ID: 42; cyclomatic complexity C(42) = 6 (5 branches + 1); functional attribute F(42) = 9 (core function); resource dependency R(42) = 5 (directly control hardware); W_init(42) = 0.4×6 + 0.4×9 + 0.2×5 = 2.4 + 3.6 + 1.0 = 7.0; Step S14: Determine the instrumentation location and initial sampling frequency, and generate the initial instrumentation configuration Based on the node importance weight W_init, the instrumentation strategy is determined: if W_init(i) ≥ 6.0, high-frequency sampling is used (every execution); if 3.0 ≤ W_init(i) < 6.0, medium-frequency sampling is used (once every five executions); and if W_init(i) < 3.0, low-frequency sampling is used (once every 20 executions). An initial instrumentation configuration file (IPC) is generated, containing records for 38 nodes to be instrumented. Each record format is: IPC(j) = {NodeID, SamplingFreq, BufferPriority}. A code structure description file (CSD) is also generated, containing the code structure hierarchy, control flow graph, and data dependency information.

[0129] Perform centrality analysis based on the structure description file and initial instrumentation configuration to build topological relationships, including: Step S21: parse the code structure description file and build the execution dependency matrix Read the CSD file generated in step S14, extract the calling relationship and execution order dependency between nodes, and construct a 77×77 execution dependency matrix EDM(i,j) = w_call·C(i,j) + w_data·D(i,j) + w_ctrl·F(i,j); where: EDM(i,j) is the dependency strength from node i to node j; C(i,j) is the calling relationship index, which is 1 if i directly calls j, otherwise it is 0; D(i,j) is the data dependency index, ranging from 0 to 1; F(i,j) is the control flow dependency index, ranging from 0 to 1; w_call is the calling relationship weight, with a value of 0.5; w_data is the data dependency weight, with a value of 0.3; w_ctrl is the control flow dependency weight, with a value of 0.2; i and j are node indexes, ranging from 1 to 77.

[0130] For example, calculate the dependency between the voltage monitoring function (i=15) and the battery management function (j=42): C(15,42) = 0 (no direct call); D(15,42) = 0.8 (strong data dependency, voltage results affect battery management); F(15,42) = 0.5 (moderate control flow dependency); EDM(15,42) = 0.5×0 + 0.3×0.8 + 0.2×0.5 = 0 + 0.24 + 0.1 = 0.34; Step S22: Convert the execution dependency matrix into a directed graph structure. First, construct the initial execution topology graph G_init = (V, E) based on the EDM: the node set V contains 77 nodes, corresponding to each code block; the edge set E contains all directed edges with dependency strength EDM(i,j) ≥ 0.2; a total of 183 directed edges are generated; Add attributes to each edge, including conditional execution relationship and execution frequency estimation: conditional execution attribute CE(i,j): records the conditions that must be met for execution from i to j; execution frequency attribute EF(i,j): estimates the execution frequency, ranging from 1 to 100.

[0131] Step S23: Apply centrality analysis algorithm to process the initial execution topology graph Apply various centrality analysis algorithms to G_init to calculate node importance: Step S231: For each node i, calculate its degree centrality DC(i) = w_in·In(i) + w_out·Out(i); where: DC(i) is the degree centrality index of node i; In(i) is the in-degree of node i, that is, the number of nodes calling i; Out(i) is the out-degree of node i, that is, the number of nodes called by i; w_in is the in-degree weight coefficient, which takes a value of 0.4; w_out is the out-degree weight coefficient, which takes a value of 0.6; i is the node index, ranging from 1 to 77.

[0132] For example, the degree centrality calculation of the battery status detection function (i=36): In(36) = 5 (called by 5 other functions); Out(36) = 3 (calls 3 other functions); DC(36) = 0.4×5 + 0.6×3 = 2.0 + 1.8 = 3.8; Step S232: Apply the improved betweenness centrality algorithm to calculate the betweenness centrality of each node BC(i) = ∑(s≠i≠t) σ_st(i) / σ_st; where: BC(i) is the betweenness centrality of node i; σ_st is the number of shortest paths from node s to node t; σ_st(i) is the number of shortest paths from s to t passing through node i; s and t are node indices, and all possible node pairs are taken; i is the node index for which the betweenness centrality is to be calculated, ranging from 1 to 77.

[0133] For example, the betweenness centrality calculation of the low-power mode switching function (i=51): After node statistics, there are 27 pairs of node pairs (s, t) whose shortest paths pass through node 51; the sum of σ_st(51) / σ_st of these 27 pairs of node pairs is 18.5; BC(51) =18.5; Step S233: Design and apply a specialized PageRank algorithm to calculate the influence index PR(i) = (1-d) +d·∑(j→i) PR(j)·w(j,i) / ∑(j→k) w(j,k); where: PR(i) is the PageRank influence value of node i; d is the damping coefficient, which is 0.85; w(j,i) is the edge weight from node j to i, i.e., EDM(j,i); j→i indicates that there is an edge from j to i; j→k indicates that there is an edge from j to any node k; i is the node index, ranging from 1 to 77. An iterative calculation method is used, with the initial PR value of all nodes being 1, and convergence after 10 iterations. For example, the final PageRank value of the main power control function (i=27) is: PR(27) = 4.62.

[0134] Step S234: Calculate the execution breakpoint sensitivity and develop an execution breakpoint sensitivity analysis method to evaluate the impact of the node on the overall execution flow: EBS(i) = 1 - (RCC_G-i / RCC_G); where: EBS(i) is the execution breakpoint sensitivity of node i; RCC_G is the number of connected components of the original execution topology graph G; RCC_G-i is the number of connected components of graph G after removing node i; i is the node index, ranging from 1 to 77.

[0135] For example, the execution breakpoint sensitivity calculation of the system initialization function (i=8) is as follows: the number of connected components of the original graph G is RCC_G = 1; after removing node 8, the graph becomes 3 connected components, RCC_G-8 = 3; EBS(8) = 1 - (3 / 1) = 1 - 3 = -2 (a negative value indicates that the node is a critical breakpoint); Step S235: Integrate the four centrality indicators and calculate the comprehensive importance score CIS(i) = w_DC·norm(DC(i)) + w_BC·norm(BC(i)) + w_PR·norm(PR(i)) + w_EBS·norm(EBS(i)); where: CIS(i) is the comprehensive centrality indicator of node i; norm() is a normalization function that scales the indicator value to the interval [0,1]; DC(i) is the degree centrality indicator of node i; BC(i) is the betweenness centrality of node i; PR(i) is the PageRank influence value of node i; EBS(i) is the execution breakpoint sensitivity of node i; w_DC is the degree centrality weight, with a value of 0.25; w_BC is the betweenness centrality weight, with a value of 0.3; w_PR is the PageRank weight, with a value of 0.25; w_EBS is the breakpoint sensitivity weight, with a value of 0.2; i is the node index, ranging from 1 to 77.

[0136] For example, the comprehensive centrality index calculation for the battery management function (i=42) is as follows: normalized degree centrality: norm(DC(42)) = 0.78; normalized betweenness centrality: norm(BC(42)) = 0.65; normalized PageRank value: norm(PR(42)) = 0.83; normalized breakpoint sensitivity: norm(EBS(42)) = 0.92; CIS(42) = 0.25×0.78 + 0.3×0.65 + 0.25×0.83 + 0.2×0.92 = 0.195 + 0.195 +0.2075 + 0.184 = 0.7815 Step S24: Identify the key paths and key nodes, and output a key node mapping table.

[0137] Based on the comprehensive centrality index CIS and the initial importance weight W_init, the final importance of the node is calculated as FI(i) = λ·W_init(i) + (1-λ)·CIS(i)·10; where: FI(i) is the final importance value of node i; W_init(i) is the initial importance weight of node i; CIS(i) is the comprehensive centrality index of node i; λ is the static weight scaling coefficient, which is 0.3; i is the node index, which ranges from 1 to 77. Based on the FI value, key nodes (FI ≥ 7.0) and important nodes (5.0 ≤ FI < 7.0) are determined. For this example, 15 key nodes and 23 important nodes are identified, and the key node mapping table KNM is generated: KNM(k) = {NodeID, FinalImportance, Priority} For example, the final importance calculation of the battery charging control function is as follows: node ID: 42; initial importance W_init(42) = 7.0; comprehensive centrality CIS(42) = 0.7815; FI(42) = 0.3×7.0 + (1-0.3)×0.7815×10 =2.1 + 5.4705 = 7.5705; priority: critical node (Priority=1).

[0138] Compress and time-degrade the execution topology graph and node mapping table, including: Step S31: Applying a community detection algorithm to the initial execution topology graph to identify highly connected node clusters. The Louvain community detection algorithm is applied to the initial execution topology graph G_init to identify highly connected node communities Q = (1 / 2m)·∑(i,j)[A(i,j) - k(i)·k(j) / (2m)]·δ(c(i),c(j)); where: Q is the modularity index used to evaluate the quality of community division; m is the total number of edges in the graph, which is 183 in this example; A(i,j) is the adjacency matrix, which is EDM(i,j) if there is an edge between i and j, and 0 otherwise; k(i) is the degree of node i; k(j) is the degree of node j; c(i) is the community to which node i belongs; c(j) is the community to which node j belongs; δ(c(i),c(j)) is the Kronecker function, which is 1 when c(i)=c(j) and 0 otherwise; i and j are node indices, ranging from 1 to 77.

[0139] Optimize the community partitioning until the modularity Q cannot be further improved. Finally, 5 communities are detected: Community 1 (power control): 23 nodes; Community 2 (battery management): 18 nodes; Community 3 (low power mode): 14 nodes; Community 4 (error handling): 12 nodes; Community 5 (system interface): 10 nodes; Generate the node community partition table NCP: NCP(i) = {NodeID, CommunityID} Step S32: Perform hierarchical graph compression based on the node community partition table and key node mapping table Step S321: Read the node community partition table NCP and the key node mapping table KNM, and construct the compression decision matrix CDM(c) = {CR(c), PN(c), KNC(c)}; where: CDM(c) is the compression decision for community c; CR(c) is the target compression ratio for community c; PN(c) is the number of protected nodes in community c; KNC(c) is the number of key nodes in community c; and c is the community ID, ranging from 1 to 5. For each community c, set the target compression ratio CR(c): CR(c) = max(0.2, 0.8 - 0.1·KNC(c)) For example, the compression decision of the battery management community (c=2): the community contains 6 key nodes, KNC(2) = 6; target compression ratio CR(2) = max(0.2, 0.8 - 0.1×6) = max(0.2, 0.2) = 0.2; number of protected nodes PN(2) = 6 (all key nodes are protected); Step S322: Based on the community compression scheme CDM, apply the node merging algorithm SIM(i,j) = α·FSim(i,j) + β·TSim(i,j) + γ·CSim(i,j) to each community; where: SIM(i,j) is the similarity between nodes i and j; FSim(i,j) is the functional similarity, ranging from 0 to 1; TSim(i,j) is the topological similarity, ranging from 0 to 1; CSim(i,j) is the connection pattern similarity, ranging from 0 to 1; α is the functional similarity weight, with a value of 0.4; β is the topological similarity weight, with a value of 0.3; γ is the connection pattern similarity weight, with a value of 0.3; i and j are node indexes, ranging from 1 to 77.

[0140] For non-critical nodes within each community, if SIM(i,j) ≥ 0.75, nodes i and j are merged into one node. For example, in the battery management community (c = 2), nodes 45 and 46 (both sub-functions of battery status check) have a similarity of SIM(45,46) = 0.87; they are merged into a new node M1, preserving all connections between the two nodes. Through this iterative merging process, the final first-level compressed graph G_comp1 is obtained, reducing the number of nodes from 77 to 53.

[0141] Step S323: Process the first-level compressed graph G_comp1 and apply the edge filtering technique EI(i,j) = EF(i,j)·EDM(i,j)·FI_edge(i,j); where: EI(i,j) is the importance index of edge (i,j); EF(i,j) is the estimated execution frequency of the edge, ranging from 1 to 100; EDM(i,j) is the execution dependency strength; FI_edge(i,j) is the importance function of the node connected by the edge, calculated as min(FI(i),FI(j)) / 10; i and j are node indices. Edges with EI(i,j) ≥ 5.0 are retained, and other edges are deleted to obtain the edge simplified model. For example: Edge evaluation from voltage detection (i=15) to normal voltage processing (j=16): execution frequency EF(15,16) = 95 (high-frequency execution); execution dependency intensity EDM(15,16) = 0.85; edge node importance FI_edge(15,16) = min(6.2, 4.3) / 10 = 0.43; EI(15,16) = 95×0.85×0.43 = 34.7 (retained); Edge evaluation from fault log (i=63) to error display (j=67): execution frequency EF(63,67) = 2 (low-frequency execution); execution dependency intensity EDM(63,67) = 0.4; edge node importance FI_edge(63,67) = min(3.2, 3.5) / 10 = 0.32; EI(63,67) = 2×0.4×0.32 = 0.256 (deleted); after edge filtering, the number of edges is reduced from 159 to 87.

[0142] Step S324: Integrate the first-level compression graph and edge simplification model to establish a multi-level abstract view: L0: original graph (77 nodes, 183 edges); L1: first-level compression (53 nodes, 159 edges); L2: edge simplification (53 nodes, 87 edges); L3: community-level view (5 community nodes, 12 inter-community edges); design the inter-level navigation index table LNI to record the mapping relationship between nodes and edges in each abstract level: LNI(l,n) = {NodeID_l, MappedNodes_l-1[], MappedEdges_l-1[]}; output the compressed execution graph G_comp = {L0, L1, L2, L3, LNI} and the multi-level node mapping relationship MLM.

[0143] This embodiment merges non-critical areas while maintaining accurate representation of key nodes, effectively reducing the complexity burden of the execution topology graph. In the power management subsystem embodiment, only 53 nodes are retained after compression of the original 77 nodes, with a compression rate of 31%, and a key information retention rate of 98%. In particular, in the battery management community, 18 nodes are compressed to 11 nodes, with a compression rate of 39%, but the key information is almost intact. This makes it possible to maintain execution monitoring of larger-scale codes under limited resource conditions of embedded systems, while reducing the computational complexity of the graph analysis algorithm from O(n²) to O(n·log(n)).

[0144] Step S33: Design and apply temporal weight decay function Step S331: Analyze the edge weight distribution characteristics and establish an edge type classification table. Analyze the edge types in the compressed execution graph and classify the edges into three categories: Type 1: Key function conversion edge (connecting two key nodes); Type 2: Regular execution edge (connecting at least one important node); Type 3: Low-value loop edge (connecting non-key and non-important nodes); Generate an edge type classification table ECT: ECT(i,j) = {EdgeType, FromNode, ToNode}.

[0145] Step S332: Design a timing decay function W_decay(i,j,t) = W_init(i,j)·DecayFunc(EdgeType(i,j),t) for different types of edges; where: W_decay(i,j,t) is the decayed weight of edge (i,j) at time t; W_init(i,j) is the initial weight of edge (i,j); DecayFunc(type,t) is the decay function, type 1 uses e^(-0.1t), type 2 uses 1-0.2t, and type 3 uses e^(-0.5t); EdgeType(i,j) is the type of edge (i,j), with a value of 1-3; t is a time parameter, indicating the time unit since the last execution; i and j are node indexes.

[0146] For example, calculate the decay coefficients of three types of edges at t=5: Type 1 (critical function conversion edge): DecayFunc(1,5) = e^(-0.1×5) = e^(-0.5) ≈ 0.607; Type 2 (regular execution edge): DecayFunc(2,5) = 1-0.2×5 = 1-1 = 0 (no more decay when reaching zero); Type 3 (low-value loop edge): DecayFunc(3,5) = e^(-0.5×5) = e^(-2.5) ≈ 0.082; Step S333: Apply the decay function to the dual time window mechanism: short-term behavior window Ws: 24 hours, high decay weight; long-term pattern window Wl: 7 days, low decay weight; calculate the timing-sensitive edge weight value W_time(i,j) = α·W_decay(i,j,t_s) + (1-α)·W_decay(i,j,t_l); where: W_time(i,j) is the timing weight of edge (i,j); W_decay(i,j,t_s) is the decay weight in the short-term window; W_decay(i,j,t_l) is the decay weight in the long-term window; α is the short-term window weight coefficient, which is 0.6; t_s is the short-term time parameter; t_l is the long-term time parameter; i and j are node indexes. For example, calculate the timing weight of the key function transition edge (i=27,j=42): short-term window decay weight: W_decay(27,42,2) = 0.9×e^(-0.1×2) = 0.9×0.819 = 0.737; long-term window decay weight: W_decay(27,42,10) = 0.9×e^(-0.1×10) = 0.9×0.368 = 0.331; timing weight: W_time(27,42) = 0.6×0.737 + 0.4×0.331 = 0.442 + 0.132 = 0.574; Step S334: Identify critical but low-frequency execution paths and apply the minimum weight guarantee strategy W_final(i,j) =max(W_time(i,j), W_min(i,j)); where: W_final(i,j) is the final weight of edge (i,j); W_time(i,j) is the timing weight of edge (i,j); W_min(i,j) is the minimum guarantee weight of edge (i,j), which is 0.3 for critical edges, 0.15 for important edges, and 0 for ordinary edges; i and j are node indexes. For example, the final weight calculation of the error handling critical path (i=42,j=63) is as follows: timing weight W_time(42,63) = 0.12 (critical edge for low-frequency execution); minimum guaranteed weight W_min(42,63) = 0.3; final weight W_final(42,63) = max(0.12, 0.3) = 0.3 (to ensure that the important path is not overly attenuated due to low frequency); the timing weight mapping table TWM is generated, combined with the multi-level compression model, to output the final compressed execution graph G_comp_final and the complete multi-level node mapping relationship MLM_final.

[0147] This example categorizes edges into three categories: critical function transition edges (slow decay), regular execution edges (linear decay), and low-value loop edges (rapid decay). Weights are calculated using a dual time window (short-term 24 hours, long-term 7 days). An importance protection mechanism is also designed to prevent excessive attenuation of critical but infrequent paths. This example demonstrates that critical paths, such as the battery overheat protection path, maintain a minimum weight of 30% even if triggered only once a week, ensuring continuous monitoring. Frequently executed but low-value log loop edges see their weight drop to 7% after three days without anomalies, significantly reducing storage burdens.

[0148] Deploy a three-level hierarchical buffer based on the compressed execution graph and multi-level mapping relationship to collect execution data, including: Step S41: Convert the monitoring point information in the compressed execution graph into actual instrumentation instructions Convert the monitoring point information in G_comp_final into actual instrumentation instructions. For the C language source code of this embodiment, 53 instrumentation instructions are generated. Each instrumentation instruction format is: probe_point(NodeID, FunctionName, LineNumber, ProbeType); for example, the instrumentation instruction generated for the battery management function is: probe_point(42, "battery_manage", 513, FUNC_ENTRY).

[0149] Step S42: Initialize the hierarchical buffer of the three time scales Step S421: Calculate the available monitoring resource quota and generate the initial buffer configuration. Read the system resource status and determine the available monitoring resources: available memory: 256KB; available storage: 1.2MB; CPU overhead limit: 3%. Allocate resources in a ratio of 5:3:2 to generate the initial buffer configuration CBC: Micro buffer (high frequency): 128KB memory; Meso buffer (medium frequency): 76.8KB memory; Macro buffer (low frequency): 51.2KB memory; Storage allocation: micro 600KB, meso 360KB, macro 240KB; Generate initial buffer configuration CBC = {MemoryAllocation, StorageAllocation, CPULimit, SamplingConfig}; Step S422: Create a micro buffer data structure to complete the micro layer monitoring initialization Based on CBC, a microbuffer data structure MicroBuffer = {Capacity, EntrySize, TimeWindow, SamplingInterval, WriteStrategy, DataStructure} is designed. Among them, Capacity is the buffer capacity, which is set to 128KB; EntrySize is the size of each record, which is set to 24 bytes; TimeWindow is the coverage time window, which is set to 10 minutes; SamplingInterval is the sampling interval, which is set to 100ms; WriteStrategy is the write strategy, which is set to "cyclic overwrite"; DataStructure is the data structure, which is set to "ring buffer".

[0150] The format of each record in the micro buffer is: MicroRecord = {Timestamp, NodeID, ExecutionCount, StateHash, ResourceUsage}; the memory layout of the micro buffer is optimized and a compact storage format is used: 8-byte timestamp (accurate to milliseconds); 2-byte node ID; 4-byte execution counter; 8-byte state hash value; 2-byte resource usage indicator; total capacity can store approximately 5461 records, covering approximately 9.1 minutes of high-frequency execution data.

[0151] Step S423: Create the meso-buffer data structure, completing meso-level monitoring initialization. MidBuffer = {Capacity, EntrySize, TimeWindow, SamplingInterval, RecordStrategy, CompressionRatio}; where Capacity is the buffer capacity, set to 76.8KB; EntrySize is the size of each record, set to 32 bytes; TimeWindow is the coverage time window, set to 4 hours; SamplingInterval is the sampling interval, set to 5 minutes; RecordStrategy is the recording strategy, set to "selective recording"; CompressionRatio is the compression ratio, set to 3:1.

[0152] Mid-buffer record format, focusing on key state transitions MidRecord = {TimeInterval,NodeSequence[], StateTransitions[], ExecutionCounts[], AggregatedResources} Set data retention rules based on importance: Critical nodes (FI based on importance): record every state change; Important nodes (5.0 points): record every 3 state changes; Ordinary nodes (FI < 5.0): record every 10 state changes; The total capacity can store approximately 2400 records, covering approximately 4 hours of medium-frequency executive summaries.

[0153] Step S424: Create a macro buffer data structure to complete macro-level monitoring initialization. MacroBuffer = {Capacity, EntrySize, TimeWindow, SamplingInterval, TriggerMechanism, DataFormat}; where Capacity is the buffer capacity, set to 51.2KB; EntrySize is the size of each record, set to 64 bytes; TimeWindow is the coverage time window, set to 7 days; SamplingInterval is the sampling interval, set to 30 minutes; TriggerMechanism is the trigger mechanism, set to "State Transition Trigger"; DataFormat is the data format, set to "Compressed Topology Summary".

[0154] Macro buffer record format, focusing on long-term execution mode MacroRecord = {TimeBlock,ActivityGraph, FrequencyDistribution, AnomalyIndicators, SystemState} Configure a triggered recording mechanism based on state transitions: records are only recorded when the system state changes significantly; significant changes are defined as: changes in the execution mode of key nodes ≥ significant changes or system state transitions; the total capacity can store approximately 800 records, covering approximately 16.7 days of low-frequency execution summaries.

[0155] Step S425: Establish data flow rules between buffers and generate a hierarchical buffer manager Integrate the three-level buffer and establish the data flow rule DataFlow(level_from, level_to) ={TransferCondition, FilterFunction, AggregationMethod, UpdateFrequency}; where: level_from is the source buffer level; level_to is the target buffer level; TransferCondition is the data transmission condition; FilterFunction is the filter function; AggregationMethod is the aggregation method; UpdateFrequency is the update frequency.

[0156] For example, the data flow rules from micro to meso are as follows: transmission condition: micro buffer fill rate ≥ (e.g., from or time interval ≥ hours and minutes); filtering function: filter by node importance, retain key nodes and nodes with significant changes; aggregation method: aggregate execution paths within the time window and calculate frequency distribution; update frequency: update every 5 minutes; Generate a unified hierarchical buffer manager BM to integrate monitoring initialization information and data flow rules.

[0157] Step S43: Real-time acquisition of instrumentation trigger data during code execution to generate a real-time execution sequence. The function that collects code execution data is logic_probe(NodeID, Context) = {record current node execution information, update counter, calculate state hash, record timestamp, write to microbuffer}; where NodeID is the ID of the currently executing node; Context is the execution context, which includes variable state and call stack information.

[0158] For example, when the battery management function (NodeID=42) is executed: the timestamp is recorded: 1621329465782 (millisecond timestamp). The execution counter is increased: Counter(42) += 1; the current state hash value is calculated: StateHash = SHA1("Voltage=3.7V;Current=0.2A;Temp=32C;..."); resource usage indicators are calculated: CPU=2.3%, Memory=340KB; the record item is written to the micro buffer: {1621329465782, 42, 1286, 0x7A23F19B, 0x0623}; The real-time execution sequence RES is continuously generated as the code is executed and dynamically recorded in the micro buffer.

[0159] Step S44: Regularly analyze the real-time execution sequence and selectively store it in the meso- and macro-buffers to form the execution trace raw data. Design a selective recording algorithm SelectiveRecord(RES, TimeWindow,ImportanceThreshold) = {Filter important events, calculate state transitions, aggregate execution data, generate summaries, and write to appropriate buffers}; where: RES is the real-time execution sequence; TimeWindow is the length of the analysis time window; ImportanceThreshold is the importance threshold that determines whether an event is recorded.

[0160] For example, analyzing the execution sequence of the past 5 minutes: extracting the key node sequence: {8 execution sequence: extracting the key node sequence: ld data,; Calculate state transitions from "normal charging" to "overheat protection." Aggregate execution statistics: The battery monitoring function was executed 86 times, with an average CPU usage of 2.1%. Generate a meso-buffer record and write the following: {1621329700000, [8,27,42,51,42,27], ["Normal"reshold) = {)rFunction, AggregationMe,17], 0x2134}. Similarly, generate a macro-buffer record every 30 minutes, focusing on system-level state changes and long-term execution patterns. Data from these three buffers collectively constitute the execution trace raw data (TRD), providing the basis for subsequent anomaly analysis.

[0161] 5. Analyze trajectory raw data through topological evolution to identify abnormal paths Step S51: Construct execution subgraphs of different time windows and calculate topological feature parameters Step S511: Segment by multiple time window scales to form a time window data set Read the execution trace raw data TRD and segment it according to multiple time window scales: W1: 5-minute window, 48 time periods in total; W2: 30-minute window, 8 time periods in total; W3: 4-hour window, 1 time period in total; W4: 24-hour window (historical data); Step S512: Apply the graph reconstruction algorithm to generate a sequential execution subgraph Apply the graph reconstruction algorithm to the dataset of each time window to restore the execution topology G_sub(tw) =GraphRebuild(TRD(tw), NodeMap, EdgeMap); where: G_sub(tw) is the execution subgraph of time window tw; TRD(tw) is the original trajectory data in time window tw; NodeMap is the multi-level node mapping relationship; EdgeMap is the edge mapping relationship; tw is the time window index; GraphRebuild is the graph reconstruction function to restore the execution topology in this time window.

[0162] For example, to perform subgraph reconstruction for a 30-minute window W2_3: Extract execution records within the window period from TRD: 378 micro-level records and 24 meso-level records; Converted into node access sequence, 37 active nodes and 68 execution edges were identified; Apply NodeMap to map the merged nodes back to the original nodes; Construct the timing execution subgraph G_sub(W2_3); Step S513: Calculate the topological feature parameters of each sequential execution subgraph to form a topological feature vector set For each execution subgraph G_sub(tw), calculate the topological feature parameters TF(tw) = {DD(tw), CC(tw), PL(tw), CN(tw), ER(tw), AS(tw)}; where: TF(tw) is the topological feature vector of the time window tw; DD(tw) is the node degree distribution vector; CC(tw) is the clustering coefficient vector; PL(tw) is the path length distribution vector; CN(tw) is the centrality index vector; ER(tw) is the edge importance vector; AS(tw) is the anomaly score vector; tw is the time window index.

[0163] For example, the topological characteristic parameters of the W2_3 window are calculated as follows: Node degree distribution DD (W2_3): Calculate the degree distribution histogram of all nodes and obtain [3, 8, 12, 9, 4, 1] (the number of nodes with degrees 1-6); Clustering coefficient CC (W2_3): Calculate the average clustering coefficient of all nodes to be 0.42; Path length distribution PL (W2_3): Calculate the distribution of the shortest path lengths between all node pairs and obtain [0, 54, 173, 92, 18] (the number of paths with lengths 1-5); Centrality index CN (W2_3): Calculate the centrality index of key nodes and obtain [0.78, 0.65, 0.83, 0.55, 0.92] (the centrality values ​​of 5 key nodes); Edge importance ER (W2_3): Calculate the distribution of high-importance edges and obtain [12, 8, 5] (the number of high, medium, and low-importance edges); Anomaly score AS (W2_3): Temporarily set to 0 and updated in subsequent steps; Step S514: Organize multi-dimensional feature data to generate a temporal topology feature matrix Arrange the feature vectors of all time windows in chronological order to generate the temporal topology feature matrix STM = [TF(tw_1), TF(tw_2), ..., TF(tw_n)], where STM is the temporal topology feature matrix, TF(tw_i) is the topological feature vector of time window tw_i, and n is the total number of time windows. The STM matrix has an n-matrix shape, where n is the number of time windows (57 in this example) and m is the feature dimension (24 in this example).

[0164] Step S52: Apply time series analysis to the temporal topological feature matrix to extract the temporal change pattern of the topological structure. Using the time series analysis method, a topological evolution model is established: TEM(t) = {BaseLine(t), Trend(t), Seasonality(t), PredictionFunc(t+1)}; where: TEM(t) is the topological evolution model at time t; BaseLine(t) is the baseline value function; Trend(t) is the trend function; Seasonality(t) is the periodic function; PredictionFunc(t+1) is the next moment prediction function; and t is the time index.

[0165] Apply time series decomposition to each feature dimension: Extract BaseLine(t): Calculate the baseline value of each feature using the moving average method; Identify Trend(t): Analyze the long-term trend of the feature using linear regression; Extract Seasonality(t): Identify periodic patterns using Fourier analysis; Construct PredictionFunc(t+1): Use the ARIMA model to predict future feature values; For example, the analysis of node degree distribution characteristics shows: baseline values: [3.1, 8.2, 11.7, 9.3, 3.8, 0.9]; trend: the number of nodes with degree 1 is increasing (slope +0.03 / window); periodicity: a 4-hour fluctuation pattern is identified; prediction function: ARIMA(2,1,2) model, predicting the value of the next time window to be [3.2, 8.1, 11.8, 9.2, 3.7,1.0]; Step S53: Perform path causal chain analysis and counterfactual comparison to identify abnormal change points Step S531: Execute path causal chain extraction and correlation analysis The execution path condition expression state and trigger condition PCM(p) = {PC(p), PF(p), IP(p)} are extracted from the temporal topology feature matrix STM; where: PCM(p) is the condition-path mapping of path p; PC(p) is the set of conditional expressions that trigger path p; PF(p) is the execution frequency of path p; IP(p) is the input parameter space of path p; and p is the execution path index.

[0166] For example, consider the path where the battery status detects overheating protection (p=27). The following describes the conditional expression: PC(p) = "Battery.Temperature>45Seasonality(t), PredictionFun"; the execution frequency: PF(p) = 0.03 (the normal execution frequency); the input parameter space: IP(p) = {Temperature:[45,60], Voltage:[3.0,3.5], Current:[0.1,0.3]}. A condition-path mapping (CPM) is constructed to record the association patterns between different condition combinations and path selection. The probability distribution of path selection under each condition combination is calculated to distinguish between paths that are necessarily triggered and those that are possibly triggered.

[0167] Step S532: Non-uniform semantic segmentation and execution profile construction Read the execution trace raw data TRD and the execution path causal model CPM, and identify the semantic boundary points of function execution SBS = {SB(i), ContextInfo(i), FuncComplete(i)}; where: SBS is the semantic boundary marker set; SB(i) is the i-th semantic boundary point; ContextInfo(i) is the context information of boundary point i; FuncComplete(i) is the function completion flag of boundary point i; i is the boundary point index.

[0168] For example, the semantic boundaries of the battery management function cycle are identified as follows: starting boundary point: SB(23) = {NodeID:42,Timestamp:1621329465782, Type:FUNC_ENTRY}; ending boundary point: SB(47) = {NodeID:42,Timestamp:1621329467156, Type:FUNC_EXIT}; context information: ContextInfo(23) = {BatteryState:"Normal", InputParams:{...}}; function completion flag: FuncComplete(47) = True.

[0169] Based on the semantic boundary marker set SBS, the continuous execution flow is divided into variable-length semantic segments according to the principle of functional integrity. SP(i) = {StartSB, EndSB, ExecutionPath, TriggerCondition, ResourceProfile}; where SP(i) is the i-th semantic execution segment; StartSB is the starting semantic boundary; EndSB is the ending semantic boundary; ExecutionPath is the execution path sequence; TriggerCondition is the trigger condition state; ResourceProfile is the resource consumption characteristic; and i is the semantic segment index. Construct a non-uniform execution profile (NEP) to describe the system execution characteristics in terms of functional completeness. NEP = {SP(1), SP(2), ..., SP(n)}.

[0170] Dividing the continuous execution flow into semantically coherent segments of variable length solves the problem of artificially fragmented function execution caused by traditional fixed time windows. This technology analyzes the control flow transition points, data dependency change points, and function call boundaries in the code execution sequence to ensure that each analysis unit contains a complete function execution unit. In the battery management embodiment, the traditional 5-second fixed window divides the battery monitoring cycle into incomplete segments, resulting in a function completeness of only 0.68; while the non-uniform segmentation is divided according to the actual function boundaries (from the start of detection to the completion of protection measures), the function completeness reaches 0.98, and the completeness score is improved by 456%. This semantic-based segmentation enables the system to fully understand the entire process of battery protection function execution, accurately locating the temperature sensor anomaly that occurs in the reading stage rather than the judgment stage, improving the root cause location accuracy from 72% to 91%, while reducing the amount of analysis data by 43%.

[0171] Step S533: Counterfactual comparative analysis and anomaly identification Read the current non-uniform execution profile NEP and the historical execution path causal model CPM to build a counterfactual model CFM(sp) = ExpectedPath(PC(sp), IP(sp)); where: CFM(sp) is the counterfactual model of the semantic segment sp; ExpectedPath is the expected execution path function; PC(sp) is the trigger condition; IP(sp) is the input parameter; sp is the semantic segment.

[0172] Compare the difference between the actual execution path and the expected path CFD(sp) = {PathDiff(sp), CondDiff(sp), ProbDiff(sp)}; where: CFD(sp) is the counterfactual difference of the semantic segment sp; PathDiff(sp) is the path structure difference measure; CondDiff(sp) is the conditional response deviation; ProbDiff(sp) is the transition probability abnormality; sp is the semantic segment.

[0173] For example, analyze the battery overheat protection function fragment sp_42: trigger condition: temperature 48, voltage 3.4V; actual execution path: 27 execution paths: overheat protection function fragment; counterfactual model expected path: 27 actual model expected path: overheat protection function fragment; path structure difference: end node mismatch; condition response deviation: under given conditions, the expectation is to return to normal mode rather than error handling; transition probability anomaly: under path conditions, the probability anomaly of path 27 should be 0.01, but it is actually 0.82; analyze CFD, distinguish between path conversion caused by normal condition changes and abnormal path selection, and output the topology anomaly indicator set TAI = {AnomalyType, AnomalyPath, AnomalyScore, TriggerCondition}; Step S54: Abnormal execution path location and root cause analysis Step S541: Abnormal propagation chain analysis and impact assessment Read the topology anomaly indicator set TAI and the execution path causal model CPM, and trace back the execution conditions of the abnormal path APM(a) = {InitSource(a), PropagationPath(a), AffectedModules(a)}; where: APM(a) is the propagation chain model of anomaly a; InitSource(a) is the initial anomaly source; PropagationPath(a) is the anomaly propagation path; AffectedModules(a) is the set of affected modules; a is the anomaly index.

[0174] For example, analyzing the propagation chain of battery overheating anomaly (a=4): Initial anomaly source: abnormal temperature sensor reading (NodeID=36); anomaly propagation path: 36 Propagation path: 36 Source: temperature sensor; Affected modules: battery management, low power control, error handling; Assess the impact of anomalies on downstream modules and system functions, calculating the functional impairment risk IR(a,m) = Severity(a) x Impact(a), Impact(m) . IR(a,m) is the functional impairment risk of anomaly a on module m; Severity(a) is the severity of anomaly a, ranging from 1 to 10; Impact(m) is the importance of module m; PropagationProb(a,m) is the probability that anomaly a propagates to module m; a is the anomaly index; and m is the module index. Generate an anomaly impact assessment report (AIR) to record the anomaly propagation and impact.

[0175] Step S542: Accurate root cause location and verification Read the preliminary results of anomaly diagnosis and the condition-path mapping diagram CPM to determine the minimum condition set RCS(a) that triggers the anomaly = {MinConditions(a), ConfidenceScore(a), VerificationResult(a)}; where: RCS(a) is the root cause candidate set of anomaly a; MinConditions(a) is the minimum condition set that triggers anomaly a; ConfidenceScore(a) is the confidence score; VerificationResult(a) is the verification result; and a is the anomaly index.

[0176] For example, to locate the root cause of a battery overheating anomaly (a=4), the minimum condition set is: {TempSensor.Offset = +10a), ConfidenceScore(a), Verificationa; Confidence score: 0.92 (high confidence); Verification result: confirmed by the counterfactual model that the anomaly no longer occurs after correcting these two conditions.

[0177] Generate an abnormal path report (APR) containing the following: Abnormal type: battery status misjudgment caused by sensor reading offset; Abnormal severity: 8 (high); Root cause confidence: 0.92; Abnormal impact: may cause battery over-discharge or charging protection error activation; Repair suggestion: calibrate the temperature sensor offset and check the ADC reference voltage.

[0178] Step S55: Dynamically adjust the instrumentation strategy and resource allocation, and generate monitoring strategy update instructions Step S551: Intelligent monitoring resource reallocation Read the abnormal path report APR and the topology anomaly indicator set TAI, analyze the system resource status and monitoring requirements MRP = {MemoryRealloc(), StorageRealloc(), SamplingRateAdjust()}; where: MRP is the monitoring resource allocation plan; MemoryRealloc() is the memory reallocation function; StorageRealloc() is the storage reallocation function; SamplingRateAdjust() is the sampling rate adjustment function.

[0179] For example, resource allocation adjustments to address temperature sensor anomalies include increasing memory allocation for sensor reading nodes from 5% to 15% and increasing storage allocation for the battery management module from 20% to 35%. Furthermore, the sampling rate for temperature reading nodes was adjusted from sampling once every five executions to sampling every execution. Generates buffer reconfiguration instructions (BRIs) to instruct the hierarchical buffer manager to adjust resource allocation.

[0180] Step S552: Adaptive instrumentation density adjustment Analyze the abnormal path report APR and the execution path causal model CPM to identify the code area that needs to be monitored: PDA = {NodeDensity(i), FrequencyAdj(i), PriorityLevel(i)}; where: PDA is the instrumentation density adjustment plan; NodeDensity(i) is the instrumentation density of node i; FrequencyAdj(i) is the frequency adjustment coefficient of node i; PriorityLevel(i) is the priority of node i; i is the node index.

[0181] For example, adjust the instrumentation density of the temperature sensor-related code area: Temperature reading function (NodeID=36): Increase the instrumentation density from 0.2 to 0.8 (insertion probability per line of code); ADC reading function (NodeID=31): Increase the instrumentation density from 0.3 to 0.7; Power control (NodeID=23) under normal circumstances: Reduce the instrumentation density from 0.5 to 0.2; Generate an instrumentation frequency configuration table PFC to guide the sampling frequency allocation of the instrumentation points.

[0182] Step S553: ​​Generate a forward-looking monitoring strategy Read the execution path causal model CPM and the topology evolution eigenvector TEV, and analyze the system behavior evolution direction RPG= {RiskNodes[], TrendAnalysis(), PredictiveEnhancement()}; where: RPG is the risk prediction map; RiskNodes[] is the list of potential risk nodes; TrendAnalysis() is the trend analysis function; PredictiveEnhancement() is the prediction enhancement function.

[0183] For example, based on trend analysis, potential problem areas were predicted: the call frequency trend of the voltage monitoring function (NodeID=15) was found to be abnormal; the probability distribution of conditional branch selection of the current limiting function (NodeID=47) was slightly shifted; and the timing characteristics of the power state switching (NodeID=27) were slightly changed, indicating potential problems. Generate a preventive monitoring strategy (PPS) to increase monitoring density in these areas in advance. Integrate the instrumentation strategy update instruction (PSI) and the preventive monitoring strategy (PPS) to form a complete monitoring strategy update instruction (MSI), which is fed back into the data collection process to achieve closed-loop adaptive monitoring (MSI = {PDA, BRI, PPS, FeedbackMechanism}).

[0184] This embodiment uses the concept of topological evolution feature vectors to effectively capture the changing patterns of the execution topology structure over time; uses a hierarchical buffer structure with three time scales to balance fine-grained data collection and long-term monitoring needs; and adopts an importance-aware multi-scale topological compression algorithm to ensure that key nodes maintain high-precision representation. Through a differentiated temporal weight decay mechanism, the use of memory and computing resources in long-term monitoring is optimized. Based on the execution path causal chain analysis technology, we have an in-depth understanding of "why execution" rather than just focusing on "what was executed." We have implemented a non-uniform segmentation technology based on functional semantics to ensure the functional integrity of the analysis unit. Combined with the introduction of counterfactual comparative analysis, we can accurately distinguish between abnormal paths and normal condition changes. A topology-aware dynamic resource allocation mechanism is established to form a closed-loop adaptive monitoring system.

[0185] This method achieved an anomaly detection accuracy of 92.5% and an average warning lead time of 5.8 seconds, while also reducing memory usage to 256KB and CPU overhead to 3.0%, a significant improvement over traditional methods. These improvements enable efficient and reliable code execution monitoring in embedded systems under strict resource constraints, providing strong support for improving system stability and reliability.

[0186] The preferred embodiments of the present invention are described in detail above. However, the present invention is not limited to the specific details in the above embodiments. Within the technical concept of the present invention, various equivalent transformations can be made to the technical solutions of the present invention, and these equivalent transformations all fall within the scope of protection of the present invention.

Claims

1. A dynamic monitoring method for embedded code instrumentation, characterized in that: include: Parse the source code, generate the structure description file and the initial instrumentation configuration; Perform centrality analysis based on the structure description file and initial instrumentation configuration, build topology relationships, and output execution topology graphs and node mapping tables; Compress and time-decay the execution topology graph and node mapping table to generate a compressed execution graph and multi-level mapping relationship; Deploy a three-level hierarchical buffer based on the compressed execution graph and multi-level mapping relationship to collect execution data and form trajectory raw data; The original trajectory data is analyzed through topological evolution to identify abnormal paths and generate monitoring strategy update instructions accordingly.

2. The method according to claim 1, characterized in that Identify abnormal execution paths, including: Based on the original trajectory data, we construct execution subgraphs of multiple time windows, calculate the topological feature parameters to form a feature matrix of the temporal topology, and extract the time-varying pattern of the topological structure from it to establish a topological evolution model. The topological features of the current trajectory data are compared with the evolution model. Through execution path causal chain analysis and counterfactual comparison, abnormal change points are identified and a set of topological anomaly indicators is generated. Based on this, the abnormal execution path is located, the severity is evaluated, and an abnormal path report is obtained.

3. The method according to claim 2, characterized in that Generate a set of topology anomaly indicators, including: Extract the conditional expression status and trigger conditions of the execution path from the feature matrix of the temporal topology, establish a mapping relationship between input conditions and path selection, and form an execution path causal model; Combining the original trace data with the execution path causal model, the semantic boundary points of function execution are identified, the execution flow is divided into semantically coherent segments of variable length, and a non-uniform execution profile is generated. Compare the current non-uniform execution profile with the execution path causal model, build a counterfactual model of the expected execution path, calculate the difference between the actual execution path and the expected path, distinguish between normal condition changes and abnormal path selection, and generate a set of topological anomaly indicators.

4. The method according to claim 3, characterized in that Extract the conditional expression status and trigger conditions of the execution path, including: Extract the conditional expression status and input parameters of each execution path from the timing topology feature matrix, record the specific condition values ​​that trigger each path, and generate a path selection condition table; Analyze the path selection condition table, build a conditional decision tree model, identify the association pattern between condition combinations and path selection, establish a mapping relationship between input conditions and path selection, and form a condition-path mapping diagram; Integrate the condition-path mapping diagram with execution frequency data, calculate the probability distribution of path selection under different condition combinations, distinguish between inevitable and possible triggering paths, and generate an execution path causal model.

5. The method according to claim 3, characterized in that Divide the execution flow into semantically coherent segments of variable length to generate non-uniform execution profiles, including: Read the original trace data and the execution path causal model, analyze the control flow transition points, data dependency change points, and function call boundaries in the code execution sequence, identify the start and end positions of execution units with semantic integrity, and form a semantic boundary marker set; Based on the semantic boundary marker set, the continuous execution flow is divided into variable-length semantic segments according to the principle of functional integrity, ensuring that each segment contains a complete functional execution unit, and generating a semantic execution segment set; For each fragment in the semantic execution fragment set, its execution environment context, trigger condition status and resource consumption characteristics are extracted, the path selection pattern and state transition characteristics within the fragment are calculated, and a non-uniform execution profile reflecting functional integrity is constructed.

6. The method according to claim 2, characterized in that Also includes: After obtaining the abnormal path report, the topology evolution feature vector is updated, the instrumentation strategy and buffer resource allocation are adjusted accordingly, and the monitoring strategy update instruction is generated. The monitoring strategy update instructions are composed of an instrumentation density adjustment plan, a buffer resource reallocation plan, and preventive monitoring enhancement instructions.

7. The method according to claim 6, characterized in that Adjust the instrumentation strategy and buffer resource allocation, and generate monitoring strategy update instructions, including: Generate a monitoring demand assessment table based on the location and impact range of the abnormal path report and the topology evolution feature vector abnormal area in the execution topology, and calculate the optimal instrumentation density adjustment strategy based on this table to form an instrumentation density adjustment plan; Analyze the current hierarchical buffer status, reallocate the resource ratio of the three-level buffer according to the instrumentation density adjustment plan, and obtain the buffer resource reallocation plan; Based on the trend information in the topology evolution feature vector, potential problem areas are predicted, the monitoring density is enhanced in advance, and preventive monitoring enhancement instructions are generated.

8. The method according to claim 1, characterized in that Deploy a three-level hierarchical buffer to collect execution data and generate raw trajectory data, including: Convert the monitoring point information in the compressed execution graph into actual instrumentation instructions to generate an instrumentation instruction set; Initialize hierarchical buffers at the micro, meso, and macro time scales based on the instrumented instruction set and system resource status; Collect the trigger data of the instrumentation points during code execution in real time, record the node access sequence and state changes, store them in the micro buffer, and generate the real-time execution sequence; Regularly analyze the real-time execution sequence, and store the critical path information and state transition data into the meso-buffer and macro-buffer according to the node importance evaluation results to form the execution trajectory raw data.

9. The method according to claim 1, characterized in that Generates a compressed execution graph and multi-level mapping relationships, including: Apply the community detection algorithm to the initial execution topology graph to form a node community partition table; Based on the node community partition table and node mapping table, hierarchical graph compression is performed to retain key nodes and generate a multi-level compression model; Apply the temporal weight decay function to make the edge weights in the multi-level compression model decay over time and establish a temporal weight mapping table; Integrate the multi-level compression model and timing weight mapping table to generate a compressed execution graph and multi-level node mapping relationship.

10. The method according to claim 1, characterized in that Perform centrality analysis and construct topological relationships, including: Parse the code structure description file, extract the calling relationship and execution order dependency between nodes, and build an execution dependency matrix; Convert the execution dependency matrix into a directed graph structure, where nodes represent code blocks and edges represent execution flows, forming an initial execution topology graph. Based on the initial execution topology graph, degree centrality, betweenness centrality and execution breakpoint sensitivity are calculated to obtain a set of topological centrality indicators, including the integrated degree centrality table, betweenness centrality table, influence indicator table and breakpoint sensitivity table.

11. The method according to claim 10, characterized in that Obtain a set of topological centrality metrics, including: Calculate the degree centrality index of each node in the initial execution topology, including the in-degree and out-degree that reflect the frequency of the node being called and calling other nodes, and generate a degree centrality table; Identify the key nodes at the intersection of multiple execution paths in the initial execution topology graph and obtain the betweenness centrality table; Analyze the directional characteristics of code execution and the frequency of node execution, calculate the influence of each node in the overall execution flow, and generate an influence index table; By simulating the removal of a single node, the impact on the connectivity of the overall execution graph is evaluated, key execution breakpoints are identified, and a breakpoint sensitivity table is formed.

12. The method according to claim 10, characterized in that Generates the structure description file and initial instrumentation configuration, including: Read the source code file and use the compiler front-end to parse and generate an abstract syntax tree; Traverse the abstract syntax tree, mark key execution nodes including function entry, branch points, and loop structures, and generate a code node index table; Analyze the static characteristics of each node in the code node index table, including complexity and functional attributes, assign an initial importance weight to each node, and form a node importance table; According to the node importance table, the instrumentation location and initial sampling frequency are determined, and the initial instrumentation configuration and code structure description file are generated.

Citation Information

Cited By

  • Road maintenance machinery fault state characterization method and device

    CN121146738A

  • Inspection monitoring method and device based on multimode data

    CN121259729A