0

I'm trying to understand why as behaves differently than nasm when doing syscalls on the assembly level. Because I'm a glutton for punishment, I'm using Intel syntax. Here's my program:

    .intel_syntax noprefix
    .section    .rodata
.LC0:
    .string "Hello world!\n"
    .text
    .globl  _start
    .type   _start, @function
_start:
    mov edx, 13
    mov ecx, OFFSET FLAT:.LC0
    mov eax, 4
    int 0x80
    ret

I assemble with as -o prog.o prog.s and link with ld -s -o prog prog.o.

But when I run it, I get:

$ ./prog 
Hello world!
Segmentation fault (core dumped)

GDB is not particularly helpful here. When I stepi on ret, it says Cannot access memory at address 0x1. Which is puzzling, because the value of ESP is:

(gdb) info registers esp
info registers esp
esp            0xbffff660       0xbffff660

Why does this program segfault?

1
  • You can't just ret from your program, you need an exit system call. The 1 is the number of arguments (argc) which happens to be on the top of the stack, so ret tries to use it as an address with obvious consequences. Commented Nov 7, 2017 at 23:52

1 Answer 1

2

Because it never exits properly. _start doesn't have a parent stack frame, so returning from it will cause a crash.

You can return from main to have the standard library's _start implementation call exit for you, but if you're writing your own _start, you need to call exit yourself, as there's no parent stack frame to return to.

Sign up to request clarification or add additional context in comments.

5 Comments

@DanBarowy Mostly copied? I'm venturing the mostly may be the problem. If ret was working then _start wouldn't be the entry point, main would be. And the way you link it would be different since you need the C runtime. What page/example in the book did you mostly copy from?
My last comment is to a now deleted comment it seems ;-)
@DanBarowy I'd go a step further: that book is simply crap, and should be discarded. It reads like it was written for DOS programmers, then hastily adapted to Linux at the last minute. (And many of the Linux details are seriously outdated, as the book was published in 2000…)
Also, a hilarious detail: edlinas, the "no.1 Linux x86 hands-on assembler development simulator" (according to the cover, at least) is actually a QBasic program, and can only be run under DOS.
Yes @MichaelPetch and @duskwuff, I realized that I had replaced main with _start after I posted the comment, which lead to the aha moment where I realized that I was the idiot here. So I deleted the comment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.