A method and system for generative code recognition based on function prologue features

By analyzing the stack frame setup instructions at the function entry point, determining the compilation optimization level, and selecting an adaptive model, the problem of feature distribution drift in generative code detection is solved, achieving optimization level perception and recognition at the binary level, and improving detection performance.

CN123116266APending Publication Date: 2026-11-17NAT UNIV OF DEFENSE TECH
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202611292414.5
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-08-25
Publication Date
2026-11-17

AI Technical Summary

Technical Problem

Existing generative code detection technologies cannot adapt to the feature distribution shifts caused by different compilation optimization levels when dealing with the binary level, thus affecting detection performance.

Method used

By analyzing the stack frame setup instructions at the function entry point, the compilation optimization level is determined, and the corresponding pre-trained code detection model is selected based on the determination result to classify the functions and realize the recognition of generative code.

Benefits of technology

It effectively mitigates feature distribution drift caused by different compilation optimization levels, achieves optimization level awareness and recognition of generative code at the binary level, and improves detection performance.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN123116266A_ABST
    Figure CN123116266A_ABST
Patent Text Reader

Abstract

This application discloses a generative code recognition method and system based on function preface features, comprising: analyzing the stack frame creation instructions at the entry point of functions in an executable file to determine whether each function has a stack frame; determining the compilation optimization level of the executable file based on a comparison of the proportion of functions with stack frames among all functions with a preset threshold; selecting a corresponding pre-trained code detection model based on the determined compilation optimization level; and classifying the functions using the selected model to obtain the detection result of the code generation source. This application automatically determines the compilation optimization level by analyzing the stack frame creation instructions at the function entry point at the binary level, and adaptively selects the corresponding pre-trained code detection model based on the determination result. This ensures that the feature distribution of the detection model is relatively aligned with the feature distribution of the data to be detected, effectively mitigating the impact of feature distribution drift caused by different compilation optimization levels on detection performance.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This application relates to the fields of software security and code analysis technology, and in particular to a generative code recognition method and system based on function prologue features. Background Technology

[0002] With the development of large-scale language modeling technology, the use of generative code in software development is becoming increasingly common, leading to a growing demand for code tracing and security auditing. Most existing generative code detection technologies rely on source code or abstract syntax trees for analysis, making them unsuitable for scenarios where only compiled binary files are available. Some binary-level detection schemes use a single model to infer all compiled binary configurations, but neglect the impact of different compilation optimization levels on the distribution of instruction sequence features, resulting in fluctuating detection performance in practical applications as optimization levels change. Therefore, how to achieve automatic recognition of generative code with optimization level awareness at the binary level is a pressing technical problem that needs to be solved. Summary of the Invention

[0003] To address the shortcomings of existing binary-level generative code detection technologies that neglect differences in compiler optimization levels, leading to a misalignment between the feature distribution of the detection model and the data to be detected, this application provides a generative code recognition method and system based on function prologue features. This method determines the compiler optimization level by analyzing the stack frame establishment instructions at the function entry point and adaptively selects the corresponding pre-trained code detection model to classify the function accordingly. This effectively mitigates the impact of feature distribution drift across optimization levels on detection performance. Specifically, this application provides the following technical solutions: This application provides a generative code recognition method based on function prologue features, comprising: analyzing the stack frame creation instructions at the entry point of functions in an executable file to determine whether each function has a stack frame; determining the compilation optimization level of the executable file based on a comparison of the proportion of functions with stack frames among all functions with a preset threshold; selecting a corresponding pre-trained code detection model based on the determined compilation optimization level; and classifying the functions using the selected model to obtain the detection result of the code generation source.

[0004] Optionally, before analyzing the stack frame creation instructions at its entry point, the method further includes: disassembling the executable file to obtain the instruction sequence of each function.

[0005] Optionally, after disassembling the executable file, the method further includes filtering the functions obtained from the disassembly according to preset rules, wherein the preset rules include at least one of name blacklist matching, special character detection, and minimum instruction count threshold.

[0006] Optionally, the analysis of the stack frame creation instruction at the entry point includes: extracting the first few instructions at the function entry point, and if the first instruction is a control flow protection instruction, determining whether a stack frame creation instruction exists starting from the next instruction.

[0007] Optionally, determining the compilation optimization level of the executable file based on a comparison of the proportion of functions with stack frames among all functions with a preset threshold includes: when the proportion is greater than the preset threshold, determining the compilation optimization level of the executable file as low optimization level and selecting a pre-trained code detection model corresponding to the low optimization level; when the proportion is not greater than the preset threshold, determining the compilation optimization level of the executable file as high optimization level and selecting a pre-trained code detection model corresponding to the high optimization level; wherein, the determination of the stack frame creation instruction includes detecting whether the opcode of the instruction at the entry point contains a push operation and whether the operand contains a stack base address register.

[0008] Optionally, after obtaining the detection results of the code generation source, the method further includes: extracting statistical features based on the probability distribution of the detection results of the function, inputting the statistical features into a pre-trained aggregation model, and obtaining a software-level judgment result.

[0009] Optionally, the pre-trained code detection model is a multi-scale convolutional neural network, which includes: a word embedding layer for mapping the labels of the instruction sequence of the function to embedding vectors; multiple parallel one-dimensional convolutional layers of different scales for extracting local features of different spans respectively; a global max pooling layer for extracting the maximum response feature from the output of each convolutional layer; a feature concatenation layer and a fully connected classification layer for outputting the detection result based on the concatenated features.

[0010] Optionally, before inputting the instruction sequence of the function into the pre-trained code detection model, the method further includes: performing operand generalization processing on each instruction in the instruction sequence, and mapping the operands to predefined generalization tags according to their types.

[0011] The beneficial effects of this application are as follows: by analyzing the stack frame at the function entry point to establish instructions, the compilation optimization level is automatically determined, and the corresponding pre-trained code detection model is adaptively selected according to the determination result, so that the feature distribution of the detection model is relatively aligned with that of the data to be detected, which effectively alleviates the impact of feature distribution drift caused by different compilation optimization levels on detection performance, and realizes generative code recognition of binary files with optimization level awareness without source code. Attached Figure Description

[0012] Figure 1 This is a schematic diagram of the overall process of the generative code recognition method based on function prologue features provided in the embodiments of this application.

[0013] Figure 2 This is a schematic diagram of the function preamble stack frame analysis subprocess provided in an embodiment of this application.

[0014] Figure 3 This is a schematic diagram of the compilation optimization level determination and model selection process provided in the embodiments of this application.

[0015] Figure 4 This is a schematic diagram of a three-level serial process for function filtering provided in an embodiment of this application.

[0016] Figure 5 This is a schematic diagram of the multi-scale convolutional neural network model structure provided in the embodiments of this application.

[0017] Figure 6 This is a schematic diagram of the instruction operand generalization processing flow provided in the embodiments of this application.

[0018] Figure 7 This is a schematic diagram of the software-level aggregation and determination process provided in the embodiments of this application.

[0019] Figure 8 This is a schematic diagram of the structure of a generative code recognition system based on function prologue features provided in an embodiment of this application.

[0020] Figure labels: 1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 11; 12; 13; 14; 15; 16; 17; 18; 19; 10 ...9; 19; Detailed Implementation

