Advertisement
drankinatty

Assembly (NASM) Read/Write String

Oct 4th, 2019
337
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. section .data
  2.         text1 db "What is your name? "
  3.         t1len equ $ - text1 ; save length of text1
  4.         text2 db "Hello, "
  5.         t2len equ $ - text2 ; save length of text2
  6.  
  7. ;reserved data for the username
  8. section .bss
  9.         name resb 32            ; Don't SKIMP on Buffer Size! 4-not enough!
  10.  
  11. section .text
  12.         global _start
  13. _start:
  14.         call _printText1
  15.         call _getName
  16.         call _printText2
  17.         mov     rdi, name       ; load name in rdi
  18.         call    _strprn         ; print it!
  19.  
  20.         mov rax, 60
  21.         mov rdi, 0
  22.         syscall
  23.  
  24. ;input Subroutines
  25. _getName:
  26.         xor     rax, rax        ; zero rax
  27.         xor     rdi, rdi        ; zero rdi
  28.  
  29.         mov     rsi, name       ; load rsi with name
  30.         xor     rdx, rdx        ; zero rdx
  31.         add     rdx, 32         ; put length in rdx
  32.         syscall
  33.         ret
  34.  
  35. ;prints the text to the screen
  36. _printText1:
  37.         mov rax, 1
  38.         mov rdi, 1
  39.         mov rsi, text1
  40.         mov     rdx, t1len      ; use declared length
  41.         syscall
  42.         ret
  43.  
  44. _printText2:
  45.         mov rax, 1
  46.         mov rdi, 1
  47.         mov rsi, text2
  48.         mov     rdx, t2len      ; use declared length
  49.         syscall
  50.         ret
  51.  
  52. ; load string in rdi before call
  53. _strprn:
  54.         push    rdi             ; push string address onto stack
  55.         call    _strlen         ; call strsz to get length
  56.         pop     rsi             ; pop string to rsi (source index)
  57.         mov     rax, 0x1        ; put write/stdout number in rax (both 1)
  58.         mov     rdi,rax         ; set destination index to rax (stdout)
  59.         syscall                 ; call kernel
  60.         ret
  61.  
  62. ;adds the additional code form the site
  63. _strlen: ; NOTE: RDI IS THE DEFAULT SRC FOR SCASB
  64.         xor     rcx, rcx        ; zero rcx
  65.         not     rcx             ; set rcx = -1 (uses bitwise id: ~x = -x-1)
  66.         xor     eax, eax        ; zero the al register (initialize to NUL)
  67.         cld                     ; clear the direction flag
  68.         repnz scasb             ; get the string length (dec rcx through NUL)
  69.         not     rcx             ; rev all bits of negative -> absolute value
  70.         lea     rdx, [rcx-1]    ; length [rcx-1] into rdx, ready for write
  71.         ret
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement