So I'm learning x86 Assembly with NASM and I'm trying to make a simple function that prints out integers. My Code...
print_integer: ; Integer input stored in eax
mov ecx, 10
print_integer_loop:
mov edx, 0
div ecx ; eax /= 10 | edx = eax % 10
or edx, 0x30 ; Convert 0-9 to ‘0’-‘9’
push edx ; Push remaineder to stack
mov eax, 4 ; sys_write
mov ebx, 1 ; STDOUT
mov ecx, esp ; Top of Stack to ecx
mov edx, 1 ; Print 1 byte
int 0x80 ; syscall
pop edx
cmp eax, 0 ; Compare quotient to 0
jnz print_integer_loop
_main:
mov eax, 4251
call print_integer
mov eax, 1 ; ‘Exit’ System call
mov ebx, 0 ; Exit with error code 0
int 0x80 ; syscall
When I run this code nothing happens. It just ends without printing anything. I've looked over all the similar topics and none I've found have been helpful. I'm not sure what is going wrong so any insight would be great.
EDIT: I updated NASM to a more recent version so I could use x86_64 syscall. Code is below
print_integer: ; Assume integers is in r15
push 0x0a ; Push endline character
mov r14, 1 ; Setup counter for printing
stack_loop:
mov rax, r15 ; Move r15 to rax for divison
xor rdx, rdx ; Avoids error
mov rcx, 10
div rcx ; rax = rdx:rax / rcx | rdx = rdx:rax % rcx
add rdx, '0' ; Convert 0-9 to ‘0’-‘9’
push rdx ; Push remainder to stack
mov r15, rax ; Move quotient to r15 register
inc r14 ; Counter + 1
cmp r15, 0 ; Compare quotient to 0
jne stack_loop ; If not zero, loop
; Characters are now on stack in reverse order
print_loop:
mov rsi, rsp ; Put remainder in rsi
mov rdx, 1 ; Print 1 char (length)
mov rax, 0x2000004 ; System call write
mov rdi, 1 ; Standard output, number of bytes
syscall ; Invoke kernal
dec r14 ; Counter - 1
pop r15 ; Remove off top of stack
cmp r14, 0
jne print_loop
ret
Hopefully this helps someone in the future. This may not be the best way to do it but it is a way.