1

I have a NASM file and a C file. My OS is Ubuntu 17.04 64 bit

I have followed the instruction from another post. Linking C with NASM

Here's my code

main.c:

#include <stdio.h>

int doit(int a, int b);

int main()
{
  printf("%d\n", doit(2,4));
  return 0;
}

doit.asm:

global doit

section .data

section .text

doit:

    xor   rax, rax          ;sets rax to 0

    mov   eax, [rsp+8]      ;sets **b** to eax(32bit = int size)
    add   eax, [rsp+16]     ;adds **a** to eax(32bit = int size)

    ret

compiling:

 home@main:~/Desktop/TEST$ nasm -f elf64 doit.asm && gcc -Wall main.c doit.o
 home@main:~/Desktop/TEST$ ./a.out 318503633
 home@main:~/Desktop/TEST$

As you can see, The result is not even close to the predicted result, which is 6

Please tell me why is the result different from the 32bit asm

Michael Petch
  • 46,082
  • 8
  • 107
  • 198
I I
  • 15
  • 4
  • The issue is calling convention. The System V 64-bit ABI can be [found here](https://github.com/hjl-tools/x86-psABI/wiki/x86-64-psABI-r252.pdf) . Parameter Passing is covered in _Section 3.4.3_. First 6 integer class parameters are passed in via the registers _RDI_,_RSI_,_RDX_,_RCX_,_R9_, and _R8_ in that order. Integer class results are returned in _RAX_. Figure 3.4 also shows which registers need to be preserved by a function. To add 2 parameters would be as easy as `add rsi, rdi` `mov rax, rsi` `ret` . A trick to add 2 registers and save to third would be `lea rax, [rdi+rsi]` – Michael Petch Dec 03 '16 at 16:57

1 Answers1

0

It's quite simple, you're using different calling conventions On x64 parameters are passed by registers Hence your assembly code is looking for a, b parameters on the stack (using esp) on 32 bit you'd be passing a, b over the stack In order to solve this either study the calling convention used on x64 and learn which registers are used to pass the parameters and how to determine that within your C code Use objdump -d and study the disassembly of that code to understand what's actually opening Or compile with gcc -m32 and force the compiler to use the proprietary calling convention (on stack)

DrPrItay
  • 793
  • 6
  • 20
  • The 32-bit x86 System V ABI is not "proprietary". I assume that's bad autocorrect or something, since the lack of paragraphs and punctuation make me think you wrote this on a phone. – Peter Cordes Dec 03 '16 at 20:16
  • yeah I'm not available on my pc right now, I'll gladly fix this when it is possible – DrPrItay Dec 04 '16 at 11:38