Skip to content

Instantly share code, notes, and snippets.

@iwillspeak
Last active Oct 12, 2015
Embed
What would you like to do?
Hello World in Assembly, OS X
/* compile with clang -m32 */
.text
.global _main
_main:
pushl %ebp
movl %esp, %ebp
/* we need to access data relative to the instruction pointer in OS X.
* This register is not readable in 32 bit mode so this trick is needed */
calll next
next:
popl %eax
/* We must also align our stack to a 16 byte boundary before each call.
* We know we are pusing one parameter, and we have pushed the stack
* pointer already so we need to simulate pusing one parameter and the
* final four is made up by the OS when the call is executed. */
subl $4, %esp
/* call the function as before */
leal greeting-next(%eax), %eax
pushl %eax
calll _printf
/* return value to EAX */
movl $0, %eax
/* exit the frame and return */
movl %ebp, %esp
popl %ebp
ret
.data
greeting:
.asciz "hello world\n"
/* set the section to text. Text means read only which is what we want for
* the code */
.text
.globl _main
_main:
/* create a new stack frame */
pushq %rbp
movq %rsp, %rbp
/* we don't have any local variables, but we would allocate stack space
* for them here if we did like this:
* subq $space, %rsp */
/* load a pointer to the string into the index register. This register
* is used as the first parameter to a function in 64 bit mode */
leaq greeting(%rip), %rdi
/* The funciton is variadic, we need to specify the number of floating
* point parameters in the lower byte of the ax register */
xorb %al, %al
/* call the function, return value is in %rax but we ignore */
callq _printf
/* move the return value of main to the return register */
movq $0, %rax
/* exit the stack frame and return from the function */
movq %rbp, %rsp
popq %rbp
ret
/* we could just stick the string in the text segment, but why not! */
.data
greeting:
.asciz "Hello World!\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment