Brian Silverman | 8fce748 | 2020-01-05 13:18:21 -0800 | [diff] [blame] | 1 | /*----------------------------------------------------------------------------*/ |
Austin Schuh | 1e69f94 | 2020-11-14 15:06:14 -0800 | [diff] [blame^] | 2 | /* Copyright (c) 2008-2020 FIRST. All Rights Reserved. */ |
Brian Silverman | 8fce748 | 2020-01-05 13:18:21 -0800 | [diff] [blame] | 3 | /* 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 Schuh | 1e69f94 | 2020-11-14 15:06:14 -0800 | [diff] [blame^] | 14 | #include "wpi/StringRef.h" |
Brian Silverman | 8fce748 | 2020-01-05 13:18:21 -0800 | [diff] [blame] | 15 | #include "wpi/raw_ostream.h" |
| 16 | |
| 17 | namespace wpi { |
| 18 | |
| 19 | std::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 Schuh | 1e69f94 | 2020-11-14 15:06:14 -0800 | [diff] [blame^] | 29 | // 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 Silverman | 8fce748 | 2020-01-05 13:18:21 -0800 | [diff] [blame] | 34 | } |
| 35 | } |
| 36 | |
| 37 | std::free(mangledSymbols); |
| 38 | |
| 39 | return trace.str(); |
| 40 | } |
| 41 | |
| 42 | } // namespace wpi |