Austin Schuh | 812d0d1 | 2021-11-04 20:16:48 -0700 | [diff] [blame^] | 1 | // Copyright (c) FIRST and other WPILib contributors. |
| 2 | // Open Source Software; you can modify and/or share it under the terms of |
| 3 | // the WPILib BSD license file in the root directory of this project. |
Brian Silverman | 8fce748 | 2020-01-05 13:18:21 -0800 | [diff] [blame] | 4 | |
| 5 | #include "wpi/StackTrace.h" |
| 6 | |
| 7 | #include <execinfo.h> |
| 8 | |
| 9 | #include "wpi/Demangle.h" |
| 10 | #include "wpi/SmallString.h" |
Austin Schuh | 812d0d1 | 2021-11-04 20:16:48 -0700 | [diff] [blame^] | 11 | #include "wpi/StringExtras.h" |
Brian Silverman | 8fce748 | 2020-01-05 13:18:21 -0800 | [diff] [blame] | 12 | #include "wpi/raw_ostream.h" |
| 13 | |
| 14 | namespace wpi { |
| 15 | |
| 16 | std::string GetStackTrace(int offset) { |
| 17 | void* stackTrace[128]; |
| 18 | int stackSize = backtrace(stackTrace, 128); |
| 19 | char** mangledSymbols = backtrace_symbols(stackTrace, stackSize); |
| 20 | wpi::SmallString<1024> buf; |
| 21 | wpi::raw_svector_ostream trace(buf); |
| 22 | |
| 23 | for (int i = offset; i < stackSize; i++) { |
| 24 | // Only print recursive functions once in a row. |
| 25 | if (i == 0 || stackTrace[i] != stackTrace[i - 1]) { |
Austin Schuh | 1e69f94 | 2020-11-14 15:06:14 -0800 | [diff] [blame] | 26 | // extract just function name from "pathToExe(functionName+offset)" |
Austin Schuh | 812d0d1 | 2021-11-04 20:16:48 -0700 | [diff] [blame^] | 27 | std::string_view sym = split(mangledSymbols[i], '(').second; |
| 28 | std::string_view offset; |
| 29 | std::tie(sym, offset) = split(sym, '+'); |
| 30 | std::string_view addr; |
| 31 | std::tie(offset, addr) = split(offset, ')'); |
| 32 | trace << "\tat " << Demangle(sym) << " + " << offset << addr << "\n"; |
Brian Silverman | 8fce748 | 2020-01-05 13:18:21 -0800 | [diff] [blame] | 33 | } |
| 34 | } |
| 35 | |
| 36 | std::free(mangledSymbols); |
| 37 | |
Austin Schuh | 812d0d1 | 2021-11-04 20:16:48 -0700 | [diff] [blame^] | 38 | return std::string{trace.str()}; |
Brian Silverman | 8fce748 | 2020-01-05 13:18:21 -0800 | [diff] [blame] | 39 | } |
| 40 | |
| 41 | } // namespace wpi |