Firmware code review method and system

By acquiring and parsing hardware-related metadata in the firmware code, generating a priority query strategy, and dynamically obtaining context information, the problem of incomplete coverage of hardware-related information in existing technologies is solved, and more accurate firmware code review is achieved.

CN123178238APending Publication Date: 2026-11-27SHANGHAI EVEX INFORMATION TECHNOLOGY CO LTD
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202611666483.8
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-10-27
Publication Date
2026-11-27

AI Technical Summary

Technical Problem

Existing firmware code review technologies, when facing scenarios with strong software-hardware coupling, suffer from insufficient coverage of key hardware-related information due to static context injection, making it impossible to accurately identify conflicts between code logic and hardware constraints, resulting in inaccurate review.

Method used

By acquiring the target data and hardware-related metadata of the firmware code to be reviewed, parsing the code element information, generating a context query strategy containing multiple query items and their priorities, executing queries on the hardware-related metadata according to priority, obtaining context information related to the target data, and combining it with the target data as input to the code review model, dynamic context acquisition is achieved.

Benefits of technology

It improves the accuracy of identifying conflicts between code logic and hardware constraints, reduces defect omissions, enhances the accuracy and reliability of firmware review, and reduces false positives and false negatives.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN123178238A_ABST
    Figure CN123178238A_ABST
Patent Text Reader

Abstract

Embodiments of the present application provide a firmware code review method and system. The method comprises: obtaining target data of a to-be-reviewed firmware code and corresponding hardware-related metadata, the hardware-related metadata comprising symbol definition information and inter-symbol relationship information related to protocol constraints of a target hardware platform; parsing the target data to obtain code element information; generating a context query strategy based on the code element information, the context query strategy comprising a plurality of query items and a priority corresponding to each query item; performing a query on the hardware-related metadata according to the priority to obtain context information related to the target data; and combining the context information and the target data as input of a code review model to obtain a code review result. The method improves the accuracy of identifying conflicts between code logic and hardware constraints, thereby improving the accuracy of firmware review.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This application relates to the field of intelligent code review technology, and in particular to a firmware code review method and system. Background Technology

[0002] With the rapid development of high-performance computing, storage devices, and IoT terminals, firmware, as a crucial bridge between hardware and upper-layer software, must adhere to the architectural specifications of specific hardware platforms while simultaneously meeting resource constraints such as memory, power consumption, and real-time performance. In such scenarios, firmware code logic is deeply coupled with hardware characteristics. Code review not only needs to detect general software defects but also verify the consistency between code logic and hardware constraints. This strong correlation between firmware code and the hardware environment places higher demands on firmware review's context awareness and domain adaptability.

[0003] Currently, existing code review technologies primarily employ a combination of static context injection and generalized large language model analysis. The process involves developers or system administrators pre-marking the code data, structure definitions, macro definitions, and other contextual information to be injected. The code data to be reviewed, along with the statically injected context, is then input into a large language model for analysis, generating a review report. To accommodate the context window limitations of large language models, some solutions use sliding windows or fixed-size block partitioning strategies to segment the code data before reviewing it block by block.

[0004] However, existing methods suffer from insufficient accuracy in reviewing hardware-software tightly coupled scenarios such as firmware, due to incomplete coverage of key hardware-related information caused by static context injection. This leads to an inability to accurately identify conflicts between code logic and hardware constraints. Summary of the Invention

[0005] The firmware code review method and system provided in this application are used to solve the problem that existing methods, when facing review scenarios with strong software and hardware coupling such as firmware, have incomplete coverage of key hardware-related information due to static context injection, and thus cannot accurately identify conflicts between code logic and hardware constraints, thereby improving the accuracy of review.

[0006] In a first aspect, embodiments of this application provide a firmware code review method, including:

[0007] Obtain the target data and corresponding hardware-related metadata of the firmware code to be reviewed. The hardware-related metadata includes symbol definition information and symbol relationship information related to the protocol constraints of the target hardware platform.

[0008] The target data is parsed to obtain code element information;

[0009] Based on code element information, a context query strategy is generated. The context query strategy includes multiple query items and the priority of each query item.

[0010] Based on priority, queries are performed on hardware-related metadata to obtain context information related to the target data;

[0011] Contextual information is combined with target data and used as input to the code review model to obtain code review results.

[0012] In one possible implementation, the target data is parsed to obtain code element information, including: identifying function boundaries in the target data to obtain a function set consisting of multiple function units; counting the number of lines of code for each function unit in the function set, identifying function units with a number of lines of code greater than a preset threshold as large functions, and identifying function units with a number of lines of code less than or equal to the preset threshold as small functions; identifying the change position of large functions, extracting the smallest enclosing scope fragment corresponding to the code change position in the large function, and combining the smallest enclosing scope fragment with the function signature and local variable declarations of the large function to obtain the code element information corresponding to the large function; and extracting whole functions from the small functions to obtain the code element information corresponding to the small functions.

[0013] In one possible implementation, a context query strategy is generated based on code element information, including: segmenting the code element information into multiple code blocks; identifying symbol references in each code block to obtain a set of symbols referenced in the code block; generating corresponding query items based on the type of each symbol in the symbol set; wherein, when the type of the symbol is a structure, macro, or type definition, a symbol definition query item is generated; when the type of the symbol is a function, a symbol relationship query item is generated; assigning priority to each query item, the priority being determined based on the reference frequency of the symbol corresponding to each query item in the code block and the degree of association between the symbol and protocol constraints; and obtaining the context query strategy based on all query items and the priority corresponding to each query item.

[0014] In one possible implementation, based on priority, queries are performed on hardware-related metadata to obtain context information related to the target data. This includes: querying hardware-related metadata according to a preset context input budget corresponding to the priority to obtain symbol information, and updating the consumed context input after each query; stopping the execution of queries for the remaining priorities when the accumulated consumed context input reaches the preset context input budget; and combining the obtained symbol information with code element information to obtain context information.

[0015] In one possible implementation, contextual information is combined with target data and used as input to a code review model to obtain code review results. This includes: dividing the contextual information into dimensional categories to obtain a syntax review context, a logic review context, and a security review context; wherein the syntax review context includes macro definitions and type definitions, the logic review context includes function call relationships and global variables, and the security review context includes pointer operations and metadata related to concurrency protection; combining the target data with the syntax review context, logic review context, and security review context respectively to obtain three sets of review input data; and inputting the three sets of review input data into the code review model for parallel review processing to obtain code review results, which include syntax review results, logic review results, and security review results.

[0016] In one possible implementation, the method further includes: normalizing each issue record in the syntax review results, logic review results, and security review results to obtain an issue fingerprint corresponding to each issue record; merging issue records with the same issue fingerprint to obtain a merged issue record; the merged issue record is marked with source dimension information and original issue details; determining the final severity level of the merged issue record based on the initial severity level corresponding to each source dimension in the merged issue record; and sorting the merged issue records after determining the final severity level according to the severity level to obtain the final review result.

[0017] In one possible implementation, the final severity level of the merged issue record is determined based on the initial severity level corresponding to each source dimension in the merged issue record. This includes: when the initial severity level corresponding to any source dimension is the highest level, the final severity level of the merged issue record is determined to be the highest level. Accordingly, the merged issue records after determining the final severity level are sorted hierarchically by severity level, and the final review result is output. This includes: arranging the merged issue records hierarchically from high to low severity level into blocking merge issues, suggested repair issues, and optional optimization issues, to obtain the final review result.

[0018] In one possible implementation, three sets of review input data are input into the code review model for parallel review processing. This includes: for multiple model calls within the same review dimension, constructing the corresponding review input data into an input message sequence, and performing structural rearrangement on the input message sequence. The structural rearrangement includes: placing the review template content corresponding to the review dimension in a first user message; placing the review context corresponding to the review dimension in the review input data, and the code fragment corresponding to the review input data in the target data, in a second user message. The first user message remains unchanged across multiple model calls within the same review dimension, allowing the inference framework corresponding to the code review model to reuse the key-value cache corresponding to the first user message. The context input size of the first user message and the second user message is less than or equal to the context window limit of the code review model.

[0019] In one possible implementation, after combining contextual information with target data as input to the code review model, the method further includes: monitoring the tool call sequence of the code review model during multiple calls, and counting the total number of tool calls and the number of deduplicated tool calls; calculating the deduplication rate based on the total number of tool calls and the number of deduplicated tool calls; and generating optimization suggestions for context query strategies and / or model call parameters based on the comparison result of the deduplication rate and a preset deduplication threshold.

[0020] Secondly, embodiments of this application provide a firmware code review system, including:

[0021] The acquisition module is used to acquire the target data and corresponding hardware-related metadata of the firmware code to be reviewed. The hardware-related metadata includes symbol definition information and symbol relationship information related to the protocol constraints of the target hardware platform.

[0022] The parsing module is used to parse the target data to obtain code element information;

[0023] The planning module is used to generate a context query strategy based on code element information. The context query strategy includes multiple query items and the priority of each query item.

[0024] The query module is used to perform queries on hardware-related metadata based on priority to obtain context information related to the target data;

[0025] The review module combines contextual information with target data as input to the code review model to obtain code review results.

[0026] The firmware code review method and system provided in this application obtain target data and corresponding hardware-related metadata of the firmware code to be reviewed, parse the target data to obtain code element information, and generate a context query strategy containing multiple query items and their priorities based on the code element information. Then, query the hardware-related metadata according to the priority to obtain context information related to the target data, and combine the context information with the target data as input to the code review model. This enables more targeted supplementation of context content related to the target hardware platform protocol constraints during the code review process, improving context integrity, thereby enhancing the code review model's ability to perceive cross-file call relationships and symbol relationships, improving the accuracy of identifying conflicts between code logic and hardware constraints, reducing defect omissions caused by missing context, and thus improving the accuracy and reliability of firmware review, reducing false positives and false negatives. Attached Figure Description

[0027] The accompanying drawings, which are incorporated in and form part of this specification, illustrate embodiments consistent with this application and, together with the description, serve to explain the principles of this application.

[0028] Figure 1 A flowchart illustrating the firmware code review method provided in this application;

[0029] Figure 2 A schematic diagram of the overall architecture of the firmware code review system provided for this application;

[0030] Figure 3 A flowchart illustrating the single-file review process in firmware code review provided in this application embodiment;

[0031] Figure 4 This is a schematic diagram illustrating the process of obtaining context information provided in an embodiment of this application.

[0032] Figure 5 A schematic diagram of the firmware code review system provided in this application;

[0033] Figure 6 A schematic diagram of the structure of the electronic device provided in this application.

[0034] The accompanying drawings illustrate specific embodiments of this application, which will be described in more detail below. These drawings and descriptions are not intended to limit the scope of the concept in any way, but rather to illustrate the concept of this application to those skilled in the art through reference to particular embodiments. Detailed Implementation

[0035] Exemplary embodiments will now be described in detail, examples of which are illustrated in the accompanying drawings. When the following description relates to the drawings, unless otherwise indicated, the same numbers in different drawings denote the same or similar elements. The embodiments described in the following exemplary embodiments do not represent all embodiments consistent with this application. Rather, they are merely examples of apparatuses and methods consistent with some aspects of this application.

[0036] Firmware code review can be applied to tightly coupled hardware and software environments such as storage controllers, bus interface devices, industrial control units, and IoT terminals. Related systems typically include firmware code data, compilation and analysis environments, and protocol specifications, symbol definitions, and relationship information corresponding to the target hardware platform.

[0037] In existing technologies, firmware code review often employs static analysis tools, rule-based detection engines, and general code models to check for syntax errors, logical anomalies, and security risks in firmware code data. These approaches typically extract local code snippets based on preset rules, or manually select structures, macros, global variables, and call relationships as supplementary context before sending the code content to the review module for analysis and generating a review report; alternatively, they may use a sliding window or fixed-size block strategy to segment the code and review each block individually.

[0038] However, in the aforementioned review process, the selection of context relies on manual pre-marking or fixed rule injection, and cannot be dynamically adjusted according to the actual symbols referenced by the code under review and the relationships between them. In firmware projects with complex cross-file call relationships, deep macro expansion levels, and numerous nested structures, it is difficult for manual marking to completely mark all key symbols related to hardware constraints. Fixed rules also lack the ability to perceive the actual dependencies of the code, causing the review model to make judgments based only on local code semantics. Lacking contextual information related to the target hardware platform protocol constraints, it is difficult to identify consistency conflicts between code logic and hardware constraints. At the same time, the mechanical block-splitting strategy does not consider the semantic coherence of the code structure. After large functions are forcibly truncated, the model is prone to review misjudgments due to the lack of complete scope information. These shortcomings mean that logically correct code may expose problems such as abnormal access, sequence conflicts, and improper resource usage in the real hardware environment, reducing the credibility of the review results and the ability to identify risks before deployment.

[0039] In summary, existing technologies, when applied to review scenarios involving strong hardware-software coupling such as firmware, suffer from incomplete coverage of key hardware-related information due to static context injection, which in turn makes it impossible to accurately identify conflicts between code logic and hardware constraints, resulting in insufficient review accuracy.

[0040] To address the aforementioned issues, this application provides a firmware code review method and system. This method constructs a dynamic context acquisition mechanism based on hardware-related metadata as the query foundation, code element information as the planning basis, and priority ranking as the scheduling method. During review, hardware-related metadata, including symbol definition information and inter-symbol relationship information related to the target hardware platform protocol constraints, is first acquired. The target data is then parsed to obtain code element information. Subsequently, a context query strategy containing multiple query items and their priorities is generated based on the code element information. Queries are then executed on the hardware-related metadata according to priority to obtain context information related to the target data. Finally, this context information is combined with the target data and input into the code review model to obtain the review result. This method utilizes query planning driven by code element information, transforming context acquisition from pre-static marking to dynamic determination based on actual code references. This avoids reliance on manual marking and omissions of key hardware information, enabling the review model to make judgments based on a more complete context, thereby improving the accuracy and reliability of firmware code review and reducing false positives and false negatives. Simultaneously, the priority mechanism schedules context queries in an orderly manner, prioritizing the acquisition of key information highly correlated with protocol constraints within a limited context input budget, ensuring review sufficiency while controlling review costs.