[0021] To make the objectives, technical solutions, and advantages of this application clearer, the technical solutions of this application will be clearly and completely described below in conjunction with the accompanying drawings and specific embodiments. Obviously, the described embodiments are only a part of the embodiments of this application, and not all of them. Based on the embodiments in this application, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of this application.

[0022] Furthermore, the terms "first" and "second" are used for descriptive purposes only and should not be construed as indicating or implying relative importance or implicitly specifying the number of technical features indicated. Thus, a feature defined as "first" or "second" may explicitly or implicitly include one or more of that feature. In the description of this application, "multiple" means two or more, unless otherwise explicitly specified.

[0023] The generative code recognition method based on function prologue features provided in this embodiment is applicable to the automatic detection of generative code in compiled executable files. The executable files include, but are not limited to, ELF format, PE format, and Mach-O format executable files. The method can be deployed on various electronic devices with general-purpose processors, such as servers, workstations, personal computers, and embedded terminals. It can also be integrated into the automated detection stages of code auditing platforms, software supply chain security analysis systems, and continuous integration and continuous delivery pipelines.

[0024] like Figure 1 As shown, this method includes the following steps: S000, System Initialization and Model Loading.

[0025] The system loads all necessary static resources before the detection pipeline starts. The system reads the configuration file to obtain the disassembler path, loads the compiler-generated function name blacklist set, and calls the deserialization interface to load two pre-trained code detection model instances and one aggregator instance.

[0026] The configuration file is a structured text file in JSON or YAML format, containing at least four necessary fields: the executable file path of the disassembler, the filter rule file path, the model repository path, and the aggregator file path. The system sequentially verifies the validity of each path and terminates the initialization process if any path is invalid.

[0027] The persistent files of the pre-trained code detection model are serialized using the joblib format. Each model file contains four essential fields: model weight parameters, vocabulary, maximum sequence length, and vocabulary size. The model weight parameters include parameter tensors for all learnable layers in the network, exemplarily including the embedding matrix of the word embedding layer, the kernel weights and biases of each convolutional layer, and the weight matrix and bias vector of the fully connected layer. The vocabulary is a dictionary mapping strings to integers, mapping each token to a unique integer index, which is used as the row index of the embedding matrix in the word embedding layer. The system loads two model files sequentially through the joblib deserialization interface to obtain a model instance corresponding to a low optimization level and a model instance corresponding to a high optimization level, respectively. During loading, the system first extracts the model weight parameters from the persistent files, then constructs a multi-scale convolutional neural network structure based on the maximum sequence length and vocabulary size, and loads the weight parameters into the network structure to restore the model state at the time of training completion.

[0028] After loading, the system verifies that the vocabularies of the two model instances are completely consistent, meaning that the same token maps to the same integer index. The technical necessity of this consistency verification lies in the fact that the two models share the same set of operand generalization and tokenization processes. The token sequence of the function is encoded before model selection. If the vocabularies of the two models differ, the same token will be mapped to different embedding vectors in different models, causing the input semantics received by the model to be inconsistent with those during training, thus outputting meaningless detection results. The system performs verification by comparing the two vocabularies key by key; if they are inconsistent, an exception is thrown and the pipeline is terminated.

[0029] The system also loads a pre-trained aggregate model instance. The persistent file of the aggregate model is also serialized in joblib format and contains the complete decision tree structure and splitting parameters of the random forest classifier. After loading, the aggregate model instance resides in memory for subsequent software-level decision-making stages.

[0030] For example, the configuration file may include the disassembler path " / usr / bin / objdump", the filtering rule path " / etc / ai_detect / filter_rules.json", the model repository path " / models / ai_code_detect / ", and the aggregator path " / models / ai_code_detect / aggregator_rf.joblib". The system loads a low-optimization model file to obtain a model instance, extracts a vocabulary containing 1200 token-to-index mapping entries, with a maximum sequence length of 256 and a vocabulary size of 1200; it then loads a high-optimization model file and verifies that its vocabulary matches the former's 1200 entries key-by-key.

[0031] In an alternative implementation, the pre-trained code detection model can also be persisted using the `state_dict` format of the PyTorch framework. The `state_dict` format stores all learnable parameters of the model as key-value pairs in a `.pt` file, where the key is the hierarchical path name of the parameter and the value is the corresponding parameter tensor. The vocabulary mapping dictionary and configuration parameters (including maximum sequence length, embedding dimension, convolutional kernel size list, etc.) are stored as separate JSON files. During loading, the system first reads the network structure parameters from the JSON configuration file, instantiates a blank model object of a multi-scale convolutional neural network accordingly, and then loads the parameter tensors from the `.pt` file into the corresponding network layers through the `load_state_dict` interface. The advantage of the `state_dict` format is its compact storage and deep integration with the PyTorch ecosystem, facilitating incremental updates and fine-tuning of the model.

[0032] In another embodiment, the pre-trained code detection model can also be exported as a computation graph in ONNX (Open Neural Network Exchange) format. The ONNX format describes the computational flow of a neural network in the form of a directed acyclic graph, where each node represents a computational operation (e.g., convolution, pooling, fully connected, activation), and edges represent the transitive relationships of tensor data. During export, the system performs a forward propagation on the model using virtual input data to track all operations and data flows in the computation graph, serializing the tracked computation graph into an ONNX format protocol buffer file. During inference, the system uses the ONNX Runtime engine to load the ONNX file and perform forward propagation computation, thereby eliminating dependence on specific deep learning frameworks and gaining cross-platform inference capabilities. The ONNX Runtime also supports multiple hardware-accelerated backends, allowing selection of CPU-optimized or GPU-accelerated execution depending on the deployment environment.

[0033] S100, the executable file is disassembled to obtain the instruction sequence of each function.

[0034] The system performs a disassembly operation on the input executable file, extracting the boundary information and instruction sequences of all functions within the executable file. In this embodiment, the executable file is an ELF (Executable and Linkable Format) executable file. An ELF file consists of a file header, a program header table, a segment header table, and several segments. The code segment stores the compiled and linked machine instructions, and the symbol table segment stores function names and address information. The system confirms the file format and target architecture by parsing the ELF file header. After confirming the target architecture is x86-64, the disassembly operation begins. In an alternative embodiment, the executable file can also be a PE (Portable Executable) format Windows platform executable file. The PE file identifies the location and size of the code segment through its COFF header and optional header. The system can perform the same function extraction operation by parsing the PE header and calling the corresponding disassembler. Subsequent prologue analysis and optimization level determination logic are unaffected by file format differences. The disassembly employs a full-file linear scan mode, disassembling the executable file's code segments address-by-address to ensure coverage of the entire executable code region.

