本文介绍了如何在NASM x86_64 Linux Assembly中将字符串中的一个字符与另一个字符进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实际上是想了解Intel x64语法中NASM汇编的基本概念,但是在尝试使strchr等效时遇到了一个问题...

I'm actually trying to understand the basic concepts of NASM Assembly in Intel x64 syntax but facing an issue while trying to make a strchr equivalent...

我一直在网上获取最大的信息,但是我不明白如何将一个字符串的当前字符(如str [i])与一个简单的字符进行比较.

I've been sailing the web to get the maximum information but I can't understand how to compare the current char of a string (like str[i]) with a simple char.

这里是测试主体:

#include <stdio.h>

extern char* my_strchr(char*, char);

int     main(void)
{
  char* str;

  str = my_strchr("foobar", 'b');
  printf("%s\n", str);
  return 0;
}

这是我的汇编代码:

我假设rdi是我的字符串,rsi是我的一字节数据.

I assume that rdi is my string and rsi my one-byte data.

my_strchr:
    push    rcx                  ;Save our counter
    xor     rcx, rcx             ;Set it to 0
loop:
    cmp     rdi, byte 0          ;Check the end of string
    jz      end
    cmp     rsi, [byte rdi+rcx]  ;Here is the point ...
    jz      end
    inc     rcx                  ;increment our counter
    jmp     loop
end:
    mov     rax, [rdi+rcx]       ;Are the brackets needed ? Is it equivalent to '&' in C ? 
    pop     rcx
    ret

Gdb为我提供了用c编写的strchr函数的输出,因此反汇编了:

Gdb gave me this output for the strchr function written in c and so disassembled :

....
cmp    al,BYTE PTR [rbp-0x1c]
....

但是我的实际上是这样做的:

But mine is actually doing this :

0x400550 <my_strchr>            push   rcx
0x400551 <my_strchr+1>          xor    rcx,rcx
0x400554 <loop>                 cmp    rdi,0x0
0x400558 <loop+4>               je     0x400566 <end>
0x40055a <loop+6>               cmp    rsi,QWORD PTR [rdi+rcx*1+0x0]

预先感谢您,希望有人会知道

Thank you in advance, Hope someone will know

推荐答案

rdi是一个指针,因此cmp rdi, 0检查空指针.您的意思是cmp byte [rdi + rcx], 0检查字符串的结尾.请注意,您需要检查当前字符,因此必须明显添加索引.

rdi is a pointer, so cmp rdi, 0 checks for a null pointer. What you meant was cmp byte [rdi + rcx], 0 to check the end of string. Note you need to check the current character so have to add the index obviously.

至于cmp rsi, [byte rdi+rcx]byte毫无意义,因为您正在比较8字节的整个rsi.应该是cmp sil, [rdi + rcx].

As for cmp rsi, [byte rdi+rcx] the byte there makes no sense, since you are comparing the whole of rsi which is 8 bytes. That should be cmp sil, [rdi + rcx].

最后,strchr应该返回一个指针,因此您应该将mov rax, [rdi+rcx]更改为lea rax, [rdi + rcx].

Finally, strchr is supposed to return a pointer so you should change mov rax, [rdi+rcx] to lea rax, [rdi + rcx].

这篇关于如何在NASM x86_64 Linux Assembly中将字符串中的一个字符与另一个字符进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 17:36