hooking ,dll injection and thread safe

626 views Asked by At

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

2

There are 2 answers

1
Deathspike On BEST ANSWER

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.

3
defragger On

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