strcmp.asm 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. section .bss
  2. teststr resb 32
  3. mystr resb 42
  4. buf resq 1
  5. section .text
  6. global _start
  7. _start:
  8. ;; setup test string
  9. mov byte [teststr+0],'T'
  10. mov byte [teststr+1],'e'
  11. mov byte [teststr+2],'s'
  12. mov byte [teststr+3],'t'
  13. mov byte [teststr+4],'S'
  14. mov byte [teststr+5],'T'
  15. mov byte [teststr+6],'r'
  16. ;; read string in
  17. mov rax,mystr
  18. call getstr
  19. ;; print it out for debugging
  20. mov rax,1
  21. mov rdi,1
  22. mov rsi,mystr
  23. mov rdx,42
  24. syscall
  25. ;; check if its equal to test string
  26. mov rcx,teststr
  27. mov rdx,mystr
  28. call strcmp
  29. ;; exit with return code
  30. mov rdi,rax
  31. mov rax,60
  32. syscall
  33. getstr:
  34. mov rbx,rax
  35. .loop:
  36. call getchar
  37. cmp rax, -1 ; check for terminator
  38. je .done
  39. mov byte [rbx],al
  40. add rbx, 1 ; number of chars read
  41. jmp .loop
  42. .done:
  43. mov byte [rbx], 0 ; write null byte at end
  44. ret
  45. getchar:
  46. mov rax,0x00
  47. mov rdi,0 ;stdin fd
  48. lea rsi,[buf]
  49. mov rdx,1 ;count
  50. syscall
  51. cmp rax,1
  52. jne .getchar_fail
  53. mov rax,0
  54. mov al,[buf]
  55. ret
  56. .getchar_fail:
  57. mov rax,-1
  58. ret
  59. putchar:
  60. mov [buf],al
  61. mov rax,0x01
  62. mov rdi,1 ;stdout fd
  63. lea rsi,[buf]
  64. mov rdx,1
  65. syscall
  66. ret
  67. strcmp:
  68. ;; inputs
  69. ;; - rcx: pointer to string 1
  70. ;; - rdx: pointer to string 2
  71. ;; outputs
  72. ;; - rax: 0 if equal, 1 if different
  73. .loop:
  74. mov al,[rcx]
  75. mov bl,[rdx]
  76. ;; if they are both zero, return equal
  77. ;; if one of them is zero, return not equal
  78. ;; otherwise compare the chars and continue
  79. cmp al,0
  80. je .al.eq
  81. ;; al != 0
  82. cmp bl,0
  83. je .bl.eq.2
  84. ;; al != 0, bl != 0
  85. cmp al,bl
  86. jne .bl.eq.2
  87. inc rcx
  88. inc rdx
  89. jmp .loop
  90. .al.eq:
  91. ;; al == 0
  92. cmp bl,0
  93. je .bl.eq.1
  94. ;; al == 0, bl != 0
  95. mov rax, 1
  96. ret
  97. .bl.eq.1:
  98. ;; al == 0, bl == 0
  99. mov rax, 0
  100. ret
  101. .bl.eq.2:
  102. ;; al != 0, bl == 0
  103. ;; (or) al != bl
  104. mov rax, 1
  105. ret