Printing Stack Frames

 ̄綄美尐妖づ 提交于 2019-12-06 15:46:38

x86-64 does not pass the first few arguments on the stack (type permitting) so you have no chance to print those. Also, the actual stack layout for the locals depends on compiler and settings.

Since you have provided the assembly code, we can examine the layout which looks like this:

        return address
rbp     saved rbp
rbp-8   local variable "sp"
rbp-16  local variable "loc"
rbp-20  local copy of argument "a"
rbp-24  local copy of argument "b"

Also note that a and b are 4 bytes, the rest are 8. Furthermore, C pointer arithmetic scales by item size, so *(sp+4) goes 4 * 8 = 32 bytes not 4 as you probably intended.

If the stack layout is unchanged, you can use this code as illustration:

#include <stdio.h>
#include <stdint.h>
int main();
void func(int a,int b)
{
    uint64_t loc = 0;
    char *sp = (char*)&loc;

    printf("main = %p\n", main);
    printf("return address = %p\n", *(void**)(sp + 24));
    printf("saved rbp = %p\n", *(void**)(sp + 16));
    printf("sp = %p\n", *(void**)(sp + 8));
    printf("loc = %lld\n", *(uint64_t*)(sp));
    printf("a = %d\n", *(int*)(sp - 4));
    printf("b = %d\n", *(int*)(sp - 8));
}

int main()
{
    func(2,3);
    return 0;
}

Sample output:

main = 0x4005e6
return address = 0x4005f9
saved rbp = 0x7ffe057bf240
sp = 0x7ffe057bf220
loc = 0
a = 2
b = 3
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!