summaryrefslogtreecommitdiffstats
path: root/fluent-bit/include/fluent-bit/flb_stacktrace.h
blob: ea4c00a717d70b322923e512d7b3606cb83eda32 (plain)
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
63
64
65
66
67
68
69
70
71
72
73
74
75
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*  Fluent Bit
 *  ==========
 *  Copyright (C) 2015-2022 The Fluent Bit Authors
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

#ifndef FLB_STACKTRACE_H
#define FLB_STACKTRACE_H

#include <fluent-bit/flb_info.h>

/* Libbacktrace support */
#if defined(FLB_HAVE_LIBBACKTRACE)
#include <backtrace.h>
#include <backtrace-supported.h>

struct flb_stacktrace {
    struct backtrace_state *state;
    int error;
    int line;
};

static void flb_stacktrace_error_callback(void *data,
                                          const char *msg, int errnum)
{
    struct flb_stacktrace *ctx = data;
    fprintf(stderr, "ERROR: %s (%d)", msg, errnum);
    ctx->error = 1;
}

static int flb_stacktrace_print_callback(void *data, uintptr_t pc,
                                         const char *filename, int lineno,
                                         const char *function)
{
    struct flb_stacktrace *p = data;

    fprintf(stderr, "#%-2i 0x%-17lx in  %s() at %s:%d\n",
            p->line,
            (unsigned long) pc,
            function == NULL ? "???" : function,
            filename == NULL ? "???" : filename + sizeof(FLB_SOURCE_DIR),
            lineno);
    p->line++;
    return 0;
}

static inline void flb_stacktrace_init(char *prog, struct flb_stacktrace *st)
{
    memset(st, '\0', sizeof(struct flb_stacktrace));
    st->state = backtrace_create_state(prog,
                                       BACKTRACE_SUPPORTS_THREADS,
                                       flb_stacktrace_error_callback, NULL);
}

static inline void flb_stacktrace_print(struct flb_stacktrace *st)
{
    backtrace_full(st->state, 3, flb_stacktrace_print_callback,
                   flb_stacktrace_error_callback, st);
}

#endif
#endif