1

I am trying to follow along this tutorial on the stack in x86 assembly. It seemed to me that esp is a register containing a pointer to the top of the stack - and to test this out I dereferenced esp and tried to store its value in eax. This gave me a segmentation fault, and I cannot figure out why. With GDB, I was able to confirm that this dereference caused the error:

(gdb) disassemble
Dump of assembler code for function main:
   0x0000000100000fa2 <+0>: pushq  $0x32
=> 0x0000000100000fa4 <+2>: mov    (%esp),%eax
   0x0000000100000fa8 <+6>: mov    $0x0,%rdi
   0x0000000100000faf <+13>:    mov    $0x2000001,%rax
   0x0000000100000fb6 <+20>:    syscall
End of assembler dump.
(gdb)

But I cannot figure out why. Does anyone acquainted with the stack in x86 know what I am doing wrong?

How I am assembling: gcc -masm=intel access_stack_via_pointer.asm It's also important to note that I am on MacOS.

    .global _main
    .text
_main:
    push 50

    # why the segmentation fault?
    # eax should have 50 in it
    mov eax, [esp]

    mov rdi, 0
    mov rax, 0x2000001
    syscall
Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Caspian Ahlberg
  • 934
  • 10
  • 19
  • 1
    That's a 32-bit tutorial. If you want to port it to 64-bit mode, you have to understand the differences. It should be obvious in GDB if you do `info reg` that RSP has a value larger than 32-bit, so RSP != ESP. – Peter Cordes Oct 01 '20 at 03:12
  • 2
    Does this answer your question? [Segfault when loading from \[esp\] in 64-bit code](https://stackoverflow.com/q/54498071) (also [A modification to %esp cause SIGSEGV](https://stackoverflow.com/q/15656887)) – Peter Cordes Oct 01 '20 at 03:14
  • 1
    bleh, the only tag you used that I have a gold badge in was [x86], you left out [assembly]. Since this is specifically an x86-64 problem, I retagged it and then couldn't dup-hammer. – Peter Cordes Oct 01 '20 at 03:15
  • 2
    Note that you really shouldn't port a tutorial to a different architecture while following it. – fuz Oct 01 '20 at 09:03
  • @PeterCordes prl solved my question – Caspian Ahlberg Oct 01 '20 at 17:09

1 Answers1

1

In 64-bit mode, the stack pointer is RSP, not ESP. Using ESP uses the low 32 bits of the register, which isn’t a valid memory address.

prl
  • 11,716
  • 2
  • 13
  • 31
  • Duplicate of [Segfault when loading from \[esp\] in 64-bit code](https://stackoverflow.com/q/54498071), if you want to help close this. – Peter Cordes Oct 01 '20 at 03:16