CSC231 SumProc3.asm

From dftwiki3
Jump to: navigation, search

Back to Class Page


;;; sumproc3.asm
;;; D. Thiebaut CSC231
;;; third 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. the
;;; sum is passed back in the stack.


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 end up

	;; -------------------------
	;; code area
	;; -------------------------

	section	.text
	global	_start

_start:
	push	eax		; make room in the stack for result
	push	dword [a]	; pass copy of a
	push	dword [b]	; pass copy of b
	call	sum		
	pop	dword [result]	; get sum from stack and restore stack
	;; exit()

	mov	eax,SYS_EXIT
	mov	ebx,0
	int	0x80		; final system call

;;; -------------------------------------------------------
;;; sum function
;;; gets 2 dwords from stack and puts sum in stack for main
;;; program to receive.
;;; registers modified:	 eax
;;; 
;;; stack looks like this after first 2 instructions:
;;;
;;;         +----------+
;;;         | "empty"  | <-- ebp+16
;;;         +----------+
;;;         |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] ; get copy of a
	mov	dword[ebp+16],eax  ; put sum in reserved space in stack
	
	pop	ebp
	ret	8		   ; we get rid of 2 dwords in stack and
				   ; keep one for main program to get sum