4

I'm new to x86 assembly and using NASM in Ubuntu 18.04(64-bit). I tried to access C++ global (count in below code) variable from NASM as below.

C++ code: (stack.cpp)

#include <iostream>

extern "C" {
    int sample_(int a, int b);
    unsigned int count = 200;
}

int main()
{
    int a = 2, b = 3;
    int ret  = sample_(a, b);
    std::cout << ret << std::endl;
    return 0;
 }

NASM code: (test.asm)

extern count
global sample_
    section .text
sample_:
    mov eax,ecx
    add eax,edx
    add eax,[count]
    ret

and I'm compiling it as below.

nasm -felf64 test.asm && g++ stack.cpp test.o && ./a.out

But it doesn't compile and throw an error.

/usr/bin/ld: test.o: relocation R_X86_64_32S against symbol `count' 
can not be used when making a PIE object; recompile with -fPIC

/usr/bin/ld: final link failed: Nonrepresentable section on output
collect2: error: ld returned 1 exit status
Vencat
  • 1,272
  • 11
  • 36
  • What operating system are you programming for? What is your question? – fuz Sep 06 '19 at 10:30
  • 1
    @fuz I'm using Ubuntu 18.04 (64 bit) and my question is "how solve that error and access the c++ global variable from nasm code"?. – Vencat Sep 06 '19 at 10:35
  • 1
    The main problem is that `g++` wants to generate a position-independent binary (PIE) on your system. You can fix this by passing `-no-pie` to `g++` at link time. I can write an answer on how to fix your code so it works with PIE later, but it all boils down to “check what assembly the compiler generates and do the same thing.” – fuz Sep 06 '19 at 10:38
  • Have a look - https://stackoverflow.com/questions/6093547/what-do-r-x86-64-32s-and-r-x86-64-64-relocation-mean – Charlie Sep 06 '19 at 10:44
  • @fuz it works.! but i'm getting wrong result as 363 instead of 205, but this might be my mistake in the code i'll check it out. If you want, post that comment as answer I'll accept it. – Vencat Sep 06 '19 at 10:49
  • 1
    huh, I should have used correct size registers rax,rcx,rdx(64 -bit) instead of eax,ecx,edx (32 - bit). Right now I'm following **Modern X86 Assembly Language Programming: Covers x86 64-bit, AVX, AVX2, and AVX-512** book which teaches x86 assembly using MASM. It would be really appreciated if any of you suggest good book whch follows Linux,nasm and x86-64. – Vencat Sep 06 '19 at 10:59
  • You can use the 32-bit registers, but you should use EDI and ESI instead of ECX and EDX. Take a look here: https://en.wikipedia.org/wiki/X86_calling_conventions#System_V_AMD64_ABI – rkhb Sep 06 '19 at 11:33

0 Answers0