1. Introduction
As now I'm getting into calculator programming, I wish I could have a cross assembler on desktop computer so I can write programs for them.
I though once that macro assemblers on modern computers are all dead. It is proved that I was wrong, by presenting Flat Assembler G. This is a macro assembler down to the level of available instructions and output formats.
Note that fasmg
itself is
implemented in x86 assembly, that doesn't mean it will expire soon
as Apple has moved a step forward to ARM, as there is still x86
emulation with macOS, and since fasmg
only used a small subset of x86 writing a emulator is not a
difficult task, besides the community of fasmg
is also thriving.
2. Hello in Mach-O
There are not as much x86 assembly programming tutorial for OS X
compared to Linux or even Windows. Most of the existing tutorials
are dated, using the nasm
instead of
the default available gas
, and they
didn't even bother to explain the differences in system call and
Mach-O format.
So, this is an example of the standard "Hail the world" for 64bit macOS.
|include 'selfhost.inc'
||
format MachO64 executable
|entry start
5 ||
interpreter '/usr/lib/dyld'
|uses '/usr/lib/libSystem.B.dylib'
||
import exit,'_exit'
10 ||
segment '__TEXT' readable executable
|section '__text' align 16
|start:
|mov rax,02000004h
15 |mov rdi,1
|mov rsi,message
|mov rdx,14
|syscall
|mov rax,02000001h
20 |xor rdi,rdi
|syscall
|segment '__DATA' readable writable
|section '__data' align 4
|message:
25 |db "Hello, World!", 10
The standard distribution has the selfhost.inc
file that can be almost directly
used for x86_64 macOS assembly programming. It is just the file
path needs to be modified to work properly. The line that has
import
is not used but it is important to have it sit
there to generated the __LINKEDIT
segment otherwise it won't be treated as valid Mach-O executable.
You do can build the __LINKEDIT
segment by self.
System calls has offset 2000000h
,
and 1
exit, 4
is write. They are available from <sys/syscall.h>
if you have installed macOS
SDK.
Directly call fasmg
on the file
will produce the Mach-O binary. Just remember to chmod
it and you are done.