kakoune

Fork of kakoune, an acceptable text editor
git clone git://git.laack.co/kakoune.git
Log | Files | Refs

backtrace.cc (1875B)


      1 #include "backtrace.hh"
      2 
      3 #include "string.hh"
      4 #include "format.hh"
      5 
      6 #if defined(__GLIBC__) || defined(__APPLE__)
      7 # include <execinfo.h>
      8 #elif defined(__CYGWIN__)
      9 # include <windows.h>
     10 # include <dbghelp.h>
     11 # include <stdio.h>
     12 #endif
     13 
     14 #if defined(__linux__) || defined(__APPLE__)
     15 # include <cstdlib>
     16 #endif
     17 
     18 namespace Kakoune
     19 {
     20 
     21 Backtrace::Backtrace()
     22 {
     23     #if defined(__GLIBC__) || defined(__APPLE__)
     24     num_frames = backtrace(stackframes, max_frames);
     25     #elif defined(__CYGWIN__)
     26     num_frames = CaptureStackBackTrace(0, max_frames, stackframes, nullptr);
     27     #endif
     28 }
     29 
     30 String Backtrace::desc() const
     31 {
     32     #if defined(__GLIBC__) || defined(__APPLE__)
     33     char** symbols = backtrace_symbols(stackframes, num_frames);
     34     ByteCount size = 0;
     35     for (int i = 0; i < num_frames; ++i)
     36         size += strlen(symbols[i]) + 1;
     37 
     38     String res; res.reserve(size);
     39     for (int i = 0; i < num_frames; ++i)
     40     {
     41         res += symbols[i];
     42         res += "\n";
     43     }
     44     free(symbols);
     45     return res;
     46     #elif defined(__CYGWIN__)
     47     HANDLE process = GetCurrentProcess();
     48 
     49     static bool symbols_initialized = false;
     50     if (not symbols_initialized)
     51     {
     52         SymInitialize(process, nullptr, true);
     53         symbols_initialized = true;
     54     }
     55 
     56     alignas(SYMBOL_INFO) char symbol_info_buffer[sizeof(SYMBOL_INFO) + 256];
     57     SYMBOL_INFO* symbol_info = reinterpret_cast<SYMBOL_INFO*>(symbol_info_buffer);
     58     symbol_info->MaxNameLen = 255;
     59     symbol_info->SizeOfStruct = sizeof(SYMBOL_INFO);
     60 
     61     String res; // res.reserve(num_frames * 276);
     62     for (int i = 0; i < num_frames; ++i)
     63     {
     64         SymFromAddr(process, (DWORD64)stackframes[i], 0, symbol_info);
     65         char desc[276];
     66         format_to(desc, "0x{} ({})\n", hex(symbol_info->Address), symbol_info->Name);
     67         res += desc;
     68     }
     69     return res;
     70     #else
     71     return "<not implemented>";
     72     #endif
     73 }
     74 
     75 }