An embedded C code reverse MBD modeling method and system based on code attribute graph and multi-agent large language model

CN122924835APending Publication Date: 2026-10-16NANJING UNIV OF AERONAUTICS & ASTRONAUTICS
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202611132639.4
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-07-29
Publication Date
2026-10-16

AI Technical Summary

Technical Problem

[0007]第二,缺乏面向嵌入式C代码的专用模式识别库

Benefits of technology

(1)自动化率提升:传统人工逆向建模需320人时/万行代码,本发明通过CPG自动分析与模式识别,将人工介入降至验证环节,整体效率提升约85%以上。

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122924835A_ABST
    Figure CN122924835A_ABST
Patent Text Reader

Abstract

The application relates to an embedded C code reverse MBD modeling method and system based on a code attribute graph and a multi-agent large language model, which comprises the following steps: constructing a code attribute graph of embedded C source code; performing pattern recognition on the code attribute graph by using an embedded code pattern recognition library; inputting the pattern recognition result and the original C source code into a first LLM verification agent together, performing a preset verification task based on a preset verification Prompt template and a structured JSON Schema constraint; performing judgment analysis on the verification recognition result and generating a model description file; packaging the model description file and a preset UML modeling specification template into an LLM modeling engine to generate a UML model file corresponding to the description file; performing three-way consistency comparison among the original C source code, the pattern recognition intermediate result and the UML model file; and uniformly packaging the verified model asset and reverse source metadata and storing them in an MBD model knowledge base.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the fields of computer software engineering, embedded system development, and artificial intelligence-assisted software engineering, and in particular to an embedded C code reverse MBD modeling method and system based on code attribute graphs and multi-agent large language models. Background Technology

[0002] Model-based development (MBD) is currently the mainstream software development paradigm in the aerospace, automotive electronics, and industrial control fields. Represented by MathWorks' Simulink / Stateflow platform, MBD defines system behavior through graphical models and automatically generates embedded C code compliant with standards such as MISRA C and AUTOSAR using toolchains like Embedded Coder. This forward development process has been widely adopted in high-security-level projects (such as DO-178C and ISO 26262 ASIL-D).

[0003] In the field of code reverse engineering, existing technologies can be mainly divided into the following three categories: (1) General UML reverse engineering tools: Tools such as Altova UModel, Sparx Systems EnterpriseArchitect, and Visual Paradigm support the reverse engineering of UML class diagrams, sequence diagrams, and component diagrams from Java, C#, and C++ source code. Some tools support class diagram reverse engineering of C code, but cannot identify embedded control logic (such as state machines, PID, interrupt services, etc.). The generated models only remain at the code structure level and cannot be directly used for MBD control algorithm development.

[0004] (2) Code Attribute Graph (CPG) analysis tools: Represented by the Joern platform, CPG has made significant progress in the field of software vulnerability detection (such as VDCPG, CSPG, etc.) in recent years by integrating Abstract Syntax Tree (AST), Control Flow Graph (CFG), Data Dependency Graph (DDG), and Call Graph (CG). However, existing CPG research focuses on security defect localization and taint analysis, and has significant technical biases. Those skilled in the art have long been limited by the inertia of thinking in this field and have failed to realize the unique value of the control flow and data flow semantics contained in CPG for the identification of embedded control patterns (state machines, PID, digital filtering, etc.).

[0005] (3) LLM-assisted code understanding tools: Large language models such as GPT-4, Claude, and DeepSeek-Coder have performed well in tasks such as code generation and vulnerability repair. Some experimental studies have explored the ability of LLM to generate UML state machine diagrams from natural language. However, existing technologies lack a systematic method for embedding LLM into the closed-loop workflow of 'code analysis → pattern recognition → model verification → model correction', and in particular, lack a mechanism for an independent LLM verification agent to perform three-way consistency comparison and automatic correction of the modeling results.

[0006] In summary, the existing technology has the following key shortcomings, some of which stem from long-standing technological biases: First, the technological bias: CPG = vulnerability detection tool. Since its inception, CPG tools like Joern have been positioned as vulnerability detection platforms, leading to a ingrained perception among those skilled in the art that 'CPG is only used for security analysis.' This invention breaks through this technological bias, for the first time migrating CPG to the field of MBD modeling, discovering the unique value of CPG in control semantic extraction (the fusion of control flow and data flow is crucial for the identification of patterns such as state machines and PIDs). Experimental data shows that the recall rate for embedded state machine identification using only AST is 62.3%, while the recall rate increases to 94.2% after using fused CPG, demonstrating the non-obviousness of this technological migration.

[0007] Second, there is a lack of dedicated pattern recognition libraries for embedded C code. Existing reverse engineering tools cannot recognize embedded-specific patterns such as state machines, PID controllers, digital filters, watchdog timers, interrupt services, lookup table interpolation, and redundant voting. As a result, the generated models only remain at the code structure level and cannot extract MBD model elements with engineering semantics.

[0008] Third, there is a lack of automated verification and closed-loop correction mechanisms. Existing reverse engineering relies on manual verification, which cannot guarantee semantic consistency from code to model conversion. Errors propagated to subsequent MBD development stages will incur high correction costs.

[0009] Fourth, there is a lack of a practical knowledge accumulation system. Existing technologies have not established a standardized model description file system (module logic description, top-level architecture description, interface relationships, data dictionary, scheduling design), which makes it impossible to directly integrate the reverse-generated model into the MBD toolchain. Summary of the Invention

[0010] The purpose of this invention is to propose an embedded C code reverse MBD modeling method and system based on code attribute graphs and multi-agent large language models, in order to solve the following technical problems: (1) How to overcome the technical bias that 'CPG is only used for vulnerability detection' and transfer CPG technology to the field of MBD modeling to achieve automated semantic analysis and pattern recognition of a large amount of legacy embedded C code; (2) How to establish a dedicated pattern recognition library for the embedded field to accurately identify typical patterns such as state machines, PID, digital filtering, watchdog, interrupt service, lookup table interpolation, and redundant voting; (3) How to use large language models to perform automated semantic verification of pattern recognition results, replace traditional manual verification, and ensure the repeatability and structured output of verification results; (4) How to generate standardized MBD model description files based on the verified pattern recognition results, and automatically drive LLM to generate standardized UML / Simulink / Stateflow models; (5) How to establish an independent LLM verification agent to perform a three-way consistency comparison of the original C source code, the intermediate results of pattern recognition, and the generated UML model, and automatically generate executable modification suggestions in JSON Patch format when there is inconsistency, driving closed-loop correction until the three are consistent.

[0011] To achieve the above objectives, the present invention provides the following solution: An embedded C code reverse MBD modeling method based on code attribute graphs and multi-agent large language models includes: Static analysis of embedded C source code to construct code property graph; Using a pre-built embedded code pattern recognition library, pattern recognition is performed on the code attribute graph to obtain the pattern recognition results; The pattern recognition result and the original C source code fragment are input into the first LLM verification agent. Based on the preset verification Prompt template and structured JSON Schema constraints, the preset verification task is executed to obtain the verification recognition result. The verification and identification results are analyzed and a model description file is generated; each type of file includes a reverse tracing field. The model description file and the pre-set UML modeling specification template are packaged and input into the LLM modeling engine to generate the UML model file corresponding to the description file; Deploy a second LLM verification agent independently to perform a three-way consistency comparison between the original C source code, intermediate pattern recognition results, and UML model files; Verified model assets and reverse-source metadata are packaged together and stored in the MBD model knowledge base.

[0012] Optionally, static analysis is performed on the embedded C source code to construct a code property graph, including: By providing standardized API extension interfaces and connecting to third-party static analysis tools, lexical analysis, syntax analysis, control flow analysis, data flow analysis, and call relationship analysis are performed on embedded C source code. Intermediate analysis results are output, and secondary fusion and embedded semantic enhancement are performed on the intermediate analysis results. Embedded-specific feature tags are added during the fusion process to construct the code attribute graph. The intermediate analysis results include: standard abstract syntax tree, control flow graph, data dependency graph, and call graph.

[0013] Optionally, the embedded specific feature marker Conditional compilation edge marking: For the numerous conditional compilation instructions in embedded code, conditional compilation edges are constructed in the code property graph to mark code branches under different hardware variants; Interrupt vector call edge marking: For the registration and call relationship of interrupt service routines, a dedicated call edge is constructed from the interrupt vector table node to the ISR function node, and the interrupt priority and interrupt number are marked; Register access node marking: For hardware register access, a register access node is constructed to mark the register address, bitmask, and read / write direction, which is used to identify the hardware-related state machine and watchdog timeout protection logic.

[0014] Optionally, the embedded code pattern recognition library includes nine categories of pattern recognition modules, each of which contains CPG graph traversal query statements, feature extractors, parameter mapping rules, and confidence evaluation mechanisms; The pattern recognition module includes: State machine model recognition module: Identifies finite state machines and hierarchical state machines based on state pattern features; Condition guard model identification module: Identifies state transition guard conditions based on Boolean expressions or condition variables; Callback scheduling model identification module: Identifies function pointer registry, callback function array, event-handler mapping table, and priority- or time-slice-based scheduling logic; PID model identification module: Identifies the discrete implementation of the proportional-integral-derivative control algorithm; Digital filter model recognition module: Recognizes typical digital filters; Watchdog timeout protection model identification module: Identifies watchdog timer initialization, watchdog feeding operation, timeout callback function, and system reset / safe state transition logic after watchdog timeout; Interrupt service model identification module: Identifies interrupt vector table registration, interrupt service function entry / exit points, interrupt priority configuration, and interrupt enable / disable logic; Table lookup and linear interpolation model identification module: Identifies one-dimensional / two-dimensional lookup table data structures, linear interpolation calculations, boundary condition handling, and table data indexing methods; Redundant voting model identification module: Identifies redundant voting logic, including input acquisition, voting calculation, fault channel marking, and safe output logic.

[0015] Optionally, performing a preset verification task includes: Verify the Prompt template structure; the Prompt template structure includes: system role definition section, task description section, input data section, output format constraint section, and few sample example section; The inference parameters that control the first LLM verification agent include: LLM temperature coefficient, Top-p sampling, maximum number of output tokens, number of times the same verification task is executed repeatedly, and result consistency threshold. The parser is used to perform schema validation on the JSON output by the first LLM validation agent.

[0016] Optionally, the model description file includes: Module logic description file: organized in YAML 1.2 format, with each identification pattern corresponding to a module entry; reverse tracing fields include: original source code file path, source code start and end line numbers, list of associated CPG node IDs, source code version Git commit hash, and identification confidence level; The top-level code architecture framework description file describes the module hierarchy, inter-module call relationships, and data dependencies; the reverse tracing fields include: a summary of the adjacency list of the CPG subgraph corresponding to the module; Interface relationship file: defines the ports, interfaces, data elements, and operation prototypes of each module; reverse tracing fields include: original C function signature and original variable name; Data dictionary file: summarizes all symbol information; reverse tracing fields include: source file path, source code line number, and scope; Scheduling design document: defines execution cycle, priority, and triggering conditions; reverse tracing fields include: original RTOS task name and original timer cycle.

[0017] Optionally, the pre-built UML modeling specification templates include: Simulink module template, Stateflow state diagram template, and SysML module definition diagram template.

[0018] Optionally, generating a three-way consistency comparison between UML models includes: If inconsistencies are found during the comparison, the second LLM verification agent generates a difference analysis report and generates modification suggestions in JSON Patch format; Modification suggestions are automatically sent back to the model description file generation stage or the LLM modeling engine stage via message queue or REST API callback; The revised model re-enters the three-party consistency comparison verification, forming a closed loop.

[0019] An embedded C code reverse MBD modeling system based on code attribute graphs and multi-agent large language models is used to implement the above-described method. The system includes: The CPG build module is used for static analysis of embedded C source code and to build a code property graph. The pattern recognition engine subsystem is used to perform pattern recognition on the code attribute graph using a pre-built embedded code pattern recognition library and obtain the pattern recognition result; The first LLM verification agent subsystem is used to input the pattern recognition result and the original C source code fragment into the first LLM verification agent, and execute a preset verification task based on the preset verification Prompt template and structured JSON Schema constraints to obtain the verification recognition result; A model description file generator is used to analyze and determine the verification and identification results and generate model description files; wherein, each type of file includes a reverse tracing field; The LLM modeling engine subsystem is used to package the model description file and the pre-set UML modeling specification template into the LLM modeling engine to generate the UML model file corresponding to the description file. The second LLM verification agent subsystem is used to independently deploy the second LLM verification agent and perform a three-way consistency comparison between the original C source code, pattern recognition intermediate results, and UML model files. The MBD model knowledge base management module is used to package verified model assets and reverse traceability metadata into the MBD model knowledge base.

[0020] A computer-readable storage medium storing a computer program that, when executed, implements an embedded C code reverse MBD modeling method based on code attribute graphs and a multi-agent large language model.

[0021] The beneficial effects of this invention are as follows: (1) Increased automation rate: Traditional manual reverse modeling requires 320 person-hours / 10,000 lines of code. This invention reduces manual intervention to the verification stage through CPG automatic analysis and pattern recognition, improving overall efficiency by more than 85%.

[0022] (2) Improved recognition accuracy: Through a dedicated embedded pattern recognition library, the recall rate of state machine recognition reaches 94.2%, the accuracy rate of PID model recognition reaches 97.5%, and the F1 score of digital filter model recognition reaches 0.93, which is significantly better than the 30%-50% pattern recognition rate of general reverse engineering tools.

[0023] (3) Reduced verification cost: The LLM dual verification layer (first verification layer + three-party comparison closed loop) replaces the traditional manual line-by-line verification, reducing the verification cost by about 78%, and increasing the verification coverage from about 35% of manual sampling to 100% full comparison.

[0024] (4) Model quality consistency: Through a three-party closed-loop correction mechanism, the generated MBD model is ensured to be consistent with the original C source code in terms of semantics, structure and interface. The first-time pass rate of the model has increased from about 62% for manual modeling to more than 91%.

[0025] (5) Knowledge asset reuse: Historical code assets are transformed into MBD reusable models through a standardized warehousing process. The model reuse rate in new projects can reach 40%-60%, significantly shortening the MBD project startup cycle.

[0026] (6) Compliance assurance: The generated model description file is compatible with AUTOSAR, OSEK, and MISRA C standards and can be directly used for airworthiness / certification document traceability for high-safety-level projects. Attached Figure Description

[0027] To more clearly illustrate the technical solutions in the embodiments of the present invention or the prior art, the drawings used in the embodiments will be briefly introduced below. Obviously, the drawings described below are only some embodiments of the present invention. For those skilled in the art, other drawings can be obtained based on these drawings without creative effort.

[0028] Figure 1 This is a schematic diagram of the process of an embedded C code reverse MBD modeling method based on code attribute graph and multi-agent large language model according to an embodiment of the present invention; Figure 2 This is a flowchart of CPG code attribute graph analysis according to an embodiment of the present invention; Figure 3 This is a flowchart of the three-way comparison closed-loop correction process according to an embodiment of the present invention; Figure 4 This is a schematic diagram of the reverse modeling of the state machine in an embodiment of the present invention. Detailed Implementation

[0029] The technical solutions of the embodiments of the present invention will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some embodiments of the present invention, and not all embodiments. Based on the embodiments of the present invention, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of the present invention.

[0030] To make the above-mentioned objects, features and advantages of the present invention more apparent and understandable, the present invention will be further described in detail below with reference to the accompanying drawings and specific embodiments.

[0031] like Figure 1 As shown, this embodiment proposes an embedded C code reverse MBD modeling method based on code attribute graphs and multi-agent large language models, including: Step 1: Perform static analysis on the embedded C source code and construct a code attribute graph; Step 2: Using a pre-built embedded code pattern recognition library, perform pattern recognition on the code attribute graph and obtain the pattern recognition results; Step 3: Input the pattern recognition result and the original C source code fragment into the first LLM verification agent, and execute the preset verification task based on the preset verification Prompt template and structured JSON Schema constraints to obtain the verification recognition result; Step 4: Analyze and determine the verification and identification results and generate model description files; each type of file includes a reverse tracing field; Step 5: Package the model description file and the pre-set UML modeling specification template and input them into the LLM modeling engine to generate the UML model file corresponding to the description file; Step Six: Independently deploy the second LLM verification agent and perform a three-way consistency comparison between the original C source code, intermediate pattern recognition results, and UML model files; Step 7: The verified model assets and reverse traceability metadata are packaged together and stored in the MBD model knowledge base.

[0032] Specifically, in this embodiment, step one: static code analysis and CPG construction, as follows: Figure 2 As shown. By providing standardized API extension interfaces, third-party static analysis tools (including but not limited to Joern, CodeQL, Clang StaticAnalyzer, Infer, etc.) are integrated to perform lexical analysis, syntax analysis, control flow analysis, data flow analysis, and call relationship analysis on embedded C source code, and to construct a code attribute graph (CPG) that integrates AST, CFG, DDG, and CG.

[0033] After receiving the embedded C source code, the third-party static analysis tool outputs intermediate analysis results such as the Standard Abstract Syntax Tree (AST), Control Flow Graph (CFG), Data Dependency Graph (DDG), and Call Graph (CG). The CPG construction module in this embodiment performs secondary fusion and embedded semantic enhancement on these intermediate results, adding the following three types of embedded-specific feature markers unique to this embodiment during the graph fusion process: a) Conditional compilation edge (COND_COMP): Marks hardware variant branches such as #ifdef; b) Interrupt Vector Call Edge (INT_VEC): Marks the call relationship and priority between the interrupt vector table and ISR functions; c) Register Access Node: Marks the register address, bitmask, and read / write direction.

[0034] The enhanced graph structure described above is stored in a graph database to form the enhanced code attribute graph (CPG) of this invention. Its node type and edge type set are significantly different from the native output result of a third-party tool (not the native CPG graph directly given by the tool).

[0035] The key difference between this embodiment and existing vulnerability detection CPGs lies in the addition of embedded, proprietary feature markers during the CPG construction process. (a) Conditional Compilation Edge Marking: For the numerous conditional compilation directives such as #ifdef HARDWARE_VARIANT_A in embedded code, conditional compilation edges are constructed in CPG to mark code branches under different hardware variants, ensuring that subsequent pattern recognition covers all hardware variant paths; (b) Interrupt Vector Call Edge Marking: For the registration and calling relationship of Interrupt Service Routine (ISR), a dedicated call edge (Interrupt Vector Call Edge) is constructed from the interrupt vector table node to the ISR function node, and the interrupt priority and interrupt number (irqNumber) are marked. (c) Register Access Node Marking: For hardware register access (such as pointer dereferencing of REG_BASE_ADDR + OFFSET), a Register Access Node is constructed, marking the register address, bitmask, and read / write direction (R / W / RW) to identify hardware-related state machines and watchdog timeout protection logic.

[0036] CPG is stored in the form of a graph database. Node types include Method, Literal, Identifier, Call, ControlStructure, LocalVariable, RegisterAccess, etc., and edge types include AST, CFG, CDG, DDG, CALL, COND_COMP, INT_VEC, etc.

[0037] In this embodiment, in the CPG fusion stage, in addition to the standard AST / CFG / DDG / CG edges, three types of embedded-specific edges are added: COND_COMP (conditional compilation edge), INT_VEC (interrupt vector call edge), and REG_ACCESS (register access edge).

[0038] Step Two: Embedded Code Pattern Recognition. An embedded code pattern recognition library will be established, containing nine categories of pattern recognition modules. Each module includes CPG graph traversal query statements (Gremlin / Cypher), feature extractors, parameter mapping rules, and confidence evaluation mechanisms. (1) State Machine Model Identification Module: Identifies Finite State Machines (FSM) and Hierarchical State Machines (HSM) based on state pattern features. CPG Traversal Query Example (Gremlin): gV().has('type','CONTROL_STRUCTURE').has('code',containing('switch')).out('AST').has('type','IDENTIFIER').as('stateVar').select('stateVar').in('DDG').has('type','LOCAL_VARIABLE').has('code',containing('enum')).dedup()... This query locates the control variables of the switch statement and traces their data dependencies to the enumeration type definition, thereby confirming the state variables.

[0039] (2) Condition Guard Model Identification Module: Identifies state transition guard conditions based on Boolean expressions or condition variables.

[0040] (3) Callback scheduling model identification module: Identifies the function pointer registry, callback function array, event-handler mapping table and scheduling logic based on priority or time slice.

[0041] (4) PID model identification module: Identifies the discrete implementation of the proportional-integral-derivative (PID) control algorithm. CPG traversal query example: gV().has('type','METHOD').has('name','*PID*').out('AST').has('type','CALL').has('code',containing('err or')).as('err').select('err').in('DDG').has('type','LOCAL_VARIABLE').has('code',containing('sum')).as('sum').sele ct('sum').in('DDG').has('type','LOCAL_VARIABLE').has('code',containing('delta')).as('delta').select('delta').in(' DDG').has('type','LOCAL_VARIABLE').has('code',containing('output')).as('out').select('out').values('lineNumber'). This query chain locates the error, integral term, derivative term, and output variable in the PID calculation function and extracts its source code line numbers.

[0042] (5) Digital filter model identification module: Identifies typical digital filter implementations such as first-order low-pass / high-pass filtering, second-order Butterworth / Chebyshev filtering, moving average filtering, and Kalman filtering.

[0043] (6) Watchdog timeout protection model identification module: Identifies watchdog timer initialization, watchdog feeding operation, timeout callback function and system reset / safe state transfer logic after watchdog timeout.

[0044] (7) Interrupt Service Model Identification Module: Identifies interrupt vector table registration, interrupt service function (ISR) entry / exit, interrupt priority configuration, and interrupt enable / mask logic.

[0045] (8) Lookup table and linear interpolation model identification module: Identify one-dimensional / two-dimensional lookup table (LUT) data structure, linear interpolation calculation, boundary condition processing and table data indexing method.

[0046] (9) Redundant voting model identification module: Identifies redundant voting logic such as 2oo3 (two out of three) and 3oo5 (three out of five), including input acquisition, voting calculation, fault channel marking and safe output logic.

[0047] Pattern recognition confidence assessment mechanism: The overall confidence score is calculated by weighted fusion of node coverage, edge coverage, and parameter matching rate: confidence = 0.4 * node coverage + 0.3 * edge coverage + 0.3 * param_match_rate. A confidence score >= 0.85 indicates successful recognition; otherwise, it is marked as low confidence and awaits manual review.

[0048] The JSON Schema definition, Gremlin / Cypher query examples, and feature extraction rules (regular expressions / CPG traversal paths) for each pattern module are all stored in a structured file in the pattern recognition library, which facilitates expansion and version management.

[0049] Step 3: LLM First Validation Layer. The pattern recognition result (JSON format) and the original C source code snippet (extracted by looking up the line number from the CPG node ID) are input into the first LLM validation agent. Based on a pre-defined validation prompt template and structured JSON Schema constraints, this agent performs the following validation tasks: (a) Verify the Prompt template structure: System role definition section: 'You are an embedded software and MBD modeling expert, responsible for verifying the correctness of code pattern recognition results. Please rigorously compare the following pattern recognition JSON with the original source code, checking semantic consistency, boundary condition integrity, and parameter accuracy.'; Task description section: 'Please determine whether the following pattern recognition results correctly describe the control logic in the source code. If you find any omissions, errors, or redundant recognitions, please indicate the specific locations and provide suggestions for correction.' Input data segment: Pattern recognition JSON + source code snippet (with line numbers) + CPG subgraph (in DOT format or adjacency list format); Output format constraints: 'Please output in JSON format, which must include the following fields: verificationResult (enumeration values: PASS / FAIL / UNCERTAIN), issues (array, each element containing type: MISSING / ERROR / EXTRA, location: line number, description: issue description, suggestedFix: suggested fix), confidenceScore (0.00~1.00, two decimal places).'; Few-sample example section: Provide 2-3 labeled Prompt-Response examples to ensure that the LLM understands the output format.

[0050] (b) LLM Inference Parameter Control: To ensure the repeatability and determinism of the verification results, the LLM temperature coefficient is set below 0.2 (preferably 0.1), the Top-p sampling limit is top_p=0.9, the maximum number of output tokens is max_tokens=4096, and JSON mode output is forcibly enabled (response_format={"type": "json_object"}). The same verification task is executed 10 times, and the consistency of the results must be higher than 98%; otherwise, a downgrade to rule engine verification is triggered.

