CSC231 Homework 5 2014
--D. Thiebaut (talk) 07:30, 29 October 2014 (EDT)
Preparation
The two programs below illustrate how you would put a function, f(), in a separate file, and call it from a main() program kept in another file.
The specific details that are important and that make the system work:
- there is only one global _start label, and it is in main. The linker (ld) will complain if there are more than one _start label, as it is where Linux will start running your program.
- The label f in f.asm must be global, so that example.asm can access it.
- The label f in example.asm must be extern, so that nasm will not complain that it is not finding the label f used in the call instruction.
- Both example.asm and f.asm should be assembled separately, and linked together with the 231Lib library.
Example.asm
;;; ; example.asm ;;; ; D. Thiebaut ;;; ; ;;; ; A simple program to demonstrate how to link a main ;;; ; program and an extern function. ;;; ; ;;; ; to assemble and run: ;;; ; ;;; ; nasm -f elf -F stabs example.asm ;;; ; nasm -f elf -F stabs f.asm ;;; ; ld -melf_i3896 -o example example.o f.o 231Lib.o ;;; ; ./example ;;; ; ------------------------------------------------------------------- ;;; ------------------------------------------------------------ ;;; data areas ;;; ------------------------------------------------------------ section .data a dd 100 b dd 200 c dd 300 result dd 0 ;;; ------------------------------------------------------------ ;;; code area ;;; ------------------------------------------------------------ section .text global _start extern _printDec extern _println extern f _start: ;;; compute f( a ) = 2*a push dword[a] call f call _printDec call _println ;;; compute f( 3 ) = 2*3 = 6 push dword 3 call f call _printDec call _println ;;; compute f( b + f (c) + 1 ) push dword[c] call f inc eax add eax, dword[b] push eax call f call _printDec call _println ;;; exit() mov eax,1 mov ebx,0 int 0x80 ; final system call
f.asm
;;; ; f.asm
;;; ; D. Thiebaut
;;; ; A simple program with one global function that computes
;;; ; f(a) = 2*a
;;; ;
;;; ; -----------------------------------------------------------
section .text
global f
;;; ;------------------------------------------------------------
;;; ; f(x): a function that receives a parameter through
;;; ; the stack and that computes y = 2*x
;;; ; x is at [ebp+8]
;;; ; returns the result in eax.
;;; ; does not modify any of the other registers (besides eax)
;;; ;------------------------------------------------------------
f: push ebp
mov ebp, esp
mov eax, dword[ebp+8]
add eax, eax
pop ebp
ret
Assembly/Link Steps
nasm -f elf example.asm nasm -f elf f.asm nasm -f efl 231Lib.asm ld -melf_i386 example.o f.o 231Lib.o -o example
Output
200 6 1602