NASM - The Netwide Assembler
NASM Forum => Programming with NASM => Topic started by: saugata bose on January 31, 2013, 05:30:32 PM
-
I am using NASM to do assembly programming. I am in the beginner stage. I am trying to write a program which will take 2 inputs and kept them in 2 variables. My output will show which one is greater. My program is following one:
section .data
msg: db "The value of the variable is: %d",10,0
msg2: db "%d y is greater than %d x",10,0
msg1: db "%d x is greater than %d y",10,0
section .text
global main
extern printf
main:
push ebp
mov ebp,esp
sub esp,10
mov DWORD [ebp-4],0x10
mov eax,DWORD[ebp-4]
mov DWORD [ebp-8],0x11
mov ebx,DWORD[ebp-8]
cmp eax, ebx
jg .xGy
push DWORD [ebp-4] ;for y greater than x
push DWORD [ebp-8]
push msg2
call printf
jmp .done
.xGy: ; x greater than y
push DWORD [ebp-8]
push DWORD [ebp-4]
push msg1
call printf
jmp .done
.done:
mov esp,ebp
pop ebp
ret
In my output .xGy section is alwayes executing whether or not x is greater than y and overpassing the block for y grater than x.
Can u pls tell me the mistake I am doing here.
Thanx in advance
-
Works for me. Try it again...
sub esp,10
I would subtract a multiple of 4, just to keep the stack aligned, but it isn't hurting you. It is "common" to clean up the stack after each C call, but you can "defer" the cleanup - "mov esp, ebp" does it. That works, too. I'm a little confused which is "x" and which is "y"... but your program seems to pick the larger one correctly Ask a HARD one! :)
Best,
Frank
-
We can clean up the code in a few ways. Using EQU or %define to create symbols can clarify your code without adding any additional overhead, so use them as much as possible. Second, as Frank stated, you should clean up the stack after each C function call. Another thing to note (and I think this *might* be what's confusing you) is that the parameters to C functions are pushed onto the stack in reverse order. In other words:
push DWORD [ebp-X]
push DWORD [ebp-Y]
push msg2
call printf
add esp, (3 * DWORD_size)
Is equal to:
printf (msg2, Y, X);
Below is a cleaned up version of your program, I hope some of the things I said here have helped you.
DWORD_size equ 4
section .data
msg: db "The value of the variable is: %d",10,0
msg2: db "%d y is greater than %d x",10,0
msg1: db "%d x is greater than %d y",10,0
section .text
global main
extern printf
main:
X equ 4 ; First DWORD Variable
Y equ 8 ; Second DWORD Variable
push ebp
mov ebp,esp
sub esp,(2 * DWORD_size) ; Allocate 2 DWORDS
mov DWORD [ebp-X],0x10
mov eax,DWORD[ebp-X]
mov DWORD [ebp-Y],0x11
mov ebx,DWORD[ebp-Y]
cmp eax, ebx
jg .xGy
.yGx: ; for y greater than x
push DWORD [ebp-X]
push DWORD [ebp-Y]
push msg2
call printf
add esp, (3 * DWORD_size)
jmp .done
.xGy: ; x greater than y
push DWORD [ebp-Y]
push DWORD [ebp-X]
push msg1
call printf
add esp, (3 * DWORD_size)
jmp .done
.done:
mov esp,ebp
pop ebp
ret