Reputation: 41
I am trying to hook a function by replacing its beginning with a JMP instruction which should lead to my function. But the problem is that I don't know how to calculate the JMP offset to target the address of my function. Well, I know how to do it if you jump forward in memory (Destination addr - Current addr), but I haven't got any ideas how to determine it when you jump back in memory.
Could somebody help?
Upvotes: 3
Views: 11309
Reputation: 3
hello i suggest you use the 'call' statement. The 'call' statement will take care of putting the return pointer on the stack.
the formula to calculate the jump you need to do is: ToAddress - FromAddress - 5
-5 this is because it is the space that the 'call' + offset instruction occupies in memory
pointers in memory are written inversely. if you want to point to memory 0x857830, in memory this value is written 307885
instructions opcode jmp = 0xE9 call = 0xE8
Upvotes: -2
Reputation: 173
Be sneaky
Make a dummy call to a location above your function
call location1
.location1
call location2
.location2
pop ax
ret
.yourfunction
You now have the address of location2 in ax
add 3 to ax and you have the memory address of your function
Upvotes: -6
Reputation: 612993
Just use negative offset to jump backwards.
And remember to account for the size of the JMP
instruction. The offset is relative to the end of the JMP
instruction and not the beginning. If the current address is where you are about to write the JMP
then you need an offet of 5+dest-current since the size of the JMP
instruction plus the offset if 5 bytes.
Upvotes: 8
Reputation: 125708
This is basic math that you should be able to figure out. :)
If a JMP forward is Destination - Origin
, then a JMP
backward would be Origin - Destination
Think about it in plain numbers: If you want to JMP
forward from 100 to 110, your JMP
would be 110 - 100 = 10
. If you want to JMP
the same amount backward, it would be 100 - 110 = -10
.
Upvotes: 7
Reputation: 26171
relative jumps are signed, that is, they have positive and negative displacement using the sign bit. absolute jumps are absolute so it doesn't matter. see volumes 2A & 2B of the intel instruction guide.
Upvotes: 1