[0035] The system invokes an external disassembler via a subprocess, passing in full-file disassembly parameters and parameters to suppress raw bytecode output, and captures the disassembler's standard output text. The full-file disassembly parameters instruct the disassembler to disassemble all segments containing executable code in the executable file, rather than just processing a specified address range. The parameters to suppress raw bytecode output instruct the disassembler to omit the raw machine code bytes of each instruction in the output, retaining only mnemonics and operand representations to simplify subsequent text parsing. The standard output text follows the disassembler's fixed output specifications: each function begins with a function label line, followed by several instruction lines. The system uses regular expressions to match the label lines to identify function boundaries. The function label line format is hexadecimal address followed by a space, a function name enclosed in angle brackets, and a colon. The instruction line format is leading whitespace, hexadecimal address, colon, tab, mnemonic, optional tab, and operands. The system chooses full-file linear scan instead of recursive descent disassembly based on the following: linear scan mode does not rely on control flow analysis, can completely cover all bytes in the code segment, and avoids missing functions due to unresolved indirect jump targets. Although it may produce a small number of invalid disassembly results in the case of data embedded in the code segment, the subsequent filtering steps will exclude these invalid entries.

[0036] The system scans the standard output text line by line, maintaining the currently parsed function names and instruction buffers. The parsing process operates as a state machine: the initial state is waiting for the first function tag line. When a new function tag line is matched, the system stores the function name and instruction list of the previous function as a record in the original function set, then updates the current function name to the newly matched function name and clears the instruction buffer to begin collecting instructions for the new function. When an instruction line is matched, the system parses the mnemonic and operand strings from it, appending the instruction record (comprising the mnemonic and operands) to the current function's instruction buffer. Blank lines and comment lines that do not match function tag lines or instruction lines are ignored. After scanning is complete, the system stores the record of the last function in the original function set. Each element of the original function set contains a function name and an ordered list of instructions for that function, the order of which corresponds to their address order in the executable file.

[0037] For example, when a small executable containing 12 functions is disassembled, the system's regular expression matches 12 lines of function tags, and the output raw function set contains 12 records, where the function main contains 42 instructions and the function compute_hash contains 28 instructions.

[0038] In an alternative implementation, the Capstone disassembler engine can be used instead of a command-line disassembler. The Capstone disassembler engine is embedded in the system process via library function calls, eliminating the need to launch external child processes. The system reads the executable file in binary mode, obtains the offset positions of the program header table and segment header table by parsing the ELF file header, traverses the segment header table to find segment entries of type code segment and extracts the offset and length of that segment in the file, and then parses the symbol entries in the symbol table segment marked as functions to obtain the names and starting addresses of each function. The system passes the raw bytes and starting addresses of the code segment to Capstone's instruction-by-instruction disassembler interface. The Capstone engine decodes each byte sequence into instruction mnemonics and operands. The system then segments the disassembled result into instruction sequences for each function based on the function address range in the symbol table. Compared to command-line disassemblers, the Capstone engine avoids the overhead of inter-process communication and text parsing, but requires the system to implement its own file format parsing and function boundary determination logic.

[0039] In another implementation, the Ghidra Headless analyzer can be used to export all functions and their instruction sequences in a structured format by calling a custom analysis script via command line. The Ghidra analyzer employs a recursive descent disassembly strategy, starting from the program entry point and the function entry point in the symbol table, recursively disassembling subsequent instructions along the control flow path, and separately tracing and disassembling the two targets of branch instructions. Compared to linear scanning, the recursive descent strategy can handle data-embedded code segments and indirect jump scenarios more accurately, but may miss code that is not on the reachable control flow path.

[0040] S200 filters the functions obtained from disassembly according to preset rules.

[0041] like Figure 4 As shown, the system sequentially performs a three-level cascaded filtering on the original function set to remove compiler-generated functions, dynamic link stub functions, and excessively short functions, ensuring that the function set participating in subsequent analysis only contains functions that reflect the actual compilation behavior of the user's source code. The technical necessity of this filtering step lies in the fact that the original function set output by disassemblers typically contains a large number of functions automatically generated by the compiler toolchain. The instruction patterns of these functions are consistent across different user programs and do not contain discriminative information that can distinguish between generative code and manually written code. If stack frame ratio statistics and model inference are performed without filtering, fixed noise will be introduced, diluting the true characteristic signals of the user code.

[0042] The first level of the three-level cascaded filtering is name blacklist filtering. The system iterates through each function in the original function set, checking if its function name belongs to a predefined compiler-generated function name blacklist set. This blacklist set is a closed set containing functions with fixed names automatically inserted by the initialization and termination frames of the C runtime library. Functions in the blacklist have the same code template in different user programs; their instruction sequences are mechanically generated by the compiler or linker and do not reflect the programming style or compilation optimization choices of the user's source code. Including them in subsequent stack frame ratio statistics would introduce noise unrelated to the user's code. Functions that match the blacklist are marked for filtering and skipped from subsequent checks. The blacklist is implemented based on a hash set, with a time complexity of O(log n). .

[0043] The second level of the three-level concatenated filtering is special character detection filtering. For functions that pass the first level of filtering, the system checks whether their function names contain predefined special characters. In the symbol table of the executable file, the names of dynamic link stub functions typically contain specific suffix markers, such as a dot or the at symbol. The dot appears in the local symbol names generated internally by the compiler, and the at symbol appears in the name suffixes of procedural link table stub functions and dynamic symbol resolution stub functions. The function body of the stub function typically contains only one indirect jump instruction and one push instruction, without containing substantial computational logic; including it in stack frame analysis would interfere with statistical accuracy. When the system detects that a function name contains any of the above special characters, it marks the function as a stub function and filters it.

[0044] The third level of the three-level cascaded filtering is a minimum instruction count threshold filtering. For functions that pass the first two levels of filtering, the system counts the number of instructions for that function. If this number is less than the minimum instruction count threshold... If the value is too short, it is considered an excessively short function and filtered out. The minimum instruction count threshold is typically in the range of 3 to 10; this embodiment uses [a specific threshold]. The value is determined based on the requirement that a function preamble requires at least 1 to 3 instructions, plus at least 2 function instructions, to constitute a meaningful analysis unit. Functions with fewer than 5 instructions lack sufficient preamble information for stack frame determination, and too few instructions result in a short effective sequence after tokenization, with padding tokens dominating, making it impossible for code detection models to extract effective discriminative features. When When the value is less than 3, single-instruction or double-instruction functions are usually compiler-generated jump stubs or no-operation placeholders, lacking analytical value; when... When the value is greater than 10, some valid short utility functions may be mistakenly filtered out.

[0045] The three-level filtering process executes in a fixed order: name blacklist, special character detection, and minimum instruction count. If any level is hit, subsequent checks are skipped. This order is designed so that the first and second levels of filtering only require string matching operations, resulting in extremely low computational overhead. This allows for the rapid elimination of a large number of compiler-inserted functions and dynamic link stubs, reducing the number of functions requiring instruction counts in the third level of filtering. After filtering, the system verifies the number of remaining functions. Does it meet the requirements? If the conditions are not met, the pipeline is terminated and a report is submitted indicating that no valid function exists. The filtered function set... Total number of functions As input for subsequent steps.

[0046] For example, when the original function set contains 12 functions, the first-level blacklist filtering hits 6 compiler-generated functions, the second-level special character detection filtering hits 1 stub function, and the third-level minimum instruction count filtering hits 1 excessively short function containing only 3 instructions. After filtering, 4 user functions are retained, containing 42, 28, 35, and 18 instructions respectively, for a total of [number missing]. ,satisfy The minimum number of valid functions required.