[0041] The technical solution of this application and how it solves the above-mentioned technical problems will be described in detail below with specific embodiments. These specific embodiments can be combined with each other, and the same or similar concepts or processes may not be described again in some embodiments. The embodiments of this application will be described below with reference to the accompanying drawings.

[0042] The firmware code review method provided in this application can be executed by a computing device such as a server or server cluster. The server can be a mobile phone, computer, tablet, or other similar device. This application does not impose any particular restrictions on the implementation method of the execution entity, as long as the entity can obtain the target data of the firmware code to be reviewed and the corresponding hardware-related metadata. The hardware-related metadata includes symbol definition information and symbol relationship information related to the protocol constraints of the target hardware platform. The entity then parses the target data to obtain code element information; generates a context query strategy based on the code element information, the context query strategy including multiple query items and the priority of each query item; performs a query on the hardware-related metadata according to the priority to obtain context information related to the target data; and combines the context information with the target data as input to the code review model to obtain the code review result.

[0043] This method is applicable to review scenarios with strong hardware-software coupling, including but not limited to embedded firmware, NVMe solid-state storage firmware, PCIe device firmware, industrial control firmware, and IoT terminal firmware. Firmware can refer to a program embedded in a hardware device used to control hardware behavior and interact with upper-layer software. A common characteristic of the aforementioned firmware is that its code logic is deeply coupled with the target hardware platform's architecture specifications, protocol constraints, and resource limitations. Code review not only needs to detect general software defects but also needs to verify the consistency between the code logic and hardware constraints. This application does not impose specific restrictions on the specific type of firmware, as long as its code undergoes a consistency review with the hardware platform constraints.

[0044] Figure 1 This is a flowchart illustrating the firmware code review method provided in this application. The executing entity of this method can be a server storing the firmware code review method or other servers, such as a code review server deployed in a firmware development continuous integration pipeline, an application server interfacing with a firmware version management system, an edge computing node, or a local development workstation. This embodiment does not impose any particular limitations. Figure 1 As shown, the method may include:

[0045] S101. Obtain the target data and corresponding hardware-related metadata of the firmware code to be reviewed. The hardware-related metadata includes symbol definition information and symbol relationship information related to the protocol constraints of the target hardware platform.

[0046] In this embodiment, the target data can refer to the code data of the firmware code to be reviewed. Its form can include a single source code file, a changeset consisting of multiple source code files, code snippets extracted from source code files, code content input through a pipeline, or intermediate representation data obtained through disassembly. For example, the target data can be a firmware source code file, or a collection of changed files or changed code snippets filtered by a version control system. In specific implementations, the aforementioned source code file can be a collection of firmware project files existing in the form of .c, .h, .cpp, .S, or other source files supported by the build system. This application does not impose any particular limitation on the specific form of the target data, as long as it can be parsed to obtain code element information and used for subsequent contextual queries.

[0047] Hardware-related metadata refers to structured or semi-structured information independent of the target data and related to the architectural specifications and protocol constraints of the target hardware platform. It provides hardware-level constraints for code review models and can originate from the target hardware platform's protocol specification documents, register manuals, header files, linker scripts, or pre-built code knowledge graph databases. Symbol definition information refers to symbolic information related to the protocol constraints of the target hardware platform, used to define hardware interaction interfaces and / or data formats. This can include structure definitions, macro definitions, type definitions, register address mappings, and constant declarations. Symbol relationship information refers to the reference relationships, call relationships, and dependencies between symbols, which can include function call relationships, structure nesting relationships, macro dependencies, and global variable read / write reference relationships. Protocol constraints can refer to platform-related rules of the target hardware platform regarding register access order, bit field definitions, timing requirements, resource mutual exclusion relationships, interrupt response rules, or bus interaction specifications.

[0048] For example, in an NVMe firmware review scenario, hardware-related metadata may include command structure definitions extracted from the NVMe protocol specification header file, register address offset macros extracted from the register mapping header file, and call relationships between interrupt handling functions and queue management functions extracted from the function call graph. As another example, the header files, linker scripts, and protocol specification documents of the target hardware platform can be parsed to automatically construct hardware-related metadata. Yet another example, hardware-related metadata can be loaded from a pre-built code knowledge graph database. This knowledge graph is constructed after static analysis of the entire firmware project's code and stores symbol nodes and the edges of relationships between symbols using a graph data structure. It should be noted that hardware-related metadata can be pre-built and stored independently, or it can be dynamically extracted from header files, linker scripts, and other files on which the target data depends during the review process; this embodiment does not impose any particular limitations.

[0049] In a practical implementation, the execution entity can be an inspection system deployed on a server. The system receives the target data of the firmware code to be inspected and synchronously loads the hardware-related metadata corresponding to the target hardware platform, so that the code content and hardware semantics are established in the initial stage of inspection, providing a unified retrieval basis for subsequent queries.

[0050] S102. Parse the target data to obtain code element information.

[0051] The code element information refers to the structured information extracted from the target data to support the generation of subsequent query strategies. This information may include a set of function units, symbol information referenced within each function unit, and the function's line number. Each function in the function unit set may contain information such as its function name, starting line number, ending line number, parameter list, and the file it belongs to.

[0052] In this step, the review system performs syntax and structure parsing on the acquired target data, identifies function definition boundaries, symbol reference relationships, and scope information in the code, and forms structured code element information so that subsequent context queries can be driven based on the actual content of the code rather than manual annotation.

[0053] For example, for NVMe firmware target data, the tree-sitter parser is used to parse the file, identify all function definition nodes, extract the function name, parameter type list, and start and end positions of the function body for each function, and traverse the identifier nodes within the function body to record the referenced structure type name, macro name, and called function name. As another example, in scenarios where syntax parsing tools are unavailable, a large language model can be used as a fallback to extract the function list from the target data, outputting function boundary and symbol reference information in JSON format.

[0054] Based on the above analysis, this step transforms the original target data into computable code element information, enabling subsequent context queries to no longer revolve solely around text fragments, but rather around symbols, scopes, reference relationships, and hardware access modes, thus providing a structured basis for context completion in complex firmware projects.

[0055] S103. Based on code element information, generate a context query strategy. The context query strategy includes multiple query items and the priority of each query item.

[0056] The context query strategy refers to a set of query instructions used to guide the retrieval of contextual information related to the code under review from hardware-related metadata. Query items are the basic retrieval units in this strategy and can include types such as structure definition queries, macro definition queries, type definition queries, and function call relationship queries. Each query item must include at least a target symbol identifier and a query category. Priority refers to the level of importance marked on each query item, used to determine the execution order of queries and the allocation of context input budget.

[0057] In this step, the review system reads the code element information, identifies the symbols actually referenced in the code and their types, generates corresponding query items accordingly, and assigns priority to each query item based on the degree of association between the symbols and the target hardware platform protocol constraints, forming an executable query strategy.

[0058] For example, in NVMe firmware review, if code element information indicates that the code under review references the structure `nvme_completion` and the macro `NVME_REG_CAP`, the generated query strategy can include: the structure query item `nvme_completion` (priority critical), the macro query item `NVME_REG_CAP` (priority high), and the function relationship query item of the called function `nvme_process_cq` (priority high). As another example, code element information can be input into a large language model, which analyzes the symbols referenced in the code and their association with protocol constraints, outputs a query plan in JSON format, and marks the priority and reason for each query item. Yet another example, a query strategy can be generated based on a preset rule engine, performing rule matching based on the frequency and type of symbols, assigning high priority to symbols with high frequency, and automatically increasing the priority of key structures defined in the protocol specification.

[0059] Based on the above analysis, it can be seen that this step is driven by code element information, which explicitly transforms the real context requirements in the target data into multiple executable query items, and allocates limited query resources in an orderly manner through a priority mechanism, so that the review process can prioritize information that is strongly related to the protocol constraints and has a significant impact on the current code semantics.

[0060] S104. Based on priority, perform a query on hardware-related metadata to obtain context information related to the target data.

[0061] Context information refers to the definition content and relationship information related to the symbols referenced in the code under review, obtained from hardware-related metadata according to a context query strategy, and organized in a structured format. The content of context information may include complete field definitions of structures, expanded macro content and values, signatures of called functions, and their call chain information, etc.

[0062] In this step, the review system, following the generated query strategy, prioritizes the query items and sequentially or in batches retrieves hardware-related metadata to obtain the definition content and relationship information corresponding to the symbols referenced in the code to be reviewed. The system then organizes the query results to form contextual information usable by the model. For example, according to the priorities marked in the query strategy, the system first queries the critical priority items: retrieving the complete definition of the structure `nvme_completion` from the knowledge graph and retrieving the expanded content of the macro `NVME_REG_CAP` from the symbol table. The query results are concatenated in Markdown format as contextual information text.

[0063] Furthermore, queries can be executed sequentially in descending order of priority, with a preset context input budget for each priority level. Higher-priority query items consume the budget first, and subsequent queries stop when the cumulative consumption reaches the preset total budget. Optionally, the query execution vehicle can be a graph database query engine for function call relationship queries; or it can be a local inverted index or symbol table lookup for fast retrieval of structures and macro definitions.

[0064] Based on the above analysis, this step implements the abstract query strategy into a specific retrieval process for metadata storage. By controlling the query order, scope of expansion, and retention strategy through priority, the obtained contextual information is closely related to the target data, thereby reducing the omissions that may occur when making judgments based solely on local code semantics.

[0065] S105. Combine the context information with the target data as input to the code review model to obtain the code review results.

[0066] The code review model refers to a pre-trained or fine-tuned large language model that can analyze the input code and contextual information and output review comments. The code review result refers to the report output by the model, indicating the problems found in the code to be reviewed, which may include a problem description, problem location, severity level classification, and remediation suggestions.

[0067] In this step, the review system combines the obtained context information and target data according to a predetermined format to generate complete input content that meets the input requirements of the code review model. The combined input is then fed into the code review model for reasoning, and the review results output by the model are received. For example, a Prompt text is constructed in the format: "The following is the hardware context information relevant to this review: [Context Information]. The following is the firmware code data to be reviewed: [Target Data Fragment]. Please review the target data based on the above context information and output the problems found and remediation suggestions." This Prompt is input into the code review model, and the model outputs a review result containing a list of issues. Alternatively, the context information and target data can first be associated according to symbolic correspondence, each piece of context information can be attached to its corresponding code fragment position, and then the complete code text with context annotations can be used as model input.

[0068] In addition, in some implementations, the code review model can be a large language model deployed locally, which is called through an internal inference service interface to ensure that the target data and hardware-related metadata do not leave the local environment.

[0069] Based on the above analysis, it can be seen that by combining contextual information with target data and inputting it into the code review model, the model can make joint judgments under conditions including target hardware platform protocol constraints, symbol definitions, and symbol relationships. This allows the code review conclusions to go beyond the surface semantics of local text and cover implicit defects related to hardware behavior. It should be understood that the above example is merely illustrative and not limiting.

[0070] The firmware code review method provided in this application obtains target data of the firmware code to be reviewed and hardware-related metadata containing symbol definition information and inter-symbol relationship information. It parses the target data to obtain code element information, generates a context query strategy containing multiple query items and their priorities based on the code element information, and performs queries on the hardware-related metadata according to the priorities to obtain context information related to the target data. Finally, it combines the context information with the target data as input to the code review model to obtain the review result. This achieves a dynamic context acquisition mechanism driven by code element information and scheduled according to priority. The hardware constraint context required during the review process no longer relies on manual pre-marking or fixed rule injection, but is dynamically determined and selectively acquired based on the actual symbols referenced by the code and the inter-symbol relationships. This avoids the problem of incomplete coverage of key hardware-related information under static context injection, which leads to the review model only being able to make judgments based on local code semantics. It improves the accuracy of identifying conflicts between code logic and hardware constraints, reduces defect omissions due to missing context, and thus improves the accuracy and reliability of firmware review, reducing false positives and false negatives.

[0071] However, in practical applications, when the target data of the firmware code to be reviewed contains both simple small functions and large functions with numerous lines of code and complex nesting levels, if all functions are extracted indiscriminately, the complete code of the large functions may exceed the context window limit of the review model, or introduce a large amount of code content that is irrelevant to this review, interfering with the review model's focused judgment on key defects. On the other hand, if only the local code near the modified line is extracted, the lack of function signatures, local variable declarations, and scope hierarchy information may prevent the review model from accurately understanding the semantic context of the code.

[0072] Therefore, based on the above embodiments, the target data is parsed to obtain code element information, including: identifying function boundaries in the target data to obtain a function set consisting of multiple function units; counting the number of lines of code for each function unit in the function set, identifying function units with a number of lines of code greater than a preset threshold as large functions, and identifying function units with a number of lines of code less than or equal to the preset threshold as small functions; identifying the change position of large functions, extracting the smallest enclosed scope fragment corresponding to the code change position in the large function, and combining the smallest enclosed scope fragment with the function signature and local variable declarations of the large function to obtain the code element information corresponding to the large function; and extracting whole functions from the small functions to obtain the code element information corresponding to the small functions.

