You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

39 lines
1.2 KiB

5 years ago
  1. ; calc_str_len.asm
  2. ; Prints calculates the length of the string "Hello, world!" and prints to stdout
  3. ; Compile with "nasm -f elf64 calc_str_len.asm && ld calc_str_len.o -o calc_str_len"
  4. .text:
  5. global _start
  6. _start:
  7. mov rax, msg ; move msg to rax register
  8. call strlen ; call strlen subroutine
  9. mov rax, 1 ; system call for write
  10. mov rdi, 1 ; file handle for stdout
  11. syscall ; call kernel
  12. mov rax, 60 ; system call for exit
  13. mov rdi, 0 ; exit code
  14. syscall ; call kernel
  15. strlen:
  16. push rax ; push rax to stack
  17. mov rbx, rax ; move rax value (msg variable) to rbx register
  18. calc_str_len:
  19. cmp byte [rax], 0 ; check if the pointer of rax equals 0 (string delimeter)
  20. jz exit_loop ; jump to "exit_loop" if zero flag has been set
  21. inc rax ; increment rax (position along string)
  22. jmp calc_str_len ; jump to start of loop
  23. exit_loop:
  24. sub rax, rbx ; subtract rbx from rax to equal to length of bytes between them
  25. mov rdx, rax ; rax will now equal the length of the string
  26. pop rsi ; pop top value on stack to rsi for printing
  27. ret
  28. .data:
  29. ; initialize doubleword msg variable
  30. msg db 'Hello, world!',0xa,0x0