将字符与Intel x86_64程序集进行比较

时间:2016-03-14 21:33:23

标签: linux assembly nasm x86-64

我是汇编的新手(Intel x86_64),我正在尝试从C库中重新编码一些函数。我在64位Linux上并使用 NASM 进行编译。

我的 strchr 功能出错,我无法找到解决方案......

这里提醒一下strchr手册的摘录:

  

char * strchr(const char * s,int c);

     

strchr()函数返回指向字符串s中第一次出现的字符c的指针。

以下是我尝试的内容:

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

这会在字符串的ned上返回一个指针而找不到字符......

我认为这条线不起作用:

    cmp [r12], r13

我测试了它并且它起作用了:

    cmp [r12], 97 ; 97 = 'a' in ASCII

示例:

char *s;

s = strchr("blah", 'a');
printf("%s\n", s);

退回:

ah

但是我无法通过寄存器比较来实现它。我做错了什么,我该如何解决?

2 个答案:

答案 0 :(得分:0)

首先,感谢您的帮助!我想我对自己的工作有了更深入的了解。

我遇到了接收8位参数而不是64位 rdi 的问题...但朋友告诉我第一个8位参数也在 sil 注册。

所以这是我的工作代码:

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

请随时告诉我是否有办法改进它并再次感谢!

答案 1 :(得分:0)

这是您的汇编代码的修复程序,该代码在手册页中定义的x86-64汇编语言中实现了strchr(3):

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