tl;dr I am getting a few different errors depending on how I try to call a C _print
function from x86-64 assembly. I would like to get it printing by calling the C function, so I know I can call C functions, but I'm not sure how to do "stack alignment" to make that happen properly. The full source code for the system is included.
I tried following these instructions but I am getting this:
Segmentation fault: 11
My assembly looks like this:
section .text
global start
extern _print
start:
mov rdi, msg
jmp _print
section .data
msg: db 0xa, " Hello StackOverflow!!!", 0xa, 0xa, 0
.len: equ $ - msg
My print.c
function is like this:
#import <stdio.h>
extern
void
print(char *str) {
puts("FOO");
puts(str);
}
I am able to use the print
function in C directly, so I know that works. So I should see FOO
in the output but I just see something like this followed by an error:
Hello StackOverflow!!@���
I compiled the C project like this:
print:
@clang -I . -dynamiclib \
-O2 \
-undefined dynamic_lookup \
-o print.dylib print.c
.PHONY: print
And I compiled the asm project like this:
asm:
@nasm -f macho64 main.asm
@ld -macosx_version_min 10.13.0 \
-lSystem -o main \
-install_name print.dylib \
main.o print.dylib
@./main
.PHONY: asm
- Call C/C++ function from assembly (OSX Mavericks x64)
- How to print argv[0] in NASM?
- x86 Assembly on a Mac
- Why does the Mac ABI require 16-byte stack alignment for x86-32?
- http://www.idryman.org/blog/2014/12/02/writing-64-bit-assembly-on-mac-os-x/
- http://nicolascormier.com/documentation/macosx-programming/MachORuntime.pdf
- http://math-atlas.sourceforge.net/devel/assembly/MachORuntime.pdf
- http://cs.lmu.edu/~ray/notes/nasmtutorial/
- https://github.com/hjl-tools/x86-psABI/wiki/X86-psABI
I don't understand how to apply this stack frame / alignment concept to the 64-bit architecture.
Tinkering around and I tried changing start
to this. I have no idea why (don't understand how to apply the stack alignment):
start:
push rbx
mov rdi, msg
call _print
pop rbx
It ends up outputting this:
Hello StackOverflow!!@���make: *** [asm] Error 109
Still no FOO
from the print as well.