A source code high-order vulnerability detection method and system based on execution path analysis

By constructing a function execution graph at the source code level and combining it with path-level semantic learning, the cross-stage state media read-write association is explicitly modeled, solving the problems of insufficient path modeling and interpretability in high-order vulnerability detection, and achieving efficient and accurate vulnerability detection and localization.

CN121561929BActive Publication Date: 2026-05-08QILU UNIVERSITY OF TECHNOLOGY (SHANDONG ACADEMY OF SCIENCES) +1
View PDF 2 Cites 0 Cited by

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Patents(China)
Current Assignee / Owner
QILU UNIVERSITY OF TECHNOLOGY (SHANDONG ACADEMY OF SCIENCES)
Filing Date
2026-01-26
Publication Date
2026-05-08

AI Technical Summary

Technical Problem

Existing source code vulnerability detection methods suffer from several problems when dealing with high-level vulnerabilities, including insufficient execution path modeling capabilities, difficulty in tracing cross-stage propagation links, a tendency for path space to explode, and insufficient interpretability of detection results.

Method used

By explicitly constructing the function execution graph at the source code level, a set of risk-prioritized function execution paths is generated. Combining cross-stage state media read-write association modeling and path-level semantic learning, a path priority function is used to filter candidate paths, and a path encoding model is used for vulnerability detection.

Benefits of technology

It effectively characterizes high-order vulnerability triggering chains that propagate across branches, loops, functions, and persistent media, improving the accuracy of vulnerability detection and the interpretability of vulnerability location, and reducing the analysis overhead in complex control flow scenarios.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN121561929B_ABST
    Figure CN121561929B_ABST
Patent Text Reader

Abstract

The application relates to the technical field of software security, and provides a source code high-order vulnerability detection method and system based on execution path analysis, which comprises the following steps: obtaining source code to be analyzed, and constructing a function execution graph for each function in the source code; starting from a function entry node on the function execution graph, generating a function execution path according to an execution order edge, and imposing a bounded constraint on the function execution path generation process; calculating a priority score for any function execution path by using a path priority function, sorting and screening the function execution paths based on the priority score, and obtaining a candidate execution path; and obtaining a vulnerability type and vulnerability positioning by using a path encoding model, a statement encoder, an attention mechanism and a vulnerability detection model. The vulnerability detection accuracy and positioning interpretability are improved under controllable computing overhead.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention belongs to the field of software security technology, and in particular relates to a method and system for detecting high-level vulnerabilities in source code based on execution path analysis. Background Technology

[0002] The statements in this section are merely background information related to the present invention and do not necessarily constitute prior art.

[0003] As software systems become larger and more complex, source code vulnerabilities exhibit characteristics such as complex triggering conditions, long propagation paths, and significant cross-stage dependencies. In particular, so-called "high-order vulnerabilities" are often not directly triggered by local defects in a single statement or function. Instead, they arise from external input undergoing multiple conditional branches, loop iterations, function calls, and read / write operations on persistent state media (such as global / static variables, caches, configuration files, databases, message queues, etc.) within the program, eventually reaching a sensitive operation point (sink) in a later stage and triggering security risks (such as command execution, out-of-bounds writes, injection, and privilege escalation). These vulnerabilities are characterized by "cross-stage propagation, cross-location triggering, and difficulty in tracing broken links," posing significant challenges to traditional detection methods.

[0004] Existing source code vulnerability detection technologies mainly include: static scanning based on rule / pattern matching, static analysis based on data flow / taint analysis, path exploration based on dynamic execution or symbolic execution, and code representation learning based on machine learning / deep learning. Rule or pattern matching methods are simple to implement and highly efficient, but they lack the ability to characterize complex semantics and cross-statement dependencies, easily leading to false negatives or false negatives. While taint analysis and traditional data flow analysis can characterize some propagation relationships, they are easily affected by problems such as the explosion of path numbers, difficulties in modeling cross-functions / modules, and information chain breaks caused by state persistence when dealing with real-world engineering code. Dynamic execution and symbolic execution methods can obtain relatively accurate execution information, but they typically suffer from high path exploration overhead, strong environment dependencies, and limited adaptability to large-scale code.

[0005] Furthermore, while recent learning-based detection methods have improved generalization capabilities to some extent, many methods rely more on local token features of statements or functions, lacking structured explicit modeling of "possible execution order," "cross-branch path differences," and "higher-order triggering patterns such as store (write / persistence) → load (read / load) → sink (sink)." At the same time, when the code is large or the control flow is complex, simply pursuing path coverage often leads to a sharp increase in the number of candidate paths, increasing computational costs and reducing attention to effective risky paths, thereby affecting detection results and the interpretability of localization. Summary of the Invention

[0006] To address the technical problems mentioned above, this invention provides a method and system for detecting high-order vulnerabilities in source code based on execution path analysis. By explicitly constructing a function execution graph at the source code level and generating a set of risk-priority function execution paths, combined with cross-stage state media read-write association modeling and path-level semantic learning, it effectively characterizes the high-order vulnerability triggering links that propagate across branches, loops, functions, and persistent media, thereby improving the accuracy of vulnerability detection and the interpretability of vulnerability location under controllable computational overhead.

[0007] To achieve the above objectives, the present invention adopts the following technical solution:

[0008] The first aspect of this invention provides a method for detecting high-level vulnerabilities in source code based on execution path analysis, comprising:

[0009] Obtain the source code to be analyzed, and construct a function execution graph for each function in the source code; the edges of the function execution graph are used to represent the relationships in the program execution process, including execution order relationships, function call relationships, variable propagation relationships, and write and read relationships of state persistence medium;

[0010] On the function execution graph, starting from the function entry node, function execution paths are generated according to the execution order edges, and bounded constraints are applied to the function execution path generation process. A path priority function is used to calculate a priority score for any function execution path, and the function execution paths are sorted and filtered based on the priority scores to obtain candidate execution paths. The path priority function is a weighted sum of path risk warning information, path novelty, and path cost.

[0011] For candidate execution paths, path-level features are obtained through a path encoding model; for each node in the function execution graph, statement feature vectors are obtained through a statement encoder, and the statement feature vectors are stacked sequentially according to the node index to obtain statement-level features; guided by the path-level features, the path-level features and statement-level features are fused through an attention mechanism to form a fused feature representation, and then the vulnerability type and vulnerability location are obtained through a vulnerability detection model.

[0012] Furthermore, the nodes of the function execution graph are used to represent statements, statement blocks, or continuous basic code segments, and are associated with their source code location information, variable access information, and node type.

[0013] Furthermore, the bounded constraints include the maximum path length, the maximum number of loop unrolls, and the maximum call depth.

[0014] Furthermore, the path risk warning information is as follows:

[0015] ;

[0016] in, Indicates the function execution path The nodes on Indicates the node type. Preset weights for node types, This is the indicator of node risk hit. This represents a preset set of risk triggering modes. Weights for risk triggering modes function execution path The hit indicator corresponding to the risk trigger mode.

[0017] Furthermore, the novelty of the path is:

[0018] ;

[0019] Among them, P The set of selected candidate execution paths; function execution paths The three types of information are: branch condition set Call information set and variable access information set Function execution path The three types of information are: branch condition set Call information set Variable access information set Path similarity Weight , For Jaccard similarity.

[0020] Furthermore, the path cost is a weighted sum of path length, cross-function call depth, and loop unrolling count.

[0021] Furthermore, positive and negative sample pairs are constructed based on the structural and semantic similarity between candidate execution paths, and the path encoding model is trained using a contrastive learning approach.

[0022] A second aspect of the present invention provides a source code high-level vulnerability detection system based on execution path analysis, comprising:

[0023] The graph construction module is configured to: acquire the source code to be analyzed, and construct a function execution graph for each function in the source code; wherein, the edges of the function execution graph are used to represent the relationships in the program execution process, including execution order relationships, function call relationships, variable propagation relationships, and write and read relationships of state persistence media;

[0024] The path generation module is configured to: generate function execution paths on the function execution graph starting from the function entry node and according to the execution order edges, and apply bounded constraints to the function execution path generation process; calculate a priority score for any function execution path using a path priority function, and sort and filter the function execution paths based on the priority scores to obtain candidate execution paths; wherein, the path priority function is a weighted sum of path risk warning information, path novelty, and path cost;

[0025] The vulnerability detection module is configured as follows: for candidate execution paths, path-level features are obtained through a path encoding model; for each node in the function execution graph, statement feature vectors are obtained through a statement encoder, and the statement feature vectors are stacked sequentially according to the node index to obtain statement-level features; guided by the path-level features, the path-level features and statement-level features are fused through an attention mechanism to form a fused feature representation, and then the vulnerability type and vulnerability location are obtained through the vulnerability detection model.

[0026] Furthermore, the nodes of the function execution graph are used to represent statements, statement blocks, or continuous basic code segments, and are associated with their source code location information, variable access information, and node type.

[0027] Furthermore, the bounded constraints include the maximum path length, the maximum number of loop unrolls, and the maximum call depth.

[0028] Compared with the prior art, the beneficial effects of the present invention are:

[0029] This invention achieves effective characterization of high-order vulnerability triggering chains that propagate across branches, loops, functions, and persistent media by explicitly constructing function execution graphs at the source code level and generating a set of risk-priority function execution paths. Combined with cross-stage state media read-write association modeling and path-level semantic learning, it improves the accuracy of vulnerability detection and the interpretability of vulnerability location under controllable computational overhead.

[0030] This invention limits the path expansion scale by using bounded constraints such as maximum path length, maximum loop unrolling count, and maximum call depth. It also constructs a priority function using risk warnings, path novelty, and path cost, and generates a candidate path set using a priority sampling strategy. This allows for the priority retention of high-value, high-risk paths without pursuing blind path coverage, significantly reducing the analysis overhead in complex control flow scenarios.

[0031] This invention performs path-level semantic representation learning on the execution path, and uses comparative learning to bring similar paths closer together and distinguish different paths, so that the path representation can more stably capture key information such as "differences in execution order", "differences in structure" and "differences in risk triggering mode", and has better discrimination ability and generalization performance in complex real engineering code.

[0032] This invention performs cross-granularity attention fusion of path-level and statement-level representations, which can output key execution paths, key statement fragments and their location indexes related to vulnerability prediction. It not only gives a judgment on "whether a vulnerability exists", but also provides a traceable explanation of "how the vulnerability triggering link is formed and where the key position is", which enhances the usability and engineering application value of the results. Attached Figure Description

[0033] The accompanying drawings, which form part of this invention, are used to provide a further understanding of the invention. The illustrative embodiments of the invention and their descriptions are used to explain the invention and do not constitute an improper limitation of the invention.

[0034] Figure 1 This is a flowchart of a high-order vulnerability detection method for source code based on execution path analysis, according to Embodiment 1 of the present invention.

[0035] Figure 2 This is a schematic diagram of the code for constructing EFG according to Embodiment 1 of the present invention. Detailed Implementation

[0036] To make the objectives, technical solutions, and advantages of the embodiments of the present invention clearer, the technical solutions of the embodiments of the present invention will be clearly and completely described below with reference to the accompanying drawings.

[0037] It should be noted that the following detailed description is illustrative and intended to provide further explanation of the invention. Unless otherwise specified, all technical and scientific terms used herein have the same meaning as commonly understood by one of ordinary skill in the art to which this invention pertains.

[0038] Terminology Explanation:

[0039] Advanced vulnerabilities: User-input data (source) is first written to some persistent medium (such as global variables, local files, databases, etc.) during program propagation. In subsequent processes, it is read again and used in security-sensitive nodes (sinks). However, because the "writing phase" and the "reuse phase" are isolated by persistent storage in terms of time and code path, static or dynamic analysis makes it difficult to restore the original data flow and control flow dependency between the two. This causes the connection from source to sink to be "broken," making this type of vulnerability, which is triggered a second time by persistent data, more concealed and more difficult to detect and locate.

[0040] Function execution path: refers to a possible execution sequence from entry to exit (return / abnormal termination) on the control structure of a given function. It is determined by sequential statements, conditional branch selection, loop iteration, and exception handling branches. It can be abstracted as an ordered link of basic blocks or statement fragments to describe "how the code will be triggered in a certain order under certain input and running conditions" and to provide accessibility and context constraints for subsequent analysis.

[0041] Source / Sink: Source refers to the location where potentially untrusted input enters the program, such as external request parameters, file reading, environment variables, IPC (Inter-Process Communication) messages, etc.; Sink refers to the location of sensitive operations that may trigger security risks, such as command execution, SQL (Structured Query Language) execution, deserialization, dangerous API (Application Programming Interface) calls, out-of-bounds write / read, format strings, etc. The reachability and propagation relationship between Source and Sink is an important basis for vulnerability detection and location.

[0042] Contrastive Learning: A representation learning method that does not directly "teach the model the answer" with human labels. Instead, it constructs sample pairs to teach the model to bring semantically similar sample representations closer together and push semantically unrelated sample representations further apart. A common approach is to take the same sample and perform two different data augmentations to obtain "positive sample pairs", then take other samples from the batch as "negative samples", and train the encoder with contrastive loss (e.g., Information-Noise Contrastive Estimation, InfoNCE). Finally, a more general and transferable feature representation is obtained, which can be used for tasks such as classification, retrieval, and clustering.

[0043] Transformer is a sequence modeling neural network architecture centered on an attention mechanism. It uses self-attention to allow each position in the sequence to "pay attention" to other positions based on the content in a single computation, thereby capturing long-distance dependencies. At the same time, it learns different association patterns in parallel through multi-head attention, and combines feedforward networks, residual connections, and layer normalization to stabilize training. It also uses positional encoding to compensate for the lack of positional information caused by its independence from recurrent or convolutional networks. Compared to RNNs (Recurrent Neural Networks) that process sequences step by step, Transformer is easier to parallelize and performs well in large-scale data and long-context tasks. It is the basic architecture of modern large language models and machine translation systems.

[0044] CodeBERT (Extended BERT Model): A pre-trained language model for source code, it can model "code" and "natural language (such as comments and requirements descriptions)" together, thereby learning a representation that better understands programming semantics. It is usually based on the Transformer architecture, and is first pre-trained on a large number of code repositories and accompanying text using self-supervised tasks similar to BERT (a bidirectional encoder based on Transformer) (such as mask prediction, code-text alignment, etc.), and then fine-tuned for downstream tasks, such as code search, code summarization generation, defect detection, clone detection, etc. Therefore, it is often used as a general foundation for code understanding and code intelligence.

[0045] Example 1

[0046] This embodiment provides a method for detecting high-level vulnerabilities in source code based on execution path analysis.

[0047] This embodiment provides a method for detecting high-order vulnerabilities in source code based on execution path analysis. It performs high-order vulnerability detection based on function execution path modeling and path priority sampling. It can be used to model, detect, and interpretably locate complex vulnerability triggering chains that propagate across branches, loops, functions, and state media in source code.

[0048] To address the shortcomings of existing source code vulnerability detection methods, such as insufficient execution path modeling capabilities, difficulty in tracing cross-stage propagation links, easy path space explosion, and insufficient interpretability of detection results when facing high-order vulnerabilities, this embodiment provides a source code high-order vulnerability detection method based on execution path analysis. This method aims to accurately characterize the possible execution order and key relationships in a program under controllable computational overhead, explicitly modeling vulnerability triggering links across branches, loops, functions, and state media, thereby achieving effective detection and interpretable localization of high-order vulnerabilities.

[0049] This embodiment provides a source code high-order vulnerability detection method based on execution path analysis, which can explicitly express the possible execution order and key relationships within functions at the source code level. It can connect and trace the propagation links caused by cross-stage state media reading and writing, and generate a more valuable set of execution paths under controllable overhead through bounded constraints and risk priority strategies, thereby achieving efficient detection and interpretable localization of high-order vulnerabilities.

[0050] This embodiment provides a method for detecting high-order vulnerabilities in source code based on execution path analysis. First, the source code to be analyzed is structurally parsed and a location mapping is established. Then, a function execution graph is constructed for each function. Using statements or statement fragments as nodes, edges such as execution order, call association, variable propagation, and state medium read / write association are established, thereby explicitly connecting the cross-stage propagation relationship caused by "writing / persistence (store) - reading / loading (load)".

[0051] This embodiment provides a method for detecting high-order vulnerabilities in source code based on execution path analysis. It generates function execution paths on the function execution graph and merges continuous statements into path fragments to obtain a compact representation. It also introduces bounded constraints such as maximum path length, maximum number of loop unrollings, and maximum call depth. Based on risk warnings, novelty, and cost, it constructs a path priority function to perform risk-priority sampling and screening of candidate paths to alleviate path space explosion.

[0052] This embodiment provides a method for detecting high-order vulnerabilities in source code based on execution path analysis. During the model training phase, positive and negative sample pairs are constructed based on path similarity. The execution path encoder is trained using a contrastive learning objective, so that similar execution path representations are close to each other in the embedding space and remain distinguishable from dissimilar paths, thereby obtaining a path-level semantic representation with discriminative capabilities.

[0053] This embodiment provides a high-level vulnerability detection method for source code based on execution path analysis. In the detection stage, it combines statement-level features and path-level features, and uses cross-granularity attention fusion to identify vulnerability types. It also outputs key execution paths, key statement fragments and their code locations, enabling interpretable localization.

[0054] This embodiment provides a method for detecting high-level vulnerabilities in source code based on execution path analysis, such as... Figure 1 As shown, it includes the following steps:

[0055] Step 1: Source code parsing and structured representation construction.

[0056] The source code to be analyzed is obtained and uniformly encoded and formatted. A source code location mapping relationship is established, and (<file>, <start and end line>) location information is generated for each word and sentence fragment. Then, the source code is parsed to construct an abstract syntax tree (AST), symbol table, and scope information, providing basic executable structure support for subsequent execution path modeling.

[0057] Step 2: Construct the function execution graph.

[0058] After the syntax parsing is completed, a corresponding function execution graph (FEG) is constructed for each function in the source code. The function execution graph is used to express the possible execution order inside the function and the key semantic relationships related to execution.

[0059] in:

[0060] The nodes in the function execution graph are used to represent statements, statement blocks, or continuous basic code segments, and are associated with their source code location information, variable access information, and node type;

[0061] The edges of the function execution graph are used to represent the relationships in the program execution process, including execution order relationships, function call relationships, variable propagation relationships, and write and read relationships of state persistence media, so as to explicitly characterize the cross-stage data propagation characteristics.

[0062] Node construction: Statements, statement blocks, or continuous basic code snippets are used as nodes. Each node is associated with at least its corresponding source code location annotation information. Furthermore, the set of variables involved in the node, call information, and node type (e.g., sequential snippet, conditional snippet, loop snippet, return snippet) can be recorded.

[0063] Edge construction: Establish the following associated edges in the function execution graph to reflect the code's execution logic:

[0064] Execution order edge: used to represent the possible execution order of a program, including sequential execution, conditional branching, and loop return to the entry point;

[0065] Call associated edges: When a node contains a function call statement, an association is established between the calling node and the entry node of the called function, which is used to support cross-function tracing when needed;

[0066] State media association edges: used to represent the persistence and reuse relationship of data on the state media, including establishing associations between "write / persistence (store)" and "read / load (load)," and continuing to associate the loaded value with subsequent sensitive usage points; the state media includes but is not limited to global variables, static members, cache, configuration items, local files, database records, message queue messages, etc., thereby supporting the modeling and location of cross-stage triggering links for high-level vulnerabilities;

[0067] Variable association edges: These represent the propagation relationship of variable values ​​in the code, that is, they associate "a variable is assigned / calculated somewhere" with "the variable is used in subsequent statements (e.g., as length, subscript, address, or parameter)", thus providing key variable link clues for the subsequent location stage.

[0068] Step 3: Generation and representation of function execution path.

[0069] On the function execution graph, starting from the function entry node, possible function execution paths are generated according to the execution order. Each execution path represents a possible execution sequence of the function under certain input or conditions. To adapt to long code scenarios, continuous statements or basic blocks in the path are merged into path fragments for representation, so as to reduce the path length and improve modeling efficiency.

[0070] The execution path can be understood as a "possible route" that a function can take during runtime: starting from where the function first enters, proceeding down the execution order of the code, and finally reaching the point where the function returns, throws an exception, or terminates (inclusive).

[0071] To adapt to scenarios with long source code, the execution path is not recorded line by line, but rather a continuous block of statements or a basic block is merged into several "path fragments" to represent it. This makes the path more compact and allows the subsequent model to focus on and perform more detailed calculations only within these fragments.

[0072] Step 4: Bounded constraints and risk-priority path sampling.

[0073] To avoid path space explosion caused by loops and calls, a bounded path sampling method is used to generate a candidate path set P={p1…p k}, and selects more "worthy of attention" paths through a priority function, rather than simply pursuing coverage; where p i Let k be the i-th candidate execution path in set P, k be the number of candidate execution paths in set P, and i be the path index (i=1,…,k).

[0074] Specifically, to avoid path space explosion caused by loop structures and function calls, bounded constraints are imposed on the execution path generation process, including maximum path length, maximum number of loop unrollings, and maximum call depth. Under the bounded constraints, a path priority function is constructed based on path risk warning information, path novelty, and path cost to sort and filter candidate paths, prioritizing the retention of execution paths with higher vulnerability triggering risk and greater structural differences, thus forming a set of candidate execution paths.

[0075] Among them, the bounded constraints (the expansion terminates when any one of them is met) include: maximum path length L max (By number of nodes or number of statements), maximum number of loop unrolls U max Maximum call depth D max (Only effective when associated edges are enabled).

[0076] The path priority function calculates a priority score (overall score) for any function execution path p:

[0077] Score(p)=α·RiskHint(p)+β·Novelty(p) γ·Cost(p);

[0078] Where α, β, and γ are the risk weight, novelty weight, and cost weight, respectively; the mean risk... , The general risk warning score for the i-th candidate execution path is the mean novelty score. , Let be the novelty of the i-th candidate execution path, and be the mean cost. , The cost and risk standard deviation of the i-th candidate execution path. Standard deviation of novelty Cost standard deviation Risk variation coefficient Novelty coefficient of variation Cost variation coefficient , For smoothing terms (such as 10) -6 ), total coefficient of variation , , , The larger the coefficient of variation, the more significant the differences in the candidate path set, the stronger the differentiation effect on path priority, and the higher the weight assigned, achieving adaptive optimization of the weight; and when the mean of a certain indicator (such as risk value) is generally high, the exponential decay factor ( , , The risk weight will decay rapidly to prevent the indicator from having too large a weight in the weight allocation, so that indicators with low mean but high volatility can also get reasonable weight. For example, in scenarios where the risk value is generally high, the risk weight will be automatically reduced to avoid over-focusing on high-risk paths and ignoring novelty and cost, so that the path sampling is more balanced.

[0079] Here, RiskHint(p) is a "general risk warning score" related to the vulnerability type, such as: the appearance of a dangerous API, length / boundary-related variables involved in memory writes, integers involved in address / length calculations, and external input involved in sensitive calls; RiskHint(p) is used to measure the vulnerability triggering risk of the function execution path, and its calculation method is to weight and accumulate the risk node events and risk pattern events within the function execution path, specifically:

[0080] ;

[0081] in, Indicates the function execution path On the node or statement unit, Indicates the node type. Preset weights for the corresponding node types, The node risk hit indicator (0 or 1); This represents a pre-defined set of risk triggering modes, including higher-order triggering modes such as "source→propagation→sink" and "store→load→sink"; Weights for risk triggering modes function execution path The hit indicator (0 or 1) corresponds to the risk trigger mode; the above weighted results are normalized and mapped so that... ;

[0082] in, To measure the difference (novelty) between a function execution path and the set of selected candidate execution paths, the novelty of a function execution path is defined as follows:

[0083] ;

[0084] Among them, P Let q be the set of selected candidate execution paths, and q be a path selected from set P. Any path extracted from the input; function execution path The three types of information are: branch condition set Call information set Variable access information set Function execution path The three types of information are: branch condition set Call information set Variable access information set ; Define path similarity as the weighted sum of the similarities of the three:

[0085] ;

[0086] Among them, weight ,and ; Similarity to Jaccard ;

[0087] in, Used to measure path cost (length, number of function crossings, number of loop unrollings, etc.), its calculation method is as follows: path length Cross-function call depth Number of loop expansions Equivalent cost index based on upper limit parameter , , After normalization and weighted summation, we get:

[0088] ;

[0089] and make This enables the prioritization and filtering of function execution paths based on risk while also considering diversity and overhead constraints.

[0090] Use priority queues The function execution path prefix is ​​expanded preferentially to generate candidate execution paths that are high-risk, low-cost, and significantly different from the selected paths.

[0091] Step 5: Output path - code location binding index.

[0092] Each candidate execution path is output as a structured record for subsequent vulnerability localization: <Path ID, Function Identifier, Node Sequence [Statement Fragment ID...], Position Sequence [(Row, Column)...], Key Variable Set, Key Call Set>.

[0093] The above process is based on Figure 2 In the example code, line 1 is the function entry point, and lines 2-4 write the user input (user_input, external untrusted input data, often used as the source) to the local file cfg.txt (a text configuration file named cfg) to complete persistent storage. Line 3, fprintf (a C standard library function for formatted writing to a file), is the key store (write / store) node; line 5 defines buf

[128] (a buffer of length 128), lines 6-8 open and read cfg.txt into buf, and line 7, fgets (a C standard library function for reading a line from a file stream, a string of a certain length, into the buffer), is the key l The `oad` (read / load) node affects the `ok` (boolean state); line 9 checks `if(ok)` (a conditional statement keyword; if the condition is true, the corresponding branch is executed). The true branch constructs `cmd="echo"+buf` on line 10, where `cmd` is the command string variable name, and `"echo"+buf` means concatenating the string `"echo"` with the content of the variable `buf` to form a complete command string. Line 11 calls `system(cmd)` (a C standard library function that calls the operating system shell to execute the command string) to reach the security-sensitive node (sink); the false branch executes the default command on line 13, and returns on line 15.

[0094] First, parse the source code and record the line numbers of these key statement fragments.

[0095] Next, construct the function execution graph (FEG): string together "persistent writing to fragment (lines 2–4) → read initialization (line 5) → read fragment (lines 6–8) → branch judgment (line 9)", and then split into two paths from line 9: one goes to "risk execution fragment (lines 10–11)" and the other goes to "default safe fragment (line 13)", and both will eventually converge to "return (line 15)";

[0096] Meanwhile, the variable / dependency relationships are marked in the function execution graph: user_input (source) is written to the file cfg.txt (store) on line 3, fgets on line 7 reads the file content back to buf (load) and affects ok. In the true branch, buf participates in the cmd construction on line 10 and is used as the parameter of system() on line 11 to reach the sensitive node (sink). Therefore, "persistent medium association edges" are introduced in FEG to explicitly associate store (writing cfg.txt on line 3) with load (reading buf on line 7) to depict the higher-order propagation chain (source→store→load→sink).

[0097] Then, a "function execution path" is generated on this FEG, and bounded constraints are set (e.g., limiting the maximum number of segments the path can traverse; in this example, there are no loops, so the main constraint is length). Bounded sampling is performed within the constraints to obtain two of the most representative paths:

[0098] P1 (True branch, risky path): "Lines 2-4 → Line 5 → Lines 6-8 → Line 9 (True) → Lines 10-11 → Line 15";

[0099] P2 (false branch, default path): "line 2-4 → line 5 → line 6-8 → line 9 (false) → line 13 → line 15";

[0100] Since P1 contains both "persistent readback data participates in the construction of sensitive parameters (line 10)" and "dangerous API: system (line 11)", and its data source can be traced back to the persistent write in line 3 (cross-stage chain break), this path is marked as a higher risk and more worthy of subsequent modeling. At the same time, each path outputs the corresponding line number sequence, which makes it convenient to directly give "vulnerability-related execution path + specific code location" later.

[0101] Step 6: Path-level semantic modeling and comparative learning training.

[0102] The candidate execution paths are input into the path encoding model to model the sequential relationships and long-distance dependencies of the nodes in the candidate execution paths, thereby obtaining path-level semantic representations (path-level features). That is, for each candidate execution path... (Node sequence) The Transformer path encoder is used to model long-distance dependencies within the path, and then pooling is used to obtain the path-level semantic representation. (Coarse-grained).

[0103] In this embodiment, positive and negative sample pairs are constructed based on the structural and semantic similarity between candidate execution paths. A contrastive learning approach is used to train the path encoding model, ensuring that semantically similar execution paths are close to each other in the embedding space, while different paths remain distinguishable, thereby obtaining an execution path representation with discriminative capabilities. Specifically:

[0104] (1) Sample construction and similarity measurement: For each function, the set of candidate execution paths P = {p1…p2} k} Calculate the similarity between candidate execution paths Sim(p) i ,p j When the similarity between two different candidate execution paths within the same function is Sim(p) i ,p j When )≥τ, (p) i ,p j () are considered positive sample pairs.

[0105] (101) Candidate execution path representation construction.

[0106] Any candidate execution path Represented as a sequence of node numbers, where, For the first candidate execution path Numerical identifiers for each node; constructing node sets respectively: Edge set: ,in, This represents the directed connection relationship formed between adjacent nodes in the candidate execution path.

[0107] (102) Define the similarity of node sets based on the intersection-union ratio of sets: Edge set similarity is defined based on the intersection-union ratio of sets: The similarity between paths is obtained by weighted fusion of node overlap and edge overlap. ;in, To integrate weights, take This means that the edge overlap weight is higher, in order to strengthen the constraint on the consistency of path order and structure.

