I am trying to create a program that calls external functions from assembly. I was following this guide https://www.devdungeon.com/content/how-mix-c-and-assembly and tried to use the code under the Calling C from Assembly section:
extern printf
SECTION .DATA
msg: db "Hello world", 0 ; Zero is Null terminator
fmt: db "%s", 10, 0 ; printf format string follow by a newline(10) and a null terminator(0), "\n",'0'
SECTION .TEXT
global main
main:
push rbp ; Push stack
; Set up parameters and call the C function
mov rdi,fmt
mov rsi,msg
mov rax,0
jmp printf
pop rbp ; Pop stack
mov rax,0 ; Exit code 0
ret ; Return
I used nasm test.asm -f elf64 and then gcc test.o -no-pie -o test
but when running it would instantly segfault.
I looked at it in gdb and it segfaults on the first instruction
► 0x402014 <main> push rbp
I think the culprit is that this section of code is not executable.
vmmap
0x400000 0x401000 r--p 1000 0 [redacted]
0x401000 0x402000 r-xp 1000 1000
0x402000 0x403000 r--p 1000 2000
0x403000 0x404000 r--p 1000 2000
0x404000 0x405000 rw-p 1000 3000
to further back this idea when compiling with gdb and not using the -no-pie argument I get this error message
/usr/bin/ld: test.o: warning: relocation in read-only section .TEXT
/usr/bin/ld: test.o: relocation R_X86_64_PC32 against symbol printf@@GLIBC_2.2.5 can not be used when making a PIE object; recompile with -fPIE
/usr/bin/ld: final link failed: bad value
collect2: error: ld returned 1 exit status
Any help is appreciated, Thanks.