1

I was experimenting and have the following assembly code, which works very well, except that I get a "Segmentation fault (core dumped)" message right before my program ends:

GLOBAL _start

%define ___STDIN 0
%define ___STDOUT 1
%define ___SYSCALL_WRITE 0x04

segment .data
segment .rodata
    L1 db "hello World", 10, 0
segment .bss
segment .text
_start:
    mov eax, ___SYSCALL_WRITE
    mov ebx, ___STDOUT
    mov ecx, L1
    mov edx, 13
    int 0x80

It doesn't matter whether or not I have ret at the end; I still get the message.

What's the problem?

I'm using x86 and nasm.

3
  • 2
    You need to syscall exit explicitly.
    – n. m.
    Sep 25, 2013 at 20:34
  • 1
    Possible duplicate of Nasm segmentation fault
    – Cody Gray
    Jun 11, 2017 at 12:49
  • 1
    Related: you can't ret from _start, you have to make a sys_exit, sys_exit_group, or raise a signal which terminates your process. Falling off the end of _start is a different problem (with the same solution) as trying to use ret at the end of _start. Feb 26, 2018 at 23:39

1 Answer 1

5

You can't ret from start; it isn't a function and there's no return address on the stack. The stack pointer points at argc on process entry.

As n.m. said in the comments, the issue is that you aren't exiting the program, so execution runs off into garbage code and you get a segfault.

What you need is:

;; Linux 32-bit x86
%define ___SYSCALL_EXIT 1

// ... at the end of _start:
    mov eax, ___SYSCALL_EXIT
    mov ebx, 0
    int 0x80

(The above is 32-bit code. In 64-bit code you want mov eax, 231 (exit_group) / syscall, with the exit status in EDI. For example:

;; Linux x86-64
    xor   edi, edi     ;  or mov edi, eax    if you have a ret val in EAX
    mov   eax, 231     ; __NR_exit_group
    syscall

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.