[0073] Function boundary identification refers to the process of identifying the start and end positions of each function definition from the target data. The identification result can include the function name, start line number, end line number, and the file path to which it belongs. A function unit refers to the complete code region of a single function obtained after function boundary identification, including the function signature, function body, and associated attribute macros. Line count refers to the effective number of lines of code in a function unit, used as a quantitative basis for distinguishing between large and small functions. The preset threshold refers to a pre-set critical value for the number of lines of code used to distinguish between large and small functions. Its specific value can be flexibly set according to the context window size of the code review model and the code style of the firmware project; for example, it can be set to 200 lines, 150 lines, or 300 lines. A large function refers to a function unit with more than the preset threshold of lines of code, typically with a longer function body, deeper nesting levels, and more complex control flow. A small function refers to a function unit with fewer than or equal to the preset threshold of lines of code, typically with a simple structure and single responsibility.

[0074] In diff review mode, the change location refers to the code position in the target data that has changed relative to the baseline version. The diff parser can parse the starting line number, the number of lines changed, and the type of change from the git diff output. In full review mode, the change location refers to the code area within the function unit that needs to be focused on during review. The smallest enclosing scope segment refers to the code segment in the abstract syntax tree of the large function that completely contains the change location and has the smallest scope. Specifically, starting from the leaf node of the AST where the change location is located, tracing back up the parent node chain level by level, the code area corresponding to the first parent node that completely contains the change location and is a statement block node is taken as the smallest enclosing scope segment. The function signature refers to the declaration information of the large function, including the return type, function name, parameter list, and attribute macros. Local variable declarations refer to the set of declaration statements for all local variables in the large function, including variable type, variable name, and initialization expression. Complete function extraction refers to the extraction of the complete code content of a small function, including the function signature, all statements within the function body, and comments.

[0075] In one example, function boundary identification can be achieved by using a tree-sitter parser to parse the target data and generate an AST, traversing all function definition type nodes in the AST, extracting the start and end positions of each function definition node, and mapping them to a range of line numbers in the target data. In another example, when tree-sitter parsing fails, a large language model can be used for function boundary identification as a fallback. The target data is input into the model, which outputs a JSON-formatted list of functions, including the function name, start line number, and end line number. In yet another example, for firmware projects with good coding style, regular expressions can be used to match the start position of function definitions, and then a curly brace matching algorithm can be used to determine the end position of the function body. For example, for firmware code data written in C, the tree-sitter parser can identify the start and end positions of a function definition node (such as an interrupt handler function) as the boundary of the function, extracting the function name and line number range.

[0076] Furthermore, the code lines can be counted either by physical lines or by logical lines. Physical line counts include blank lines and comment lines, while logical line counts only include lines containing actual statements. In some embodiments, the preset threshold can also be dynamically adjusted based on the size of the inspection model's context window. For example, the preset threshold is set to 200 lines when the inspection model supports a 128K token context window, and reduced to 100 lines when using a 32K token context window model.

[0077] In one example, the extraction method for the smallest enclosing scope fragment of a large function can be as follows: Locate the leaf node of the AST corresponding to the change location in the constructed AST, backtrack upwards along the parent node chain, and check in turn whether the parent node is a statement block node (such as an if statement block, for loop body, while loop body, or switch branch). Take the first complete statement block node containing the change location as the smallest enclosing scope, and extract the complete code text of that node and its corresponding original line number range. For example, in a large function with 350 lines of code, if a change is located in an if statement block spanning lines 175 to 195, then the code of the if statement block from lines 175 to 195 is extracted as the smallest enclosing scope fragment. In another example, in a downgraded scenario where the AST is unavailable, the smallest complete code block containing the change location can be found by analyzing the nesting level of curly braces based on the line number of the change location and scanning upwards from the line where the change location is located.

[0078] Furthermore, the code element information corresponding to a large function can be combined as follows: the smallest enclosing scope segment, function signature, and local variable declarations are concatenated according to a preset template format, while retaining the original line number information within the segment. For example, the generated code element information for a large function may include: the function signature of the large function (return type + function name + parameter list), the local variable declarations related to the changed location within the large function, and the smallest enclosing scope segment code with the original line number range marked.

[0079] In some embodiments, the extraction method for small functions can be: directly using the complete code text corresponding to the function unit as code element information, while retaining the start and end line numbers of the function, so that the review model can map the analysis results back to the original code location.

[0080] By identifying function boundaries in the target data, the function set is divided into large and small functions based on the number of lines of code. For large functions, only the smallest enclosed scope fragment corresponding to the code change location, along with its function signature and local variable declarations, are extracted. For small functions, the entire function is extracted. This achieves a differentiated code element extraction strategy at the function granularity. This allows the large function to provide the model with the control flow environment and scope conditions of the changed code without requiring the entire large function to be input. While effectively controlling the length of the input context, type and interface information are preserved. This avoids semantic incompleteness or context windowing issues caused by the complete truncation of large functions and reduces interference from irrelevant code in the review judgment. This makes the subsequent context query strategy generated based on code element information more targeted, thereby improving the accuracy and efficiency of firmware code review.

[0081] Based on the above embodiments, the method for generating a context query strategy based on code element information may include: dividing the code element information into blocks to obtain multiple code blocks; identifying symbol references in each code block to obtain a set of symbols referenced in the code block; generating corresponding query items according to the type of each symbol in the symbol set; wherein, when the type of the symbol is a structure, macro, or type definition, a symbol definition query item is generated; when the type of the symbol is a function, a symbol relationship query item is generated; assigning priority to each query item, the priority being determined based on the reference frequency of the symbol corresponding to each query item in the code block and the degree of association between the symbol and protocol constraints; and obtaining the context query strategy based on all query items and the priority corresponding to each query item.

[0082] Block processing refers to dividing code element information into multiple code blocks according to a preset block size or a preset number of functions within a block. Each code block can contain code element information corresponding to one or more function units, aiming to control the amount of code processed in a single query strategy. Symbol reference recognition refers to scanning the code content in each code block to identify references to external symbols appearing in that code block. Symbols can include structure type names, macro names, type definition names, global variable names, and the names of called functions. The symbol set can refer to the deduplicated set of all identified referenced symbols in a code block.

[0083] Symbol definition query items can refer to query items generated for symbol types such as structures, macros, or type definitions, used to retrieve the complete definition of that symbol from hardware-related metadata. Symbol relationship query items can refer to query items generated for function type symbols, used to retrieve the function call relationships (callers and callees) from hardware-related metadata. Priority refers to the importance level marked on a query item, used to guide the execution order of subsequent queries and the allocation of context input budget.

[0084] Reference frequency refers to the number of times a symbol appears in a corresponding code block. A higher reference frequency generally indicates that the symbol is more important to the semantic understanding of the code block. Protocol constraint correlation refers to the degree of association between a symbol and the target hardware platform's protocol specifications. For example, structures directly related to the protocol specifications (such as command queue descriptor structures), register address macros, and interrupt handlers have a higher correlation, while general utility functions or local auxiliary types have a lower correlation. The correlation of protocol constraints can be determined through a pre-defined symbol importance mapping table or by a large language model based on symbol names and contextual semantics.

[0085] In this step, the code element information is first divided into blocks to obtain multiple code blocks; then, symbol references are identified for each code block to obtain the set of symbols referenced by that code block; next, corresponding query items are generated according to the type of each symbol; then, each query item is marked with priority according to the reference frequency and protocol constraint association degree of each symbol; finally, all query items and their priorities are summarized to obtain the context query strategy.

[0086] In one example, the code element information can be divided into blocks of four function units each. For example, a function set containing 12 function units would be divided into three blocks, each containing four function units. Another example is block division based on lines of code, such as dividing a block into blocks of 500 lines. Yet another example is block division based on function call relationships, grouping closely related functions into the same block to maintain semantic coherence. For instance, for code element information containing 28 function units, dividing it into blocks of four would result in seven blocks.

[0087] Furthermore, there are several methods for identifying symbolic references. One example is based on AST traversal, performing node traversal on the AST corresponding to each code block, identifying identifier nodes that serve as type references, identifier nodes that match known macro names, and nodes representing the called function names in function call expressions, thus summarizing to obtain a symbol set. Another example, when AST is unavailable, can be downgraded to using a large language model to identify symbolic references in code blocks, with the model outputting a JSON-formatted list of symbols and the type of each symbol. Yet another example is using regular expressions to match common symbolic reference patterns, extracting a candidate symbol set, and then filtering and confirming it through lexical analysis.

[0088] In one example, query items can be generated as follows: for symbols of type struct in the symbol set, generate corresponding struct definition query items; for symbols of type macro, generate corresponding macro definition query items; for symbols of type function, generate corresponding function call relationship query items. Each query item can record the symbol name, symbol type, and the identifier of the code block to which it belongs.

[0089] Furthermore, there are several ways to determine priorities. One example is to first determine the reference frequency of each symbol within its corresponding code block, and then, based on a pre-defined protocol constraint symbol mapping table, assign the highest priority to symbols with high reference frequency and strong protocol relevance, and the lowest priority to symbols with low reference frequency and weak protocol relevance. Another example is that a large language model can assign priority to each query item, comprehensively considering the symbol's reference frequency, semantic role, and protocol constraint relevance, and outputting the priority annotation results and the reasons for the annotation. Yet another example is to combine a rule engine with model annotation, where the rule engine provides an initial priority based on reference frequency, and the model adjusts it based on protocol relevance.

[0090] In some embodiments, before generating a query strategy, the symbol set can be deduplicated to avoid generating duplicate query items when the same symbol is repeatedly identified in multiple code blocks. Deduplication can be based on a combination of symbol name and symbol type. If symbols with the same name and type are identified in multiple code blocks, only one query item is retained, and all code block identifiers referencing that symbol are merged and recorded in that query item.

[0091] By segmenting code element information and identifying symbolic references and generating query items for each code block, and prioritizing query items based on reference frequency and protocol constraint correlation, the query strategy generation process can proceed systematically based on symbolic references at the code block level. This controls the scale of each processing run while ensuring the correspondence between query items and actual referenced symbols in the code, avoiding symbol omissions or query item redundancy caused by excessive code volume in the overall processing approach, and reducing interference from irrelevant information in query strategy generation. Furthermore, by using both reference frequency and protocol constraint correlation as the basis for priority determination, high-frequency referenced symbols closely related to protocol constraints receive higher query priority. This allows subsequent context queries to prioritize covering hardware constraint information more critical to review within a limited budget, ensuring highly correlated symbols enter the review model's context first. This improves the targeting of the query strategy and the effectiveness of context information acquisition, thereby enhancing the accuracy of firmware code review.

[0092] Based on the above embodiments, the method for querying hardware-related metadata according to priority to obtain context information related to target data may include: querying hardware-related metadata according to a preset context input budget corresponding to the priority to obtain symbol information, and updating the consumed context input after each query; stopping the execution of queries for the remaining priorities when the accumulated consumed context input reaches the preset context input budget; and combining the obtained symbol information with code element information to obtain context information.

[0093] The preset context input budget refers to the upper limit of context input, measured in tokens, pre-allocated for the context query phase. Context input refers to the number of tokens occupied by the retrieved symbol information when it is input into the code review model. The specific value of the preset context input budget can be configured based on the context window size of the code review model, the token usage of the code to be reviewed, and the review efficiency requirements.

[0094] Symbolic information can refer to the symbol definitions or relationships between symbols obtained from hardware-related metadata based on the query item. For example, the symbolic information corresponding to a structure definition query item could be the complete field definitions and field comments of that structure; the symbolic information corresponding to a macro definition query item could be the expanded content and values ​​of that macro; and the symbolic information corresponding to a function relationship query item could be the list of callers and callees of that function.

[0095] The consumed context input can refer to the total number of tokens used by all executed queries up to the current moment. Updating the consumed context input after each query means that after completing a query and obtaining the corresponding symbol information, the token count of that symbol information is added to the consumed context input.

[0096] In this step, queries are first executed sequentially according to priority from high to low, under the constraint of a preset context input budget. After each query is executed and the corresponding symbol information is obtained, the consumed context input is updated. When the accumulated consumed context input reaches the preset context input budget, the execution of the remaining lower priority queries is stopped. Finally, the obtained symbol information and code element information are combined to generate context information. It can be understood that symbol information provides the definition and relationship basis at the hardware constraint level, while code element information provides the structure and reference information of the code to be reviewed. The combination of the two constitutes the input of the code review model, enabling the model to understand the hardware constraints while simultaneously understanding the code structure, thus facilitating a joint judgment on the consistency between the code logic and the hardware constraints.

[0097] In one example, the preset context input budget corresponding to the priority can refer to the total token budget set for the entire query phase. For example, the total budget is 4000 tokens, and the query strategy includes 3 critical priority query items, 5 high priority query items, and 8 medium priority query items. The queries are executed sequentially in the order of critical-high-medium. After querying each symbol, its token usage is accumulated. When the accumulated value reaches 4000 tokens, the query stops even if there are still unexecuted query items.

[0098] In another example, the preset context input budget corresponding to the priority can refer to the sub-budget set for each priority level. For example, the critical priority level is allocated 2000 tokens, the high priority level is allocated 1500 tokens, and the medium priority level is allocated 500 tokens. When querying, all query items within the critical priority level are executed first, and the cumulative token consumption does not exceed 2000. If the excess is exceeded or the remaining budget is insufficient, the unexecuted query items within that priority level are skipped and the process moves to the next priority level.

[0099] In another example, the number of symbolic information tokens for each query can be estimated before execution. If the estimated number of tokens plus the consumed context input will exceed the budget, the query can be skipped or the symbolic information of the query can be truncated, retaining only the most critical fields or relational information in the symbol definition.

[0100] Furthermore, there are several ways to combine symbol information and code element information. In one example, the retrieved symbol information can be arranged sequentially according to the priority of the query items, concatenated in Markdown format as contextual information text, and then appended with the corresponding code block content from the code element information. In another example, the location of symbol references can be marked in the code element information, and symbol information for that symbol can be inserted near the corresponding location, making the contextual information more coherent in the code reading order. Yet another example is that the contextual information can be organized in a structured format (such as JSON), storing symbol information and code element information in different fields.

[0101] In addition, in some embodiments, when the accumulated consumed context input reaches the preset context input budget, in addition to stopping the execution of queries with the remaining priority, the system can also output query execution status records. The records may include the number of executed query items, the token consumption of each priority level, a list of skipped query items and the reasons for skipping, so as to evaluate the rationality of the query strategy and make subsequent optimizations.

[0102] This implementation allows for precise control over the query scope of hardware-related metadata based on the context input, preventing the query resources from expanding indefinitely and prioritizing key symbols within the context information. Since symbol information and code element information are combined and directly used for review input, the completeness and accuracy of contextual association during firmware code review are improved, and misjudgments caused by excessive or missing context are reduced.

[0103] In practical applications, indiscriminately combining all acquired contextual information with the target data and inputting it into the code review model will cause the contextual content required by different review dimensions to become mixed and intertwined. Syntax review may be interfered with by metadata related to concurrency protection, and security review may be unable to trace cross-function data flow due to the lack of function call relationship information, resulting in blurred focus of judgment on each review dimension and reduced relevance and accuracy of review results.

[0104] Therefore, based on the above embodiments, the method described in S105 for combining context information with target data as input to a code review model to obtain code review results may include: dividing the context information into dimensions to obtain a syntax review context, a logic review context, and a security review context; wherein, the syntax review context includes macro definitions and type definitions, the logic review context includes function call relationships and global variables, and the security review context includes pointer operations and metadata related to concurrency protection; combining the target data with the syntax review context, the logic review context, and the security review context respectively to obtain three sets of review input data; and inputting the three sets of review input data into the code review model for parallel review processing to obtain code review results, which include syntax review results, logic review results, and security review results.

[0105] Among them, dimension partitioning can refer to the process of splitting the context information obtained in S104 into multiple context subsets according to the different requirements of the review dimension. Each context subset contains only symbolic information related to the review dimension, so that each review dimension can obtain the context content corresponding to its review target at the input level.

[0106] Syntax review context refers to a subset of contexts used to support syntax and style review, including macro definitions and type definitions. Macro definitions can refer to the macro expansion and values ​​corresponding to macro names referenced in the code under review. Type definitions can refer to structure definitions, enumeration type definitions, union definitions, and type alias declarations corresponding to type names referenced in the code under review. Logic review context refers to a subset of contexts used to support logic and complexity review, including function call relationships and global variables. Function call relationships can refer to the caller and callee lists related to functions in the code under review. Global variables can refer to the declaration information and read / write locations of global variables referenced in the code under review. Security review context refers to a subset of contexts used to support security vulnerability review, including metadata related to pointer operations and concurrency protection. Metadata related to pointer operations can refer to structure definitions, memory layout information, and type information of objects pointed to by pointers related to pointer usage in the code under review. Metadata related to concurrency protection can refer to the symbol definitions and relationship information of concurrency protection mechanisms such as mutexes, spinlocks, atomic operations, and interrupt masking related to shared resource access in the code under review.

[0107] The three sets of review input data can refer to three independent model input contents formed by combining the target data with the syntax review context, logic review context, and security review context, respectively. Each set of review input data corresponds to a review dimension. Parallel review processing refers to the process of inputting the three sets of review input data into the code review model for processing in an overlapping manner in time. This can be achieved by concurrently calling the same code review model instance through multi-threading, or by calling multiple code review model instances.

[0108] In this step, the context information obtained in S104 is first divided into dimensions. According to the requirements of each review dimension, the corresponding symbol information is selected from the context information to form three context subsets. Then, the target data is combined with the above three context subsets to obtain three sets of review input data. Finally, the three sets of review input data are input into the code review model for parallel review processing to obtain the corresponding review results.

[0109] In one example, the context information can be divided into dimensions based on a predefined mapping relationship between symbol types and review dimensions. For example, the predefined mapping relationship stipulates that macro definitions and type definitions belong to the syntax review context, function call relationships and global variables belong to the logic review context, and pointer operation-related metadata and concurrency protection-related metadata belong to the security review context. When dividing, each symbol information in the context information is traversed, and it is assigned to the corresponding context subset according to its symbol type.

[0110] In another example, the dimension partitioning can be done as follows: the large language model performs semantic judgment on each piece of symbolic information in the context information according to the review objectives of each review dimension, and then assigns it. For example, if the large language model determines that a certain structure definition contains a pointer field, which directly helps in pointer out-of-bounds judgment in security review, then this piece of information is assigned to both the syntax review context and the security review context. It is understandable that the same symbolic information can be assigned to multiple context subsets; that is, dimension partitioning allows symbolic information to be shared between different review dimensions, as long as the symbolic information is helpful for the judgment of multiple review dimensions.

[0111] In another example, when generating the query strategy in S103, each query item can be labeled with its corresponding review dimension, so that the symbolic information obtained from the query has dimension labels. Then, the dimension division can be completed simply by grouping according to the dimension labels.

[0112] Alternatively, the three sets of review input data can be combined by concatenating the target data with three context subsets according to a preset Prompt template, generating three independent Prompt texts. In another example, the review context can be placed at the beginning of the Prompt template as background knowledge, and the target data at the end as the analysis object. Yet another example allows placing the review context and target data in different message structures to accommodate different model input format requirements.

[0113] For example, for syntax review, the syntax review context (containing macro expansion content and type definitions) is combined with the target data to generate syntax review input data; for logic review, the logic review context (containing function call relationships and global variable information) is combined with the target data to generate logic review input data; for security review, the security review context (containing pointer operations and concurrency protection metadata) is combined with the target data to generate security review input data. These three sets of input data are fed into the code review model, which outputs syntax review results, logic review results, and security review results, respectively.

[0114] Furthermore, parallel review processing can be implemented as follows: Three worker threads are created using a thread pool. Each worker thread carries a set of review input data and calls the code to review the model. The three threads execute concurrently, and the three sets of review results are aggregated after all threads have completed. In another example, asynchronous calls can be used to initiate three model inference requests simultaneously, collecting review results for each dimension through callbacks or polling. Yet another example can call three different model service instances, each specifically handling the review task for one dimension.

[0115] By mapping the same target data to different review dimensions and inputting them into the code review model in parallel, syntax, logic, and security issues can be judged independently under their respective contexts and then aggregated into code review results. This ensures that the review output corresponds to the specific issue type of the target data, reduces misjudgments caused by mixed contexts, and improves the consistency of identifying macro dependencies, call chain anomalies, and concurrent access risks in firmware. This method improves the targeting and accuracy of reviews in each dimension while also taking into account review efficiency.

[0116] Based on the above embodiments, a specific implementation method for knowledge base-driven adaptive query planning can be provided to achieve intelligent generation from code element information to context query strategies.

[0117] In one optional implementation, given a set of functions F={f1,f2,...,fn} (corresponding to the set of functions in the code element information) and a code knowledge base K (corresponding to hardware-related metadata), where the code knowledge base K contains structure definitions, macro definitions, and global symbol information, this implementation designs an intelligent planning system that automatically generates a query list Q={q1,q2,...,qm}, ensuring that the injected context C=QueryKnowledgeBase(K,Q) (corresponding to context information) covers more than 90% of the information required for review. The code knowledge base can refer to a pre-built set of hardware-related metadata stored in a graph data structure or index structure, whose content may include structure definitions, macro definitions, global symbol declarations, and function call relationships. The query list can refer to a list generated by the intelligent planning system containing multiple query items, each specifying the symbol name or relationship type to be queried from the code knowledge base. The information required for review can refer to all the context information needed by the code review model to accurately judge the code under review.

[0118] Furthermore, it can be understood that the code knowledge base is an optional storage and organization form of hardware-related metadata. Hardware-related metadata can be stored in a graph data structure as the code knowledge base, or in other structures such as symbol tables and inverted indexes. The query list corresponds to the context query strategy in the aforementioned embodiments, and the query item corresponds to the query item in the context query strategy.

[0119] Specifically, the query plan is generated by the large language model based on the code blocks to be reviewed (corresponding to multiple code blocks), protocol constraint information, and historical defect patterns. Historical defect patterns refer to confirmed defect types accumulated in previous reviews and their corresponding contextual patterns, such as DMA buffer misalignment, incorrect register access order, and unlocked shared resource access in interrupt handlers. Using historical defect patterns as input allows the large language model to assign higher priority to symbols closely associated with known high-frequency defects.

[0120] The large language model outputs a query plan in JSON format. The JSON schema of this query plan defines four types of query items: struct queries, macro queries, symbol queries (corresponding to symbol definition queries), and function relationship queries (corresponding to symbol relationship queries). Each struct, macro, or symbol query item contains a name field, a priority field, and a reason field. Each function relationship query item contains a function name field, a priority field, and a reason field. The priority field has three values: critical, high, and medium. It should be noted that the JSON schema is only one optional structured representation of the query plan in this implementation; the query plan can also be represented using other structured formats or key-value pair formats.

[0121] For example, the query plan output by the large language model may include: a structure query item named "STRUCT_A" with high priority, because the structure is used as a command descriptor in the code to be reviewed; a macro query item named "MACRO_B" with critical priority, because the macro is a register offset address macro and is closely related to protocol constraints; a symbol query item named "GLOBAL_C" with medium priority, because the symbol is a global state variable and affects the logic review judgment; and a function relationship query item for the function "caller_func" with critical priority, because the call chain of the function needs to be traced to determine the interrupt handling context.

[0122] The model incorporates deduplication logic when generating query plans, ensuring that symbols with the same name and type are not listed repeatedly. Simultaneously, the model identifies structures and macros directly related to the target hardware platform's protocol specifications and automatically prioritizes them (i.e., priority is determined based on the degree of protocol constraint correlation). For example, in NVMe firmware review scenarios, command queue structures and register offset macros directly related to the NVMe protocol will have their priority automatically elevated to critical or high levels.

[0123] After obtaining the query plan, queries are executed on the code knowledge base according to priority: Critical priority queries are executed first, allocating the largest context input budget; then High and Medium priority queries are executed in descending order of budget; if the context input budget is exhausted, the query automatically stops. The context input budget refers to the upper limit of context input measured in Tokens, and the budget allocation for each priority level can be dynamically configured based on the context window size of the review model and the Token usage of the code to be reviewed. Query results are organized in Markdown format and code blocks to ensure clear positioning of each symbol within the context, enabling the large language model to accurately locate symbol information.

[0124] Based on this, the system generates a unique subset of context for each review dimension (i.e., a dimensional division of context information). The syntax review context includes macro definitions, type definitions, and function signatures; the logic review context includes symbolic information related to function call relationships, global variables, and loop structures; and the security review context includes metadata related to pointer operations, DMA registers, and concurrency protection. Each review dimension only receives its unique subset of context in subsequent model calls, avoiding interference from irrelevant information.

[0125] In this way, the generation of query strategies is driven by the large language model based on the actual code reference situation, protocol constraints, and historical defect patterns, no longer relying on manual labeling or fixed rules. This allows the query strategy to dynamically cover the key context information required for review, and high-criticality symbols are preferentially queried and injected under the context input budget constraint. This enables the code review model to make defect judgments in a more complete hardware constraint context, improving the accuracy of identifying conflicts between code logic and hardware constraints and the efficiency of context acquisition in firmware review.

[0126] Furthermore, in practical applications, after the three dimensions of syntax review, logic review, and security review are executed in parallel and independently, the review results output by each may contain different descriptions or severity levels of the same problem. If the three sets of results are directly summarized without cross-dimensional deduplication and merging, the same defect may appear repeatedly in the form of multiple records, causing developers to repeatedly investigate the same problem; if duplicate records are simply discarded during merging, the discovery details or problem location information specific to a certain dimension may be lost; if the severity level is not uniformly processed during merging, and the severity level of the same problem is marked inconsistently in different dimensions, the merged report may have a level confusion, affecting the developer's judgment on the priority of defect remediation.

[0127] Therefore, based on the above embodiments, the method may further include: standardizing each issue record in the syntax review results, logic review results, and security review results to obtain an issue fingerprint corresponding to each issue record; merging issue records with the same issue fingerprint to obtain a merged issue record; the merged issue record is marked with source dimension information and original issue details; determining the final severity level of the merged issue record based on the initial severity level corresponding to each source dimension in the merged issue record; and sorting the merged issue records after determining the final severity level according to the severity level to obtain the final review result.

[0128] Issue records can refer to single issue descriptions output from syntax review, logic review, or security review results. They may include fields such as the function identifier where the issue occurs, the issue type, the location of the affected code, the issue description, the severity level, and remediation suggestions. Normalization refers to the process of converting issue records from different review dimensions into a unified format, enabling subsequent fingerprint calculation and merging operations to be performed on a consistent data structure. An issue fingerprint is an identifier generated after feature extraction from the normalized issue record, uniquely identifying a specific issue. It can be calculated based on the function identifier, issue type, and location of the affected code. Identical issue fingerprints mean that two issue records point to the same type of issue in the same piece of code.

[0129] A merged issue record refers to a single, consolidated record resulting from merging issue records with identical issue fingerprints. The merged issue record includes source dimension information and original issue details. Source dimension information indicates which review dimensions jointly discovered the merged issue record. Original issue details refer to the original descriptions of the issue from each source dimension before merging, including the original issue descriptions, remediation suggestions, and initial severity levels provided by each dimension. Retaining these original issue details ensures that no findings from any dimension are lost during the merge process.