[0051] (c) Confidence filtering: The parser performs schema validation on the JSON output by LLM. It is determined to pass the validation only if confidenceScore>= 0.90 and verificationResult == PASS; otherwise, the correction process is triggered.

[0052] If the verification fails, the suggestedFix generated by the LLM agent is automatically converted into parameter adjustment instructions for the pattern recognition library (such as modifying the regular expression threshold, supplementing the traversal depth, and adding candidate nodes), and then sent back to the pattern recognition stage for automatic correction. The maximum number of correction iterations is 5.

[0053] The Prompt template is stored in Jinja2 format and supports variable interpolation ({{pattern_json}}, {{source_snippet}}, {{cpg_dot}}), which facilitates reuse and version control. LLM output is formatted using a JSON Schema validator (such as the python-jsonschema library), and retries are triggered when fields are missing or have incorrect types. When the LLM service is unavailable, it automatically degrades to rule engine validation (a set of validation rules based on regular expressions and template matching) to ensure the feasibility of the technical solution.

[0054] Step Four: Model Description File Generation. Based on the pattern recognition results that pass the first verification layer, five types of standardized model description files are automatically generated. Each type of file contains reverse tracing fields: (1) Module logic description file (.mld): Organized in YAML 1.2 format, each identification pattern corresponds to a module entry. Reverse tracing fields include: sourceFile (original source file path), lineNumberStart / lineNumberEnd (source code start and end line numbers), cpgNodeIds (list of associated CPG node IDs), gitCommitId (source code version Git commit hash), and patternConfidence (identification confidence).

[0055] (2) Code top-level architecture framework description file (.caf): describes the module hierarchy, inter-module call relationships and data dependencies. Reverse tracing fields include: moduleCpgSubgraph (a summary of the adjacency list of the CPG subgraph corresponding to the module).

[0056] (3) Interface relationship file (.irf): Defines the Port, Interface, DataElement, and Operation prototypes for each module. Reverse tracing fields include: sourceFunctionSignature (original C function signature) and sourceVariableName (original variable name). Among them, Port is: port (or "software component port"), defined as the connection point for interaction between the module (software component) and external or other modules, divided into P-Port (providing port) and R-Port (requirement port), used to attach Interface. Interface is: interface, defined as the communication contract specification followed by the port, including two types: Sender-Receiver Interface and Client-Server Interface. DataElement is data element, defined as: the smallest data unit transmitted in the interface, carrying attributes such as name, data type, dimension, and initial value, corresponding to variables or signals in the C source code. Operation is operation prototype (or "service operation"), a callable service primitive defined in the Client-Server Interface, containing operation name, parameter list, and return value type, corresponding to function prototypes in the C source code.

[0057] (4) Data dictionary file (.ddf): Summarizes all symbol information. Reverse tracing fields include: sourceFile, lineNumber, and scope (GLOBAL / LOCAL / MODULE). Among them, sourceFile is the source file path (or "source code file path"), defined as: the absolute or relative path of the original C source code, such as src / heater_ctrl.c. lineNumber is: the source code line number, defined as: the position of the symbol or pattern in the source code, which can be further divided into lineNumberStart (starting line number) and lineNumberEnd (ending line number). scope is: the scope, defined as: the visible range of the symbol, with enumerated values ​​of: GLOBAL (global scope), LOCAL (local scope / within function), and MODULE (module-level scope / static within file).

[0058] (5) Scheduling design file (.sdf): Defines the execution cycle, priority, and triggering conditions. The reverse tracing fields include: sourceTaskName (original RTOS task name) and sourceTimerPeriodMs (original timer period).

[0059] The above five types of files are compatible with AUTOSAR software component (SWC) description files and AADL thread / process descriptions, but the invention adds a unique reverse tracing field, forming a complete traceable link from code to model.

[0060] YAML files are serialized using the PyYAML library, ensuring UTF-8 encoding and cross-platform compatibility. Reverse tracing fields are named in YAML with the prefix `meta_cpgsource` for easy subsequent retrieval.

[0061] Step 5: LLM UML Modeling Engine. Package the model description file and the pre-built UML modeling specification templates (including Simulink module template, Stateflow state diagram template, and SysML module definition diagram template) and input them into the LLM modeling engine.

[0062] The output of Step 5 (LLM UML Modeling Engine) is: UML model files (i.e., executable MBD model files). Specifically, this includes: Simulink module diagrams (.slx / .mdl), Stateflow state diagrams, and SysML module definition diagrams.

[0063] Step Six: LLM Three-Way Consistency Verification Agent. A second LLM verification agent is independently deployed to perform a three-way consistency comparison between the original C source code, intermediate pattern recognition results, and the generated UML model. Figure 3 As shown.

[0064] The UML model file generated in Step 5 serves as one of the inputs to Step 6, and together with the original C source code and intermediate pattern recognition results, it undergoes a three-way comparison and verification process in Step 6. Closed-loop correction—If Step 6 detects inconsistencies, the second LLM verification agent automatically generates modification suggestions in JSON Patch format, which are then sent back to Step 5 (LLM modeling engine) or Step 4 via a message queue (RabbitMQ / Kafka) or REST API, driving the model to be regenerated / corrected. Iterative relationship—The corrected model re-enters Step 6 for verification, forming a closed loop of "modeling → comparison → correction → re-verification," with a configurable maximum number of iterations.

[0065] Specifically, in step six, if inconsistencies are found during the comparison, the agent generates a difference analysis report (Diff Report) and provides modification suggestions in JSON Patch format: The suggested JSON patch format is: {"op": "add / remove / replace", "path": " / modules / 0 / parameters / 2 / value", "value": 2.5, "reason": "PID Kp parameter is missing in the model, defined as 2.5 on line 156 of the source code"}.

[0066] Modification suggestions are automatically sent back to the model description file generator (Step 4) or LLM modeling engine (Step 5) via message queues (such as RabbitMQ / Kafka) or REST API callbacks. The corrected model re-enters Step 6 for verification, forming a closed loop. The maximum number of iterations is set to 10. If inconsistency is still not achieved after exceeding this limit, it is marked as a manual intervention anomaly, and a complete difference log is output.

