在扩展内联 ASM 中调用 printf [英] Calling printf in extended inline ASM

查看:29
本文介绍了在扩展内联 ASM 中调用 printf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 64 位 Linux 上 GCC 的扩展内联 ASM 中输出相同的字符串两次.

I'm trying to output the same string twice in extended inline ASM in GCC, on 64-bit Linux.

int main()
{
    const char* test = "test
";

    asm(
        "movq %[test], %%rdi
"    // Debugger shows rdi = *address of string*  
        "movq $0, %%rax
"

        "push %%rbp
"
        "push %%rbx
"
        "call printf
"         
        "pop %%rbx
"
        "pop %%rbp
"

        "movq %[test], %%rdi
" // Debugger shows rdi = 0
        "movq $0, %%rax
"

        "push %%rbp
"
        "push %%rbx
"
        "call printf
"     
        "pop %%rbx
"
        "pop %%rbp
"
        : 
        :  [test] "g" (test)
        : "rax", "rbx","rcx", "rdx", "rdi", "rsi", "rsp"
        );

    return 0;
}

现在,字符串只输出一次.我尝试了很多东西,但我想我遗漏了一些关于调用约定的警告.我什至不确定 clobber 列表是否正确,或者我是否需要保存和恢复 RBPRBX.

Now, the string is outputted only once. I have tried many things, but I guess I am missing some caveats about the calling convention. I'm not even sure if the clobber list is correct or if I need to save and restore RBP and RBX at all.

为什么字符串没有输出两次?

使用调试器查看显示,当字符串第二次加载到 rdi 时,它的值是 0 而不是字符串的实际地址.

Looking with a debugger shows me that somehow when the string is loaded into rdi for the second time it has the value 0 instead of the actual address of the string.

我无法解释为什么,似乎在第一次调用后堆栈已损坏?我必须以某种方式恢复它吗?

I cannot explain why, it seems like after the first call the stack is corrupted? Do I have to restore it in some way?

推荐答案

您的代码的特定问题:RDI 不是跨函数调用维护的(见下文).在第一次调用 printf 之前它是正确的,但被 printf 破坏了.您需要先将其暂时存储在其他地方.一个不被破坏的寄存器会很方便.然后,您可以在 printf 之前保存一份副本,然后将其复制回 RDI.

Specific problem to your code: RDI is not maintained across a function call (see below). It is correct before the first call to printf but is clobbered by printf. You'll need to temporarily store it elsewhere first. A register that isn't clobbered will be convenient. You can then save a copy before printf, and copy it back to RDI after.

我不建议您按照您的建议进行操作(在内联汇编程序中进行函数调用).编译器将很难优化事物.很容易把事情弄错.David Wohlferd 写了一篇关于不使用内联汇编的原因的非常好的文章,除非绝对必要.

I do not recommend doing what you are suggesting (making function calls in inline assembler). It will be very difficult for the compiler to optimize things. It is very easy to get things wrong. David Wohlferd wrote a very good article on reasons not to use inline assembly unless absolutely necessary.

除其他外,64 位 System V ABI 要求 128-字节红色区域.这意味着您不能在没有潜在损坏的情况下将任何内容压入堆栈.请记住:执行 CALL 会将返回地址压入堆栈.解决这个问题的快速而肮脏的方法是在您的内联汇编器启动时从 RSP 中减去 128,然后在完成时将 128 加回来.

Among other things the 64-bit System V ABI mandates a 128-byte red zone. That means you can't push anything onto the stack without potential corruption. Remember: doing a CALL pushes a return address on the stack. Quick and dirty way to resolve this problem is to subtract 128 from RSP when your inline assembler starts and then add 128 back when finished.

超出 %rsp 指向的位置的 128 字节区域被认为是保留,不得被信号或中断处理程序修改. 8 因此,函数可以将此区域用于跨函数不需要的临时数据调用.特别是,叶函数可能会在整个堆栈帧中使用该区域,而不是在序言和尾声中调整堆栈指针.这个区域是被称为红色区域.

The 128-byte area beyond the location pointed to by %rsp is considered to be reserved and shall not be modified by signal or interrupt handlers.8 Therefore, functions may use this area for temporary data that is not needed across function calls. In particular, leaf functions may use this area for their entire stack frame, rather than adjusting the stack pointer in the prologue and epilogue. This area is known as the red zone.

另一个需要关注的问题是在任何函数调用之前堆栈必须是 16 字节对齐(或者可能是 32 字节对齐,具体取决于参数).这也是 64 位 ABI 所要求的:

Another issue to be concerned about is the requirement for the stack to be 16-byte aligned (or possibly 32-byte aligned depending on the parameters) prior to any function call. This is required by the 64-bit ABI as well:

输入参数区域的末尾应对齐在 16(32,如果 __m256 是在堆栈上传递)字节边界.换句话说,值 (%rsp + 8) 总是当控制权转移到函数入口点时为 16 (32) 的倍数.

The end of the input argument area shall be aligned on a 16 (32, if __m256 is passed on stack) byte boundary. In other words, the value (%rsp + 8) is always a multiple of 16 (32) when control is transferred to the function entry point.

