0

I am playing around trying to call assembly functions I have written in Nasm within C. For some reason things are not behaving as I am expecting.

NASM:

SECTION .DATA
  hello: db 'Hello', 0x0a ; Hello/n

SECTION .TEXT
  global sayHello

sayHello:
  mov rax, 4           ; write()
  mov rbx, 1           ; stdout
  mov rcx, hello       ; add hello to register
  mov rdx, 6           ; length of string
  int 0x80             ; interrupt
  ret                  ; return
C:

#include <stdio.h>

extern int sayHello();

int main(int argc, char **argv) {

  printf("ASM Function is saying Hello:\n");
  sayHello();
  

  return 0;
}

compiled with: nasm -f elf64 and gcc

result:

ASM Function is saying Hello:

expected result:

ASM Function is saying Hello:
Hello

What am I missing?

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
  • Modern GCC makes PIE executables so the string address will be outside the low 32 bits. Truncating it to 32-bit with the `int 0x80` 32-bit ABI will make `write` return `-EFAULT`. Use `strace` or a debugger (like GDB) to single-step your code. – Peter Cordes Aug 07 '20 at 02:39

1 Answers1

1

You are making a 32-bit syscall in a 64-bit program.

That works on Linux, but only if your pointers fit in 32 bits! They probably don't (check the address of hello) otherwise you will probably get EFAULT (because the address is truncated, and probably points to unmapped memory).

Making a 64-bit syscall

  • Use the correct registers for 64-bit (rax, rdi, rsi, rdx)

  • You need to use the 64-bit syscall numbers (asm/unistd_64.h defines __NR_write 1, consider using #include if possible).

  • Use syscall instead of int 0x80.

Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415
  • The x86-64 SysV `syscall` calling convention is similar to the function-calling convention, with args in EDI, RSI, RDX (in that order). Only the 32-bit ABI makes the unfortunate choice of EBX (a call-preserved register) as the first arg, which makes libc wrapper functions less efficient. – Peter Cordes Aug 07 '20 at 02:40
  • Gah, thanks. I should go to bed. – Dietrich Epp Aug 07 '20 at 02:45