In assembly, how do I add a 5 byte instruction into a 3 byte space in the debugger

萝らか妹 提交于 2021-02-11 07:49:40

问题


I'm trying to change this line

0041DE91 | 8B 46 64                 | mov eax,dword ptr ds:[esi+64]  
0041DE94 | 83 C4 0C                 | add esp,C                                   
0041DE97 | 83 F8 01                 | cmp eax,1                                   

to

0041DE91 |  mov eax, 10

But the instruction which was 3 bytes occupies 5 bytes and spills into the two addresses below it:

0041DE91 | B8 0A 00 00 00           | mov eax,10                                    
0041DE96 | 0C 83                    | or al,83                                    
0041DE98 | F8                       | clc                                    

Is it possible to do this in a debugger to a pre-compiled program?


回答1:


In 32-bit code (where there's no red-zone to clobber) you can move imm8 constants into registers (inefficiently) with 3 bytes:

push   10       ; 2B
pop    eax      ; 1B

You can also get 1 into a register in 3B

xor    eax, eax  ; 2B
inc    eax       ; 1B

Or, given any other register of known contents:

lea    eax, [ecx+/-imm8]   ; 3B

Other code-golf / code-size-optimization tricks:

xor    eax,eax   ; 2B
cdq              ; 1B to zero edx as well

xchg   eax, ecx  ; 1B.  Shorter than MOV if you want ecx=eax and can trash eax (or both parts are actually useful)

Many of these are applicable to 16-bit and 64-bit code as well. See for example my adler32 in 32B of x86-64 machine code, and the x86-16 version.




回答2:


If you have some spaces left around that 3-byte area you can put the new code there and do a near jump, do what you need and jump back.

That technique is used to implement hot-patching in Windows. It's done by putting MOV EDI, EDI as a 2-byte NOP at the beginning of the function. Then when the function needs to be patched, they replace that "NOP" with a JMP $-5 and a full jump to the new function would be put in the 5 bytes before the function

  • Why do Windows functions all begin with a pointless MOV EDI, EDI instruction?

  • What does "Hot Patchability" mean and what is it for?

So now basically you need to change

mov eax, dword ptr ds:[esi+64]
add esp, C
cmp eax, 1

to

    jmp new_instruction
continue:
    add esp, C
    cmp eax, 1
...
new_instruction:
    mov eax, 10
    jmp continue

With this method you can replace the original instruction any sequence of instructions. However for setting small values then Peter's solution is better



来源:https://stackoverflow.com/questions/40363247/in-assembly-how-do-i-add-a-5-byte-instruction-into-a-3-byte-space-in-the-debugg

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!