2

我正在尝试编写一个函数,该函数将字符串打印到标准输出而不导入<cstdio><iostream>.

为此,我尝试将 2 个参数(const char* 和 const unsigned)传递给asm(...)c++ 代码中的部分。并调用write系统调用。

这工作正常:

void writeInAsm(const char* str, const unsigned len) {
    register const char* arg3 asm("rsi") = str; 
    register const unsigned arg4 asm("rdx") = len;
    asm(
        "mov rax, 1 ;" // write syscall
        "mov rdi, 1 ;" // file descriptor 1 - stdout
        "syscall ;"
    );
}

如果没有我将参数分配给寄存器的前两行,是否可以做到这一点?

下一行不起作用:

mov rsi, str; 
// error: relocation R_X86_64_32S against undefined symbol `str' can not be used when making a PIE object; recompile with -fPIC
// compiled with -fPIC - still got this error
mov rsi, [str]; 
// error: relocation R_X86_64_32S against undefined symbol `str' can not be used when making a PIE object; recompile with -fPIC
// compiled with -fPIC - still got this error

mov rsi, dword ptr str; 
// incorrect register `rsi' used with `l' suffix
mov rsi, dword ptr [str]; 
// incorrect register `rsi' used with `l' suffix

我正在用g++ -masm=intel. 我在 x86_64 Intel® Core™ i7-7700HQ CPU @ 2.80GHz × 8,Ubuntu 19.04 5.0.0-36-generic 内核(如果重要的话)。

$ g++ --version 
g++ (Ubuntu 8.3.0-6ubuntu1) 8.3.0

编辑:根据Compiler Explorer,可以使用下一个:

void writeInAsm(const char* str, const unsigned len) {
    asm(
        "mov rax, 1 ;"
        "mov rdi, 1 ;"
        "mov rsi, QWORD PTR [rbp-8] ;"
        "mov edx, DWORD PTR [rbp-12] ;"
        "syscall ;"
    );
}

但它总是rbp寄存器吗?它会如何随着参数数量的增加而变化?

4

0 回答 0