1

I'm studying NASM on Linux 64-bit and have been trying to implement some examples of code. However I got a problem in the following example. The function donothing is implemented in NASM and is supposed to be called in a program implemented in C:

File main.c:

#include <stdio.h>
#include <stdlib.h>

int donothing(int, int);

int main() {
    printf(" == %d\n", donothing(1, 2));
    return 0;
}

File first.asm

global donothing

section .text
    donothing:
    push rbp
    mov rbp, rsp
    mov eax, [rbp-0x4]
    pop rbp
    ret

What donothing does is nothing more than returning the value of the first parameter. But when donothing is called the value 0 is printed instead of 1. I tried rbp+0x4, but it doesn't work too. I compile the files using the following command:

  nasm -f elf64 first.asm && gcc first.o main.c

Compiling the function 'test' in C by using gcc -s the assembly code generated to get the parameters looks similar to the donothing:

int test(int a, int b) {
    return a > b;
}

Assembly generated by gcc for the function 'test' above:

test:
.LFB0:
    .cfi_startproc
    pushq   %rbp
    .cfi_def_cfa_offset 16
    .cfi_offset 6, -16
    movq    %rsp, %rbp
    .cfi_def_cfa_register 6
    movl    %edi, -4(%rbp)
    movl    %esi, -8(%rbp)
    movl    -4(%rbp), %eax
    cmpl    -8(%rbp), %eax
    setg    %al
    movzbl  %al, %eax
    popq    %rbp
    .cfi_def_cfa 7, 8
    ret
    .cfi_endproc

So, what's wrong with donothing?

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
user12707
  • 294
  • 1
  • 5
  • 12
  • More generic what are the calling conventions question: http://stackoverflow.com/questions/8691792/how-to-write-assembly-language-hello-world-program-for-64-bit-mac-os-x-using-pri?lq=1 – Ciro Santilli OurBigBook.com Jul 08 '15 at 15:17

1 Answers1

4

In x86-64 calling conventions the first few parameters are passed in registers rather than on the stack. In your case you should find the 1 and 2 in RDI and RSI.

As you can see in the compiled C code, it takes a from edi and b from esi (although it goes through an unnecessary intermediate step by placing them in memory)

Michael
  • 57,169
  • 9
  • 80
  • 125