Stack trace function in C

607 views Asked by At

Im trying to write a function in C that identifies the top of the stack and determines the first frame pointer. Then I have a different function that recursively prints the current stack frame and calls itself with the next stack frame's pointer. Any tips on how to do this and get started?

    void stackTrace(int prms, int localVars){

    }

    void nextTrace(unsigned int *framePointer, int prms, int localVars){

    }
1

There are 1 answers

0
exebook On
int backtrace(void **buffer, int size) {
    extern uint64_t *__libc_stack_end;
    uint64_t **p, *bp, *frame;
    asm ("mov %%rbp, %0;" : "=r" (bp));
    p = (uint64_t**) bp;
    int i = 0;
    while (i < size) {
        frame = p[0];
        if (frame < bp || frame > __libc_stack_end) {
            return i;
        }
        buffer[i++] = p[1];
        p = (uint64_t**) frame;
    }
    return i;
}

That's how I did it, because GNU backtrace did not work with TinyC. I think my function wotks witm gcc/clang as well. The trick here is to start from the address stored in RBP (on x86_64) and walk until __libc_stack_end which is a builtin variable.