[0130] The initial severity level refers to the severity level assigned to the issue by each source dimension in its respective review results. This can be based on a pre-defined severity level system, such as Must-Fix, Should-Fix, and Nice-to-Have, or a critical / high / medium / low rating system. The final severity level refers to the severity level determined after cross-dimensional comparison of merged issue records and presented in the final review results. Hierarchical sorting refers to the process of grouping and arranging merged issue records according to their final severity level, from highest to lowest.

[0131] In this step, each issue record in the three review results is first standardized, and the issue fingerprint of each issue record is calculated after unifying the field format. Then, issue records with the same issue fingerprint are merged into a merged issue record, and the source dimension information and the original issue details of each source dimension are marked. Next, the initial severity levels corresponding to each source dimension are compared to determine the final severity level. Finally, all merged issue records are sorted hierarchically according to the final severity level to obtain the final review result.

[0132] In one example, the normalization process can be as follows: Issue records from different dimensions are uniformly mapped to a standard field structure. These standard fields can include function ID (function_id), issue type (issue_type), affected code location (affected_code_location), issue description, severity level, and remediation suggestions. The function ID can be extracted from the output of each dimension or determined by backtracking from the code location. The affected code location can be standardized to the format "file path:start line number-end line number," and the issue type can be mapped to standard categories based on a pre-defined classification mapping table, mapping custom tags from each dimension to standard categories.

[0133] For example, in the syntax review results, one issue record states "An unused variable exists on line 45 of function foo," and in the logic review results, another issue record states "A variable near line 45 of function foo was assigned a value but was not read." After normalization, both records have the function identifier foo, the affected code location is line 45, and the issue type is mapped to "redundant code." At this point, the two issues have the same fingerprint and can be merged in subsequent steps.

[0134] In another example, the problem fingerprint can be calculated by concatenating the function identifier, problem type, and affected code location, and then performing a hash operation to obtain a fixed-length problem fingerprint value. In yet another example, the normalized string of these three elements can be used directly as the problem fingerprint, eliminating the need for hash operations and facilitating tracing and debugging.

[0135] In one example, merging issue records with the same issue fingerprint can be done by selecting one issue record as the base record, and appending the source dimension information and original issue details of the remaining issue records with the same fingerprint to the base record to form a merged issue record. For example, if the same issue is found in both syntax review and security review, the merged record will be marked "Source: Syntax / Security," and the original descriptions and remediation suggestions for both dimensions will be retained respectively.

[0136] Furthermore, there are several ways to determine the final severity level. One example is to use the highest initial severity level marked across all source dimensions as the final severity level. That is, if any source dimension marks the issue as Must-Fix, the final severity level of the merged issue records is Must-Fix, ensuring that critical defects are not downgraded due to lower markings in other dimensions. Another example is to determine the final severity level by weighting the initial severity levels from each source dimension. The weights can be configured based on the credibility of each review dimension's identification of firmware defects.

[0137] In some embodiments, the hierarchical sorting method can be as follows: merged problem records are classified into three levels: Must-Fix, Should-Fix, and Nice-to-Have. Within each level, secondary sorting can be performed according to the function or file path where the problem is located, and finally presented in the form of a structured report.

[0138] This approach unifies problem descriptions, performs cross-dimensional deduplication, preserves source information and original details, and combines multiple source severity levels to determine the final severity level. This ensures that the same defect is not repeatedly displayed in the final result, while maintaining problem traceability and consistency in severity classification. After the final review results are output in tiers according to severity level, users can directly prioritize and process high-severity issues based on the ranking, and form an executable code review conclusion accordingly.

[0139] Furthermore, if the same issue is found across multiple review dimensions, each dimension may assign inconsistent initial severity levels due to its different review perspectives. If the initial severity levels of each source dimension are simply averaged or the lowest value is taken during merging, the final severity level of the issue may be lowered, and high-priority defects identified by security dimensions may be masked in the lower-level merging result. Therefore, based on the above embodiments, the method for determining the final severity level of a merged issue record according to the initial severity levels corresponding to each source dimension in the merged issue record may include: determining the final severity level of the merged issue record as the highest level when the initial severity level corresponding to any source dimension is the highest level; correspondingly, the method for hierarchically sorting the merged issue records by severity level after determining the final severity level and outputting the final review result may include: arranging the merged issue records by severity level from high to low into blocking merge issues, suggested repair issues, and optional optimization issues, thus obtaining the final review result.

[0140] The highest level can refer to the most severe level in a predefined severity level system. For example, in the above severity level system, the highest level corresponds to the Must-Fix level, meaning the issue must be fixed before code merging is allowed. An initial severity level of the highest level for any source dimension implies that at least one review dimension has determined the issue to be a critical defect that must be fixed.

[0141] Blocking merge issues refer to the issue hierarchy comprised of merge issues with the highest final severity level (e.g., Must-Fix). Issues at this level are defects that must be fixed before code can be merged. Recommended fix issues refer to the issue hierarchy comprised of merge issues with the second-highest final severity level (e.g., Should-Fix). Issues at this level are defects that are recommended to be fixed in the current or near future but will not block merging. Optional optimization issues refer to the issue hierarchy comprised of merge issues with the lowest final severity level (e.g., Nice-to-Have). Issues at this level are optional code optimization suggestions and do not constitute defects.

[0142] In this step, for each merged issue record, the initial severity level corresponding to each source dimension is checked one by one to determine whether any source dimension marks the issue as the highest level. If so, the final severity level of the merged issue record is directly determined as the highest level, and lower markings from other source dimensions are no longer considered. If not, the final severity level is determined based on the highest non-top-level level marked in each source dimension. After determining the final severity level of all merged issue records, the merged issue records are arranged in layers from high to low according to their final severity level: blocking merged issue layer, suggested repair issue layer, and optional optimization issue layer, to obtain the final review result.

[0143] In one example, the highest severity level can be determined as follows: A pre-defined severity level mapping table defines Must-Fix as the highest level, Should-Fix as the second highest level, and Nice-to-Have as the lowest level. When the initial severity level of a merged issue record is Must-Fix for the security review dimension and Should-Fix for the syntax review dimension, the final severity level of that merged issue record is determined to be Must-Fix. In another example, if no highest level is marked in any of the source dimensions, the highest level appearing in each source dimension is taken as the final severity level. For example, if the syntax review dimension is marked Should-Fix and the logic review dimension is marked Nice-to-Have, the final severity level is determined to be Should-Fix. In yet another example, if the initial severity levels marked in all source dimensions are the same, that level is directly used as the final severity level.

[0144] Furthermore, there are several ways to execute hierarchical sorting. In one example, three lists can be created corresponding to the blocking merge issue layer, the suggested fix issue layer, and the optional optimization issue layer, respectively. All merged issue records are iterated through, and records are placed into the corresponding lists according to their final severity level. Finally, the final review result is output by concatenating the three lists in the order they appear. In another example, after hierarchical sorting, a secondary sort can be performed on the issue records within each level, such as sorting by the path of the file containing the issue or sorting by the severity of the issue type, so that the output order within the same level also follows a predictable pattern.

[0145] For example, if a merged issue record is labeled "Source: Syntax / Security," with an initial severity level of Should-Fix for the syntax dimension and Must-Fix for the security dimension, then the final severity level of this merged issue record is determined to be Must-Fix, and it is classified into the blocking merged issue layer. Another merged issue record originates only from the logic dimension, with an initial severity level of Should-Fix; therefore, its final severity level is Should-Fix, and it is classified into the suggested fix issue layer.

[0146] The above processing can be completed by the code review result aggregation module. This module can maintain a severity level mapping table in memory and perform aggregation on similar issues based on record identifiers to avoid the same defect being displayed repeatedly due to different sources.

[0147] By clearly defining severity level rules, it is ensured that defects identified as requiring remediation in high-credibility dimensions such as security reviews are not downgraded due to lower ratings in other dimensions. This ensures that the severity level in the final review result truly reflects the highest severity of the issue across all review dimensions, resulting in a clearly hierarchical code review conclusion at the output. Consequently, the final review result prioritizes high-risk defects as blocking merging issues, while retaining remediation suggestions and optimization hints, enhancing the operability of the review result and enabling reviewers to quickly determine the order of actions.

[0148] Furthermore, in practical implementation, the aforementioned deduplication and priority protection mechanisms can be implemented through a pre-defined merging rule system. Given a result set R of three independent review dimensions... syntax R logic R security Each result contains a function identifier (function_id), issue type (issue_type), severity level (severity_level), and issue description (description). Design a lossless merging algorithm to produce a summary result set R. merged This lossless merging method satisfies the following constraints: First, the lossless constraint, i.e., R... merged The merging process includes three key aspects: First, it incorporates all issues from the original three sets without deletion or excessive merging. Second, it adheres to deduplication constraints, meaning that if the same issue appears in multiple dimensions, it is merged into a single record with its source labeled. Third, it enforces priority consistency constraints, ensuring that if an issue is labeled Must-Fix (severity level) in any dimension, the merged issue must also be Must-Fix, and downgrading due to lower labels in other dimensions is not permitted. In some implementations, the merging process may include the following steps:

[0149] (1) Issue Normalization: Each issue is normalized to generate a unique issue fingerprint fp, calculated as: fp = hash(function_id + issue_type + affected_code_location). Here, function_id refers to the identifier of the function containing the issue, issue_type refers to the issue type, and affected_code_location refers to the code location affected by the issue. Issue fingerprints are used for cross-dimensional issue matching, i.e., identifying different representations of the same issue across different dimensions.

[0150] (2) Based on the problem fingerprint, strict multiple merging rules are executed. The merging rules specifically include the following five items:

[0151] Rule 1 (Preserve Integrity): Every problem that appears in any dimension must be included in R. mergedThe text appears here and cannot be deleted due to space constraints or other reasons;

[0152] Rule 2 (Deduplication without deletion): When the same problem occurs in multiple dimensions, retain the discovery information of all dimensions and mark it in the results as "Source: Syntax / Logic / Security";

[0153] Rule 3 (Detail Protection): When merging, retain the original field names, function names, code snippets, and other specific details, and avoid excessive merging of descriptions;

[0154] Rule 4 (Priority does not degrade): If a problem is marked as Must-Fix (corresponding to Severity=critical) in one dimension and Should-Fix (corresponding to Severity=medium) in other dimensions, then the highest priority Must-Fix must be used after merging;

[0155] Rule 5 (Avoid overgeneralization): For example, "missing null pointer check" and "missing integer overflow check" cannot be combined into "missing input validation" because this would lose specific technical details and fix instructions.

[0156] In one example, the five merging rules described above can be executed as follows: Maintain a mapping table in memory with issue fingerprints as keys; iterate through the result sets of the three dimensions; calculate the issue fingerprint for each issue record; and check if a record with the same fingerprint already exists in the mapping table. If not, add the record as a new entry to the mapping table; if it already exists, append the source dimension label of the record to the source label of the existing entry according to rule 2, and retain the original description details of the record according to rule 3. After all records have been processed, all entries in the mapping table constitute the merged set of issue records.

[0157] (3) Layer output: The merged R merged The system is categorized by severity level into three tiers: Must-Fix (blocking and merging), Should-Fix (suggested fixes), and Nice-to-Have (optional optimizations).

[0158] For example, the final review result after layered output can be presented in the following structure: In the Must-Fix layer, issue 1 is labeled "[Source: Syntax / Safety] Function X Null pointer not checked", and the suggested fix is ​​"Add NULL check before use"; issue 2 is labeled "[Source: Logic] Function Y Integer overflow risk", and the suggested fix is ​​"Use safe arithmetic operations". In the Should-Fix layer, issue 3 is labeled "[Source: Logic] Function Z Loop complexity too high", and the suggested fix is ​​"Consider splitting into multiple helper functions". In the Nice-to-Have layer, issue 4 is labeled "[Source: Syntax] Function W Variable naming does not conform to naming conventions", and the suggested fix is ​​"Rename according to naming conventions".

[0159] Through the aforementioned merging rule system, the merging process possesses clear and verifiable rules in three dimensions: "lossless," "duplicate," and "priority protection." Rule 1 ensures that no issues are lost in the aggregated result set due to the merging operation; Rules 2 and 3 ensure that cross-dimensional duplicate identification issues are merged by indicating the source and preserving original details, rather than simply deleting or overgeneralizing; Rule 4 ensures that the severity level is not downgraded after merging due to differences in classification; and Rule 5 prevents the loss of technical details due to overgeneralization. Compared to existing solutions that use fuzzy heuristic rules, each rule in the above merging rule system has clear judgment conditions and verifiable execution results, allowing the correctness of the merging behavior to be verified item by item, ensuring that serious defects are not hidden.

[0160] Furthermore, in practical applications, multiple model calls are typically required for multiple code blocks within the same review dimension, with the same review template content but different code snippets in each call. If the review template and code snippets are mixed and sent in the same user message, the inference framework's automatic prefix caching mechanism cannot recognize shared prefixes and changing suffixes within the message. This results in the need to recalculate the key-value cache for the entire message with each call, causing redundant consumption of GPU computing power and video memory. The review time increases linearly with the number of code blocks.

[0161] Therefore, based on the above embodiments, the method of inputting three sets of review input data into the code review model for parallel review processing may include: for multiple model calls within the same review dimension, constructing the corresponding review input data into an input message sequence, and performing structural rearrangement processing on the input message sequence. The structural rearrangement processing includes: placing the review template content corresponding to the review dimension in the first user message; placing the review context corresponding to the review dimension in the review input data, and the code fragment corresponding to the review input data in the target data, in the second user message; wherein, the first user message remains unchanged in multiple model calls within the same review dimension, so that the inference framework corresponding to the code review model reuses the key-value cache corresponding to the first user message; the context input amount of the first user message and the second user message is less than or equal to the context window limit of the code review model.

