File indexing completed on 2024-05-12 17:15:55

0001 /*
0002     SPDX-FileCopyrightText: 2019 Volodymyr Nikolaichuk <nikolaychuk.volodymyr@gmail.com>
0003 
0004     SPDX-License-Identifier: LGPL-2.1-or-later
0005 */
0006 
0007 /**
0008  * @brief A unwind-tables based backtrace.
0009  */
0010 
0011 #include "trace.h"
0012 
0013 #include <cstdint>
0014 #include <cstdio>
0015 #include <unwind.h>
0016 
0017 namespace {
0018 
0019 struct backtrace
0020 {
0021     void** data = nullptr;
0022     int ctr = 0;
0023     int max_size = 0;
0024 };
0025 
0026 _Unwind_Reason_Code unwind_backtrace_callback(struct _Unwind_Context* context, void* arg)
0027 {
0028     backtrace* trace = static_cast<backtrace*>(arg);
0029 
0030     uintptr_t pc = _Unwind_GetIP(context);
0031     if (pc && trace->ctr < trace->max_size - 1) {
0032         trace->data[trace->ctr++] = (void*)(pc);
0033     }
0034 
0035     return _URC_NO_REASON;
0036 }
0037 
0038 }
0039 
0040 void Trace::setup()
0041 {
0042 }
0043 
0044 void Trace::print()
0045 {
0046     Trace trace;
0047     trace.fill(1);
0048     for (auto ip : trace) {
0049         fprintf(stderr, "%p\n", ip);
0050     }
0051 }
0052 
0053 int Trace::unwind(void** data)
0054 {
0055     backtrace trace;
0056     trace.data = data;
0057     trace.max_size = MAX_SIZE;
0058 
0059     _Unwind_Backtrace(unwind_backtrace_callback, &trace);
0060     return trace.ctr;
0061 }