I took this code and modified it to look like this:
std::string Backtrace(int skip = 1)
{
void *callstack[128];
const int nMaxFrames = sizeof(callstack) / sizeof(callstack[0]);
char buf[1024];
int nFrames = backtrace(callstack, nMaxFrames);
char **symbols = backtrace_symbols(callstack, nFrames);
string message = "";
for (int i = skip; i < nFrames; i++) {
Dl_info info;
if (dladdr(callstack[i], &info)) {
char *demangled = nullptr;
int status;
demangled = abi::__cxa_demangle(info.dli_sname, NULL, 0, &status);
if(demangled != nullptr)
message += string(demangled) + ": " +
to_string((char *)callstack[i] - (char *)info.dli_saddr) + "\n";
free(demangled);
}
}
free(symbols);
if (nFrames == nMaxFrames)
message += "[truncated]\n";
return message;
}
This is supposed to print a stack trace of my current program to identify where things went awry without having to turn on gdb every time my program crashes.
When I run this code (in a state guaranteed to trigger an issue) I get the following stack trace:
DebugCallback(VkDebugUtilsMessageSeverityFlagBitsEXT, unsigned int, VkDebugUtilsMessengerCallbackDataEXT const*, void*): 146
vk::DispatchLoaderStatic::vkQueueSubmit(VkQueue_T*, unsigned int, VkSubmitInfo const*, VkFence_T*) const: 50
Display::UpdateFrame(): 1088
RenderingPipeline::RenderFrame(vk::Buffer&, vk::Buffer&, Image&, unsigned int): 63
RenderHandler::RenderHandler(Window*, HardwareInterface*, Display*, Memory*): 784
My goal is to try to print as much relevant information as possible. (file, function, line). Now, I thought that the instruction:
(char *)callstack[i] - (char *)info.dli_saddr) which I copied from the original script, would get me the line where the code was called, but for example the file where Display::UpdateFrame() is defined doesn;t even have 1000 lines, so trivially that number isn't the number of the calling code in the original file.
Is there a way to obtain this information with stack trace similarly to how GDB does it?
i.e if the function was called in the source code at
File: Display.hpp
Function: Display::UpdateFrame()
Line: 227
Can I retrieve that information at runtime using stacktrace?