I'm new to assembly (Intel x86_64) and I am trying to recode some functions from the C library. I am on a 64-bit Linux and compiling with NASM .
I have an error with the strchr function and I can't find a solution...
As a reminder here is an extract from the man page of strchr :
char *strchr(const char *s, int c);
The strchr() function returns a pointer to the first occurrence of the character c in the string s.
Here is what I tried :
strchr:
push rpb
mov rbp, rsp
mov r12, rdi ; get first argument
mov r13, rsi ; get second argument
call strchr_loop
strchr_loop:
cmp [r12], r13 ; **DON'T WORK !** check if current character is equal to character given in parameter...
je strchr_end ; go to end
cmp [r12], 0h ; test end of string
je strchr_end ; go to end
inc r12 ; move to next character of the string
jmp strchr_loop ; loop
strchr_end
mov rax, r12 ; set function return
mov rsp, rbp
pop rbp
This return a pointer on the ned of the string and don't find the character...
I think it's this line which doesn't work :
cmp [r12], r13
I tested with this and it worked :
cmp [r12], 97 ; 97 = 'a' in ASCII
The example :
char *s;
s = strchr("blah", 'a');
printf("%s\n", s);
Returned :
ah
But I can't make it work with a register comparison. What am I doing wrong, and how can I fix it?
First, thanks for your help ! I think I have a better understanding of what I am doing.
I was stuck with the problem of receiving a 8bits parameter instead of the 64bits rdi ... But a friend shows me that the first 8bit parameter is also in the sil register.
So here's my working code :
strchr:
push rpb
mov rbp, rsp
call strchr_loop
strchr_loop:
cmp byte [rdi], sil ; check if current character is equal to character given in parameter
je strchr_end ; go to end
cmp byte [rdi], 0h ; test end of string
je strchr_end ; go to end
inc rdi ; move to next character of the string
jmp strchr_loop ; loop
strchr_end
mov rax, rdi ; set function return
mov rsp, rbp
pop rbp
Please feel free to tell me if there is a way to improve it and thanks again !
Here is a fix for your assembly code, which implements the strchr(3), in x86-64 Assembly as defined in the man pages:
asm_strchr:
push rbp
mov rbp, rsp
strchr_loop:
cmp byte [rdi], 0 ; test end of string
je fail_end ; go to end
cmp byte [rdi], sil ; check if current character is equal to character given in parameter
je strchr_end ; go to end
inc rdi ; move to next character of the string
jmp strchr_loop ; loop
strchr_end:
mov rax, rdi ; set function return
mov rsp, rbp
pop rbp
ret
fail_end:
mov rax, 0
mov rsp, rbp
pop rbp
ret
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.