Home > database >  running NASM assembly gives a segfault
running NASM assembly gives a segfault

Time:12-13

I'm trying to make ELFs from scratch to better understand how they work. I tried this simple program:

mov eax,1
mov ebx,4
syscall

Which should simply exit with code 4, but when I assemble (nasm test.asm -o asm.bin) put it in the ELF and run it it doesn't work and it segfaults. It could be a problem of the ELF, but I don't think so because I tried with the manual assembly of the tutorial I'm following and it works as expected. The weird thing is that the assembly the tutorial I'm following uses (which is manually assembled) is different than the one nasm produces (for example, mov rax,0 is encoded as 66 B8 00 00 00 00 by nasm where the tutorial encodes it as B8 00 00 00 00, without the leading 0x66). As I said though, the tutorial's is working while the assembler's isn't. I've never used NASM before, so am I missing some assembler flags or something like that?

CodePudding user response:

The 66 byte indicates the issue; nasm is assembling in 16-bit mode by default, so mov eax,1 requires an opcode size prefix (the 66 byte) to switch to a 32-bit operation. However, (I'm assuming) you're running this program in a 32/64-bit OS, which means the CPU is interpreting the prefix to switch to 16-bit; thus it sees the instruction as 66 B8 01 00, aka mov ax,1; now the instruction pointer is misaligned, hence the crash.

The fix is to put a bits 32 or bits 64 (whichever is appropriate) directive at the top of your assembly file.

  • Related