here is the code(exit.s):
.section .data,
.section .text,
.globl _start
_start:
movl $1, %eax
movl $32, %ebx
syscall
when I execute " as exit.s -o exit.o && ld exit.o -o exit -e _start && ./exit"
the return is “Bus error: 10” and the output of “echo $?” is 138
I also tried the example of the correct answer in this question: Process command line in Linux 64 bit
stil get “bus error”…
First, you are using old 32-bit Linux kernel calling convention on Mac OS X – this absolutely doesn’t work.
Second, syscalls in Mac OS X are structured in a different way – they all have a leading class identifier and a syscall number. The class can be Mach, BSD or something else (see here in the XNU source) and is shifted 24 bits to the left. Normal BSD syscalls have class
2and thus begin from0x2000000. Syscalls in class0are invalid.As per §A.2.1 of the SysV AMD64 ABI, also followed by Mac OS X, syscall id (together with its class on XNU!) goes to
%rax(or to%eaxas the high 32 bits are unused on XNU). The fist argument goes in%rdi. Next goes to%rsi. And so on.%rcxis used by the kernel and its value is destroyed and that’s why all functions inlibc.dyldsave it into%r10before making syscalls (similarly to thekernel_trapmacro fromsyscall_sw.h).Third, code sections in Mach-O binaries are called
__textand not.textas in Linux ELF and also reside in the__TEXTsegment, collectively referred as(__TEXT,__text)(nasmautomatically translates.textas appropriate if Mach-O is selected as target object type) – see the Mac OS X ABI Mach-O File Format Reference. Even if you get the assembly instructions right, putting them in the wrong segment/section leads to bus error. You can either use the.section __TEXT,__textdirective (see here for directive syntax) or you can also use the (simpler).textdirective, or you can drop it altogether since it is assumed if no-noption was supplied toas(see the manpage ofas).Fourth, the default entry point for the Mach-O
ldis calledstart(although, as you’ve already figured it out, it can be changed via the-elinker option).Given all the above you should modify your assembler source to read as follows:
Here it is, working as expected: