Instruction conversion context switching optimization method 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
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2025-03-17
- Publication Date
- 2025-04-15
- 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 build a collection of save instructions and a collection of recovery instructions that includes the complete process of context switching. During the storage stage, a register group is constructed according to the correlation degree of the registers, the register data is merged and stored using continuous memory space, and the stacked data is compressed layer by layer. In the recovery stage, the recovery of register data and stack-pressed data is achieved based on the mapping relationship table and association relationship table recorded during the storage process.
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 CN119829133A_ABST
Abstract
Description
Technical Field
[0001] The invention belongs to the technical field of computer architecture and instruction set conversion, and in particular relates to an instruction conversion context switching optimization method based on stack frame hierarchical compression. Background Art
[0002] In order to realize the concurrent execution of multiple tasks in the x86 system, it is necessary to perform context switching between different tasks. Context switching refers to saving the execution state of the current task, that is, 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 registers, which need to save the values of all general registers, including EAX, EBX, ECX, EDX, ESI, EDI, etc.; control registers, such as the base pointer register EBP, the stack pointer register ESP, etc., 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 will save all the register states of the current task to the task control block (TCB) of the task, then load the corresponding register states from the TCB of another task, and finally jump to the execution location of the task to continue execution.
[0003] Therefore, context preservation and restoration during program execution is crucial when performing instruction conversion between different computer architectures. Existing methods usually simply integrate the basic features of x86 and ARM architectures, and have 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 converting stack frames, the processing of complex nested structures and data types is not flexible enough, resulting in inaccurate context recovery, which in turn affects the correct execution of the program. Summary of the invention
[0004] In view of this, the present invention provides an instruction conversion context switch optimization method based on stack frame hierarchical compression, which realizes the conversion of context save and restore related instructions and improves the execution efficiency of context save and restore.
[0005] The present invention provides an instruction conversion context switch optimization method based on stack frame hierarchical compression, which specifically includes the following steps: 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 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.
[0006] Furthermore, the x86 target instruction set in step 1 includes MOV, PUSH, POP and XCHG instructions.
[0007] Furthermore, 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.
[0008] Furthermore, the instruction window is set based on experience.
[0009] Furthermore, the calculation method of the correlation degree in step 2 is: Establish an association matrix, where the rows and columns of the matrix are registers respectively, and the values of the matrix elements are the association degrees. Initially, the values of the matrix elements are all 0. When multiple registers exist in the same x86 instruction at the same time, the element values determined by these registers will be incremented by 1. After completing the analysis of all instructions, the values of the elements in the association matrix are updated.
[0010] Furthermore, 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.
[0011] Furthermore, consistency maintenance is added 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.
[0012] Furthermore, 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 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.
[0013] Furthermore, the association relationship table is maintained by an association relationship table construction module.
[0014] Furthermore, the changes in the values of the global variables and program counters are monitored by the monitoring module, and 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. Beneficial Effects
[0015] The present invention loads and executes executable files in a dynamic instruction conversion manner, establishes a save instruction set and a restore instruction set containing the complete context switch process for context switch related instructions, constructs a register group in the save instruction set according to the association degree of the registers to realize the combined storage of register data in a continuous memory space in the ARM architecture, compresses the pushed data in layers according to the function call hierarchy, and realizes the recovery of register data and pushed data in the restore instruction set according to the mapping relationship table and the association relationship table recorded in the saving process, thereby improving the flexibility of processing complex nested structures and data types and ensuring the correct execution of the program. BRIEF DESCRIPTION OF THE DRAWINGS
[0016] Figure 1 A schematic flow chart of an instruction conversion context switch optimization method based on stack frame hierarchical compression provided by the present invention. DETAILED DESCRIPTION
[0017] The present invention is described in detail below with reference to the accompanying drawings and with reference to the embodiments.
[0018] In the x86 architecture, context switching involves multiple instructions, which are mainly related to task switching and register operations. Task switching related instructions include LTR, CALL far, JMP far and IRET, and register operation related instructions include PUSH, POP, MOV and XCHG.
[0019] LTR (Load Task Register): Used to load the selector of the task state segment (TSS) into the task register (TR) to achieve task switching. This instruction triggers the hardware to perform a series of operations, including loading various register states of the new task, to complete the switch from one task context to another.
[0020] CALL far: It is used to implement inter-task calls. By specifying a far address (including segment selector and offset), it jumps to the code segment of another task for execution. When executing the CALL far instruction to switch tasks, the CPU automatically saves the context information of the current task and loads the context of the target task.
[0021] JMP far: Used to jump to a far address unconditionally. It can also be used for task switching. Similar to CALL far, it changes the flow of program execution to another task, but it does not automatically return after switching like CALL far.
[0022] IRET (Interrupted Return): Usually 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 is processed, the IRET instruction can be used to restore the previously saved context and continue the program from the interrupt point.
[0023] PUSH and POP: used to push data into or pop data from the stack. These instructions can be used to save and restore the values of general registers when switching contexts. For example, before entering a new task or function, push the register values used by the current task or function into the stack, and pop them from the stack to restore the values of these registers when returning.
[0024] MOV: Used to transfer data between registers or between registers and memory. During context switching, it is often used to load saved register values from memory into registers, or to save register values to a specified location in memory.
[0025] 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 in context switching.
[0026] These instructions play a key role in the context switching of the x86 architecture. They enable switching between tasks and saving and restoring task context information, ensuring the correct execution of programs and the system's multitasking capabilities.
[0027] In modern operating systems, software-simulated context switching is more often used. This process uses multiple instructions in succession to complete, including saving the current context and loading the new context.
[0028] Among them, saving the current context is to use instructions such as MOV and PUSH to save the values of registers used by the current task (such as general registers, segment registers, etc.) to the context area allocated for the task in the memory.
[0029] The sample code for saving the current context is as follows: MOV [current_task_context + eax_offset], EAX / / Save the value of the EAX register to memory MOV [current_task_context + ebx_offset], EBX / / Save the value of the EBX register to memory Loading a new context is to use instructions such as MOV and POP to load the values of registers from the context area allocated for the new task in memory.
[0030] The sample code for loading a new context is as follows: MOV EAX, [new_task_context + eax_offset] / / Load the value of the EAX register from memory MOV EBX, [new_task_context + ebx_offset] / / Load the value of the EBX register from memory The invention provides an instruction conversion context switching optimization method based on stack frame hierarchical compression, the core idea of which is: loading and executing an executable file in a dynamic instruction conversion manner, establishing a save instruction set and a restore instruction set containing the complete context switch process for context switch related instructions, constructing a register group in the save instruction set according to the association degree of the registers to realize the combined storage of register data in a continuous memory space in the ARM architecture, hierarchically compressing the pushed data according to the function call hierarchy, and realizing the recovery of the register data and the pushed data in the restore instruction set according to the mapping relationship table and the association relationship table recorded in the saving process.
[0031] The present invention provides an instruction conversion context switching optimization method based on stack frame layered compression, the specific process is as follows Figure 1 As shown, the specific steps include: Step 1: Build an x86 target instruction set containing context switch related instructions in the x86 architecture, and load and execute the executable file through dynamic instruction conversion in the ARM architecture.
[0032] Among them, the context switching related instructions contained in the x86 target instruction set mainly include MOV, PUSH, POP, XCHG and other instructions.
[0033] Step 2, obtain the current instruction to be converted, if the current instruction to be converted belongs to the x86 target instruction set, form a first x86 instruction set from the instructions to be converted in the set instruction window centered on the current instruction to be converted, and execute step 3; otherwise, convert the current instruction to be converted into an ARM instruction and then execute step 9. The first x86 instruction set includes the complete process of x86 context switching, that is, includes the save phase and the restore phase.
[0034] The instruction window may be set based on experience or determined based on the analysis result of the instruction stream.
[0035] Step 3, parse the instructions in the first x86 instruction set to obtain instruction names and operands, form a save instruction set from the context switch related instructions belonging to the save phase in the first x86 instruction set, and execute step 4; form a restore instruction set from the context switch related instructions belonging to the restore phase in the first x86 instruction set, and execute step 7.
[0036] Step 4, execute step 5 for the registers in the saved instruction set; execute step 6 for the call instruction group related to the nested call of the function in the saved instruction set, wherein the call instruction group consists of PUSH instructions and CALL instructions.
[0037] Step 5, form a register set by saving operands of the register class except the stack pointer register in the instruction set, determine the correlation between the registers in the register set, form a register group by registers with a correlation greater than a threshold, calculate the size of the continuous first memory space required to allocate for saving the data in the register group according to the size of the register, and record it as the first memory size; select a group of registers corresponding to the register group in the ARM architecture, construct an ARM instruction for allocating the first memory space as the first ARM instruction, and construct an instruction group for saving the data in the register group to the first memory space as the second ARM instruction group; save the correspondence between the ARM register and the x86 register and the memory address in the mapping relationship table, and execute step 7.
[0038] The method for determining the association degree between the registers in the register set may be: Step 5.1, establish an association matrix. The rows and columns of the matrix represent each register, and the value of the matrix element is the association 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 will be increased by 1, indicating that the association degree between these registers has increased.
[0039] Furthermore, when the instruction to be analyzed is a complex instruction, first, two elements determined by two registers are added by 1, and then different associations are set according to the complexity of the operation related to the complex instruction to reflect the closeness of the registers in the operation. For example, when the complex instruction is a multiplication operation, the association of the register corresponding to the operand is modified to add 1.5, and when the complex instruction is an addition operation, the association of the register corresponding to the operand is modified to add 1.
[0040] Step 5.2: traverse the instruction set to complete instruction analysis, and divide the registers in the association matrix whose association values are greater than a threshold into one group.
[0041] Step 6, traverse the saved instruction set to obtain the call instruction group layer by layer, save the base pointer, stack pointer and return address related to each layer of function call, calculate and determine the stack frame boundary and stack frame structure of each layer of function call; for each layer of call instruction group, determine the data type of its push data according to the PUSH instruction, and construct a third ARM instruction group for merging and storing the push data with the same data type into a larger data unit of the ARM architecture; for push data with different data types, construct a fourth ARM instruction group that stores data in a manner that the push data of short word length is saved in the low position of the register; according to the function call hierarchy structure, use the third ARM instruction group or the fourth ARM instruction group layer by layer in an order from outside to inside to save the push data of each layer into the stack; save the register name, register value and stack pointer in the PUSH instruction as the push data into the association table, save the name, memory address and current value of the global variable into the association table, and save the value of the x86 program counter in the association table; execute step 7.
[0042] Step 7, parse the recovery instruction set to obtain the x86 register to be restored, obtain the corresponding ARM register to be restored and the memory address according to the mapping relationship table, and construct the fifth ARM instruction group for loading data from the memory address to the ARM register; construct the sixth ARM instruction group for restoring the pushed data of each layer from the stack layer by layer in an order from the inside to the outside according to the function call hierarchy structure, and construct the seventh ARM instruction group for restoring the corresponding register according to the record of the pushed data in the association relationship table; construct the eighth ARM instruction group for restoring the global variables according to the record of the global variables in the association relationship table.
[0043] In order to further improve the reliability of the recovery process, the present invention adds consistency maintenance before preparing to start the recovery phase, including: Step 7.1, record the data read from the memory address of the global variable as the current value, query the association table to obtain the initial value of the global variable recorded before the system call, compare the current value and 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.
[0044] The global variable check is mainly used to maintain the consistency of global variables before and after the system call. It ensures that the value of the global variable is not accidentally modified during the system call. Through this checksum processing mechanism, it is ensured that the state of the global variable is correct after the system call returns, thus avoiding program running errors caused by global variable state errors.
[0045] Step 7.2, get the current value of the 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 table to get 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 process and jump relationship recorded in the save stage, otherwise keep the current value of the program counter unchanged.
[0046] By maintaining the consistency of the program counter, it is ensured that the program can continue to execute from the correct position after the system call returns. By checking and adjusting the program counter, program execution errors caused by program counter errors during instruction set conversion and system calls are avoided, ensuring the correctness of the program execution process.
[0047] Step 8. Convert the PUSH instruction in each layer of the calling instruction group 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, and convert other x86 instructions into ARM instructions with the same functions, thereby constructing an ARM instruction set starting with the first ARM instruction and the second ARM instruction group and including the above-mentioned converted ARM instructions, and completing the conversion of the first x86 instruction set.
[0048] Furthermore, after completing register recovery, stack frame recovery, global variable verification and program counter adjustment, the present invention performs context overall verification, including: checking whether the values of all registers or global variables are equal to the values of corresponding positions in the stack frame according to the association table; if the registers or global variables are not equal, re-obtaining the correct values from the association table; if the stack frames are inconsistent, reporting an exception and exiting program execution; otherwise completing the verification.
[0049] Maintain the overall consistency of the context, including registers, stack frames, global variables, program counters, etc. Through a comprehensive verification and repair mechanism, ensure that the execution state of the program can be accurately restored before and after the system call, avoid program operation errors caused by inconsistencies in any link, and ensure the stability and correctness of the program.
[0050] Step 9: If the executable file is executed and the conversion is completed, then the process ends; otherwise, proceed to step 2. Example
[0051] In this embodiment, an instruction conversion context switch optimization method based on stack frame hierarchical compression provided by the present invention is adopted to realize the reliable execution of x86 architecture executable files on ARM architecture, including the following steps: S1. Dynamically analyze the instruction stream. If the instruction is detected to be an x86 system call, the context is saved, including dynamic grouping and stack frame layering compression.
[0052] In the x86 architecture, system calls are an important interface for user programs to interact with the operating system kernel. User programs run in user mode, have lower permissions, 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, has the highest permissions, and can comprehensively manage and control system resources.
[0053] S1.1, Real-time system call instruction stream analysis: When an x86 system call instruction is detected, the x86 instruction stream is fully decoded. For each instruction, its opcode and operand are parsed. For example, for the instruction MOV EAX, [EBX], not only is the instruction operation identified, that is, loading 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 association between registers is determined by maintaining the instruction window.
[0054] S1.2, determine the association between registers and group them according to the association, including the following steps: Set up an association matrix. When analyzing instructions such as ADD EAX, ECX, add 1 to the element values of the EAX row and ECX column and the ECX row and EAX column in the matrix, indicating that the association between EAX and ECX is enhanced. For complex instructions such as MUL EAX, EDX, EAX is the multiplicand and EDX is the multiplier, then the association weight between EAX and EDX is set to 1.5.
[0055] If the correlation values between EAX, EBX and ECX are all greater than 2, they are grouped together.
[0056] S1.3, package and save according to register grouping. The specific steps are as follows: S1.3.1. Memory space allocation. According to the determined register grouping, allocate continuous memory space for each group of registers. Assuming that a group of registers {R0, R1, R2} is 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. Obtain the starting address MEM_ADDR of this memory space through the memory allocation function of the operating system, such as allocate_memory.
[0057] S1.3.2, Pack and save. The grouped registers are packed and saved through a series of ARM instruction combinations. For example, the operation of saving R0, R1, and R2 to MEM_ADDR includes: STR R0, [MEM_ADDR] STR R1, [MEM_ADDR, #4] STR R2, [MEM_ADDR, #8] 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, thus saving the values of a group of registers to the memory continuously. At the same time, the mapping relationship between the save address of each group of registers and the registers in the group is recorded, for example, R0 corresponds to EAX, R1 corresponds to EBX, R2 corresponds to ECX, and the memory address MEM_ADDR where they are saved.
[0058] S1.4, compressing the stack frame in layers before saving the stack frame, including the following steps: S1.4.1、Stack frame structure analysis: Starting from the top of the x86 stack, the stack frame structure is analyzed by tracking the stack operation instructions. For example, when encountering the PUSH EBP instruction, the current stack pointer position is recorded, that is, the starting point of the new stack frame, and then the subsequent instructions such as MOV EBP, ESP are decoded to further confirm the stack frame boundary.
[0059] S1.4.2, Hierarchical division: For nested function call stack frames, the CALL instruction is the key to hierarchical division. Each time a CALL instruction is executed, the return address is pushed into the stack and jumps to the starting address of the called function. By recording the return address and stack pointer changes of the CALL instruction, the boundaries of each layer of stack frames are determined. Because each function call will add a new stack frame level to the stack, the stack frame of the outer function contains relevant information about the inner function call. By tracing the hierarchical relationship of the CALL instruction, the hierarchical structure of the stack frame can be clearly sorted out.
[0060] The following is an example of assembly code: / / Outer function PUSH EBP MOV EBP, ESP / / Some operations MOV EAX, 5 CALL MIDDLE_FUNCTION / / Middle level function PUSH EBP MOV EBP, ESP / / Some operations MOV EBX, 10 CALL INNER_FUNCTION / / Inner function PUSH EBP MOV EBP, ESP / / Inner function operation MOV ECX, 15 / / End of inner function MOV ESP, EBP POP EBP RET / / End of middle-level function MOV ESP, EBP POP EBP RET / / End of outer function MOV ESP, EBP POP EBP RET 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 location of each CALL instruction and the stack pointer change. For example, when the outer function calls the middle function, record the location and related information of the middle function call in the stack; when the middle function calls the inner function, also record the location and related information of the inner function call in 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, thereby dividing the stack frame into three layers.
[0061] S1.4.3. Layered compression includes the following steps: Data type identification: Determine the data type by analyzing the instructions pushed into the stack. PUSH AL means pushing byte data, that is, 8-bit data; PUSH AX means pushing word data, that is, 16-bit data; PUSH EAX means pushing double word data, that is, 32-bit data. Because different registers represent different data widths, the instructions that push these registers into the stack also 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.
[0062] The following is an example of assembly code: MOV AL, 0x10 PUSH AL MOV AX, 0x1234 PUSH AX MOV EAX, 0x12345678 PUSH EAX In the above sample code, PUSH AL is used to determine that byte data is stored at that position in the stack, PUSH AX is used to determine that 16-bit integer data is stored at the subsequent position in the stack, and PUSH EAX is used to determine that 32-bit integer data is stored at the subsequent position in the stack.
[0063] S2. Stack frame compression.
[0064] For data of the same data type, the ARM architecture features are used to merge them into larger data units for storage, thus reducing storage space. Assuming that ARM supports 64-bit operations, two 32-bit integer data can be merged into 64-bit data. This is based on the storage continuity of data in memory and the principle of bit operation, and two 32-bit data are combined into one 64-bit data through logical operations. Because in memory, data is stored in binary form, multiple smaller data units can be merged into a larger data unit through reasonable shifting and logical operations, thereby occupying less memory space during storage.
[0065] The following is an example of assembly code: / / Assume that ESI and EDI are two 32-bit integer registers stored at a specific offset in the stack LDR R0, [SP, #ESI_OFFSET] LDR R1, [SP, #EDI_OFFSET] ORR R2, R0, LSL R1, #32 STR R2, [SP, #NEW_OFFSET] In the above sample code, the LDR instruction is used to read the values of ESI and EDI from the stack to the R0 and R1 registers, and then the ORR instruction is used to perform a logical OR operation on the value of R0 and the value of R1 shifted left by 32 bits, obtaining a 64-bit data stored in the R2 register, and finally the STR instruction is used to save the value of R2 to the new position NEW_OFFSET in 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.
[0066] For data of different data types, the data with short word length is stored in the lower bits of the register. For example, when byte data and 32-bit integer data are mixed, the byte data is first stored in the lower 8 bits of the temporary register, and then the 32-bit integer data is stored in the upper 24 bits. This makes it possible to reasonably arrange data of different sizes within a limited storage space, 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 of storage space, and the data can be restored through the opposite operation during recovery.
[0067] The following is an example of assembly code: / / Assume AL is byte data and EAX is 32-bit integer data LDR R0, [SP, #AL_OFFSET] LDR R1, [SP, #EAX_OFFSET] MOV R2, R0 ORR R2, R2, LSL R1, #8 STR R2, [SP, #MIXED_OFFSET] In the above sample code, the LDR instruction is used to read the values of AL and EAX from the stack to the R0 and R1 registers, and then the value of R0 (byte data) is stored in the lower 8 bits of R2. R1 is shifted left by 8 bits and then logically ORed with R2, and the upper 24 bits of the 32-bit integer data are stored in the upper 24 bits of R2. Finally, the STR instruction is used to save the value of R2 to the MIXED_OFFSET position in the stack. During the saving process, the compression method, data type distribution, and storage location of each layer of the stack frame are recorded in detail to accurately restore them when they are restored.
[0068] S3. Performing an association operation on the context element, including the following steps: S3.1. Establish association between registers and stack frames.
[0069] Instruction monitoring and data extraction: Before the x86 code is executed to the system call point, the instruction stream is parsed in real time. Take the following x86 assembly code as an example: MOV EAX, 0x12345678 PUSH EAX MOV EBX, [ESI] MOV [ESP + 4], EBX When the instruction MOV EAX, 0x12345678 is encountered, record that the EAX register is about to be assigned 0x12345678. Then, when the PUSH EAX instruction is executed, obtain the value of the current stack pointer ESP, assuming it is 0x7FFFFFF0. Use the assembly instruction MOV R1 to store the value of ESP in the temporary register R1, and then pass the value of EAX and the value of R1 to the association table construction module.
[0070] Association table construction and update: The association table construction module uses a structure array-like method to build an association table in memory. For example, define a structure in C language: typedef struct {char reg_name[4]; uint32_t reg_value; uint32_t stack_addr;} RegStackAssociation; In assembly, similar structure array operations are simulated through memory operation instructions. For the above PUSH EAX operation, a new record is created in the association table, and the register name EAX, the value of EAX 0x12345678, and the stack address 0x7FFFFFF0 are stored in the association table. Among them, the register name EAX can be stored in an encoded manner to save memory space, such as encoding EAX as 0x454158.
[0071] For complex stack operations, such as when executing MOV EBX, [ESI], the value of the ESI register is parsed first. Assuming that ESI points to the memory address 0x80000000, the value at the memory address 0x80000000 is loaded into the temporary register R2 through the assembly instruction LDR R2, [ESI]. This value is the value that EBX will be assigned. Next, when encountering the MOV [ESP +4], EBX instruction, the value of ESP + 4 is calculated first. Assuming that ESP is still 0x7FFFFFF0, ESP + 4 is 0x7FFFFFF4. Use the assembly instruction ADD R3, R1, #4 to get 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.
[0072] By recording the correspondence between register values and storage locations in the stack, a close association between registers and stack frames is achieved. In the subsequent recovery phase, when the value of the EAX register needs to be restored, 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 the address and restored to the EAX register. This association ensures that when the context is restored, the data in the register and stack frame can accurately correspond to each other, and there will be no data misalignment.
[0073] The association process can monitor the instruction flow in real time, dynamically adapt to instruction changes, and dynamically capture changes in register and stack operations. Whether it is a simple register assignment followed by stack push, or a complex stack operation through memory indirection, relevant information can be accurately extracted. For example, for operations involving stack offsets such as MOV [ESP + 4], EBX, the correct stack address can be automatically calculated and associated with the EBX register value. Compared with existing methods that can only handle fixed-mode stack operations, it can flexibly respond to various complex register and stack interactions based on the actual situation of the instructions.
[0074] Accurate 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, which enables the correct data to be quickly and accurately obtained from the stack to restore the register value during the context recovery phase, greatly improving the accuracy and efficiency of context recovery.
[0075] S3.2. Establish global variable association.
[0076] Variable address and value acquisition: In an x86 executable file, the memory address of a global variable is determined through a symbol table or static analysis. Assume that there is a global variable GLOBAL_VAR, and its memory address is 0x10000000. Before the system call, use the assembly instruction LDR R4, [0x10000000] to load the value of GLOBAL_VAR into a temporary register R4. Assume that the value is 0x98765432.
[0077] Record and update of the association table: pass the name of the global variable GLOBAL_VAR, the memory address 0x10000000, and the value 0x98765432 to the association table construction module. The association table construction module creates a new record in the association table. If the value of the global variable changes during code execution, such as executing the MOV [0x10000000], 0xABCDEF01 instruction, the monitoring module captures this change and first uses the assembly instruction MOV R5, #0xABCDEF01 to load the new value into the temporary register R5, and then updates the record of GLOBAL_VAR in the association table and updates its value to 0xABCDEF01.
[0078] In this way, the name, memory address and value of the global variable are associated and recorded. In the context recovery phase, the accurate value of the global variable before the system call can be obtained by querying the association table, and it can be restored to the corresponding address in the 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, automatic perception of variable changes is realized, and changes in global variable values can be automatically monitored. Different from the existing methods that require manual marking or periodic checking of variables, by real-time monitoring of the instruction stream, write operations on global variables are discovered, and the values in the association table are immediately captured and updated. For example, when the MOV [0x10000000], 0xABCDEF01 instruction is executed, it can be monitored in real time, and the association table can be updated to ensure that the latest variable value is recorded.
[0079] S4. After the system call ends, the execution context is restored.
[0080] S4.1. Context recovery based on fast retrieval.
[0081] Mapping table search: After the ARM architecture call is completed, the ARM register group save address corresponding to the x86 register group to be restored is found according to the mapping table recorded in the save phase. For example, if the x86 register group to be restored is known to be {EAX, EBX, ECX}, the corresponding ARM register group {R0, R1, R2} is found through the mapping table. The memory address MEM_ADDR saved.
[0082] Restore instruction execution: The following ARM instructions are used to restore the values of R0, R1, and R2 from the MEM_ADDR address: LDR R0, [MEM_ADDR] LDR R1, [MEM_ADDR, #4] LDR R2, [MEM_ADDR, #8] According to the mapping relationship recorded in the save phase, the values of R0, R1, and R2 are restored to the corresponding x86 registers EAX, EBX, and ECX respectively. For example, the restore operation is completed using the MOV EAX, R0, MOV EBX, R1, and MOV ECX, R2 instructions.
[0083] S4.2. Perform incremental stack frame recovery on the stack frames saved by layered compression.
[0084] Restore from the inside out layer by layer. The stack frame is built layer by layer in the order of function calls, and restored from the inside out layer by layer to ensure the correct stack frame structure. The innermost function stack frame is built first and destroyed last. The innermost function stack frame is restored first to ensure that the related data of the inner function stack frame is correctly restored when the outer function stack frame is restored, and will not be overwritten or destroyed by the outer function stack frame restoration process. Because the hierarchical structure of the stack frame determines that the stack frame data of the inner function is the basis of the stack frame data of the outer function, only by restoring the inner function stack frame first can the integrity and correctness of the entire stack frame structure be guaranteed.
[0085] The following is an example of assembly code: / / Restore the merged 64-bit data in the inner function stack frame to two 32-bit data LDR R2, [SP, #COMPRESSED_OFFSET] MOV R0, R2 MOV R1, R2, LSR #32 / / Restore R0 and R1 to the corresponding x86 registers ESI and EDI MOV ESI, R0 MOV EDI, R1 In the above code, the combined 64-bit data is first read from the stack into the R2 register through the LDR instruction, then decompressed into two 32-bit data R0 and R1 through the MOV and LSR instructions, and finally the values of R0 and R1 are restored to the corresponding x86 registers ESI and EDI respectively. In this way, the data in the innermost function stack frame is restored first, laying the foundation for the subsequent restoration of the middle and outer function stack frames.
[0086] S4.3. Maintain consistency during context recovery.
[0087] S4.3.1. Check before system call returns. The specific steps are as follows: After the ARM system call is completed, before resuming the x86 context, the global variables are checked. For example, for the previously recorded GLOBAL_VAR, the current value is read from the memory address 0x2000, assuming it is CURRENT_VALUE.
[0088] Query the association table to obtain the value recorded by GLOBAL_VAR before the system call, assuming it is ORIGINAL_VALUE. Use assembly instructions for comparison, such as CMP CURRENT_VALUE, ORIGINAL_VALUE.
[0089] If the comparison result is not equal, restore the value of the variable from the backup data, or restore it to the correct value through a specific recovery mechanism, such as re-executing the relevant initialization code.
[0090] This step mainly maintains the consistency of global variables before and after the system call, ensuring that the value of the global variable is not accidentally modified during the system call. Through this checksum processing mechanism, it is ensured that the state of the global variable is correct after the system call returns, thus avoiding program running errors caused by global variable state errors.
[0091] S4.3.2. Program counter verification and adjustment.
[0092] In the save phase, the value of the program counter (assumed to be EIP) before the x86 system call is recorded, assuming EIP_VALUE. After the ARM system call is completed, the value of the current ARM program counter (assumed to be PC) is obtained, assuming PC_VALUE.
[0093] Since the length of ARM instructions is different from that of x86 instructions, conversion calculation is required. According to the mapping relationship between x86 instructions and ARM instructions, the value of the x86 program counter that the PC should correspond to is calculated. For example, if one x86 instruction becomes multiple after being converted to an ARM instruction, the correct x86 program counter position needs to be calculated based on the instruction mapping table and the number of ARM instructions executed.
[0094] 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 PC according to the instruction execution flow and jump relationship recorded in the save phase. For example, if there is a conditional jump instruction JZ recorded before the system call in 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. You can modify the value of the PC register to point to the correct location to ensure that the program can continue to execute correctly after returning from the system call.
[0095] This step maintains the consistency of the program counter and ensures that the program can continue to execute from the correct position after the system call returns. By checking and adjusting the program counter, program execution errors caused by program counter errors during instruction set conversion and system calls are avoided, ensuring the correctness of the program execution process.
[0096] S4.3.3. Contextual overall verification.
[0097] Check whether the value of a register matches the value stored at the corresponding position in the stack through the association table. Assuming that the value of EAX recorded in the association table should be obtained from the stack address 0x1000, check whether the value of EAX is indeed the same as the value read from 0x1000 after recovery. Check whether the stack frame structure is complete and meets the expectations of x86 programs, for example, check whether the base pointer of the stack frame correctly points to the starting position of the stack frame, and whether the local variables in the stack frame are stored in the expected order and offset.
[0098] If any inconsistency is found, the save and restore process is checked step by step through the pre-set backtracking mechanism. If the register or global variable is inconsistent, the correct value is retrieved from the backup data. If the stack frame is inconsistent, an exception is reported and exited.
[0099] 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 operation errors caused by inconsistencies in any link, and ensuring the stability and correctness of the program.
[0100] In summary, the above are only preferred embodiments of the present invention and are not intended to limit the protection scope of the present invention. Any modifications, equivalent substitutions, improvements, etc. made within the spirit and principles of the present invention should 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 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.
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 switching optimization method according to claim 1, characterized in that: The calculation method of the correlation degree in step 2 is: Establish an association matrix, where the rows and columns of the matrix are registers respectively, and the values of the matrix elements are the association degrees. Initially, the values of the matrix elements are all 0. When multiple registers exist in the same x86 instruction at the same time, the element values determined by these registers will be incremented by 1. After completing the analysis of all instructions, the values of the elements in the association matrix are updated.
6. The instruction conversion context switch optimization method according to claim 5, characterized in that: 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.
7. 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.
8. 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.
9. 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.
10. The instruction conversion context switch optimization method according to claim 9, 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
Virtual processor context switching method and device, storage medium and electronic equipment
CN119201352A
Processor, which stores interrupt enable flags in a location used for other functions
GB2461851A
Stack switching mechanism in a computer system
US20020019902A1
Cited By
Reverse debugging increment recording method based on dynamic layering and predictive filtering
CN121301173A
Reverse debugging delta recording method based on dynamic layering and predictive filtering
CN121301173B