[0162] In this embodiment, the review template content can refer to a pre-defined prompt text for a specific review dimension, used to guide the code review model in performing review tasks for that dimension. It may include a description of the review objectives, review rules, output format requirements, and a list of issue types to be addressed under that dimension. All code blocks within the same review dimension use the same review template content. The input message sequence can refer to the message array corresponding to a single model call, consisting of one or more user messages arranged sequentially. The structural rearrangement process can refer to adjusting the content boundaries of each message in the input message sequence, splitting shared and changed content into different message positions.

[0163] The first user message can refer to the message carrying the review template content after the structural rearrangement. This content is completely consistent across multiple model calls within the same review dimension, serving as the anchor point for the prefix cache. The second user message can refer to the message carrying the changed content after the structural rearrangement. The changed content is the review context and code snippet corresponding to this call, and it is the only part of the key-value cache that needs to be recalculated in each model call.

[0164] Key-value caching refers to the cached key and value tensors of historical tokens during the decoding process in a large language model inference framework, used to avoid redundant calculations during subsequent token generation. Automatic prefix caching refers to an optimization mechanism where the inference framework identifies shared token prefixes between the input sequence and historical requests and directly reuses the corresponding key-value cache. Context window limitation refers to the maximum number of input tokens that a code review model can accept.

[0165] In this step, for multiple model calls within the same review dimension, the review input data for each call is constructed into two user messages: the first user message carries the review template content for that dimension, and the second user message carries the review context and corresponding code snippet for that dimension. Since the template content remains unchanged while the code snippet changes within the same dimension, the first user message remains consistent per token across multiple calls. In subsequent calls, the inference framework can directly reuse the key-value cache corresponding to the first user message through prefix matching, only needing to calculate the key-value cache corresponding to the second user message.

[0166] In one example, the message structure comparison before and after the structural rearrangement can be as follows: Before rearrangement, a single call contains one user message, which is composed of the review template content, review context, and code snippets; after rearrangement, a single call contains two user messages, the first user message containing only the review template content, and the second user message containing the review context and code snippets.

[0167] In another example, the second user message can be further split into two messages: one carrying the review context and the other carrying the code snippet. This allows the review context to be reused by prefix caching if there are shared parts within the same dimension. In yet another example, the static and dynamic population parts of the review template content can be further separated. The completely static template framework can be placed in the first user message, and the population content containing code block-specific information can be placed in the second user message, thereby maximizing the caching reuse scope of the first user message.

[0168] For example, the syntax review dimension requires calling the model for each of the seven code blocks. The syntax review template is placed in the first user message, and the syntax review context and code snippet corresponding to the i-th code block are placed in the second user message. On the first call, the inference framework computes the key-value caches for both messages; on the second call, the first user message is identical to the first, and the inference framework directly reuses its key-value cache, only computing the key-value cache for the second user message.

[0169] Furthermore, the control method for the amount of context input can be as follows: before constructing the input message sequence, the number of tokens in the first user message and the number of tokens in the second user message are counted respectively to ensure that the sum of the two does not exceed the context window limit of the code review model. If the target data segment in the second user message is too long, causing the sum to exceed the limit, the segment can be truncated or reverted to the minimum closed scope segment extraction method described in the above embodiment to regenerate more concise code element information.

[0170] This implementation method can reduce the inference overhead caused by repeated coding within the same review dimension and keep the template content consistent, thereby improving the processing efficiency and result consistency of multiple code review model calls; at the same time, by controlling the amount of context input to not exceed the window limit, semantic loss caused by input truncation can be avoided.

[0171] Furthermore, in practical applications, the aforementioned message structure rearrangement mechanism can be designed in conjunction with Token budget control to form a two-layer strategy of "Token budget control + Message structure rearrangement" to further improve the KV-Cache hit rate.

[0172] In a code review pipeline, there are numerous model calls with similar structures. For example, 10 functions are divided into 3 chunks (i.e., the code blocks obtained after the aforementioned block processing). Each chunk undergoes review across three dimensions: syntax, logic, and security, plus a final summary, resulting in a total of 3 × 3 + 1 = 10 model calls. The message structure for each call is as follows: the `system` message carries the system context (`system_context.md`), which is identical across all 10 calls; the `user` message carries the review template (`review_template.md`) and the code snippet to be reviewed. The review template is identical across the 3 chunks in the same dimension, while the code snippet to be reviewed differs for each chunk.

[0173] In mainstream inference frameworks (such as vLLM, SGLang, and TensorRT-LLM), the automatic prefix caching mechanism identifies shared prefixes and reuses their KV-Cache through a prefix matching algorithm of the token sequence. However, the default block caching mechanism only works for consecutive and completely identical token prefixes. If a shared prefix (inspection template) and a modified suffix (code snippet) are wrapped in the same user message, the inference framework cannot recognize it as a reusable prefix segment. This causes the entire prompt's KV-Cache to be recalculated on each call, resulting in a serious waste of GPU computing power and video memory.

[0174] To address the aforementioned issues, this embodiment employs a two-tiered strategy of "Token budget control + Message structure rearrangement." Token budget control refers to ensuring that the prompt in each call does not exceed the window limit under the constraint of a limited context window (e.g., 128K tokens), while simultaneously creating a stable token boundary for cache hits of shared prefixes. Message structure rearrangement refers to reorganizing the message array while ensuring that tokens do not exceed the window limit, splitting shared and variable content into different messages, enabling the prefix matching algorithm of the inference framework to identify and cache shared prefixes. The two are a sequential and collaborative relationship of "first ensuring no window exceedance, then optimizing the layout within the window": budget control provides a stable token boundary for structure rearrangement, and structure rearrangement utilizes the space created by budget control to expose shared prefixes in cache-friendly locations.

[0175] Specifically, the reordering principle is as follows: the original single user message is split into two. The first user message carries an inspection template (one for syntax, one for logic, and one for security), which is completely consistent across all chunks in the same dimension, becoming the anchor point for the prefix cache; the second user message carries the modified code snippet, which is the only part that needs to be recalculated in each call to the KV-Cache. This reordering method is consistent with the structure of "the first user message carrying the inspection template content, and the second user message carrying the inspection context and code snippet" in the aforementioned embodiment.

[0176] In one example, based on the rearrangement, budget control can be further applied to the token count of the two user messages in each call. For instance, before constructing the message sequence, the token counts of the first and second user messages are counted to ensure that their sum does not exceed the context window limit of the code review model. If the code fragment of the second user message is too long, causing the sum to exceed the limit, the code fragment is truncated, or a fallback to the minimum enclosed scope fragment extraction method described in the previous embodiments is used to regenerate more concise code element information.

[0177] Furthermore, in multi-round review scenarios, the review results and code context of the previous round need to be retained in subsequent rounds. To control the growth of the context window, historical code blocks can be compressed into summaries. Summary compression refers to re-incorporating the content of code blocks that have been fully entered in the previous round of review into the context in subsequent rounds in the form of a summary. The summary content can include a brief description of the issues found in the code block, a concise expression of the definitions of key symbols, and dependency information that is still relevant to the current review round.

[0178] For example, in the syntax review dimension, the model is invoked for each of the three chunks. In each invocation, the first user message carries the exact same syntax review template (fixed number of tokens), while the second user message carries the syntax review context and code snippet corresponding to that chunk. During the first invocation, the inference framework calculates the KV-Cache for all messages; during the second and third invocations, the first user message is identical to the previous one token-by-token, and the inference framework directly reuses its KV-Cache through prefix matching, only needing to calculate the KV-Cache corresponding to the second user message.

[0179] Through the aforementioned two-layer strategy of "Token budget control + Message structure rearrangement," budget control ensures that the prompt for each call remains within the context window, providing a stable token boundary for structure rearrangement. Structure rearrangement utilizes the space created by budget control to expose the shared prefix (review template) in a cache-friendly location, enabling the inference framework's automatic prefix caching mechanism to continuously reuse the KV-Cache of the first user message. These two strategies form a sequential collaborative relationship of "first ensuring no window overflow, then optimizing the layout within the window." When the number of code blocks is large, this reduces GPU computing power and memory consumption caused by repeated KV-Cache calculations, lowering the total time consumption of multiple model calls. Simultaneously, by controlling the growth of the context window through digest compression in multiple rounds of review, the review pipeline maintains stable inference efficiency and result consistency in large-scale code review scenarios.

[0180] Furthermore, in practical implementation, the code review model may frequently query symbolic information in the knowledge graph through tool calls during multiple rounds of calls. When processing multiple code blocks consecutively, the model may repeatedly query the same structure definitions or function call relationships due to a lack of memory of the queried content, resulting in redundant tool calls, which increases review time and wastes computational resources. If this redundant behavior is not monitored and quantified, developers will find it difficult to identify problems in the query strategy or model parameter settings in a timely manner, and optimization work can only rely on manual investigation afterward. Therefore, based on the above embodiments, after combining context information and target data as input to the code review model, the method may further include: monitoring the tool call sequence of the code review model during multiple calls, and counting the total number of tool calls and the number of deduplicated tool calls; calculating the deduplication rate based on the total number of tool calls and the number of deduplicated tool calls; and generating optimization suggestions for the context query strategy and / or model call parameters based on the comparison result of the deduplication rate and the preset deduplication threshold.

[0181] Here, "tool call" refers to a function call initiated by the code review model during the review process to query symbol definitions or relationships between symbols from external knowledge sources. "Tool call sequence" refers to a sequence formed by arranging all tool calls initiated by the code review model in chronological order over multiple calls. "Total tool call count" refers to the total number of tool calls in the tool call sequence. "Deduplicated tool call count" refers to the number of unique tool calls remaining after deduplicating the tool call sequence according to the query target.

[0182] Deduplication rate refers to an indicator used to quantify the proportion of redundant calls in a tool call sequence. It can be calculated as "Deduplication rate = 1 - Number of tool calls after deduplication / Total number of tool calls". The higher the deduplication rate, the more severe the redundant calls. The preset deduplication threshold refers to a pre-set deduplication rate threshold, used to determine whether the current level of redundancy requires triggering the generation of optimization suggestions.

[0183] Optimization suggestions can refer to recommendations generated based on a comparison between the deduplication rate and a preset deduplication threshold, used to guide adjustments to context query strategies or model invocation parameters. Adjustments to context query strategies may include adding deduplication constraints when generating query plans, or merging duplicate query items in the query plan; adjustments to model invocation parameters may include reducing the maximum allowed number of tool call rounds.

[0184] In one example, monitoring tool call sequences can be achieved by setting up a call logging intermediary layer between the code review model and the knowledge graph query tool. Each time the model initiates a tool call, it records the target symbol name and query type, forming a tool call sequence log. In another example, tool call records can be parsed from the inference framework's call log to extract the target parameters for each tool call.

[0185] For example, in 10 tool calls, the code review model queries the definition of the same structure 7 times and different symbols 3 times. The total number of tool calls is 10, and the number of tool calls after deduplication is 4. The deduplication rate is 1 - 4 / 10 = 60%.

[0186] Furthermore, there are multiple ways to compare the deduplication rate with the preset deduplication threshold and generate optimization suggestions. In one example, the preset deduplication threshold can be set to 50%: when the deduplication rate is below 30%, it is considered normal, and no optimization suggestions are generated; when the deduplication rate is between 30% and 50%, suggestions for optimizing keyword design are generated; when the deduplication rate is above 50%, suggestions for adjusting model call parameters are generated. In another example, only a single threshold can be set, and comprehensive optimization suggestions can be generated directly when the deduplication rate exceeds this threshold.

[0187] In some embodiments, the optimization suggestions may take the form of text prompts or structured parameter adjustment instructions. For example, when the deduplication rate exceeds 50%, suggestions may be generated such as "add deduplication constraints to query planning prompts" and "adjust the maximum number of tool call rounds from 10 to 5".

[0188] By monitoring and calculating the deduplication rate of tool call sequences in multiple code review model calls, the degree of duplicate tool calls is quantified into a comparable indicator. Then, based on thresholds, adjustment suggestions for query strategies or model parameters are generated, making context acquisition and code review model calls more aligned with actual review needs. This reduces redundant tool calls, lowers resource consumption caused by repeated retrieval and invalid inference, and makes context organization and code review model call configuration more stable during firmware code review.

[0189] Furthermore, in practical applications, the aforementioned tool call deduplication rate monitoring mechanism can be used to identify redundant behavior of the code review model in multiple rounds of calls and automatically generate optimization suggestions, transforming cost control from passive (i.e., only optimizing when the cost exceeds a preset value) to proactive monitoring and optimization suggestions.

[0190] Specifically, the monitoring system monitors the code review model's calls to a specific tool (such as "querying structure definitions") during multiple calls, identifying repeated calls to the same query target. The monitored objects can include the query type of the tool call (such as structure definition query, macro definition query, function call relationship query) and the symbol name of the query target.

[0191] During monitoring, the system counts the total number of tool calls and the number of deduplicated tool calls, and calculates the deduplication rate using the following formula: Dedup Rate = 1 - Unique Tool Calls / Total Tool Calls. Here, Unique Tool Calls refers to the number of deduplicated tool calls, i.e., the number of unique tool calls after deduplication based on query type and query target symbol name; Total Tool Calls refers to the total number of tool calls. A higher deduplication rate indicates a greater proportion of redundant calls.

[0192] The system's preset deduplication threshold rules are as follows: when the deduplication rate is below 30%, it is considered normal and no optimization suggestions are generated; when the deduplication rate is between 30% and 50%, suggestions to optimize the Prompt design are generated; when the deduplication rate is above 50%, a prompt indicating that the Agent parameter configuration needs to be improved is generated.