注意:对函数的 CALL 进行 16 字节对齐的要求也是 在 32 位 Linux 上需要 GCC >= 4.5:

Note: This requirement for 16-byte alignment upon a CALL to a function is also required on 32-bit Linux for GCC >= 4.5:

在 C 编程语言的上下文中,函数参数以相反的顺序压入堆栈.在 Linux 中,GCC 为调用约定设置了事实上的标准.从 GCC 4.5 版本开始,调用函数时栈必须对齐到 16 字节边界(以前的版本只需要 4 字节对齐.)

In context of the C programming language, function arguments are pushed on the stack in the reverse order. In Linux, GCC sets the de facto standard for calling conventions. Since GCC version 4.5, the stack must be aligned to a 16-byte boundary when calling a function (previous versions only required a 4-byte alignment.)

由于我们在内联汇编程序中调用了 printf,因此我们应该确保在调用之前将堆栈对齐到 16 字节的边界.

Since we call printf in inline assembler we should ensure that we align the stack to a 16-byte boundary before making the call.

您还必须注意,在调用函数时,某些寄存器会在函数调用中保留,而有些则不会.具体来说,可能被函数调用破坏的那些列在 64 位 ABI 的图 3.4 中(参见上一个链接).这些寄存器是RAXRCXRDXRD8-RD11XMM0-XMM15MMX0-MMX7ST0-ST7 .这些都可能被破坏,因此如果它们没有出现在输入和输出约束中,则应将它们放入 clobber 列表中.

You also have to be aware that when calling a function some registers are preserved across a function call and some are not. Specifically those that may be clobbered by a function call are listed in Figure 3.4 of the 64-bit ABI (see previous link). Those registers are RAX, RCX, RDX, RD8-RD11, XMM0-XMM15, MMX0-MMX7, ST0-ST7 . These are all potentially destroyed so should be put in the clobber list if they don't appear in the input and output constraints.

以下代码应满足大部分条件,以确保调用另一个函数的内联汇编器不会无意中破坏寄存器、保留 redzone 并在调用前保持 16 字节对齐:

The following code should satisfy most of the conditions to ensure that inline assembler that calls another function will not inadvertently clobber registers, preserves the redzone, and maintains 16-byte alignment before a call:

int main()
{
    const char* test = "test
";
    long dummyreg; /* dummyreg used to allow GCC to pick available register */

    __asm__ __volatile__ (
        "add $-128, %%rsp
	"   /* Skip the current redzone */
        "mov %%rsp, %[temp]
	" /* Copy RSP to available register */
        "and $-16, %%rsp
	"    /* Align stack to 16-byte boundary */
        "mov %[test], %%rdi
	" /* RDI is address of string */
        "xor %%eax, %%eax
	"   /* Variadic function set AL. This case 0 */
        "call printf
	"
        "mov %[test], %%rdi
	" /* RDI is address of string again */
        "xor %%eax, %%eax
	"   /* Variadic function set AL. This case 0 */
        "call printf
	"
        "mov %[temp], %%rsp
	" /* Restore RSP */
        "sub $-128, %%rsp
	"   /* Add 128 to RSP to restore to orig */
        :  [temp]"=&r"(dummyreg) /* Allow GCC to pick available output register. Modified
                                    before all inputs consumed so use & for early clobber*/
        :  [test]"r"(test),      /* Choose available register as input operand */
           "m"(test)             /* Dummy constraint to make sure test array
                                    is fully realized in memory before inline
                                    assembly is executed */
        : "rax", "rcx", "rdx", "rsi", "rdi", "r8", "r9", "r10", "r11",
          "xmm0","xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7",
          "xmm8","xmm9", "xmm10", "xmm11", "xmm12", "xmm13", "xmm14", "xmm15",
          "mm0","mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm6",
          "st", "st(1)", "st(2)", "st(3)", "st(4)", "st(5)", "st(6)", "st(7)"
        );

    return 0;
}

我使用了一个输入约束来允许模板选择一个可用的寄存器来传递 str 地址.这确保我们有一个寄存器来存储对 printf 的调用之间的 str 地址.我还让汇编模板选择一个可用的位置来临时存储 RSP 使用虚拟寄存器.选择的寄存器将不包括任何已选择/列为输入/输出/clobber 操作数的寄存器.

I used an input constraint to allow the template to choose an available register to be used to pass the str address through. This ensures that we have a register to store the str address between the calls to printf. I also get the assembler template to choose an available location for storing RSP temporarily by using a dummy register. The registers chosen will not include any one already chosen/listed as an input/output/clobber operand.

这看起来很乱,但如果不正确执行,可能会在以后随着您的程序变得更加复杂而导致问题.这就是为什么在内联汇编器中调用符合 System V 64 位 ABI 的函数通常不是最好的方法.

This looks very messy, but failure to do it correctly could lead to problems later as you program becomes more complex. This is why calling functions that conform to the System V 64-bit ABI within inline assembler is generally not the best way to do things.

这篇关于在扩展内联 ASM 中调用 printf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