Difference between revisions of "CSC231 SumProc4.asm"
(One intermediate revision by the same user not shown) | |||
Line 2: | Line 2: | ||
---- | ---- | ||
− | < | + | <source lang="asm"> |
;;; sumproc4.asm | ;;; sumproc4.asm | ||
;;; D. Thiebaut CSC231 | ;;; D. Thiebaut CSC231 | ||
Line 18: | Line 18: | ||
− | + | SYS_EXIT equ 1 | |
− | + | SYS_WRITE equ 4 | |
− | + | STDOUT equ 1 | |
;; ------------------------- | ;; ------------------------- | ||
Line 87: | Line 87: | ||
ret 12 ; we can now get rid of 3 dwords in stack | ret 12 ; we can now get rid of 3 dwords in stack | ||
− | </ | + | </source> |
Latest revision as of 08:19, 30 October 2014
Back to Class Page
;;; sumproc4.asm
;;; D. Thiebaut CSC231
;;; fourth of a series of programs illustrating how to pass and receive
;;; information to and from a function in assembly.
;;;
;;; This and all associated programs simply add the contents of
;;; two variables a and b and store the resulting sum in a variable
;;; called result (all are double words)
;;;
;;; this version passes a and b by value through the stack, and
;;; result by reference, so that the function can directly modify
;;; the variable result.
SYS_EXIT equ 1
SYS_WRITE equ 4
STDOUT equ 1
;; -------------------------
;; data segment
;; -------------------------
section .data
a dd 0x1234 ; operand #1
b dd 0x5555 ; operand #2
result dd 0 ; where sum will be stored by function
;; -------------------------
;; code area
;; -------------------------
section .text
global _start
_start:
lea eax,[result]
push eax ; push address of result in stack
push dword [a] ; push copy of variable a
push dword [b] ; push copy of variable b
call sum ; call function which will modify
; variable result directly
;; exit()
mov eax,SYS_EXIT
mov ebx,0
int 0x80 ; final system call
;;; -------------------------------------------------------
;;; sum function
;;; gets 2 dwords from stack and uses address of result to
;;; store sum in it.
;;; registers modified: eax ebx
;;;
;;;
;;; stack looks like this after first 2 instructions:
;;;
;;; +----------+
;;; | &result | <-- ebp+16 (address of result)
;;; +----------+
;;; |copy of a | <-- ebp+12
;;; +----------+
;;; |copy of b | <-- ebp+8
;;; +----------+
;;; |retrn addr| <-- ebp+4 (plus 4 because double words!)
;;; +----------+
;;; |"old" ebp | <-- ebp <-- esp
;;; +----------+
;;; | |
;;; -------------------------------------------------------
sum: push ebp
mov ebp,esp
mov eax,dword [ebp+8] ; get copy of b
add eax,dword [ebp+12] ; add copy of a to it
mov ebx,dword [ebp+16] ; get address of result in ebx
mov dword [ebx],eax ; store sum at that address
pop ebp
ret 12 ; we can now get rid of 3 dwords in stack