Home > Software engineering >  strcasecmp implementation not printing
strcasecmp implementation not printing

Time:02-28

I'm working on a little project where I have to recode a function from the lib C. Actually I'm working on strcasecmp:

BITS 64

%include "minilib.inc"

section .text

my_strcasecmp:
init:
    mov r10b, [rdi]
    mov r11b, [rsi]
    jmp while

while:
    cmp r10b, 0
    je end
    cmp r11b, 0
    je end
    cmp r10b, 90
    jle checkfirstup
    cmp r11b, 90
    jle checksecondup
    jmp strcasecmp

strcasecmp:
    cmp r10b, r11b
    jne end
    inc rdi
    inc rsi
    jmp init

checkfirstup:
    cmp r10b, 65
    jge r10btolowcase
    jmp checksecondup

r10btolowcase:
    add r10b, 32
    jmp while

checksecondup:
    cmp r11b, 65
    jge r11btolowcase
    jmp strcasecmp

r11btolowcase:
    add r11b, 32
    jmp while

end:
    movzx rax, r10b
    movzx rbx, r11b
    sub rax, rbx
    ret

and this is the code in c :

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

extern int my_strcasecmp(const char *string1, const char *string2); /* Prototype */

int main(void)
{
    char *str1 = "S";
    char *str2 = "S";
    int result;

    result = strcasecmp(str1, str2);

    if (result == 0)
        printf("Strings compared equal.\n");
    else if (result < 0)
        printf("\"%s\" is less than \"%s\".\n", str1, str2);
    else
        printf("\"%s\" is greater than \"%s\".\n", str1, str2);

    return 0;}

when I try my strcasecmp I always have "nanana is greater than nanana" and I don't understand why.

How can I fix this?

CodePudding user response:

The problem is that when the first char is not in [A,Z], you immediately jump to checksecondup where you only ever check the lower bound for the second char. The cmp r11b, 90 was never performed at that point! (It triggers an unwanted add r11b, 32.)

The solution is to LCase both characters independently:

  ...
  cmp r10b, 65
  jb  Next
  cmp r10b, 90
  ja  Next
  add r10b, 32
Next:
  cmp r11b, 65
  jb  Next_
  cmp r11b, 90
  ja  Next_
  add r11b, 32
Next_:
  cmp r10b, r11b
  ...
  • Related