64 位汇编 4 位以上的参数入栈为什么从 32[rsp]开始?

2022-02-25 12:12:16 +08:00
 Kasumi20

是为了兼容 32 位吗?

代码

int printf_param(int a, int b, int c, int d, int e, int f)
{
        return a+b+c+d+e+f;
}

int main()
{
        return printf_param(1, 2, 3, 4, 5, 6);
}

汇编

main:
        push    rbp
        .seh_pushreg    rbp
        mov     rbp, rsp
        .seh_setframe   rbp, 0
        sub     rsp, 48
        .seh_stackalloc 48
        .seh_endprologue
        call    __main
        mov     DWORD PTR 40[rsp], 6
        mov     DWORD PTR 32[rsp], 5
        mov     r9d, 4
        mov     r8d, 3
        mov     edx, 2
        mov     ecx, 1
        call    printf_param
        add     rsp, 48
        pop     rbp
        ret
1197 次点击
所在节点    C++
3 条回复
CRVV
2022-02-25 12:20:12 +08:00
https://en.wikipedia.org/wiki/X86_calling_conventions#Microsoft_x64_calling_convention


In the Microsoft x64 calling convention, it is the caller's responsibility to allocate 32 bytes of "shadow space" on the stack right before calling the function (regardless of the actual number of parameters used), and to pop the stack after the call.
ShiaoQuR
2022-02-25 12:39:45 +08:00
前几个参数通过寄存器传递了,具体使用的寄存器要看 ABI 规定(像 MSVC 这边前 4 个通常是 RCX/RDX/R8/R9 )。

但栈上也会保留这部分参数占的空间(考虑递归调用的情况)。
ChaosesIb
2022-02-26 00:00:34 +08:00
保留 shadow space 主要是为了方便保留参数的原值,以及使得参数能够在栈上保持连续,方便遍历栈( va_list )。
另外,即使参数不到 4 个,微软的 x64 调用约定也要求保留 shadow space 。这条规则的主要原因是 C 允许 unprototyped function ,一个函数在被调用时传入了几个参数是不确定的,如果不统一 shadow space 大小,编译器实际上就没法利用 shadow space 了。
shadow space 提供的好处算不上很强,不过倒也没什么开销,所以微软这么规定也没什么。另一个主流 x64 调用约定 System V 没有 shadow space ,不过有个 red zone ,虽然同样是预留空间,不过设计 red zone 的原因主要跟内核中断有关,和 shadow space 不是一码事。

可以读下 Raymond Chen 的文章,更详细了解一下:
Can an x64 function repurpose parameter home space as general scratch space? aHR0cHM6Ly9kZXZibG9ncy5taWNyb3NvZnQuY29tL29sZG5ld3RoaW5nLzIwMTMwODMwLTAwLz9wPTMzNjM=
Why does the x64 calling convention reserve four home spaces for parameters even for functions that take fewer than four parameters? aHR0cHM6Ly9kZXZibG9ncy5taWNyb3NvZnQuY29tL29sZG5ld3RoaW5nLzIwMTYwNjIzLTAwLz9wPTkzNzM1

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/836362

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX