Difference between revisions of "CSC231 No-no! and Be-Careful! situations"
(→Helpful Trick) |
(→What's wrong with the following code?) |
||
Line 4: | Line 4: | ||
=What's wrong with the following code?= | =What's wrong with the following code?= | ||
− | < | + | <source lang="asm"> |
; this function will compute N results and store them in the stack... | ; this function will compute N results and store them in the stack... | ||
Line 22: | Line 22: | ||
ret | ret | ||
− | </ | + | </source> |
=What's tricky about the following code?= | =What's tricky about the following code?= |
Revision as of 07:22, 30 October 2014
--D. Thiebaut 13:15, 10 November 2010 (UTC)
What's wrong with the following code?
; this function will compute N results and store them in the stack...
compute:
pushad
mov ecx, N ;loop some number of times
mov eax, data1 ;get some data
mov ebx, data2
.for: call doSomething ;operate on eax and ebx
; on return, eax contains
; result we're interested in
push eax ;save result in stack
loop .for
;;; we're done
popad
ret
What's tricky about the following code?
compute:
pushad
push ebp
mov ebp, esp
;;; get parameters from the stack
mov ecx,[ebp+XX] ;XX is some offset
mov eax,[ebp+YY] ;YY is some offset
mov ebx,[ebp+ZZ] ;ZZ is some offset
.for: call doSomething ;operate on eax and ebx
; on return, eax contains
; result we're interested in
loop .for
;;; we're done
pop ebp
popad
ret 3*4
Helpful Trick
- We can use the %define directive to assign names to our parameters living in the stack.
- More information on %define: Nasm Preprocessor
- Example:
;;; -------------------------------------------------------------- ;;; openFile( filename, handle ) ;;; opens a file for reading, puts handle in dword whose address ;;; is passed in stack. ;;; Does not modify the registers, but modifies flags. openFile: push ebp mov ebp, esp pushad %define of_fileName dword[ebp+12] %define of_handle dword[ebp+8] mov eax,SYS_OPEN mov ebx, of_fileName mov ecx, O_RDONLY mov edx, S_IRUSR|S_IWUSR|S_IXUSR int 0x80 test eax,eax jns .fileOk print2 "Error opening file" mov eax, SYS_EXIT mov ebx, 1 int 0x80 .fileOk: mov ebx, of_handle mov [ebx], eax ; save handle clc ; clear carry if ok .done: popad ; restore registers pop ebp ret 8