From b0a3da746ffc66b8edf587f44bfd497229f911ee Mon Sep 17 00:00:00 2001 From: Kwarde Date: Sat, 5 Jul 2025 01:45:58 +0200 Subject: [PATCH] Adds strlen() --- src/core.asm | 5 +++++ src/string.asm | 20 ++++++++++++++++++++ src/tests.asm | 25 +++++++++++++++++++++++++ 3 files changed, 50 insertions(+) diff --git a/src/core.asm b/src/core.asm index a19062f..a4e0a01 100644 --- a/src/core.asm +++ b/src/core.asm @@ -4,6 +4,11 @@ section .text global exit ;----- exit(exit_code) -----; +; Exits the program with given exit code +; Return value: N/A +; Used registers: +; rax* syscall +; rdi (arg) code to exit the program with exit: mov rax, NR_exit syscall diff --git a/src/string.asm b/src/string.asm index 2e069bf..4563754 100644 --- a/src/string.asm +++ b/src/string.asm @@ -1 +1,21 @@ %include "src/constants.asm" + +section .text + global strlen + +;----- strlen(*str[]) -----; +; Gets the length of given string +; Return value: Length of given string +; Used registers: +; rax* Byte to check in str[] >> (ret) length of given string +; rdi* (arg) Pointer to str[] +; rcx* Counter for scasb +strlen: + xor rax, rax + mov rcx, -1 + cld + repne scasb + mov rax, rcx + not rax + dec rax + ret diff --git a/src/tests.asm b/src/tests.asm index b9715c4..6870e54 100644 --- a/src/tests.asm +++ b/src/tests.asm @@ -4,8 +4,20 @@ extern exit ; console.asm ; string.asm +extern strlen ; convert.asm +section .rodata + TEST_strlen equ 1 + + ; strlen() + strlenStr1 db "Hello",EOS + strlenStr2 db "Hello, world!",NL,EOS + +section .data + +section .bss + section .text global _start _start: @@ -13,6 +25,19 @@ _start: mov rbp, rsp sub rsp, SIZE_QWORD +;--- +;--- strlen() +;--- + ; TEST 1 + lea rdi, [rel strlenStr1] + call strlen + ; TEST 2 + lea rdi, [rel strlenStr2] + call strlen + +;--- +;--- exit() +;--- leave mov rdi, 0 call exit