fork download
  1. ; Simon Whitehead
  2.  
  3. section .data
  4.  
  5. newline db 10
  6.  
  7. number dd 123456789 ; The number to print
  8.  
  9. ; Syscall information
  10. sys_exit equ 1
  11. sys_write equ 4
  12.  
  13. ; Streams
  14. stdout equ 1
  15.  
  16. ; Constants
  17. BUFFER_SIZE equ 10
  18.  
  19. section .bss
  20.  
  21. numbuf resb BUFFER_SIZE ; A buffer to store our string of numbers in
  22.  
  23. section .text
  24.  
  25. global _start
  26.  
  27. _start:
  28.  
  29. mov rdi,[number] ; Move the number (123456789) into rax
  30. call itoa ; call the function
  31.  
  32. ; Write the string returned in rax out to stdout
  33. mov rdi,rax ; The string pointer is returned in rax - move it to rdi for the function call
  34. mov rsi,rcx
  35. call print
  36.  
  37. ; Write the newline character to stdout
  38. mov rdi,newline
  39. mov rsi,1
  40. call print
  41.  
  42. ; Exit
  43. mov rax,sys_exit
  44. mov rbx,0
  45.  
  46. int 0x80
  47.  
  48. ; Args: (rdi: char*, rsi: int)
  49. print:
  50.  
  51. mov rax,sys_write
  52. mov rbx,stdout
  53. mov rcx,rdi
  54. mov rdx,rsi
  55.  
  56. int 0x80
  57.  
  58. ret
  59.  
  60.  
  61. push rbp
  62. mov rbp,rsp
  63. sub rsp,4 ; allocate 4 bytes for our local string length counter
  64.  
  65. mov rax,rdi ; Move the passed in argument to rax
  66. lea rdi,[numbuf+10] ; load the end address of the buffer (past the very end)
  67. mov rcx,10 ; divisor
  68. mov [rbp-4],dword 0 ; rbp-4 will contain 4 bytes representing the length of the string - start at zero
  69.  
  70. .divloop:
  71. xor rdx,rdx ; Zero out rdx (where our remainder goes after idiv)
  72. idiv rcx ; divide rax (the number) by 10 (the remainder is placed in rdx)
  73. add rdx,0x30 ; add 0x30 to the remainder so we get the correct ASCII value
  74. dec rdi ; move the pointer backwards in the buffer
  75. mov byte [rdi],dl ; move the character into the buffer
  76. inc dword [rbp-4] ; increase the length
  77.  
  78. cmp rax,0 ; was the quotient zero?
  79. jnz .divloop ; no it wasn't, keep looping
  80.  
  81. mov rax,rdi ; rdi now points to the beginning of the string - move it into rax
  82. mov rcx,[rbp-4] ; rbp-4 contains the length - move it into rcx
  83.  
  84. leave ; clean up our stack
  85. ret
  86.  
Success #stdin #stdout 0s 156KB
stdin
Standard input is empty
stdout
123456789