1

Why is it possible to do something like:

mov %rbx, %rcx

But not to do:

mov %rip, %rax
# lea (%rip), %rax

Why is this the case, and how does call go about calculating the return address?

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
samuelbrody1249
  • 4,379
  • 1
  • 15
  • 58
  • 2
    Because the `rip` is not a general purpose register and has no encoding. The `lea` is legal and works, however. `call` basically uses `rip` as the return address as that already points past the current instruction in the x86 architecture. – Jester Aug 29 '20 at 22:59
  • @Jester ok, so then `call func` basically does: `sub $8, %rsp`; `lea %rip, %rax`; `mov %rax, (%rsp)`; `jmp func` (ignoring that the instructions themselves will alter the return address) ? – samuelbrody1249 Aug 29 '20 at 23:10
  • 4
    How instructions work "internally" is not limited to the operations which the ISA makes available to machine code – harold Aug 29 '20 at 23:12
  • @harold thanks, could you please explain that a bit? I'm very new to assembly. – samuelbrody1249 Aug 29 '20 at 23:13
  • Yes, that's basically how it works. You also need to ignore `rax` and flags being overwritten. – Jester Aug 29 '20 at 23:30
  • Look in the x86 documentation to see what each instruction does and what the possible operands are. – old_timer Aug 29 '20 at 23:39
  • My answer on [Why can't you set the instruction pointer directly?](https://stackoverflow.com/a/41150027) has some conceptual discussion about general-purpose registers vs. special registers that need special instructions or addressing modes to access them. Also [How to know if a register is a "general purpose register"?](https://stackoverflow.com/a/45538667) has more about that concept. Are those answers what you were looking for with your question about how call can work? IDK why you have a commented-out RIP-relative LEA; that solves everything in 64-bit mode. – Peter Cordes Aug 30 '20 at 02:01
  • @samuelbrody1249 The CPU vendor can do whatever he wants to implement an instruction. He does not need to implement more complex instructions exactly in terms of simpler instructions. – fuz Aug 30 '20 at 10:45

0 Answers0