I am new to assembly i want to write a function to print number in assembly and call it from c++ see code below
cpp:
#include <iostream>
#include <stdint.h>
extern "C" void printunum(uint64_t);
int main()
{
printunum(12345);
std::cout<<std::endl;
return 0;
}
assembly:
global printunum
section .text
printunum:
mov rax,rdi
mov rdi,10
mov rsi,0
while1:
cmp rax,0
je endwhile1
mov rdx,0
div rdi
inc rsi
add rdx,48
push rdx
jmp while1
endwhile1:
mov r10,rsi
while2:
cmp r10,0
je endwhile2
mov rax,1
mov rdi,1
mov rsi,rsp ;to pass memory address
add rsp,8 ;it is equal to pop or it is wrong and it will add 8 bytes here?
mov rdx,1
syscall
dec r10
jmp while2
endwhile2:
ret
Edited assembly:
global print_uint64
section .text
print_uint64:
;init
mov rax,rdi
mov rdi,10
mov rsi,rsp
;endinit
while:
xor rdx ,rdx
div rdi
add rdx ,48
dec rsi
mov [rsi],dl
cmp rax ,0
je else
if:
jmp while
else:
endwhile:
;print
mov rax,1
mov rdi,1
mov rdx,rsp
sub rdx,rsi
syscall
;endprint
;return
mov rax,rsp
sub rax,rsi
ret
i compiled by:
srilakshmikanthanp@HP-245-G5-NOTEBOOK-PC:~/Documents/Learn$ nasm -f elf64 asm.asm
srilakshmikanthanp@HP-245-G5-NOTEBOOK-PC:~/Documents/Learn$ g++ main.cpp asm.o -o main
srilakshmikanthanp@HP-245-G5-NOTEBOOK-PC:~/Documents/Learn$ ./main
12345
srilakshmikanthanp@HP-245-G5-NOTEBOOK-PC:~/Documents/Learn$
My processer amd64(x86-x64) and i am using kali linux
1)The above code is fine or it is wrong (pop is equal to rsp+8 in x64 bit machine).
2)mul operation puts result into rdx:rax how can i take it into single memory
3)div operation takes dividend from rdx:rax how can i put single value in to rdx:rax. Thanks for your response.