NASM - The Netwide Assembler

NASM Forum => Using NASM => Topic started by: dhazeghi on December 13, 2010, 10:00:34 PM

Title: _ functions in MacOS X
Post by: dhazeghi on December 13, 2010, 10:00:34 PM
Hello all,

I'm trying to move some of my code over from nasm in Linux to MacOS X.  I have a simple mixed C/assembly program.  The problem is that the C version is prepending _ to the symbols, so the link fails.  I can manually fix this by renaming my assembly routines, but this is not ideal.  Here's a simplified testcase which works fine under Linux.  Thanks for any suggestions,

# nasm -f macho test1.asm
# gcc -m32 -c test.c
# gcc -m32 test.o test1.o
Undefined symbols:
  "_asmFunc", referenced from:
      _main in test.o
ld: symbol(s) not found
collect2: ld returned 1 exit status

test.c:
extern int asmFunc(int);

int main(int argc, char *argv[])
{ return asmFunc(1); }

test1.asm:
SECTION .text
global asmFunc

asmFunc:
    mov eax, [ebp + 4]
    ret
Title: Re: _ functions in MacOS X
Post by: Frank Kotler on December 13, 2010, 10:54:29 PM
# nasm -f macho --prefix _ test1.asm

This prepends an underscore to any symbol declared global or extern. Should fix it.

Best,
Frank

Title: Re: _ functions in MacOS X
Post by: dhazeghi on December 14, 2010, 06:28:45 AM
Thanks Frank!  That did the trick.

Now on to figuring out why calls to C functions almost alway (but not always) segfault.  Must be some bizarre alignment convention or something...
Title: Re: _ functions in MacOS X
Post by: Keith Kanios on December 14, 2010, 02:52:09 PM
The Mac OS X ABI for IA-32 (http://developer.apple.com/library/mac/#documentation/DeveloperTools/Conceptual/LowLevelABI/130-IA-32_Function_Calling_Conventions/IA32.html#//apple_ref/doc/uid/TP40002492-SW4) explains everything.
Title: Re: _ functions in MacOS X
Post by: dhazeghi on December 15, 2010, 08:29:05 AM
Yes, thanks for the ABI doc.  Looks like it was the 16-byte alignment rule that was throwing me off, particularly because of the extra 4-bytes that the call instruction automatically inserts.

I wasn't able to find a similar ABI doc for x86-64 OS X, but I assume it must not be too different from the Linux one.
Title: Re: _ functions in MacOS X
Post by: Keith Kanios on December 15, 2010, 04:55:11 PM
Mac OS X ABI (http://lmgtfy.com/?q=mac+os+x+abi).