summaryrefslogtreecommitdiffstats
path: root/vespamalloc/src/vespamalloc/util/callstack.cpp
blob: 088b277d3cf53a8059f7cebc1f5ab5b367ce5d56 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <dlfcn.h>
#include <ctype.h>
#include <vespamalloc/util/callstack.h>

namespace vespamalloc {

const char * dlAddr(const void * func) {
    static const char * _unknown = "UNKNOWN";
    const char * funcName = _unknown;
    Dl_info info;
    int ret = dladdr(func, &info);
    if (ret != 0) {
        funcName = info.dli_sname;
    }
    return funcName;
}

const void * dlNextSym(const void * func)
{
    const char * f = static_cast<const char *>(func);
    size_t i(0);
    bool done(false);
    for( i = 0; !done; i++) {
        Dl_info info;
        int ret = dladdr(f+i, &info);
        if (ret == 0) {
            fprintf(stderr, "dladdr failed for %p\n", f+i);
        }
        done = (f != info.dli_saddr);
    }
    return f+i;
}

static void verifyAndCopy(const void * addr, char *v, size_t sz)
{
    size_t pos(0);
    const char * sym = dlAddr(addr);
    for (;sym && (sym[pos] != '\0') && (pos < sz-1); pos++) {
        char c(sym[pos]);
        v[pos] = isprint(c) ? c : '.';
    }
    v[pos] = '\0';
}

void StackReturnEntry::info(FILE * os) const
{
    static char tmp[0x400];
    verifyAndCopy(_return, tmp, sizeof(tmp));
    fprintf(os, "%s(%p)", tmp, _return);
}

asciistream & operator << (asciistream & os, const StackReturnEntry & v)
{
    static char tmp[0x100];
    static char t[0x200];
    verifyAndCopy(v._return, tmp, sizeof(tmp));
    snprintf(t, sizeof(t), "%s(%p)", tmp, v._return);
    return os << t;
}

}