etopiei's blog

A blog about minimalism, programming, productivity and happiness.
All Posts - RSS Feed

Writing x86 Assembly for macOS - Part 1


This blog post details my beginning to writing x86 assembly for macOS and what I have learnt along the way.
First off you might wonder why I would bother with such a task, and the answer to that has a few parts. Firstly, I really enjoyed doing MIPS in university classes and getting down to a lower level of computing. Secondly, I am interested in learning about reversing, and being able to write assembly should help reading it. Last but not least, why not? I love learning and this is something that is really interesting to me.
I am writing nasm syntax assembly, and I thought I would begin with the traditional hello world.
The first step was setting up the basic sections of the assembly file like so:

Then I had a look here to find the right syscalls to print to std out and exit the program. The table I found was really helpful and also had which arguments went in which registers.
Here it is.
Upon trying this I realised something wasn't working, so I did some research and found out that on macOS, which has an openBSD base, you need to add 2MB to the addresses of all syscalls so I got to this stage:

Now came the scary time, it was time to try and compile.
After some googling around as to the best way to do this I tried to compile with: nasm -f macho64 helloWorld.asm
To my amazement, this actually worked and created a helloWorld.o file. Next it was time to make this file executable, so I headed over to gcc, and tried the following command: gcc -o helloWorld helloWorld.o
However at this point I discovered that I got an error:

At first I was concerned, after a bit more google-fu I realised that I needed to add the -e _start flag to my command. Satisfied I had solved the problem I tried again. And Voila. I was away, with a working hello world in x86_64 assembly.
So what did I learn along the way? I learnt that there are often little things underneath the surface that you are not aware of, and that if you're not careful these can trip you up.
I'm looking forward to continuing my journey into assembly and learning more as I go. There will be more parts to this series coming, so I'll catch you guys in the next one, and I hope you enjoyed this post.

- etopiei (24/10/17)

< Previous Post Next Post >

Post History