Formal verification method based on LLM and electronic equipment

By constructing a function call graph and local context information, combined with a large language model and a multi-agent repair mechanism, the problem of long writing time for Rust code formal specifications is solved, and automated, accurate and efficient formal verification is achieved.

CN123138083APending Publication Date: 2026-11-20ALIPAY (HANGZHOU) INFORMATION TECH CO LTD
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202611200125.8
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-08-07
Publication Date
2026-11-20

AI Technical Summary

Technical Problem

Existing technologies require deep expertise and are extremely time-consuming to write formal specifications for Rust code, resulting in high human resource costs and hindering the large-scale application of formal verification in industry.

Method used

By constructing a function call graph and adopting a bottom-up traversal order, local context information is built for each function. Formal specifications are generated using a large language model, and a multi-agent collaboration mechanism is used to fix the problem when verification fails.

Benefits of technology

It enables the automatic generation of complete formal specifications for system-level code without the need for manual pre-definition of contracts, improving the accuracy and efficiency of specification generation and reducing labor costs.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN123138083A_ABST
    Figure CN123138083A_ABST
Patent Text Reader

Abstract

The specification provides an LLM-based formal verification method, which constructs a function call graph of target code, processes each function in turn in a bottom-up traversal order, constructs local context information containing direct call relationships for each target function, and inputs the prompt word generated based on the context to the LLM to generate the formal specification of the target function by the LLM. This method can automatically generate a complete specification without manual predefinition of contracts, overcoming the problem of inter-module dependency coupling in system-level code, while avoiding irrelevant information interference through precise limitation of local context, effectively improving the automation level and specification quality of industrial code generation.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This specification relates to one or more embodiments in the field of artificial intelligence, and more particularly to a formal verification method and electronic device method and apparatus based on LLM. Background Technology

[0002] Formal verification is a technique that uses mathematical methods to prove that a program's behavior conforms to its design specifications. It is widely recognized as the gold standard for ensuring the correctness of software in high-security domains. In scenarios with extremely high reliability requirements, such as operating system kernels and financial trading systems, formal verification can provide more stringent correctness guarantees than testing.

[0003] In recent years, Rust has been increasingly adopted by high-security systems due to its memory-safe features. To further verify the functional correctness of Rust code, verification tools such as Verus have been developed. Verus allows developers to write formal specifications using a syntax highly consistent with Rust syntax, which lowers the barrier to verification to some extent.

[0004] However, writing correct formal specifications requires deep expertise and is extremely time-consuming. This bottleneck is particularly pronounced in industrial-grade system code. This high human resource cost severely hinders the large-scale application of formal verification in industry. Summary of the Invention

[0005] This specification aims to disclose a formal verification solution based on a large language model. This solution can automatically generate complete formal specifications for system-level code and efficiently and accurately complete the repair when verification fails through a multi-agent collaboration mechanism.

[0006] According to a first aspect of the embodiments of this specification, a formal verification method based on LLM is provided, comprising: Construct a function call graph corresponding to the target code to be verified; wherein, the nodes on the function call graph represent functions contained in the target code; and the edges on the function call graph represent the call relationships between the functions connected by the edges. By traversing from the leaf nodes to the root node in the function call graph, the functions corresponding to each node in the function call graph are sequentially identified as target functions to be verified. Context information for generating formal specifications is then constructed for the target functions based on the function call graph. This context information includes local context information related to other functions that have a direct call relationship with the target function. Based on the context information, a cue word is constructed to generate a formal reduction for the objective function, and the cue word is input into the LLM so that the LLM can generate a formal reduction for the objective function based on the context information contained in the cue word; wherein, the formal reduction is used to perform formal verification of the objective function.

[0007] Optionally, the target code includes a system-level code library; wherein the system-level code library contains code segments corresponding to different functional modules; and the call relationships represented by the edges in the function call graph include function call relationships across functional modules. Construct a function call graph corresponding to the target code to be verified, including: The code segments contained in the code library are parsed sequentially using static analysis tools, and the calling relationships between functions contained in the code segments are determined based on the parsing results; wherein, the calling relationships include the function calling relationships between functions contained in the same code segment; and the cross-functional module function calling relationships between functions contained in different code segments; Based on the determined calling relationships, a function call graph corresponding to the code library is constructed.

[0008] Optionally, the context information constructed for the target function includes first context information related to the caller function and second context information related to the callee function; wherein, the caller function refers to the function that calls the target function; and the callee function refers to the function called by the target function. Based on the function call graph, context information for generating formal specifications is constructed for the target function, including: Determine the upstream and downstream neighbor nodes in the function call graph that have a direct neighbor relationship with the node corresponding to the target function; wherein, the upstream neighbor node represents the caller function; and the downstream neighbor node represents the callee function; First context information related to the caller function and second context information related to the callee function are obtained respectively. Based on the obtained first context information and second context information, context information with a two-way perspective for generating formal specifications is constructed for the target function.

[0009] Optionally, the first context information associated with the caller function includes code snippets associated with the caller function; the second context information associated with the callee function includes at least some information contained in the formal specification already generated for the callee function.

[0010] Optionally, the formal specification includes a contract and a proof; wherein, the contract describes preconditions and postconditions; the preconditions refer to the conditions that need to be met when initiating a function call; the postconditions refer to the conditions that need to be met when the execution result is generated after the function call is completed; the proof is used to verify whether the actual running behavior of the function conforms to the preconditions and postconditions described by the contract; The second context information associated with the callee function includes the contract contained in the formal specification that has been generated for the callee function.

[0011] Optionally, the formal reduction generated by the LLM for the objective function includes multiple sets of candidate formal reductions; The method further includes: Obtain multiple sets of candidate formal reductions generated by the LLM for the objective function; The candidate formal specifications from the multiple sets are further input into the validator, which performs formal verification on the objective function based on the candidate formal specifications from the multiple sets, and generates verification scores for each candidate formal specification from the multiple sets based on the verification results; wherein, the verification scores are used to represent the generation quality of the candidate formal specifications; The candidate formal reduction with the highest verification score is determined as the target formal reduction generated by the objective function for formal verification of the objective function.

[0012] Optionally, the formal verification includes several verification items related to the formal verification objective; Validation scores are generated for each of the multiple groups of candidate formal specifications, including: Based on the verification results, the first number of verification items that pass the verification for each of the multiple groups of candidate formal specifications is counted. Based on the first number of verified items included in the multiple sets of candidate formal specifications, a verification score is generated for each of the multiple sets of candidate formal specifications.

[0013] Optionally, before generating verification scores for each of the multiple sets of candidate formal specifications based on a first number of verified items included in the multiple sets of candidate formal specifications, the method further includes: Based on the verification results, the second number of verification items that failed the verification of the candidate formal specifications in each of the multiple groups is counted. Based on the first number of validated items included in the multiple sets of candidate formal specifications, validation scores are generated for each of the multiple sets of candidate formal specifications, including: Based on the first number of verified items that have passed verification and the second number of verified items that have failed verification contained in the multiple sets of candidate formal specifications, verification scores are generated for the multiple sets of candidate formal specifications respectively.

[0014] Optionally, the verifier includes an SMT solver.

[0015] Optionally, the method further includes: Determine whether the target formal specification contains any verification items that have not yet passed verification; If the target formal specification has any verification items that have not yet passed verification, the target formal specification is further input into a repairer built based on an LLM agent, so that the repairer can repair the target formal specification.

[0016] Optionally, the repairer built based on the LLM agent includes a first repairer built based on the LLM agent for repairing the contract contained in the target formal specification; and a second repairer built based on the LLM agent for repairing the proof contained in the target formal specification. The target formal reduction is input into a repairer built on an LLM agent, so that the repairer repairs the target formal reduction, including: The target formal specification is input into the first repairer built on an LLM agent, so that the first repairer can repair the contract contained in the target formal specification. In response to the completion of the repair of the contract contained in the target formal specification by the first repairer, the target formal specification is further input into the second repairer built on the LLM agent so that the second repairer can repair the proof contained in the target formal specification.

[0017] Optionally, the first repairer adopts a dual LLM agent architecture; the first repairer includes: a first LLM agent; and a second LLM agent; wherein, the first LLM agent is used to evaluate the consistency of the code semantics of the contract and the target function; the second LLM agent is used to repair the contract based on the repair suggestions output by the first LLM agent when the code semantics of the contract and the target function are inconsistent; The target formal specification is input into the first repairer built on an LLM agent, so that the first repairer repairs the contract contained in the target formal specification, including: The formal specification of the target and the code related to the target function are input into the first LLM agent, so that the first LLM agent can evaluate the consistency of the code semantics of the contract and the target function, and output a repair suggestion for the contract if the code semantics of the contract and the target function are inconsistent. The target formal specification and the repair suggestion are further input into the second LLM agent, so that the second LLM agent can repair the contract contained in the target formal specification based on the repair suggestion.