[0067] The specific implementation of closed-loop correction: (1) Root cause localization: A bidirectional index is established from CPG node → pattern recognition result → model description file → UML model element through traceability ID, and the accuracy of difference localization reaches the element level; (2) JSON Patch Generation: Generate JSON Patch based on RFC 6902 standard, and verify the validity of the Patch using the jsonpatch-python library; (3) Automatic feedback: The message queue uses RabbitMQ, the Topic format is model.correct.{module_id}, and the consumer is the model description file generator or LLM modeling engine; (4) Retry and circuit breaker: The exponential backoff retry strategy is adopted (initial interval 1s, maximum interval 60s, maximum retry 10 times). Manual intervention alarm is triggered after the threshold is exceeded.

[0068] Step 7: MBD Model Knowledge Base Storage. Verified model assets and reverse-source metadata are packaged together and stored in the MBD model knowledge base. The state machine reverse modeling illustration in this embodiment is shown below. Figure 4 As shown.

[0069] This embodiment also proposes an embedded C code reverse MBD modeling system based on code attribute graphs and multi-agent large language models, including: a CPG construction module (containing conditional compilation edges, interrupt vector call edges, and register access node markers), a pattern recognition engine (containing nine pattern modules and a confidence evaluator), a first LLM verification agent (containing Jinja2 templates, a JSON Schema validator, and a rule engine degradation module), a model description file generator (outputting five types of files containing reverse tracing fields), an LLM modeling engine, a second LLM verification agent (containing a three-party comparison engine, a JSON Patch generator, and a RabbitMQ message queue feedback module), and an MBD model knowledge base management module.

[0070] The system in this embodiment specifically includes: The CPG build module is used for static analysis of embedded C source code and to build a code property graph. The pattern recognition engine subsystem is used to perform pattern recognition on the code attribute graph using a pre-built embedded code pattern recognition library and obtain the pattern recognition result; The first LLM verification agent subsystem is used to input the pattern recognition result and the original C source code fragment into the first LLM verification agent, and execute a preset verification task based on the preset verification Prompt template and structured JSON Schema constraints to obtain the verification recognition result; A model description file generator is used to analyze and determine the verification and identification results and generate model description files; wherein, each type of file includes a reverse tracing field; The LLM modeling engine subsystem is used to package the model description file and the pre-set UML modeling specification template into the LLM modeling engine to generate the UML model file corresponding to the description file. The second LLM verification agent subsystem is used to independently deploy the second LLM verification agent and perform a three-way consistency comparison between the original C source code, pattern recognition intermediate results, and UML model files. The MBD model knowledge base management module is used to package verified model assets and reverse traceability metadata into the MBD model knowledge base.

[0071] The following is a concrete implementation case that can be put into practice to prove the authenticity and feasibility of this technical solution.

[0072] Implementation Case Background: The implementation case study selects the battery heater control module in a certain type of satellite energy management system (EMS). The original C code of this module is about 1,200 lines long, containing a three-state mode state machine (IDLE / HEATING / SAFE) and a PID temperature control loop, running on a spaceborne computer with SPARC V8 architecture (RTOS is VxWorks 6.9).

[0073] Implementation steps: Step A: CPG Construction. Import the source code via the Joern API and perform fuzzy parsing. The generated CPG contains: 42 Method nodes, 18 ControlStructure nodes, 67 Call nodes, 124 LocalVariable nodes, 15 RegisterAccess nodes, and 3 InterruptVector nodes. The CPG is stored in the Neo4j graph database, occupying approximately 8.5MB of storage space.

[0074] Step B: Pattern recognition.

[0075] (a) State machine identification: Locate the state machine control structure through Gremlin query. Identify the state variable g_heaterState (enumeration type: HEATER_IDLE=0, HEATER_HEATING=1, HEATER_SAFE=2). Extract state transitions: IDLE→HEATING (trigger condition: temp<LOW_THRESHOLD&&cmd == HEAT_CMD_ON, guard: batterySoC>0.3), HEATING→SAFE (trigger condition: temp>HIGH_THRESHOLD, guard: timeout>300s), SAFE→IDLE (trigger condition: cmd == HEAT_CMD_OFF, no guard). Identify entry actions: call HeaterPID_Init() in the HEATING state; call Heater_Disable() and CanTx_SendAlarm(ALARM_HEATER_OVERTEMP) in the SAFE state. Identification confidence: node_coverage=0.96, edge_coverage=0.91, param_match_rate=0.95, overall confidence=0.94.

[0076] (b) PID identification: Locate the function HeaterPID_Calculate(). Extract parameters: Kp=2.5, Ki=0.15, Kd=0.8, DT=0.1s. Identify anti-integral saturation logic: sum_error is limited to ±100.0. Identify output limiting: 0~255.0. Identification confidence: node_coverage=0.98, edge_coverage=0.97, param_match_rate=0.97, overall confidence=0.97.

[0077] (c) Watchdog identification: Locate the function Heater_WatchdogFeed(), identify the watchdog handle wdgHandle, timeout period WATCHDOG_TIMEOUT_MS=5000ms, and timeout callback function Heater_WatchdogCallback(). Identification confidence: 0.96.

[0078] Step C: LLM First Validation. Input the above recognition results (JSON) and the original source code snippet (approximately 80 lines) into the GPT-4o model (temperature=0.1, top_p=0.9, max_tokens=4096, response_format forced to JSON). The validation prompt includes system roles, task description, input data, output format constraints, and 3 Few-shot examples. LLM returns the validation result: PASS, confidenceScore=0.97, no correction suggestions. The same task was repeated 10 times, with 100% consistency.

[0079] Step D: Model Description File Generation. Five types of files are generated, all containing reverse tracing fields. For example, BatteryHeaterControl.mld contains: meta_cpgsource.sourceFile='src / heater_ctrl.c', meta_cpgsource.lineNumberStart=45, meta_cpgsource.lineNumberEnd=189, meta_cpgsource.cpgNodeIds=[1245,1246,...,1389], meta_cpgsource.gitCommitId='a3f7d2e', meta_cpgsource.patternConfidence=0.94.

[0080] Step E: LLM UML Modeling. Package the model description file and the Simulink / Stateflow template and input them into the LLM modeling engine. Generate the Simulink model file BatteryHeater.slx.