[0108] (103) If and only if the following condition is met: At that time, Considered as positive sample pairs, where the threshold Used to control the similarity strength of positive sample pairs, taking When a higher purity positive sample pair is required, one can take... .

[0109] (2) Negative Sample Selection: In addition to positive samples, candidate execution paths from other functions or other code units are considered negative samples; and a "difficult negative sample" strategy can be introduced, that is, candidate execution paths with a high Sim value to the anchor path but not meeting the positive sample condition are preferentially selected into the negative sample set. When constructing negative sample pairs, instead of randomly selecting from all dissimilar candidate execution path pairs, candidate execution path pairs with a high degree of overlap with the anchor path in terms of nodes / edges, but which have not reached the positive sample judgment threshold or meet the exclusion conditions are preferentially selected as negative sample pairs to enhance the model's ability to distinguish differences in features under similar structures.

[0110] The anchor path refers to the reference path used for comparative learning, which comes from the set of candidate paths obtained by the function through bounded constraints and risk-priority sampling. During training, a path is selected from the set as the anchor (usually, each path is used as the anchor in turn in a batch).

[0111] (3) The problem of having only one candidate execution path: When a function obtains only a single candidate execution path p through bounded sampling, noise is processed through the unique candidate execution path as "different perspectives of the same path" to form positive sample pairs, thereby avoiding the inability of the function to participate in comparative learning due to the lack of positive samples.

[0112] Assume a unique candidate execution path via path encoder , thus obtaining path-level feature vectors A noise processing step is performed on the candidate execution path to obtain a perturbation view. Its path-level representation is defined as: Among them, R d It is a d-dimensional real-valued vector. For noise intensity parameters, (Generally, 0.02 is used); for 3D identity matrix; This represents the path-level feature vector after noise has been added; Zero-mean Gaussian noise is used to slightly perturb the path representation. Since the noise acts on the path-level representation rather than the path structure, it does not change the path's topological relationships or inlet-outlet connectivity. This perturbation yields a view that is semantically consistent with the original path but not entirely identical in representation, thus maintaining consistency with the original representation. This constitutes a positive sample pair.

[0113] Specifically, the Transformer path encoder incorporates positional encoding to perform self-attention modeling of long-distance dependencies within the path. Output pooling: Where p is a candidate execution path; v1,…,v KThe first to the Kth node segments arranged sequentially on path p; s vi For the i-th node v in the path i The vector representation of S p P is a matrix formed by sequentially assembling the node vectors of the entire path; E For position encoding; TransformerEnc( ) represents the Transformer encoder (multi-layer self-attention + feedforward network); H represents the output sequence representation of the Transformer; Pool( ) represents the pooling / aggregation function; z p Let p be the final path-level representation vector.

[0114] (4) Comparative learning objectives: The path encoder is trained using InfoNCE loss.

[0115] For each anchor sample path view Its corresponding positive sample view via path encoder The normalized representation is obtained as follows:

[0116] ;

[0117] Maintaining a negative sample queue The path representations calculated in the current batch are continuously stored, with the most recent path being retained on a rolling basis. A set of 1000 path embedding vectors is used as the negative sample set for subsequent iterations. The negative sample queue is not generated separately; instead, it is a FIFO (First-In-First-Out) cache of the path embedding vectors continuously generated during training, keeping only the most recently generated vectors. One. Among them, This is the path representation vector for historical samples.

[0118] The similarity function is defined as follows: Since it has already been carried out Normalization, dot product is equivalent to cosine similarity.

[0119] Then for anchor vectors The InfoNCE loss is defined as:

[0120] ;

[0121] in, This represents the positive samples in the queue. The negative sample representation in the queue; θ θ is a temperature coefficient used to adjust the discriminative strength of the similarity distribution. It is set according to a trade-off between training stability and representation discriminative ability: a smaller θ enhances the distinction between positive and negative samples but is prone to instability, while a larger θ makes training smoother and more stable but weakens the discriminative ability. By minimizing the InfoNCE loss, the positive sample representations corresponding to the same path (or similar paths) are made close to each other in the embedding space, while maintaining a distance from the representations in the negative sample queue, thereby obtaining a discriminative path-level representation.

[0122] (5) Training output: Obtain the execution path encoder This allows any path to be represented as a d-dimensional vector, which can be used for vulnerability detection and location.

[0123] Step 7: Cross-granularity feature fusion and vulnerability detection.

[0124] Step 701: Encode the statement units corresponding to each node in the function execution graph to obtain statement-level semantic features (fine-grained). That is, feed one statement / statement fragment corresponding to each node in the function execution graph (FEG) into a statement encoder (such as CodeBERT) to obtain a vector representation of each statement, which is then stacked into a matrix according to node index order. .

[0125] Specifically, the statement units corresponding to each node in the function execution graph are obtained, and each node is regarded as a statement (or a normalized statement fragment). After lexical normalization and word segmentation, the statements are input into the statement encoder. Generate fixed-length statement feature vectors. The statement encoder is preferably implemented using CodeBERT, which inputs the statement token sequence into CodeBERT and extracts its... (Classification labels, used to aggregate the overall semantic representation of the entire input) The location hidden state or the pooled representation is used as the vector of the statement. . Execute all functions in the graph. The statement vectors of each node are concatenated into row vectors according to their node index order to form a statement-level feature matrix. ,in, The number of nodes (statements). For statement vector dimensions, matrix Used for attention alignment and feature fusion of subsequent path-level and statement-level representations.

[0126] Step 702: Guided by path-level representation, the path-level features and statement-level features are fused through an attention mechanism to form a fused feature representation that takes into account both execution context and local semantics.

[0127] Specifically, cross-granularity attention fusion: using path-level features as queries and statement-level features as keys / values, the attention weight A is calculated to achieve explicit alignment of "which statements the path focuses on"; attention can be combined with the path-statement inclusion relationship and position mask to allow only statements within the path coverage to participate in attention calculation.

[0128] (1) Calculate the query Q, key K, and value V in cross-granularity attention:

[0129] ;

[0130] ;

[0131] ;