[0018] Optionally, the unverified verification items existing in the target formal specification include proofs that the verifier failed to verify; The second repairer employs a multi-LLM agent architecture; the second repairer includes: a third LLM agent, an LLM agent pool composed of multiple fourth LLM agents, and a fifth LLM agent; wherein, the third LLM agent is used to classify the verification failure types of the verification failure proofs included in the target formal specification, and selects a fourth LLM agent from the accessed LLM agent pool that matches the verification failure type based on the classification result; the fourth LLM agent is used to repair the verification failure proofs corresponding to the verification failure type that matches it, and generates a repair plan for repairing the verification failure proofs; the fifth LLM agent is used to repair the verification failure proofs based on the repair plan generated by the fourth LLM agent; The target formal specification is input into the second repairer built on an LLM agent, so that the second repairer repairs the proof contained in the target formal specification, including: The target formal specification, the code related to the target function, and the error message output by the verifier related to the proof of the failure of the target formal specification are input to the third LLM agent, so that the third LLM agent can classify the proof failure type of the proof of the failure of the target formal specification, and select a fourth LLM agent that matches the proof failure type from the pool of connected LLM agents based on the classification result. After the third LLM agent selects a fourth LLM agent from the pool of connected LLM agents that matches the verification failure type, the target formal reduction, the code related to the target function, and the error message output by the verifier related to the verification failure proof of the target formal reduction are further input to the fourth LLM agent, so that the fourth agent can repair the verification failure proof corresponding to the verification failure type and generate a repair plan for repairing the verification failure proof; The formal specification of the objective function, the code associated with the objective function, and the repair plan are further input into the fifth LLM agent, so that the fifth LLM agent can repair the proof that failed to be verified based on the repair plan generated by the fourth LLM agent.

[0019] Optionally, the fifth LLM agent is used to repair the proof that failed to be verified based on the repair plan generated by the fourth LLM agent, according to a preset repair round; The second repairer also includes a sixth LLM agent; wherein the sixth LLM agent is used to delete redundant statements generated during the iterative repair process in the proof that the verification failed, and to regenerate the proof contained in the target formal specification based on the code semantics of the target function; The method further includes: If the fourth LLM agent reaches the maximum number of iterations in repairing the failed proof, and the verifier still fails to verify the proof, then the target formal specification after iterative repair and the code related to the target function are further input into the sixth LLM agent. The sixth LLM agent then removes redundant statements generated during the iterative repair process from the failed proof and regenerates the proof contained in the target formal specification based on the code semantics of the target function.

[0020] Optionally, the target code includes Rust code; correspondingly, the system-level codebase includes a system-level Rust codebase.

[0021] According to a second aspect of the embodiments of this specification, an electronic device is provided, including one or more processors and a memory, wherein the memory stores a computer program, and the processor executes the computer program to implement the method described in any of the first aspects above.

[0022] According to a third aspect of the embodiments of this specification, a computer program product includes a computer program / instructions that, when executed by a processor, implement the method described in any of the first aspects above.

[0023] In the method described above, a function call graph is constructed, and functions are processed one by one in a traversal order from leaf nodes to root nodes. This ensures that when each function is processed, the specifications of the called functions it depends on have already been generated, thus decomposing the cross-module verification problem into a localized specification generation task. Simultaneously, by constructing local context information for each target function that includes other functions with which it has direct call relationships, instead of inputting the entire global context of the codebase into the model, interference from irrelevant information in specification generation is avoided, and the burden on the model to process long texts is reduced. These methods work together to enable this scheme to automatically generate complete formal specifications for system-level code without requiring any pre-defined contracts.

[0024] Furthermore, when the target code contains a system-level code library and the function call relationships include cross-functional module calls, static analysis tools can be used to parse each code segment in the code library. This allows for the automatic identification of function call dependencies between different functional modules, and the constructed function call graph fully reflects the cross-module call structure in the code library. This enables the solution to be directly applied to industrial-grade software systems containing multiple functional modules without the need for manual analysis of module dependencies.

[0025] Furthermore, by identifying the upstream and downstream neighbor nodes in the function call graph that have direct neighbor relationships with the target function node, and obtaining the first context information related to the caller function and the second context information related to the callee function respectively, a bidirectional context information is constructed for the target function. This bidirectional perspective enables the LLM to understand, during specification generation, which functions call the target function and in what way, as well as which other functions the target function calls and what the contract boundaries of these functions are, thereby generating a specification that aligns with the overall design intent of the codebase. Figure 1 The agreed-upon regulations.

[0026] Furthermore, by incorporating code snippets related to the caller function as part of the first context information, LLM can understand the use case and expected behavior of the target function from the caller's perspective. By using the contract already generated by the callee function as part of the second context information, it can ensure that contract constraints on the call chain are correctly transmitted. These two types of information, each with its own emphasis and complementing each other, jointly improve the accuracy of specification generation.

[0027] Furthermore, when the formal specification includes a contract and a proof, the contract already generated for the callee function is used as part of the second context information. This allows the current function to know the preconditions that its downstream function needs to meet when generating the specification, thereby ensuring the correctness of the calling relationship at the contract level.

[0028] Furthermore, by obtaining multiple sets of candidate formal specifications generated by LLM and having them verified one by one by a validator, and then scoring the candidate specifications based on the verification results and selecting the best one, this mechanism of multiple candidate generation plus validator scoring can screen out the highest quality specifications in the initial generation stage, reducing the workload of subsequent repair.

[0029] Furthermore, by generating a verification score based on the first number of verified items that pass verification, the score directly reflects the specification's performance in terms of logical integrity, providing an objective basis for the sorting and selection of specifications.

[0030] Furthermore, by generating verification scores for each group of candidate formal specifications based on a first number of verified items that passed verification and a second number of verified items that failed verification, the quality of the specification can be evaluated simultaneously from both positive and negative dimensions. Specifically, the first number positively reflects the completeness of the specification in terms of logical proof; the more verified items that passed verification, the more verification objectives the specification covered and all of them were confirmed by the verifier. Conversely, the second number negatively reflects the degree of defects in the specification; the more verified items that failed verification, the more logical gaps or errors exist in the specification. Compared to schemes that score based solely on the number of verified items that passed verification, this approach, by introducing the number of verified items that failed verification as a penalty factor in the scoring, can more accurately assess the quality differences between different specifications.

[0031] Furthermore, when the verifier includes an SMT solver, this solution can seamlessly integrate with existing SMT-based verification toolchains, demonstrating good compatibility.

[0032] Furthermore, by determining whether there are any unverified verification items in the target formal specification, and inputting them into a repairer built on an LLM agent for repair when such items exist, an automatic repair mechanism is provided on the basis of automatic generation, enabling the specification to gradually approach a fully verified state from an imperfect initial state through iteration.

[0033] Furthermore, by distinguishing the repairers into a first repairer for repairing contracts and a second repairer for repairing proofs, and by performing contract repair first and then proof repair, this cascaded repair sequence can prevent errors at the contract level from propagating to the proof repair stage, thereby improving repair efficiency.

[0034] Furthermore, by setting up a first LLM agent in the first repairer to evaluate the semantic consistency between the contract and the code, and a second LLM agent to repair based on repair suggestions when there is semantic inconsistency, a closed loop of "evaluation-diagnosis-modification" is formed, which can accurately locate semantic deviations in the contract and make targeted corrections.

[0035] Furthermore, by setting up a third LLM agent for classifying verification failure types, a pool of agents consisting of multiple fourth LLM agents for different failure types, and a fifth LLM agent for performing the repair in the second repairer, the classification and specialized repair of verification failure errors are achieved. The third LLM agent distributes errors to the fourth LLM agent, which is best suited to handle that type of error, which can significantly reduce the inference space for each repair and improve the success rate of the repair.

[0036] Furthermore, by setting up a sixth LLM agent to delete redundant statements and regenerate proofs after the iterative repair reaches its limit, a structural reset can be performed when too many redundant assertions accumulate during the repair process. This avoids redundant information dragging down the performance of the SMT solver and provides an effective escape route for the repair process that has reached a deadlock.

[0037] Furthermore, when the target code is Rust code, this solution can be directly applied to the increasingly popular high-security systems developed using the Rust language, demonstrating good industrial applicability. Attached Figure Description

[0038] Figure 1 This is a schematic diagram of the architecture of an LLM-based formal verification system provided in an exemplary embodiment.

[0039] Figure 2 This is a flowchart illustrating a formal verification method based on a large language model, provided as an exemplary embodiment.

[0040] Figure 3 This is a schematic diagram of a function call graph and a bottom-up traversal order provided in an exemplary embodiment.

[0041] Figure 4 This is a schematic diagram of a bidirectional context construction provided in an exemplary embodiment.

[0042] Figure 5 This is a schematic diagram of the architecture of a multi-agent repair system provided in an exemplary embodiment.

[0043] Figure 6 This is an interactive timing diagram of the repair process provided in an exemplary embodiment.

[0044] Figure 7This is a schematic diagram of the structure of an electronic device provided in an exemplary embodiment.

[0045] Figure 8 This is a block diagram of an LLM-based formal verification apparatus provided in an exemplary embodiment. Detailed Implementation

[0046] To enable those skilled in the art to better understand the technical solutions in this specification, the technical solutions in the embodiments of this specification will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some embodiments of this specification, and not all embodiments. Based on the embodiments in this specification, all other embodiments obtained by those skilled in the art without creative effort should fall within the scope of protection of this specification.

[0047] The user information (including but not limited to user device information, user personal information, etc.) and data (including but not limited to data used for analysis, data stored, data displayed, etc.) involved in this manual are all information and data authorized by the user or fully authorized by all parties. The collection, use and processing of related data shall comply with the relevant laws, regulations and standards of the relevant countries and regions, and corresponding operation portals shall be provided for users to choose to authorize or refuse.

[0048] In recent years, Rust, with its ownership mechanism and borrow checker, has eliminated classic memory safety vulnerabilities such as buffer overflows and dangling pointers at the compilation stage. As a result, an increasing number of high-security systems are adopting Rust for development. To further verify the functional correctness of Rust code, verification tools such as Verus have been developed. Verus allows developers to write formal specifications using a syntax highly consistent with Rust syntax, thereby lowering the learning curve and integration cost of formal verification.

[0049] In practical applications, a complete formal specification usually consists of two parts: the contract and the proof.

[0050] The contract describes the boundaries of the function's input and output behavior through preconditions and postconditions.

[0051] Preconditions refer to the conditions that the caller must meet before initiating a function call, such as the input parameters must be non-empty or must be within a valid range of values.

[0052] Postconditions refer to the conditions that the execution result must meet after the function has finished executing, such as the return value must be within the expected range, or certain state variables must be updated correctly.

[0053] The proof section includes auxiliary structures such as loop invariants and assertions, which provide the necessary logical support for the underlying SMT solver, enabling it to reason and prove that the function body does indeed comply with its contract.

[0054] Writing correct formal specifications requires a strong foundation in mathematical logic and expertise in formal methods, and is extremely time-consuming. This bottleneck is particularly pronounced in industrial-grade system code.

[0055] For example, in the verification process of the seL4 operating system microkernel, writing formal specifications and proofs consumed dozens of person-years of work; in the X509-parser project, writing the specifications alone took about five months. This high human resource cost seriously hinders the large-scale application of formal verification in industry.

[0056] To alleviate the aforementioned bottlenecks, in recent years, technical attempts have emerged to automatically generate formal specifications using large language models. These methods typically employ a "generate-repair" paradigm: first, an initial specification is generated by the large language model, and then the specification is iteratively repaired based on error information fed back by the validator until the specification fully passes verification.

[0057] A typical existing approach is the partial reduction generation method, represented by AlphaVerus.

[0058] In this scheme, the contract is predefined manually, and the large language model is only responsible for generating the proof. The implicit premise of this setup is that the contract is relatively easy to write, or that the contract has already been written by domain experts in the early stages.

[0059] However, this premise often doesn't hold true in real-world industrial scenarios. For system-level codebases containing hundreds or thousands of functions, writing precise contracts for each function in advance is an extremely arduous task. Therefore, while this approach reduces the technical difficulty of automatic generation, it doesn't fundamentally solve the problem of the total workload of contract writing, significantly limiting its applicability.

[0060] Another existing approach attempts to take into account the dependencies between code modules when generating specifications.

[0061] This method relies on a manually predefined set of relationships to extract relevant code information when constructing the context, and then aggregates this information into a single file and inputs it into the large language model. This approach has two drawbacks.

[0062] Regarding information integrity, predefined relation sets are insufficient to cover the dynamically changing and evolving dependency structures in a real-world codebase. When the codebase undergoes refactoring, function signature adjustments, or changes in inter-module dependencies, the predefined relation sets need to be updated synchronously; otherwise, critical contextual information may be missing. Regarding information redundancy, simply concatenating information from multiple modules and inputting it into a large language model not only rapidly expands the input length, thus limiting its effectiveness within the model's context window, but may also introduce redundant information unrelated to the current objective function. This redundant information can interfere with the accuracy of reduction generation.

[0063] In terms of specification repair, most existing methods rely on repeated attempts using a single large language model. Since verifiers such as Verus are based on SMT (Simplified Language Modeling) solutions, their error reports exhibit cascading propagation characteristics.

[0064] Specifically, a low-level reduction error (such as a postcondition that does not match the actual behavior of the function) often triggers multiple seemingly unrelated verification error reports, such as loop invariant verification failures or assertions that cannot be proven. Faced with such mixed error feedback, a single model struggles to accurately determine which errors are the root cause and which are derivative results, and the repair process is prone to getting bogged down in ineffective iterations.

[0065] In addition, during the repeated repair process, the model tends to add new assertions and patch statements in order to pass the verification, resulting in a large amount of redundant information accumulating in the specification. This redundant information increases the inference burden of the SMT solver and makes verification more difficult.

[0066] In view of this, this specification provides a formal verification method based on a large language model. By constructing a function call graph of the target code and adopting a bottom-up traversal order, it constructs local context information containing direct call relationships for each function, thereby automatically generating complete formal specifications for system-level code without the need for manual pre-definition of contracts. Furthermore, when verification fails, a multi-agent collaborative repair mechanism is used to decouple the contract and proof and repair them sequentially, thereby improving repair efficiency and success rate.

[0067] The solution provided in this specification will be described in detail below with reference to the accompanying drawings.

[0068] Figure 1 This is an exemplary embodiment of a formal verification system based on a large language model.

[0069] like Figure 1 As shown, the system may include a code analysis server 11, a large language model server 12, a verification server 13, and a network 14. The code analysis server 11, the large language model server 12, and the verification server 13 interact with each other via the network 14.

[0070] The code analysis server 11 can consist of a single physical server or a cluster of virtual servers. During operation, the code analysis server 11 can run static analysis tools to parse the target codebase, construct a function call graph, and determine the bottom-up traversal order of each function. The code analysis server 11 can also construct a bidirectional context for the target function, containing caller and callee information, and generate prompt words based on this context.

[0071] The large language model server 12 may comprise one or more servers equipped with high-performance computing units (such as GPUs or TPUs). During operation, a trained large language model is deployed on the large language model server 12, which can generate corresponding formal specifications based on input prompts. The large language model server 12 can receive prompt requests from the code analysis server 11, generate candidate specifications, and return them to the code analysis server 11.

[0072] Verification server 13 can consist of a single physical server or a virtual server hosted in a cluster of hosts. During operation, verification server 13 runs verifiers such as Verus, which are used to perform formal verification on candidate specifications and output verification results, including the number of verified proof obligations, the number of errors, and error messages.

[0073] The network 14 connecting the code analysis server 11, the large language model server 12, and the verification server 13 can be either wired or wireless, depending on the communication methods supported by each server. For example, the servers can be located within the same data center and connected via a high-speed wired local area network; or they can be distributed in different geographical locations and communicate via the Internet.

[0074] In practical deployments, the three servers mentioned above can be deployed independently or combined on the same physical device or in the same cluster as needed. For example, in small-scale verification scenarios, code analysis, large language model inference, and verification functions can be deployed on the same high-performance server; in large-scale industrial verification scenarios, the three can be deployed separately to make full use of their respective computing resources.

[0075] Figure 2 This is a flowchart illustrating a formal verification method based on a large language model, provided as an exemplary embodiment. This method can be applied to... Figure 1 The code analysis server 11 shown or an electronic device integrated with code analysis capabilities. The method includes the following steps.

[0076] Step 201: Construct a function call graph corresponding to the target code to be verified; wherein, the nodes on the function call graph represent the functions contained in the target code, and the edges on the function call graph represent the call relationships between the functions connected by the edges.

[0077] In some embodiments, the target code may include a system-level code library. This system-level code library may contain code segments corresponding to different functional modules.

[0078] For example, the operating system kernel code can contain multiple functional modules such as memory management module, process scheduling module, file system module, and device driver module, with each functional module corresponding to one or more code segments.

[0079] The call relationships represented by the edges in the function call graph can include function call relationships across functional modules.

[0080] For example, a function in the process scheduling module might call a function in the memory management module to obtain the process's memory mapping information.

[0081] When constructing a function call graph, static analysis tools can be used to sequentially parse the code segments contained in the code repository and determine the call relationships between functions within those segments based on the parsing results. These call relationships can include function call relationships between functions within the same code segment, as well as cross-functional module function call relationships between functions within different code segments. Then, a function call graph corresponding to the code repository is constructed based on the determined call relationships.

[0082] Static analysis refers to extracting structural and semantic information from source code through lexical, syntactic, and semantic analysis without running the code.

[0083] Specifically, in practical applications, the open-source SCIP tool can be used to parse the Rust codebase.

[0084] It should be noted that SCIP (Source Code Intelligence Protocol) is a source code indexing protocol that can perform structured parsing of code and extract code elements such as function definitions, function calls, type definitions, and variable references, as well as their interrelationships.

[0085] Static analysis using the SCIP tool can accurately identify the definition location of each function and the called function corresponding to each function call.

[0086] When constructing a function call graph, the nodes in the graph... The edges in the graph represent the set of functions in the codebase. This represents a set of call relationships. If the function... The function was called Then there exists a slave node in the function call graph. Pointing to node directed edges .

[0087] For example, suppose function A calls function B, and function B calls function C. Then, the function call graph contains directed edges A→B and B→C. This directed graph structure fully reflects the dependencies between functions in the codebase.

[0088] In some embodiments, after constructing the function call graph, cycle detection can be performed on the function call graph to identify whether recursive calls exist in the codebase.

[0089] If recursive calls are detected, a pre-defined recursion handling strategy can be used to process them, such as generating a special specification template for the recursive function, or reminding the developer to handle it manually through comments.

[0090] Step 202: Using the traversal order from the leaf nodes to the root node on the function call graph, the functions corresponding to each node on the function call graph are sequentially determined as the target functions to be verified, and context information for generating formal specifications is constructed for the target functions based on the function call graph; wherein, the context information includes local context information related to other functions that have a direct call relationship with the target function.

[0091] It's important to note that leaf nodes are nodes in the function call graph that have no outgoing edges (i.e., do not call any other functions). The functions corresponding to these leaf nodes are the lowest-level functions; they do not depend on any other functions and therefore can be the first to be reduced and verified.

[0092] A root node is a node in the function call graph that has no incoming edges (i.e., is not called by any other function). The function corresponding to these root nodes is the top-level entry function.

[0093] The traversal order from leaf node to root node is essentially processing the functions from shallow to deep according to their dependency depth.

[0094] The reason for doing this is that when a function is processed, all the sub-functions it calls (i.e., downstream called functions) have already completed the reduction generation and can pass the verification. These generated reductions can serve as contextual information for the current function, helping the large language model understand which constraints need to be met when the current function calls sub-functions.

[0095] For example, suppose the function call graph contains the following call relationships: Function A calls functions B and C, function B calls function D, and function C calls functions E and F. The leaf nodes are D, E, and F (and possibly other nodes that do not call any functions). Following a bottom-up order, D, E, and F are processed first, then B and C (at which point the reduction of D, E, and F is complete), and finally A is processed (at which point the reduction of B and C is complete).

[0096] In this specification, the core feature of the context information constructed for each target function is "locality," which includes only information related to other functions that have a direct calling relationship with the target function, rather than including all global information of the entire codebase.

[0097] In some implementations, this local context information may include two types: first context information related to the caller function and second context information related to the callee function.

[0098] The caller function is the function that calls the target function.

[0099] For example, if function A calls function B, then from the perspective of the target function B, function A is the caller function.

[0100] In some embodiments, the first context information associated with the caller function may include a call point code snippet in the caller function that invokes the target function. This call point code snippet reflects how the target function is used in the actual code; for example, what parameters are passed in, how the return value is handled, and under what conditions it is invoked.

[0101] This information helps large language models understand the expected behavior of the objective function.

[0102] The callee function is the function called by the target function.

[0103] For example, if function B calls function C, then for the target function B, function C is the callee function.

[0104] In some embodiments, the second context information associated with the callee function may include at least some of the information already contained in the formal specification generated for the callee function, particularly the contract information of the callee function.

[0105] This information tells the large language model what preconditions the target function needs to meet when calling the callee function, and what postconditions it will guarantee after the callee function finishes execution.

[0106] In some embodiments, when constructing context information for the current target function, the upstream and downstream neighbor nodes that have a direct neighbor relationship with the node corresponding to the target function in the function call graph can be determined first. The upstream neighbor node represents the caller function, and the downstream neighbor node represents the callee function.

[0107] For example, in one instance, when it comes to the target function, a breadth-first neighbor search can be performed on the function call graph, strictly limiting the extraction to only the direct callers and direct callees of the target function.

[0108] Then, the first context information related to the caller function and the second context information related to the callee function can be obtained separately. Finally, based on the obtained first and second context information, context information with a two-way perspective can be constructed for the target function.

[0109] It is important to emphasize that the aforementioned two-way perspective means that the contextual information includes both "looking up" information (who calls the target function and how it is called) and "looking down" information (who the target function calls and what the contracts of these callees are).

[0110] This two-way perspective enables large language models to simultaneously understand the "use case" (expectations from the caller) and "dependency constraints" (requirements from the callee) of the target function when generating specifications, thereby generating specifications that align with the overall design of the codebase. Figure 1 The agreed-upon regulations.

[0111] In some embodiments, the first context information related to the caller function may further include the caller function's signature information, including the function name, parameter list, return type, etc. This information helps the large language model understand the overall functionality and calling context of the caller function.

[0112] In some embodiments, for the second context information related to the callee function, if the callee function has not yet generated a specification (e.g., when processing very early leaf nodes), a default specification template or an empty specification can be used as an alternative.

[0113] However, this situation is less common in bottom-up traversal order because leaf nodes do not depend on any functions, while their dependents will reference the specifications already generated by the leaf nodes in subsequent processing.

[0114] Step 203: Construct prompt words for generating formal specifications for the objective function based on contextual information, and input the prompt words into the large language model so that the large language model can generate formal specifications for the objective function based on the contextual information contained in the prompt words; wherein, the formal specifications are used to perform formal verification of the objective function.

[0115] In some implementation examples, the prompt word can be constructed by concatenating the source code of the target function, the first context information (caller's call point code fragment), and the second context information (callee's contract) into a natural language instruction and code text according to a preset template.

[0116] In practical applications, the prompt word may include the following: The role-setting instruction directs the large language model to act as a formal verification expert; The task description instruction directs the large language model to generate a complete formal specification containing the contract and proof for the objective function; Objective function source code; Caller call point code snippet; Callee contract information; Output format requirements instruct the large language model to output the specification according to the preset format.

[0117] In some embodiments, a large language model can generate multiple sets of candidate formal specifications.

[0118] To increase the diversity of candidate reductions, a higher temperature parameter can be set when calling the large language model. The temperature parameter is a hyperparameter that controls the randomness of the large language model's output. The higher the temperature value, the greater the diversity of the model's output; the lower the temperature value, the higher the determinism of the model's output.

[0119] In some embodiments, the temperature parameter can be set to 1.0 or higher to generate a variety of candidate specifications.

[0120] In some embodiments, after generating multiple sets of candidate formal specifications, these candidate specifications can be input into a validator for verification.

[0121] The verifier can perform formal verification of the objective function based on the candidate reduction and output the verification results. Then, based on the verification results, it can determine the candidate formal reduction that has passed the verification among the above multiple groups of candidate formal reductions.

[0122] In some embodiments, the formal verification described above may include several verification items related to the formal verification objective.

[0123] It should be noted that the verification item is the proof obligation related to formal verification. In practical applications, each verification item can correspond to a logical proposition that needs to be proven. These logical propositions together constitute the complete set of proof objectives when the verifier performs formal verification on the objective function.

[0124] In the actual verification process, the verifier generates several verification items for the reduction of the objective function, and each verification item represents an independent proof task.

[0125] For example, for functions containing loops, verification items can include the obligation to prove the initial validity, preservation, and validity of the loop invariant. The initial validity requirement is that the verifier proves the invariant is true before entering the loop; the preservation requirement is that the verifier proves that if the invariant is true at the start of any iteration, it remains true after the iteration ends; and the validity requirement is that the verifier proves that after the loop ends, the invariant implies a function postcondition or other logical conclusion. For functions containing assertions, verification items can include the obligation to prove that the assertion is necessarily true when the program reaches that point. Furthermore, for codebases containing multiple functions, verification items can also include cross-function contract consistency verification, such as whether the actual parameters passed by the caller satisfy the callee's preconditions. Different types of verification items examine the correctness of the specification from different dimensions, collectively ensuring the completeness and reliability of formal verification.

[0126] In some embodiments, when determining the candidate formal specifications that have passed verification among multiple groups of candidate formal specifications based on the verification results, the first number of verification items that have passed verification and the second number of verification items that have not passed verification can be counted based on the verification results.

[0127] In practical applications, the verifier outputs either "proven" (meaning the logical proposition corresponding to the verification item has been successfully proven to be true) or "unproven" (meaning the verifier cannot prove the proposition to be true, usually accompanied by an error message output).

[0128] Based on this, the first number of verified items can reflect which parts of the specification's logical proofs have been confirmed by the verifier, while the second number of verified items that failed verification can reflect the logical gaps in the specification that have not yet passed the verifier.

[0129] In this case, if the first number of validated items of any candidate formal specification is greater than zero and the second number of validated items that fail to pass verification is equal to zero, then the candidate formal specification is determined to have passed verification.