[0047] In an alternative implementation, a filtering method based on executable file segment attributes can replace string matching. This method parses the executable file header and segment header table, traversing each segment entry in the segment header table to identify the address ranges of dynamically linked segments, initialization segments, and termination segments. The segment type of the dynamically linked segments is marked as relocatable or dynamic, and stores stub function code from the procedural link table and global offset table. The initialization and termination segments store initialization and cleanup functions that are automatically executed before program startup and upon program exit, respectively. When the starting address of a function falls within the address range of the aforementioned segments, the system directly marks the function as a non-user function and filters it. The advantage of this method is that it does not rely on string matching based on function names and is equally effective for binary files after removing symbol information (i.e., after stripping), but it requires precise parsing of the segment structure of the target file format.

[0048] In another implementation, a function call graph-based filtering method can be used. The system constructs a global function call graph by analyzing the target addresses of all call instructions in the executable file. In this graph, the user's main function is used as the root node, and a set of function nodes reachable from the main function is obtained through breadth-first or depth-first traversal. Function nodes that are only called by the dynamic linker or only serve as initialization termination hooks and are not in the reachable function set are considered non-user functions and filtered out. This method can more accurately identify the boundaries of user code, but constructing a complete call graph requires additional control flow analysis overhead, and may produce an incomplete call graph in the presence of indirect function pointer calls.

[0049] S300 analyzes the stack frame creation instructions at the entry point of functions in the executable file to determine whether each function has a stack frame.

[0050] like Figure 2 As shown, the system performs prologue instruction analysis on each function in the filtered function set to determine whether the function contains stack frame creation instructions and outputs the stack frame flag for each function. This prologue instruction analysis is the core creative step of the entire method. It infers the compiler optimization level by analyzing the patterns of a small number of instructions at the function entry point, without accessing compiler parameters, debugging information, or source code. The stack frame flag is a Boolean value stored in a flag array corresponding to the function index. Subsequent optimization level determination steps will make a determination based on the statistical characteristics of this flag array.

[0051] The system extracts the first few instructions at the entry point of each function as a preamble window. The size of the preamble window is... Typically, the value is in the range of 2 to 5; in this embodiment, it is taken as... Its value is determined by the fact that a standard function prologue consists of a maximum of three instructions: a control flow protection instruction, a stack push instruction, and a frame pointer set instruction. This is sufficient to cover all common preface patterns. When When the value is 2, in a compilation environment with Intel CET enabled, the first instruction at the function entry point is endbr64, leaving only one instruction bit for detecting push %rbp. Although this is just enough, it does not include the subsequent verification opportunity for mov %rsp,%rbp; when When the value is greater than 5, the window may expand beyond the function preamble to the function instruction area, increasing unnecessary computation without improving accuracy. If the function has fewer than 5 instructions... If the window size is the actual number of instructions, then this mainly occurs in very short leaf functions.

[0052] The system performs a two-step check on the preamble window. First, it checks if the opcode of the first instruction in the preamble window is the control flow protection instruction `endbr64`. The `endbr64` instruction is inserted at the function entry point by Intel CET (Control-flow Enforcement Technology) as an indirect branch termination marker. Intel CET is a hardware-level control flow integrity protection mechanism. When the processor enables CET's indirect branch tracing function, an `endbr64` instruction must be present at the target address of each indirect call or indirect jump; otherwise, the processor will trigger a control flow exception. In a CET-enabled compilation environment, the compiler automatically inserts an `endbr64` instruction at the entry point of each function. This instruction itself does not perform any operations; it only serves as a marker for a valid jump target. Since `endbr64` is not a stack frame creation operation, when the system detects that the first instruction is `endbr64`, it adjusts the starting position to the second instruction of the window to skip this safety marker instruction and directly check subsequent stack frame creation instructions. If the first instruction is not `endbr64`, it means that CET support was not enabled during the executable file compilation, and the system sets the starting position to the first instruction of the window.

[0053] The system checks at the starting position whether the instruction is a stack frame creation instruction. The rules for determining a stack frame creation instruction are: the instruction's opcode contains a push operation, and the instruction's operands include a stack base register. The stack base register is %rbp in x86-64 architecture and %ebp in x86 architecture. When both conditions are met, the system determines that the function has a stack frame and sets the stack frame flag. Otherwise set The mathematical form of its judgment rule is:

[0054] in If the first instruction is endbr64, otherwise . Returns the opcode string of the instruction. Returns the operand string. .

[0055] The technical basis for the above judgment rule is as follows: In the x86 / x86-64 architecture, the function call process follows a specific calling convention to manage the stack space. At low optimization levels (e.g., O0 level), the compiler by default generates a standard prologue `push %rbp` for functions, pushing the caller's frame pointer onto the stack. Then, it executes `mov %rsp,%rbp` to copy the current stack pointer to the frame pointer register to create a new stack frame. The technical function of this standard prologue is to provide a complete stack frame chain for the debugger and exception handling mechanism. Each function's `%rbp` points to the location where its caller's `%rbp` is stored, thus forming a stack frame linked list that traces back from the current function to the program entry point, allowing the debugger to perform stack backtracking by traversing this list. At high optimization levels (e.g., O2, O3 levels), the compiler enables frame pointer omission optimization. This optimization releases `%rbp` as a general-purpose register for operation allocation, reducing the number of instructions in the function prologue and epilogue. In frame pointer omission mode, the function no longer executes the `push %rbp` operation, but instead directly adjusts the stack pointer through the `sub` instruction to allocate space for local variables. Based on the aforementioned differences in compiler behavior, the presence or absence of push %rbp constitutes a signal for distinguishing between low and high optimization levels.

[0056] For example, performing a prologue analysis on the function `main` extracts the first three instructions as `endbr64`, `push %rbp`, and `mov%rsp,%rbp`. The first instruction is `endbr64`, and the starting position is set to the second instruction, `push %rbp`. This instruction's opcode contains `push` and its operand contains `%rbp`, thus determining... For the function `compute_hash`, the first three instructions are `push%rbp`, `mov %rsp,%rbp`, and `mov %rdi,-0x8(%rbp)`. The first instruction is not `endbr64`, and the starting position is the first instruction `push %rbp`, which also satisfies the condition. .

[0057] In another embodiment, the determination of the stack frame creation instruction can also be achieved by detecting the combination sequence of two instructions: `push %rbp` and `mov %rsp,%rbp`. This two-instruction determination method requires that the starting instruction is `push %rbp` and its next instruction is `mov %rsp,%rbp`; only when both instructions are satisfied is a stack frame determined to exist. This two-instruction determination method is more stringent than single-instruction determination, and can exclude a few special functions that only save the value of the `%rbp` register but do not use it as a frame pointer. For example, some manually written assembly functions save the caller's `%rbp` at the entry point but directly access local variables through `%rsp` plus an offset, without creating a standard stack frame. However, this two-instruction determination method requires a window size. A minimum of 3 (which requires overriding endbr64 and two frame setup instructions when CET is enabled) increases the minimum window size requirement.