[0132] Among them, z p Let S be the path-level semantic representation of path p; S is the statement-level feature matrix, containing vector representations of N nodes in FEG; W q W k W v The weight matrix is ​​a learnable matrix; N represents the query length; N represents the number of statements or nodes.

[0133] (2) Location / containment relationship mask.

[0134] To prevent "path vectors from focusing on statements outside the path", a mask is constructed. If statement Candidate execution path The set of nodes covered (or within the defined "path segment coverage"), then ,otherwise In this way, after applying softmax (normalized exponential function), the weight of statements outside the candidate execution path will become 0 (i.e., they will be blocked).

[0135] (3) Attention weights and context vectors.

[0136] Attention weight Context vector ;

[0137] Here It means "the degree to which this execution path pays the most attention to the i-th statement".

[0138] The fusion function Fuse combines path semantics with the semantics of the statements of interest to synthesize a fused feature representation. :

[0139] ;

[0140] When a function has multiple candidate paths, the process involves merging paths within a single path and pooling paths between paths.

[0141] Where, k is the number of candidate paths obtained by the function through bounded constraints and risk-priority sampling; p j For the j-th candidate execution path (j=1,…,k); h fuse (p j ) indicates path p j The fused feature vector obtained after cross-granularity attention fusion; MeanPool() represents the average pooling operation; h f This is the final characteristic of the function, used for subsequent vulnerability classification and location output.

[0142] Step 703: Input the fused feature representation into the vulnerability detection model, and output the vulnerability detection results and the corresponding vulnerability types.

[0143] Specifically, Input classifier outputs vulnerability type; simultaneously utilizes attention weights. It provides interpretable location results at the statement and path levels, including key execution paths, key statement fragments and their (file, row and column) location information, thereby enabling the detection and traceable location of high-order vulnerabilities.

[0144] Step 8: Vulnerability location and output of interpretable results.

[0145] Based on path-level attention weights and statement-level attention levels, the system outputs key execution paths, key statement fragments, and their specific locations in the source code that are related to the vulnerability detection results, enabling interpretable localization of high-order vulnerabilities.

[0146] This embodiment provides a source code high-order vulnerability detection method based on execution path analysis. By explicitly constructing a function execution graph at the source code level and generating a set of risk-priority function execution paths, combined with cross-stage state media read-write association modeling and path-level semantic learning, it achieves effective characterization of high-order vulnerability triggering links that propagate across branches, loops, functions, and persistent media, thereby improving vulnerability detection accuracy and location interpretability with controllable computational overhead.

[0147] This embodiment provides a source code high-order vulnerability detection method based on execution path analysis, which enhances the explicit modeling capability of high-order vulnerability links: by introducing execution order edges, call association edges, variable association edges, and state medium association edges into the function execution graph, the high-order triggering modes such as "source→propagation→sink" and "store→load→sink" are expressed in a structured way, which can effectively connect the cross-stage propagation relationships that are easily broken in traditional static analysis, and improve the coverage and detection capabilities of hidden high-order vulnerabilities.

[0148] This embodiment provides a source code high-order vulnerability detection method based on execution path analysis, which alleviates path space explosion and reduces computational overhead. It limits the path expansion scale by using bounded constraints such as maximum path length, maximum loop unrolling count, and maximum call depth, and constructs a priority function using risk warnings, path novelty, and path cost. It then uses a priority sampling strategy to generate a candidate path set, thereby prioritizing the retention of high-value risk paths without pursuing blind path coverage, significantly reducing the analysis overhead in complex control flow scenarios.

[0149] This embodiment provides a high-level vulnerability detection method for source code based on execution path analysis, which improves detection accuracy and generalization ability: it performs path-level semantic representation learning on the execution path, and through comparative learning, it brings similar paths closer together and distinguishes different paths, so that the path representation can more stably capture key information such as "differences in execution order", "differences in structure" and "differences in risk triggering mode". Compared with methods that only rely on local token features of statements or functions, it has better discrimination ability and generalization performance in complex real-world engineering code.

[0150] This embodiment provides a high-level vulnerability detection method for source code based on execution path analysis, which provides interpretable vulnerability location results: by performing cross-granularity attention fusion between path-level representation and statement-level representation, it can output key execution paths, key statement fragments and their (file, row and column) position indexes related to vulnerability prediction. It not only gives a judgment on "whether a vulnerability exists", but also provides a traceable explanation of "how the vulnerability triggering chain is formed and where the key positions are", which enhances the usability and engineering application value of the results.

[0151] Example 2

[0152] This embodiment provides a high-level source code vulnerability detection system based on execution path analysis, including:

[0153] The graph construction module is configured to: acquire the source code to be analyzed, and construct a function execution graph for each function in the source code; wherein, the edges of the function execution graph are used to represent the relationships in the program execution process, including execution order relationships, function call relationships, variable propagation relationships, and write and read relationships of state persistence media;

[0154] The path generation module is configured to: generate function execution paths on the function execution graph starting from the function entry node and according to the execution order edges, and apply bounded constraints to the function execution path generation process; calculate a priority score for any function execution path using a path priority function, and sort and filter the function execution paths based on the priority scores to obtain candidate execution paths; wherein, the path priority function is a weighted sum of path risk warning information, path novelty, and path cost;

[0155] The vulnerability detection module is configured as follows: for candidate execution paths, path-level features are obtained through a path encoding model; for each node in the function execution graph, statement feature vectors are obtained through a statement encoder, and the statement feature vectors are stacked sequentially according to the node index to obtain statement-level features; guided by the path-level features, the path-level features and statement-level features are fused through an attention mechanism to form a fused feature representation, and then the vulnerability type and vulnerability location are obtained through the vulnerability detection model.

[0156] Furthermore, the nodes of the function execution graph are used to represent statements, statement blocks, or continuous basic code segments, and are associated with their source code location information, variable access information, and node type.

[0157] Furthermore, the bounded constraints include the maximum path length, the maximum number of loop unrolls, and the maximum call depth.

[0158] Furthermore, the path risk warning information is as follows:

[0159] ;

