Files
klibc/string.asm

161 lines
2.6 KiB
NASM

section .text
global strlen
global strcpy
global strlcpy
global strcat
global strcmp
global strclr
global strlclr
;----- strlen(char* str) -----;
; return value: amount of characters before EOS was found
strlen:
push rbp
mov rbp, rsp
xor rax, rax
.findEOS:
cmp byte [rdi+rax], 0x0
je .quit
inc rax
jmp .findEOS
.quit:
leave
ret
;----- strcpy(char* dest, char* src) -----;
; return value: pointer to dest or NULL if nothing was copied (note that EOS is always copied to dest)
strcpy:
push rbp
mov rbp, rsp
mov r11, rdi
xor rax, rax
xor rcx, rcx
.loop:
cmp byte [rsi], 0x0
je .0f
mov r10b, byte [rsi]
mov byte [r11], r10b
inc rsi
inc r11
inc rcx
jmp .loop
.0f:
mov byte [r11], 0x0
cmp rcx, 0
je .quit
mov rax, rdi
.quit:
leave
ret
;----- strlcpy(char* dest, char* src, int size) -----;
; return value: Length of src
strlcpy:
push rbp
mov rbp, rsp
mov r9, rsi
test rdx, rdx
jz .quit
js .quit
dec rdx
.loop:
cmp byte [rsi], 0x0
je .0f
mov r10b, byte [rsi]
mov byte [rdi], r10b
inc rsi
inc rdi
dec rdx
cmp rdx, 0x0
ja .loop
.0f:
mov byte [rdi], 0x0
.quit:
mov rdi, r9
call strlen
leave
ret
;----- strcat(char* dest, char* src) -----;
; return value: pointer to dest
strcat:
push rbp
mov rbp, rsp
mov r8, rdi
call strlen
add rdi, rax
call strcpy
mov rax, r8
leave
ret
;----- strcmp(char* str1, char* str2) -----;
; return value: 0 if both strings are the same, otherwise index in array str1 where strings are to become different
; returns -1 if str2 is longer than str1 and no difference was found before that happens
; TODO: FIX length 13 for TEST strcmp(strBuff1, str1) (see tests.asm, test 1)
strcmp:
push rbp
mov rbp, rsp
call strlen
mov rcx, rax
mov rax, -1
.compareLoop:
inc rax
cmp byte [rdi+rax], 0x0
je .eosFound
mov r10b, byte [rsi+rax]
cmp byte [rdi+rax], r10b
je .compareLoop
jmp .quit
.eosFound:
mov r10, rax
mov rdi, rsi
call strlen
cmp rax, r10
jle .quit
mov rax, -1
.quit:
leave
ret
;----- strclr(char* str) -----;
; Replaces all characters of a string with \0 untill EOS is found
; returns amount of changed characters
strclr:
push rbp
mov rbp, rsp
call strlen
mov rcx, rax
mov rdx, rax
xor rax, rax
cld
rep stosb
mov rax, rdx
leave
ret
;----- strlclr(char* str, int size) -----;
; Replaces characters of a string with \0, using arg size
; <!> DANGEROUS FUNCTION, it might exceed string boundaries if used incorrectly. Use strclr() instead!
; Function has no return value, rax will be 0 (0x0 stored in rax for opcode stosb)
strlclr:
push rbp
mov rbp, rsp
mov rcx, rsi
xor rax, rax
cld
rep stosb
leave
ret