NetBSD-Users archive

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index][Old Index]

Re: Stack dump using backtrace() and backtrace_symbols()



In article <38739B27-76E0-4408-8FC9-512F8AEE0D88%yahoo.com@localhost>,
Owen Orakwue  <aninione%yahoo.com@localhost> wrote:
>
>Does NetBSD have any equivalent of the GNU extensions backtrace() and
>backtrace_symbols()?
>Thanks.
>
>-Owen

No, but they are ~trivial to write... Ahem, but without libelf there is
no easy access to symbols:

christos

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#ifdef __MACHINE_STACK_GROWS_UP
#define BELOW >
#else
#define BELOW <
#endif

struct frameinfo {
        struct frameinfo *next;
        void *return_address;
};

size_t
backtrace(void **trace, size_t len)
{
        const struct frameinfo *frame = __builtin_frame_address(0);
        void *stack = &stack;

        for (size_t i = 0; i < len; i++) {
                if ((void *)frame BELOW stack)
                        return i;
                trace[i] = frame->return_address;
                frame = frame->next;
        }

        return len;
}

char **
backtrace_symbols(void *const *trace, size_t len)
{
        static const size_t slen = sizeof("0x123456789abcdef");
        char **ptr = calloc(len, sizeof(*ptr) + slen);

        if (ptr == NULL)
                return NULL;

        char *str = (void *)(ptr + len);
        size_t cur = 0, left = len * slen;

        for (size_t i = 0; i < len; i++) {
                ptr[i] = str + cur;
                cur += snprintf(str + cur, left - cur, "%p", trace[i]) + 1;
                assert(cur < left);
        }

        return ptr;
}



Home | Main Index | Thread Index | Old Index