x64内联汇编注意点

#include <windows.h>
#include <stdio.h>


extern "C" int MyPrintf(ULONGLONG,ULONGLONG);


void MyFunc(int a, int b)
{
    printf("%d", 3);
}

int main()
{
    ULONGLONG ullAddr = (ULONGLONG)printf;
    char* szInt = "%d";

    int ret = MyPrintf(ullAddr, (ULONGLONG)szInt);
    //发现了问题,是在call r10里,printf函数里面,竟然把堆栈乱J8改
    //导致ret的时候地址不对,出错。 这个似乎我没什么办法。。

    /*MyFunc(3,4);*/


    system("pause");

    return 0;
}
.code 

MyPrintf proc
    
    sub rsp,40h
    mov [rsp+8h],rcx
    mov [rsp+10h],rdx
    mov rcx,rdx
    mov rdx,3
    call qword ptr [rsp+8h]

    lea rsp,[rsp+40h]
   
    ret
MyPrintf endp
end

main


  MyPrintf()
    printf()


main调用MyPrintf rsp-=8 并储存 "返回地址到main"
MyPrintf中调用printf,那么rsp-=8,并储存 "返回地址到MyPrintf"
printf拿到参数,直接放在[rsp+8h][rsp+10h][rsp+18h][rsp+20h] 似乎一直是四个参数的,无论实参传几个.....
那么,"返回到MyPrintf"是正常的,但是"返回到main"就被覆盖了

所以MyPrintf应该扩一下自己的堆栈

原文地址:https://www.cnblogs.com/cqubsj/p/6040306.html