Reputation: 1159
i try write simple assemble program with printf function. I compile it nasm -f elf 64
and link using gcc
. After run i see segmentation fault
. What is wrong?
[Bits 32]
extern printf
global main
section .data
hello:
db "Hello", 0xa, 0
section .text
main:
push hello
call [printf]
add esp, 4
mov eax, 1
mov ebx, 0
int 80h
Upvotes: 6
Views: 8598
Reputation: 2914
If you really want to get a 32 bit binary as your code header shows then you just need to fix the line:
call [printf]
changing it to:
call printf
When you do call [printf]
you are not calling printf but the address pointed by first printf code bytes, that construction ([address]
) is called an effective address.
Upvotes: 3
Reputation:
Linux on ia32 doesn't use the same calling convention as on amd64. As your code uses the former you must assemble it as 32 bits and link with a 32 bits libc. On debian you'll need the libc6-dev-i386 package.
You must also replace 'call [printf]' with 'call printf', that's a mistake.
Note also that as you are using the main interface you should return from main instead of performing an exit system call to allow the C runtime shutdown code to run.
Hello World example for x86-32 with build instructions.
If you are working on amd64, you might want to learn how to write 64 bits assembly instead.
Hello World example for x86-64 with build instructions.
Upvotes: 8