Search code examples
delphiassemblypage-jump

What is relative jump?


Why it is used to hook and redirect functions?

Like this:

procedure RedirectProcedure(OldAddress, NewAddress: Pointer);
var
  NewCode: TInstruction;
begin
  NewCode.Opcode := $E9; //relative jump
  NewCode.Offset := NativeInt(NewAddress)-NativeInt(OldAddress)-SizeOf(NewCode);
  PatchCode(OldAddress, NewCode, SizeOf(NewCode));
end;

By the way, what $E9 constant means?


Solution

  • A jump instruction moves the instruction pointer to a new location. It's the machine language equivalent of goto. Absolute jumps move the instruction pointer to an absolute address. A relative jump jumps to an address specified relative to the current instruction pointer.

    The $E9 opcode is a relative jump with a 32 bit offset. Note that there are different jump opcodes for jumps with differently sized offsets.

    The address is relative to the end of the jump instruction, hence the SizeOf(NewCode) adjustment.

    That code does look familiar to me. I think I wrote it!