Apply clang-format to folly/experimental/exception_tracer/ (headers)
[folly.git] / folly / experimental / exception_tracer / ExceptionTracer.cpp
1 /*
2  * Copyright 2017 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <folly/experimental/exception_tracer/ExceptionTracer.h>
18
19 #include <exception>
20 #include <iostream>
21
22 #include <dlfcn.h>
23
24 #include <glog/logging.h>
25
26 #include <folly/String.h>
27 #include <folly/experimental/exception_tracer/ExceptionAbi.h>
28 #include <folly/experimental/exception_tracer/StackTrace.h>
29 #include <folly/experimental/symbolizer/Symbolizer.h>
30
31 namespace {
32
33 using namespace ::folly::exception_tracer;
34 using namespace ::folly::symbolizer;
35 using namespace __cxxabiv1;
36
37 extern "C" {
38 StackTraceStack* getExceptionStackTraceStack(void) __attribute__((__weak__));
39 typedef StackTraceStack* (*GetExceptionStackTraceStackType)(void);
40 GetExceptionStackTraceStackType getExceptionStackTraceStackFn;
41 }
42
43 }  // namespace
44
45 namespace folly {
46 namespace exception_tracer {
47
48 std::ostream& operator<<(std::ostream& out, const ExceptionInfo& info) {
49   printExceptionInfo(out, info, SymbolizePrinter::COLOR_IF_TTY);
50   return out;
51 }
52
53 void printExceptionInfo(
54     std::ostream& out,
55     const ExceptionInfo& info,
56     int options) {
57   out << "Exception type: ";
58   if (info.type) {
59     out << folly::demangle(*info.type);
60   } else {
61     out << "(unknown type)";
62   }
63   out << " (" << info.frames.size()
64       << (info.frames.size() == 1 ? " frame" : " frames")
65       << ")\n";
66   try {
67     size_t frameCount = info.frames.size();
68
69     // Skip our own internal frames
70     static constexpr size_t kInternalFramesNumber = 3;
71     if (frameCount > kInternalFramesNumber) {
72       auto addresses = info.frames.data() + kInternalFramesNumber;
73       frameCount -= kInternalFramesNumber;
74
75       std::vector<SymbolizedFrame> frames;
76       frames.resize(frameCount);
77
78       Symbolizer symbolizer(
79           (options & SymbolizePrinter::NO_FILE_AND_LINE)
80               ? Dwarf::LocationInfoMode::DISABLED
81               : Symbolizer::kDefaultLocationInfoMode);
82       symbolizer.symbolize(addresses, frames.data(), frameCount);
83
84       OStreamSymbolizePrinter osp(out, options);
85       osp.println(addresses, frames.data(), frameCount);
86     }
87   } catch (const std::exception& e) {
88     out << "\n !! caught " << folly::exceptionStr(e) << "\n";
89   } catch (...) {
90     out << "\n !!! caught unexpected exception\n";
91   }
92 }
93
94 namespace {
95
96 /**
97  * Is this a standard C++ ABI exception?
98  *
99  * Dependent exceptions (thrown via std::rethrow_exception) aren't --
100  * exc doesn't actually point to a __cxa_exception structure, but
101  * the offset of unwindHeader is correct, so exc->unwindHeader actually
102  * returns a _Unwind_Exception object.  Yeah, it's ugly like that.
103  */
104 bool isAbiCppException(const __cxa_exception* exc) {
105   // The least significant four bytes must be "C++\0"
106   static const uint64_t cppClass =
107     ((uint64_t)'C' << 24) |
108     ((uint64_t)'+' << 16) |
109     ((uint64_t)'+' << 8);
110   return (exc->unwindHeader.exception_class & 0xffffffff) == cppClass;
111 }
112
113 }  // namespace
114
115 std::vector<ExceptionInfo> getCurrentExceptions() {
116   struct Once {
117     Once() {
118       // See if linked in with us (getExceptionStackTraceStack is weak)
119       getExceptionStackTraceStackFn = getExceptionStackTraceStack;
120
121       if (!getExceptionStackTraceStackFn) {
122         // Nope, see if it's in a shared library
123         getExceptionStackTraceStackFn =
124           (GetExceptionStackTraceStackType)dlsym(
125               RTLD_NEXT, "getExceptionStackTraceStack");
126       }
127     }
128   };
129   static Once once;
130
131   std::vector<ExceptionInfo> exceptions;
132   auto currentException = __cxa_get_globals()->caughtExceptions;
133   if (!currentException) {
134     return exceptions;
135   }
136
137   StackTraceStack* traceStack = nullptr;
138   if (!getExceptionStackTraceStackFn) {
139     static bool logged = false;
140     if (!logged) {
141       LOG(WARNING)
142         << "Exception tracer library not linked, stack traces not available";
143       logged = true;
144     }
145   } else if ((traceStack = getExceptionStackTraceStackFn()) == nullptr) {
146     static bool logged = false;
147     if (!logged) {
148       LOG(WARNING)
149         << "Exception stack trace invalid, stack traces not available";
150       logged = true;
151     }
152   }
153
154   StackTrace* trace = traceStack ? traceStack->top() : nullptr;
155   while (currentException) {
156     ExceptionInfo info;
157     // Dependent exceptions (thrown via std::rethrow_exception) aren't
158     // standard ABI __cxa_exception objects, and are correctly labeled as
159     // such in the exception_class field.  We could try to extract the
160     // primary exception type in horribly hacky ways, but, for now, nullptr.
161     info.type =
162       isAbiCppException(currentException) ?
163       currentException->exceptionType :
164       nullptr;
165     if (traceStack) {
166       CHECK(trace) << "Invalid trace stack!";
167       info.frames.assign(trace->addresses,
168                          trace->addresses + trace->frameCount);
169       trace = traceStack->next(trace);
170     }
171     currentException = currentException->nextException;
172     exceptions.push_back(std::move(info));
173   }
174   CHECK(!trace) << "Invalid trace stack!";
175
176   return exceptions;
177 }
178
179 namespace {
180
181 std::terminate_handler origTerminate = abort;
182 std::unexpected_handler origUnexpected = abort;
183
184 void dumpExceptionStack(const char* prefix) {
185   auto exceptions = getCurrentExceptions();
186   if (exceptions.empty()) {
187     return;
188   }
189   LOG(ERROR) << prefix << ", exception stack follows";
190   for (auto& exc : exceptions) {
191     LOG(ERROR) << exc << "\n";
192   }
193   LOG(ERROR) << "exception stack complete";
194 }
195
196 void terminateHandler() {
197   dumpExceptionStack("terminate() called");
198   origTerminate();
199 }
200
201 void unexpectedHandler() {
202   dumpExceptionStack("Unexpected exception");
203   origUnexpected();
204 }
205
206 }  // namespace
207
208 void installHandlers() {
209   struct Once {
210     Once() {
211       origTerminate = std::set_terminate(terminateHandler);
212       origUnexpected = std::set_unexpected(unexpectedHandler);
213     }
214   };
215   static Once once;
216 }
217
218 }  // namespace exception_tracer
219 }  // namespace folly