Skip to content

Instantly share code, notes, and snippets.

@Kafva
Created May 11, 2019 14:22
Show Gist options
  • Save Kafva/ace1b0d176cb54a50623c34d334a2d58 to your computer and use it in GitHub Desktop.
Save Kafva/ace1b0d176cb54a50623c34d334a2d58 to your computer and use it in GitHub Desktop.
Printing the argument vector on x86_64 MAC OS X (Assembly)
// •••••••••••••••••••••
// %bx, %bp and %r12 – %r14 (NEED TO BE PUSHED)
// •••••••••••••••••••••
// Argument parsing : %ri , %si , %dx , %cx , %r8 , %r9
// •••••••••••••••••••••
.extern _puts
.text
.global print_argv
print_argv:
// Save the return address from print_argv in %rax
// and pop/push it throughout the procedure since the stack will be
// continously popped throughout the procedure
popq %rax
POP_Stack:
// The macho64 executable follows a format where the stack is populated
// with several types of system information before the actual argument vector appears.
// One can differentiate the argument vector (and the preceding argc value) from the other data by
// the NULL termination which appears on the stack before it
popq %rsi
// Once the null sign has been encounterd one can begin fetching the actual arguments
cmpq $0, %rsi
jne POP_Stack
// Save the argc value which is actually available directly in %rdi from a call to _main
// (decremented by 1 due to the popping of the executable name) in %r8
popq %rdi
subq $1, %rdi
movq %rdi, %rcx // Initialiase the counter
popq %rdi // POP the executable name
POP_loop:
popq %rdi // POP the stack to aquire the next argument
pushq %rax // PUSH the print_argv return value
pushq %rcx // PUSH the iterator value
call _puts
popq %rcx // POP the iterator value
popq %rax // POP the print_argv return value
loop POP_loop
pushq %rax // PUSH the return value from print_argv back onto the stack
xorq %rax, %rax // Set the return value to zero
ret
.end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment