内联汇编中的string_cmp

问题描述 投票:0回答:1

我正在尝试在汇编中编写 string_cmp 函数,您可以在其中尝试比较两个字符串是否相同。

int string_cmp(const char* str1, char* str2) { int res;

// Your inline assembly code goes here. Note that volatile keyword ensure that the assembly code will not be moved around by the compiler
asm volatile (
    "loop1:"
        "mov (%[s1]), %%rsi\n"   // Move the source address to rsi
        "mov (%[s2]), %%rdx\n" //I wanted a name register but i couldnt initialsied rdx for some reason and %0 cannot be tested
        "inc %[s1]\n"
        "inc %[s2]\n" //check for end of a string then comp last char
        "test %%rsi, %%rdx\n"
        "jl neg\n"
        "jg pos\n"
        "cmp $0, %%rsi\n"
        "jne loop1\n"
        "je zero\n"

    "pos:"
        "mov $1, %%eax\n"
        "jmp fin\n"

    "zero:"
        "mov $0, %%eax\n"
        "jmp fin\n"

    "neg:"
        "mov $0xFFFFFFFF, %%eax\n"
        "jmp fin\n"

    "fin:"




    // Continue with the string copy using appropriate instructions
: "=a" (res)
: [s1] "r" (str1), [s2] "r" (str1) //need to initiate variables somewhere
: "%rsi"  // Use these as needed //clobbbered
);
return res;

}

这是我迄今为止的实现,因此我将字符串的指针移动到寄存器中,使用测试检查它们是否不同,然后循环直到我到达其中一个字符串的空字符。

然而,即使字符串相等,这也总是返回 1,这是因为 jg 总是在大多数情况下看到零和符号位吗?

是否可以使用不同的条件,以便比较正常工作,以便当左侧参数的值更大时它会跳转到 1?

下面的行是我试图将结果放入寄存器并返回这些结果。 我还在条件分支之后添加了一个 jmp ,但这并没有阻止字符串始终只是值 1,尽管将单词与空字符串进行比较并将字符串与空单词进行比较(这些应该是不同的)。 非常感谢。

assembly inline-assembly
1个回答
0
投票

如果您转到

zero:
,也没有什么可以阻止 CPU 之后执行接下来的两个
mov
。所以你总是会得到 1。在末尾添加一个额外的标签,并在设置 res 值后无条件跳转到该标签。

类似:

    "zero:"
        "mov $0, %1\n"
        "jmp finish\n"
    "neg:"
        "mov $0xFFFFFFFF, %1\n"
        "jmp finish\n"
    "pos:"
        "mov $1, %1\n"
    "finish:"
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.