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