【问题标题】:How does one compare values in GAS assembly architecture?如何比较 GAS 装配体系结构中的值?
【发布时间】:2015-09-29 18:44:28
【问题描述】:

对于这个看似无害且简单的问题,我很难找到答案。我希望使用 cmp 或其衍生物之一(cmpl、cmpb 等)来比较 GAS 汇编程序中的两个值。问题是,当我进行多次比较时,结果应该不同,它们的结果是一样的。我相信这涉及我对如何将数据与 cmp 操作进行比较的误解。

情况如下:

我有一个填充变量来接受这样的输入,用一个 equ 来保存大小:

buff:    .fill    20
         .equ     bufLen, .-buff

然后我把bufLen变量放到一个寄存器里,比较值放到另一个寄存器里:

         movl     $bufLen, %eax
         movl     $0x03, %ebx

最后,我比较,如果比较相等,跳转到另一行:

         cmpl     %eax, %ebx
         je       anotherplace

但是,当我比较长度为 2 和 4 的输入时,它们都小于(我将 je 更改为 jl 以进行快速调试)。谁能告诉我我做错了什么或指出我错过的问题可能会告诉我我是如何搞砸的?

提醒一下,这是 GAS 组装架构。

非常感谢所有帮助。

【问题讨论】:

  • 你能发布你的整个代码吗?至少MCVE...
  • @DanielKamilKozar 我最初也怀疑这一点,但是因为当我尝试“je”时它不起作用,这与它们的顺序无关,我倾向于相信操作顺序不正确。此外,我对操作顺序的理解与您的解释相符。
  • @Enzo Ferber 这是完整的相关代码。创建缓冲区大小变量,然后将其与 3 进行比较。唯一缺少的是通常的形式,例如 .globl _start 和 .section .data 顶部。
  • @MichaelPetch 你能详细说明一下吗?恐怕我还很陌生,很难完全理解装配。我被告知您可以使用带 $ 或不带 $ 的变量名,但有什么区别?
  • 其实我看错了你的代码,忘了你看到我的评论

标签: assembly gnu-assembler


【解决方案1】:

根据 cmets,我向您展示了一些在 Linux 中获取以零结尾的字符串 (.asciz) 长度的方法:

witch.s:

.data

witches: .asciz "Double, double toil and trouble; Fire burn, and cauldron bubble"
format0: .asciz "%s\n"
format1: .asciz "Return of printf: %u\n"
format2: .asciz "Return of strlen: %u\n"
format3: .asciz "Return of repne scasb: %u\n"

.text
.global main
main:

    push $witches
    push $format0
    call printf         # returns in EAX the amount of printed chars (+ \n!)
    add $8, %esp

    push %eax
    push $format1
    call printf
    add $8, %esp

    push $witches
    call strlen         # returns in EAX the length of the string
    add $4, %esp

    push %eax
    push $format2
    call printf
    add $8, %esp

    mov $witches, %edi
    xor %al, %al
    xor %ecx, %ecx
    dec %ecx
    repne scasb
    neg %ecx            # returns in ECX the length of the string + 2

    push %ecx
    push $format3
    call printf
    add $8, %esp

    mov $0, %eax        # return 0;
    ret

编译并运行:

gcc -m32 witch.s
./a.out

还有更多方法

【讨论】:

  • 通常repne scasb 得到相当于 strlen 我会使用 not %ecx 然后做 dec %ecx (如果我从字符串长度中排除终止符)
【解决方案2】:

正如我在原始问题的 cmets 中发现的那样,问题是我没有意识到 bufLen 是 20 长,正如 buff 变量中定义的那样。因此,我与之比较的所有较低值都返回小于 20。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-21
    • 1970-01-01
    相关资源
    最近更新 更多