gaultier/blog

Question: lea rsi, [rsp] in this context equivalent to mov rsi, rsp?

sy2002 opened this issue · 2 comments

sy2002 commented

Thank you for writing the blog article https://gaultier.github.io/blog/x11_x64.html

Was a fun read! :-)

I do have a question about this very piece of code:

%define SYSCALL_WRITE 1
%define STDOUT 1

print_hello:
  push rbp ; Save rbp on the stack to be able to restore it at the end of the function.
  mov rbp, rsp ; Set rbp to rsp

  sub rsp, 5 ; Reserve 5 bytes of space on the stack.
  mov BYTE [rsp + 0], 'h' ; Set each byte on the stack to a string character.
  mov BYTE [rsp + 1], 'e'
  mov BYTE [rsp + 2], 'l'
  mov BYTE [rsp + 3], 'l'
  mov BYTE [rsp + 4], 'o'

  ; Make the write syscall
  mov rax, SYSCALL_WRITE
  mov rdi, STDOUT ; Write to stdout.
  lea rsi, [rsp] ; Address on the stack of the string.
  mov rdx, 5 ; Pass the length of the string which is 5.
  syscall

  add rsp, 5 ; Restore the stack to its original value.

  pop rbp ; Restore rbp
  ret

You write lea rsi, [rsp] .

But if you would omit the brackets [ and ] : Wouldn't then a

mov rsi, rsp equivalent and sufficient in this situation?

I am not super fit in X86 assembly, so I might be totally wrong - just curious because I thought the brackets are "de-referencing" the pointer (i.e. deliver the value at the address) so what if you are not de-referencing the pointer in the first place and just move the actual stack pointer?

Hi!
In this context, yes. mov & lea overlap in some cases, here they are the same, with one caveat.

On macos, lea is preferred: https://stackoverflow.com/a/47301555

I have not tested this code on macos, but I expect mov to fail and lea to succeed (see the stack overflow link).
On other Unices, changing lea to mov here should be perfectly fine.

sy2002 commented

Thank you for taking the time and for your very helpful answer: You boosted my understanding of x86 assembly :-)