Skip to content

Instantly share code, notes, and snippets.

@wolfiestyle
Created March 19, 2013 22:06
Show Gist options
  • Select an option

  • Save wolfiestyle/5200575 to your computer and use it in GitHub Desktop.

Select an option

Save wolfiestyle/5200575 to your computer and use it in GitHub Desktop.
example asm code with function call
; example ASM code
; compile with 'nasm -f elf test.asm && gcc -m32 -o test test.o'
bits 32 ; use 32 bit architecture
global main ; declare 'main' funcion (called by the OS)
extern printf ; 'printf' from libc
; read-only variables
section .data
strDesu db "desu desu purrRRrRr %d", 10, 0 ; string, must end with 0, the 10 is "\n"
strRet db "function returned %d", 10, 0
; uninitialized variables (writeable)
section .bss
var resd 1 ; d -> 4 bytes
; program code
section .text
main:
; var = 33
mov dword [var], 33
; calculate the answer
add dword [var], 9
; call the function
push dword [var]
call testfunc
add esp, 4*1 ; pop without writing to a register
; (now eax holds the return value)
; printf(strRet, <return value of testfunc>)
push eax ; second param
push dword strRet ; first param
call printf
add esp, 4*2 ; remove args from stack, equivalent to 'pop' twice
; return exit status 0
xor eax, eax ; eax = 0
ret ; returning from main ends the program
testfunc:
; initialize stack frame
push ebp
mov ebp, esp
; printf(strDesu, <argument>)
push dword [ebp+8] ; second arg, take from value passed to function
push dword strDesu ; first arg
call printf
add esp, 4*2 ; remove args from stack, equivalent to 'pop' twice
; return constant 3
mov eax, 3 ; by convention eax holds the return value
leave ; cleanup stack frame
ret ; return to caller
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment