blob: 004eb39ad116fa6de5a24d698c3bba7d3b73add2 [file] [log] [blame]
Brian Silverman8fce7482020-01-05 13:18:21 -08001/*----------------------------------------------------------------------------*/
Austin Schuh1e69f942020-11-14 15:06:14 -08002/* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */
Brian Silverman8fce7482020-01-05 13:18:21 -08003/* Open Source Software - may be modified and shared by FRC teams. The code */
4/* must be accompanied by the FIRST BSD license file in the root directory of */
5/* the project. */
6/*----------------------------------------------------------------------------*/
7
8#include "wpi/StackTrace.h"
9
10#include <execinfo.h>
11
12#include "wpi/Demangle.h"
13#include "wpi/SmallString.h"
Austin Schuh1e69f942020-11-14 15:06:14 -080014#include "wpi/StringRef.h"
Brian Silverman8fce7482020-01-05 13:18:21 -080015#include "wpi/raw_ostream.h"
16
17namespace wpi {
18
19std::string GetStackTrace(int offset) {
20 void* stackTrace[128];
21 int stackSize = backtrace(stackTrace, 128);
22 char** mangledSymbols = backtrace_symbols(stackTrace, stackSize);
23 wpi::SmallString<1024> buf;
24 wpi::raw_svector_ostream trace(buf);
25
26 for (int i = offset; i < stackSize; i++) {
27 // Only print recursive functions once in a row.
28 if (i == 0 || stackTrace[i] != stackTrace[i - 1]) {
Austin Schuh1e69f942020-11-14 15:06:14 -080029 // extract just function name from "pathToExe(functionName+offset)"
30 StringRef sym{mangledSymbols[i]};
31 sym = sym.split('(').second;
32 sym = sym.split('+').first;
33 trace << "\tat " << Demangle(sym) << "\n";
Brian Silverman8fce7482020-01-05 13:18:21 -080034 }
35 }
36
37 std::free(mangledSymbols);
38
39 return trace.str();
40}
41
42} // namespace wpi