0

I am trying to learn how to use .s files, and wrote the following:

    .globl main
    .text

main:
    mov $msg, %rdi
    call puts

    ret

    .data
msg:
    .asciz "Hello, world!"

I then compile with the following:

$ gcc -no-pie -c -o example.o example.s
$ gcc -no-pie -o example example.s

The example executable produced prints Hello, world! as expected, but exits with exit code 14, suggesting that something went wrong regarding the print?

I tried exiting manually like so:

    .globl main
    .text

main:
    mov $msg, %rdi
    call puts

    mov 0, %rdi
    call exit

    ret

    .data
msg:
    .asciz "Hello, world!"

However, this segfaulted. From gdb, it seems to segfault on the line mov 0, %rdi, however I've tried multiple ways of moving (movq 0, %edi, movl 0, %edi, mov 0x0, %rdi) and all have segfaulted.

Am I doing something wrong?

Basil
  • 488
  • 1
  • 15
  • In the first program, before the `ret` instruction, set `%rax` to zero. This is equivalent to `return 0;` in a C program. – Some programmer dude Dec 13 '22 at 16:33
  • @Someprogrammerdude Ah I see, it's in `%rax`? I just tried `mov 0, %rax` but this segfaulted as well? Am I moving immediates into registers wrong? – Basil Dec 13 '22 at 16:35
  • @Someprogrammerdude Ah whoops, that was a typo - In my actual code, `ret` is after `exit`. Just fixed that ^^ – Basil Dec 13 '22 at 16:38
  • By the way, if you're wondering what the exit code `14` comes from, it just happens to be what [`puts`](https://en.cppreference.com/w/c/io/puts) returned (because that's what happens to be in `%rax` when you invoke the `ret` instruction). – Some programmer dude Dec 13 '22 at 16:42
  • @Someprogrammerdude Ah gotcha, that makes sense - I thought `ret`'s exit code would be in `%rdi` like function arguments. – Basil Dec 13 '22 at 16:45
  • What resource have you used to learn that the first argument should be in `%rdi`? Didn't it say that the returned value should be in `%rax`? – Some programmer dude Dec 13 '22 at 16:47
  • 4
    Try `mov $0, %rax`. Without a dollar sign, the number is interpreted as an absolute address; you are effectively dereferencing a null pointer. – fuz Dec 13 '22 at 16:55
  • You're lucky `puts` itself didn't fault; [glibc scanf Segmentation faults when called from a function that doesn't align RSP](https://stackoverflow.com/q/51070716) – Peter Cordes Dec 13 '22 at 17:49

0 Answers0