0

Hello wonderful people,

I am a complete newbie in assembler. Knowing that, can someone explain to me why this code linked with ld crashes (nasm syntax):

section .text
    global _start
_start:
enter 0, 0
call main
leave

main:
    enter 16, 0
    mov dword [rbp - 4], 4
    leave
    ret

while this, linked using gcc does not?

section .text
global main

main:
    enter 16, 0
    mov dword [rbp - 4], 4
    leave
    ret

I think the magic happens in the _start defined by gcc but when I looked into it, I really saw just some really random operations. Here is _start disassembled in case someone can see what makes the gcc version work as opposed to mine:

   0x0000000000401020 <+0>: endbr64 
   0x0000000000401024 <+4>: xor    ebp,ebp
   0x0000000000401026 <+6>: mov    r9,rdx
   0x0000000000401029 <+9>: pop    rsi
   0x000000000040102a <+10>:    mov    rdx,rsp
   0x000000000040102d <+13>:    and    rsp,0xfffffffffffffff0
   0x0000000000401031 <+17>:    push   rax
   0x0000000000401032 <+18>:    push   rsp
   0x0000000000401033 <+19>:    mov    r8,0x401190
   0x000000000040103a <+26>:    mov    rcx,0x401120
   0x0000000000401041 <+33>:    mov    rdi,0x401110
   0x0000000000401048 <+40>:    call   QWORD PTR [rip+0x2fa2]        # 0x403ff0
   0x000000000040104e <+46>:    hlt 

I compile using the following commands:

nasm -f elf64 file.asm
ld file.o

and

nasm -f elf64 file.asm 
gcc file.o

Thank you for your time.

ecm
  • 2,583
  • 4
  • 21
  • 29
  • 1
    Your `_start` code does `leave` but nothing after that, so that `main` is re-entered after control flow passes by the `leave`. This will eventually try to return, but `_start` is not a function so it doesn't get a valid return address on the stack, leading to a crash. You have to invoke an exit system call to return the control flow to the operating system. – ecm Feb 07 '23 at 08:29
  • 1
    The details aren't identical to the duplicates, but the result is the same: running a `ret` with RSP where it was on entry to `_start`, pointing at `argc` – Peter Cordes Feb 07 '23 at 08:39

0 Answers0