[0058] In an alternative implementation, a method based on stack operation instruction statistics can be used. This statistical method iterates through all instructions in the preamble window, counting the number of instructions involving operations on the stack pointer register %rsp, including push, sub %rsp, and mov %rsp operations. The ratio of the number of stack operation instructions to the total number of instructions in the window is used as the stack operation density. When the stack operation density exceeds a preset density threshold, explicit stack frame management is determined to exist. This method offers better fault tolerance for non-standard preamble modes, but introduces an additional density threshold parameter.

[0059] S400, the compilation optimization level of the executable file is determined based on the comparison result of the proportion of functions with stack frames among all functions and a preset threshold.

[0060] like Figure 3 As shown, the system determines the compilation optimization level of the executable file based on the statistical results of the stack frame flags of all functions, and selects the corresponding pre-trained code detection model accordingly. The technical motivation for the adaptive model selection of the optimization level is that the binary code generated by different compilation optimization levels has significant differences in instruction patterns. Using a single model cannot simultaneously adapt to two completely different instruction distributions of low optimization and high optimization. Therefore, it is necessary to determine the optimization level first and then select a dedicated model that matches it.

[0061] The system calculates the stack frame ratio. The calculation formula is as follows:

[0062] in The total number of functions in the filtered function set. This serves as the stack frame flag for each function. The range of values ​​is This represents the proportion of functions that have stack frames among all functions. Approaching version 1.0 indicates that the vast majority of functions retain the standard stack frame creation sequence, corresponding to low-optimization compilation behavior; when A value close to 0 indicates that the vast majority of functions performed frame pointer omission optimization, corresponding to a high level of compilation optimization. In a typical compilation scenario, an executable file compiled with O0 will... Typically in the range of 0.90 to 1.00, a few functions may not include a standard prologue due to the compiler's special handling of inline assembly; executables compiled using O2 or O3... Typically in the range of 0.05 to 0.50, a small number of functions still retain stack frames for reasons including the use of variable-length arrays, stack operations in inline assembly, or being marked as non-optimizable.

[0063] The system compares the stack frame ratio with a preset threshold. Comparison. When When the executable file's compilation optimization level is determined to be low, a pre-trained code detection model corresponding to the low optimization level is selected; when Not greater than When the compilation optimization level is determined to be high optimization level, a pre-trained code detection model corresponding to the high optimization level is selected. The preset threshold... Typically, the value is in the range of 0.70 to 0.95; this embodiment uses... It is set within a safe region between the lower bound of the stack frame ratio for low optimization (approximately 0.90) and the upper bound of the stack frame ratio for high optimization (approximately 0.50), providing a safety margin of approximately 0.05. The existence of this safe region ensures that the threshold selection maintains correctness across a wide range: when... When taking values ​​in the range of 0.80 to 0.90, due to the differences between low and high optimization levels... There is a wide interval of approximately 0.40 between the distributions, and the judgment results remain stable for the vast majority of real samples. When At speeds below 0.70, in mixed compilation scenarios, high-optimization executables containing some unoptimized external library functions may be misclassified as low-optimization executables; when At values ​​above 0.95, misjudgments may occur in low-optimization executables that link a small number of external library functions that do not retain frame pointers.

[0064] The technical basis for sharing two pre-trained models for the low-optimization level and the high-optimization level is as follows: In the low-optimization level, the compiler generates standard stack frames by default, causing most user functions to include a `push %rbp` preamble; in the high-optimization level, after enabling frame pointer omitting optimization, many functions no longer create explicit stack frames. The O2 and O3 optimization levels have minimal differences in frame pointer omitting behavior, both enabling it by default. The main difference lies in backend optimization strategies such as loop unrolling and automatic vectorization. These backend optimizations affect the instruction selection and arrangement order within the function body, but do not change the frame pointer creation behavior in the function preamble. Therefore, they can share the same detection model, reducing model maintenance overhead without sacrificing detection accuracy.

[0065] For example, when the filtered function set contains 4 functions and the stack frame flag of all functions is 1, , If the result is determined to be of low optimization level, the corresponding low optimization level pre-trained model is selected. When another executable file, after filtering, contains 20 functions, and only 6 of them have stack frames... , If it is determined to be at a high optimization level, the corresponding high optimization level pre-trained model is selected.

[0066] In another embodiment, the determination of the compilation optimization level can also be achieved through joint determination of multiple features. In addition to the stack frame ratio, the system additionally calculates the following auxiliary features: the average number of instructions in the filtered functions (low-optimization-level functions typically contain more instructions due to unexecuted instruction merging and dead code elimination), the frequency of specific instructions (for example, nop-aligned instructions appear more frequently in high-optimization-level functions), and the variance of instruction distribution between functions. The multi-dimensional feature vector composed of the stack frame ratio and the above auxiliary features is input into a pre-trained support vector machine or a small neural network classifier for optimization level determination. This multi-feature approach... It exhibits better robustness in decision-making on fuzzy samples near the threshold boundary (exemplarily between 0.80 and 0.90), but increases the computational overhead of feature extraction and the complexity of model training.

[0067] In an alternative implementation, a cluster-based determination method can be used. The system encodes the preamble features of each function (including the presence of `push %rbp`, the number of preamble instructions, and the presence of `sub %rsp` instructions) into a low-dimensional feature vector, and performs K-means clustering analysis on the preamble feature vectors of all functions. The system categorizes clusters into two levels: low optimization and high optimization. It calculates the distance between each cluster center and a predefined optimization-level feature prototype, mapping each cluster to its corresponding optimization-level label. This method eliminates the need for preset threshold parameters and adaptively accommodates differences in prologue patterns generated by different compiler versions; however, the clustering results may be unstable due to a small number of functions.

[0068] S500: The selected model is used to classify the function to obtain the detection results of the code generation source.

[0069] like Figure 5 and Figure 6As shown, the system utilizes a selected pre-trained code detection model to perform binary classification inference on each function in the filtered function set, obtaining function-level generative probabilities as the detection results for the code generation source. The inference process includes three stages: first, operand generalization processing is performed on the original assembly instruction sequence of the function to generate a token sequence; then, the token sequence is encoded and its length is standardized to adapt to the fixed input format of the model; finally, the encoded token sequence is input into the selected multi-scale convolutional neural network for forward propagation to obtain the classification probability. During the inference stage, the model runs in evaluation mode, which disables the random behavior of the random deactivation layer and batch normalization layer during training, ensuring that the same input always produces the same output. The system also disables gradient calculation to reduce memory consumption and accelerate the inference process.

