3

I try to implement the C sqrt function in Nasm elf64, it works correctly without argument (with the value of "a" define in the function), but when I try to pass an argument to this function ,the code return an error "Stopped reason: SIGFPE".

Here's my code

The c function

int le_sqrt(int a) {
   int n=1;
   int number = a;
   for (int i=0; i<10; i++) {
       n=(n+number/n)/2;  
   }
   return n; 
}

The nasm program

bits 64
global _start
extern le_sqrt 

_start:
    mov rbp,9 ;argument 
    push rbp ;same argument push
    call le_sqrt ; my c function

    mov rax,60 ;exit program
    mov rsi,0
    syscall
BerretMan
  • 95
  • 6
  • 2
    It seems that you are using the wrong calling convention. Which OS and which command line instruction do you use to compile the C program? See here for a list of calling conventions on amd64: https://en.wikipedia.org/wiki/X86_calling_conventions#List_of_x86_calling_conventions – Kolodez Jun 19 '22 at 06:44
  • I used ubuntu wsl 64 bits. For compiling, I compile my c function in .o and my nasm elf64 in .o, then y mixed the twiced. gcc -c sqrt.c -o sqrt.o | nasm -f elf64 test.asm -o test.o | ld -o app sqrt.o test.o – BerretMan Jun 19 '22 at 06:46
  • If an answer solved your problem, please accept it. – Kolodez Jun 19 '22 at 07:32

2 Answers2

3

If you want to call le_sqrt(9) with System V AMD64 ABI calling convention, do this:

_start:
    mov rdi,9
    call le_sqrt
Kolodez
  • 553
  • 2
  • 9
1

SIGFPE usually happens when you divide a number by 0. In your assembly program, you are using mov rbp, 9 for passing an argument to c function, which might be wrong in your case. It becomes obvious since you're getting SIGFPE. See Microsoft calling conventions and System V ABI calling conventions (for 64-bit). For 32-bit, follow these calling conventions.

L_R
  • 170
  • 11