Path: blob/main/system/lib/libcxxabi/src/cxa_exception.cpp
6173 views
//===----------------------------------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//7// This file implements the "Exception Handling APIs"8// https://itanium-cxx-abi.github.io/cxx-abi/abi-eh.html9//10//===----------------------------------------------------------------------===//1112#include "cxxabi.h"1314#include <exception> // for std::terminate15#include <string.h> // for memset16#include "cxa_exception.h"17#include "cxa_handlers.h"18#include "fallback_malloc.h"19#include "include/atomic_support.h" // from libc++2021#if __has_feature(address_sanitizer)22#include <sanitizer/asan_interface.h>23#endif2425// +---------------------------+-----------------------------+---------------+26// | __cxa_exception | _Unwind_Exception CLNGC++\0 | thrown object |27// +---------------------------+-----------------------------+---------------+28// ^29// |30// +-------------------------------------------------------+31// |32// +---------------------------+-----------------------------+33// | __cxa_dependent_exception | _Unwind_Exception CLNGC++\1 |34// +---------------------------+-----------------------------+3536namespace __cxxabiv1 {3738// Utility routines39static40inline41__cxa_exception*42cxa_exception_from_thrown_object(void* thrown_object)43{44return static_cast<__cxa_exception*>(thrown_object) - 1;45}4647// Note: This is never called when exception_header is masquerading as a48// __cxa_dependent_exception.49static50inline51void*52thrown_object_from_cxa_exception(__cxa_exception* exception_header)53{54return static_cast<void*>(exception_header + 1);55}5657// Get the exception object from the unwind pointer.58// Relies on the structure layout, where the unwind pointer is right in59// front of the user's exception object60static61inline62__cxa_exception*63cxa_exception_from_exception_unwind_exception(_Unwind_Exception* unwind_exception)64{65return cxa_exception_from_thrown_object(unwind_exception + 1 );66}6768// Round s up to next multiple of a.69static inline70size_t aligned_allocation_size(size_t s, size_t a) {71return (s + a - 1) & ~(a - 1);72}7374static inline75size_t cxa_exception_size_from_exception_thrown_size(size_t size) {76return aligned_allocation_size(size + sizeof (__cxa_exception),77alignof(__cxa_exception));78}7980void __setExceptionClass(_Unwind_Exception* unwind_exception, uint64_t newValue) {81::memcpy(&unwind_exception->exception_class, &newValue, sizeof(newValue));82}838485static void setOurExceptionClass(_Unwind_Exception* unwind_exception) {86__setExceptionClass(unwind_exception, kOurExceptionClass);87}8889static void setDependentExceptionClass(_Unwind_Exception* unwind_exception) {90__setExceptionClass(unwind_exception, kOurDependentExceptionClass);91}9293// Is it one of ours?94uint64_t __getExceptionClass(const _Unwind_Exception* unwind_exception) {95// On x86 and some ARM unwinders, unwind_exception->exception_class is96// a uint64_t. On other ARM unwinders, it is a char[8].97// See: http://infocenter.arm.com/help/topic/com.arm.doc.ihi0038b/IHI0038B_ehabi.pdf98// So we just copy it into a uint64_t to be sure.99uint64_t exClass;100::memcpy(&exClass, &unwind_exception->exception_class, sizeof(exClass));101return exClass;102}103104bool __isOurExceptionClass(const _Unwind_Exception* unwind_exception) {105return (__getExceptionClass(unwind_exception) & get_vendor_and_language) ==106(kOurExceptionClass & get_vendor_and_language);107}108109static bool isDependentException(_Unwind_Exception* unwind_exception) {110return (__getExceptionClass(unwind_exception) & 0xFF) == 0x01;111}112113// This does not need to be atomic114static inline int incrementHandlerCount(__cxa_exception *exception) {115return ++exception->handlerCount;116}117118// This does not need to be atomic119static inline int decrementHandlerCount(__cxa_exception *exception) {120return --exception->handlerCount;121}122123/*124If reason isn't _URC_FOREIGN_EXCEPTION_CAUGHT, then the terminateHandler125stored in exc is called. Otherwise the exceptionDestructor stored in126exc is called, and then the memory for the exception is deallocated.127128This is never called for a __cxa_dependent_exception.129*/130static131void132exception_cleanup_func(_Unwind_Reason_Code reason, _Unwind_Exception* unwind_exception)133{134__cxa_exception* exception_header = cxa_exception_from_exception_unwind_exception(unwind_exception);135if (_URC_FOREIGN_EXCEPTION_CAUGHT != reason)136std::__terminate(exception_header->terminateHandler);137// Just in case there exists a dependent exception that is pointing to this,138// check the reference count and only destroy this if that count goes to zero.139__cxa_decrement_exception_refcount(unwind_exception + 1);140}141142static _LIBCXXABI_NORETURN void failed_throw(__cxa_exception* exception_header) {143// Section 2.5.3 says:144// * For purposes of this ABI, several things are considered exception handlers:145// ** A terminate() call due to a throw.146// and147// * Upon entry, Following initialization of the catch parameter,148// a handler must call:149// * void *__cxa_begin_catch(void *exceptionObject );150(void) __cxa_begin_catch(&exception_header->unwindHeader);151std::__terminate(exception_header->terminateHandler);152}153154// Return the offset of the __cxa_exception header from the start of the155// allocated buffer. If __cxa_exception's alignment is smaller than the maximum156// useful alignment for the target machine, padding has to be inserted before157// the header to ensure the thrown object that follows the header is158// sufficiently aligned. This happens if _Unwind_exception isn't double-word159// aligned (on Darwin, for example).160static size_t get_cxa_exception_offset() {161struct S {162} __attribute__((aligned));163164// Compute the maximum alignment for the target machine.165constexpr size_t alignment = alignof(S);166constexpr size_t excp_size = sizeof(__cxa_exception);167constexpr size_t aligned_size =168(excp_size + alignment - 1) / alignment * alignment;169constexpr size_t offset = aligned_size - excp_size;170static_assert((offset == 0 || alignof(_Unwind_Exception) < alignment),171"offset is non-zero only if _Unwind_Exception isn't aligned");172return offset;173}174175extern "C" {176177// Allocate a __cxa_exception object, and zero-fill it.178// Reserve "thrown_size" bytes on the end for the user's exception179// object. Zero-fill the object. If memory can't be allocated, call180// std::terminate. Return a pointer to the memory to be used for the181// user's exception object.182void *__cxa_allocate_exception(size_t thrown_size) throw() {183size_t actual_size = cxa_exception_size_from_exception_thrown_size(thrown_size);184185// Allocate extra space before the __cxa_exception header to ensure the186// start of the thrown object is sufficiently aligned.187size_t header_offset = get_cxa_exception_offset();188char *raw_buffer =189(char *)__aligned_malloc_with_fallback(header_offset + actual_size);190if (NULL == raw_buffer)191std::terminate();192__cxa_exception *exception_header =193static_cast<__cxa_exception *>((void *)(raw_buffer + header_offset));194::memset(exception_header, 0, actual_size);195return thrown_object_from_cxa_exception(exception_header);196}197198199// Free a __cxa_exception object allocated with __cxa_allocate_exception.200void __cxa_free_exception(void *thrown_object) throw() {201// Compute the size of the padding before the header.202size_t header_offset = get_cxa_exception_offset();203char *raw_buffer =204((char *)cxa_exception_from_thrown_object(thrown_object)) - header_offset;205__aligned_free_with_fallback((void *)raw_buffer);206}207208__cxa_exception* __cxa_init_primary_exception(void* object, std::type_info* tinfo,209#ifdef __wasm__210// In Wasm, a destructor returns its argument211void *(_LIBCXXABI_DTOR_FUNC* dest)(void*)) throw() {212#else213void(_LIBCXXABI_DTOR_FUNC* dest)(void*)) throw() {214#endif215__cxa_exception* exception_header = cxa_exception_from_thrown_object(object);216exception_header->referenceCount = 0;217exception_header->unexpectedHandler = std::get_unexpected();218exception_header->terminateHandler = std::get_terminate();219exception_header->exceptionType = tinfo;220exception_header->exceptionDestructor = dest;221setOurExceptionClass(&exception_header->unwindHeader);222exception_header->unwindHeader.exception_cleanup = exception_cleanup_func;223224return exception_header;225}226227// This function shall allocate a __cxa_dependent_exception and228// return a pointer to it. (Really to the object, not past its' end).229// Otherwise, it will work like __cxa_allocate_exception.230void * __cxa_allocate_dependent_exception () {231size_t actual_size = sizeof(__cxa_dependent_exception);232void *ptr = __aligned_malloc_with_fallback(actual_size);233if (NULL == ptr)234std::terminate();235::memset(ptr, 0, actual_size);236return ptr;237}238239240// This function shall free a dependent_exception.241// It does not affect the reference count of the primary exception.242void __cxa_free_dependent_exception (void * dependent_exception) {243__aligned_free_with_fallback(dependent_exception);244}245246247// 2.4.3 Throwing the Exception Object248/*249After constructing the exception object with the throw argument value,250the generated code calls the __cxa_throw runtime library routine. This251routine never returns.252253The __cxa_throw routine will do the following:254255* Obtain the __cxa_exception header from the thrown exception object address,256which can be computed as follows:257__cxa_exception *header = ((__cxa_exception *) thrown_exception - 1);258* Save the current unexpected_handler and terminate_handler in the __cxa_exception header.259* Save the tinfo and dest arguments in the __cxa_exception header.260* Set the exception_class field in the unwind header. This is a 64-bit value261representing the ASCII string "XXXXC++\0", where "XXXX" is a262vendor-dependent string. That is, for implementations conforming to this263ABI, the low-order 4 bytes of this 64-bit value will be "C++\0".264* Increment the uncaught_exception flag.265* Call _Unwind_RaiseException in the system unwind library, Its argument is the266pointer to the thrown exception, which __cxa_throw itself received as an argument.267__Unwind_RaiseException begins the process of stack unwinding, described268in Section 2.5. In special cases, such as an inability to find a269handler, _Unwind_RaiseException may return. In that case, __cxa_throw270will call terminate, assuming that there was no handler for the271exception.272*/273274#if defined(__EMSCRIPTEN__) && defined(__WASM_EXCEPTIONS__) && !defined(NDEBUG)275extern "C" {276void __throw_exception_with_stack_trace(_Unwind_Exception*);277} // extern "C"278#endif279280void281#ifdef __wasm__282// In Wasm, a destructor returns its argument283__cxa_throw(void *thrown_object, std::type_info *tinfo, void *(_LIBCXXABI_DTOR_FUNC *dest)(void *)) {284#else285__cxa_throw(void *thrown_object, std::type_info *tinfo, void (_LIBCXXABI_DTOR_FUNC *dest)(void *)) {286#endif287__cxa_eh_globals* globals = __cxa_get_globals();288globals->uncaughtExceptions += 1; // Not atomically, since globals are thread-local289290__cxa_exception* exception_header = __cxa_init_primary_exception(thrown_object, tinfo, dest);291exception_header->referenceCount = 1; // This is a newly allocated exception, no need for thread safety.292293#if __has_feature(address_sanitizer)294// Inform the ASan runtime that now might be a good time to clean stuff up.295__asan_handle_no_return();296#endif297298#ifdef __USING_SJLJ_EXCEPTIONS__299_Unwind_SjLj_RaiseException(&exception_header->unwindHeader);300#elif defined(__EMSCRIPTEN__) && defined(__WASM_EXCEPTIONS__) && !defined(NDEBUG)301// In debug mode, call a JS library function to use WebAssembly.Exception JS302// API, which enables us to include stack traces303__throw_exception_with_stack_trace(&exception_header->unwindHeader);304#else305_Unwind_RaiseException(&exception_header->unwindHeader);306#endif307// This only happens when there is no handler, or some unexpected unwinding308// error happens.309failed_throw(exception_header);310}311312313// 2.5.3 Exception Handlers314/*315The adjusted pointer is computed by the personality routine during phase 1316and saved in the exception header (either __cxa_exception or317__cxa_dependent_exception).318319Requires: exception is native320*/321void *__cxa_get_exception_ptr(void *unwind_exception) throw() {322#if defined(_LIBCXXABI_ARM_EHABI)323return reinterpret_cast<void*>(324static_cast<_Unwind_Control_Block*>(unwind_exception)->barrier_cache.bitpattern[0]);325#else326return cxa_exception_from_exception_unwind_exception(327static_cast<_Unwind_Exception*>(unwind_exception))->adjustedPtr;328#endif329}330331#if defined(_LIBCXXABI_ARM_EHABI)332/*333The routine to be called before the cleanup. This will save __cxa_exception in334__cxa_eh_globals, so that __cxa_end_cleanup() can recover later.335*/336bool __cxa_begin_cleanup(void *unwind_arg) throw() {337_Unwind_Exception* unwind_exception = static_cast<_Unwind_Exception*>(unwind_arg);338__cxa_eh_globals* globals = __cxa_get_globals();339__cxa_exception* exception_header =340cxa_exception_from_exception_unwind_exception(unwind_exception);341342if (__isOurExceptionClass(unwind_exception))343{344if (0 == exception_header->propagationCount)345{346exception_header->nextPropagatingException = globals->propagatingExceptions;347globals->propagatingExceptions = exception_header;348}349++exception_header->propagationCount;350}351else352{353// If the propagatingExceptions stack is not empty, since we can't354// chain the foreign exception, terminate it.355if (NULL != globals->propagatingExceptions)356std::terminate();357globals->propagatingExceptions = exception_header;358}359return true;360}361362/*363The routine to be called after the cleanup has been performed. It will get the364propagating __cxa_exception from __cxa_eh_globals, and continue the stack365unwinding with _Unwind_Resume.366367According to ARM EHABI 8.4.1, __cxa_end_cleanup() should not clobber any368register, thus we have to write this function in assembly so that we can save369{r1, r2, r3}. We don't have to save r0 because it is the return value and the370first argument to _Unwind_Resume(). The function also saves/restores r4 to371keep the stack aligned and to provide a temp register. _Unwind_Resume never372returns and we need to keep the original lr so just branch to it. When373targeting bare metal, the function also clobbers ip/r12 to hold the address of374_Unwind_Resume, which may be too far away for an ordinary branch.375*/376__attribute__((used)) static _Unwind_Exception *377__cxa_end_cleanup_impl()378{379__cxa_eh_globals* globals = __cxa_get_globals();380__cxa_exception* exception_header = globals->propagatingExceptions;381if (NULL == exception_header)382{383// It seems that __cxa_begin_cleanup() is not called properly.384// We have no choice but terminate the program now.385std::terminate();386}387388if (__isOurExceptionClass(&exception_header->unwindHeader))389{390--exception_header->propagationCount;391if (0 == exception_header->propagationCount)392{393globals->propagatingExceptions = exception_header->nextPropagatingException;394exception_header->nextPropagatingException = NULL;395}396}397else398{399globals->propagatingExceptions = NULL;400}401return &exception_header->unwindHeader;402}403404asm(" .pushsection .text.__cxa_end_cleanup,\"ax\",%progbits\n"405" .globl __cxa_end_cleanup\n"406" .type __cxa_end_cleanup,%function\n"407"__cxa_end_cleanup:\n"408#if defined(__ARM_FEATURE_BTI_DEFAULT)409" bti\n"410#endif411" push {r1, r2, r3, r4}\n"412" mov r4, lr\n"413" bl __cxa_end_cleanup_impl\n"414" mov lr, r4\n"415#if defined(LIBCXXABI_BAREMETAL)416" ldr r4, =_Unwind_Resume\n"417" mov ip, r4\n"418#endif419" pop {r1, r2, r3, r4}\n"420#if defined(LIBCXXABI_BAREMETAL)421" bx ip\n"422#else423" b _Unwind_Resume\n"424#endif425" .popsection");426#endif // defined(_LIBCXXABI_ARM_EHABI)427428/*429This routine can catch foreign or native exceptions. If native, the exception430can be a primary or dependent variety. This routine may remain blissfully431ignorant of whether the native exception is primary or dependent.432433If the exception is native:434* Increment's the exception's handler count.435* Push the exception on the stack of currently-caught exceptions if it is not436already there (from a rethrow).437* Decrements the uncaught_exception count.438* Returns the adjusted pointer to the exception object, which is stored in439the __cxa_exception by the personality routine.440441If the exception is foreign, this means it did not originate from one of throw442routines. The foreign exception does not necessarily have a __cxa_exception443header. However we can catch it here with a catch (...), or with a call444to terminate or unexpected during unwinding.445* Do not try to increment the exception's handler count, we don't know where446it is.447* Push the exception on the stack of currently-caught exceptions only if the448stack is empty. The foreign exception has no way to link to the current449top of stack. If the stack is not empty, call terminate. Even with an450empty stack, this is hacked in by pushing a pointer to an imaginary451__cxa_exception block in front of the foreign exception. It would be better452if the __cxa_eh_globals structure had a stack of _Unwind_Exception, but it453doesn't. It has a stack of __cxa_exception (which has a next* in it).454* Do not decrement the uncaught_exception count because we didn't increment it455in __cxa_throw (or one of our rethrow functions).456* If we haven't terminated, assume the exception object is just past the457_Unwind_Exception and return a pointer to that.458*/459void*460__cxa_begin_catch(void* unwind_arg) throw()461{462_Unwind_Exception* unwind_exception = static_cast<_Unwind_Exception*>(unwind_arg);463bool native_exception = __isOurExceptionClass(unwind_exception);464__cxa_eh_globals* globals = __cxa_get_globals();465// exception_header is a hackish offset from a foreign exception, but it466// works as long as we're careful not to try to access any __cxa_exception467// parts.468__cxa_exception* exception_header =469cxa_exception_from_exception_unwind_exception470(471static_cast<_Unwind_Exception*>(unwind_exception)472);473474#if defined(__MVS__)475// Remove the exception object from the linked list of exceptions that the z/OS unwinder476// maintains before adding it to the libc++abi list of caught exceptions.477// The libc++abi will manage the lifetime of the exception from this point forward.478_UnwindZOS_PopException();479#endif480481if (native_exception)482{483// Increment the handler count, removing the flag about being rethrown484exception_header->handlerCount = exception_header->handlerCount < 0 ?485-exception_header->handlerCount + 1 : exception_header->handlerCount + 1;486// place the exception on the top of the stack if it's not already487// there by a previous rethrow488if (exception_header != globals->caughtExceptions)489{490exception_header->nextException = globals->caughtExceptions;491globals->caughtExceptions = exception_header;492}493globals->uncaughtExceptions -= 1; // Not atomically, since globals are thread-local494#if defined(_LIBCXXABI_ARM_EHABI)495return reinterpret_cast<void*>(exception_header->unwindHeader.barrier_cache.bitpattern[0]);496#else497return exception_header->adjustedPtr;498#endif499}500// Else this is a foreign exception501// If the caughtExceptions stack is not empty, terminate502if (globals->caughtExceptions != 0)503std::terminate();504// Push the foreign exception on to the stack505globals->caughtExceptions = exception_header;506return unwind_exception + 1;507}508509510/*511Upon exit for any reason, a handler must call:512void __cxa_end_catch ();513514This routine can be called for either a native or foreign exception.515For a native exception:516* Locates the most recently caught exception and decrements its handler count.517* Removes the exception from the caught exception stack, if the handler count goes to zero.518* If the handler count goes down to zero, and the exception was not re-thrown519by throw, it locates the primary exception (which may be the same as the one520it's handling) and decrements its reference count. If that reference count521goes to zero, the function destroys the exception. In any case, if the current522exception is a dependent exception, it destroys that.523524For a foreign exception:525* If it has been rethrown, there is nothing to do.526* Otherwise delete the exception and pop the catch stack to empty.527*/528void __cxa_end_catch() {529static_assert(sizeof(__cxa_exception) == sizeof(__cxa_dependent_exception),530"sizeof(__cxa_exception) must be equal to "531"sizeof(__cxa_dependent_exception)");532static_assert(__builtin_offsetof(__cxa_exception, referenceCount) ==533__builtin_offsetof(__cxa_dependent_exception,534primaryException),535"the layout of __cxa_exception must match the layout of "536"__cxa_dependent_exception");537static_assert(__builtin_offsetof(__cxa_exception, handlerCount) ==538__builtin_offsetof(__cxa_dependent_exception, handlerCount),539"the layout of __cxa_exception must match the layout of "540"__cxa_dependent_exception");541__cxa_eh_globals* globals = __cxa_get_globals_fast(); // __cxa_get_globals called in __cxa_begin_catch542__cxa_exception* exception_header = globals->caughtExceptions;543// If we've rethrown a foreign exception, then globals->caughtExceptions544// will have been made an empty stack by __cxa_rethrow() and there is545// nothing more to be done. Do nothing!546if (NULL != exception_header)547{548bool native_exception = __isOurExceptionClass(&exception_header->unwindHeader);549if (native_exception)550{551// This is a native exception552if (exception_header->handlerCount < 0)553{554// The exception has been rethrown by __cxa_rethrow, so don't delete it555if (0 == incrementHandlerCount(exception_header))556{557// Remove from the chain of uncaught exceptions558globals->caughtExceptions = exception_header->nextException;559// but don't destroy560}561// Keep handlerCount negative in case there are nested catch's562// that need to be told that this exception is rethrown. Don't563// erase this rethrow flag until the exception is recaught.564}565else566{567// The native exception has not been rethrown568if (0 == decrementHandlerCount(exception_header))569{570// Remove from the chain of uncaught exceptions571globals->caughtExceptions = exception_header->nextException;572// Destroy this exception, being careful to distinguish573// between dependent and primary exceptions574if (isDependentException(&exception_header->unwindHeader))575{576// Reset exception_header to primaryException and deallocate the dependent exception577__cxa_dependent_exception* dep_exception_header =578reinterpret_cast<__cxa_dependent_exception*>(exception_header);579exception_header =580cxa_exception_from_thrown_object(dep_exception_header->primaryException);581__cxa_free_dependent_exception(dep_exception_header);582}583// Destroy the primary exception only if its referenceCount goes to 0584// (this decrement must be atomic)585__cxa_decrement_exception_refcount(thrown_object_from_cxa_exception(exception_header));586}587}588}589else590{591// The foreign exception has not been rethrown. Pop the stack592// and delete it. If there are nested catch's and they try593// to touch a foreign exception in any way, that is undefined594// behavior. They likely can't since the only way to catch595// a foreign exception is with catch (...)!596_Unwind_DeleteException(&globals->caughtExceptions->unwindHeader);597globals->caughtExceptions = 0;598}599}600}601602void __cxa_call_terminate(void* unwind_arg) throw() {603__cxa_begin_catch(unwind_arg);604std::terminate();605}606607// Note: exception_header may be masquerading as a __cxa_dependent_exception608// and that's ok. exceptionType is there too.609// However watch out for foreign exceptions. Return null for them.610std::type_info *__cxa_current_exception_type() {611// get the current exception612__cxa_eh_globals *globals = __cxa_get_globals_fast();613if (NULL == globals)614return NULL; // If there have never been any exceptions, there are none now.615__cxa_exception *exception_header = globals->caughtExceptions;616if (NULL == exception_header)617return NULL; // No current exception618if (!__isOurExceptionClass(&exception_header->unwindHeader))619return NULL;620return exception_header->exceptionType;621}622623// 2.5.4 Rethrowing Exceptions624/* This routine can rethrow native or foreign exceptions.625If the exception is native:626* marks the exception object on top of the caughtExceptions stack627(in an implementation-defined way) as being rethrown.628* If the caughtExceptions stack is empty, it calls terminate()629(see [C++FDIS] [except.throw], 15.1.8).630* It then calls _Unwind_RaiseException which should not return631(terminate if it does).632Note: exception_header may be masquerading as a __cxa_dependent_exception633and that's ok.634*/635void __cxa_rethrow() {636__cxa_eh_globals* globals = __cxa_get_globals();637__cxa_exception* exception_header = globals->caughtExceptions;638if (NULL == exception_header)639std::terminate(); // throw; called outside of a exception handler640bool native_exception = __isOurExceptionClass(&exception_header->unwindHeader);641if (native_exception)642{643// Mark the exception as being rethrown (reverse the effects of __cxa_begin_catch)644exception_header->handlerCount = -exception_header->handlerCount;645globals->uncaughtExceptions += 1;646// __cxa_end_catch will remove this exception from the caughtExceptions stack if necessary647}648else // this is a foreign exception649{650// The only way to communicate to __cxa_end_catch that we've rethrown651// a foreign exception, so don't delete us, is to pop the stack here652// which must be empty afterwards. Then __cxa_end_catch will do653// nothing654globals->caughtExceptions = 0;655}656#ifdef __USING_SJLJ_EXCEPTIONS__657_Unwind_SjLj_RaiseException(&exception_header->unwindHeader);658#elif defined(__EMSCRIPTEN__) && defined(__WASM_EXCEPTIONS__) && !defined(NDEBUG)659// In debug mode, call a JS library function to use WebAssembly.Exception JS660// API, which enables us to include stack traces661__throw_exception_with_stack_trace(&exception_header->unwindHeader);662#else663_Unwind_RaiseException(&exception_header->unwindHeader);664#endif665666// If we get here, some kind of unwinding error has occurred.667// There is some weird code generation bug happening with668// Apple clang version 4.0 (tags/Apple/clang-418.0.2) (based on LLVM 3.1svn)669// If we call failed_throw here. Turns up with -O2 or higher, and -Os.670__cxa_begin_catch(&exception_header->unwindHeader);671if (native_exception)672std::__terminate(exception_header->terminateHandler);673// Foreign exception: can't get exception_header->terminateHandler674std::terminate();675}676677/*678If thrown_object is not null, atomically increment the referenceCount field679of the __cxa_exception header associated with the thrown object referred to680by thrown_object.681682Requires: If thrown_object is not NULL, it is a native exception.683*/684void685__cxa_increment_exception_refcount(void *thrown_object) throw() {686if (thrown_object != NULL )687{688__cxa_exception* exception_header = cxa_exception_from_thrown_object(thrown_object);689std::__libcpp_atomic_add(&exception_header->referenceCount, size_t(1));690}691}692693/*694If thrown_object is not null, atomically decrement the referenceCount field695of the __cxa_exception header associated with the thrown object referred to696by thrown_object. If the referenceCount drops to zero, destroy and697deallocate the exception.698699Requires: If thrown_object is not NULL, it is a native exception.700*/701_LIBCXXABI_NO_CFI702void __cxa_decrement_exception_refcount(void *thrown_object) throw() {703if (thrown_object != NULL )704{705__cxa_exception* exception_header = cxa_exception_from_thrown_object(thrown_object);706if (std::__libcpp_atomic_add(&exception_header->referenceCount, size_t(-1)) == 0)707{708if (NULL != exception_header->exceptionDestructor)709exception_header->exceptionDestructor(thrown_object);710__cxa_free_exception(thrown_object);711}712}713}714715/*716Returns a pointer to the thrown object (if any) at the top of the717caughtExceptions stack. Atomically increment the exception's referenceCount.718If there is no such thrown object or if the thrown object is foreign,719returns null.720721We can use __cxa_get_globals_fast here to get the globals because if there have722been no exceptions thrown, ever, on this thread, we can return NULL without723the need to allocate the exception-handling globals.724*/725void *__cxa_current_primary_exception() throw() {726// get the current exception727__cxa_eh_globals* globals = __cxa_get_globals_fast();728if (NULL == globals)729return NULL; // If there are no globals, there is no exception730__cxa_exception* exception_header = globals->caughtExceptions;731if (NULL == exception_header)732return NULL; // No current exception733if (!__isOurExceptionClass(&exception_header->unwindHeader))734return NULL; // Can't capture a foreign exception (no way to refcount it)735if (isDependentException(&exception_header->unwindHeader)) {736__cxa_dependent_exception* dep_exception_header =737reinterpret_cast<__cxa_dependent_exception*>(exception_header);738exception_header = cxa_exception_from_thrown_object(dep_exception_header->primaryException);739}740void* thrown_object = thrown_object_from_cxa_exception(exception_header);741__cxa_increment_exception_refcount(thrown_object);742return thrown_object;743}744745/*746If reason isn't _URC_FOREIGN_EXCEPTION_CAUGHT, then the terminateHandler747stored in exc is called. Otherwise the referenceCount stored in the748primary exception is decremented, destroying the primary if necessary.749Finally the dependent exception is destroyed.750*/751static752void753dependent_exception_cleanup(_Unwind_Reason_Code reason, _Unwind_Exception* unwind_exception)754{755__cxa_dependent_exception* dep_exception_header =756reinterpret_cast<__cxa_dependent_exception*>(unwind_exception + 1) - 1;757if (_URC_FOREIGN_EXCEPTION_CAUGHT != reason)758std::__terminate(dep_exception_header->terminateHandler);759__cxa_decrement_exception_refcount(dep_exception_header->primaryException);760__cxa_free_dependent_exception(dep_exception_header);761}762763/*764If thrown_object is not null, allocate, initialize and throw a dependent765exception.766*/767void768__cxa_rethrow_primary_exception(void* thrown_object)769{770if ( thrown_object != NULL )771{772// thrown_object guaranteed to be native because773// __cxa_current_primary_exception returns NULL for foreign exceptions774__cxa_exception* exception_header = cxa_exception_from_thrown_object(thrown_object);775__cxa_dependent_exception* dep_exception_header =776static_cast<__cxa_dependent_exception*>(__cxa_allocate_dependent_exception());777dep_exception_header->primaryException = thrown_object;778__cxa_increment_exception_refcount(thrown_object);779dep_exception_header->exceptionType = exception_header->exceptionType;780dep_exception_header->unexpectedHandler = std::get_unexpected();781dep_exception_header->terminateHandler = std::get_terminate();782setDependentExceptionClass(&dep_exception_header->unwindHeader);783__cxa_get_globals()->uncaughtExceptions += 1;784dep_exception_header->unwindHeader.exception_cleanup = dependent_exception_cleanup;785#ifdef __USING_SJLJ_EXCEPTIONS__786_Unwind_SjLj_RaiseException(&dep_exception_header->unwindHeader);787#elif defined(__EMSCRIPTEN__) && defined(__WASM_EXCEPTIONS__) && !defined(NDEBUG)788// In debug mode, call a JS library function to use789// WebAssembly.Exception JS API, which enables us to include stack790// traces791__throw_exception_with_stack_trace(&dep_exception_header->unwindHeader);792#else793_Unwind_RaiseException(&dep_exception_header->unwindHeader);794#endif795// Some sort of unwinding error. Note that terminate is a handler.796__cxa_begin_catch(&dep_exception_header->unwindHeader);797}798// If we return client will call terminate()799}800801bool802__cxa_uncaught_exception() throw() { return __cxa_uncaught_exceptions() != 0; }803804unsigned int805__cxa_uncaught_exceptions() throw()806{807// This does not report foreign exceptions in flight808__cxa_eh_globals* globals = __cxa_get_globals_fast();809if (globals == 0)810return 0;811return globals->uncaughtExceptions;812}813814} // extern "C"815816} // abi817818819