[0081] Step F: Three-way comparison and verification. Generate 100 test cases (BVA+ECP) to drive the C source code compilation and execution (GCC for SPARC+VxWorks simulator) and Simulink SIL simulation respectively. Comparison results: Output sequence consistency rate 99.7% (tolerance 1e-4), structural consistency 100%, interface consistency 100%. The three-way comparison passed, no correction is required.

[0082] Step G: Knowledge Base Storage. The model asset package is stored in the MBD knowledge base, with the asset ID being EMS_BAT_HEATER_2024_001.

[0083] Implementation effect verification: This implementation case took approximately 4.5 hours from source code submission to model storage. Compared to historical data on manual reverse modeling (which requires approximately 45 person-hours for a module of the same size), this represents an efficiency improvement of about 90%. The model was verified by test cases, achieving a semantic consistency of 99.7%, meeting the reuse requirements for subsequent MBD projects.

[0084] Compared with existing tools: Reverse engineering was performed on the same module using UModel, EA, and VP respectively. The results are as follows: UModel generated a class diagram containing 12 classes and 89 methods, but without state machine / PID identification; EA generated a class diagram + sequence diagram, with the sequence diagram containing 3 lifelines, but without control logic; VP generated a similar result to UModel. None of the three can directly generate a usable MBD model, requiring manual processing of approximately 38-42 person-hours. This invention directly generates an executable Simulink model, eliminating the need for manual processing.

[0085] To demonstrate the deficiencies of existing technologies, a comparative experiment was conducted. The same satellite energy management system module (approximately 1,200 lines of C code) was selected, and reverse modeling was performed using Altova UModel 2024, Enterprise Architect 17, VisualParadigm 17.1, and the method of this invention, respectively. The comparison results are shown in Table 1. Table 1. Quantitative Comparison of the Invention with Existing General Reverse Engineering Tools Note: The comparative experiments were performed under the same hardware environment (Intel i9-13900K, 64GB RAM). The reverse engineering results of UModel / EA / VP need to be manually processed before they can be used for MBD.

[0086] This embodiment demonstrates a cross-domain migration method for Code Attribute Graph (CPG) that overcomes technological biases. For the first time, CPG technology is migrated from the field of software vulnerability detection to the field of MBD model reverse engineering. By adding three types of embedded-specific features—conditional compilation edges (COND_COMP), interrupt vector call edges (INT_VEC), and register access nodes (RegisterAccess)—it achieves accurate characterization of embedded control semantics using CPG. Experimental data shows that compared to using only AST, the recall rate of state machine identification after integrating CPG increases from 62.3% to 94.2%.

[0087] This embodiment sets up nine categories of pattern recognition libraries for the embedded field. It innovatively establishes an embedded code pattern recognition library that includes CPG graph traversal query statements, feature extractors, parameter mapping rules, and a confidence evaluation mechanism (confidence = 0.4*node_coverage + 0.3*edge_coverage + 0.3*param_match_rate), filling the technical gap where existing general-purpose reverse engineering tools cannot recognize embedded-specific patterns.

[0088] This embodiment is based on a structured validation method for LLM using Prompt projects and JSON Schema constraints. For the first time, it introduces an LLM structured validation layer in the code-to-model reverse engineering process, based on pre-built Jinja2 templates, few-sample examples, mandatory JSON Schema validation, and temperature coefficient control (temperature < 0.2). This ensures the repeatability and determinism of validation results and supports a rule engine degradation scheme when LLM is unavailable.

[0089] This embodiment proposes an LLM-driven dual-verification closed-loop mechanism. It introduces two layers of LLM verification for the first time: the first layer verifies the semantic consistency between the pattern recognition result and the source code; the second layer uses an independent LLM agent to perform a three-way comparison of the original source code, intermediate results, and UML model. The two layers of verification achieve closed-loop correction through JSON Patch modification suggestions and an automatic message queue feedback mechanism, with a maximum of 10 iterations to ensure end-to-end consistency.

[0090] This embodiment proposes a standardized MBD model description file system that includes reverse tracing fields. It pioneers five types of model description files (.mld / .caf / .irf / .ddf / .sdf), which, while compatible with AUTOSAR / AADL standard fields, add reverse tracing fields with the meta_cpgsource prefix (sourceFile, lineNumber, cpgNodeIds, gitCommitId, patternConfidence), forming a complete traceable link from code to model.

[0091] This embodiment proposes an automated UML modeling engine based on LLM. By packaging the model description file with pre-built modeling templates and MAAB specifications and inputting them into the LLM, it achieves automatic generation from structured text description to executable model files (.slx / .mdl), and supports automatic interface connection, automatic parameter mapping, and automatic scheduling configuration.

[0092] This embodiment proposes a traceable MBD model knowledge base. It establishes a model knowledge base that supports multi-dimensional retrieval and reuse, uniformly linking and storing reverse-generated model assets with source code versions, verification reports, and pattern recognition metadata. This enables the continuous accumulation and cross-project reuse of historical code assets into MBD knowledge capital.

[0093] The embodiments described above are merely preferred embodiments of the present invention and are not intended to limit the scope of the present invention. Various modifications and improvements made to the technical solutions of the present invention by those skilled in the art without departing from the spirit of the present invention should fall within the protection scope defined by the claims of the present invention.

Claims

1. An embedded C code reverse MBD modeling method based on code attribute graphs and multi-agent large language models, characterized in that, include: Static analysis of embedded C source code to construct code property graph; Using a pre-built embedded code pattern recognition library, pattern recognition is performed on the code attribute graph to obtain the pattern recognition results; The pattern recognition result and the original C source code fragment are input into the first LLM verification agent. Based on the preset verification Prompt template and structured JSON Schema constraints, the preset verification task is executed to obtain the verification recognition result. The verification and identification results are analyzed and a model description file is generated; each type of file includes a reverse tracing field. The model description file and the preset UML modeling specification template are packaged and input into the LLM modeling engine to generate the UML model file corresponding to the description file; Deploy a second LLM verification agent independently to perform a three-way consistency comparison between the original C source code, intermediate pattern recognition results, and UML model files; Verified model assets and reverse-source metadata are packaged together and stored in the MBD model knowledge base.