[0070] The system performs operand generalization processing on the instruction sequence of each function. The operand generalization processing performs the following steps sequentially for each assembly instruction: First, the instruction is split into two parts, a mnemonic and operands, using whitespace characters. The mnemonic is retained as the original token without transformation. Then, the operand part is split into one or more independent operand segments using comma separators. Type identification and generalization mapping are performed on each operand segment. The type identification determination order is as follows: First, check if the operand segment starts with a percent sign followed by a register name. If so, it is further classified according to the register bit width: names prefixed with 'r' and belonging to 64-bit general-purpose registers are mapped to the REG64 label; names prefixed with 'e' and belonging to 32-bit general-purpose registers are mapped to the REG32 label; and 8-bit registers are mapped to the REG8 label. If the operand segment starts with a dollar sign, it is identified as an immediate value and mapped to the IMM label. If the operand segment contains parentheses and the parentheses contain register references, it is further distinguished based on the presence of offsets and index registers: a mapping containing only a base register is labeled MEM_BASE; a mapping containing a combination of offset and base register is labeled MEM_DISP; and a mapping containing a base register, index register, and scaling factor is labeled MEM_IDX. If the operand segment is a hexadecimal address, it is mapped to JMP_REL; and an address prefixed with an asterisk is mapped to JMP_ABS. Operand segments that do not conform to any of the above rules are preserved as independent tokens. After the above processing, each instruction produces a subsequence consisting of a mnemonic token and several generalized operand tokens. All subsequences of the instructions are concatenated in their original order to form the complete token sequence of the function. The technical purpose of the generalization processing is to map semantically equivalent operands to the same token, thereby reducing the vocabulary size and improving the model's generalization ability to different register allocations and address offsets.

[0071] The system adds a classification tag CLS to the beginning of the generalized token sequence and unifies the sequence length to the maximum sequence length. The aforementioned Typically, the value is in the range of 128 to 512; in this embodiment, it is taken as... The value is based on the fact that the length of the tokenized sequence for most user functions is between 100 and 300. It can completely retain all the instruction information of most functions; if the value is too small, too much information will be truncated, leading to a decrease in detection accuracy; if the value is too large, the padding ratio and computational overhead will increase. When the token sequence length exceeds... At that time, cut off from the tail to Retain the prologue and initial instructions at the beginning of the function, as the instruction pattern at the beginning of the function is more discriminative in distinguishing between generated code and manually written code; when insufficient At the same time, PAD markers are filled in at the end. The system also generates an attention mask, marking the valid token position as 1 and the PAD position as 0. The attention mask enables the model to distinguish between valid content and filling positions during the calculation process.

[0072] The pre-trained code detection model is a multi-scale convolutional neural network, which includes a word embedding layer, multiple parallel one-dimensional convolutional layers of different scales, a global max pooling layer, a feature concatenation layer, and a fully connected classification layer.

[0073] The word embedding layer is used to map the labels of the instruction sequence of the function into embedding vectors. Internally, the word embedding layer maintains a learnable embedding matrix, the number of rows of which is equal to the size of the vocabulary. The number of columns equals the embedding dimension. The integer index of each token is used as the row index to look up and return the corresponding token in the matrix. A dense vector. Typically, the value is in the range of 32 to 128; in this embodiment, it is taken as... The selection criteria are as follows: the semantic granularity of assembly instruction-level tokens is coarser than that of natural language vocabulary, and 64 dimensions are sufficient to capture the semantic differences between opcode categories and operand types; values ​​that are too small may not adequately represent the semantic distinctions between different instructions, while values ​​that are too large increase the number of model parameters and the risk of overfitting. The vocabulary size... This value covers approximately 500 mnemonics for the x86-64 instruction set, approximately 20 types of generalized operand tokens, and special tokens such as classification tokens, padding tokens, and unknown tokens, with some margin to accommodate special instructions generated by different compilers. After processing by the word embedding layer, the input index sequence Converted into an embedding matrix Each row of the matrix corresponds to an embedding vector of a token.

[0074] The parallel one-dimensional convolutional layers of different scales are used to extract local features of different spans. This embodiment sets up three parallel convolutions with kernel sizes of 3, 5, and 7, and the number of input channels for each convolution is equal to... The output channel count is 64. The one-dimensional convolution operation slides the convolution kernel along the sequence dimension, performing a weighted summation on the embedding vectors of several consecutive tokens to extract local pattern features. The convolutional layer uses a no-padding mode, and the kernel size is [missing information]. The length of the output sequence is A convolutional kernel of size 3 has a receptive field covering 2 to 3 adjacent instructions, capturing short-range local patterns at the instruction pair level, such as a stack frame creation sequence consisting of `push` and `mov`. A convolutional kernel of size 5 has a receptive field covering 4 to 5 instructions, capturing medium-span operation sequence patterns, such as a complete action sequence from stack frame creation to parameter saving in a function preamble. A convolutional kernel of size 7 has a receptive field covering 6 to 7 instructions, capturing longer-span code structure patterns, such as a combination of loop initialization and conditional judgment instructions. The three convolutional paths output feature maps respectively. , and The purpose of the multi-scale parallel design is to enable the model to simultaneously perceive instruction sequence features of different granularities, avoiding the limitation that a single-scale convolutional kernel can only capture local patterns with a fixed span.

[0075] The global max pooling layer is used to extract the maximum response feature from the output of each convolutional layer. The global max pooling layer takes the maximum value along the sequence dimension of each feature map, obtaining... , and The global max pooling technique extracts the maximum activation value of each feature channel from the variable-length convolution output, ensuring that the pooled output is always a fixed-dimensional vector regardless of the original instruction length of the function. This transforms the variable-length input problem into a fixed-length feature classification problem. Compared to global average pooling, max pooling is more sensitive to key instruction patterns and can more effectively capture discriminative features that distinguish generative code from manually written code.

[0076] The feature concatenation layer and fully connected classification layer are used to output the detection result based on the concatenated features. The feature concatenation layer concatenates the three pooling vectors along the channel dimension. The concatenation allows subsequent classification layers to simultaneously utilize feature information extracted by convolutional kernels of three different scales. The fully connected classification layer employs a two-stage fully connected structure: the first stage maps the 192-dimensional feature vector to 64 dimensions, and after ReLU non-linear activation, the second stage maps the 64-dimensional vector to a 2-dimensional output. A random deactivation layer is placed before both fully connected layers; this random deactivation is applied probabilistically during the training phase. Randomly setting the neuron output to zero forces the network to learn more generalized feature representations rather than relying on strong responses from a few neurons. Typically, the value is in the range of 0.2 to 0.5; in this embodiment, it is taken as... The fully connected layer outputs a two-dimensional vector. ,in and The unnormalized log probabilities of manually written categories and generative categories are given, respectively. After normalization using the softmax function, the generative probabilities are obtained.

[0077] The The range of values ​​is , representing a function The probability of generative code.

[0078] For example, operand generalization is performed on the function `main`. The instruction `endbr64` retains the mnemonic `endbr64`, the instruction `push %rbp` is generalized to `push` with a REG64 tag, the instruction `mov %rsp,%rbp` is generalized to `mov` with two REG64 tags, and the instruction `sub \$0x20,%rsp` is generalized to `sub` with an IMM tag and a REG64 tag. After generalization, the token sequence is marked with a CLS tag and padded with PADs up to 256. After the four functions are inferred by the model, the generative probabilities obtained are 0.23, 0.87, 0.15, and 0.91, respectively.

[0079] In another embodiment, the pre-trained code detection model can also be implemented using a bidirectional long short-term memory (LSTM) network. The bidirectional LSTM network comprises an embedding layer and two bidirectional LSTM layers with a hidden dimension of 64. The bidirectional LSTM processes the tokenized instruction sequence stepwise along both the forward and reverse directions of the sequence. Each LSTM maintains a hidden state and a memory cell state at each time step, controlling the inflow, retention, and output of information through three gating mechanisms: an input gate, a forget gate, and an output gate. The model concatenates the forward and reverse hidden states at the last time step into a 128-dimensional classification feature vector, which is then passed through a fully connected layer to output a binary classification result. The advantage of the bidirectional LSTM is its ability to capture long-distance dependencies between instructions, such as the association between the introductory pattern at the beginning of a function and the coda pattern at the end.

