0

I'm starting to pock around with assembly for a school project. The project stipulates we have to write in ASM 64 bits.

Here is my code :

global _start

_start:
    sub esp, 4
    mov [esp], byte 'H'
    mov [esp+1], byte 'e'
    mov [esp+2], byte 'y'
    mov [esp+3], byte '!'
    mov eax, 4
    mov ebx, 1
    mov ecx, esp
    mov edx, 4
    int 0x80
    mov eax, 1
    mov ebx, 0
    int 0x80

Compiling and linking with this works :

 ➜  nasm -f elf32 ex3.asm && ld -m elf_i386 ex3.o -o ex3 && ./ex3
Hey!

But compiling with this doesn't :

 ➜  nasm -f elf64 ex3.asm && ld -m elf_x86_64 ex3.o -o ex3 && ./ex3
[1]    17876 segmentation fault (core dumped)  ./ex3

My idea is that I use a 64 bits cpu machine (xubuntu on a VM provided by the school for this project), and the project states it has to be 64bits code, so I should compile with the later flags, but it will only work with the former. What causes the segmentation fault ?

Any idea why my code is not right for 64 bits compilation ?

Cheers !

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Bstorm
  • 247
  • 1
  • 10
  • Truncating the RSP (the stack pointer) to 32 bits will lead to a fault when you try to use `[esp]`. And even if you avoided that, `int 0x80` would return `-EFAULT` for reasons explained in [What happens if you use the 32-bit int 0x80 Linux ABI in 64-bit code?](https://stackoverflow.com/q/46087730) – Peter Cordes Jun 07 '20 at 11:40
  • [assembly, segmentation fault](https://stackoverflow.com/q/31887645) explains a similar segfault from 32-bit pointers in 64-bit code. Can't add it as a duplicate because nobody's upvoted the answer (turns out to be one I wrote 5 years ago :). – Peter Cordes Jun 07 '20 at 11:46
  • And BTW, use `push 'Hey!'` like a normal person; no need for four separate byte stores, and NASM has convenient syntax for multi-character character constants as numeric literals. – Peter Cordes Jun 07 '20 at 11:49
  • Thanks for your answer and the links, indeed it start to make sens to me, I didn't realised I was truncating it until you pointed it out. Well about using push 'Hey!' like a normal person, I will wait until I am a normal person, as of now I am trying to understand exactly what is going on for each and every thing that I do so... thanks for the heads up, but I will keep being a noob for a little while longer ;) – Bstorm Jun 07 '20 at 14:35
  • heh, fair enough. :P That does save the trouble of checking how NASM handles strings as numbers if you didn't already know, or of manually doing little-endian `0xwhatever` with ASCII codes in the right order. – Peter Cordes Jun 07 '20 at 14:40

0 Answers0