[0160] in, Indicates the function execution path The nodes on Indicates the node type. Preset weights for node types, This is the indicator of node risk hit. This represents a preset set of risk triggering modes. Weights for risk triggering modes function execution path The hit indicator corresponding to the risk trigger mode.

[0161] Furthermore, the novelty of the path is:

[0162] ;

[0163] Among them, P The set of selected candidate execution paths; function execution paths The three types of information are: branch condition set Call information set and variable access information set Function execution path The three types of information are: branch condition set Call information set Variable access information set Path similarity Weight , For Jaccard similarity.

[0164] Furthermore, the path cost is a weighted sum of path length, cross-function call depth, and loop unrolling count.

[0165] Furthermore, positive and negative sample pairs are constructed based on the structural and semantic similarity between candidate execution paths, and the path encoding model is trained using a contrastive learning approach.

[0166] It should be noted that each module in this embodiment corresponds one-to-one with each step in Embodiment 1, and their specific implementation processes are the same, so they will not be repeated here.

[0167] The above description is merely a preferred embodiment of the present invention and is not intended to limit the invention. Various modifications and variations can be made to the present invention by those skilled in the art. Any modifications, equivalent substitutions, improvements, etc., made within the spirit and principles of the present invention should be included within the scope of protection of the present invention.

Claims

1. A method for detecting high-order vulnerabilities in source code based on execution path analysis, characterized in that, include: Obtain the source code to be analyzed, and construct a function execution graph for each function in the source code; the edges of the function execution graph are used to represent the relationships in the program execution process, including execution order relationships, function call relationships, variable propagation relationships, and write and read relationships of state persistence medium; On the function execution graph, starting from the function entry node, function execution paths are generated according to the execution order edges, and bounded constraints are applied to the function execution path generation process. A path priority function is used to calculate a priority score for any function execution path, and the function execution paths are sorted and filtered based on the priority scores to obtain candidate execution paths. The path priority function is a weighted sum of path risk warning information, path novelty, and path cost. For candidate execution paths, path-level features are obtained through a path encoding model; for each node in the function execution graph, statement feature vectors are obtained through a statement encoder, and the statement feature vectors are stacked sequentially according to the node index to obtain statement-level features; guided by the path-level features, the path-level features and statement-level features are fused through an attention mechanism to form a fused feature representation, and then the vulnerability type and vulnerability location are obtained through a vulnerability detection model. The path risk warning information is as follows: ;in, Indicates the function execution path The nodes on Indicates the node type. Preset weights for node types, This is the indicator of node risk hit. This represents a preset set of risk triggering modes. Weights for risk triggering modes function execution path The hit indicator corresponding to the risk triggering mode; The novelty of the path is: Among them, P The set of selected candidate execution paths; function execution paths The three types of information are: branch condition set Call information set and variable access information set Function execution path The three types of information are: branch condition set Call information set Variable access information set Path similarity Weight , For Jaccard similarity.

2. The method for detecting high-level vulnerabilities in source code based on execution path analysis as described in claim 1, characterized in that, The nodes in a function execution graph are used to represent statements, statement blocks, or consecutive basic code segments, and are associated with their source code location information, variable access information, and node type.

3. The method for detecting high-level vulnerabilities in source code based on execution path analysis as described in claim 1, characterized in that, The bounded constraints include the maximum path length, the maximum number of loop unrolls, and the maximum call depth.

4. The method for detecting high-level vulnerabilities in source code based on execution path analysis as described in claim 1, characterized in that, The path cost is a weighted sum of path length, cross-function call depth, and loop unrolling count.

5. The method for detecting high-level vulnerabilities in source code based on execution path analysis as described in claim 1, characterized in that, Positive and negative sample pairs are constructed based on the structural and semantic similarity between candidate execution paths, and the path encoding model is trained using a contrastive learning approach.

6. A source code high-level vulnerability detection system based on execution path analysis, characterized in that, include: The graph construction module is configured to: acquire the source code to be analyzed, and construct a function execution graph for each function in the source code; wherein, the edges of the function execution graph are used to represent the relationships in the program execution process, including execution order relationships, function call relationships, variable propagation relationships, and write and read relationships of state persistence media; The path generation module is configured to: generate function execution paths on the function execution graph starting from the function entry node and according to the execution order edges, and apply bounded constraints to the function execution path generation process; calculate a priority score for any function execution path using a path priority function, and sort and filter the function execution paths based on the priority scores to obtain candidate execution paths; wherein, the path priority function is a weighted sum of path risk warning information, path novelty, and path cost; The vulnerability detection module is configured as follows: for candidate execution paths, path-level features are obtained through a path encoding model; for each node of the function execution graph, statement feature vectors are obtained through a statement encoder, and the statement feature vectors are stacked sequentially according to the node index to obtain statement-level features; guided by the path-level features, the path-level features and statement-level features are fused through an attention mechanism to form a fused feature representation, and then the vulnerability type and vulnerability location are obtained through the vulnerability detection model. The path risk warning information is as follows: ;in, Indicates the function execution path The nodes on Indicates the node type. Preset weights for node types, This is the indicator of node risk hit. This represents a preset set of risk triggering modes. Weights for risk triggering modes function execution path The hit indicator corresponding to the risk triggering mode; The novelty of the path is: Among them, P The set of selected candidate execution paths; function execution paths The three types of information are: branch condition set Call information set and variable access information set Function execution path The three types of information are: branch condition set Call information set Variable access information set Path similarity Weight , For Jaccard similarity.

7. The source code high-level vulnerability detection system based on execution path analysis as described in claim 6, characterized in that, The nodes in a function execution graph are used to represent statements, statement blocks, or consecutive basic code segments, and are associated with their source code location information, variable access information, and node type.

8. The source code high-level vulnerability detection system based on execution path analysis as described in claim 7, characterized in that, The bounded constraints include the maximum path length, the maximum number of loop unrolls, and the maximum call depth.

Citation Information

Patent Citations

  • Program vulnerability path tracking method and device, computer equipment and storage medium

    CN111625835A

  • Vulnerability reachable path detection method and device combining SCA with SAST

    CN119337386A