2. The embedded C code reverse MBD modeling method based on code attribute graph and multi-agent large language model according to claim 1, characterized in that, Static analysis of embedded C source code, constructing a code property graph including: By providing standardized API extension interfaces and connecting to third-party static analysis tools, lexical analysis, syntax analysis, control flow analysis, data flow analysis, and call relationship analysis are performed on embedded C source code. Intermediate analysis results are output, and secondary fusion and embedded semantic enhancement are performed on the intermediate analysis results. Embedded-specific feature tags are added during the fusion process to construct the code attribute graph. The intermediate analysis results include: standard abstract syntax tree, control flow graph, data dependency graph, and call graph.

3. The embedded C code reverse MBD modeling method based on code attribute graph and multi-agent large language model according to claim 2, characterized in that, The embedded specific feature markers include: Conditional compilation edge marking: For the numerous conditional compilation instructions in embedded code, conditional compilation edges are constructed in the code property graph to mark code branches under different hardware variants; Interrupt vector call edge marking: For the registration and call relationship of interrupt service routines, a dedicated call edge is constructed from the interrupt vector table node to the ISR function node, and the interrupt priority and interrupt number are marked; Register access node marking: For hardware register access, a register access node is constructed to mark the register address, bitmask, and read / write direction, which is used to identify the hardware-related state machine and watchdog timeout protection logic.

4. The embedded C code reverse MBD modeling method based on code attribute graph and multi-agent large language model according to claim 1, characterized in that, The embedded code pattern recognition library includes nine categories of pattern recognition modules. Each module contains CPG graph traversal query statements, feature extractors, parameter mapping rules, and confidence evaluation mechanisms. The pattern recognition module includes: State machine model recognition module: Identifies finite state machines and hierarchical state machines based on state pattern features; Condition guard model identification module: Identifies state transition guard conditions based on Boolean expressions or condition variables; Callback scheduling model identification module: Identifies function pointer registry, callback function array, event-handler mapping table, and priority- or time-slice-based scheduling logic; PID model identification module: Identifies the discrete implementation of the proportional-integral-derivative control algorithm; Digital filter model recognition module: Recognizes typical digital filters; Watchdog timeout protection model identification module: Identifies watchdog timer initialization, watchdog feeding operation, timeout callback function, and system reset / safe state transition logic after watchdog timeout; Interrupt service model identification module: Identifies interrupt vector table registration, interrupt service function entry / exit points, interrupt priority configuration, and interrupt enable / disable logic; Table lookup and linear interpolation model identification module: Identifies one-dimensional / two-dimensional lookup table data structures, linear interpolation calculations, boundary condition handling, and table data indexing methods; Redundant voting model identification module: Identifies redundant voting logic, including input acquisition, voting calculation, fault channel marking, and safe output logic.

5. The embedded C code reverse MBD modeling method based on code attribute graph and multi-agent large language model according to claim 1, characterized in that, Performing the preset verification tasks includes: Verify the Prompt template structure; the Prompt template structure includes: system role definition section, task description section, input data section, output format constraint section, and few sample example section; The inference parameters that control the first LLM verification agent include: LLM temperature coefficient, Top-p sampling, maximum number of output tokens, number of times the same verification task is executed repeatedly, and result consistency threshold. The parser is used to perform schema validation on the JSON output by the first LLM validation agent.

6. The embedded C code reverse MBD modeling method based on code attribute graph and multi-agent large language model according to claim 1, characterized in that, The model description file includes: Module logic description file: organized in YAML 1.2 format, with each identification pattern corresponding to a module entry; reverse tracing fields include: original source code file path, source code start and end line numbers, list of associated CPG node IDs, source code version Git commit hash, and identification confidence level; The top-level code architecture framework description file describes the module hierarchy, inter-module call relationships, and data dependencies; the reverse tracing fields include: a summary of the adjacency list of the CPG subgraph corresponding to the module; Interface relationship file: defines the ports, interfaces, data elements, and operation prototypes of each module; reverse tracing fields include: original C function signature and original variable name; Data dictionary file: summarizes all symbol information; reverse tracing fields include: source file path, source code line number, and scope; Scheduling design document: defines execution cycle, priority, and triggering conditions; reverse tracing fields include: original RTOS task name and original timer cycle.

7. The embedded C code reverse MBD modeling method based on code attribute graph and multi-agent large language model according to claim 1, characterized in that, The pre-built UML modeling specification templates include: Simulink module template, Stateflow state diagram template, and SysML module definition diagram template.

8. The embedded C code reverse MBD modeling method based on code attribute graph and multi-agent large language model according to claim 1, characterized in that, The three-way consistency comparison between generated UML models includes: If inconsistencies are found during the comparison, the second LLM verification agent generates a difference analysis report and generates modification suggestions in JSON Patch format; Modification suggestions are automatically sent back to the model description file generation stage or the LLM modeling engine stage via message queue or REST API callback; The revised model re-enters the three-party consistency comparison verification, forming a closed loop.

9. An embedded C code reverse MBD modeling system based on code attribute graphs and multi-agent large language models, characterized in that, The system for implementing the method as described in any one of claims 1-8 includes: The CPG build module is used for static analysis of embedded C source code and to build a code property graph. The pattern recognition engine subsystem is used to perform pattern recognition on the code attribute graph using a pre-built embedded code pattern recognition library and obtain the pattern recognition result; The first LLM verification agent subsystem is used to input the pattern recognition result and the original C source code fragment into the first LLM verification agent, and execute a preset verification task based on the preset verification Prompt template and structured JSON Schema constraints to obtain the verification recognition result; A model description file generator is used to analyze and determine the verification and identification results and generate model description files; wherein, each type of file includes a reverse tracing field; The LLM modeling engine subsystem is used to package the model description file and the pre-set UML modeling specification template into the LLM modeling engine to generate the UML model file corresponding to the description file. The second LLM verification agent subsystem is used to independently deploy the second LLM verification agent and perform a three-way consistency comparison between the original C source code, pattern recognition intermediate results, and UML model files. The MBD model knowledge base management module is used to package verified model assets and reverse traceability metadata into the MBD model knowledge base.

10. A computer-readable storage medium, characterized in that, The computer-readable storage medium stores a computer program that, when executed, implements the method as described in any one of claims 1 to 8.