[0130] In other words, a candidate specification is considered to have passed formal verification if: at least one verification term is successfully proven (indicating that the verifier actually performed meaningful verification on the objective function, rather than skipping all verification steps due to incorrect input format), and no verification term fails verification (indicating that the specification satisfies the verifier's logical proof requirements in all dimensions). Only when both conditions are met is the candidate specification considered to have fully passed formal verification.

[0131] In some embodiments, the validator may also generate a verification score for each of the candidate formal specifications in the above groups based on the verification results.

[0132] The verification score is used to represent the generation quality of the candidate formal specifications.

[0133] In some embodiments, when generating a verification score for a candidate formal specification, the verification score may be generated based on a first number of verified items contained in the candidate formal specification.

[0134] It should be noted that since the first number of verified items reflects the specification’s performance in terms of logical integrity, the more items that pass verification, the more verification targets the specification covers and all of them pass verification. Therefore, the score generated based on this number can objectively quantify the quality of the specification’s generation.

[0135] For example, the first number can be directly used as the score value. The more first numbers there are, the higher the score, indicating that the specification covers more verification objectives and all of them pass verification. Therefore, its quality is better than that of a specification with fewer verification items.

[0136] In another embodiment, based on the first number of verified items that have passed verification, a second number of verified items that have failed verification can be taken into account to generate verification scores for the above-mentioned multiple groups of candidate formal specifications; for example, the scoring logic can be the first number minus the weighted value of the second number.

[0137] Based on this, when multiple candidate reductions pass verification, the candidate formal reduction with the highest verification score can be determined as the target formal reduction generated by the objective function for formal verification of the objective function, because this reduction performs optimally in terms of the number of verification terms that pass verification, representing the highest reduction quality. In some embodiments, the verifier may include an SMT solver.

[0138] Among them, the SMT (Satisfiability Modulo Theories) solver is an automatic theorem proving tool that can determine the satisfiability of first-order logic formulas under specific theoretical combinations.

[0139] In formal verification, the SMT solver transforms program code and specifications into logical formulas and then attempts to prove that the formulas are true on all possible execution paths.

[0140] If the solver can prove that the formula is a tautology, the verification passes; if the solver finds a counterexample (i.e., the formula is false under a certain execution path), the verification fails and an error message is output.

[0141] Please see Figure 3 , Figure 3 This is a schematic diagram of a function call graph and a bottom-up traversal order provided in an exemplary embodiment.

[0142] like Figure 3 As shown, the function call graph contains multiple function nodes, where nodes 301 to 306 are leaf nodes (no outgoing edges), nodes 307 to 310 are intermediate nodes, and nodes 311 and 312 are root nodes (no incoming edges). Following a bottom-up traversal order, leaf nodes 301 to 306 are processed first, then intermediate nodes 307 to 310, and finally root nodes 311 and 312. The graph uses arrows to indicate call relationships; for example, node 307 calls nodes 301 and 302, and node 308 calls nodes 303 and 304.

[0143] Please see Figure 4 , Figure 4 This is a schematic diagram of a bidirectional context construction provided in an exemplary embodiment.

[0144] like Figure 4 As shown, for the target function 401, its caller function 402 provides first context information 403 (call point code snippet), and its callee function 404 provides second context information 405 (callee contract). The context fusion module 406 fuses the first context information 403 and the second context information 405 to generate complete context information 407 with a bidirectional perspective. This complete context information 407 is input to the prompt word construction module 408 to generate large language model prompt words 409.

[0145] In some embodiments, continue to refer to Figure 2 After generating the target formal reduction in step 203, the method may further include: Determine if there are any unverified validation items in the target formal specification.

[0146] If the target formal specification has unverified validation items, it means that the current specification does not meet the conditions for passing the validation (i.e., the validated items are greater than zero, while the unverified items are equal to 0), and it has not passed the validation completely, so it needs to enter the repair phase.

[0147] At this point, the target formal reduction is input into the repairer built on the large language model agent, and the repairer repairs the target formal reduction.

[0148] In some embodiments, the repair process can be divided into two phases: a contract repair phase and a proof repair phase.

[0149] This cascaded repair sequence design stems from an in-depth analysis of the error propagation characteristics of validators.

[0150] For example, in a SMT-based validator, a contract-level error (such as a postcondition that doesn't match the function's actual behavior) can have a cascading effect, triggering multiple proof-level error reports. If all errors in the contract and proof are processed simultaneously, it's difficult to distinguish between the root causes and derivatives. By fixing the contract first, then the proof, the root cause of the contract-level error can be eliminated before proof repair, thus preventing these errors from interfering with proof repair.

[0151] Please see Figure 5 , Figure 5 This is a schematic diagram of the architecture of a multi-agent repair system provided in an exemplary embodiment.

[0152] like Figure 5 As shown, the repair system may include a first repairer 501 and a second repairer 502.

[0153] The first repairer 501 is used to repair contracts and can employ a dual-agent architecture.

[0154] The second repairer 502 is used to repair proofs and can employ a multi-agent architecture.

[0155] The first repairer 501 can adopt a dual large language model agent architecture, which may include a first LLM agent (Judge agent) and a second LLM agent (Aligner agent).

[0156] The Judge agent is used to evaluate the consistency between the code semantics of the contract and the objective function.

[0157] The Aligner agent is used to repair contracts based on repair suggestions output by the Judge agent when there is a semantic inconsistency between the contract and the objective function.

[0158] In some embodiments, when performing contract repair via the first repairer 501, the target formal specification and the code associated with the target function can be input into the Judge agent.

[0159] The Judge agent can determine whether the preconditions and postconditions of the contract accurately reflect the expected behavior of the code implementation based on the code implementation of the objective function, the contract in the current specification, and bidirectional context information.

[0160] The input to the Judge agent can be represented as: in, Represents the Judge agent. This represents the code implementation of the objective function. This represents the current reduction at the k-th iteration. Represents the bidirectional context of the objective function. Indicates the alignment status, with values ​​of "Aligned" or "Misaligned"; This indicates diagnostic feedback, including a detailed description of semantic differences and revision suggestions.

[0161] The Judge agent outputs the alignment state and diagnostic feedback. The alignment state can be selected as "Aligned" or "Aligned". When the alignment state is "Aligned", it means that the current contract is consistent with the code semantics and no modification is needed; the proof and repair phase can proceed. When the alignment state is "Aligned", it means that there is an inconsistency between the current contract and the code semantics, and modification is required.

[0162] In some embodiments, if the Judge agent determines that the contract is "misaligned," the target formal specification and diagnostic feedback can be further input into the Aligner agent. The Aligner agent can then modify the preconditions and / or postconditions of the contract in the current specification based on the revision suggestions in the diagnostic feedback.

[0163] The input to the Aligner agent can be represented as: in, This represents the Aligner agent. The meanings of the other parameters will not be elaborated further.

[0164] After the Aligner agent completes the revision, it can return to the Judge agent to re-evaluate semantic consistency. The above evaluation and revision steps are repeated until the Judge agent's decision is "aligned" or the number of iterations reaches the preset limit.

[0165] In some embodiments, the preset upper limit can be set to 3 times. If the Judge agent still determines that the alignment is "misaligned" when the preset upper limit is reached, it will directly enter the proof and repair phase and will not continue iterating.

[0166] After the contract is repaired, the proof repair phase can begin.

[0167] In some embodiments, validation items in the target formal specification that have not yet passed validation may include proofs that the validator has failed to validate. For example, in practical applications, these proofs may be validation failures due to loop invariants, assertions, or syntax errors.

[0168] In some implementation examples, the second repairer 502 described above may employ a multi-LLM agent architecture.

[0169] Specifically, the second repairer 502 may include a third LLM agent (Planner agent), an LLM agent pool (Repairer pool) consisting of multiple fourth LLM agents, a fifth LLM agent (Actor agent), and a sixth LLM agent (Rewriter agent).

[0170] The Planner agent is used to classify the verification failure types of the proofs that fail to be verified in the target formal specification, and selects a fourth LLM agent from the pool of connected LLM agents based on the classification results.

[0171] Each fourth LLM agent in the Repairer pool corresponds to a proof error type, including but not limited to syntax errors, loop invariant violations, assertion failures, etc.

[0172] The Actor agent is used to repair proofs that have failed to be verified, based on a repair plan generated by the fourth LLM agent.

[0173] The Rewriter agent is used to delete redundant statements generated during the iterative repair process in the proofs that failed to be verified when the repair rounds reach a preset limit and the verification still fails, and to regenerate the proofs contained in the target formal specification based on the code semantics of the target function.

[0174] When performing proof repair via the second repairer 502, the target formal specification, the code related to the target function, and the error message output by the verifier related to the proof that failed to be verified in the target formal specification can be input into the Planner agent.

[0175] The input to the Planner agent can be represented as: in, This represents the Planner agent. This represents the error message output by the validator during the t-th round of repair. This indicates the selected Repairer agent.

[0176] In some embodiments, the Planner agent can classify the verification failure types of proofs that fail to be verified.

[0177] Specifically, the Planner agent performs root cause analysis on the error messages output by the validator to determine the proof error type corresponding to the current verification failure. Then, the Planner agent selects the Repairer agent from the Repairer pool that corresponds to the determined proof error type as the target Repairer.

[0178] After classifying the error messages, the Planner agent can route the task to the corresponding dedicated Repairer agent.

[0179] After the Planner agent selects a matching Repairer agent, the formal reduction of the objective function, the code related to the objective function, and the error messages output by the verifier can be further input into the Repairer agent.

[0180] The input to the Repairer agent can be represented as: in, This represents the cumulative repair history. The meanings of the other parameters will not be elaborated further.

[0181] In some embodiments, the Repairer agent can also generate a repair plan for the corresponding verification failure type.

[0182] The aforementioned remediation plan can be a natural language description explaining how to modify the proof to resolve the verification failure issue.

[0183] In practical applications, the Repairer agent can consult the repair history to understand previous repair attempts and their results.

[0184] The repair history includes all repair operations and their corresponding verification feedback.

[0185] Inputting the repair history into the Repairer agent allows the Repairer agent to know which repair strategies have been tried and failed, thus avoiding repeated and invalid edits.

[0186] In some embodiments, when the Repairer agent is a dedicated Repairer for assertion repair, the Repairer agent can determine whether the failed assertion is due to insufficient inductive strength.

[0187] Inductive strength refers to the strength of the inductive hypothesis provided by the loop invariant. If the invariant is too weak to support the reasoning within the loop, it will lead to verification failure. If so, the Repairer agent can generate a repair plan to elevate the failed assertion to a loop invariant.

[0188] The reason for promoting an assertion to a loop invariant is that when an assertion must be true in every iteration of a loop, but fails to be verified only in one iteration, promoting it to a loop invariant can provide the SMT solver with a stronger inductive hypothesis, thus maintaining the logical property across all iterations.

[0189] Then, the formal reduction of the objective, the code related to the objective function, and the repair plan can be further input into the Actor agent.

[0190] Among them, the Actor agent repairs the proofs that have failed to be verified based on the repair plan generated by the Repairer agent.

[0191] The Actor agent can take the parts to be repaired in the current specification and the repair plan as input to generate one or more update specifications.

[0192] In some embodiments, the Actor can generate three update specifications. When generating the update specifications, a lower temperature parameter can be used to prioritize stability. In some embodiments, the temperature parameter can be set to 0.3.

[0193] After generating one or more update specifications, the Actor inputs these specifications into a validator for verification, selecting the optimal specification using the same scoring rules as in the initial generation phase. If the optimal update specification passes verification, the repair is complete. If the optimal update specification fails verification, the error feedback output by the validator is recorded, and the process proceeds to the next repair iteration.

[0194] The output and verification feedback records of the Actor agent can be represented as follows: in, This represents the repair plan and corresponding verification feedback for the t-th round of repair. This represents the error message output by the validator after the t-th round of repair.

[0195] In some embodiments, the Actor agent can iteratively repair the proofs that have failed to be verified according to a preset repair cycle.

[0196] For example, the initial repair rounds can be set to 3 rounds. In each repair round, the Planner agent analyzes the current error, routes the corresponding Repairer agent to generate a repair plan, and the Actor agent executes the repair and verifies it.

[0197] In some embodiments, if the Actor agent reaches the maximum number of iterations for repairing a proof that has failed to be verified, and the verifier still fails to verify the proof, then the target formal reduction after iterative repair and the code related to the target function are further input into the Rewriter agent.

[0198] The input to the Rewriter agent can be represented as: in, Represents the Rewriter agent. This represents the current reduction when the maximum number of iterations is reached. This indicates the specification after Rewriter smart rewrite.

[0199] The Rewriter agent can identify redundant assertions in the current specification. These redundant assertions are unnecessary local assertions accumulated during iterative fixes. As the number of fix rounds increases, the model tends to add new assertions in order to pass validation. Although these assertions help pass validation at the time, many of them are temporary patches that are no longer necessary in subsequent rounds, yet they are still retained in the specification.

[0200] This "assertion inflation" phenomenon significantly increases the inference burden of the SMT solver and reduces verification efficiency.

[0201] In this scenario, the Rewriter agent can delete the identified redundant assertions and then resynthesize the loop invariants based on the current code logic, replacing the inductive logic carried by the deleted assertions with the resynthesized loop invariants.

[0202] This structural reset is equivalent to a "reconstruction" of the proof, not a simple patching, but a complete overhaul of the proof structure. It should be noted that in practical applications, the Rewriter agent can be triggered at most once for each objective function to avoid infinite loops.

[0203] Please see Figure 6 , Figure 6 This is an interactive timing diagram of the repair process provided in an exemplary embodiment.

[0204] like Figure 6As shown, this sequence diagram illustrates the interaction flow between the Planner agent, Repairer agent, Actor agent, and verifier during the proof-repair phase.

[0205] In step 601, Planner receives the target function code, the current reduction, and verifier error information.

[0206] In step 602, Planner categorizes the error messages and determines the failure type.

[0207] In step 603, the Planner selects a Repairer from the Repairer pool that matches the failure type.

[0208] In step 604, the Planner forwards the target function code, current specification, and error information to the selected Repairer.

[0209] In step 605, Repairer generates a repair plan.

[0210] In step 606, the Repairer sends the repair plan to the Actor.

[0211] In step 607, the Actor generates candidate update specifications based on the repair plan.

[0212] In step 608, the Actor sends the candidate update specification to the validator for verification.

[0213] In step 609, the verifier returns the verification result.

[0214] In step 610, the Actor selects the optimal reduction based on the verification results.

[0215] If the specification selected in step 610 fails verification, the process can return to step 601 to proceed to the next iteration. If verification still fails after reaching the maximum number of iterations, the Rewriter is triggered to reset the structure.

[0216] In some embodiments, the methods provided in this specification can be applied to the formal verification of Rust code.

[0217] In this context, the target code mentioned above can include Rust code, while the system-level codebase can include a system-level Rust codebase.

[0218] For example, this method can be applied to the FVT (Formal Verification Target) module in the vostd library of the Asterinas operating system kernel, which is involved in the verification of underlying operating system functions such as memory region initialization, page lifecycle safety, and page table cursor navigation.

[0219] In these scenarios, the code involves complex pointer reasoning and deep invariants, which places high demands on formal verification.

[0220] In practical applications, this method can be used not only for Verus verification of Rust code, but also with reasonable modifications to be applied to similar scenarios in other languages ​​and verification tools.

[0221] For example, it can be applied to VeriFast verification of C language code, JML (Java Modeling Language) verification of Java language code, etc., simply by adjusting the type of static analysis tool and verifier accordingly.

[0222] The above description is merely a preferred embodiment of this specification and is not intended to limit this specification. Any modifications, equivalent substitutions, improvements, etc., made within the spirit and principles of this specification should be included within the scope of protection of this specification.

[0223] Figure 7 This is a schematic structural diagram of a device provided in an exemplary embodiment. For example... Figure 7 As shown, device 700 mainly consists of a communication interface 702, a user interface 704, a processor 706, and a data storage 708. These components are interconnected and communicate with each other via a system bus, network, or other connection mechanism 710. The communication interface 702 enables device 700 to communicate with other devices, access networks, and transmission networks via analog or digital modulation. For example, the communication interface 702 may include a chipset and antenna for wireless communication with a radio access network or access point. Furthermore, the communication interface 702 can be a wired interface such as Ethernet, Token Ring, or a USB port, or a wireless interface such as Wi-Fi, Bluetooth, Global Positioning System (GPS), or a wide-area wireless interface (e.g., WiMAX or LTE). Of course, the communication interface 702 can also support other forms of physical layer interfaces and standard or proprietary communication protocols. The communication interface 702 may also include multiple physical communication interfaces, such as Wi-Fi, Bluetooth, and wide-area wireless interfaces.

[0224] User interface 704 includes receiving user input and providing output to the user. Therefore, user interface 704 may include input components such as a keypad, keyboard, touch-sensitive or presence-sensitive panel, computer mouse, trackball, joystick, microphone, still camera, and video camera, and output components such as a display screen (which may be combined with a touch-sensitive panel), CRT, LCD, LED, display using DLP technology, printer, and other similar devices known or developed in the future. User interface 704 may also generate auditory output via speakers, speaker jacks, audio output ports, audio output devices, headphones, and other similar devices known or developed in the future. In some embodiments, user interface 704 may include software, circuitry, or other forms of logic capable of transmitting and receiving data from external user input / output devices. Additionally or alternatively, device 700 may support remote access from other devices via communication interface 702 or another physical interface (not shown). User interface 704 may be configured to receive user input, the position and movement of which may be indicated by indicators or cursors described herein. User interface 704 may also be configured as a display device for rendering or displaying text fragments.

[0225] Processor 706 may contain one or more general-purpose processors and / or special-purpose processors.

[0226] Data storage 708 may include one or more volatile and / or non-volatile storage components and may be integrated wholly or partially with processor 706. Data storage 708 may include removable and non-removable components.

[0227] Processor 706 is capable of executing program instructions 718 (e.g., compiled or uncompiled program logic and / or machine code) stored in data storage 708 to perform the various functions described herein. Data storage 708 may contain a non-transitory computer-readable medium on which program instructions are stored, which, when executed by device 700, enable device 700 to perform any methods, processes, or functions disclosed in this specification and / or the accompanying drawings. Processor 706 executing program instructions 718 may result in processor 706 using data 712.

[0228] For example, program instructions 718 may include an operating system 722 (e.g., an operating system kernel, device drivers, and / or other modules) installed on device 700 and one or more applications 720 (e.g., a browser, social application, or game application). Similarly, data 712 may include operating system data 716 and application data 714. Operating system data 716 is primarily accessible to the operating system 722, while application data 714 is primarily accessible to one or more applications 720. Application data 714 may reside in a file system visible or hidden from the user of device 700.

[0229] Application 720 can communicate with operating system 722 through one or more application programming interfaces (APIs). These APIs help application 720 read and / or write application data 714, transmit or receive information via communication interface 702, receive or display information on user interface 704, etc.

[0230] In some terminology, application 720 may be simply referred to as "app". Furthermore, application 720 can be downloaded to device 700 through one or more online app stores or app markets. However, applications can also be installed on device 700 in other ways, such as through a web browser or a physical interface on device 700 (e.g., a USB port).

[0231] Please refer to Figure 8 This specification also proposes an LLM-based formal verification apparatus, which can be applied to, for example... Figure 7 The device shown is used to implement the technical solution of this specification. The device may include: Module 801 constructs a function call graph corresponding to the target code to be verified; wherein, the nodes on the function call graph represent functions contained in the target code; and the edges on the function call graph represent the call relationships between the functions connected by the edges. The traversal module 802 adopts a traversal order from the leaf nodes to the root node on the function call graph, sequentially determining the functions corresponding to each node on the function call graph as target functions to be verified, and constructing context information for generating formal specifications for the target functions based on the function call graph; wherein, the context information includes local context information related to other functions that have a direct call relationship with the target function; The generation module 803 constructs prompt words for generating formal specifications for the objective function based on the context information, and inputs the prompt words into the LLM so that the LLM can generate formal specifications for the objective function based on the context information contained in the prompt words; wherein, the formal specifications are used to perform formal verification on the objective function.

[0232] For ease of description, the above devices are described by dividing them into various modules or units based on their functions. Of course, when implementing one or more of these specifications, the functions of each module or unit can be implemented in the same or different software and / or hardware, or a module that performs the same function can be implemented by a combination of multiple sub-modules or sub-units, etc. The device embodiments described above are merely illustrative. For example, the division of units is only 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.

[0233] Based on the same concept as the methods described above, this specification also provides an electronic device, including: a processor; a memory for storing processor-executable instructions; wherein the processor performs the steps of the method as described in any of the above embodiments by executing the executable instructions.

[0234] Based on the same concept as the methods described above, this specification also provides a computer-readable storage medium having computer instructions stored thereon that, when executed by a processor, implement the steps of the methods as described in any of the above embodiments.

[0235] Based on the same concept as the methods described above, this specification also provides a computer program product, including a computer program / instructions that, when executed by a processor, implement the steps of the methods as described in any of the above embodiments.

[0236] What those skilled in the art will understand is: In this specification, the terms "comprising," "including," or any other variations thereof are intended to cover a non-exclusive inclusion, such that a process, method, product, or apparatus that comprises a list of elements includes not only those elements but also other elements not expressly listed, or elements inherent to such a process, method, product, or apparatus. Without further limitation, the presence of additional identical or equivalent elements in a process, method, product, or apparatus that includes said elements is not excluded.

[0237] In this specification, “a,” “an,” and “the” do not specifically refer to the singular, but may also include the plural.

[0238] In this specification, ordinal numbers such as "first," "second," etc., do not necessarily indicate order; they are often used to distinguish between objects. For example, "first server" and "second server" usually refer to two servers. To differentiate between these two servers, they are described as "first server" and "second server." Of course, sometimes these two servers may be the same server.

[0239] In this specification, unless explicitly stated otherwise, "receiving and sending data" does not necessarily mean direct receiving and sending; it can also mean indirect receiving and sending. For example, A receiving data sent by B can be understood as A directly receiving the data sent by B, or it can be understood as A indirectly receiving the data sent by B through other entities such as C. Similarly, B sending data to A can be understood as B sending the data directly to A, or it can be understood as B indirectly sending the data to A through other entities such as C. Here, C can be one entity, or it can be two or more entities.

[0240] In this specification, unless explicitly stated otherwise, the relationships between structures can be direct or indirect. For example, when describing "A is connected to B," unless it is explicitly stated that A and B are directly connected, it should be understood that A can be directly connected to B or indirectly connected to B. Similarly, when describing "A is on top of B," unless it is explicitly stated that A is directly above B (AB is adjacent and A is above B), it should be understood that A can be directly above B or indirectly above B (AB is separated by other elements, and A is above B). And so on.

[0241] This specification uses specific terms to describe embodiments thereof. Terms such as "an embodiment," "one embodiment," and / or "some embodiments" refer to a particular feature, structure, or characteristic associated with at least one embodiment of this specification. Therefore, it should be emphasized and noted that references to "an embodiment," "one embodiment," or "an alternative embodiment" in different locations throughout this specification do not necessarily refer to the same embodiment. Furthermore, those skilled in the art can combine and integrate the different embodiments or examples described herein, as well as the features of those different embodiments or examples, without contradiction.

[0242] Although one or more embodiments of this specification provide method steps as described in the embodiments or flowcharts, it is understood that the order of steps listed in the embodiments or flowcharts is only one of many possible execution orders and does not represent the only execution order. Therefore, when the claims involve method steps, any changes or adjustments to the order of such steps, or the parallelism between steps, are also within the scope of protection of the claims.

Claims

1. A formal verification method based on LLM, comprising: Construct a function call graph corresponding to the target code to be verified; wherein, the nodes on the function call graph represent functions contained in the target code; and the edges on the function call graph represent the call relationships between the functions connected by the edges. By traversing from the leaf nodes to the root node in the function call graph, the functions corresponding to each node in the function call graph are sequentially identified as target functions to be verified. Context information for generating formal specifications is then constructed for the target functions based on the function call graph. This context information includes local context information related to other functions that have a direct call relationship with the target function. Based on the context information, a cue word is constructed to generate a formal reduction for the objective function, and the cue word is input into the LLM so that the LLM can generate a formal reduction for the objective function based on the context information contained in the cue word; wherein, the formal reduction is used to perform formal verification of the objective function.

2. The method as described in claim 1, wherein the target code includes a system-level code library; wherein, The system-level code library contains code segments corresponding to different functional modules; the call relationships represented by the edges in the function call graph include function call relationships across functional modules; Construct a function call graph corresponding to the target code to be verified, including: The code segments contained in the code library are parsed sequentially using static analysis tools, and the calling relationships between functions contained in the code segments are determined based on the parsing results; wherein, the calling relationships include the function calling relationships between functions contained in the same code segment; and the cross-functional module function calling relationships between functions contained in different code segments; Based on the determined calling relationships, a function call graph corresponding to the code library is constructed.

3. The method as described in claim 2, wherein the context information constructed for the target function includes first context information related to the caller function and second context information related to the callee function; wherein, The caller function is the function that calls the target function; The called function refers to the function called by the target function; Based on the function call graph, context information for generating formal specifications is constructed for the target function, including: Determine the upstream and downstream neighbor nodes in the function call graph that have a direct neighbor relationship with the node corresponding to the target function; wherein, the upstream neighbor node represents the caller function; and the downstream neighbor node represents the callee function; First context information related to the caller function and second context information related to the callee function are obtained respectively. Based on the obtained first context information and second context information, context information with a two-way perspective for generating formal specifications is constructed for the target function.

4. The method of claim 3, wherein the first context information associated with the caller function includes code segments associated with the caller function; and the second context information associated with the callee function includes at least some information contained in the formal specification already generated for the callee function.

5. The method of claim 4, wherein the formal specification comprises a contract and a proof; wherein, The contract is used to describe preconditions and postconditions; the preconditions are the conditions that must be met to initiate a function call; the postconditions are the conditions that must be met to produce the execution result after the function call is completed. The proof is used to verify whether the actual behavior of the function conforms to the preconditions and postconditions described in the contract; The second context information associated with the callee function includes the contract contained in the formal specification that has been generated for the callee function.

6. The method as described in claim 5, wherein the formal reduction generated by the LLM for the objective function includes multiple sets of candidate formal reductions; The method further includes: Obtain multiple sets of candidate formal reductions generated by the LLM for the objective function; The candidate formal specifications from the multiple sets are further input into the validator, which performs formal verification on the objective function based on the candidate formal specifications from the multiple sets, and generates verification scores for each candidate formal specification from the multiple sets based on the verification results; wherein, the verification scores are used to represent the generation quality of the candidate formal specifications; The candidate formal reduction with the highest verification score is determined as the target formal reduction generated by the objective function for formal verification of the objective function.

7. The method of claim 6, wherein the formal verification includes several verification items related to the formal verification objective; Generate verification scores for each of the multiple groups of candidate formal specifications, including: Based on the verification results, the first number of verification items that pass the verification for each of the multiple groups of candidate formal specifications is counted. Based on the first number of verified items included in the multiple sets of candidate formal specifications, verification scores are generated for each of the multiple sets of candidate formal specifications.

8. The method of claim 7, further comprising, before generating verification scores for each of the multiple sets of candidate formal specifications based on a first number of verified items included in the multiple sets of candidate formal specifications, the following: Based on the verification results, the second number of verification items that failed the verification of the candidate formal specifications in each of the multiple groups is counted. Based on the first number of validated items included in the multiple sets of candidate formal specifications, validation scores are generated for each of the multiple sets of candidate formal specifications, including: Based on the first number of verified items that have passed verification and the second number of verified items that have failed verification contained in the multiple sets of candidate formal specifications, verification scores are generated for the multiple sets of candidate formal specifications respectively.

9. The method of claim 6, wherein the verifier comprises an SMT solver.

10. The method of claim 7, further comprising: Determine whether the target formal specification contains any verification items that have not yet passed verification; If the target formal specification has any verification items that have not yet passed verification, the target formal specification is further input into a repairer built based on an LLM agent, so that the repairer can repair the target formal specification.

11. The method of claim 10, wherein the repairer based on the LLM agent comprises a first repairer based on the LLM agent for repairing the contract contained in the target formal specification; And a second repairer constructed based on an LLM agent for repairing the proof contained in the formal specification of the target; The target formal reduction is input into a repairer built on an LLM agent, so that the repairer repairs the target formal reduction, including: The target formal specification is input into the first repairer built on an LLM agent, so that the first repairer can repair the contract contained in the target formal specification. In response to the completion of the repair of the contract contained in the target formal specification by the first repairer, the target formal specification is further input into the second repairer built on the LLM agent so that the second repairer can repair the proof contained in the target formal specification.

12. The method of claim 11, wherein the first repairer employs a dual LLM agent architecture; The first repairer includes: a first LLM agent; and a second LLM agent; wherein the first LLM agent is used to evaluate the consistency of the code semantics of the contract and the target function; and the second LLM agent is used to repair the contract based on the repair suggestions output by the first LLM agent when the code semantics of the contract and the target function are inconsistent. The target formal specification is input into the first repairer built on an LLM agent, so that the first repairer repairs the contract contained in the target formal specification, including: The formal specification of the target and the code related to the target function are input into the first LLM agent, so that the first LLM agent can evaluate the consistency of the code semantics of the contract and the target function, and output a repair suggestion for the contract if the code semantics of the contract and the target function are inconsistent. The target formal specification and the repair suggestion are further input into the second LLM agent, so that the second LLM agent can repair the contract contained in the target formal specification based on the repair suggestion.

13. The method of claim 11, wherein the unverified verification items existing in the target formal specification include proofs of verification failures by the verifier; The second repairer employs a multi-LLM agent architecture; The second repairer includes: a third LLM agent, an LLM agent pool consisting of multiple fourth LLM agents, and a fifth LLM agent; wherein, the third LLM agent is used to classify the verification failure types of the verification failure proofs included in the target formal specification, and select a fourth LLM agent from the accessed LLM agent pool that matches the verification failure type based on the classification result; the fourth LLM agent is used to repair the verification failure proofs corresponding to the verification failure types that match it, and generate a repair plan for repairing the verification failure proofs; the fifth LLM agent is used to repair the verification failure proofs based on the repair plan generated by the fourth LLM agent; The target formal specification is input into the second repairer built on an LLM agent, so that the second repairer repairs the proof contained in the target formal specification, including: The target formal specification, the code related to the target function, and the error message output by the verifier related to the proof of the failure of the target formal specification are input to the third LLM agent, so that the third LLM agent can classify the proof failure type of the proof of the failure of the target formal specification, and select a fourth LLM agent that matches the proof failure type from the pool of connected LLM agents based on the classification result. After the third LLM agent selects a fourth LLM agent from the pool of connected LLM agents that matches the verification failure type, the target formal reduction, the code related to the target function, and the error message output by the verifier related to the verification failure proof of the target formal reduction are further input to the fourth LLM agent, so that the fourth agent can repair the verification failure proof corresponding to the verification failure type and generate a repair plan for repairing the verification failure proof; The formal specification of the objective function, the code associated with the objective function, and the repair plan are further input into the fifth LLM agent, so that the fifth LLM agent can repair the proof that failed to be verified based on the repair plan generated by the fourth LLM agent.

14. The method as described in claim 13, wherein the fifth LLM agent is used to repair the proof that failed to be verified iteratively according to a preset repair round based on the repair plan generated by the fourth LLM agent; The second repairer also includes a sixth LLM agent; wherein, The sixth LLM agent is used to delete redundant statements generated during the iterative repair process in the proof that failed to be verified, and to regenerate the proof contained in the target formal specification based on the code semantics of the target function. The method further includes: If the fourth LLM agent reaches the maximum number of iterations in repairing the failed proof, and the verifier still fails to verify the proof, then the target formal specification after iterative repair and the code related to the target function are further input into the sixth LLM agent. The sixth LLM agent then removes redundant statements generated during the iterative repair process from the failed proof and regenerates the proof contained in the target formal specification based on the code semantics of the target function.

15. The method of claim 2, wherein the target code includes Rust code; correspondingly, the system-level codebase includes a system-level Rust codebase.

16. An electronic device, characterized in that, include: processor; A memory for storing processor-executable instructions; wherein the processor implements the steps of the method as described in any one of claims 1-15 by executing the executable instructions.

17. A computer program product, characterized in that, Includes a computer program / instructions that, when executed by a processor, implement the steps of the method as described in any one of claims 1-15.