An Optimization Method for Instruction Conversion Context Switching Based on Stack Frame Hierarchical Compression
By adopting instruction conversion method based on stack frame layer compression between different computer architectures, the problem of inaccurate context recovery in the prior art is solved, efficient context preservation and recovery is achieved, and the correct execution of the program is ensured.
Patent Information
- Application Number
- CN202510307611.9
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2025-03-17
- Publication Date
- 2025-06-03
- Estimated Expiration
- 2045-03-17
AI Technical Summary
When performing instruction conversion between different computer architectures, existing methods have shortcomings in register mapping, stack frame processing and consistency maintenance, resulting in inaccurate context recovery and affecting the correct execution of the program.
Using the instruction conversion method based on stack frame layer compression, the executable file is loaded through dynamic instruction conversion to establish a set of save instructions and a set of recovery instructions that include the complete process of context switching. In the storage stage, a register group is constructed based on the correlation degree of the register to realize the merge and storage of register data; in the recovery stage, the recovery of register data and stack-pressed data is realized based on the mapping relationship table and the correlation relationship table.
Improves the execution efficiency of context preservation and recovery, enhances flexibility in processing complex nested structures and data type, and ensures correct execution of programs.
Smart Images

Figure CN119829133B_ABST
Abstract
Description
Technical Field
[0001] The present invention belongs to the technical field of computer architecture and instruction set conversion, and particularly relates to an optimization method for instruction conversion context switching based on stack frame hierarchical compression. Background Art
[0002] In the x86 system, to achieve concurrent execution of multiple tasks, context switching between different tasks is required. Context switching refers to saving the execution state of the current task, i.e., the context, and then loading the context of another task so that the CPU can continue to execute another task. The registers and operations involved in this process include: general-purpose registers, where the values of all general-purpose registers need to be saved, including EAX, EBX, ECX, EDX, ESI, EDI, etc.; control registers, such as the base pointer register EBP and the stack pointer register ESP, which are used to save and restore the stack state of the task; segment registers, such as CS, DS, ES, FS, GS, etc., which are used to save and restore the memory segment information of the task. For example, when the operating system kernel performs context switching, it saves the states of all registers of the current task into the task control block (TCB) of that task, then loads the corresponding register states from the TCB of another task, and finally jumps to the execution position of that task to continue execution.
[0003] Therefore, when performing instruction conversion between different computer architectures, the context saving and restoration during program execution are crucial. Existing methods usually simply integrate the basic characteristics of the x86 and ARM architectures, and there are many deficiencies in register mapping, stack frame processing, and consistency maintenance. For example, the fixed register mapping method cannot adapt to the diversity of register usage in different x86 programs; when performing stack frame conversion, the processing of complex nested structures and data types is not flexible enough, resulting in inaccurate context restoration and thus affecting the correct execution of the program. Summary of the Invention
[0004] In view of this, the present invention provides an optimization method for instruction conversion context switching based on stack frame hierarchical compression, which realizes the conversion of instructions related to context saving and restoration and improves the execution efficiency of context saving and restoration.
[0005] The optimization method for instruction conversion context switching based on stack frame hierarchical compression provided by the present invention specifically includes the following steps:
[0006] Step 1, constructing an x86 target instruction set related to context switching, and loading and executing an executable file in the ARM architecture through dynamic instruction conversion; for the current instructions to be converted belonging to the x86 target instruction set, forming a first x86 instruction set from a selected number of instructions to be converted, forming a save instruction set from instructions belonging to the save stage, executing step 2 for registers, executing step 3 for a call instruction group of a nested function call; and forming a restore instruction set from instructions belonging to the restore stage and executing step 4;
[0007] Step 2, forming a register set from registers other than the stack pointer register, wherein registers with a correlation greater than a threshold constitute a register group, and calculating the first memory space to be allocated; constructing a first ARM instruction to allocate the first memory space, and constructing a second ARM instruction group to save the data in the register group to the first memory space; saving the correspondence between the ARM register and the x86 register and the memory address in a mapping relationship table, and executing step 4;
[0008] Step 3, obtain the call instruction group layer by layer, construct a third ARM instruction group that merges and stores the same type of stacked data, and construct a fourth ARM instruction group that stores different types of stacked data; use the third ARM instruction group or the fourth ARM instruction group layer by layer to save the stacked data to the stack; save the register name, register value and stack pointer of the stacked data into the association table, save the information of the global variables and the x86 program counter in the association table, and execute step 4;
[0009] Step 4, obtain the x86 register to be restored, obtain the corresponding ARM register and memory address according to the mapping relationship table, construct a fifth ARM instruction group for loading data from the memory address to the ARM register, construct a sixth ARM instruction group for sequentially restoring the pushed data layer by layer from the stack, construct a seventh ARM instruction group for restoring the register according to the association relationship table, and construct an eighth ARM instruction group for restoring the global variable according to the association relationship table;
[0010] Step 5, convert the PUSH instruction in the first x86 instruction set into a third ARM instruction group or a fourth ARM instruction group, convert the POP instruction into a recovery instruction sequence consisting of a fifth ARM instruction group, a sixth ARM instruction group, a seventh ARM instruction group and an eighth ARM instruction group, convert other x86 instructions into ARM instructions with the same functions, construct an ARM instruction set starting with the first ARM instruction and the second ARM instruction group and including the above-converted ARM instructions, and complete the conversion of the first x86 instruction set.
[0011] Furthermore, the x86 target instruction set in step 1 includes MOV, PUSH, POP and XCHG instructions.
[0012] Further, the manner of forming the first x86 instruction set from the selected number of instructions to be converted in step 1 is: forming the first x86 instruction set from the instructions to be converted within a set instruction window centered on the current instruction to be converted.
[0013] Further, the instruction window is set according to experience.
[0014] Further, the calculation method of the association degree in step 2 is:
[0015] Establish an association matrix, where the rows and columns of the matrix are each register, and the value of the matrix element is the association degree; initially, the value of the matrix element is 0 for all, and when multiple registers exist in the same x86 instruction simultaneously, the element values determined by these registers are incremented by 1; after analyzing all instructions, the value of the element in the association matrix is updated.
[0016] Further, when the instruction is a complex instruction, the value of the element in the association matrix is set to be incremented by n according to the complexity of the operation, where n is a value greater than 1.
[0017] Further, add consistency maintenance before the startup recovery phase, including:
[0018] Record the data read from the memory address of the global variable as the current value, query the association relationship table to obtain the initial value recorded by the global variable, if the current value and the initial value are not equal, then restore it to the initial value, if they are equal, then keep the current value unchanged; obtain the value of the current ARM program counter and record it as the current value of the program counter, calculate the corresponding value of the x86 program counter corresponding to the current value of the program counter, query the association relationship table to obtain the initial value of the x86 program counter, if the two values are different, then restore it to the initial value, otherwise keep the current value of the program counter unchanged.
[0019] Further, after completing register recovery, stack frame recovery, global variable verification, and program counter adjustment, perform an overall verification of the execution context, including: checking whether the values of all registers or global variables are equal to the values at the corresponding positions in the stack frame according to the association relationship table, if the register or global variable is not equal, then re-obtain the correct value from the association relationship table, if the stack frame is inconsistent, then report an exception and exit the program execution; otherwise, complete the verification.
[0020] Further, the association relationship table is maintained by an association relationship table construction module.
[0021] Further, the changes in the values of the global variables and program counter are monitored by a monitoring module, and when a value change is detected, the association relationship table construction module is called to modify the association relationship table according to the change value. Beneficial effects
[0022] The present invention loads and executes an executable file in a dynamic instruction conversion manner. For instructions related to context switching, a set of save instructions and a set of restore instructions that include the complete process of context switching are established. In the set of save instructions, register groups are constructed according to the correlation degree of registers to achieve the combined storage of register data in a continuous memory space in the ARM architecture. The stack data is hierarchically compressed according to the function call hierarchy. In the set of restore instructions, the restoration of register data and stack data is achieved according to the mapping relation table and the association relation table recorded during the save process, improving the flexibility in processing complex nested structures and data types and ensuring the correct execution of the program. Description of the Drawings
[0023] Figure 1 It is a schematic flowchart of an instruction conversion context switching optimization method based on stack frame hierarchical compression provided by the present invention. Detailed Embodiment
[0024] The following examples are enumerated in conjunction with the drawings to describe the present invention in detail.
[0025] In the x86 architecture, context switching involves multiple instructions, mainly related to task switching and register operations, etc. Among them, instructions related to task switching include LTR, CALL far, JMP far, and IRET, and instructions related to register operations include PUSH, POP, MOV, and XCHG.
[0026] LTR (Load Task Register): It is used to load the selector of the task state segment (TSS) into the task register (TR) to achieve task switching. This instruction will trigger the hardware to perform a series of operations, including loading the various register states of the new task, etc., to complete the switching from one task context to another task context.
[0027] CALL far: It is used to implement the call between tasks. By specifying a far address (including a segment selector and an offset), it jumps to the code segment of another task for execution. When the CALL far instruction is executed for task switching, the CPU will automatically save the context information of the current task and load the context of the target task.
[0028] JMP far: It is used to unconditionally jump to a far address and can also be used for task switching. Similar to CALL far, it will change the program execution flow to another task, but it will not automatically return after the switch like CALL far.
[0029] IRET (Interrupted Return): Commonly used to return from an interrupt handler. When an interrupt occurs, the CPU saves the current context information, including register status, program counter, etc. After the interrupt handling is completed, the IRET instruction can be used to restore the previously saved context and resume program execution from the interrupt point.
[0030] PUSH and POP: Used to push data onto the stack or pop data from the stack. During context switching, these instructions can be used to save and restore the values of general-purpose registers. For example, before entering a new task or function, push the register values used by the current task or function onto the stack, and then pop and restore these register values when returning.
[0031] MOV: Used to transfer data between registers or between a register and memory. During context switching, it is often used to load the saved register values from memory into registers or save the register values to specified locations in memory.
[0032] XCHG: Used to exchange the values of two operands. In some cases, it can be used to assist in implementing operations such as register value exchange during context switching.
[0033] These instructions play a crucial role in context switching in the x86 architecture. Through them, task switching can be achieved, as well as saving and restoring task context information, ensuring the correct execution of programs and the multitasking capabilities of the system.
[0034] In modern operating systems, a software-simulated context switching method is more commonly used. This process uses multiple instructions continuously to complete, including saving the current context and loading the new context.
[0035] Among them, saving the current context is to use instructions such as MOV and PUSH to save the values of registers (such as general-purpose registers, segment registers, etc.) used by the current task to the context area allocated for this task in memory.
[0036] An example code for saving the current context is as follows:
[0037] MOV [current_task_context + eax_offset], EAX / / Save the value of the EAX register to memory
[0038] MOV [current_task_context + ebx_offset], EBX / / Save the value of the EBX register to memory
[0039] Loading a new context is to load the values of registers from the context area allocated for a new task in memory using instructions such as MOV and POP.
[0040] An example code for loading a new context is as follows:
[0041] MOV EAX, [new_task_context + eax_offset] / / Load the value of the EAX register from memory
[0042] MOV EBX, [new_task_context + ebx_offset] / / Load the value of the EBX register from memory
[0043] An optimization method for instruction conversion context switching based on stack frame hierarchical compression provided by the present invention has a core idea: loading and executing an executable file in a dynamic instruction conversion manner, establishing a set of save instructions and a set of restore instructions that contain the complete process of context switching for context switching related instructions, constructing register groups according to the correlation degree of registers in the set of save instructions to achieve the combined storage of register data in continuous memory space in the ARM architecture, hierarchically compressing the stack data according to the function call hierarchy, and restoring the register data and stack data according to the mapping relation table and association relation table recorded during the save process in the set of restore instructions.
[0044] An optimization method for instruction conversion context switching based on stack frame hierarchical compression provided by the present invention, the specific process is as Figure 1 shown, and specifically includes the following steps:
[0045] Step 1: Construct an x86 target instruction set containing context switching related instructions in the x86 architecture, and load and execute the executable file through dynamic instruction conversion in the ARM architecture.
[0046] Among them, the context switching related instructions included in the x86 target instruction set mainly include instructions such as MOV, PUSH, POP, and XCHG.
[0047] Step 2: Obtain the currently to-be-converted instruction. If the currently to-be-converted instruction belongs to the x86 target instruction set, form a first x86 instruction set from the to-be-converted instructions within a set instruction window centered on the currently to-be-converted instruction, and execute Step 3; otherwise, convert the currently to-be-converted instruction into an ARM instruction and then execute Step 9. Among them, the first x86 instruction set contains the complete process of x86 context switching, that is, it contains a save stage and a restore stage.
[0048] Among them, the instruction window can be set according to experience or determined according to the parsing result of the instruction stream.
[0049] Step 3: Parse the instructions in the first x86 instruction set to obtain the instruction names and operands. Form a save instruction set from the context switch-related instructions in the first x86 instruction set that belong to the save stage, and execute Step 4; form a restore instruction set from the context switch-related instructions in the first x86 instruction set that belong to the restore stage, and execute Step 7.
[0050] Step 4: For the registers in the save instruction set, execute Step 5; for the call instruction group related to function nested calls in the save instruction set, execute Step 6, where the call instruction group consists of PUSH instructions and CALL instructions.
[0051] Step 5: Form a register set from the operands of the register classes in the save instruction set except the stack pointer register. Determine the correlation degree between the registers in the register set. Form a register group from the registers with a correlation degree greater than the threshold. Calculate the size of the continuous first memory space required to save the data in the register group according to the size of the registers, and record it as the first memory size; select a group of registers in the ARM architecture corresponding to the register group, construct an ARM instruction for allocating the first memory space and record it as the first ARM instruction, and construct an instruction group for saving the data in the register group to the first memory space and record it as the second ARM instruction group; save the correspondence between ARM registers, x86 registers, and memory addresses in the mapping relationship table, and execute Step 7.
[0052] Among them, the implementation method for determining the correlation degree between the registers in the register set can be:
[0053] Step 5.1: Establish a correlation matrix. The rows and columns of the matrix represent each register respectively, and the value of the matrix element is the correlation degree; initially, the matrix element values are all 0. When multiple registers exist in the same instruction at the same time, the element values determined by these registers are all incremented by 1, indicating that the correlation degree between these registers has increased.
[0054] Furthermore, when the instruction to be analyzed is a complex instruction, first increment the two elements determined by the two registers by 1, and then set different correlation degrees according to the complexity of the complex instruction-related operations to reflect the tightness of the registers in the operation. For example, when the complex instruction is a multiplication operation, modify the correlation degree of the registers corresponding to the operands to be incremented by 1.5, and when the complex instruction is an addition operation, modify the correlation degree of the registers corresponding to the operands to be incremented by 1.
[0055] Step 5.2: Traverse the instruction set to complete instruction analysis, and divide the registers in the correlation matrix with correlation degree values greater than the threshold into a group.
[0056] Step 6: Traverse the saved instruction set to obtain the call instruction groups layer by layer, save the base pointer, stack pointer, and return address related to each layer of function calls, and calculate and determine the stack frame boundary and stack frame structure for each layer of function calls; for each layer of call instruction groups, determine the data type of the pushed data according to the PUSH instruction, and construct a third ARM instruction group for merging and storing the pushed data of the same data type into a larger data unit in the ARM architecture; for the pushed data of different data types, construct a fourth ARM instruction group for storing the data in the way that the pushed data with a short word length is stored in the lower bits of the register; according to the function call hierarchy, use the third ARM instruction group or the fourth ARM instruction group layer by layer from the outside to the inside to save the pushed data of each layer to the stack; save the register name, register value, and stack pointer as the pushed data in the PUSH instruction to the association table, save the name, memory address, and current value of the global variable to the association table, and save the value of the x86 program counter to the association table; execute Step 7.
[0057] Step 7: Parse the restore instruction set to obtain the x86 registers to be restored, obtain the corresponding ARM registers and memory addresses to be restored according to the mapping relation table, and construct a fifth ARM instruction group for loading data from the memory address to the ARM register; construct a sixth ARM instruction group for restoring the pushed data of each layer from the stack layer by layer in the order from the inside to the outside according to the function call hierarchy, and construct a seventh ARM instruction group for restoring the corresponding registers according to the records of the pushed data in the association table; construct an eighth ARM instruction group for restoring the global variables according to the records of the global variables in the association table.
[0058] To further improve the reliability of the restoration process, the present invention adds consistency maintenance before preparing to start the restoration phase, including:
[0059] Step 7.1: Denote the data read from the memory address of the global variable as the current value, query the association table to obtain the initial value recorded for the global variable before the system call, compare the current value with the initial value, if they are not equal, restore the initial value of the variable from the association table, if they are equal, keep the current value unchanged.
[0060] The verification of global variables is mainly used to maintain the consistency of global variables before and after system calls. Ensure that the values of global variables are not accidentally modified during system calls. Through this verification and processing mechanism, it is ensured that after the system call returns, the state of the global variables is correct, thus avoiding program running errors caused by incorrect global variable states.
[0061] Step 7.2: Obtain the value of the current ARM program counter, denoted as the current value of the program counter. Calculate the corresponding value of the x86 program counter corresponding to the current value of the program counter. Query the association relationship table to obtain the initial value of the program counter. Compare the initial value with the corresponding value. If they are different, modify the current value of the program counter according to the instruction execution flow and jump relationship recorded in the save stage; otherwise, keep the current value of the program counter unchanged.
[0062] By maintaining the consistency of the program counter, it can be ensured that the program can continue to execute from the correct position after the system call returns. Through the verification and adjustment of the program counter, the program execution error caused by the error of the program counter during the instruction set conversion and system call process is avoided, ensuring the correctness of the program execution flow.
[0063] Step 8: Convert the PUSH instructions in each layer of call instruction groups in the first x86 instruction set into the third ARM instruction group or the fourth ARM instruction group, convert the POP instructions into a restore instruction sequence composed of the fifth ARM instruction group, the sixth ARM instruction group, the seventh ARM instruction group, and the eighth ARM instruction group, and convert other x86 instructions into ARM instructions with the same function. In this way, an ARM instruction set starting with the first ARM instruction and the second ARM instruction group and containing the above-converted ARM instructions is constructed to complete the conversion of the first x86 instruction set.
[0064] Further, after the present invention completes register restoration, stack frame restoration, global variable verification, and program counter adjustment, an overall execution context verification is performed, including: checking whether the values of all registers or global variables are equal to the values at the corresponding positions in the stack frame according to the association relationship table. If the register or global variable is not equal, obtain the correct value from the association relationship table again. If the stack frame is inconsistent, report an exception and exit the program execution; otherwise, complete the verification.
[0065] Maintaining the consistency of the overall context, including various aspects such as registers, stack frames, global variables, and program counters. Through a comprehensive verification and repair mechanism, it is ensured that the execution state of the program can be accurately restored before and after the system call, avoiding program running errors caused by inconsistencies in any link, and ensuring the stability and correctness of the program.
[0066] Step 9: If the conversion execution of the executable file is completed, end this process; otherwise, execute Step 2. Embodiment
[0067] In this embodiment, an instruction conversion context switching optimization method based on stack frame hierarchical compression provided by the present invention is adopted to achieve the reliable execution of x86 architecture executable files on the ARM architecture, including the following steps:
[0068] S1. Dynamically analyze the instruction stream. If an instruction is detected as an x86 system call, context preservation is performed, including dynamic grouping and packing, and hierarchical compression of the stack frame.
[0069] In the x86 architecture, the system call is an important interface for user programs to interact with the operating system kernel. User programs run in user mode with lower privileges and cannot directly access the underlying resources of the system, such as hardware devices, file systems, and process management, because these operations may affect the stability and security of the system. However, the operating system kernel runs in kernel mode with the highest privileges and can comprehensively manage and control system resources.
[0070] S1.1. Real-time analysis of the system call instruction stream: When an x86 system call instruction is detected, the x86 instruction stream is completely decoded. For each instruction, its opcode and operands are parsed. For example, for the instruction MOV EAX, [EBX], not only is it recognized that the operation performed by the instruction is to load the memory content pointed to by EBX into the EAX register, but also the potential use of EAX and EBX in subsequent instructions is analyzed, and the correlation between registers is judged by maintaining an instruction window.
[0071] S1.2. Determine the correlation between registers and group them according to the correlation, including the following steps:
[0072] Set up a correlation matrix. When an instruction such as ADD EAX, ECX is analyzed, the element values in the EAX row and ECX column as well as the ECX row and EAX column in the matrix are incremented by 1, indicating an enhanced correlation between EAX and ECX; for a complex instruction such as MUL EAX, EDX, where EAX is the multiplicand and EDX is the multiplier, the correlation weight between EAX and EDX is set to 1.5.
[0073] If the correlation values between EAX, EBX, and ECX are all greater than 2, they are grouped together.
[0074] S1.3. Pack and save according to the register grouping. The specific steps are as follows:
[0075] S1.3.1. Memory space allocation. According to the determined register grouping, continuous memory space is allocated for each group of registers. Suppose a group of registers {R0, R1, R2} is to be saved to memory. First, calculate the total number of bytes required for this group of registers. Since each register is usually 32 bits (4 bytes), if there are 3 registers, 12 bytes of continuous memory space are required. Through the memory allocation function of the operating system, such as allocate_memory, the starting address MEM_ADDR of this memory space is obtained.
[0076] S1.3.2, Pack and save. Use a series of ARM instruction combinations to achieve packing and saving of grouped registers. For example, for the operation of saving R0, R1, and R2 to MEM_ADDR, it includes:
[0077] STR R0, [MEM_ADDR]
[0078] STR R1, [MEM_ADDR, #4]
[0079] STR R2, [MEM_ADDR, #8]
[0080] Among them, the first instruction saves the value of R0 to the MEM_ADDR address, the second instruction saves the value of R1 to the MEM_ADDR + 4 address, and the third instruction saves the value of R2 to the MEM_ADDR + 8 address, achieving continuous saving of the values of a group of registers to memory. At the same time, record the save address of each group of registers and the mapping relationship of the registers within the group. For example, record that R0 corresponds to EAX, R1 corresponds to EBX, R2 corresponds to ECX, and the memory address MEM_ADDR where they are saved.
[0081] S1.4. Before saving the stack frame, perform hierarchical compression on the stack frame, including the following steps:
[0082] S1.4.1, Stack frame structure parsing: Starting from the x86 stack top, parse the stack frame structure by tracking stack operation instructions. For example, when encountering the PUSH EBP instruction, record the position of the current stack pointer, which is the starting point of the new stack frame, and then continue to decode subsequent instructions, such as MOV EBP, ESP, to further confirm the stack frame boundary.
[0083] S1.4.2, Hierarchical division: For the function nested call stack frame, the CALL instruction is the key to dividing the levels. Each time the CALL instruction is executed, the return address is pushed onto the stack and jumps to the starting address of the called function. By recording the return address of the CALL instruction and the change of the stack pointer, determine the boundaries of each layer of the stack frame. Because each function call will add a new stack frame level to the stack, the stack frame of the outer function contains the relevant information of the inner function call. By tracking the hierarchical relationship of the CALL instructions, the hierarchical structure of the stack frame can be clearly sorted out.
[0084] The assembly code example is as follows:
[0085] / / Outer function
[0086] PUSH EBP
[0087] MOV EBP, ESP
[0088] / / Some operations
[0089] MOV EAX, 5
[0090] CALL MIDDLE_FUNCTION
[0091] / / Middle function
[0092] PUSH EBP
[0093] MOV EBP, ESP
[0094] / / Some operations
[0095] MOV EBX, 10
[0096] CALL INNER_FUNCTION
[0097] / / Inner function
[0098] PUSH EBP
[0099] MOV EBP, ESP
[0100] / / Inner function operations
[0101] MOV ECX, 15
[0102] / / End of inner function
[0103] MOV ESP, EBP
[0104] POP EBP
[0105] RET
[0106] / / End of middle function
[0107] MOV ESP, EBP
[0108] POP EBP
[0109] RET
[0110] / / End of outer function
[0111] MOV ESP, EBP
[0112] POP EBP
[0113] RET
[0114] In the above example, starting from the outer function, each time a new function is called, a new stack frame level is formed. Record the position of each CALL instruction and the change in the stack pointer. For example, when the outer function calls the middle function, record the position and relevant information of the middle function call on the stack; when the middle function calls the inner function, also record the position and relevant information of the inner function call on the stack. In this way, it is determined that the outer function stack frame contains the middle function call information, and the middle function stack frame contains the inner function call information, thus dividing the stack frame into three layers.
[0115] S1.4.3. Hierarchical compression includes the following steps:
[0116] Data type identification: Determine the data type by analyzing the instructions pushed onto the stack. PUSH AL indicates pushing a byte - type data, that is, 8 - bit data; PUSH AX indicates pushing a word - type data, that is, 16 - bit data; PUSH EAX indicates pushing a double - word - type data, that is, 32 - bit data. Since different registers represent different data widths, the instructions that push these registers onto the stack determine the data type of the data in the stack. Therefore, by parsing the instructions, the data type of each data item in the stack frame can be accurately identified, providing a basis for subsequent compression operations.
[0117] An example of assembly code is as follows:
[0118] MOV AL, 0x10
[0119] PUSH AL
[0120] MOV AX, 0x1234
[0121] PUSH AX
[0122] MOV EAX, 0x12345678
[0123] PUSH EAX
[0124] In the above example code, it is determined that the byte - type data is stored at this position in the stack through PUSH AL, the 16 - bit integer data is stored at the subsequent position in the stack through PUSH AX, and the 32 - bit integer data is stored at the position after that in the stack through PUSH EAX.
[0125] S2. Stack frame compression.
[0126] For data of the same data type, utilize the ARM architecture features to merge them into larger data units for storage, reducing the storage space. Assume that ARM supports 64-bit operations, then two 32-bit integer data can be merged into a 64-bit data. This is based on the storage continuity of data in memory and the principle of bit operations, and combines two 32-bit data into a 64-bit data through logical operations. Because in memory, data is stored in binary form, through reasonable shifting and logical operations, multiple smaller data units can be merged into a larger data unit, thus occupying less memory space when storing.
[0127] The following is an example of assembly code:
[0128] / / Assume that ESI and EDI are two 32-bit integer registers, stored at specific offset positions on the stack
[0129] LDR R0, [SP, #ESI_OFFSET]
[0130] LDR R1, [SP, #EDI_OFFSET]
[0131] ORR R2, R0, LSL R1, #32
[0132] STR R2, [SP, #NEW_OFFSET]
[0133] In the above example code, first, use the LDR instruction to read the values of ESI and EDI from the stack into the R0 and R1 registers, then use the ORR instruction to perform a logical OR operation on the value of R0 and the value of R1 shifted left by 32 bits to obtain a 64-bit data stored in the R2 register, and finally use the STR instruction to save the value of R2 to the new position NEW_OFFSET on the stack. In this way, the data that originally required two 32-bit storage spaces is merged into a 64-bit storage space, achieving space compression.
[0134] For data of different data types, store them according to the rule that the data with the shorter word length is stored in the lower bits of the register. For example, when byte-type data and 32-bit integer data are mixed, first store the byte-type data in the lower 8 bits of a temporary register, and then store the 32-bit integer data in the upper 24 bits. Thus, within the limited storage space, different-sized data can be reasonably arranged, while ensuring accurate restoration during recovery. Because the data widths of different data types are different, through this mixed storage method, different types of data can be stored in different bits of the register to improve the utilization rate of the storage space, and the data can be restored through the reverse operation during recovery.
[0135] The following is an example of assembly code:
[0136] / / Assume AL is a byte - type data and EAX is a 32 - bit integer data
[0137] LDR R0, [SP, #AL_OFFSET]
[0138] LDR R1, [SP, #EAX_OFFSET]
[0139] MOV R2, R0
[0140] ORR R2, R2, LSL R1, #8
[0141] STR R2, [SP, #MIXED_OFFSET]
[0142] In the above example code, first, the values of AL and EAX are read from the stack into registers R0 and R1 through the LDR instruction. Then, the value of R0 (byte - type data) is stored in the lower 8 bits of R2, and then the value of R1 is shifted left by 8 bits and logically OR - ed with R2. The upper 24 bits of the 32 - bit integer data are stored in the upper 24 bits of R2. Finally, the value of R2 is saved to the position of MIXED_OFFSET in the stack through the STR instruction. During the saving process, the compression method, data - type distribution of each stack frame, and the storage position in the ARM stack are recorded in detail for accurate restoration during recovery.
[0143] S3. Perform association operations on context elements, including the following steps:
[0144] S3.1. Establish the association between registers and stack frames.
[0145] Instruction monitoring and data extraction: Before the x86 code executes to the system call point, the instruction stream is parsed in real - time. Take the following x86 assembly code as an example:
[0146] MOV EAX, 0x12345678
[0147] PUSH EAX
[0148] MOV EBX, [ESI]
[0149] MOV [ESP + 4], EBX
[0150] When encountering the instruction MOV EAX, 0x12345678, record that the EAX register is about to be assigned the value 0x12345678. Then, when the PUSH EAX instruction is executed, obtain the value of the current stack pointer ESP, assumed to be 0x7FFFFFF0. Use the assembly instruction MOV R1 to store the value of ESP in the temporary register R1, and then pass the values of EAX and R1 to the association table construction module.
[0151] Association table construction and update: The association table construction module constructs the association table in memory using a method similar to a structure array. For example, define a structure in C language:
[0152] typedef struct {char reg_name[4]; uint32_t reg_value; uint32_t stack_addr;} RegStackAssociation;
[0153] In assembly, simulate similar structure array operations through memory operation instructions. For the above PUSH EAX operation, create a new record in the association table and store the register name EAX, the value of EAX 0x12345678, and the stack address 0x7FFFFFF0 in the association table. Among them, the register name EAX can be stored in an encoded way to save memory space, such as encoding EAX as 0x454158.
[0154] For complex stack operations, such as when executing MOV EBX, [ESI], first parse the value of the ESI register. Assume that ESI points to the memory address 0x80000000. Use the assembly instruction LDR R2, [ESI] to load the value at the memory address 0x80000000 into the temporary register R2, and this value is the value that EBX is about to be assigned. Then, when encountering the instruction MOV [ESP +4], EBX, first calculate the value of ESP + 4. Assume that ESP is still 0x7FFFFFF0, then ESP + 4 is 0x7FFFFFF4. Use the assembly instruction ADD R3, R1, #4 to obtain the calculated stack address, where R1 is the previously saved ESP value. Then pass the value of EBX, that is, the value of R2, and the calculated stack address 0x7FFFFFF4 to the association table construction module, and create a new record in the association table to record the value of the EBX register and its storage address in the stack.
[0155] By recording the correspondence between register values and storage locations in the stack, a tight association between registers and stack frames is achieved. In the subsequent recovery phase, when it is necessary to restore the value of the EAX register, the address 0x1000 where the value is stored in the stack can be found by querying the association table, and then the data is read from this address and restored to the EAX register. This association ensures that during context recovery, the data in the registers and stack frames can accurately correspond, and there will be no data misalignment.
[0156] The association process can monitor the instruction stream in real time, adapt dynamically to instruction changes, and dynamically capture changes in register and stack operations. Whether it is a simple push operation after register assignment or a complex indirect stack operation through memory, relevant information can be accurately extracted. For example, for an operation like MOV [ESP + 4], EBX that involves stack offset, the correct stack address can be automatically calculated and associated with the value of the EBX register. Compared with existing methods that can only handle fixed-mode stack operations, it can flexibly handle various complex register and stack interaction situations according to the actual situation of the instructions.
[0157] Precise data tracking is achieved. Through continuous monitoring and recording, the association process can accurately track the storage location of each register value in the stack. In the above example, for the EAX and EBX registers, their values and storage addresses in the stack are accurately recorded respectively, which enables the correct data to be quickly and accurately retrieved from the stack to restore the register values during the context recovery phase, greatly improving the accuracy and efficiency of context recovery.
[0158] S3.2. Establish global variable associations.
[0159] Variable address and value acquisition: In the x86 executable file, the memory address of the global variable is determined through the symbol table or static analysis. Suppose there is a global variable GLOBAL_VAR with a memory address of 0x10000000. Before the system call, the assembly instruction LDR R4, [0x10000000] is used to load the value of GLOBAL_VAR into the temporary register R4, and assume the value is 0x98765432.
[0160] Record and update of the association relationship table: Pass the name GLOBAL_VAR of the global variable, the memory address 0x10000000, and the value 0x98765432 to the association relationship table construction module. The association relationship table construction module creates a new record in the association relationship table. If during the execution of the code, the value of the global variable changes, for example, when the instruction MOV [0x10000000], 0xABCDEF01 is executed, the monitoring module captures this change. First, use the assembly instruction MOV R5, #0xABCDEF01 to load the new value into the temporary register R5, and then update the record of GLOBAL_VAR in the association relationship table, updating its value to 0xABCDEF01.
[0161] In this way, the name, memory address, and value of the global variable are associated and recorded. During the context recovery phase, by querying the association relationship table, the accurate value of the global variable before the system call can be obtained and restored to the corresponding address in memory, ensuring the consistency of the global variable before and after the system call and avoiding the loss or error of the global variable state caused by the system call. At the same time, it realizes the automatic perception of variable changes and can automatically monitor the changes in the value of the global variable. Different from the existing methods that require manual marking or periodic checking of variables, by real-time monitoring the instruction stream, when a write operation to the global variable is found, it immediately captures and updates the value in the association relationship table. For example, when the instruction MOV [0x10000000], 0xABCDEF01 is executed, it can be monitored in real time, and the association relationship table is updated to ensure that the recorded value is the latest variable value.
[0162] S4. After the system call ends, perform context recovery.
[0163] S4.1 Context recovery based on fast retrieval.
[0164] Mapping relationship table lookup: After the ARM architecture call is completed, according to the mapping relationship table recorded in the save phase, find the save address of the ARM register group corresponding to the x86 register group to be restored. For example, given that the x86 register group to be restored is {EAX, EBX, ECX}, through the mapping relationship table, find the memory address MEM_ADDR where the corresponding ARM register group {R0, R1, R2} is saved.
[0165] Recovery instruction execution: It is implemented through the following ARM instructions to restore the values of R0, R1, and R2 from the MEM_ADDR address:
[0166] LDR R0, [MEM_ADDR]
[0167] LDR R1, [MEM_ADDR, #4]
[0168] LDR R2, [MEM_ADDR, #8]
[0169] According to the mapping relationship recorded in the save stage, restore the values of R0, R1, and R2 to the corresponding x86 registers EAX, EBX, and ECX respectively. For example, use the MOV EAX, R0, MOV EBX, R1, MOV ECX, R2 instructions to complete the restoration operation.
[0170] S4.2. Perform incremental stack frame restoration for the hierarchically compressed stack frames.
[0171] Restore layer by layer from the inside out. The stack frames are constructed layer by layer in the function call order. Restoring layer by layer from the inside out ensures the correct stack frame structure. The innermost function stack frame is constructed earliest and destroyed latest. First, restore the innermost function stack frame to ensure that the data related to the innermost function stack frame has been correctly restored when restoring the outer function stack frames, and will not be overwritten or damaged during the restoration process of the outer function stack frames. Because the hierarchical structure of the stack frames determines that the stack frame data of the inner function is the basis for the stack frame data of the outer function. Only by restoring the innermost function stack frame first can the integrity and correctness of the entire stack frame structure be ensured.
[0172] An example of assembly code is as follows:
[0173] / / Restore the merged 64-bit data in the innermost function stack frame to two 32-bit data
[0174] LDR R2, [SP, #COMPRESSED_OFFSET]
[0175] MOV R0, R2
[0176] MOV R1, R2, LSR #32
[0177] / / Restore R0 and R1 to the corresponding x86 registers ESI and EDI
[0178] MOV ESI, R0
[0179] MOV EDI, R1
[0180] In the above code, first, read the merged 64-bit data from the stack to the R2 register through the LDR instruction, then decompress it into two 32-bit data R0 and R1 through the MOV and LSR instructions, and finally restore the values of R0 and R1 to the corresponding x86 registers ESI and EDI respectively. In this way, first restore the data in the innermost function stack frame, laying the foundation for the subsequent restoration of the middle and outer function stack frames.
[0181] S4.3. Perform consistency maintenance during context restoration.
[0182] S4.3.1. Perform verification before the system call returns. The specific steps are as follows:
[0183] After the ARM system call is completed and before preparing to restore the x86 context, first verify the global variables. For example, for the previously recorded GLOBAL_VAR, read the current value from memory address 0x2000, assumed to be CURRENT_VALUE.
[0184] Query the association relationship table to obtain the value of GLOBAL_VAR recorded before the system call, assumed to be ORIGINAL_VALUE. Use an assembly instruction for comparison, such as CMP CURRENT_VALUE, ORIGINAL_VALUE.
[0185] If the comparison result is not equal, restore the value of the variable from the backup data, or through a specific recovery mechanism, such as re-executing the relevant initialization code to restore it to the correct value.
[0186] This step mainly maintains the consistency of global variables before and after the system call, ensuring that the values of global variables are not accidentally modified during the system call. Through this verification and processing mechanism, it is ensured that after the system call returns, the state of the global variables is correct, thus avoiding program running errors caused by incorrect global variable states.
[0187] S4.3.2. Program counter verification and adjustment.
[0188] During the save phase, the value of the program counter (assumed to be EIP) before the x86 system call was recorded, assumed to be EIP_VALUE. After the ARM system call is completed, obtain the value of the current ARM program counter (assumed to be PC), assumed to be PC_VALUE.
[0189] Since the lengths of ARM instructions and x86 instructions are different, conversion calculations are required. According to the mapping relationship from x86 instructions to ARM instructions, calculate the value of the x86 program counter that PC should correspond to. For example, if an x86 instruction becomes multiple instructions after being converted to ARM instructions, the correct x86 program counter position needs to be deduced based on the instruction mapping relationship table and the number of ARM instructions executed.
[0190] Use assembly instructions for comparison, such as CMP PC_VALUE, EXPECTED_EIP_VALUE, where EXPECTED_EIP_VALUE is the value of the x86 program counter that the calculated PC should correspond to. If they are inconsistent, adjust the value of the PC according to the instruction execution flow and jump relationship recorded during the save phase. For example, if a conditional jump instruction JZ is recorded before the system call during the save phase, determine whether the PC should be adjusted to the jump target address based on the jump condition and the current register status. The value of the PC register can be modified to point to the correct location to ensure that the program can continue to execute correctly after returning from the system call.
[0191] This step maintains the consistency of the program counter, ensuring that the program can continue to execute from the correct location after returning from the system call. By verifying and adjusting the program counter, it avoids program execution errors caused by incorrect program counters during the instruction set conversion and system call process, ensuring the correctness of the program execution flow.
[0192] S4.3.3. Overall context verification.
[0193] Check whether the value of a certain register matches the value stored at the corresponding position in the stack through the association table. Assume that the value of EAX is supposed to be obtained from the stack address 0x1000 in the association table. After restoration, check whether the value of EAX is indeed the same as the value read from 0x1000. Check whether the stack frame structure is complete and conforms to the expectations of the x86 program. For example, check whether the base pointer of the stack frame correctly points to the start position of the stack frame, and whether the local variables in the stack frame are stored in the expected order and offsets.
[0194] If any inconsistent situation is found, gradually check the save and restore processes through a pre-set backtracking mechanism. If it is an inconsistent register or global variable, obtain the correct value from the backup data again. If it is an inconsistent stack frame, report an exception and exit.
[0195] This step maintains the consistency of the entire context, including registers, stack frames, global variables, program counters, etc. Through a comprehensive verification and repair mechanism, it ensures that the execution state of the program can be accurately restored before and after the system call, avoiding program running errors caused by inconsistencies in any link, and ensuring the stability and correctness of the program.
[0196] In summary, the above are only the preferred embodiments of the present invention and are not used to limit the protection scope of the present invention. Any modifications, equivalent replacements, improvements, etc. made within the spirit and principle of the present invention shall be included in the protection scope of the present invention.
Claims
1. A context switch optimization method for instruction conversion based on stack frame hierarchical compression, characterized in that: The specific steps include: Step 1, constructing an x86 target instruction set related to context switching, and loading and executing an executable file in the ARM architecture through dynamic instruction conversion; for the current instructions to be converted belonging to the x86 target instruction set, forming a first x86 instruction set from a selected number of instructions to be converted, forming a save instruction set from instructions belonging to the save stage, executing step 2 for registers, executing step 3 for a call instruction group of a nested function call; and forming a restore instruction set from instructions belonging to the restore stage and executing step 4; Step 2, forming a register set from registers other than the stack pointer register, wherein registers with a correlation greater than a threshold constitute a register group, and calculating the first memory space to be allocated; constructing a first ARM instruction to allocate the first memory space, and constructing a second ARM instruction group to save the data in the register group to the first memory space; saving the correspondence between the ARM register and the x86 register and the memory address in a mapping relationship table, and executing step 4; Step 3, obtain the call instruction group layer by layer, construct a third ARM instruction group that merges and stores the same type of stacked data, and construct a fourth ARM instruction group that stores different types of stacked data; use the third ARM instruction group or the fourth ARM instruction group layer by layer to save the stacked data to the stack; save the register name, register value and stack pointer of the stacked data into the association table, save the information of the global variables and the x86 program counter in the association table, and execute step 4; Step 4, obtain the x86 register to be restored, obtain the corresponding ARM register and memory address according to the mapping relationship table, construct a fifth ARM instruction group for loading data from the memory address to the ARM register, construct a sixth ARM instruction group for sequentially restoring the pushed data layer by layer from the stack, construct a seventh ARM instruction group for restoring the register according to the association relationship table, and construct an eighth ARM instruction group for restoring the global variable according to the association relationship table; Step 5, convert the PUSH instruction in the first x86 instruction set into the third ARM instruction group or the fourth ARM instruction group, convert the POP instruction into a recovery instruction sequence consisting of the fifth ARM instruction group, the sixth ARM instruction group, the seventh ARM instruction group and the eighth ARM instruction group, convert other x86 instructions into ARM instructions with the same functions, construct an ARM instruction set starting with the first ARM instruction and the second ARM instruction group and including the above converted ARM instructions, and complete the conversion of the first x86 instruction set; The calculation method of the correlation degree in step 2 is: Establish an association matrix, the rows and columns of which are registers respectively, and the values of the matrix elements are the association degrees; initially, the values of the matrix elements are all 0, and when multiple registers exist in the same x86 instruction at the same time, the element values determined by these registers are all incremented by 1; complete the analysis of all instructions, and complete the update of the values of the elements in the association matrix; When the instruction is a complex instruction, the value of the element in the association matrix is set to be incremented by n according to the complexity of the operation, where n is a value greater than 1.
2. The instruction conversion context switching optimization method according to claim 1, characterized in that: The x86 target instruction set in step 1 includes MOV, PUSH, POP and XCHG instructions.
3. The instruction conversion context switching optimization method according to claim 1, characterized in that: The method of forming the first x86 instruction set from the selected number of instructions to be converted in step 1 is: forming the first x86 instruction set from the instructions to be converted within a set instruction window centered on the current instruction to be converted.
4. The instruction conversion context switching optimization method according to claim 3, characterized in that: The command window is set based on experience.
5. The instruction conversion context switch optimization method according to claim 1, characterized in that: Add consistency maintenance before starting the recovery phase, including: The data read from the memory address of the global variable is recorded as the current value, and the association table is queried to obtain the initial value of the global variable record. If the current value and the initial value are not equal, they are restored to the initial value, and if they are equal, the current value is kept unchanged; the value of the current ARM program counter is obtained and recorded as the current value of the program counter, and the corresponding value of the x86 program counter corresponding to the current value of the program counter is calculated, and the association table is queried to obtain the initial value of the x86 program counter. If the two values are different, they are restored to the initial value, otherwise the current value of the program counter is kept unchanged.
6. The instruction conversion context switch optimization method according to claim 1, characterized in that: After completing register recovery, stack frame recovery, global variable verification and program counter adjustment, the overall context verification is performed, including: checking whether the values of all registers or global variables are equal to the values of the corresponding positions in the stack frame according to the association table; if the registers or global variables are not equal, the correct values are retrieved from the association table; if the stack frames are inconsistent, an exception is reported and the program execution is exited; otherwise, the verification is completed.
7. The instruction conversion context switch optimization method according to claim 1, characterized in that: The association relationship table is maintained by an association relationship table construction module.
8. The instruction conversion context switch optimization method according to claim 7, characterized in that: The changes of the values of the global variables and the program counter are monitored by the monitoring module. When a change in the value is found, the association table construction module is called to modify the association table according to the changed value.
Citation Information
Patent Citations
Implementation of multi-tasking on a digital signal processor
CN101176061A
Coroutine implementation method and system
CN113608843A