Files
klibc/string.asm
2025-06-23 17:46:42 +02:00

97 lines
1.5 KiB
NASM

section .text
global strlen
global strcpy
global strcat
global strcmp
;----- 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
;----- strcat(char* dest, char* src) -----;
; return value: pointer to dest
strcat:
push rbp
mov rbp, rsp
push rdi
sub rsp, 8
call strlen
add rdi, rax
call strcpy
add rsp, 8
pop rax
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
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