2 * Copyright 2016 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include <folly/experimental/exception_tracer/ExceptionAbi.h>
20 #include <folly/experimental/exception_tracer/StackTrace.h>
21 #include <folly/experimental/exception_tracer/ExceptionTracer.h>
22 #include <folly/experimental/exception_tracer/ExceptionTracerLib.h>
23 #include <folly/experimental/symbolizer/Symbolizer.h>
25 using namespace folly::exception_tracer;
29 // If we somehow ended up in an invalid state, we don't want to print any stack
30 // trace at all because in could be bogus
31 FOLLY_TLS bool invalid;
33 FOLLY_TLS StackTraceStack activeExceptions;
34 FOLLY_TLS StackTraceStack caughtExceptions;
38 // This function is exported and may be found via dlsym(RTLD_NEXT, ...)
39 extern "C" StackTraceStack* getExceptionStackTraceStack() {
40 return invalid ? nullptr : &caughtExceptions;
45 void addActiveException() {
46 // Capture stack trace
48 if (!activeExceptions.pushCurrent()) {
49 activeExceptions.clear();
50 caughtExceptions.clear();
56 void moveTopException(StackTraceStack& from, StackTraceStack& to) {
60 if (!to.moveTopFrom(from)) {
69 registerCxaThrowCallback(
70 [](void*, std::type_info*, void (*)(void*)) { addActiveException(); });
72 registerCxaBeginCatchCallback(
73 [](void*) { moveTopException(activeExceptions, caughtExceptions); });
75 registerCxaRethrowCallback(
76 []() { moveTopException(caughtExceptions, activeExceptions); });
78 registerCxaEndCatchCallback([]() {
83 __cxxabiv1::__cxa_exception* top =
84 __cxxabiv1::__cxa_get_globals_fast()->caughtExceptions;
85 // This is gcc specific and not specified in the ABI:
86 // abs(handlerCount) is the number of active handlers, it's negative
87 // for rethrown exceptions and positive (always 1) for regular
89 // In the rethrow case, we've already popped the exception off the
90 // caught stack, so we don't do anything here.
91 if (top->handlerCount == 1) {
92 if (!caughtExceptions.pop()) {
93 activeExceptions.clear();
99 registerRethrowExceptionCallback(
100 [](std::exception_ptr) { addActiveException(); });
103 ::folly::exception_tracer::installHandlers();
109 Initializer initializer;