I have a simple program in x86 asm, which makes z = x/y. The thing is, the code should be written correctly when it comes to division, but nothing is printed. There is no output. I have no idea what's wrong, because I can't debug when the program doesn't use eax, ebx etc.
global main
extern printf
section .text
main:
finit
fild dword[x]
fild dword[y]
fdiv
fist dword[z]
push dword[z]
push frm
call printf
add esp,8
mov ebx,0
mov eax,1
int 0x80
section .data
x: dd 1.2
y: dd 3.14
z: dd 0.0
frm: dd '%lf',10,0
1) The C library - I guess you use the one from GCC - doesn't output the result of printf immediately. Rather, it is stored in a separate memory called cache and outputted by chance. In this case the program will be ended by int 0x80/eax=1 faster than the cache will be flushed. You can insert a manual flush:
...
extern fflush
...
push 0
call fflush
add esp, 4
...
The best solution is to use the C exit function. Replace
mov ebx,0
mov eax,1
int 0x80
by
push 0
call exit
2) printf with format %lf needs a double floating point number (8 bytes = QWORD) as input. So change the code:
...
fstp qword[z]
...
push dword[z+4]
push dword[z]
push frm
call printf
add esp,12
...
z: dq 0.0
3) NASM will interpret and convert 1.2 and 3.14 as floating point number. Defined as dd it will be stored as single floating point number. However, fild expects and loads an integer number. Let it load as single:
fld dword[x]
fld dword[y]
The whole bunch:
global main
extern printf, fflush, exit
section .text
main:
finit
fld dword[x]
fld dword[y]
fdiv
fstp qword[z]
push dword[z+4]
push dword[z]
push frm
call printf
add esp,12
push 0
call fflush
add esp, 4
push 0
call exit
section .data
x: dd 1.2
y: dd 3.14
z: dq 0.0
frm: dd '%lf',10,0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With