How can I determine the return address on stack?

前端 未结 6 2185
旧巷少年郎
旧巷少年郎 2020-12-28 17:29

I know that if I am inside some function foo() which is called somewhere from bar() function, then this return address is pushed on stack.

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-28 18:03

    Try this

    //test1.cc
    //compile with
    //g++ -g test1.cc -o test1 
    
    #include 
    
    void
    print_function(void *p) {
        char cmd[128];
        FILE *fp;
    
        snprintf(cmd, sizeof(cmd), "addr2line -e %s -f %p", "test1", p);
        fp = popen(cmd, "r");
        if (fp) {
        char buf[128];
        while (fgets(buf, sizeof(buf), fp)) {
            printf("%s", buf); 
        }
        }
    }
    
    void
    f2(void) {
        print_function(__builtin_return_address(0));
    }
    
    void
    f1(void) {
        f2();
    }
    
    int
    main(int argc, char *argv[]) {
        f1();
        return(0);
    }
    

    The output should look like

    _Z2f1v
    /home///test1.cc:30
    

提交回复
热议问题