V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
Kasumi20
V2EX  ›  C++

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

  •  
  •   Kasumi20 ·
    develon2015 · 2022-02-25 12:12:16 +08:00 · 1187 次点击
    这是一个创建于 785 天前的主题,其中的信息可能已经有所发展或是发生改变。

    是为了兼容 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
    
    3 条回复
    CRVV
        1
    CRVV  
       2022-02-25 12:20:12 +08:00   ❤️ 2
    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
        2
    ShiaoQuR  
       2022-02-25 12:39:45 +08:00
    前几个参数通过寄存器传递了,具体使用的寄存器要看 ABI 规定(像 MSVC 这边前 4 个通常是 RCX/RDX/R8/R9 )。

    但栈上也会保留这部分参数占的空间(考虑递归调用的情况)。
    ChaosesIb
        3
    ChaosesIb  
       2022-02-26 00:00:34 +08:00   ❤️ 1
    保留 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
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2606 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 39ms · UTC 04:46 · PVG 12:46 · LAX 21:46 · JFK 00:46
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.