summaryrefslogtreecommitdiffstats
path: root/vespamalloc/src/vespamalloc/util/callstack.cpp
blob: e072dda91c471dc07e92899779e1da576948ceb0 (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
// Copyright 2017 Yahoo Holdings. 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;
}

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;
}

}