[0193] For example, if the system finds that the code review model queries "the same structure" (i.e., the same query type and the same target symbol) 7 out of 10 tool calls, then the total number of tool calls is 10. After deduplication, the number of tool calls is 4 (7 duplicate queries are counted as 1, plus the remaining 3 different queries), and the deduplication rate is 1 - 4 / 10 = 70%. If the deduplication rate exceeds 50%, the system automatically generates the following optimization suggestions: First, explicitly indicate in the Prompt that "this structure definition has been queried in the previous step"; Second, adjust the max_tool_rounds parameter to reduce the number of allowed tool call rounds.

[0194] In one example, the aforementioned monitoring and optimization suggestion generation can be performed by a separate monitoring module. This module continuously records tool call events during each model call in the code review pipeline and calculates the deduplication rate at the end of a preset statistical period, generating corresponding optimization suggestions based on the deduplication rate range. In another example, the monitoring module can calculate the deduplication rate in real time during model calls, triggering an alarm and outputting optimization suggestions once the deduplication rate exceeds a preset threshold.

[0195] Through the aforementioned production-level monitoring mechanism, cost control is transformed from a passive, post-hoc process of discovering excessive costs and then optimizing, to a proactive, real-time monitoring process during operation that generates optimization suggestions. This enables developers to promptly identify redundant behaviors in the code review model at the tool invocation level and adjust the Prompt design or Agent parameter configuration based on the system-generated suggestions. This reduces invalid and repetitive queries in subsequent reviews, lowers review time and computational resource consumption, and improves the overall operational efficiency of the firmware code review pipeline.

[0196] As can be seen from the above embodiments, the firmware code review method provided in this application solves the problems of strong coupling between code and hardware context, complex review dimensions, and confusing results in firmware development by using dynamic context injection, multi-dimensional review collaboration, and hardware characteristic verification, thereby improving the accuracy and efficiency of firmware code review. Specifically, in terms of context coverage, adaptive query planning dynamically obtains hardware constraint information based on the symbols actually referenced in the code and their correlation with protocol constraints, avoiding deployment failures caused by missing key information under static injection. In terms of review results, strict deduplication and priority protection mechanisms ensure that serious defects are not downgraded, and the final results are presented in layers according to severity level, reducing the burden of developer investigation. In terms of resource utilization, deduplication rate monitoring and Prompt structure rearrangement reduce LLM redundant calls and repeated inference overhead, reducing GPU computing power waste. In terms of hardware compatibility, by introducing symbol definitions and relationship information related to protocol constraints, the review model can identify logically valid but conflicting issues with hardware limitations, improving the firmware deployment success rate.

[0197] The firmware code review process is described in detail below through some embodiments. In some embodiments, Figure 2 A schematic diagram of the overall architecture of the firmware code review system provided in this application is shown below. Figure 2 As shown, the system adopts a layered pipeline architecture, which consists of a CLI entry layer, a pipeline orchestration layer, a core processing stage layer, and a support output layer from top to bottom. It fully covers the entire process of code review from task triggering to report generation. Each layer performs its own function and works together to achieve intelligent, high-precision, and low-cost firmware code review.

[0198] The top layer is the CLI entry point, with main.py as the program startup entry point. It provides two running modes: full file review and diff difference review. The diff mode further supports multiple difference input formats such as git diff, staged staging area, and pipe, which can adapt to different application scenarios such as full code review and incremental change review. It provides a unified task trigger entry and running mode configuration for the entire review process, flexibly adapting to the daily iteration and version review needs of firmware development.

[0199] The next level after the CLI entry is the CodeReviewPipeline orchestrator, which serves as the core scheduling unit of the entire review system. It is responsible for coordinating and managing the execution logic and data flow of the entire process. It breaks down the complete review task into five core processing stages that are connected in a serial manner: graph initialization, function extraction, diff change processing, three-dimensional parallel review, and hierarchical summary. It drives each stage to execute in a preset order and transmits the processed data, thereby realizing the standardized pipeline orchestration and control of the review process.

[0200] In the five core processing stages of pipeline orchestrator scheduling, the first stage is the graph initialization stage. This stage mainly performs the automatic graph DB construction operation, builds a code knowledge graph database based on the acquired hardware-related metadata and code basic information, accurately stores symbol definition information and symbol relationship information related to the target hardware platform protocol constraints, and builds a dedicated firmware code knowledge base, providing a core data foundation for subsequent intelligent query planning and contextual knowledge enhancement.

[0201] The second stage is the function extraction stage. This stage uses the tree-sitter syntax parsing tool to parse the target data (such as embedded firmware source code), completes function boundary identification and function unit splitting, and configures an LLM degradation processing mechanism. Different extraction processing strategies are adopted for functions of different code sizes to achieve the simplification of large functions and the complete extraction of small functions. While ensuring processing efficiency, the integrity of code element information is maintained, laying the code data foundation for accurate block review and adaptive query planning.

[0202] The third stage is the diff change processing stage. This stage performs function filtering and large function scope extraction operations. First, based on the code difference information, the scope of functions that have changed is filtered out. Then, the change location is identified for the filtered large functions, the smallest enclosed scope fragment corresponding to the change location is extracted, and this fragment is combined with the function signature and local variable declaration of the corresponding function. While ensuring the integrity of the review context, the amount of review data is reduced, adapting to the incremental review requirements of the diff mode and reducing the consumption of ineffective computing power.

[0203] The fourth stage is a three-dimensional parallel review stage. This stage conducts code reviews in parallel across three dimensions: Syntax, Logic, and Security. The review dimensions are divided according to the core requirements of firmware review, and each dimension is matched with its own unique review context information. This context information, combined with corresponding code snippets, forms differentiated review inputs, which are then fed into the code review model for parallel processing. This multi-dimensional review approach enhances the targeting and comprehensiveness of the review. This stage relies on a query planning module to achieve knowledge-based adaptive context retrieval, and the PromptBudget module to achieve fine-grained token budget control. Simultaneously, it optimizes the KV-Cache hit rate based on Prompt structure rearrangement, and uses a Dedup deduplication engine to monitor tool call redundancy and optimize deduplication of problem results. This approach accurately supplements the hardware protocol context, ensures review accuracy, and controls token consumption and model inference costs, achieving a balance between review quality and computational efficiency.

[0204] The fifth stage is the hierarchical aggregation stage. This stage employs a hierarchical aggregation mechanism from Sub-Summary to SummaryReport. First, preliminary sub-aggregations are performed on the review results for each of the three dimensions, and then these are integrated to generate a global review report. During the aggregation process, a multi-dimensional result deduplication and priority protection mechanism is strictly implemented. Issue records for each dimension undergo standardized fingerprint generation, redundant issue merging, highest priority locking, and hierarchical sorting. Finally, a standardized hierarchical review report in Markdown format is output, clearly distinguishing between three categories of issues: blocking merging, suggested fixes, and optional optimizations, presenting the final code review results completely and accurately.

[0205] Furthermore, Figure 3 This is a flowchart illustrating the single-file review process in firmware code review, as provided in an embodiment of this application. Figure 3 As shown, this process takes a single source code file as the starting point and executes the entire processing logic in a serial pipeline manner, including preprocessing, function extraction, change scope filtering, code sharding, multi-dimensional parallel review, and hierarchical summary output. It can adapt to both full file review and incremental diff review modes.

[0206] The process begins by reading the source file, performing language detection and prompt word verification in sequence, and then starting the graph_build module to locate the root directory of the git repository and automatically build a code knowledge base. This completes the storage of hardware-related metadata such as structures, macros, and global symbols, providing underlying knowledge support for subsequent adaptive context queries.

[0207] Next, the function extraction stage begins. The tree-sitter tool is used first to perform accurate syntax parsing of the code and generate a list of functions. If parsing fails, the LLM is automatically called to complete function identification and output a JSON-formatted function list, thus achieving stable function unit splitting under different code scenarios.

[0208] If the current mode is diff review, the DiffParser will parse the code change hunk, filter out the set of functions that have changed, and generate additional contextual hints for non-function-level changes such as macros and global variables. Then, the DiffScopeExtractor will differentiate between large and small functions and perform different processing. For large functions with more than 200 lines, the smallest enclosing scope chain will be searched upwards using the AST, and only the changed scope fragment, function signature, local variables and scope metadata will be retained. Small functions will be extracted directly and completely, and the code artifacts carrying metadata, original line numbers and precise diff markers will be uniformly output.

[0209] After the code snippet processing is completed, the system enters the function selection stage. The system summarizes the set of functions to be reviewed and processes them into chunks according to the preset chunk size. In the example, 28 functions are divided into chunks of 4 functions each, in order to control the input volume of a single LLM call and adapt to the token budget constraint.

[0210] After being sharded, the code tasks are scheduled by the ThreadPoolExecutor, which simultaneously initiates parallel reviews in three dimensions: Syntax, Logic, and Security. Within each dimension, query planning, knowledge base context injection, and LLM review are executed sequentially. Different review dimensions are matched with a suitable subset of context to avoid irrelevant symbol information interfering with model judgment.

[0211] All multi-dimensional review results from all blocks are summarized in the summary_report module. This module is set with a dynamic summary strategy. When the number of blocks is no more than 6, the results are directly merged. When the number of blocks exceeds 6, sub-summaries are first performed in units of 6 blocks, and then the global summary is completed. During the summary process, issue fingerprint deduplication and severity level protection are performed simultaneously.

[0212] Finally, the system outputs a standardized Markdown review report based on three priority levels: Must Fix (blocking merging), Should Fix (suggested fixes), and Niceto Have (optional optimizations). The report will retain the source of the problem, details of the original code, and corresponding fix guidelines.

[0213] Furthermore, in some examples, Figure 4 This is a schematic diagram illustrating the process of obtaining context information provided in an embodiment of this application, such as... Figure 4 As shown, this process relies on LLM to complete adaptive query planning and combines a knowledge graph database to realize the automatic collection and assembly of code context, providing complete input materials for subsequent code review models, while also being compatible with degradation processing logic when the knowledge base is unavailable.

[0214] The process starts with the divided code chunk as input, calls the LLM query planning module corresponding to query_planning.md, and the model automatically identifies the content to be retrieved in the current code block, outputs a JSON-formatted query list containing information on structures, macros, symbols, function callers and callees, and clarifies the knowledge items to be retrieved subsequently.

[0215] The system performs batch retrieval operations based on the generated query list. It first determines whether the graph DB knowledge graph database is available. If the database is normal, it calls the corresponding graph query tool to complete the query of information such as structure, macro, and function call relationship. When graph DB is unavailable, it automatically switches to the tree-sitter syntax parsing tool to complete the downgraded query locally, ensuring that the process is not interrupted.

[0216] The retrieved symbols and relational information will be injected into the review prompt. In the diff incremental review mode, an additional constraint instruction of "for understanding the impact only" will be added to limit the usage boundaries of the context and prevent irrelevant information from interfering with the review judgment.

[0217] The final assembled context will be sent to the LLM along with the code chunk for a one-time code review. The entire process pre-fetches all the necessary information, eliminating the need for repeated tool calls during the review phase. This reduces the computational overhead and latency caused by multiple rounds of interaction while ensuring sufficient context.

[0218] The firmware code review and system provided in this application relies on four mechanisms: knowledge base-driven adaptive query planning, multi-dimensional result deduplication and priority protection, tool call redundancy monitoring and optimization, and KV-Cache cache hit rate optimization. This constructs an intelligent, high-precision, and low-cost code review system adapted to firmware hardware constraints. Through knowledge graph enhancement, it achieves deep context awareness across files and related hardware protocols, solving the pain point that general review tools cannot identify firmware hardware compatibility defects. Through three-dimensional parallel review and differentiated context matching, it achieves comprehensive detection of code syntax, logic, and security risks. Through standardized result merging and hierarchical output, it accurately distinguishes the severity level of defects, adapting to firmware version merging and management requirements. Through full-process computing power optimization and dynamic iteration mechanisms, it significantly reduces inference costs while ensuring review accuracy, overcoming the shortcomings of traditional firmware code review, which relies on manual labor, has low accuracy, poor efficiency, and high false negative rates. This improves the professionalism, accuracy, and efficiency of firmware code review and can be widely applied to firmware code iteration review and quality control scenarios on various hardware platforms.

[0219] Figure 5 A schematic diagram of the firmware code review system provided in this application is shown below. Figure 5 As shown, the firmware code review system 50 provided in this embodiment includes:

[0220] The acquisition module 501 is used to acquire the target data and corresponding hardware-related metadata of the firmware code to be reviewed. The hardware-related metadata includes symbol definition information and symbol relationship information related to the protocol constraints of the target hardware platform.

[0221] Parsing module 502 is used to parse the target data to obtain code element information;

[0222] Planning module 503 is used to generate a context query strategy based on code element information. The context query strategy includes multiple query items and the priority of each query item.

[0223] The query module 504 is used to perform queries on hardware-related metadata according to priority to obtain context information related to the target data;

[0224] The review module 505 is used to combine contextual information with target data as input to the code review model to obtain code review results.

[0225] In one possible implementation, the parsing module 502 can also be used to: identify function boundaries in the target data to obtain a function set consisting of multiple function units; count the number of lines of code for each function unit in the function set, identify function units with a number of lines of code greater than a preset threshold as large functions, and identify function units with a number of lines of code less than or equal to the preset threshold as small functions; identify the change position of large functions, extract the smallest enclosed scope fragment corresponding to the change position in the large function, and combine the smallest enclosed scope fragment with the function signature and local variable declarations of the large function to obtain the code element information corresponding to the large function; and extract the entire function from the small functions to obtain the code element information corresponding to the small functions.