[0080] In an alternative implementation, the pre-trained code detection model can also be implemented using a Transformer encoder based on a multi-head self-attention mechanism. The Transformer encoder consists of two stacked encoder layers, each containing a four-head self-attention module and a feedforward neural network module. The self-attention mechanism calculates the attention weights between any two token positions in the sequence, enabling the model to directly model instruction pairs at arbitrary distances, unaffected by the receptive field limitations of the convolutional kernels. The model takes the output vector at the CLS marker position as the representation of the entire sequence, and outputs the detection result through a fully connected layer. The computational complexity of the Transformer encoder is on the order of the square of the sequence length; when the sequence length is 256, approximately 65,536 attention calculations are required, which is computationally expensive than multi-scale convolutional neural networks.

[0081] S600, based on the probability distribution of the detection results of the function, extract statistical features, input the statistical features into the pre-trained aggregation model, and obtain software-level judgment results.

[0082] like Figure 7As shown, the system aggregates the generative probabilities of all functions into a software-level decision, outputting the final decision result and a list of suspicious functions. The technical necessity of this aggregation lies in the fact that function-level detection results only reflect the confidence level of the code generation source of a single function, while actual security audits and compliance checks typically require a holistic determination of whether the entire executable file is generative. In hybrid programming scenarios (where some functions are manually written and others are generated by generative tools), simply taking the maximum or average of all function probabilities as the software-level decision may introduce bias: the maximum value strategy is too sensitive to a single misclassified high-probability function, while the average value strategy is diluted by a large number of low-probability manually generated functions. Therefore, the system employs an aggregation strategy based on multidimensional statistical features, extracting statistics from the probability set that fully describe its distribution characteristics, and then inputting these statistics into a trained aggregation model for decision-making.

[0083] The system originates from a set of function-level generative probabilities. Extracting statistical feature vectors The extraction of the statistical feature vectors is divided into three categories of features.

[0084] The first category is characterized by central tendency and dispersion. The system calculates the probability mean. This is used to reflect the overall generative tendency of all functions. The system considers the probability set... Take the median after sorting The median is more robust to extreme probability values ​​than the mean, and it more stably reflects typical probability levels when the number of functions is small. The system calculates the standard deviation. The standard deviation is used to measure the dispersion of the probability distribution; the larger the standard deviation, the greater the difference in the generative probabilities of each function, suggesting that the executable file may contain both generative functions and manually written functions.

[0085] The second category is tail distribution and extreme value characteristics. The system calculates the 75th, 90th, 95th, and 99th quantiles to characterize the right-tail shape of the probability distribution, i.e., the concentration of high-probability functions and the distribution of extreme values. The system also records the maximum value. This is the highest generative probability of a single function. The system extracts the mean of the Top-5% and the mean of the Top-10% elements from the sorted probability set, that is, selects the highest probability elements. One and before The probability mean of each function is used to capture the average confidence level of the most suspicious function group.

[0086] The third category is the proportion of high-probability functions. The system uses thresholds of 0.5, 0.7, and 0.9 respectively to statistically analyze the proportion of functions whose probabilities exceed each threshold. The system calculates the absolute number and normalized value of the function. The three thresholds correspond to relaxed, moderate, and strict generative decision criteria, respectively, and the resulting gradient ratio reflects the central tendency of the probability distribution at different confidence levels. The system also calculates the logarithm of the total number of functions. This is used to eliminate the impact of differences in the number of functions in executable files of different sizes on statistical characteristics.

[0087] The statistical feature vector The input is a fixed 17-dimensional real vector. Since different executables contain different numbers of functions, directly using a variable-length probability set cannot fit the aggregation model with a fixed input dimension. By extracting the three types of statistics mentioned above, the system maps the variable-length probability set to a fixed-dimensional representation, preserving key characteristics such as the central tendency, dispersion, and tail behavior of the distribution while eliminating the influence of differences in the number of functions.

[0088] The system inputs the statistical feature vector into a pre-trained aggregation model to obtain a software-level judgment score. The aggregation model is a random forest classifier, composed of multiple decision trees. The training process of the random forest employs a bagging strategy: each decision tree samples with replacement from the training set to obtain an independent training subset, and at each split node, a subset is randomly selected from all feature dimensions as candidate split features. From these candidate features, the feature that maximizes the reduction in information gain or Gini impurity, along with a splitting threshold, is selected for node splitting. This dual randomization of sample and feature sampling ensures diversity among the decision trees, reducing the ensemble model's sensitivity to noise in the training data. During inference, the statistical feature vector is fed into each decision tree, and each decision tree traverses the splitting path from the root node to the leaf node, outputting a binary classification prediction. The output of the random forest... Predict generative voting proportions for all decision trees. The range of values ​​is , representing the confidence level for determining it as generative. The technical basis for choosing random forest as the aggregation model is that random forest is not sensitive to scale differences in feature dimensions and does not require additional normalization processing of statistical feature vectors; at the same time, random forest can effectively handle nonlinear interaction relationships between features, such as the combination pattern of high probability function proportion and probability standard deviation.

[0089] The system will Software-level judgment threshold Comparison. When When, the executable file is determined to be a generative type; when At that time, it was determined to be manually written. Typically, the value is in the range of 0.3 to 0.7; in this embodiment, it is taken as... This represents the natural decision boundary in a binary classification task. (The last part, "reducing," appears to be an unrelated fragment and is left untranslated.) This will improve the recall rate of detection but also increase the false positive rate, making it suitable for scenarios such as security audits where it is better to overreport than underreport; This reduces the false positive rate but may miss some generative code, making it suitable for scenarios sensitive to the cost of false positives. The system also sorts functions in descending order of generative probability and outputs a Top-K list of suspicious functions, providing auditors with a priority reference for manual review.

[0090] For example, when and First, calculate the central tendency and dispersion characteristics: probability mean. Sort the probability set as The median was then taken as Standard deviation Calculate the tail distribution feature: the maximum value is 0.91, and the mean of the top-5% and top-10% elements is 0.91 across all four samples (taking the element with the highest probability). Calculate the proportion of high-probability functions: the proportion of high-probability functions with a threshold of 0.5 is... The proportion with a threshold of 0.7 is The proportion with a threshold of 0.9 is The total number of functions is logarithmic. By inputting the aforementioned 17-dimensional statistical feature vector into the random forest aggregator, an exemplary result can be obtained. , The function was determined to be a generative function. The list of suspicious functions, sort_results (0.91) and compute_hash (0.87) in descending order of probability, can be prioritized for manual review by auditors.

