1

Intel/AMD says that this:

mov rax, 0xabc
jmp rax

is not equivalent to this:

jmp 0xabc

Since the first assumes absolute jumps because of the register, and the second assumes relative jumps. My question is, what if I wanted to do a relative jump where the offset is stored in a register such as rdi?

I searched other answers in SO, however they weren't so enlightening.

  • 3
    Relative to what? When you `jmp label`, the assembler automatically subtracts the address of the instruction following the `jmp` from the value of `label`, and inserts that value in the instruction. In ordinary use, you wouldn't ever have a relative offset in a register, because you wouldn't know what offset to use. The concept doesn't apply. – Tim Roberts Aug 28 '23 at 04:03
  • Hey @TimRoberts. Actually, it's not ordinary use. I'm simply curious because, since we can do relative short jumps with immediate values, I tried doing them by hand, without using labels. Now I just wanna know how I would do the same but when the register contains the value. – Pedro Vinícius Aug 28 '23 at 05:57
  • There's no POINT to it. We use relative jumps for two reasons: to keep the instruction size down, and to avoid having to patch those instructions when the code is moved. The same limitations don't apply to register jumps. – Tim Roberts Aug 28 '23 at 06:10

1 Answers1

2

You would have to add the base address to the offset to form an absolute address in the register and then jump to that.

For example

    ; jump table contains offsets relative to jump_base
    ; index into jump table is in rax
    lea rcx, [rel jump_table]
    mov ecx, [rcx+rax*4]
    lea rax, [rel jump_base]
    add rax, rcx
    jmp rax
jump_base:
prl
  • 11,716
  • 2
  • 13
  • 31
  • 1
    This is more or less what `gcc -fPIE` / `-fPIC` does for `switch` statements when it decides to make a jump table. [GCC Jump Table initialization code generating movsxd and add?](https://stackoverflow.com/q/52190313) - instead of two LEAs, it makes the displacements relative to the `jump_table` address. In the "small PIC" code model, all static code+data is within 2GiB of each other. (It uses a `movsxd` sign-extending load so the displacements can be negative.) – Peter Cordes Aug 28 '23 at 06:35