[0226] In one possible implementation, the planning module 503 can also be used to: divide the code element information into blocks to obtain multiple code blocks; identify symbol references in each code block to obtain a set of symbols referenced in the code block; generate corresponding query items based on the type of each symbol in the symbol set; wherein, when the type of the symbol is a structure, macro, or type definition, a symbol definition query item is generated; when the type of the symbol is a function, a symbol relationship query item is generated; assign a priority to each query item, the priority being determined based on the reference frequency of the symbol corresponding to each query item in the code block and the degree of association between the symbol and the protocol constraint; and obtain a context query strategy based on all query items and the priority corresponding to each query item.

[0227] In one possible implementation, the query module 504 can also be used to: perform a query on hardware-related metadata according to the preset context input budget corresponding to the priority, obtain symbol information, and update the consumed context input after each query; when the accumulated consumed context input reaches the preset context input budget, stop executing the query for the remaining priority; and combine the obtained symbol information with the code element information to obtain context information.

[0228] In one possible implementation, the review module 505 can also be used to: divide the context information into dimensions to obtain a syntax review context, a logic review context, and a security review context; wherein, the syntax review context includes macro definitions and type definitions, the logic review context includes function call relationships and global variables, and the security review context includes pointer operations and metadata related to concurrency protection; combine the target data with the syntax review context, the logic review context, and the security review context respectively to obtain three sets of review input data; input the three sets of review input data into the code review model for parallel review processing to obtain code review results, which include syntax review results, logic review results, and security review results.

[0229] In one possible implementation, the review module 505 can also be used to: standardize each issue record in the syntax review results, logic review results, and security review results to obtain the issue fingerprint corresponding to each issue record; merge issue records with the same issue fingerprint to obtain merged issue records; the merged issue records are marked with source dimension information and original issue details; determine the final severity level of the merged issue records based on the initial severity level corresponding to each source dimension in the merged issue records; and sort the merged issue records after determining the final severity level by severity level to obtain the final review result.

[0230] In one possible implementation, the review module 505 can also be used to: determine the final severity level of the merged issue record as the highest level when the initial severity level corresponding to any source dimension is the highest level; accordingly, sort the merged issue records by severity level after determining the final severity level, and output the final review result, including: arranging the merged issue records by severity level from high to low as blocking merged issues, suggested repair issues and optional optimization issues, to obtain the final review result.

[0231] In one possible implementation, the review module 505 can also be used to: construct an input message sequence from the corresponding review input data for multiple model calls within the same review dimension, and perform structural rearrangement processing on the input message sequence. The structural rearrangement processing includes: placing the review template content corresponding to the review dimension in a first user message; placing the review context corresponding to the review dimension in the review input data, and the code fragment corresponding to the review input data in the target data, in a second user message; wherein the first user message remains unchanged in multiple model calls within the same review dimension, so that the inference framework corresponding to the code review model reuses the key-value cache corresponding to the first user message; the context input amount of the first user message and the second user message is less than or equal to the context window limit of the code review model.

[0232] In one possible implementation, the review module 505 can also be used to: monitor the tool call sequence of the code review model during multiple calls, and count the total number of tool calls and the number of deduplicated tool calls; calculate the deduplication rate based on the total number of tool calls and the number of deduplicated tool calls; and generate optimization suggestions for context query strategies and / or model call parameters based on the comparison result of the deduplication rate and the preset deduplication threshold.

[0233] The firmware code review system provided in this embodiment can execute the methods provided in the above method embodiments. Its implementation principle and technical effect are similar, and will not be described in detail here.

[0234] Figure 6 A schematic diagram of the structure of the electronic device provided in this application. Figure 6 As shown, the electronic device 60 provided in this embodiment includes at least one processor 601 and a memory 602. Optionally, the device 60 further includes a communication component 603. The processor 601, memory 602, and communication component 603 are connected via a bus 604.

[0235] In a specific implementation, at least one processor 601 executes computer execution instructions stored in memory 602, causing at least one processor 601 to perform the above-described method.

[0236] The specific implementation process of processor 601 can be found in the above method embodiments, and its implementation principle and technical effect are similar. It will not be repeated here.

[0237] In the above embodiments, it should be understood that the processor can be a Central Processing Unit (CPU), or other general-purpose processors, digital signal processors (DSPs), application-specific integrated circuits (ASICs), etc. The general-purpose processor can be a microprocessor or any conventional processor. The steps of the method disclosed in this invention can be directly implemented by a hardware processor, or implemented by a combination of hardware and software modules within the processor.

[0238] The memory may include random access memory (RAM) and may also include non-volatile memory (NVM), such as at least one disk storage device.

[0239] The bus can be an Industry Standard Architecture (ISA) bus, a Peripheral Component Interconnect (PCI) bus, or an Extended Industry Standard Architecture (EISA) bus, etc. Buses can be categorized as address buses, data buses, control buses, etc. For ease of illustration, the buses shown in the accompanying drawings are not limited to a single bus or a single type of bus.

[0240] This application also provides a computer program product, including a computer program that, when executed by a processor, implements the above-described method.

[0241] This application also provides a computer-readable storage medium storing computer-executable instructions, which, when executed by a processor, implement the above-described method.

[0242] The aforementioned readable storage medium can be implemented by any type of volatile or non-volatile storage device or a combination thereof, such as static random access memory (SRAM), electrically erasable programmable read-only memory (EEPROM), erasable programmable read-only memory (EPROM), programmable read-only memory (PROM), read-only memory (ROM), magnetic storage, flash memory, magnetic disk, or optical disk. The readable storage medium can be any available medium accessible to a general-purpose or special-purpose computer.

[0243] An exemplary readable storage medium is coupled to a processor, enabling the processor to read information from and write information to the readable storage medium. Of course, the readable storage medium can also be a component of the processor. The processor and the readable storage medium can reside in an Application Specific Integrated Circuit (ASIC). Alternatively, the processor and the readable storage medium can exist as discrete components in the device.

[0244] The division of units is merely a logical functional division; in actual implementation, there may be other division methods. For example, multiple units or components may be combined or integrated into another system, or some features may be ignored or not executed. Furthermore, the coupling or direct coupling or communication connection shown or discussed may be indirect coupling or communication connection through some interfaces, devices, or units, and may be electrical, mechanical, or other forms.

[0245] The units described as separate components may or may not be physically separate. The components shown as units may or may not be physical units; that is, they may be located in one place or distributed across multiple network units. Some or all of the units can be selected to achieve the purpose of this embodiment according to actual needs.

[0246] In addition, the functional units in the various embodiments of the present invention can be integrated into one processing unit, or each unit can exist physically separately, or two or more units can be integrated into one unit.

[0247] If a function is implemented as a software functional unit and sold or used as an independent product, it can be stored in a computer-readable storage medium. Based on this understanding, the technical solution of this invention, or the part that contributes to the prior art, or a part of the technical solution, can be embodied in the form of a software product. This computer software product is stored in a storage medium and includes several instructions to cause a computer device (which may be a personal computer, server, or network device, etc.) to execute all or part of the steps of the methods of the various embodiments of this invention. The aforementioned storage medium includes various media capable of storing program code, such as USB flash drives, portable hard drives, read-only memory (ROM), random access memory (RAM), magnetic disks, or optical disks.

[0248] Those skilled in the art will understand that all or part of the steps of the above-described method embodiments can be implemented by hardware related to program instructions. The aforementioned program can be stored in a computer-readable storage medium. When executed, the program performs the steps of the above-described method embodiments; and the aforementioned storage medium includes various media capable of storing program code, such as ROM, RAM, magnetic disks, or optical disks.

[0249] It should be understood that the terms “comprising” and “having” and any variations thereof used in this application are intended to cover but not exclude inclusion. For example, a product or device that includes a series of components is not necessarily limited to those components that are explicitly listed, but may include other components that are not explicitly listed or that are inherent to such product or device.

[0250] As used in this application, the term "module" means any known or subsequently developed hardware, software, firmware, artificial intelligence, fuzzy logic, or combination of hardware and / or software code capable of performing the functions associated with that element.

[0251] Finally, it should be noted that other embodiments of the invention will readily occur to those skilled in the art upon consideration of the specification and practice of the invention disclosed herein. This invention is intended to cover any variations, uses, or adaptations of the invention that follow the general principles of the invention and include common knowledge or customary techniques in the art not disclosed herein, and is not limited to the precise structures described above and shown in the accompanying drawings, and various modifications and changes can be made without departing from its scope.

Claims

1. A firmware code review method, characterized in that, include: Obtain the target data and corresponding hardware-related metadata of the firmware code to be reviewed. The hardware-related metadata includes symbol definition information and symbol relationship information related to the protocol constraints of the target hardware platform. The target data is parsed to obtain code element information; Based on the code element information, a context query strategy is generated, which includes multiple query items and the priority of each query item. Based on the priority, a query is performed on the hardware-related metadata to obtain context information related to the target data; The context information is combined with the target data and used as input to the code review model to obtain the code review result.

2. The method according to claim 1, characterized in that, The step of parsing the target data to obtain code element information includes: The target data is subjected to function boundary identification to obtain a function set consisting of multiple function units; For each function unit in the function set, the number of lines of code is counted. Function units with a number of lines of code greater than a preset threshold are identified as large functions, and function units with a number of lines of code less than or equal to the preset threshold are identified as small functions. The change location of the large function is identified, the smallest enclosed scope fragment corresponding to the code change location in the large function is extracted, and the smallest enclosed scope fragment is combined with the function signature and local variable declaration of the large function to obtain the code element information corresponding to the large function; The small function is extracted as an integer to obtain the code element information corresponding to the small function.

3. The method according to claim 1, characterized in that, The generation of a context query strategy based on the code element information includes: The code element information is divided into blocks to obtain multiple code blocks; For each code block, identify symbol references to obtain the set of symbols referenced in the code block; Based on the type of each symbol in the symbol set, a corresponding query item is generated; wherein, when the type of the symbol is a structure, macro, or type definition, a symbol definition query item is generated; when the type of the symbol is a function, a symbol relationship query item is generated. Each query item is assigned a priority, which is determined based on the frequency of reference of the symbol corresponding to each query item in the code block and the degree of association between the symbol and the protocol constraints; The context query strategy is derived based on all query items and the priority of each query item.

4. The method according to claim 1, characterized in that, The step of querying the hardware-related metadata according to the priority to obtain context information related to the target data includes: Based on the preset context input quantity budget corresponding to the priority, a query is performed on the hardware-related metadata to obtain symbol information, and the consumed context input quantity is updated after each query; When the accumulated consumed context input reaches the preset context input budget, the execution of queries with remaining priority is stopped; The symbol information obtained from the query is combined with the code element information to obtain the context information.

5. The method according to any one of claims 1-4, characterized in that, The step of combining the context information with the target data as input to the code review model to obtain the code review result includes: The context information is divided into three dimensions: syntax review context, logic review context, and security review context. The syntax review context includes macro definitions and type definitions, the logic review context includes function call relationships and global variables, and the security review context includes pointer operations and metadata related to concurrency protection. The target data is combined with the syntax review context, the logic review context, and the security review context respectively to obtain three sets of review input data; The three sets of review input data are respectively input into the code review model for parallel review processing to obtain code review results, which include syntax review results, logic review results, and security review results.

6. The method according to claim 5, characterized in that, The method further includes: Each issue record in the syntax review results, logic review results, and security review results is standardized to obtain the issue fingerprint corresponding to each issue record; Problem records with the same problem fingerprint are merged to obtain a merged problem record; the merged problem record is marked with source dimension information and original problem details; The final severity level of the merged issue record is determined based on the initial severity level corresponding to each source dimension in the merged issue record. The merged issue records, after determining the final severity level, are sorted hierarchically according to severity level to obtain the final review results.

7. The method according to claim 6, characterized in that, The step of determining the final severity level of the merged issue record based on the initial severity level corresponding to each source dimension in the merged issue record includes: When the initial severity level corresponding to any source dimension is the highest level, the final severity level of the merged problem record is determined to be the highest level; Accordingly, the process of sorting the merged issue records by severity level after determining the final severity level and outputting the final review results includes: The merge issues are recorded and arranged in a hierarchical manner from highest to lowest severity as blocking merge issues, suggested repair issues, and optional optimization issues, thus obtaining the final review results.

8. The method according to claim 5, characterized in that, The step of inputting the three sets of review input data into the code review model for parallel review processing includes: For multiple model calls within the same review dimension, the corresponding review input data is constructed into an input message sequence, and the input message sequence is subjected to structural rearrangement processing, which includes: Place the review template content corresponding to the review dimension in the first user message; The review context corresponding to the review dimension in the review input data and the code snippet corresponding to the review input data in the target data are placed in the second user message; Specifically, the first user message remains unchanged across multiple model calls within the same review dimension, so that the inference framework corresponding to the code review model can reuse the key-value cache corresponding to the first user message; the context input of the first user message and the second user message is less than or equal to the context window limit of the code review model.

9. The method according to any one of claims 1-4, characterized in that, After combining the context information with the target data as input to the code review model, the method further includes: The tool call sequence of the code review model during multiple calls is monitored, and the total number of tool calls and the number of deduplicated tool calls are counted. The deduplication rate is calculated based on the total number of tool calls and the number of deduplicated tool calls. Based on the comparison between the deduplication rate and the preset deduplication threshold, optimization suggestions are generated for the context query strategy and / or model call parameters.

10. A firmware code review system, characterized in that, include: The acquisition module is used to acquire the target data and corresponding hardware-related metadata of the firmware code to be reviewed. The hardware-related metadata includes symbol definition information and symbol relationship information related to the protocol constraints of the target hardware platform. The parsing module is used to parse the target data to obtain code element information; The planning module is used to generate a context query strategy based on the code element information. The context query strategy includes multiple query items and the priority of each query item. The query module is used to perform a query on the hardware-related metadata according to the priority, and obtain context information related to the target data; The review module is used to combine the context information with the target data as input to the code review model to obtain the code review result.