0

I am working with the following scenario: I need to get the call stack at the entry point of some APIs. So I wrote some wrappers and use libunwind to perform stack backtracing before executing the real API.

For example:

#include <libunwind.h>

void doBackTrace() {
    unw_cursor_t cursor;
    unw_context_t context;

    unw_getcontext(&context);
    unw_init_local(&cursor, &context);

    while (unw_step(&cursor) > 0) {
        unw_word_t offset, pc;
        char fname[FUNC_NAME_LENGTH];
        
        unw_get_reg(&cursor, UNW_REG_IP, &pc);
        unw_get_proc_name(&cursor, fname, sizeof(fname), &offset);
    }
}

void funcE() {
    doBackTrace();
}

void funcC() {
    funcE();
}

void funcD() {
    funcE();
}

void funcB() {
    funcC();
    funcD();
}

void funcA() {
    funcB();
    funcC();
    funcD();
    funcE();
}

int main() {
    funcA()
    return 0;
}

In the above code, funcE() is responsible for stack backtracing using libunwind, which would be executed for four times. Some times call path share the same prefix, such as A -> B -> C -> E and A -> B -> D -> E in the example. The question is, due to the fact that the call stack is organized in a single-direction linked list, I could not judge whether the prefix has already appeared in the previous backtracing until I traverse the whole path to the root using unw_step, which has an overhead of O(N), where N is the depth of the call stack. So how to reduce the backtracing overhead for calls sharing the same prefix?

flyingrose
  • 107
  • 2
  • 11
  • You can't. How would you tell the difference between A->B->C->E and Z->B->C->E without going all the way back to A/Z? – user253751 May 12 '22 at 13:40
  • maybe you can **guess** that if SP is the same as last time, it's the same stack frame. But that is only a guess. It is sometimes wrong. – user253751 May 12 '22 at 13:41
  • @user253751 That is exactly my question. I once read a paper saying that using `trampoline` or sth could help identify the same call path prefix ([paper](https://dl.acm.org/doi/pdf/10.1145/3392717.3392752), Section 3.1), but I do not know what trampoline is. – flyingrose May 12 '22 at 14:02
  • you see where it says "trampolines [11]"? That [11] is a *citation*. You can go to the end, to the *bibliography* and look for number 11, and it will tell you the name of another paper. Read that paper and you will find out more about trampolines. It is like a hyperlink for printed text. – user253751 May 12 '22 at 14:46

0 Answers0