1

I would like to call ASM (MASM) from C (GCC). Easy! Now i would like my asm function to be able to use data and to call functions like printf().

I got two problems: the data section and the call to printf()

I have read examples on internet which are exactly like mine but don't seem to fail. Any help is welcomed.

test.c:

#include <stdio.h>
int64_t asmfunc();
int main() {
asmfunc());
return 0;
}

test.asm

global  asmfunc
section .data
msg: db "a very inspired message!",10,0
section .text
extern printf
asmfunc:
mov edi,msg
xor eax,eax
call printf
ret 

compilation:

nasm -felf64 maxofthree.asm 
gcc callmaxofthree.c maxofthree.o 

result:

/usr/bin/ld: maxofthree.o: relocation R_X86_64_32 against `.data' can not  
be used when making a shared object; recompile with -fPIC

if i just leave the printf call, removing the .data section and the "mov edi,msg", i get

 /usr/bin/ld: maxofthree.o: relocation R_X86_64_PC32 against symbol 
`printf@@GLIBC_2.2.5' can not be used when making a shared object; 
recompile with -fPIC

Thanks fellow coders

Ross Ridge
  • 38,414
  • 7
  • 81
  • 112
Mist
  • 11
  • 3
  • 1
    Use `call printf wrt ..plt`. Some versions of gcc create position independent code by default. `gcc -no-pie` could work too. See also [this answer](https://stackoverflow.com/a/28699189/547981). You might also have to replace `mov edi,msg` with `lea rdi, [rel msg]`. – Jester Jul 04 '18 at 16:26
  • call print wrt ..plt gives me a segmentation fault unfortunatly, thanks for the hint anyway, we may be getting closer – Mist Jul 04 '18 at 16:37
  • 1
    You also need to align the stack. – Jester Jul 04 '18 at 16:39
  • Your solution were good and solved the problem. Thanks you. Due to my noobness i forgotten edi has become rdi thanks to asm32/64. Not even needed to align the stack. Thanks again – Mist Jul 04 '18 at 17:26
  • @Mist Please don't add “solved” to your post titles. Instead, add an answer for you own question addressing how you solved it. – fuz Jul 04 '18 at 17:35

1 Answers1

0

solution:

test.asm

global  asmfunc
section .data
msg: db "a very inspired message!",10,0
section .text
extern printf
asmfunc:
lea rdi,[rel msg]
xor rax,rax
call printf wrt ..plt
ret 

thanks for your help

Mist
  • 11
  • 3
  • 1
    This misaligns the stack for printf, and could potentially segfault on some future version of libc ([like glibc scanf currently does](https://stackoverflow.com/questions/51070716/scanf-throws-segmentation-fault-core-dumped-when-using-nasm-gcc-on-linux-64b)). Use `jmp printf wrt ..plt` to tailcall it, or put a dummy push/pop around it. – Peter Cordes Jul 05 '18 at 20:17