0

I have some code that hooks a function via dll injection. The code works fine but i'm a little perplexed as to how it works. The code needs to calculate the offset from the function that i'm going to hook to the hooked function. It works perfectly but i've noticed that sometimes the offset is positive and sometimes it's negative (e.g. m_hkFuncAddr < m_hkAddr). Sometimes my dll is loaded before the address i'm trying to hook and sometimes it is after (I check using a utility called vmmap if that means anything). Regardless, it will work. But if I reverse the two, it's a guaranteed crash, regardless of where my dll is placed.

dwhkRelative = (((DWORD)m_hkFuncAddr - (DWORD)m_hkAddr) - 5);

Why is it that when I reverse the two it crashes, but when it's a negative offset, it works fine? Thanks in advance!

  • Please add details on what's m_hkFuncAddr and m_hkAddr – sudhackar Oct 18 at 4:52
  • What do you do with dwhkRelative? – Igor Skochinsky Oct 19 at 20:25
  • Sorry I should have elaborated more. m_hkFuncAddr is the address of the function in my Dll that i'm injecting where I want the hook to jump to. m_hkAddr is the address of the function I want to hook. dwhkRelative is the relative offset between the two. I calculate the offset and place a relative jmp instruction (0xE9) at m_hkAddr and then one byte after that that I place dwhkRelative. It works perfectly but I don't understand how or why when m_hkFuncAddr is less than m_hkAddr. – user192148 Oct 20 at 19:08
  • Why does this matter? DLLs do sometimes have preferred base addresses (especially the ones that ship with Windows), but this stuff is all negotiable and your address space is going to be swiss cheese eventually after DLLs load/unload and perform init. If you reverse the two, you are jumping to a completely unrelated address. Why wouldn't it crash? – MrGencyExit64 Oct 22 at 5:18
0

The jmp instruction with opcode 0xE9 uses a 32bit signed integer as its parameter.

This parameter is added to the address of the instruction after the jmp instruction to calculate the final address. It is allowed to be negative which is the case when your hook address is less than your hooked function's address.

As to why swapping them around crashes - it calculates the wrong number. It would calculate What do I have to add to the hook address to get to the hooked function's address which is the other way round.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.