[0091] In an alternative implementation, the aggregation model can also be implemented using a threshold voting method. The threshold voting method assigns the generative probabilities of each function... Compared with the function-level decision threshold (usually 0.5), if If the function is voted as generative, then the vote is for manually written functions; otherwise, the vote is for manually written functions. The system calculates the proportion of functions that are voted as generative. If this proportion exceeds a software-level voting threshold, the entire executable file is determined to be generative. This threshold voting method is simple to implement and does not require training an aggregation model, but discretizing continuous probability values ​​into binary voting results in significant information loss and fails to utilize rich information such as the shape and tail characteristics of the probability distribution.

[0092] In another embodiment, the aggregation model can also be implemented using a gradient boosting tree. The gradient boosting tree sequentially constructs multiple decision trees, with each new decision tree fitting the residuals of all preceding decision trees. Overall accuracy is improved by iteratively correcting the prediction error. The input to the gradient boosting tree is the same as that of the random forest, which is the statistical feature vector. Compared to the independent parallel training strategy of random forests, the sequential error correction mechanism of gradient boosting trees gives them a stronger ability to model feature interactions. However, during training, the decision trees have sequential dependencies, which does not support parallel training. Furthermore, they are more sensitive to hyperparameters (such as learning rate and tree depth) and require more careful parameter tuning.

[0093] Based on the same inventive concept, embodiments of this application also provide a generative code recognition system based on function prologue features. For example... Figure 8 As shown, the system includes a preamble analysis module 1, an optimization level determination module 2, a model selection module 3, and a function classification module 4. These four modules are organized in a serial pipeline manner: the output of the preamble analysis module 1 serves as the input to the optimization level determination module; the output of the optimization level determination module 2 serves as the input to the model selection module; and the output of the model selection module 3, together with the filtered function set, serves as the input to the function classification module 4. The system runs on a computing device equipped with a processor and memory. The processor can be a general-purpose central processing unit or a heterogeneous computing platform equipped with a graphics processing unit. The memory stores computer programs that implement the functions of each module. The processor loads and executes the computer programs to implement the steps of the above method.

[0094] The preface analysis module 1 is used to analyze the stack frame creation instructions at the entry points of functions in the executable file to determine whether each function has a stack frame. The preface analysis module receives a filtered set of functions as input, extracts the first few instructions at the entry point of each function, detects control flow protection instructions and adjusts the judgment start position, checks whether the instruction at the target location is a push operation and whether the operand includes the stack base address register, and outputs the stack frame flag for each function. The preface analysis module can be implemented by the processor executing a computer program stored in memory.

[0095] The optimization level determination module 2 is used to determine the compilation optimization level of the executable file based on a comparison between the proportion of functions with stack frames among all functions and a preset threshold. The optimization level determination module receives the stack frame flag set and the total number of functions output by the prologue analysis module, calculates the stack frame proportion and compares it with the preset threshold, and outputs a compilation optimization level label. The optimization level determination module can be implemented by a processor executing a computer program stored in memory.

[0096] The model selection module 3 is used to select the corresponding pre-trained code detection model based on the determined compilation optimization level. The model selection module receives the compilation optimization level label output by the optimization level determination module, selects a reference to a pre-trained code detection model instance corresponding to that optimization level from the pre-loaded model instance cache, and outputs the selected model instance. The model selection module can be implemented by a processor executing a computer program stored in memory.

[0097] The function classification module 4 is used to classify the functions using the selected model to obtain detection results of the code generation source. The function classification module receives the model instance and filtered function set output by the model selection module, performs operand generalization and tokenization on each function, inputs the token sequence into the selected multi-scale convolutional neural network for forward propagation, and outputs the function-level generative probability as the detection result. The function classification module can be implemented by a processor executing a computer program stored in memory.

[0098] Furthermore, the functional units in the various embodiments of this application can be integrated into one processing unit, or each unit can exist physically separately, or two or more units can be integrated into one unit. The integrated unit described above can be implemented in hardware.

[0099] The above description is merely a specific embodiment of this application, but the scope of protection of this application is not limited thereto. Any changes or substitutions within the technical scope disclosed in this application should be included within the scope of protection of this application. Therefore, the scope of protection of this application should be determined by the scope of the claims.

Claims

1. A generative code recognition method based on function prologue features, characterized in that, include: For functions in an executable file, analyze the stack frame creation instructions at their entry points to determine whether each function has a stack frame. The compilation optimization level of the executable file is determined by comparing the proportion of functions with stack frames among all functions with a preset threshold. Select the corresponding pre-trained code detection model based on the determined compilation optimization level; The selected model is used to classify the function to obtain the detection results of the code generation source.

2. The method according to claim 1, characterized in that, Before analyzing the stack frame creation instructions at its entry point, the analysis also includes: The executable file is disassembled to obtain the instruction sequence of each function.

3. The method according to claim 2, characterized in that, After disassembling the executable file, the process further includes: The functions obtained from disassembly are filtered according to preset rules, which include at least one of name blacklist matching, special character detection, and minimum instruction number threshold.

4. The method according to claim 1, characterized in that, The analysis of the stack frame creation instructions at its entry point includes: Extract the first few instructions at the function entry point. If the first instruction is a control flow protection instruction, determine whether there is a stack frame creation instruction starting from the next instruction.

5. The method according to claim 1, characterized in that, The step of determining the compilation optimization level of the executable file based on a comparison of the proportion of functions with stack frames among all functions with a preset threshold includes: When the proportion is greater than the preset threshold, the compilation optimization level of the executable file is determined to be low optimization level; when the proportion is not greater than the preset threshold, the compilation optimization level is determined to be high optimization level; based on the determined compilation optimization level, a corresponding pre-trained code detection model is selected. The determination of the stack frame creation instruction includes detecting whether the opcode of the instruction at the entry point contains a push operation and whether the operand contains a stack base address register.

6. The method according to claim 1, characterized in that, After obtaining the detection results of the code generation source, the process also includes: Statistical features are extracted based on the probability distribution of the detection results of the function, and the statistical features are input into a pre-trained aggregation model to obtain software-level judgment results.

7. The method according to claim 2, characterized in that, The pre-trained code detection model is a multi-scale convolutional neural network, which includes: A word embedding layer is used to map the tokens of the instruction sequence of the function into embedding vectors; Multiple one-dimensional convolutional layers of different scales are used in parallel to extract local features of different spans. A global max pooling layer is used to extract the maximum response feature from the output of each convolutional layer; The feature concatenation layer and the fully connected classification layer are used to output the detection results based on the concatenated features.

8. The method according to claim 7, characterized in that, Before inputting the instruction sequence of the function into the pre-trained code detection model, the method further includes: Operand generalization processing is performed on each instruction in the instruction sequence, mapping the operands to predefined generalization tags according to their types.

9. A generative code recognition system based on function prologue features, characterized in that, include: The preface analysis module is used to analyze the stack frame creation instructions at the entry point of functions in the executable file and determine whether each function has a stack frame. The optimization level determination module is used to determine the compilation optimization level of the executable file based on the comparison result of the proportion of functions with stack frames among all functions and a preset threshold. The model selection module is used to select the corresponding pre-trained code detection model based on the determined compilation optimization level; The function classification module is used to classify the function using the selected model and obtain the detection results of the code generation source.

10. A computer-readable storage medium having a computer program stored thereon, characterized in that, When the computer program is executed by a processor, it implements the method of any one of claims 1 to 8.