I am trying to print an integer in 32 bit x86 assembly on macOS High Sierra using this code:
.cstring
STR_D:
.asciz "%d"
.globl _main
_main:
movl $53110, %edi #moves constant int into register
sub $8, %esp #make space on stack
movl %edi, 4(%esp) #move int to stack
movl $STR_D, 0(%esp) #move "%d" to stack
call _printf
add $8, %esp #restore stack pointer
ret
I am compiling using the command
gcc -m32 -Wl,-no_pie -o foo foo.s
and then executing the executable foo. I then get an error saying "Illegal instruction: 4". I am pretty sure the error lies in the instruction moving the string constant to the stack. If I remove that line and the following function call, everything works. What am I doing wrong?
Further information/question: I am doing this as part of a project to write a compiler. When I execute these instructions on Linux (while of course changing platform-specific stuff such as main instead of _main, .data instead of .cstring, etc), it works. Why does macOS not work? Does this have to do with stack alignment?
My compiler version (obtained by gcc -version) is Apple LLVM 9.0.0 (clang-900.0.39.2).