From a1ef7f924109aa0c8b4c9d629dc0b0a7ce69ad96 Mon Sep 17 00:00:00 2001 From: Jason Gauci Date: Wed, 29 Jul 2020 13:30:19 -0500 Subject: [PATCH] Import UST --- .../UniversalStacktrace/.gitignore | 36 ++ .../UniversalStacktrace/.gitmodules | 3 + .../UniversalStacktrace/CMakeLists.txt | 57 +++ external_imported/UniversalStacktrace/LICENSE | 201 ++++++++ .../UniversalStacktrace/README.md | 2 + .../UniversalStacktrace/test/BasicTest.cpp | 31 ++ .../UniversalStacktrace/test/Main.cpp | 13 + .../UniversalStacktrace/ust/ust.hpp | 441 ++++++++++++++++++ 8 files changed, 784 insertions(+) create mode 100644 external_imported/UniversalStacktrace/.gitignore create mode 100644 external_imported/UniversalStacktrace/.gitmodules create mode 100644 external_imported/UniversalStacktrace/CMakeLists.txt create mode 100644 external_imported/UniversalStacktrace/LICENSE create mode 100644 external_imported/UniversalStacktrace/README.md create mode 100644 external_imported/UniversalStacktrace/test/BasicTest.cpp create mode 100644 external_imported/UniversalStacktrace/test/Main.cpp create mode 100644 external_imported/UniversalStacktrace/ust/ust.hpp diff --git a/external_imported/UniversalStacktrace/.gitignore b/external_imported/UniversalStacktrace/.gitignore new file mode 100644 index 000000000..4a66d697e --- /dev/null +++ b/external_imported/UniversalStacktrace/.gitignore @@ -0,0 +1,36 @@ +.vscode +build +msvc_build + +# Prerequisites +*.d + +# Compiled Object files +*.slo +*.lo +*.o +*.obj + +# Precompiled Headers +*.gch +*.pch + +# Compiled Dynamic libraries +*.so +*.dylib +*.dll + +# Fortran module files +*.mod +*.smod + +# Compiled Static libraries +*.lai +*.la +*.a +*.lib + +# Executables +*.exe +*.out +*.app diff --git a/external_imported/UniversalStacktrace/.gitmodules b/external_imported/UniversalStacktrace/.gitmodules new file mode 100644 index 000000000..800345d16 --- /dev/null +++ b/external_imported/UniversalStacktrace/.gitmodules @@ -0,0 +1,3 @@ +[submodule "external/Catch2"] + path = external/Catch2 + url = https://github.com/catchorg/Catch2.git diff --git a/external_imported/UniversalStacktrace/CMakeLists.txt b/external_imported/UniversalStacktrace/CMakeLists.txt new file mode 100644 index 000000000..14a799ff0 --- /dev/null +++ b/external_imported/UniversalStacktrace/CMakeLists.txt @@ -0,0 +1,57 @@ +cmake_minimum_required (VERSION 3.0.2) +project (UniversalStackTrace VERSION 0.0.1) + +# Enable C++-17 +SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -std=c++17") + +# Enable debug info +SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g -ggdb3") +SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g -ggdb3") + +IF(APPLE) +# Turn off address randomizing to get debug prints +SET(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -fno-pie") +ELSEIF(UNIX) +# Enable dynamic relocation +SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -rdynamic") +ENDIF() + +include_directories( + external + ust + ) + +IF(MINGW) +SET( + CORE_LIBRARIES + + dbghelp +) +ELSEIF(WIN32) +SET( + CORE_LIBRARIES + + Shlwapi + dbghelp +) +ELSE() +SET( + CORE_LIBRARIES +) +ENDIF() + +add_executable( + ust-test + + test/Main.cpp + test/BasicTest.cpp +) +target_link_libraries( + ust-test + + ${CORE_LIBRARIES} +) +add_test( + ust-test + ust-test +) diff --git a/external_imported/UniversalStacktrace/LICENSE b/external_imported/UniversalStacktrace/LICENSE new file mode 100644 index 000000000..261eeb9e9 --- /dev/null +++ b/external_imported/UniversalStacktrace/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/external_imported/UniversalStacktrace/README.md b/external_imported/UniversalStacktrace/README.md new file mode 100644 index 000000000..6976c2124 --- /dev/null +++ b/external_imported/UniversalStacktrace/README.md @@ -0,0 +1,2 @@ +# UniversalStacktrace +C++ Stacktrace for windows linux and os/x diff --git a/external_imported/UniversalStacktrace/test/BasicTest.cpp b/external_imported/UniversalStacktrace/test/BasicTest.cpp new file mode 100644 index 000000000..7e6d878c1 --- /dev/null +++ b/external_imported/UniversalStacktrace/test/BasicTest.cpp @@ -0,0 +1,31 @@ +#include "Catch2/include/catch.hpp" + +#include "ust.hpp" + +inline void checkBetween(int x, int low, int high) { + REQUIRE(x >= low); + REQUIRE(x <= high); +} + +void f2(); +void f(); + +void f() { f2(); } + +void f2() { + auto traceEntries = ust::generate(); + std::cout << traceEntries << std::endl; + std::string fileName = std::string(__FILE__); + fileName = ust::ustBasenameString(fileName); + REQUIRE(ust::ustBasenameString(traceEntries.entries[0].sourceFileName) == + fileName); + checkBetween(traceEntries.entries[0].lineNumber, __LINE__ - 6, __LINE__ - 5); + REQUIRE(ust::ustBasenameString(traceEntries.entries[1].sourceFileName) == + fileName); + REQUIRE(traceEntries.entries[1].lineNumber == __LINE__ - 12); + REQUIRE(ust::ustBasenameString(traceEntries.entries[2].sourceFileName) == + fileName); + REQUIRE(traceEntries.entries[2].lineNumber == __LINE__ + 3); +} + +TEST_CASE("ConnectionTest", "[ConnectionTest]") { f(); } diff --git a/external_imported/UniversalStacktrace/test/Main.cpp b/external_imported/UniversalStacktrace/test/Main.cpp new file mode 100644 index 000000000..1e916fc16 --- /dev/null +++ b/external_imported/UniversalStacktrace/test/Main.cpp @@ -0,0 +1,13 @@ +#define CATCH_CONFIG_RUNNER +#include "Catch2/single_include/catch2/catch.hpp" + +#include + +int main(int argc, char **argv) { + std::cout << "Beginning tests" << std::endl; + srand(1); + + int result = Catch::Session().run(argc, argv); + + return result; +} diff --git a/external_imported/UniversalStacktrace/ust/ust.hpp b/external_imported/UniversalStacktrace/ust/ust.hpp new file mode 100644 index 000000000..be7607e09 --- /dev/null +++ b/external_imported/UniversalStacktrace/ust/ust.hpp @@ -0,0 +1,441 @@ +#pragma once + +#ifdef _WIN32 +#include +#include +#else +#include +#include +#include +#include +#endif + +#ifdef _MSC_VER +#include +#else +#include +#if defined(__MINGW32__) || defined(__MINGW64__) +#define WEXITSTATUS(w) (((w) >> 8) & 0xff) +#else +#include +#endif +#endif + +#ifdef __APPLE__ +#include +#endif + +#ifdef __linux__ +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace ust { +template +inline void split(const std::string &s, char delim, Out result) { + std::stringstream ss; + ss.str(s); + std::string item; + while (std::getline(ss, item, delim)) { + *(result++) = item; + } +} + +inline std::vector split(const std::string &s, char delim) { + std::vector elems; + split(s, delim, std::back_inserter(elems)); + return elems; +} + +#ifndef _MSC_VER +// Needed for calling addr2line / atos +inline std::string SystemToStr(const char *cmd) { + std::array buffer; + std::string result; + FILE *pipe = popen(cmd, "r"); + if (!pipe) { + throw std::runtime_error("popen() failed!"); + } + while (!feof(pipe)) { + if (fgets(buffer.data(), 128, pipe) != nullptr) result += buffer.data(); + } + auto closeValue = pclose(pipe); + auto exitCode = WEXITSTATUS(closeValue); + if (exitCode) { + return ""; + } + return result; +} +#endif + +#ifdef _MSC_VER +// Replacement for basename() +inline char *ustBasename(char *path) { + PathStripPathA(path); + return path; +} +inline std::string ustBasenameString(std::string input) { + PathStripPathA(&input[0]); + return input; +} +#else +inline char *ustBasename(char *path) { return ::basename(path); } +inline std::string ustBasenameString(std::string input) { + input = std::string(::basename(&input[0])); + return input; +} +#endif + +inline std::string addressToString(uint64_t address) { + std::ostringstream ss; + ss << "0x" << std::hex << uint64_t(address); + return ss.str(); +} + +static const int MAX_STACK_FRAMES = 64; +class StackTraceEntry { + public: + StackTraceEntry(int _stackIndex, const std::string &_address, + const std::string &_binaryFileName, + const std::string &_functionName, + const std::string &_sourceFileName, int _lineNumber) + : stackIndex(_stackIndex), + address(_address), + binaryFileName(_binaryFileName), + functionName(_functionName), + sourceFileName(_sourceFileName), + lineNumber(_lineNumber) {} + + int stackIndex; + std::string address; + std::string binaryFileName; + std::string functionName; + std::string sourceFileName; + int lineNumber; + + friend std::ostream &operator<<(std::ostream &ss, const StackTraceEntry &si); + + private: + StackTraceEntry(void); +}; + +inline std::ostream &operator<<(std::ostream &ss, const StackTraceEntry &si) { + ss << "[" << si.stackIndex << "] " << si.address; + if (!si.functionName.empty()) { + ss << " " << si.functionName; + } + if (si.lineNumber > 0) { + std::string sourceFileNameCopy = si.sourceFileName; + ss << " (" << ustBasename(&sourceFileNameCopy[0]) << ":" << si.lineNumber + << ")"; + } + return ss; +} + +class StackTrace { + public: + StackTrace(const std::vector &_entries) + : entries(_entries) {} + friend std::ostream &operator<<(std::ostream &ss, const StackTrace &si); + + std::vector entries; +}; + +inline std::ostream &operator<<(std::ostream &ss, const StackTrace &si) { + for (const auto &it : si.entries) { + ss << it << "\n"; + } + return ss; +} + +#ifdef _MSC_VER +// Visual studio uses StackWalker to get stack trace info +inline StackTrace generate() { + std::vector stackTrace; + HANDLE process = GetCurrentProcess(); + HANDLE thread = GetCurrentThread(); + + CONTEXT context; + memset(&context, 0, sizeof(CONTEXT)); + context.ContextFlags = CONTEXT_FULL; + RtlCaptureContext(&context); + + SymSetOptions(SYMOPT_LOAD_LINES); + SymInitialize(process, NULL, TRUE); + + DWORD image; + STACKFRAME64 stackframe; + ZeroMemory(&stackframe, sizeof(STACKFRAME64)); + +#ifdef _M_IX86 + image = IMAGE_FILE_MACHINE_I386; + stackframe.AddrPC.Offset = context.Eip; + stackframe.AddrPC.Mode = AddrModeFlat; + stackframe.AddrFrame.Offset = context.Ebp; + stackframe.AddrFrame.Mode = AddrModeFlat; + stackframe.AddrStack.Offset = context.Esp; + stackframe.AddrStack.Mode = AddrModeFlat; +#elif _M_X64 + image = IMAGE_FILE_MACHINE_AMD64; + stackframe.AddrPC.Offset = context.Rip; + stackframe.AddrPC.Mode = AddrModeFlat; + stackframe.AddrFrame.Offset = context.Rsp; + stackframe.AddrFrame.Mode = AddrModeFlat; + stackframe.AddrStack.Offset = context.Rsp; + stackframe.AddrStack.Mode = AddrModeFlat; +#elif _M_IA64 + image = IMAGE_FILE_MACHINE_IA64; + stackframe.AddrPC.Offset = context.StIIP; + stackframe.AddrPC.Mode = AddrModeFlat; + stackframe.AddrFrame.Offset = context.IntSp; + stackframe.AddrFrame.Mode = AddrModeFlat; + stackframe.AddrBStore.Offset = context.RsBSP; + stackframe.AddrBStore.Mode = AddrModeFlat; + stackframe.AddrStack.Offset = context.IntSp; + stackframe.AddrStack.Mode = AddrModeFlat; +#endif + + // Skip the first frame + BOOL result = StackWalk64(image, process, thread, &stackframe, &context, NULL, + SymFunctionTableAccess64, SymGetModuleBase64, NULL); + if (result) { + for (int i = 0; i < MAX_STACK_FRAMES; i++) { + BOOL result = + StackWalk64(image, process, thread, &stackframe, &context, NULL, + SymFunctionTableAccess64, SymGetModuleBase64, NULL); + + if (!result) { + break; + } + + if (stackframe.AddrPC.Offset == stackframe.AddrReturn.Offset) break; + + const int cnBufferSize = 4096; + unsigned char byBuffer[sizeof(IMAGEHLP_SYMBOL64) + cnBufferSize]; + IMAGEHLP_SYMBOL64 *pSymbol = (IMAGEHLP_SYMBOL64 *)byBuffer; + memset(pSymbol, 0, sizeof(IMAGEHLP_SYMBOL64) + cnBufferSize); + pSymbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64); + pSymbol->MaxNameLength = cnBufferSize; + + std::string binaryFileName; + std::string functionName; + DWORD64 displacement = 0; + if (SymGetSymFromAddr64(process, stackframe.AddrPC.Offset, &displacement, + pSymbol)) { + functionName = std::string(pSymbol->Name); + } + + DWORD displacement32 = 0; + IMAGEHLP_LINE64 theLine; + memset(&theLine, 0, sizeof(theLine)); + theLine.SizeOfStruct = sizeof(theLine); + std::string sourceFileName; + int lineNumber = -1; + if (SymGetLineFromAddr64(process, stackframe.AddrPC.Offset, + &displacement32, &theLine)) { + sourceFileName = std::string(theLine.FileName); + lineNumber = int(theLine.LineNumber); + } + + stackTrace.push_back(StackTraceEntry( + i, addressToString(stackframe.AddrPC.Offset), binaryFileName, + functionName, sourceFileName, lineNumber)); + } + } + + SymCleanup(process); + + return StackTrace(stackTrace); +#else +// Non-visual studio compilers use a mess of things: +// Apple uses backtrace() + atos +// Linux uses backtrace() + addr2line +// MinGW uses CaptureStackBackTrace() + addr2line +inline StackTrace generate() { + std::vector stackTrace; + std::map baseAddresses; + std::string line; + std::string procMapFileName = std::string("/proc/self/maps"); + std::ifstream infile(procMapFileName.c_str()); + // Some OSes don't have /proc/*/maps, so we won't have base addresses for them + while (std::getline(infile, line)) { + std::istringstream iss(line); + std::string addressRange; + std::string perms; + std::string offset; + std::string device; + std::string inode; + std::string path; + + if (!(iss >> addressRange >> perms >> offset >> device >> inode >> path)) { + break; + } // error + uint64_t baseAddress = stoull(split(addressRange, '-')[0], NULL, 16); + if (baseAddresses.find(path) == baseAddresses.end() || + baseAddresses[path] > baseAddress) { + baseAddresses[path] = baseAddress; + } + } + + void *stack[MAX_STACK_FRAMES]; + int numFrames; +#if defined(__MINGW32__) || defined(__MINGW64__) + numFrames = CaptureStackBackTrace(1, MAX_STACK_FRAMES, stack, NULL); + + for (unsigned short a = 0; a < numFrames; a++) { + HMODULE moduleHandle; + GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, + (const char *)stack[a], &moduleHandle); + std::string fileName(4096, '\0'); + auto fileNameSize = + GetModuleFileNameA(moduleHandle, &fileName[0], fileName.size()); + if (fileNameSize == 0 || fileNameSize == (ssize_t)fileName.size()) { + /* Error, possibly not enough space. */ + fileName = ""; + } else { + fileName = fileName.substr(0, fileNameSize); + std::replace(fileName.begin(), fileName.end(), '\\', '/'); + } + std::string addr = addressToString(uint64_t(stack[a])); + StackTraceEntry entry(a, addr, fileName, "", "", -1); + stackTrace.push_back(entry); + } +#else + numFrames = backtrace(stack, MAX_STACK_FRAMES); + memmove(stack, stack + 1, sizeof(void *) * (numFrames - 1)); + numFrames--; + + char **strings = backtrace_symbols(stack, numFrames); + for (int a = 0; a < numFrames; ++a) { + std::string addr; + std::string fileName; + std::string functionName; + + const std::string line(strings[a]); +#ifdef __APPLE__ + // Example: ust-test 0x000000010001e883 + // _ZNK5Catch21TestInvokerAsFunction6invokeEv + 19 + auto p = line.find("0x"); + if (p != std::string::npos) { + addr = line.substr(p); + auto spaceLoc = addr.find(" "); + functionName = addr.substr(spaceLoc + 1); + functionName = functionName.substr(0, functionName.find(" +")); + addr = addr.substr(0, spaceLoc); + } +#else + // Example: ./ust-test(_ZNK5Catch21TestInvokerAsFunction6invokeEv+0x16) + // [0x55f1278af96e] + auto parenStart = line.find("("); + auto parenEnd = line.find(")"); + fileName = line.substr(0, parenStart); + // Convert filename to canonical path + char buf[PATH_MAX]; + ::realpath(fileName.c_str(), buf); + fileName = std::string(buf); + functionName = line.substr(parenStart + 1, parenEnd - (parenStart + 1)); + // Strip off the offset from the name + functionName = functionName.substr(0, functionName.find("+")); + if (baseAddresses.find(fileName) != baseAddresses.end()) { + // Make address relative to process start + addr = addressToString(uint64_t(stack[a]) - baseAddresses[fileName]); + } else { + addr = addressToString(uint64_t(stack[a])); + } +#endif + // Perform demangling if parsed properly + if (!functionName.empty()) { + int status = 0; + auto demangledFunctionName = + abi::__cxa_demangle(functionName.data(), 0, 0, &status); + // if demangling is successful, output the demangled function name + if (status == 0) { + // Success (see + // http://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-4.3/a01696.html) + functionName = std::string(demangledFunctionName); + } + free(demangledFunctionName); + } + StackTraceEntry entry(a, addr, fileName, functionName, "", -1); + stackTrace.push_back(entry); + } + free(strings); +#endif + +// Fetch source file & line numbers +#ifdef __APPLE__ + std::ostringstream ss; + ss << "atos -p " << std::to_string(getpid()) << " "; + for (int a = 0; a < numFrames; a++) { + ss << "0x" << std::hex << uint64_t(stack[a]) << " "; + } + auto atosOutput = SystemToStr(ss.str().c_str()); + if (atosOutput.length()) { + auto atosLines = split(atosOutput, '\n'); + std::regex fileLineRegex("\\(([^\\(]+):([0-9]+)\\)$"); + for (int a = 0; a < numFrames; a++) { + // Find the filename and line number + std::smatch matches; + if (regex_search(atosLines[a], matches, fileLineRegex)) { + stackTrace[a].sourceFileName = matches[1]; + stackTrace[a].lineNumber = std::stoi(matches[2]); + } + } + } +#else + // Unix & MinGW + std::map > fileAddresses; + std::map > fileData; + for (const auto &it : stackTrace) { + if (it.binaryFileName.length()) { + if (fileAddresses.find(it.binaryFileName) == fileAddresses.end()) { + fileAddresses[it.binaryFileName] = {}; + } + fileAddresses.at(it.binaryFileName).push_back(it.address); + } + } + for (const auto &it : fileAddresses) { + std::string fileName = it.first; + std::ostringstream ss; + ss << "addr2line -C -f -p -e " << fileName << " "; + for (const auto &it2 : it.second) { + ss << it2 << " "; + } + auto addrLineOutput = SystemToStr(ss.str().c_str()); + if (addrLineOutput.length()) { + auto outputLines = split(addrLineOutput, '\n'); + fileData[fileName] = + std::list(outputLines.begin(), outputLines.end()); + } + } + std::regex addrToLineRegex("^(.+?) at (.+):([0-9]+)$"); + for (auto &it : stackTrace) { + if (it.binaryFileName.length() && fileData.find(it.binaryFileName) != fileData.end()) { + std::string outputLine = fileData.at(it.binaryFileName).front(); + fileData.at(it.binaryFileName).pop_front(); + if (outputLine == std::string("?? ??:0")) { + continue; + } + std::smatch matches; + if (regex_search(outputLine, matches, addrToLineRegex)) { + it.functionName = matches[1]; + it.sourceFileName = matches[2]; + it.lineNumber = std::stoi(matches[3]); + } + } + } +#endif + + return StackTrace(stackTrace); +#endif +} +} // namespace ust