Comparing character with Intel x86_64 assembly

Viewed 5901

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?

2 Answers

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
Related