I am a beginner in Assembly and i have a simple question. This is my code :
BITS 64 ; 64−bit mode
global strchr ; Export 'strchr'
SECTION .text ; Code section
strchr:
mov rcx, -1
.loop:
inc rcx
cmp byte [rdi+rcx], 0
je exit_null
cmp byte [rdi+rcx], sil
jne .loop
mov rax, [rdi+rcx]
ret
exit_null:
mov rax, 0
ret
This compile but doesn't work. I want to reproduce the function strchr as you can see. When I test my function with a printf it crashed ( the problem isn't the test ). I know I can INC rdi directly to move into the rdi argument and return it at the position I want. But I just want to know if there is a way to return rdi at the position rcx to fix my code and probably improve it.
Your function
strchrseems to expect two parameters:RDI, andRSI.Register
rcxis used as index inside the string? In this case you should usealinstead ofcl. Be aware that you don't limit the search size. When the character refered byRSIis not found in the string, it will probably trigger an exception. Perhaps you should testalloaded from[rdi+rcx]and quit further searching whenal=0.If you want it to return pointer to the first occurence of character inside the string, just
replace
mov rax,[rdi+rcx]withlea rax,[rdi+rcx].