1

When I'm overwriting the first opcodes of a function with the jmp opcode , I'm actually writting 5 bytes (or 2 for jmp short). But what if another thread (from the same proccess) will call this function while I'm changing it? This will cause unexpected behavior. But I didn't find any explaination . The hooking articles igonre it , like there is no problem.

Maybe in win32api you use the fact that there are nops with mov edi,edi . but my question is more theoretical

thanks

avi.c
  • 65
  • 6

2 Answers2

1

It is quite possible to cause issues. You can create a critical section on the to-change code and enter the critical section to ensure exclusive access while changing the code.

In the mutual access case, the executing thread can (theoretically) see the first byte and will proceed to execute a jump on the following 4 bytes (in case of a long jump). In case of a call, the next instruction (IP) is pushed prior to the jump, and that is current + 5. Theoretically, a ret may cause that thread to run into unmodified instructions (where you might need a nop, for example).

This is all theoretical, but you should prevent mutual access while changing code.

Deathspike
  • 8,582
  • 6
  • 44
  • 82
  • A critical section will not help because only your code will be using it. Threads that are not yours will simply execute the instructions while your thread owns the critical section. – Marc Sherman Sep 04 '13 at 15:17
1

If you inject into a specific process you are able to suspend the process, install all your hooks and continue after that.

defragger
  • 156
  • 4
  • Not 100% because a thread might be suspended at the exact moment it is in the middle of executing the very instructions a hook overwrites. – Marc Sherman Sep 04 '13 at 15:20
  • 2
    maybe you can check the eip for the specific thread with GetThreadContext before you change the code – defragger Sep 05 '13 at 09:48
  • That should make it 100%. I guess if the eip for any thread is there the code can wait until none of the threads have their eip there and then overwrite the instructions. – Marc Sherman Sep 05 '13 at 12:33