diff --git a/contrib/libcxxrt/atomic.h b/contrib/libcxxrt/atomic.h index 701d05337cf1..0768c08038df 100644 --- a/contrib/libcxxrt/atomic.h +++ b/contrib/libcxxrt/atomic.h @@ -1,102 +1,102 @@ #ifndef __has_builtin # define __has_builtin(x) 0 #endif #ifndef __has_feature # define __has_feature(x) 0 #endif #ifndef __has_extension # define __has_extension(x) 0 #endif #if !__has_extension(c_atomic) # define _Atomic(T) T #endif #if __has_builtin(__c11_atomic_exchange) # define ATOMIC_BUILTIN(name) __c11_atomic_##name #else # define ATOMIC_BUILTIN(name) __atomic_##name##_n #endif namespace { /** * C++11 memory orders. We only need a subset of them. */ enum memory_order { /** * Acquire order. */ acquire = __ATOMIC_ACQUIRE, /** * Release order. */ release = __ATOMIC_RELEASE, /** * Sequentially consistent memory ordering. */ seqcst = __ATOMIC_SEQ_CST }; /** * Atomic, implements a subset of `std::atomic`. */ template class atomic { /** * The underlying value. Use C11 atomic qualification if available. */ _Atomic(T) val; public: /** * Constructor, takes a value. */ - atomic(T init) : val(init) {} + constexpr atomic(T init) : val(init) {} /** * Atomically load with the specified memory order. */ T load(memory_order order = memory_order::seqcst) { return ATOMIC_BUILTIN(load)(&val, order); } /** * Atomically store with the specified memory order. */ void store(T v, memory_order order = memory_order::seqcst) { return ATOMIC_BUILTIN(store)(&val, v, order); } /** * Atomically exchange with the specified memory order. */ T exchange(T v, memory_order order = memory_order::seqcst) { return ATOMIC_BUILTIN(exchange)(&val, v, order); } /** * Atomically exchange with the specified memory order. */ bool compare_exchange(T & expected, T desired, memory_order order = memory_order::seqcst) { #if __has_builtin(__c11_atomic_compare_exchange_strong) return __c11_atomic_compare_exchange_strong( &val, &expected, desired, order, order); #else return __atomic_compare_exchange_n( &val, &expected, desired, true, order, order); #endif } }; } // namespace #undef ATOMIC_BUILTIN diff --git a/contrib/libcxxrt/cxxabi.h b/contrib/libcxxrt/cxxabi.h index ef4076a08a0a..2bf7f99b5245 100644 --- a/contrib/libcxxrt/cxxabi.h +++ b/contrib/libcxxrt/cxxabi.h @@ -1,259 +1,266 @@ /* * Copyright 2012 David Chisnall. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef __CXXABI_H_ #define __CXXABI_H_ #include #include #include "unwind.h" namespace std { class type_info; } /* * The cxxabi.h header provides a set of public definitions for types and * functions defined by the Itanium C++ ABI specification. For reference, see * the ABI specification here: * * http://sourcery.mentor.com/public/cxx-abi/abi.html * * All deviations from this specification, unless otherwise noted, are * accidental. */ #ifdef __cplusplus +#if __cplusplus < 201103L +#define _LIBCXXRT_NOEXCEPT throw() +#else +#define _LIBCXXRT_NOEXCEPT noexcept +#endif namespace __cxxabiv1 { extern "C" { +#else +#define _LIBCXXRT_NOEXCEPT #endif /** * Function type to call when an unexpected exception is encountered. */ typedef void (*unexpected_handler)(); /** * Function type to call when an unrecoverable condition is encountered. */ typedef void (*terminate_handler)(); /** * Structure used as a header on thrown exceptions. This is the same layout as * defined by the Itanium ABI spec, so should be interoperable with any other * implementation of this spec, such as GNU libsupc++. * * This structure is allocated when an exception is thrown. Unwinding happens * in two phases, the first looks for a handler and the second installs the * context. This structure stores a cache of the handler location between * phase 1 and phase 2. Unfortunately, cleanup information is not cached, so * must be looked up in both phases. This happens for two reasons. The first * is that we don't know how many frames containing cleanups there will be, and * we should avoid dynamic allocation during unwinding (the exception may be * reporting that we've run out of memory). The second is that finding * cleanups is much cheaper than finding handlers, because we don't have to * look at the type table at all. * * Note: Several fields of this structure have not-very-informative names. * These are taken from the ABI spec and have not been changed to make it * easier for people referring to to the spec while reading this code. */ struct __cxa_exception { -#if __LP64__ +#ifdef __LP64__ /** * Now _Unwind_Exception is marked with __attribute__((aligned)), which * implies __cxa_exception is also aligned. Insert padding in the * beginning of the struct, rather than before unwindHeader. */ void *reserve; /** * Reference count. Used to support the C++11 exception_ptr class. This * is prepended to the structure in 64-bit mode and squeezed in to the * padding left before the 64-bit aligned _Unwind_Exception at the end in * 32-bit mode. * * Note that it is safe to extend this structure at the beginning, rather * than the end, because the public API for creating it returns the address * of the end (where the exception object can be stored). */ uintptr_t referenceCount; #endif /** Type info for the thrown object. */ std::type_info *exceptionType; /** Destructor for the object, if one exists. */ void (*exceptionDestructor) (void *); /** Handler called when an exception specification is violated. */ unexpected_handler unexpectedHandler; /** Hander called to terminate. */ terminate_handler terminateHandler; /** * Next exception in the list. If an exception is thrown inside a catch * block and caught in a nested catch, this points to the exception that * will be handled after the inner catch block completes. */ __cxa_exception *nextException; /** * The number of handlers that currently have references to this * exception. The top (non-sign) bit of this is used as a flag to indicate * that the exception is being rethrown, so should not be deleted when its * handler count reaches 0 (which it doesn't with the top bit set). */ int handlerCount; #if defined(__arm__) && !defined(__ARM_DWARF_EH__) /** * The ARM EH ABI requires the unwind library to keep track of exceptions * during cleanups. These support nesting, so we need to keep a list of * them. */ _Unwind_Exception *nextCleanup; /** * The number of cleanups that are currently being run on this exception. */ int cleanupCount; #endif /** * The selector value to be returned when installing the catch handler. * Used at the call site to determine which catch() block should execute. * This is found in phase 1 of unwinding then installed in phase 2. */ int handlerSwitchValue; /** * The action record for the catch. This is cached during phase 1 * unwinding. */ const char *actionRecord; /** * Pointer to the language-specific data area (LSDA) for the handler * frame. This is unused in this implementation, but set for ABI * compatibility in case we want to mix code in very weird ways. */ const char *languageSpecificData; /** The cached landing pad for the catch handler.*/ void *catchTemp; /** * The pointer that will be returned as the pointer to the object. When * throwing a class and catching a virtual superclass (for example), we * need to adjust the thrown pointer to make it all work correctly. */ void *adjustedPtr; -#if !__LP64__ +#ifndef __LP64__ /** * Reference count. Used to support the C++11 exception_ptr class. This * is prepended to the structure in 64-bit mode and squeezed in to the * padding left before the 64-bit aligned _Unwind_Exception at the end in * 32-bit mode. * * Note that it is safe to extend this structure at the beginning, rather * than the end, because the public API for creating it returns the address * of the end (where the exception object can be stored) */ uintptr_t referenceCount; #endif /** The language-agnostic part of the exception header. */ _Unwind_Exception unwindHeader; }; /** * ABI-specified globals structure. Returned by the __cxa_get_globals() * function and its fast variant. This is a per-thread structure - every * thread will have one lazily allocated. * * This structure is defined by the ABI, so may be used outside of this * library. */ struct __cxa_eh_globals { /** * A linked list of exceptions that are currently caught. There may be * several of these in nested catch() blocks. */ __cxa_exception *caughtExceptions; /** * The number of uncaught exceptions. */ unsigned int uncaughtExceptions; }; /** * ABI function returning the __cxa_eh_globals structure. */ __cxa_eh_globals *__cxa_get_globals(void); /** * Version of __cxa_get_globals() assuming that __cxa_get_globals() has already * been called at least once by this thread. */ __cxa_eh_globals *__cxa_get_globals_fast(void); std::type_info * __cxa_current_exception_type(); -void *__cxa_allocate_exception(size_t thrown_size) throw(); +void *__cxa_allocate_exception(size_t thrown_size) _LIBCXXRT_NOEXCEPT; -void __cxa_free_exception(void* thrown_exception) throw(); +void __cxa_free_exception(void* thrown_exception) _LIBCXXRT_NOEXCEPT; __cxa_exception *__cxa_init_primary_exception( - void *object, std::type_info* tinfo, void (*dest)(void *)) throw(); + void *object, std::type_info* tinfo, void (*dest)(void *)) _LIBCXXRT_NOEXCEPT; /** * Throws an exception returned by __cxa_current_primary_exception(). This * exception may have been caught in another thread. */ void __cxa_rethrow_primary_exception(void* thrown_exception); /** * Returns the current exception in a form that can be stored in an * exception_ptr object and then rethrown by a call to * __cxa_rethrow_primary_exception(). */ void *__cxa_current_primary_exception(void); /** * Increments the reference count of an exception. Called when an * exception_ptr is copied. */ void __cxa_increment_exception_refcount(void* thrown_exception); /** * Decrements the reference count of an exception. Called when an * exception_ptr is deleted. */ void __cxa_decrement_exception_refcount(void* thrown_exception); /** * Demangles a C++ symbol or type name. The buffer, if non-NULL, must be * allocated with malloc() and must be *n bytes or more long. This function * may call realloc() on the value pointed to by buf, and will return the * length of the string via *n. * * The value pointed to by status is set to one of the following: * * 0: success * -1: memory allocation failure * -2: invalid mangled name * -3: invalid arguments */ char* __cxa_demangle(const char* mangled_name, char* buf, size_t* n, int* status); #ifdef __cplusplus } // extern "C" } // namespace namespace abi = __cxxabiv1; #endif /* __cplusplus */ #endif /* __CXXABI_H_ */ diff --git a/contrib/libcxxrt/exception.cc b/contrib/libcxxrt/exception.cc index b56333e979a2..c87fe5ac4468 100644 --- a/contrib/libcxxrt/exception.cc +++ b/contrib/libcxxrt/exception.cc @@ -1,1629 +1,1635 @@ /* * Copyright 2010-2011 PathScale, Inc. All rights reserved. * Copyright 2021 David Chisnall. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS * IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #include #include #include #include #include #include "typeinfo.h" #include "dwarf_eh.h" #include "atomic.h" #include "cxxabi.h" #pragma weak pthread_key_create #pragma weak pthread_setspecific #pragma weak pthread_getspecific #pragma weak pthread_once #ifdef LIBCXXRT_WEAK_LOCKS #pragma weak pthread_mutex_lock #define pthread_mutex_lock(mtx) do {\ if (pthread_mutex_lock) pthread_mutex_lock(mtx);\ } while(0) #pragma weak pthread_mutex_unlock #define pthread_mutex_unlock(mtx) do {\ if (pthread_mutex_unlock) pthread_mutex_unlock(mtx);\ } while(0) #pragma weak pthread_cond_signal #define pthread_cond_signal(cv) do {\ if (pthread_cond_signal) pthread_cond_signal(cv);\ } while(0) #pragma weak pthread_cond_wait #define pthread_cond_wait(cv, mtx) do {\ if (pthread_cond_wait) pthread_cond_wait(cv, mtx);\ } while(0) #endif using namespace ABI_NAMESPACE; /** * Saves the result of the landing pad that we have found. For ARM, this is * stored in the generic unwind structure, while on other platforms it is * stored in the C++ exception. */ static void saveLandingPad(struct _Unwind_Context *context, struct _Unwind_Exception *ucb, struct __cxa_exception *ex, int selector, dw_eh_ptr_t landingPad) { #if defined(__arm__) && !defined(__ARM_DWARF_EH__) // On ARM, we store the saved exception in the generic part of the structure ucb->barrier_cache.sp = _Unwind_GetGR(context, 13); ucb->barrier_cache.bitpattern[1] = static_cast(selector); ucb->barrier_cache.bitpattern[3] = reinterpret_cast(landingPad); #endif // Cache the results for the phase 2 unwind, if we found a handler // and this is not a foreign exception. if (ex) { ex->handlerSwitchValue = selector; ex->catchTemp = landingPad; } } /** * Loads the saved landing pad. Returns 1 on success, 0 on failure. */ static int loadLandingPad(struct _Unwind_Context *context, struct _Unwind_Exception *ucb, struct __cxa_exception *ex, unsigned long *selector, dw_eh_ptr_t *landingPad) { #if defined(__arm__) && !defined(__ARM_DWARF_EH__) *selector = ucb->barrier_cache.bitpattern[1]; *landingPad = reinterpret_cast(ucb->barrier_cache.bitpattern[3]); return 1; #else if (ex) { *selector = ex->handlerSwitchValue; *landingPad = reinterpret_cast(ex->catchTemp); return 0; } return 0; #endif } static inline _Unwind_Reason_Code continueUnwinding(struct _Unwind_Exception *ex, struct _Unwind_Context *context) { #if defined(__arm__) && !defined(__ARM_DWARF_EH__) if (__gnu_unwind_frame(ex, context) != _URC_OK) { return _URC_FAILURE; } #endif return _URC_CONTINUE_UNWIND; } -extern "C" void __cxa_free_exception(void *thrown_exception) throw(); +extern "C" void __cxa_free_exception(void *thrown_exception) _LIBCXXRT_NOEXCEPT; extern "C" void __cxa_free_dependent_exception(void *thrown_exception); extern "C" void* __dynamic_cast(const void *sub, const __class_type_info *src, const __class_type_info *dst, ptrdiff_t src2dst_offset); /** * The type of a handler that has been found. */ typedef enum { /** No handler. */ handler_none, /** * A cleanup - the exception will propagate through this frame, but code * must be run when this happens. */ handler_cleanup, /** * A catch statement. The exception will not propagate past this frame * (without an explicit rethrow). */ handler_catch } handler_type; /** * Per-thread info required by the runtime. We store a single structure * pointer in thread-local storage, because this tends to be a scarce resource * and it's impolite to steal all of it and not leave any for the rest of the * program. * * Instances of this structure are allocated lazily - at most one per thread - * and are destroyed on thread termination. */ struct __cxa_thread_info { /** The termination handler for this thread. */ terminate_handler terminateHandler; /** The unexpected exception handler for this thread. */ unexpected_handler unexpectedHandler; #ifndef LIBCXXRT_NO_EMERGENCY_MALLOC /** * The number of emergency buffers held by this thread. This is 0 in * normal operation - the emergency buffers are only used when malloc() * fails to return memory for allocating an exception. Threads are not * permitted to hold more than 4 emergency buffers (as per recommendation * in ABI spec [3.3.1]). */ int emergencyBuffersHeld; #endif /** * The exception currently running in a cleanup. */ _Unwind_Exception *currentCleanup; /** * Our state with respect to foreign exceptions. Usually none, set to * caught if we have just caught an exception and rethrown if we are * rethrowing it. */ enum { none, caught, rethrown } foreign_exception_state; /** * The public part of this structure, accessible from outside of this * module. */ __cxa_eh_globals globals; }; /** * Dependent exception. This */ struct __cxa_dependent_exception { -#if __LP64__ +#ifdef __LP64__ void *reserve; void *primaryException; #endif std::type_info *exceptionType; void (*exceptionDestructor) (void *); unexpected_handler unexpectedHandler; terminate_handler terminateHandler; __cxa_exception *nextException; int handlerCount; #if defined(__arm__) && !defined(__ARM_DWARF_EH__) _Unwind_Exception *nextCleanup; int cleanupCount; #endif int handlerSwitchValue; const char *actionRecord; const char *languageSpecificData; void *catchTemp; void *adjustedPtr; -#if !__LP64__ +#ifndef __LP64__ void *primaryException; #endif _Unwind_Exception unwindHeader; }; static_assert(sizeof(__cxa_exception) == sizeof(__cxa_dependent_exception), "__cxa_exception and __cxa_dependent_exception should have the same size"); static_assert(offsetof(__cxa_exception, referenceCount) == offsetof(__cxa_dependent_exception, primaryException), "referenceCount and primaryException should have the same offset"); static_assert(offsetof(__cxa_exception, unwindHeader) == offsetof(__cxa_dependent_exception, unwindHeader), "unwindHeader fields should have the same offset"); static_assert(offsetof(__cxa_dependent_exception, unwindHeader) == offsetof(__cxa_dependent_exception, adjustedPtr) + 8, "there should be no padding before unwindHeader"); namespace std { void unexpected(); class exception { public: - virtual ~exception() throw(); - virtual const char* what() const throw(); + virtual ~exception() _LIBCXXRT_NOEXCEPT; + virtual const char* what() const _LIBCXXRT_NOEXCEPT; }; } /** * Class of exceptions to distinguish between this and other exception types. * * The first four characters are the vendor ID. Currently, we use GNUC, * because we aim for ABI-compatibility with the GNU implementation, and * various checks may test for equality of the class, which is incorrect. */ static const uint64_t exception_class = EXCEPTION_CLASS('G', 'N', 'U', 'C', 'C', '+', '+', '\0'); /** * Class used for dependent exceptions. */ static const uint64_t dependent_exception_class = EXCEPTION_CLASS('G', 'N', 'U', 'C', 'C', '+', '+', '\x01'); /** * The low four bytes of the exception class, indicating that we conform to the * Itanium C++ ABI. This is currently unused, but should be used in the future * if we change our exception class, to allow this library and libsupc++ to be * linked to the same executable and both to interoperate. */ static const uint32_t abi_exception_class = GENERIC_EXCEPTION_CLASS('C', '+', '+', '\0'); static bool isCXXException(uint64_t cls) { return (cls == exception_class) || (cls == dependent_exception_class); } static bool isDependentException(uint64_t cls) { return cls == dependent_exception_class; } static __cxa_exception *exceptionFromPointer(void *ex) { return reinterpret_cast<__cxa_exception*>(static_cast(ex) - offsetof(struct __cxa_exception, unwindHeader)); } static __cxa_exception *realExceptionFromException(__cxa_exception *ex) { if (!isDependentException(ex->unwindHeader.exception_class)) { return ex; } return reinterpret_cast<__cxa_exception*>((reinterpret_cast<__cxa_dependent_exception*>(ex))->primaryException)-1; } namespace std { // Forward declaration of standard library terminate() function used to // abort execution. - void terminate(void); + [[noreturn]] void terminate(void) _LIBCXXRT_NOEXCEPT; } using namespace ABI_NAMESPACE; +#ifdef LIBCXXRT_NO_DEFAULT_TERMINATE_DIAGNOSTICS +/** The global termination handler. */ +static atomic terminateHandler = abort; +#else +/** + * Callback function used with _Unwind_Backtrace(). + * + * Prints a stack trace. Used only for debugging help. + * + * Note: As of FreeBSD 8.1, dladdr() still doesn't work properly, so this only + * correctly prints function names from public, relocatable, symbols. + */ +static _Unwind_Reason_Code trace(struct _Unwind_Context *context, void *c) +{ + Dl_info myinfo; + int mylookup = + dladdr(reinterpret_cast(__cxa_current_exception_type), &myinfo); + void *ip = reinterpret_cast(_Unwind_GetIP(context)); + Dl_info info; + if (dladdr(ip, &info) != 0) + { + if (mylookup == 0 || strcmp(info.dli_fname, myinfo.dli_fname) != 0) + { + printf("%p:%s() in %s\n", ip, info.dli_sname, info.dli_fname); + } + } + return _URC_CONTINUE_UNWIND; +} + +static void terminate_with_diagnostics() { + __cxa_eh_globals *globals = __cxa_get_globals(); + __cxa_exception *ex = globals->caughtExceptions; + + if (ex != nullptr) { + fprintf(stderr, "Terminating due to uncaught exception %p", static_cast(ex)); + ex = realExceptionFromException(ex); + static const __class_type_info *e_ti = + static_cast(&typeid(std::exception)); + const __class_type_info *throw_ti = + dynamic_cast(ex->exceptionType); + if (throw_ti) + { + std::exception *e = + static_cast(e_ti->cast_to(static_cast(ex+1), throw_ti)); + if (e) + { + fprintf(stderr, " '%s'", e->what()); + } + } + + size_t bufferSize = 128; + char *demangled = static_cast(malloc(bufferSize)); + const char *mangled = ex->exceptionType->name(); + int status; + demangled = __cxa_demangle(mangled, demangled, &bufferSize, &status); + fprintf(stderr, " of type %s\n", + status == 0 ? demangled : mangled); + if (status == 0) { free(demangled); } + + _Unwind_Backtrace(trace, 0); + } + abort(); +} /** The global termination handler. */ -static atomic terminateHandler = abort; +static atomic terminateHandler = terminate_with_diagnostics; +#endif + /** The global unexpected exception handler. */ static atomic unexpectedHandler = std::terminate; /** Key used for thread-local data. */ static pthread_key_t eh_key; /** * Cleanup function, allowing foreign exception handlers to correctly destroy * this exception if they catch it. */ static void exception_cleanup(_Unwind_Reason_Code reason, struct _Unwind_Exception *ex) { // Exception layout: // [__cxa_exception [_Unwind_Exception]] [exception object] // // __cxa_free_exception expects a pointer to the exception object __cxa_free_exception(static_cast(ex + 1)); } static void dependent_exception_cleanup(_Unwind_Reason_Code reason, struct _Unwind_Exception *ex) { __cxa_free_dependent_exception(static_cast(ex + 1)); } /** * Recursively walk a list of exceptions and delete them all in post-order. */ static void free_exception_list(__cxa_exception *ex) { if (0 != ex->nextException) { free_exception_list(ex->nextException); } // __cxa_free_exception() expects to be passed the thrown object, which // immediately follows the exception, not the exception itself __cxa_free_exception(ex+1); } /** * Cleanup function called when a thread exists to make certain that all of the * per-thread data is deleted. */ static void thread_cleanup(void* thread_info) { __cxa_thread_info *info = static_cast<__cxa_thread_info*>(thread_info); if (info->globals.caughtExceptions) { // If this is a foreign exception, ask it to clean itself up. if (info->foreign_exception_state != __cxa_thread_info::none) { _Unwind_Exception *e = reinterpret_cast<_Unwind_Exception*>(info->globals.caughtExceptions); if (e->exception_cleanup) e->exception_cleanup(_URC_FOREIGN_EXCEPTION_CAUGHT, e); } else { free_exception_list(info->globals.caughtExceptions); } } free(thread_info); } /** * Once control used to protect the key creation. */ static pthread_once_t once_control = PTHREAD_ONCE_INIT; /** * We may not be linked against a full pthread implementation. If we're not, * then we need to fake the thread-local storage by storing 'thread-local' * things in a global. */ static bool fakeTLS; /** * Thread-local storage for a single-threaded program. */ static __cxa_thread_info singleThreadInfo; /** * Initialise eh_key. */ static void init_key(void) { if ((0 == pthread_key_create) || (0 == pthread_setspecific) || (0 == pthread_getspecific)) { fakeTLS = true; return; } pthread_key_create(&eh_key, thread_cleanup); pthread_setspecific(eh_key, reinterpret_cast(0x42)); fakeTLS = (pthread_getspecific(eh_key) != reinterpret_cast(0x42)); pthread_setspecific(eh_key, 0); } /** * Returns the thread info structure, creating it if it is not already created. */ static __cxa_thread_info *thread_info() { if ((0 == pthread_once) || pthread_once(&once_control, init_key)) { fakeTLS = true; } if (fakeTLS) { return &singleThreadInfo; } __cxa_thread_info *info = static_cast<__cxa_thread_info*>(pthread_getspecific(eh_key)); if (0 == info) { info = static_cast<__cxa_thread_info*>(calloc(1, sizeof(__cxa_thread_info))); pthread_setspecific(eh_key, info); } return info; } /** * Fast version of thread_info(). May fail if thread_info() is not called on * this thread at least once already. */ static __cxa_thread_info *thread_info_fast() { if (fakeTLS) { return &singleThreadInfo; } return static_cast<__cxa_thread_info*>(pthread_getspecific(eh_key)); } /** * ABI function returning the __cxa_eh_globals structure. */ extern "C" __cxa_eh_globals *ABI_NAMESPACE::__cxa_get_globals(void) { return &(thread_info()->globals); } /** * Version of __cxa_get_globals() assuming that __cxa_get_globals() has already * been called at least once by this thread. */ extern "C" __cxa_eh_globals *ABI_NAMESPACE::__cxa_get_globals_fast(void) { return &(thread_info_fast()->globals); } #ifdef LIBCXXRT_NO_EMERGENCY_MALLOC static char *alloc_or_die(size_t size) { char *buffer = static_cast(calloc(1, size)); if (buffer == nullptr) { fputs("Out of memory attempting to allocate exception\n", stderr); std::terminate(); } return buffer; } static void free_exception(char *e) { free(e); } #else /** * An emergency allocation reserved for when malloc fails. This is treated as * 16 buffers of 1KB each. */ static char emergency_buffer[16384]; /** * Flag indicating whether each buffer is allocated. */ static bool buffer_allocated[16]; /** * Lock used to protect emergency allocation. */ static pthread_mutex_t emergency_malloc_lock = PTHREAD_MUTEX_INITIALIZER; /** * Condition variable used to wait when two threads are both trying to use the * emergency malloc() buffer at once. */ static pthread_cond_t emergency_malloc_wait = PTHREAD_COND_INITIALIZER; /** * Allocates size bytes from the emergency allocation mechanism, if possible. * This function will fail if size is over 1KB or if this thread already has 4 * emergency buffers. If all emergency buffers are allocated, it will sleep * until one becomes available. */ static char *emergency_malloc(size_t size) { if (size > 1024) { return 0; } __cxa_thread_info *info = thread_info(); // Only 4 emergency buffers allowed per thread! if (info->emergencyBuffersHeld > 3) { return 0; } pthread_mutex_lock(&emergency_malloc_lock); int buffer = -1; while (buffer < 0) { // While we were sleeping on the lock, another thread might have free'd // enough memory for us to use, so try the allocation again - no point // using the emergency buffer if there is some real memory that we can // use... void *m = calloc(1, size); if (0 != m) { pthread_mutex_unlock(&emergency_malloc_lock); return static_cast(m); } for (int i=0 ; i<16 ; i++) { if (!buffer_allocated[i]) { buffer = i; buffer_allocated[i] = true; break; } } // If there still isn't a buffer available, then sleep on the condition // variable. This will be signalled when another thread releases one // of the emergency buffers. if (buffer < 0) { pthread_cond_wait(&emergency_malloc_wait, &emergency_malloc_lock); } } pthread_mutex_unlock(&emergency_malloc_lock); info->emergencyBuffersHeld++; return emergency_buffer + (1024 * buffer); } /** * Frees a buffer returned by emergency_malloc(). * * Note: Neither this nor emergency_malloc() is particularly efficient. This * should not matter, because neither will be called in normal operation - they * are only used when the program runs out of memory, which should not happen * often. */ static void emergency_malloc_free(char *ptr) { int buffer = -1; // Find the buffer corresponding to this pointer. for (int i=0 ; i<16 ; i++) { if (ptr == static_cast(emergency_buffer + (1024 * i))) { buffer = i; break; } } assert(buffer >= 0 && "Trying to free something that is not an emergency buffer!"); // emergency_malloc() is expected to return 0-initialized data. We don't // zero the buffer when allocating it, because the static buffers will // begin life containing 0 values. memset(ptr, 0, 1024); // Signal the condition variable to wake up any threads that are blocking // waiting for some space in the emergency buffer pthread_mutex_lock(&emergency_malloc_lock); // In theory, we don't need to do this with the lock held. In practice, // our array of bools will probably be updated using 32-bit or 64-bit // memory operations, so this update may clobber adjacent values. buffer_allocated[buffer] = false; pthread_cond_signal(&emergency_malloc_wait); pthread_mutex_unlock(&emergency_malloc_lock); } static char *alloc_or_die(size_t size) { char *buffer = static_cast(calloc(1, size)); // If calloc() doesn't want to give us any memory, try using an emergency // buffer. if (0 == buffer) { buffer = emergency_malloc(size); // This is only reached if the allocation is greater than 1KB, and // anyone throwing objects that big really should know better. if (0 == buffer) { fprintf(stderr, "Out of memory attempting to allocate exception\n"); std::terminate(); } } return buffer; } static void free_exception(char *e) { // If this allocation is within the address range of the emergency buffer, // don't call free() because it was not allocated with malloc() if ((e >= emergency_buffer) && (e < (emergency_buffer + sizeof(emergency_buffer)))) { emergency_malloc_free(e); } else { free(e); } } #endif /** * Allocates an exception structure. Returns a pointer to the space that can * be used to store an object of thrown_size bytes. This function will use an * emergency buffer if malloc() fails, and may block if there are no such * buffers available. */ -extern "C" void *__cxa_allocate_exception(size_t thrown_size) throw() +extern "C" void *__cxa_allocate_exception(size_t thrown_size) _LIBCXXRT_NOEXCEPT { size_t size = thrown_size + sizeof(__cxa_exception); char *buffer = alloc_or_die(size); return buffer+sizeof(__cxa_exception); } extern "C" void *__cxa_allocate_dependent_exception(void) { size_t size = sizeof(__cxa_dependent_exception); char *buffer = alloc_or_die(size); return buffer+sizeof(__cxa_dependent_exception); } /** * __cxa_free_exception() is called when an exception was thrown in between * calling __cxa_allocate_exception() and actually throwing the exception. * This happens when the object's copy constructor throws an exception. * * In this implementation, it is also called by __cxa_end_catch() and during * thread cleanup. */ -extern "C" void __cxa_free_exception(void *thrown_exception) throw() +extern "C" void __cxa_free_exception(void *thrown_exception) _LIBCXXRT_NOEXCEPT { __cxa_exception *ex = reinterpret_cast<__cxa_exception*>(thrown_exception) - 1; // Free the object that was thrown, calling its destructor if (0 != ex->exceptionDestructor) { try { ex->exceptionDestructor(thrown_exception); } catch(...) { // FIXME: Check that this is really what the spec says to do. std::terminate(); } } free_exception(reinterpret_cast(ex)); } static void releaseException(__cxa_exception *exception) { if (isDependentException(exception->unwindHeader.exception_class)) { __cxa_free_dependent_exception(exception+1); return; } if (__sync_sub_and_fetch(&exception->referenceCount, 1) == 0) { // __cxa_free_exception() expects to be passed the thrown object, // which immediately follows the exception, not the exception // itself __cxa_free_exception(exception+1); } } void __cxa_free_dependent_exception(void *thrown_exception) { __cxa_dependent_exception *ex = reinterpret_cast<__cxa_dependent_exception*>(thrown_exception) - 1; assert(isDependentException(ex->unwindHeader.exception_class)); if (ex->primaryException) { releaseException(realExceptionFromException(reinterpret_cast<__cxa_exception*>(ex))); } free_exception(reinterpret_cast(ex)); } -/** - * Callback function used with _Unwind_Backtrace(). - * - * Prints a stack trace. Used only for debugging help. - * - * Note: As of FreeBSD 8.1, dladd() still doesn't work properly, so this only - * correctly prints function names from public, relocatable, symbols. - */ -static _Unwind_Reason_Code trace(struct _Unwind_Context *context, void *c) -{ - Dl_info myinfo; - int mylookup = - dladdr(reinterpret_cast(__cxa_current_exception_type), &myinfo); - void *ip = reinterpret_cast(_Unwind_GetIP(context)); - Dl_info info; - if (dladdr(ip, &info) != 0) - { - if (mylookup == 0 || strcmp(info.dli_fname, myinfo.dli_fname) != 0) - { - printf("%p:%s() in %s\n", ip, info.dli_sname, info.dli_fname); - } - } - return _URC_CONTINUE_UNWIND; -} - /** * Report a failure that occurred when attempting to throw an exception. * * If the failure happened by falling off the end of the stack without finding - * a handler, prints a back trace before aborting. + * a handler, catch the exception before calling terminate. The default + * terminate handler will print a backtrace before aborting. */ #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4) -extern "C" void *__cxa_begin_catch(void *e) throw(); +extern "C" void *__cxa_begin_catch(void *e) _LIBCXXRT_NOEXCEPT; #else extern "C" void *__cxa_begin_catch(void *e); #endif static void report_failure(_Unwind_Reason_Code err, __cxa_exception *thrown_exception) { switch (err) { default: break; case _URC_FATAL_PHASE1_ERROR: fprintf(stderr, "Fatal error during phase 1 unwinding\n"); break; #if !defined(__arm__) || defined(__ARM_DWARF_EH__) case _URC_FATAL_PHASE2_ERROR: fprintf(stderr, "Fatal error during phase 2 unwinding\n"); break; #endif case _URC_END_OF_STACK: __cxa_begin_catch (&(thrown_exception->unwindHeader)); - std::terminate(); - fprintf(stderr, "Terminating due to uncaught exception %p", - static_cast(thrown_exception)); - thrown_exception = realExceptionFromException(thrown_exception); - static const __class_type_info *e_ti = - static_cast(&typeid(std::exception)); - const __class_type_info *throw_ti = - dynamic_cast(thrown_exception->exceptionType); - if (throw_ti) - { - std::exception *e = - static_cast(e_ti->cast_to(static_cast(thrown_exception+1), - throw_ti)); - if (e) - { - fprintf(stderr, " '%s'", e->what()); - } - } - - size_t bufferSize = 128; - char *demangled = static_cast(malloc(bufferSize)); - const char *mangled = thrown_exception->exceptionType->name(); - int status; - demangled = __cxa_demangle(mangled, demangled, &bufferSize, &status); - fprintf(stderr, " of type %s\n", - status == 0 ? demangled : mangled); - if (status == 0) { free(demangled); } - // Print a back trace if no handler is found. - // TODO: Make this optional -#ifndef __arm__ - _Unwind_Backtrace(trace, 0); -#endif - - // Just abort. No need to call std::terminate for the second time - abort(); break; } std::terminate(); } static void throw_exception(__cxa_exception *ex) { __cxa_thread_info *info = thread_info(); ex->unexpectedHandler = info->unexpectedHandler; if (0 == ex->unexpectedHandler) { ex->unexpectedHandler = unexpectedHandler.load(); } ex->terminateHandler = info->terminateHandler; if (0 == ex->terminateHandler) { ex->terminateHandler = terminateHandler.load(); } info->globals.uncaughtExceptions++; _Unwind_Reason_Code err = _Unwind_RaiseException(&ex->unwindHeader); // The _Unwind_RaiseException() function should not return, it should // unwind the stack past this function. If it does return, then something // has gone wrong. report_failure(err, ex); } extern "C" __cxa_exception *__cxa_init_primary_exception( - void *object, std::type_info* tinfo, void (*dest)(void *)) throw() { + void *object, std::type_info* tinfo, void (*dest)(void *)) _LIBCXXRT_NOEXCEPT { __cxa_exception *ex = reinterpret_cast<__cxa_exception*>(object) - 1; ex->referenceCount = 0; ex->exceptionType = tinfo; ex->exceptionDestructor = dest; ex->unwindHeader.exception_class = exception_class; ex->unwindHeader.exception_cleanup = exception_cleanup; return ex; } /** * ABI function for throwing an exception. Takes the object to be thrown (the * pointer returned by __cxa_allocate_exception()), the type info for the * pointee, and the destructor (if there is one) as arguments. */ extern "C" void __cxa_throw(void *thrown_exception, std::type_info *tinfo, void(*dest)(void*)) { __cxa_exception *ex = __cxa_init_primary_exception(thrown_exception, tinfo, dest); ex->referenceCount = 1; throw_exception(ex); } extern "C" void __cxa_rethrow_primary_exception(void* thrown_exception) { if (NULL == thrown_exception) { return; } __cxa_exception *original = exceptionFromPointer(thrown_exception); __cxa_dependent_exception *ex = reinterpret_cast<__cxa_dependent_exception*>(__cxa_allocate_dependent_exception())-1; ex->primaryException = thrown_exception; __cxa_increment_exception_refcount(thrown_exception); ex->exceptionType = original->exceptionType; ex->unwindHeader.exception_class = dependent_exception_class; ex->unwindHeader.exception_cleanup = dependent_exception_cleanup; throw_exception(reinterpret_cast<__cxa_exception*>(ex)); } extern "C" void *__cxa_current_primary_exception(void) { __cxa_eh_globals* globals = __cxa_get_globals(); __cxa_exception *ex = globals->caughtExceptions; if (0 == ex) { return NULL; } ex = realExceptionFromException(ex); __sync_fetch_and_add(&ex->referenceCount, 1); return ex + 1; } extern "C" void __cxa_increment_exception_refcount(void* thrown_exception) { if (NULL == thrown_exception) { return; } __cxa_exception *ex = static_cast<__cxa_exception*>(thrown_exception) - 1; if (isDependentException(ex->unwindHeader.exception_class)) { return; } __sync_fetch_and_add(&ex->referenceCount, 1); } extern "C" void __cxa_decrement_exception_refcount(void* thrown_exception) { if (NULL == thrown_exception) { return; } __cxa_exception *ex = static_cast<__cxa_exception*>(thrown_exception) - 1; releaseException(ex); } /** * ABI function. Rethrows the current exception. Does not remove the * exception from the stack or decrement its handler count - the compiler is * expected to set the landing pad for this function to the end of the catch * block, and then call _Unwind_Resume() to continue unwinding once * __cxa_end_catch() has been called and any cleanup code has been run. */ extern "C" void __cxa_rethrow() { __cxa_thread_info *ti = thread_info(); __cxa_eh_globals *globals = &ti->globals; // Note: We don't remove this from the caught list here, because // __cxa_end_catch will be called when we unwind out of the try block. We // could probably make this faster by providing an alternative rethrow // function and ensuring that all cleanup code is run before calling it, so // we can skip the top stack frame when unwinding. __cxa_exception *ex = globals->caughtExceptions; if (0 == ex) { fprintf(stderr, "Attempting to rethrow an exception that doesn't exist!\n"); std::terminate(); } if (ti->foreign_exception_state != __cxa_thread_info::none) { ti->foreign_exception_state = __cxa_thread_info::rethrown; _Unwind_Exception *e = reinterpret_cast<_Unwind_Exception*>(ex); _Unwind_Reason_Code err = _Unwind_Resume_or_Rethrow(e); report_failure(err, ex); return; } assert(ex->handlerCount > 0 && "Rethrowing uncaught exception!"); // `globals->uncaughtExceptions` was decremented by `__cxa_begin_catch`. // It's normally incremented by `throw_exception`, but this path invokes // `_Unwind_Resume_or_Rethrow` directly to rethrow the exception. // This path is only reachable if we're rethrowing a C++ exception - // foreign exceptions don't adjust any of this state. globals->uncaughtExceptions++; // ex->handlerCount will be decremented in __cxa_end_catch in enclosing // catch block // Make handler count negative. This will tell __cxa_end_catch that // exception was rethrown and exception object should not be destroyed // when handler count become zero ex->handlerCount = -ex->handlerCount; // Continue unwinding the stack with this exception. This should unwind to // the place in the caller where __cxa_end_catch() is called. The caller // will then run cleanup code and bounce the exception back with // _Unwind_Resume(). _Unwind_Reason_Code err = _Unwind_Resume_or_Rethrow(&ex->unwindHeader); report_failure(err, ex); } /** * Returns the type_info object corresponding to the filter. */ static std::type_info *get_type_info_entry(_Unwind_Context *context, dwarf_eh_lsda *lsda, int filter) { // Get the address of the record in the table. dw_eh_ptr_t record = lsda->type_table - dwarf_size_of_fixed_size_field(lsda->type_table_encoding)*filter; //record -= 4; dw_eh_ptr_t start = record; // Read the value, but it's probably an indirect reference... int64_t offset = read_value(lsda->type_table_encoding, &record); // (If the entry is 0, don't try to dereference it. That would be bad.) if (offset == 0) { return 0; } // ...so we need to resolve it return reinterpret_cast(resolve_indirect_value(context, lsda->type_table_encoding, offset, start)); } /** * Checks the type signature found in a handler against the type of the thrown * object. If ex is 0 then it is assumed to be a foreign exception and only * matches cleanups. */ static bool check_type_signature(__cxa_exception *ex, const std::type_info *type, void *&adjustedPtr) { void *exception_ptr = static_cast(ex+1); const std::type_info *ex_type = ex ? ex->exceptionType : 0; bool is_ptr = ex ? ex_type->__is_pointer_p() : false; if (is_ptr) { exception_ptr = *static_cast(exception_ptr); } // Always match a catchall, even with a foreign exception // // Note: A 0 here is a catchall, not a cleanup, so we return true to // indicate that we found a catch. if (0 == type) { if (ex) { adjustedPtr = exception_ptr; } return true; } if (0 == ex) { return false; } // If the types are the same, no casting is needed. if (*type == *ex_type) { adjustedPtr = exception_ptr; return true; } if (type->__do_catch(ex_type, &exception_ptr, 1)) { adjustedPtr = exception_ptr; return true; } return false; } /** * Checks whether the exception matches the type specifiers in this action * record. If the exception only matches cleanups, then this returns false. * If it matches a catch (including a catchall) then it returns true. * * The selector argument is used to return the selector that is passed in the * second exception register when installing the context. */ static handler_type check_action_record(_Unwind_Context *context, dwarf_eh_lsda *lsda, dw_eh_ptr_t action_record, __cxa_exception *ex, unsigned long *selector, void *&adjustedPtr) { if (!action_record) { return handler_cleanup; } handler_type found = handler_none; while (action_record) { int filter = read_sleb128(&action_record); dw_eh_ptr_t action_record_offset_base = action_record; int displacement = read_sleb128(&action_record); action_record = displacement ? action_record_offset_base + displacement : 0; // We only check handler types for C++ exceptions - foreign exceptions // are only allowed for cleanups and catchalls. if (filter > 0) { std::type_info *handler_type = get_type_info_entry(context, lsda, filter); if (check_type_signature(ex, handler_type, adjustedPtr)) { *selector = filter; return handler_catch; } } else if (filter < 0 && 0 != ex) { bool matched = false; *selector = filter; #if defined(__arm__) && !defined(__ARM_DWARF_EH__) filter++; std::type_info *handler_type = get_type_info_entry(context, lsda, filter--); while (handler_type) { if (check_type_signature(ex, handler_type, adjustedPtr)) { matched = true; break; } handler_type = get_type_info_entry(context, lsda, filter--); } #else unsigned char *type_index = reinterpret_cast(lsda->type_table) - filter - 1; while (*type_index) { std::type_info *handler_type = get_type_info_entry(context, lsda, *(type_index++)); // If the exception spec matches a permitted throw type for // this function, don't report a handler - we are allowed to // propagate this exception out. if (check_type_signature(ex, handler_type, adjustedPtr)) { matched = true; break; } } #endif if (matched) { continue; } // If we don't find an allowed exception spec, we need to install // the context for this action. The landing pad will then call the // unexpected exception function. Treat this as a catch return handler_catch; } else if (filter == 0) { *selector = filter; found = handler_cleanup; } } return found; } static void pushCleanupException(_Unwind_Exception *exceptionObject, __cxa_exception *ex) { #if defined(__arm__) && !defined(__ARM_DWARF_EH__) __cxa_thread_info *info = thread_info_fast(); if (ex) { ex->cleanupCount++; if (ex->cleanupCount > 1) { assert(exceptionObject == info->currentCleanup); return; } ex->nextCleanup = info->currentCleanup; } info->currentCleanup = exceptionObject; #endif } /** * The exception personality function. This is referenced in the unwinding * DWARF metadata and is called by the unwind library for each C++ stack frame * containing catch or cleanup code. */ extern "C" BEGIN_PERSONALITY_FUNCTION(__gxx_personality_v0) // This personality function is for version 1 of the ABI. If you use it // with a future version of the ABI, it won't know what to do, so it // reports a fatal error and give up before it breaks anything. if (1 != version) { return _URC_FATAL_PHASE1_ERROR; } __cxa_exception *ex = 0; __cxa_exception *realEx = 0; // If this exception is throw by something else then we can't make any // assumptions about its layout beyond the fields declared in // _Unwind_Exception. bool foreignException = !isCXXException(exceptionClass); // If this isn't a foreign exception, then we have a C++ exception structure if (!foreignException) { ex = exceptionFromPointer(exceptionObject); realEx = realExceptionFromException(ex); } #if defined(__arm__) && !defined(__ARM_DWARF_EH__) unsigned char *lsda_addr = static_cast(_Unwind_GetLanguageSpecificData(context)); #else unsigned char *lsda_addr = reinterpret_cast(static_cast(_Unwind_GetLanguageSpecificData(context))); #endif // No LSDA implies no landing pads - try the next frame if (0 == lsda_addr) { return continueUnwinding(exceptionObject, context); } // These two variables define how the exception will be handled. dwarf_eh_action action = {0}; unsigned long selector = 0; // During the search phase, we do a complete lookup. If we return // _URC_HANDLER_FOUND, then the phase 2 unwind will call this function with // a _UA_HANDLER_FRAME action, telling us to install the handler frame. If // we return _URC_CONTINUE_UNWIND, we may be called again later with a // _UA_CLEANUP_PHASE action for this frame. // // The point of the two-stage unwind allows us to entirely avoid any stack // unwinding if there is no handler. If there are just cleanups found, // then we can just panic call an abort function. // // Matching a handler is much more expensive than matching a cleanup, // because we don't need to bother doing type comparisons (or looking at // the type table at all) for a cleanup. This means that there is no need // to cache the result of finding a cleanup, because it's (quite) quick to // look it up again from the action table. if (actions & _UA_SEARCH_PHASE) { struct dwarf_eh_lsda lsda = parse_lsda(context, lsda_addr); if (!dwarf_eh_find_callsite(context, &lsda, &action)) { // EH range not found. This happens if exception is thrown and not // caught inside a cleanup (destructor). We should call // terminate() in this case. The catchTemp (landing pad) field of // exception object will contain null when personality function is // called with _UA_HANDLER_FRAME action for phase 2 unwinding. return _URC_HANDLER_FOUND; } handler_type found_handler = check_action_record(context, &lsda, action.action_record, realEx, &selector, ex->adjustedPtr); // If there's no action record, we've only found a cleanup, so keep // searching for something real if (found_handler == handler_catch) { // Cache the results for the phase 2 unwind, if we found a handler // and this is not a foreign exception. if (ex) { saveLandingPad(context, exceptionObject, ex, selector, action.landing_pad); ex->languageSpecificData = reinterpret_cast(lsda_addr); ex->actionRecord = reinterpret_cast(action.action_record); // ex->adjustedPtr is set when finding the action record. } return _URC_HANDLER_FOUND; } return continueUnwinding(exceptionObject, context); } // If this is a foreign exception, we didn't have anywhere to cache the // lookup stuff, so we need to do it again. If this is either a forced // unwind, a foreign exception, or a cleanup, then we just install the // context for a cleanup. if (!(actions & _UA_HANDLER_FRAME)) { // cleanup struct dwarf_eh_lsda lsda = parse_lsda(context, lsda_addr); dwarf_eh_find_callsite(context, &lsda, &action); if (0 == action.landing_pad) { return continueUnwinding(exceptionObject, context); } handler_type found_handler = check_action_record(context, &lsda, action.action_record, realEx, &selector, ex->adjustedPtr); // Ignore handlers this time. if (found_handler != handler_cleanup) { return continueUnwinding(exceptionObject, context); } pushCleanupException(exceptionObject, ex); } else if (foreignException) { struct dwarf_eh_lsda lsda = parse_lsda(context, lsda_addr); dwarf_eh_find_callsite(context, &lsda, &action); check_action_record(context, &lsda, action.action_record, realEx, &selector, ex->adjustedPtr); } else if (ex->catchTemp == 0) { // Uncaught exception in cleanup, calling terminate std::terminate(); } else { // Restore the saved info if we saved some last time. loadLandingPad(context, exceptionObject, ex, &selector, &action.landing_pad); ex->catchTemp = 0; ex->handlerSwitchValue = 0; } _Unwind_SetIP(context, reinterpret_cast(action.landing_pad)); _Unwind_SetGR(context, __builtin_eh_return_data_regno(0), reinterpret_cast(exceptionObject)); _Unwind_SetGR(context, __builtin_eh_return_data_regno(1), selector); return _URC_INSTALL_CONTEXT; } /** * ABI function called when entering a catch statement. The argument is the * pointer passed out of the personality function. This is always the start of * the _Unwind_Exception object. The return value for this function is the * pointer to the caught exception, which is either the adjusted pointer (for * C++ exceptions) of the unadjusted pointer (for foreign exceptions). */ #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4) -extern "C" void *__cxa_begin_catch(void *e) throw() +extern "C" void *__cxa_begin_catch(void *e) _LIBCXXRT_NOEXCEPT #else extern "C" void *__cxa_begin_catch(void *e) #endif { // We can't call the fast version here, because if the first exception that // we see is a foreign exception then we won't have called it yet. __cxa_thread_info *ti = thread_info(); __cxa_eh_globals *globals = &ti->globals; _Unwind_Exception *exceptionObject = static_cast<_Unwind_Exception*>(e); if (isCXXException(exceptionObject->exception_class)) { // Only exceptions thrown with a C++ exception throwing function will // increment this, so don't decrement it here. globals->uncaughtExceptions--; __cxa_exception *ex = exceptionFromPointer(exceptionObject); if (ex->handlerCount == 0) { // Add this to the front of the list of exceptions being handled // and increment its handler count so that it won't be deleted // prematurely. ex->nextException = globals->caughtExceptions; globals->caughtExceptions = ex; } if (ex->handlerCount < 0) { // Rethrown exception is catched before end of catch block. // Clear the rethrow flag (make value positive) - we are allowed // to delete this exception at the end of the catch block, as long // as it isn't thrown again later. // Code pattern: // // try { // throw x; // } // catch() { // try { // throw; // } // catch() { // __cxa_begin_catch() <- we are here // } // } ex->handlerCount = -ex->handlerCount + 1; } else { ex->handlerCount++; } ti->foreign_exception_state = __cxa_thread_info::none; return ex->adjustedPtr; } else { // If this is a foreign exception, then we need to be able to // store it. We can't chain foreign exceptions, so we give up // if there are already some outstanding ones. if (globals->caughtExceptions != 0) { std::terminate(); } globals->caughtExceptions = reinterpret_cast<__cxa_exception*>(exceptionObject); ti->foreign_exception_state = __cxa_thread_info::caught; } // exceptionObject is the pointer to the _Unwind_Exception within the // __cxa_exception. The throw object is after this return (reinterpret_cast(exceptionObject) + sizeof(_Unwind_Exception)); } /** * ABI function called when exiting a catch block. This will free the current * exception if it is no longer referenced in other catch blocks. */ extern "C" void __cxa_end_catch() { // We can call the fast version here because the slow version is called in // __cxa_throw(), which must have been called before we end a catch block __cxa_thread_info *ti = thread_info_fast(); __cxa_eh_globals *globals = &ti->globals; __cxa_exception *ex = globals->caughtExceptions; assert(0 != ex && "Ending catch when no exception is on the stack!"); if (ti->foreign_exception_state != __cxa_thread_info::none) { if (ti->foreign_exception_state != __cxa_thread_info::rethrown) { _Unwind_Exception *e = reinterpret_cast<_Unwind_Exception*>(ti->globals.caughtExceptions); if (e->exception_cleanup) e->exception_cleanup(_URC_FOREIGN_EXCEPTION_CAUGHT, e); } globals->caughtExceptions = 0; ti->foreign_exception_state = __cxa_thread_info::none; return; } bool deleteException = true; if (ex->handlerCount < 0) { // exception was rethrown. Exception should not be deleted even if // handlerCount become zero. // Code pattern: // try { // throw x; // } // catch() { // { // throw; // } // cleanup { // __cxa_end_catch(); <- we are here // } // } // ex->handlerCount++; deleteException = false; } else { ex->handlerCount--; } if (ex->handlerCount == 0) { globals->caughtExceptions = ex->nextException; if (deleteException) { releaseException(ex); } } } /** * ABI function. Returns the type of the current exception. */ extern "C" std::type_info *__cxa_current_exception_type() { __cxa_eh_globals *globals = __cxa_get_globals(); __cxa_exception *ex = globals->caughtExceptions; return ex ? ex->exceptionType : 0; } /** * Cleanup, ensures that `__cxa_end_catch` is called to balance an explicit * `__cxa_begin_catch` call. */ static void end_catch(char *) { __cxa_end_catch(); } /** * ABI function, called when an exception specification is violated. * * This function does not return. */ extern "C" void __cxa_call_unexpected(void*exception) { _Unwind_Exception *exceptionObject = static_cast<_Unwind_Exception*>(exception); // Wrap the call to the unexpected handler in calls to `__cxa_begin_catch` // and `__cxa_end_catch` so that we correctly update exception counts if // the unexpected handler throws an exception. __cxa_begin_catch(exceptionObject); __attribute__((cleanup(end_catch))) char unused; if (exceptionObject->exception_class == exception_class) { __cxa_exception *ex = exceptionFromPointer(exceptionObject); if (ex->unexpectedHandler) { ex->unexpectedHandler(); // Should not be reached. abort(); } } std::unexpected(); // Should not be reached. abort(); } /** * ABI function, called when an object destructor exits due to an * exception during stack unwinding. * * This function does not return. */ -extern "C" void __cxa_call_terminate(void *exception) throw() +extern "C" void __cxa_call_terminate(void*exception) _LIBCXXRT_NOEXCEPT { std::terminate(); // Should not be reached. abort(); } /** * ABI function, returns the adjusted pointer to the exception object. */ extern "C" void *__cxa_get_exception_ptr(void *exceptionObject) { return exceptionFromPointer(exceptionObject)->adjustedPtr; } /** * As an extension, we provide the ability for the unexpected and terminate * handlers to be thread-local. We default to the standards-compliant * behaviour where they are global. */ static bool thread_local_handlers = false; namespace pathscale { /** * Sets whether unexpected and terminate handlers should be thread-local. */ - void set_use_thread_local_handlers(bool flag) throw() + void set_use_thread_local_handlers(bool flag) _LIBCXXRT_NOEXCEPT { thread_local_handlers = flag; } /** * Sets a thread-local unexpected handler. */ - unexpected_handler set_unexpected(unexpected_handler f) throw() + unexpected_handler set_unexpected(unexpected_handler f) _LIBCXXRT_NOEXCEPT { static __cxa_thread_info *info = thread_info(); unexpected_handler old = info->unexpectedHandler; info->unexpectedHandler = f; return old; } /** * Sets a thread-local terminate handler. */ - terminate_handler set_terminate(terminate_handler f) throw() + terminate_handler set_terminate(terminate_handler f) _LIBCXXRT_NOEXCEPT { static __cxa_thread_info *info = thread_info(); terminate_handler old = info->terminateHandler; info->terminateHandler = f; return old; } } namespace std { /** * Sets the function that will be called when an exception specification is * violated. */ - unexpected_handler set_unexpected(unexpected_handler f) throw() + unexpected_handler set_unexpected(unexpected_handler f) _LIBCXXRT_NOEXCEPT { if (thread_local_handlers) { return pathscale::set_unexpected(f); } return unexpectedHandler.exchange(f); } /** * Sets the function that is called to terminate the program. */ - terminate_handler set_terminate(terminate_handler f) throw() + terminate_handler set_terminate(terminate_handler f) _LIBCXXRT_NOEXCEPT { if (thread_local_handlers) { return pathscale::set_terminate(f); } return terminateHandler.exchange(f); } /** * Terminates the program, calling a custom terminate implementation if * required. */ - void terminate() + [[noreturn]] void terminate() _LIBCXXRT_NOEXCEPT { static __cxa_thread_info *info = thread_info(); if (0 != info && 0 != info->terminateHandler) { info->terminateHandler(); // Should not be reached - a terminate handler is not expected to // return. abort(); } terminateHandler.load()(); } /** * Called when an unexpected exception is encountered (i.e. an exception * violates an exception specification). This calls abort() unless a * custom handler has been set.. */ void unexpected() { static __cxa_thread_info *info = thread_info(); if (0 != info && 0 != info->unexpectedHandler) { info->unexpectedHandler(); // Should not be reached - a terminate handler is not expected to // return. abort(); } unexpectedHandler.load()(); } /** * Returns whether there are any exceptions currently being thrown that * have not been caught. This can occur inside a nested catch statement. */ - bool uncaught_exception() throw() + bool uncaught_exception() _LIBCXXRT_NOEXCEPT { __cxa_thread_info *info = thread_info(); return info->globals.uncaughtExceptions != 0; } /** * Returns the number of exceptions currently being thrown that have not * been caught. This can occur inside a nested catch statement. */ - int uncaught_exceptions() throw() + int uncaught_exceptions() _LIBCXXRT_NOEXCEPT { __cxa_thread_info *info = thread_info(); return info->globals.uncaughtExceptions; } /** * Returns the current unexpected handler. */ - unexpected_handler get_unexpected() throw() + unexpected_handler get_unexpected() _LIBCXXRT_NOEXCEPT { __cxa_thread_info *info = thread_info(); if (info->unexpectedHandler) { return info->unexpectedHandler; } return unexpectedHandler.load(); } /** * Returns the current terminate handler. */ - terminate_handler get_terminate() throw() + terminate_handler get_terminate() _LIBCXXRT_NOEXCEPT { __cxa_thread_info *info = thread_info(); if (info->terminateHandler) { return info->terminateHandler; } return terminateHandler.load(); } } #if defined(__arm__) && !defined(__ARM_DWARF_EH__) extern "C" _Unwind_Exception *__cxa_get_cleanup(void) { __cxa_thread_info *info = thread_info_fast(); _Unwind_Exception *exceptionObject = info->currentCleanup; if (isCXXException(exceptionObject->exception_class)) { __cxa_exception *ex = exceptionFromPointer(exceptionObject); ex->cleanupCount--; if (ex->cleanupCount == 0) { info->currentCleanup = ex->nextCleanup; ex->nextCleanup = 0; } } else { info->currentCleanup = 0; } return exceptionObject; } asm ( ".pushsection .text.__cxa_end_cleanup \n" ".global __cxa_end_cleanup \n" ".type __cxa_end_cleanup, \"function\" \n" "__cxa_end_cleanup: \n" " push {r1, r2, r3, r4} \n" " mov r4, lr \n" " bl __cxa_get_cleanup \n" " mov lr, r4 \n" " pop {r1, r2, r3, r4} \n" " b _Unwind_Resume \n" " bl abort \n" ".popsection \n" ); #endif diff --git a/contrib/libcxxrt/libelftc_dem_gnu3.c b/contrib/libcxxrt/libelftc_dem_gnu3.c index dbdbd6f2414e..7e03385e2d16 100644 --- a/contrib/libcxxrt/libelftc_dem_gnu3.c +++ b/contrib/libcxxrt/libelftc_dem_gnu3.c @@ -1,4326 +1,4320 @@ /*- * Copyright (c) 2007 Hyogeol Lee * Copyright (c) 2015-2017 Kai Wang * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer * in this position and unchanged. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #include #include #include #include #include #include #include #include /** * @file cpp_demangle.c * @brief Decode IA-64 C++ ABI style implementation. * * IA-64 standard ABI(Itanium C++ ABI) references. * * http://www.codesourcery.com/cxx-abi/abi.html#mangling \n * http://www.codesourcery.com/cxx-abi/abi-mangling.html */ /** @brief Dynamic vector data for string. */ struct vector_str { /** Current size */ size_t size; /** Total capacity */ size_t capacity; /** String array */ char **container; }; #define BUFFER_GROWFACTOR 1.618 #define BUFFER_GROW(x) (((x)+0.5)*BUFFER_GROWFACTOR) #define ELFTC_FAILURE 0 #define ELFTC_ISDIGIT(C) (isdigit((C) & 0xFF)) #define ELFTC_SUCCESS 1 #define VECTOR_DEF_CAPACITY 8 enum type_qualifier { TYPE_PTR, TYPE_REF, TYPE_CMX, TYPE_IMG, TYPE_EXT, TYPE_RST, TYPE_VAT, TYPE_CST, TYPE_VEC, TYPE_RREF }; struct vector_type_qualifier { size_t size, capacity; enum type_qualifier *q_container; struct vector_str ext_name; }; enum read_cmd { READ_FAIL, READ_NEST, READ_TMPL, READ_EXPR, READ_EXPL, READ_LOCAL, READ_TYPE, READ_FUNC, READ_PTRMEM }; struct read_cmd_item { enum read_cmd cmd; void *data; }; struct vector_read_cmd { size_t size, capacity; struct read_cmd_item *r_container; }; enum push_qualifier { PUSH_ALL_QUALIFIER, PUSH_CV_QUALIFIER, PUSH_NON_CV_QUALIFIER, }; struct cpp_demangle_data { struct vector_str output; /* output string vector */ struct vector_str subst; /* substitution string vector */ struct vector_str tmpl; struct vector_str class_type; struct vector_str *cur_output; /* ptr to current output vec */ struct vector_read_cmd cmd; bool mem_rst; /* restrict member function */ bool mem_vat; /* volatile member function */ bool mem_cst; /* const member function */ bool mem_ref; /* lvalue-ref member func */ bool mem_rref; /* rvalue-ref member func */ bool is_tmpl; /* template args */ bool is_functype; /* function type */ bool ref_qualifier; /* ref qualifier */ enum type_qualifier ref_qualifier_type; /* ref qualifier type */ enum push_qualifier push_qualifier; /* which qualifiers to push */ int func_type; const char *cur; /* current mangled name ptr */ const char *last_sname; /* last source name */ }; struct type_delimit { bool paren; bool firstp; }; #define CPP_DEMANGLE_TRY_LIMIT 128 #define FLOAT_SPRINTF_TRY_LIMIT 5 #define FLOAT_QUADRUPLE_BYTES 16 #define FLOAT_EXTENED_BYTES 10 #define SIMPLE_HASH(x,y) (64 * x + y) #define DEM_PUSH_STR(d,s) cpp_demangle_push_str((d), (s), strlen((s))) #define VEC_PUSH_STR(d,s) vector_str_push((d), (s), strlen((s))) static size_t get_strlen_sum(const struct vector_str *v); static bool vector_str_grow(struct vector_str *v); static size_t get_strlen_sum(const struct vector_str *v) { size_t i, len = 0; if (v == NULL) return (0); assert(v->size > 0); for (i = 0; i < v->size; ++i) len += strlen(v->container[i]); return (len); } /** * @brief Deallocate resource in vector_str. */ static void vector_str_dest(struct vector_str *v) { size_t i; if (v == NULL) return; for (i = 0; i < v->size; ++i) free(v->container[i]); free(v->container); } /** * @brief Find string in vector_str. * @param v Destination vector. * @param o String to find. * @param l Length of the string. * @return -1 at failed, 0 at not found, 1 at found. */ static int vector_str_find(const struct vector_str *v, const char *o, size_t l) { size_t i; if (v == NULL || o == NULL) return (-1); for (i = 0; i < v->size; ++i) if (strncmp(v->container[i], o, l) == 0) return (1); return (0); } /** * @brief Get new allocated flat string from vector. * * If l is not NULL, return length of the string. * @param v Destination vector. * @param l Length of the string. * @return NULL at failed or NUL terminated new allocated string. */ static char * vector_str_get_flat(const struct vector_str *v, size_t *l) { - ssize_t elem_pos, elem_size, rtn_size; size_t i; - char *rtn; + char *rtn, *p; + ssize_t rtn_size; if (v == NULL || v->size == 0) return (NULL); if ((rtn_size = get_strlen_sum(v)) == 0) return (NULL); if ((rtn = malloc(sizeof(char) * (rtn_size + 1))) == NULL) return (NULL); - elem_pos = 0; - for (i = 0; i < v->size; ++i) { - elem_size = strlen(v->container[i]); - - memcpy(rtn + elem_pos, v->container[i], elem_size); - - elem_pos += elem_size; - } - - rtn[rtn_size] = '\0'; + p = rtn; + for (i = 0; i < v->size; ++i) + p = stpcpy(p, v->container[i]); if (l != NULL) *l = rtn_size; return (rtn); } static bool vector_str_grow(struct vector_str *v) { size_t i, tmp_cap; char **tmp_ctn; if (v == NULL) return (false); assert(v->capacity > 0); tmp_cap = BUFFER_GROW(v->capacity); assert(tmp_cap > v->capacity); if ((tmp_ctn = malloc(sizeof(char *) * tmp_cap)) == NULL) return (false); for (i = 0; i < v->size; ++i) tmp_ctn[i] = v->container[i]; free(v->container); v->container = tmp_ctn; v->capacity = tmp_cap; return (true); } /** * @brief Initialize vector_str. * @return false at failed, true at success. */ static bool vector_str_init(struct vector_str *v) { if (v == NULL) return (false); v->size = 0; v->capacity = VECTOR_DEF_CAPACITY; assert(v->capacity > 0); if ((v->container = malloc(sizeof(char *) * v->capacity)) == NULL) return (false); assert(v->container != NULL); return (true); } /** * @brief Remove last element in vector_str. * @return false at failed, true at success. */ static bool vector_str_pop(struct vector_str *v) { if (v == NULL) return (false); if (v->size == 0) return (true); --v->size; free(v->container[v->size]); v->container[v->size] = NULL; return (true); } +/** + * @brief Implements strlcpy() without result. + */ +static void +copy_string(char *dst, const char *src, size_t dsize) +{ + size_t remain; + if ((remain = dsize)) + while (--remain) + if (!(*dst++ = *src++)) + break; + if (!remain && dsize) + *dst = 0; +} + /** * @brief Push back string to vector. * @return false at failed, true at success. */ static bool vector_str_push(struct vector_str *v, const char *str, size_t len) { if (v == NULL || str == NULL) return (false); if (v->size == v->capacity && vector_str_grow(v) == false) return (false); if ((v->container[v->size] = malloc(sizeof(char) * (len + 1))) == NULL) return (false); - snprintf(v->container[v->size], len + 1, "%s", str); + copy_string(v->container[v->size], str, len + 1); ++v->size; return (true); } /** * @brief Push front org vector to det vector. * @return false at failed, true at success. */ static bool vector_str_push_vector_head(struct vector_str *dst, struct vector_str *org) { size_t i, j, tmp_cap; char **tmp_ctn; if (dst == NULL || org == NULL) return (false); tmp_cap = BUFFER_GROW(dst->size + org->size); if ((tmp_ctn = malloc(sizeof(char *) * tmp_cap)) == NULL) return (false); for (i = 0; i < org->size; ++i) if ((tmp_ctn[i] = strdup(org->container[i])) == NULL) { for (j = 0; j < i; ++j) free(tmp_ctn[j]); free(tmp_ctn); return (false); } for (i = 0; i < dst->size; ++i) tmp_ctn[i + org->size] = dst->container[i]; free(dst->container); dst->container = tmp_ctn; dst->capacity = tmp_cap; dst->size += org->size; return (true); } /** * @brief Push org vector to the tail of det vector. * @return false at failed, true at success. */ static bool vector_str_push_vector(struct vector_str *dst, struct vector_str *org) { size_t i, j, tmp_cap; char **tmp_ctn; if (dst == NULL || org == NULL) return (false); tmp_cap = BUFFER_GROW(dst->size + org->size); if ((tmp_ctn = malloc(sizeof(char *) * tmp_cap)) == NULL) return (false); for (i = 0; i < dst->size; ++i) tmp_ctn[i] = dst->container[i]; for (i = 0; i < org->size; ++i) if ((tmp_ctn[i + dst->size] = strdup(org->container[i])) == NULL) { for (j = 0; j < i + dst->size; ++j) free(tmp_ctn[j]); free(tmp_ctn); return (false); } free(dst->container); dst->container = tmp_ctn; dst->capacity = tmp_cap; dst->size += org->size; return (true); } /** * @brief Get new allocated flat string from vector between begin and end. * * If r_len is not NULL, string length will be returned. * @return NULL at failed or NUL terminated new allocated string. */ static char * vector_str_substr(const struct vector_str *v, size_t begin, size_t end, size_t *r_len) { - size_t cur, i, len; - char *rtn; + char *rtn, *p; + size_t i, len; if (v == NULL || begin > end) return (NULL); len = 0; for (i = begin; i < end + 1; ++i) len += strlen(v->container[i]); if ((rtn = malloc(sizeof(char) * (len + 1))) == NULL) return (NULL); if (r_len != NULL) *r_len = len; - cur = 0; - for (i = begin; i < end + 1; ++i) { - len = strlen(v->container[i]); - memcpy(rtn + cur, v->container[i], len); - cur += len; - } - rtn[cur] = '\0'; + p = rtn; + for (i = begin; i < end + 1; ++i) + p = stpcpy(p, v->container[i]); return (rtn); } static void cpp_demangle_data_dest(struct cpp_demangle_data *); static int cpp_demangle_data_init(struct cpp_demangle_data *, const char *); static int cpp_demangle_get_subst(struct cpp_demangle_data *, size_t); static int cpp_demangle_get_tmpl_param(struct cpp_demangle_data *, size_t); static int cpp_demangle_push_fp(struct cpp_demangle_data *, char *(*)(const char *, size_t)); static int cpp_demangle_push_str(struct cpp_demangle_data *, const char *, size_t); static int cpp_demangle_pop_str(struct cpp_demangle_data *); static int cpp_demangle_push_subst(struct cpp_demangle_data *, const char *, size_t); static int cpp_demangle_push_subst_v(struct cpp_demangle_data *, struct vector_str *); static int cpp_demangle_push_type_qualifier(struct cpp_demangle_data *, struct vector_type_qualifier *, const char *); static int cpp_demangle_read_array(struct cpp_demangle_data *); static int cpp_demangle_read_encoding(struct cpp_demangle_data *); static int cpp_demangle_read_expr_primary(struct cpp_demangle_data *); static int cpp_demangle_read_expression(struct cpp_demangle_data *); static int cpp_demangle_read_expression_flat(struct cpp_demangle_data *, char **); static int cpp_demangle_read_expression_binary(struct cpp_demangle_data *, const char *, size_t); static int cpp_demangle_read_expression_unary(struct cpp_demangle_data *, const char *, size_t); static int cpp_demangle_read_expression_trinary(struct cpp_demangle_data *, const char *, size_t, const char *, size_t); static int cpp_demangle_read_function(struct cpp_demangle_data *, int *, struct vector_type_qualifier *); static int cpp_demangle_local_source_name(struct cpp_demangle_data *ddata); static int cpp_demangle_read_local_name(struct cpp_demangle_data *); static int cpp_demangle_read_name(struct cpp_demangle_data *); static int cpp_demangle_read_name_flat(struct cpp_demangle_data *, char**); static int cpp_demangle_read_nested_name(struct cpp_demangle_data *); static int cpp_demangle_read_number(struct cpp_demangle_data *, long *); static int cpp_demangle_read_number_as_string(struct cpp_demangle_data *, char **); static int cpp_demangle_read_nv_offset(struct cpp_demangle_data *); static int cpp_demangle_read_offset(struct cpp_demangle_data *); static int cpp_demangle_read_offset_number(struct cpp_demangle_data *); static int cpp_demangle_read_pointer_to_member(struct cpp_demangle_data *, struct vector_type_qualifier *); static int cpp_demangle_read_sname(struct cpp_demangle_data *); static int cpp_demangle_read_subst(struct cpp_demangle_data *); static int cpp_demangle_read_subst_std(struct cpp_demangle_data *); static int cpp_demangle_read_subst_stdtmpl(struct cpp_demangle_data *, const char *); static int cpp_demangle_read_tmpl_arg(struct cpp_demangle_data *); static int cpp_demangle_read_tmpl_args(struct cpp_demangle_data *); static int cpp_demangle_read_tmpl_param(struct cpp_demangle_data *); static int cpp_demangle_read_type(struct cpp_demangle_data *, struct type_delimit *); static int cpp_demangle_read_type_flat(struct cpp_demangle_data *, char **); static int cpp_demangle_read_uqname(struct cpp_demangle_data *); static int cpp_demangle_read_v_offset(struct cpp_demangle_data *); static char *decode_fp_to_double(const char *, size_t); static char *decode_fp_to_float(const char *, size_t); static char *decode_fp_to_float128(const char *, size_t); static char *decode_fp_to_float80(const char *, size_t); static char *decode_fp_to_long_double(const char *, size_t); static int hex_to_dec(char); static void vector_read_cmd_dest(struct vector_read_cmd *); static struct read_cmd_item *vector_read_cmd_find(struct vector_read_cmd *, enum read_cmd); static int vector_read_cmd_init(struct vector_read_cmd *); static int vector_read_cmd_pop(struct vector_read_cmd *); static int vector_read_cmd_push(struct vector_read_cmd *, enum read_cmd, void *); static void vector_type_qualifier_dest(struct vector_type_qualifier *); static int vector_type_qualifier_init(struct vector_type_qualifier *); static int vector_type_qualifier_push(struct vector_type_qualifier *, enum type_qualifier); /** * @brief Decode the input string by IA-64 C++ ABI style. * * GNU GCC v3 use IA-64 standard ABI. * @return New allocated demangled string or NULL if failed. * @todo 1. Testing and more test case. 2. Code cleaning. */ char * __cxa_demangle_gnu3(const char *org) { struct cpp_demangle_data ddata; struct vector_str ret_type; struct type_delimit td; ssize_t org_len; unsigned int limit; char *rtn = NULL; bool has_ret = false, more_type = false; if (org == NULL) return (NULL); org_len = strlen(org); // Try demangling as a type for short encodings if ((org_len < 2) || (org[0] != '_' || org[1] != 'Z' )) { if (!cpp_demangle_data_init(&ddata, org)) return (NULL); if (!cpp_demangle_read_type(&ddata, 0)) goto clean; rtn = vector_str_get_flat(&ddata.output, (size_t *) NULL); goto clean; } if (org_len > 11 && !strncmp(org, "_GLOBAL__I_", 11)) { if ((rtn = malloc(org_len + 19)) == NULL) return (NULL); snprintf(rtn, org_len + 19, "global constructors keyed to %s", org + 11); return (rtn); } if (!cpp_demangle_data_init(&ddata, org + 2)) return (NULL); if (!cpp_demangle_read_encoding(&ddata)) goto clean; /* * Pop function name from substitution candidate list. */ if (*ddata.cur != 0 && ddata.subst.size >= 1) { if (!vector_str_pop(&ddata.subst)) goto clean; } td.paren = false; td.firstp = true; limit = 0; /* * The first type is a return type if we just demangled template * args. (the template args is right next to the function name, * which means it's a template function) */ if (ddata.is_tmpl) { ddata.is_tmpl = false; if (!vector_str_init(&ret_type)) goto clean; ddata.cur_output = &ret_type; has_ret = true; } while (*ddata.cur != '\0') { /* * Breaking at some gcc info at tail. e.g) @@GLIBCXX_3.4 */ if (*ddata.cur == '@' && *(ddata.cur + 1) == '@') break; if (has_ret) { /* Read return type */ if (!cpp_demangle_read_type(&ddata, NULL)) goto clean; } else { /* Read function arg type */ if (!cpp_demangle_read_type(&ddata, &td)) goto clean; } if (has_ret) { /* Push return type to the beginning */ if (!VEC_PUSH_STR(&ret_type, " ")) goto clean; if (!vector_str_push_vector_head(&ddata.output, &ret_type)) goto clean; ddata.cur_output = &ddata.output; vector_str_dest(&ret_type); has_ret = false; more_type = true; } else if (more_type) more_type = false; if (limit++ > CPP_DEMANGLE_TRY_LIMIT) goto clean; } if (more_type) goto clean; if (ddata.output.size == 0) goto clean; if (td.paren && !VEC_PUSH_STR(&ddata.output, ")")) goto clean; if (ddata.mem_vat && !VEC_PUSH_STR(&ddata.output, " volatile")) goto clean; if (ddata.mem_cst && !VEC_PUSH_STR(&ddata.output, " const")) goto clean; if (ddata.mem_rst && !VEC_PUSH_STR(&ddata.output, " restrict")) goto clean; if (ddata.mem_ref && !VEC_PUSH_STR(&ddata.output, " &")) goto clean; if (ddata.mem_rref && !VEC_PUSH_STR(&ddata.output, " &&")) goto clean; rtn = vector_str_get_flat(&ddata.output, (size_t *) NULL); clean: if (has_ret) vector_str_dest(&ret_type); cpp_demangle_data_dest(&ddata); return (rtn); } static void cpp_demangle_data_dest(struct cpp_demangle_data *d) { if (d == NULL) return; vector_read_cmd_dest(&d->cmd); vector_str_dest(&d->class_type); vector_str_dest(&d->tmpl); vector_str_dest(&d->subst); vector_str_dest(&d->output); } static int cpp_demangle_data_init(struct cpp_demangle_data *d, const char *cur) { if (d == NULL || cur == NULL) return (0); if (!vector_str_init(&d->output)) return (0); if (!vector_str_init(&d->subst)) goto clean1; if (!vector_str_init(&d->tmpl)) goto clean2; if (!vector_str_init(&d->class_type)) goto clean3; if (!vector_read_cmd_init(&d->cmd)) goto clean4; assert(d->output.container != NULL); assert(d->subst.container != NULL); assert(d->tmpl.container != NULL); assert(d->class_type.container != NULL); d->mem_rst = false; d->mem_vat = false; d->mem_cst = false; d->mem_ref = false; d->mem_rref = false; d->is_tmpl = false; d->is_functype = false; d->ref_qualifier = false; d->push_qualifier = PUSH_ALL_QUALIFIER; d->func_type = 0; d->cur = cur; d->cur_output = &d->output; d->last_sname = NULL; return (1); clean4: vector_str_dest(&d->class_type); clean3: vector_str_dest(&d->tmpl); clean2: vector_str_dest(&d->subst); clean1: vector_str_dest(&d->output); return (0); } static int cpp_demangle_push_fp(struct cpp_demangle_data *ddata, char *(*decoder)(const char *, size_t)) { size_t len; int rtn; const char *fp; char *f; if (ddata == NULL || decoder == NULL) return (0); fp = ddata->cur; while (*ddata->cur != 'E') ++ddata->cur; if ((f = decoder(fp, ddata->cur - fp)) == NULL) return (0); rtn = 0; if ((len = strlen(f)) > 0) rtn = cpp_demangle_push_str(ddata, f, len); free(f); ++ddata->cur; return (rtn); } static int cpp_demangle_push_str(struct cpp_demangle_data *ddata, const char *str, size_t len) { if (ddata == NULL || str == NULL || len == 0) return (0); /* * is_tmpl is used to check if the type (function arg) is right next * to template args, and should always be cleared whenever new string * pushed. */ ddata->is_tmpl = false; return (vector_str_push(ddata->cur_output, str, len)); } static int cpp_demangle_pop_str(struct cpp_demangle_data *ddata) { if (ddata == NULL) return (0); return (vector_str_pop(ddata->cur_output)); } static int cpp_demangle_push_subst(struct cpp_demangle_data *ddata, const char *str, size_t len) { if (ddata == NULL || str == NULL || len == 0) return (0); if (!vector_str_find(&ddata->subst, str, len)) return (vector_str_push(&ddata->subst, str, len)); return (1); } static int cpp_demangle_push_subst_v(struct cpp_demangle_data *ddata, struct vector_str *v) { size_t str_len; int rtn; char *str; if (ddata == NULL || v == NULL) return (0); if ((str = vector_str_get_flat(v, &str_len)) == NULL) return (0); rtn = cpp_demangle_push_subst(ddata, str, str_len); free(str); return (rtn); } static int cpp_demangle_push_type_qualifier(struct cpp_demangle_data *ddata, struct vector_type_qualifier *v, const char *type_str) { struct vector_str subst_v; enum type_qualifier t; size_t idx, e_idx, e_len; char *buf; int rtn; bool cv; if (ddata == NULL || v == NULL) return (0); if ((idx = v->size) == 0) return (1); rtn = 0; if (type_str != NULL) { if (!vector_str_init(&subst_v)) return (0); if (!VEC_PUSH_STR(&subst_v, type_str)) goto clean; } cv = true; e_idx = 0; while (idx > 0) { switch (v->q_container[idx - 1]) { case TYPE_PTR: cv = false; if (ddata->push_qualifier == PUSH_CV_QUALIFIER) break; if (!DEM_PUSH_STR(ddata, "*")) goto clean; if (type_str != NULL) { if (!VEC_PUSH_STR(&subst_v, "*")) goto clean; if (!cpp_demangle_push_subst_v(ddata, &subst_v)) goto clean; } break; case TYPE_REF: cv = false; if (ddata->push_qualifier == PUSH_CV_QUALIFIER) break; if (!DEM_PUSH_STR(ddata, "&")) goto clean; if (type_str != NULL) { if (!VEC_PUSH_STR(&subst_v, "&")) goto clean; if (!cpp_demangle_push_subst_v(ddata, &subst_v)) goto clean; } break; case TYPE_RREF: cv = false; if (ddata->push_qualifier == PUSH_CV_QUALIFIER) break; if (!DEM_PUSH_STR(ddata, "&&")) goto clean; if (type_str != NULL) { if (!VEC_PUSH_STR(&subst_v, "&&")) goto clean; if (!cpp_demangle_push_subst_v(ddata, &subst_v)) goto clean; } break; case TYPE_CMX: cv = false; if (ddata->push_qualifier == PUSH_CV_QUALIFIER) break; if (!DEM_PUSH_STR(ddata, " complex")) goto clean; if (type_str != NULL) { if (!VEC_PUSH_STR(&subst_v, " complex")) goto clean; if (!cpp_demangle_push_subst_v(ddata, &subst_v)) goto clean; } break; case TYPE_IMG: cv = false; if (ddata->push_qualifier == PUSH_CV_QUALIFIER) break; if (!DEM_PUSH_STR(ddata, " imaginary")) goto clean; if (type_str != NULL) { if (!VEC_PUSH_STR(&subst_v, " imaginary")) goto clean; if (!cpp_demangle_push_subst_v(ddata, &subst_v)) goto clean; } break; case TYPE_EXT: cv = false; if (ddata->push_qualifier == PUSH_CV_QUALIFIER) break; if (v->ext_name.size == 0 || e_idx > v->ext_name.size - 1) goto clean; if ((e_len = strlen(v->ext_name.container[e_idx])) == 0) goto clean; if ((buf = malloc(e_len + 2)) == NULL) goto clean; snprintf(buf, e_len + 2, " %s", v->ext_name.container[e_idx]); if (!DEM_PUSH_STR(ddata, buf)) { free(buf); goto clean; } if (type_str != NULL) { if (!VEC_PUSH_STR(&subst_v, buf)) { free(buf); goto clean; } if (!cpp_demangle_push_subst_v(ddata, &subst_v)) { free(buf); goto clean; } } free(buf); ++e_idx; break; case TYPE_RST: if (ddata->push_qualifier == PUSH_NON_CV_QUALIFIER && cv) break; if (ddata->push_qualifier == PUSH_CV_QUALIFIER && !cv) break; if (!DEM_PUSH_STR(ddata, " restrict")) goto clean; if (type_str != NULL) { if (!VEC_PUSH_STR(&subst_v, " restrict")) goto clean; if (idx - 1 > 0) { t = v->q_container[idx - 2]; if (t == TYPE_RST || t == TYPE_VAT || t == TYPE_CST) break; } if (!cpp_demangle_push_subst_v(ddata, &subst_v)) goto clean; } break; case TYPE_VAT: if (ddata->push_qualifier == PUSH_NON_CV_QUALIFIER && cv) break; if (ddata->push_qualifier == PUSH_CV_QUALIFIER && !cv) break; if (!DEM_PUSH_STR(ddata, " volatile")) goto clean; if (type_str != NULL) { if (!VEC_PUSH_STR(&subst_v, " volatile")) goto clean; if (idx - 1 > 0) { t = v->q_container[idx - 2]; if (t == TYPE_RST || t == TYPE_VAT || t == TYPE_CST) break; } if (!cpp_demangle_push_subst_v(ddata, &subst_v)) goto clean; } break; case TYPE_CST: if (ddata->push_qualifier == PUSH_NON_CV_QUALIFIER && cv) break; if (ddata->push_qualifier == PUSH_CV_QUALIFIER && !cv) break; if (!DEM_PUSH_STR(ddata, " const")) goto clean; if (type_str != NULL) { if (!VEC_PUSH_STR(&subst_v, " const")) goto clean; if (idx - 1 > 0) { t = v->q_container[idx - 2]; if (t == TYPE_RST || t == TYPE_VAT || t == TYPE_CST) break; } if (!cpp_demangle_push_subst_v(ddata, &subst_v)) goto clean; } break; case TYPE_VEC: cv = false; if (ddata->push_qualifier == PUSH_CV_QUALIFIER) break; if (v->ext_name.size == 0 || e_idx > v->ext_name.size - 1) goto clean; if ((e_len = strlen(v->ext_name.container[e_idx])) == 0) goto clean; if ((buf = malloc(e_len + 12)) == NULL) goto clean; snprintf(buf, e_len + 12, " __vector(%s)", v->ext_name.container[e_idx]); if (!DEM_PUSH_STR(ddata, buf)) { free(buf); goto clean; } if (type_str != NULL) { if (!VEC_PUSH_STR(&subst_v, buf)) { free(buf); goto clean; } if (!cpp_demangle_push_subst_v(ddata, &subst_v)) { free(buf); goto clean; } } free(buf); ++e_idx; break; } --idx; } rtn = 1; clean: if (type_str != NULL) vector_str_dest(&subst_v); return (rtn); } static int cpp_demangle_get_subst(struct cpp_demangle_data *ddata, size_t idx) { size_t len; if (ddata == NULL || ddata->subst.size <= idx) return (0); if ((len = strlen(ddata->subst.container[idx])) == 0) return (0); if (!cpp_demangle_push_str(ddata, ddata->subst.container[idx], len)) return (0); /* skip '_' */ ++ddata->cur; return (1); } static int cpp_demangle_get_tmpl_param(struct cpp_demangle_data *ddata, size_t idx) { size_t len; if (ddata == NULL || ddata->tmpl.size <= idx) return (0); if ((len = strlen(ddata->tmpl.container[idx])) == 0) return (0); if (!cpp_demangle_push_str(ddata, ddata->tmpl.container[idx], len)) return (0); ++ddata->cur; return (1); } static int cpp_demangle_read_array(struct cpp_demangle_data *ddata) { size_t i, num_len, exp_len, p_idx, idx; const char *num; char *exp; if (ddata == NULL || *(++ddata->cur) == '\0') return (0); if (*ddata->cur == '_') { if (*(++ddata->cur) == '\0') return (0); if (!cpp_demangle_read_type(ddata, NULL)) return (0); if (!DEM_PUSH_STR(ddata, " []")) return (0); } else { if (ELFTC_ISDIGIT(*ddata->cur) != 0) { num = ddata->cur; while (ELFTC_ISDIGIT(*ddata->cur) != 0) ++ddata->cur; if (*ddata->cur != '_') return (0); num_len = ddata->cur - num; assert(num_len > 0); if (*(++ddata->cur) == '\0') return (0); if (!cpp_demangle_read_type(ddata, NULL)) return (0); if (!DEM_PUSH_STR(ddata, " [")) return (0); if (!cpp_demangle_push_str(ddata, num, num_len)) return (0); if (!DEM_PUSH_STR(ddata, "]")) return (0); } else { p_idx = ddata->output.size; if (!cpp_demangle_read_expression(ddata)) return (0); if ((exp = vector_str_substr(&ddata->output, p_idx, ddata->output.size - 1, &exp_len)) == NULL) return (0); idx = ddata->output.size; for (i = p_idx; i < idx; ++i) if (!vector_str_pop(&ddata->output)) { free(exp); return (0); } if (*ddata->cur != '_') { free(exp); return (0); } ++ddata->cur; if (*ddata->cur == '\0') { free(exp); return (0); } if (!cpp_demangle_read_type(ddata, NULL)) { free(exp); return (0); } if (!DEM_PUSH_STR(ddata, " [")) { free(exp); return (0); } if (!cpp_demangle_push_str(ddata, exp, exp_len)) { free(exp); return (0); } if (!DEM_PUSH_STR(ddata, "]")) { free(exp); return (0); } free(exp); } } return (1); } static int cpp_demangle_read_expr_primary(struct cpp_demangle_data *ddata) { const char *num; if (ddata == NULL || *(++ddata->cur) == '\0') return (0); if (*ddata->cur == '_' && *(ddata->cur + 1) == 'Z') { ddata->cur += 2; if (*ddata->cur == '\0') return (0); if (!cpp_demangle_read_encoding(ddata)) return (0); ++ddata->cur; return (1); } switch (*ddata->cur) { case 'b': if (*(ddata->cur + 2) != 'E') return (0); switch (*(++ddata->cur)) { case '0': ddata->cur += 2; return (DEM_PUSH_STR(ddata, "false")); case '1': ddata->cur += 2; return (DEM_PUSH_STR(ddata, "true")); default: return (0); } case 'd': ++ddata->cur; return (cpp_demangle_push_fp(ddata, decode_fp_to_double)); case 'e': ++ddata->cur; if (sizeof(long double) == 10) return (cpp_demangle_push_fp(ddata, decode_fp_to_double)); return (cpp_demangle_push_fp(ddata, decode_fp_to_float80)); case 'f': ++ddata->cur; return (cpp_demangle_push_fp(ddata, decode_fp_to_float)); case 'g': ++ddata->cur; if (sizeof(long double) == 16) return (cpp_demangle_push_fp(ddata, decode_fp_to_double)); return (cpp_demangle_push_fp(ddata, decode_fp_to_float128)); case 'i': case 'j': case 'l': case 'm': case 'n': case 's': case 't': case 'x': case 'y': if (*(++ddata->cur) == 'n') { if (!DEM_PUSH_STR(ddata, "-")) return (0); ++ddata->cur; } num = ddata->cur; while (*ddata->cur != 'E') { if (!ELFTC_ISDIGIT(*ddata->cur)) return (0); ++ddata->cur; } ++ddata->cur; return (cpp_demangle_push_str(ddata, num, ddata->cur - num - 1)); default: return (0); } } static int cpp_demangle_read_expression(struct cpp_demangle_data *ddata) { if (ddata == NULL || *ddata->cur == '\0') return (0); switch (SIMPLE_HASH(*ddata->cur, *(ddata->cur + 1))) { case SIMPLE_HASH('s', 't'): ddata->cur += 2; return (cpp_demangle_read_type(ddata, NULL)); case SIMPLE_HASH('s', 'r'): ddata->cur += 2; if (!cpp_demangle_read_type(ddata, NULL)) return (0); if (!cpp_demangle_read_uqname(ddata)) return (0); if (*ddata->cur == 'I') return (cpp_demangle_read_tmpl_args(ddata)); return (1); case SIMPLE_HASH('a', 'a'): /* operator && */ ddata->cur += 2; return (cpp_demangle_read_expression_binary(ddata, "&&", 2)); case SIMPLE_HASH('a', 'd'): /* operator & (unary) */ ddata->cur += 2; return (cpp_demangle_read_expression_unary(ddata, "&", 1)); case SIMPLE_HASH('a', 'n'): /* operator & */ ddata->cur += 2; return (cpp_demangle_read_expression_binary(ddata, "&", 1)); case SIMPLE_HASH('a', 'N'): /* operator &= */ ddata->cur += 2; return (cpp_demangle_read_expression_binary(ddata, "&=", 2)); case SIMPLE_HASH('a', 'S'): /* operator = */ ddata->cur += 2; return (cpp_demangle_read_expression_binary(ddata, "=", 1)); case SIMPLE_HASH('c', 'l'): /* operator () */ ddata->cur += 2; return (cpp_demangle_read_expression_binary(ddata, "()", 2)); case SIMPLE_HASH('c', 'm'): /* operator , */ ddata->cur += 2; return (cpp_demangle_read_expression_binary(ddata, ",", 1)); case SIMPLE_HASH('c', 'o'): /* operator ~ */ ddata->cur += 2; return (cpp_demangle_read_expression_binary(ddata, "~", 1)); case SIMPLE_HASH('c', 'v'): /* operator (cast) */ ddata->cur += 2; return (cpp_demangle_read_expression_binary(ddata, "(cast)", 6)); case SIMPLE_HASH('d', 'a'): /* operator delete [] */ ddata->cur += 2; return (cpp_demangle_read_expression_unary(ddata, "delete []", 9)); case SIMPLE_HASH('d', 'e'): /* operator * (unary) */ ddata->cur += 2; return (cpp_demangle_read_expression_unary(ddata, "*", 1)); case SIMPLE_HASH('d', 'l'): /* operator delete */ ddata->cur += 2; return (cpp_demangle_read_expression_unary(ddata, "delete", 6)); case SIMPLE_HASH('d', 'v'): /* operator / */ ddata->cur += 2; return (cpp_demangle_read_expression_binary(ddata, "/", 1)); case SIMPLE_HASH('d', 'V'): /* operator /= */ ddata->cur += 2; return (cpp_demangle_read_expression_binary(ddata, "/=", 2)); case SIMPLE_HASH('e', 'o'): /* operator ^ */ ddata->cur += 2; return (cpp_demangle_read_expression_binary(ddata, "^", 1)); case SIMPLE_HASH('e', 'O'): /* operator ^= */ ddata->cur += 2; return (cpp_demangle_read_expression_binary(ddata, "^=", 2)); case SIMPLE_HASH('e', 'q'): /* operator == */ ddata->cur += 2; return (cpp_demangle_read_expression_binary(ddata, "==", 2)); case SIMPLE_HASH('g', 'e'): /* operator >= */ ddata->cur += 2; return (cpp_demangle_read_expression_binary(ddata, ">=", 2)); case SIMPLE_HASH('g', 't'): /* operator > */ ddata->cur += 2; return (cpp_demangle_read_expression_binary(ddata, ">", 1)); case SIMPLE_HASH('i', 'x'): /* operator [] */ ddata->cur += 2; return (cpp_demangle_read_expression_binary(ddata, "[]", 2)); case SIMPLE_HASH('l', 'e'): /* operator <= */ ddata->cur += 2; return (cpp_demangle_read_expression_binary(ddata, "<=", 2)); case SIMPLE_HASH('l', 's'): /* operator << */ ddata->cur += 2; return (cpp_demangle_read_expression_binary(ddata, "<<", 2)); case SIMPLE_HASH('l', 'S'): /* operator <<= */ ddata->cur += 2; return (cpp_demangle_read_expression_binary(ddata, "<<=", 3)); case SIMPLE_HASH('l', 't'): /* operator < */ ddata->cur += 2; return (cpp_demangle_read_expression_binary(ddata, "<", 1)); case SIMPLE_HASH('m', 'i'): /* operator - */ ddata->cur += 2; return (cpp_demangle_read_expression_binary(ddata, "-", 1)); case SIMPLE_HASH('m', 'I'): /* operator -= */ ddata->cur += 2; return (cpp_demangle_read_expression_binary(ddata, "-=", 2)); case SIMPLE_HASH('m', 'l'): /* operator * */ ddata->cur += 2; return (cpp_demangle_read_expression_binary(ddata, "*", 1)); case SIMPLE_HASH('m', 'L'): /* operator *= */ ddata->cur += 2; return (cpp_demangle_read_expression_binary(ddata, "*=", 2)); case SIMPLE_HASH('m', 'm'): /* operator -- */ ddata->cur += 2; return (cpp_demangle_read_expression_binary(ddata, "--", 2)); case SIMPLE_HASH('n', 'a'): /* operator new[] */ ddata->cur += 2; return (cpp_demangle_read_expression_unary(ddata, "new []", 6)); case SIMPLE_HASH('n', 'e'): /* operator != */ ddata->cur += 2; return (cpp_demangle_read_expression_binary(ddata, "!=", 2)); case SIMPLE_HASH('n', 'g'): /* operator - (unary) */ ddata->cur += 2; return (cpp_demangle_read_expression_unary(ddata, "-", 1)); case SIMPLE_HASH('n', 't'): /* operator ! */ ddata->cur += 2; return (cpp_demangle_read_expression_binary(ddata, "!", 1)); case SIMPLE_HASH('n', 'w'): /* operator new */ ddata->cur += 2; return (cpp_demangle_read_expression_unary(ddata, "new", 3)); case SIMPLE_HASH('o', 'o'): /* operator || */ ddata->cur += 2; return (cpp_demangle_read_expression_binary(ddata, "||", 2)); case SIMPLE_HASH('o', 'r'): /* operator | */ ddata->cur += 2; return (cpp_demangle_read_expression_binary(ddata, "|", 1)); case SIMPLE_HASH('o', 'R'): /* operator |= */ ddata->cur += 2; return (cpp_demangle_read_expression_binary(ddata, "|=", 2)); case SIMPLE_HASH('p', 'l'): /* operator + */ ddata->cur += 2; return (cpp_demangle_read_expression_binary(ddata, "+", 1)); case SIMPLE_HASH('p', 'L'): /* operator += */ ddata->cur += 2; return (cpp_demangle_read_expression_binary(ddata, "+=", 2)); case SIMPLE_HASH('p', 'm'): /* operator ->* */ ddata->cur += 2; return (cpp_demangle_read_expression_binary(ddata, "->*", 3)); case SIMPLE_HASH('p', 'p'): /* operator ++ */ ddata->cur += 2; return (cpp_demangle_read_expression_binary(ddata, "++", 2)); case SIMPLE_HASH('p', 's'): /* operator + (unary) */ ddata->cur += 2; return (cpp_demangle_read_expression_unary(ddata, "+", 1)); case SIMPLE_HASH('p', 't'): /* operator -> */ ddata->cur += 2; return (cpp_demangle_read_expression_binary(ddata, "->", 2)); case SIMPLE_HASH('q', 'u'): /* operator ? */ ddata->cur += 2; return (cpp_demangle_read_expression_trinary(ddata, "?", 1, ":", 1)); case SIMPLE_HASH('r', 'm'): /* operator % */ ddata->cur += 2; return (cpp_demangle_read_expression_binary(ddata, "%", 1)); case SIMPLE_HASH('r', 'M'): /* operator %= */ ddata->cur += 2; return (cpp_demangle_read_expression_binary(ddata, "%=", 2)); case SIMPLE_HASH('r', 's'): /* operator >> */ ddata->cur += 2; return (cpp_demangle_read_expression_binary(ddata, ">>", 2)); case SIMPLE_HASH('r', 'S'): /* operator >>= */ ddata->cur += 2; return (cpp_demangle_read_expression_binary(ddata, ">>=", 3)); case SIMPLE_HASH('r', 'z'): /* operator sizeof */ ddata->cur += 2; return (cpp_demangle_read_expression_unary(ddata, "sizeof", 6)); case SIMPLE_HASH('s', 'v'): /* operator sizeof */ ddata->cur += 2; return (cpp_demangle_read_expression_unary(ddata, "sizeof", 6)); } switch (*ddata->cur) { case 'L': return (cpp_demangle_read_expr_primary(ddata)); case 'T': return (cpp_demangle_read_tmpl_param(ddata)); } return (0); } static int cpp_demangle_read_expression_flat(struct cpp_demangle_data *ddata, char **str) { struct vector_str *output; size_t i, p_idx, idx, exp_len; char *exp; output = &ddata->output; p_idx = output->size; if (!cpp_demangle_read_expression(ddata)) return (0); if ((exp = vector_str_substr(output, p_idx, output->size - 1, &exp_len)) == NULL) return (0); idx = output->size; for (i = p_idx; i < idx; ++i) { if (!vector_str_pop(output)) { free(exp); return (0); } } *str = exp; return (1); } static int cpp_demangle_read_expression_binary(struct cpp_demangle_data *ddata, const char *name, size_t len) { if (ddata == NULL || name == NULL || len == 0) return (0); if (!cpp_demangle_read_expression(ddata)) return (0); if (!cpp_demangle_push_str(ddata, name, len)) return (0); return (cpp_demangle_read_expression(ddata)); } static int cpp_demangle_read_expression_unary(struct cpp_demangle_data *ddata, const char *name, size_t len) { if (ddata == NULL || name == NULL || len == 0) return (0); if (!cpp_demangle_read_expression(ddata)) return (0); return (cpp_demangle_push_str(ddata, name, len)); } static int cpp_demangle_read_expression_trinary(struct cpp_demangle_data *ddata, const char *name1, size_t len1, const char *name2, size_t len2) { if (ddata == NULL || name1 == NULL || len1 == 0 || name2 == NULL || len2 == 0) return (0); if (!cpp_demangle_read_expression(ddata)) return (0); if (!cpp_demangle_push_str(ddata, name1, len1)) return (0); if (!cpp_demangle_read_expression(ddata)) return (0); if (!cpp_demangle_push_str(ddata, name2, len2)) return (0); return (cpp_demangle_read_expression(ddata)); } static int cpp_demangle_read_function(struct cpp_demangle_data *ddata, int *ext_c, struct vector_type_qualifier *v) { struct type_delimit td; struct read_cmd_item *rc; size_t class_type_size, class_type_len, limit; const char *class_type; int i; bool paren, non_cv_qualifier; if (ddata == NULL || *ddata->cur != 'F' || v == NULL) return (0); ++ddata->cur; if (*ddata->cur == 'Y') { if (ext_c != NULL) *ext_c = 1; ++ddata->cur; } /* Return type */ if (!cpp_demangle_read_type(ddata, NULL)) return (0); if (*ddata->cur != 'E') { if (!DEM_PUSH_STR(ddata, " ")) return (0); non_cv_qualifier = false; if (v->size > 0) { for (i = 0; (size_t) i < v->size; i++) { if (v->q_container[i] != TYPE_RST && v->q_container[i] != TYPE_VAT && v->q_container[i] != TYPE_CST) { non_cv_qualifier = true; break; } } } paren = false; rc = vector_read_cmd_find(&ddata->cmd, READ_PTRMEM); if (non_cv_qualifier || rc != NULL) { if (!DEM_PUSH_STR(ddata, "(")) return (0); paren = true; } /* Push non-cv qualifiers. */ ddata->push_qualifier = PUSH_NON_CV_QUALIFIER; if (!cpp_demangle_push_type_qualifier(ddata, v, NULL)) return (0); if (rc) { if (non_cv_qualifier && !DEM_PUSH_STR(ddata, " ")) return (0); if ((class_type_size = ddata->class_type.size) == 0) return (0); class_type = ddata->class_type.container[class_type_size - 1]; if (class_type == NULL) return (0); if ((class_type_len = strlen(class_type)) == 0) return (0); if (!cpp_demangle_push_str(ddata, class_type, class_type_len)) return (0); if (!DEM_PUSH_STR(ddata, "::*")) return (0); /* Push pointer-to-member qualifiers. */ ddata->push_qualifier = PUSH_ALL_QUALIFIER; if (!cpp_demangle_push_type_qualifier(ddata, rc->data, NULL)) return (0); ++ddata->func_type; } if (paren) { if (!DEM_PUSH_STR(ddata, ")")) return (0); paren = false; } td.paren = false; td.firstp = true; limit = 0; ddata->is_functype = true; for (;;) { if (!cpp_demangle_read_type(ddata, &td)) return (0); if (*ddata->cur == 'E') break; if (limit++ > CPP_DEMANGLE_TRY_LIMIT) return (0); } ddata->is_functype = false; if (td.paren) { if (!DEM_PUSH_STR(ddata, ")")) return (0); td.paren = false; } /* Push CV qualifiers. */ ddata->push_qualifier = PUSH_CV_QUALIFIER; if (!cpp_demangle_push_type_qualifier(ddata, v, NULL)) return (0); ddata->push_qualifier = PUSH_ALL_QUALIFIER; /* Release type qualifier vector. */ vector_type_qualifier_dest(v); if (!vector_type_qualifier_init(v)) return (0); /* Push ref-qualifiers. */ if (ddata->ref_qualifier) { switch (ddata->ref_qualifier_type) { case TYPE_REF: if (!DEM_PUSH_STR(ddata, " &")) return (0); break; case TYPE_RREF: if (!DEM_PUSH_STR(ddata, " &&")) return (0); break; default: return (0); } ddata->ref_qualifier = false; } } ++ddata->cur; return (1); } /* read encoding, encoding are function name, data name, special-name */ static int cpp_demangle_read_encoding(struct cpp_demangle_data *ddata) { char *name, *type, *num_str; long offset; int rtn; if (ddata == NULL || *ddata->cur == '\0') return (0); /* special name */ switch (SIMPLE_HASH(*ddata->cur, *(ddata->cur + 1))) { case SIMPLE_HASH('G', 'A'): if (!DEM_PUSH_STR(ddata, "hidden alias for ")) return (0); ddata->cur += 2; if (*ddata->cur == '\0') return (0); return (cpp_demangle_read_encoding(ddata)); case SIMPLE_HASH('G', 'R'): if (!DEM_PUSH_STR(ddata, "reference temporary #")) return (0); ddata->cur += 2; if (*ddata->cur == '\0') return (0); if (!cpp_demangle_read_name_flat(ddata, &name)) return (0); rtn = 0; if (!cpp_demangle_read_number_as_string(ddata, &num_str)) goto clean1; if (!DEM_PUSH_STR(ddata, num_str)) goto clean2; if (!DEM_PUSH_STR(ddata, " for ")) goto clean2; if (!DEM_PUSH_STR(ddata, name)) goto clean2; rtn = 1; clean2: free(num_str); clean1: free(name); return (rtn); case SIMPLE_HASH('G', 'T'): ddata->cur += 2; if (*ddata->cur == '\0') return (0); switch (*ddata->cur) { case 'n': if (!DEM_PUSH_STR(ddata, "non-transaction clone for ")) return (0); break; case 't': default: if (!DEM_PUSH_STR(ddata, "transaction clone for ")) return (0); break; } ++ddata->cur; return (cpp_demangle_read_encoding(ddata)); case SIMPLE_HASH('G', 'V'): /* sentry object for 1 time init */ if (!DEM_PUSH_STR(ddata, "guard variable for ")) return (0); ddata->cur += 2; break; case SIMPLE_HASH('T', 'c'): /* virtual function covariant override thunk */ if (!DEM_PUSH_STR(ddata, "virtual function covariant override ")) return (0); ddata->cur += 2; if (*ddata->cur == '\0') return (0); if (!cpp_demangle_read_offset(ddata)) return (0); if (!cpp_demangle_read_offset(ddata)) return (0); return (cpp_demangle_read_encoding(ddata)); case SIMPLE_HASH('T', 'C'): /* construction vtable */ if (!DEM_PUSH_STR(ddata, "construction vtable for ")) return (0); ddata->cur += 2; if (*ddata->cur == '\0') return (0); if (!cpp_demangle_read_type_flat(ddata, &type)) return (0); rtn = 0; if (!cpp_demangle_read_number(ddata, &offset)) goto clean3; if (*ddata->cur++ != '_') goto clean3; if (!cpp_demangle_read_type(ddata, NULL)) goto clean3; if (!DEM_PUSH_STR(ddata, "-in-")) goto clean3; if (!DEM_PUSH_STR(ddata, type)) goto clean3; rtn = 1; clean3: free(type); return (rtn); case SIMPLE_HASH('T', 'D'): /* typeinfo common proxy */ break; case SIMPLE_HASH('T', 'F'): /* typeinfo fn */ if (!DEM_PUSH_STR(ddata, "typeinfo fn for ")) return (0); ddata->cur += 2; if (*ddata->cur == '\0') return (0); return (cpp_demangle_read_type(ddata, NULL)); case SIMPLE_HASH('T', 'h'): /* virtual function non-virtual override thunk */ if (!DEM_PUSH_STR(ddata, "virtual function non-virtual override ")) return (0); ddata->cur += 2; if (*ddata->cur == '\0') return (0); if (!cpp_demangle_read_nv_offset(ddata)) return (0); return (cpp_demangle_read_encoding(ddata)); case SIMPLE_HASH('T', 'H'): /* TLS init function */ if (!DEM_PUSH_STR(ddata, "TLS init function for ")) return (0); ddata->cur += 2; if (*ddata->cur == '\0') return (0); break; case SIMPLE_HASH('T', 'I'): /* typeinfo structure */ if (!DEM_PUSH_STR(ddata, "typeinfo for ")) return (0); ddata->cur += 2; if (*ddata->cur == '\0') return (0); return (cpp_demangle_read_type(ddata, NULL)); case SIMPLE_HASH('T', 'J'): /* java class */ if (!DEM_PUSH_STR(ddata, "java Class for ")) return (0); ddata->cur += 2; if (*ddata->cur == '\0') return (0); return (cpp_demangle_read_type(ddata, NULL)); case SIMPLE_HASH('T', 'S'): /* RTTI name (NTBS) */ if (!DEM_PUSH_STR(ddata, "typeinfo name for ")) return (0); ddata->cur += 2; if (*ddata->cur == '\0') return (0); return (cpp_demangle_read_type(ddata, NULL)); case SIMPLE_HASH('T', 'T'): /* VTT table */ if (!DEM_PUSH_STR(ddata, "VTT for ")) return (0); ddata->cur += 2; if (*ddata->cur == '\0') return (0); return (cpp_demangle_read_type(ddata, NULL)); case SIMPLE_HASH('T', 'v'): /* virtual function virtual override thunk */ if (!DEM_PUSH_STR(ddata, "virtual function virtual override ")) return (0); ddata->cur += 2; if (*ddata->cur == '\0') return (0); if (!cpp_demangle_read_v_offset(ddata)) return (0); return (cpp_demangle_read_encoding(ddata)); case SIMPLE_HASH('T', 'V'): /* virtual table */ if (!DEM_PUSH_STR(ddata, "vtable for ")) return (0); ddata->cur += 2; if (*ddata->cur == '\0') return (0); return (cpp_demangle_read_type(ddata, NULL)); case SIMPLE_HASH('T', 'W'): /* TLS wrapper function */ if (!DEM_PUSH_STR(ddata, "TLS wrapper function for ")) return (0); ddata->cur += 2; if (*ddata->cur == '\0') return (0); break; } return (cpp_demangle_read_name(ddata)); } static int cpp_demangle_read_local_name(struct cpp_demangle_data *ddata) { struct vector_str local_name; struct type_delimit td; size_t limit; bool more_type; if (ddata == NULL) return (0); if (*(++ddata->cur) == '\0') return (0); if (!vector_str_init(&local_name)) return (0); ddata->cur_output = &local_name; if (!cpp_demangle_read_encoding(ddata)) { vector_str_dest(&local_name); return (0); } ddata->cur_output = &ddata->output; td.paren = false; td.firstp = true; more_type = false; limit = 0; /* * The first type is a return type if we just demangled template * args. (the template args is right next to the function name, * which means it's a template function) */ if (ddata->is_tmpl) { ddata->is_tmpl = false; /* Read return type */ if (!cpp_demangle_read_type(ddata, NULL)) { vector_str_dest(&local_name); return (0); } more_type = true; } /* Now we can push the name after possible return type is handled. */ if (!vector_str_push_vector(&ddata->output, &local_name)) { vector_str_dest(&local_name); return (0); } vector_str_dest(&local_name); while (*ddata->cur != '\0') { if (!cpp_demangle_read_type(ddata, &td)) return (0); if (more_type) more_type = false; if (*ddata->cur == 'E') break; if (limit++ > CPP_DEMANGLE_TRY_LIMIT) return (0); } if (more_type) return (0); if (*(++ddata->cur) == '\0') return (0); if (td.paren == true) { if (!DEM_PUSH_STR(ddata, ")")) return (0); td.paren = false; } if (*ddata->cur == 's') ++ddata->cur; else { if (!DEM_PUSH_STR(ddata, "::")) return (0); if (!cpp_demangle_read_name(ddata)) return (0); } if (*ddata->cur == '_') { ++ddata->cur; while (ELFTC_ISDIGIT(*ddata->cur) != 0) ++ddata->cur; } return (1); } static int cpp_demangle_read_name(struct cpp_demangle_data *ddata) { struct vector_str *output, v; size_t p_idx, subst_str_len; int rtn; char *subst_str; if (ddata == NULL || *ddata->cur == '\0') return (0); output = ddata->cur_output; subst_str = NULL; switch (*ddata->cur) { case 'S': return (cpp_demangle_read_subst(ddata)); case 'N': return (cpp_demangle_read_nested_name(ddata)); case 'Z': return (cpp_demangle_read_local_name(ddata)); } if (!vector_str_init(&v)) return (0); p_idx = output->size; rtn = 0; if (!cpp_demangle_read_uqname(ddata)) goto clean; if ((subst_str = vector_str_substr(output, p_idx, output->size - 1, &subst_str_len)) == NULL) goto clean; if (subst_str_len > 8 && strstr(subst_str, "operator") != NULL) { rtn = 1; goto clean; } if (!vector_str_push(&v, subst_str, subst_str_len)) goto clean; if (!cpp_demangle_push_subst_v(ddata, &v)) goto clean; if (*ddata->cur == 'I') { p_idx = output->size; if (!cpp_demangle_read_tmpl_args(ddata)) goto clean; free(subst_str); if ((subst_str = vector_str_substr(output, p_idx, output->size - 1, &subst_str_len)) == NULL) goto clean; if (!vector_str_push(&v, subst_str, subst_str_len)) goto clean; if (!cpp_demangle_push_subst_v(ddata, &v)) goto clean; } rtn = 1; clean: free(subst_str); vector_str_dest(&v); return (rtn); } static int cpp_demangle_read_name_flat(struct cpp_demangle_data *ddata, char **str) { struct vector_str *output; size_t i, p_idx, idx, name_len; char *name; output = ddata->cur_output; p_idx = output->size; if (!cpp_demangle_read_name(ddata)) return (0); if ((name = vector_str_substr(output, p_idx, output->size - 1, &name_len)) == NULL) return (0); idx = output->size; for (i = p_idx; i < idx; ++i) { if (!vector_str_pop(output)) { free(name); return (0); } } *str = name; return (1); } static int cpp_demangle_read_nested_name(struct cpp_demangle_data *ddata) { struct vector_str *output, v; size_t limit, p_idx, subst_str_len; int rtn; char *subst_str; if (ddata == NULL || *ddata->cur != 'N') return (0); if (*(++ddata->cur) == '\0') return (0); do { switch (*ddata->cur) { case 'r': ddata->mem_rst = true; break; case 'V': ddata->mem_vat = true; break; case 'K': ddata->mem_cst = true; break; case 'R': ddata->mem_ref = true; break; case 'O': ddata->mem_rref = true; break; default: goto next; } } while (*(++ddata->cur)); next: output = ddata->cur_output; if (!vector_str_init(&v)) return (0); rtn = 0; limit = 0; for (;;) { p_idx = output->size; switch (*ddata->cur) { case 'I': if (!cpp_demangle_read_tmpl_args(ddata)) goto clean; break; case 'S': if (!cpp_demangle_read_subst(ddata)) goto clean; break; case 'T': if (!cpp_demangle_read_tmpl_param(ddata)) goto clean; break; default: if (!cpp_demangle_read_uqname(ddata)) goto clean; } if (p_idx == output->size) goto next_comp; if ((subst_str = vector_str_substr(output, p_idx, output->size - 1, &subst_str_len)) == NULL) goto clean; if (!vector_str_push(&v, subst_str, subst_str_len)) { free(subst_str); goto clean; } free(subst_str); if (!cpp_demangle_push_subst_v(ddata, &v)) goto clean; next_comp: if (*ddata->cur == 'E') break; else if (*ddata->cur != 'I' && *ddata->cur != 'C' && *ddata->cur != 'D' && p_idx != output->size) { if (!DEM_PUSH_STR(ddata, "::")) goto clean; if (!VEC_PUSH_STR(&v, "::")) goto clean; } if (limit++ > CPP_DEMANGLE_TRY_LIMIT) goto clean; } ++ddata->cur; rtn = 1; clean: vector_str_dest(&v); return (rtn); } /* * read number * number ::= [n] */ static int cpp_demangle_read_number(struct cpp_demangle_data *ddata, long *rtn) { long len, negative_factor; if (ddata == NULL || rtn == NULL) return (0); negative_factor = 1; if (*ddata->cur == 'n') { negative_factor = -1; ++ddata->cur; } if (ELFTC_ISDIGIT(*ddata->cur) == 0) return (0); errno = 0; if ((len = strtol(ddata->cur, (char **) NULL, 10)) == 0 && errno != 0) return (0); while (ELFTC_ISDIGIT(*ddata->cur) != 0) ++ddata->cur; assert(len >= 0); assert(negative_factor == 1 || negative_factor == -1); *rtn = len * negative_factor; return (1); } static int cpp_demangle_read_number_as_string(struct cpp_demangle_data *ddata, char **str) { long n; if (!cpp_demangle_read_number(ddata, &n)) { *str = NULL; return (0); } if (asprintf(str, "%ld", n) < 0) { *str = NULL; return (0); } return (1); } static int cpp_demangle_read_nv_offset(struct cpp_demangle_data *ddata) { if (ddata == NULL) return (0); if (!DEM_PUSH_STR(ddata, "offset : ")) return (0); return (cpp_demangle_read_offset_number(ddata)); } /* read offset, offset are nv-offset, v-offset */ static int cpp_demangle_read_offset(struct cpp_demangle_data *ddata) { if (ddata == NULL) return (0); if (*ddata->cur == 'h') { ++ddata->cur; return (cpp_demangle_read_nv_offset(ddata)); } else if (*ddata->cur == 'v') { ++ddata->cur; return (cpp_demangle_read_v_offset(ddata)); } return (0); } static int cpp_demangle_read_offset_number(struct cpp_demangle_data *ddata) { bool negative; const char *start; if (ddata == NULL || *ddata->cur == '\0') return (0); /* offset could be negative */ if (*ddata->cur == 'n') { negative = true; start = ddata->cur + 1; } else { negative = false; start = ddata->cur; } while (*ddata->cur != '_') ++ddata->cur; if (negative && !DEM_PUSH_STR(ddata, "-")) return (0); assert(start != NULL); if (!cpp_demangle_push_str(ddata, start, ddata->cur - start)) return (0); if (!DEM_PUSH_STR(ddata, " ")) return (0); ++ddata->cur; return (1); } static int cpp_demangle_read_pointer_to_member(struct cpp_demangle_data *ddata, struct vector_type_qualifier *v) { size_t class_type_len, i, idx, p_idx; int p_func_type, rtn; char *class_type; if (ddata == NULL || *ddata->cur != 'M' || *(++ddata->cur) == '\0') return (0); p_idx = ddata->output.size; if (!cpp_demangle_read_type(ddata, NULL)) return (0); if ((class_type = vector_str_substr(&ddata->output, p_idx, ddata->output.size - 1, &class_type_len)) == NULL) return (0); rtn = 0; idx = ddata->output.size; for (i = p_idx; i < idx; ++i) if (!vector_str_pop(&ddata->output)) goto clean1; if (!vector_read_cmd_push(&ddata->cmd, READ_PTRMEM, v)) goto clean1; if (!vector_str_push(&ddata->class_type, class_type, class_type_len)) goto clean2; p_func_type = ddata->func_type; if (!cpp_demangle_read_type(ddata, NULL)) goto clean3; if (p_func_type == ddata->func_type) { if (!DEM_PUSH_STR(ddata, " ")) goto clean3; if (!cpp_demangle_push_str(ddata, class_type, class_type_len)) goto clean3; if (!DEM_PUSH_STR(ddata, "::*")) goto clean3; } rtn = 1; clean3: if (!vector_str_pop(&ddata->class_type)) rtn = 0; clean2: if (!vector_read_cmd_pop(&ddata->cmd)) rtn = 0; clean1: free(class_type); vector_type_qualifier_dest(v); if (!vector_type_qualifier_init(v)) return (0); return (rtn); } /* read source-name, source-name is */ static int cpp_demangle_read_sname(struct cpp_demangle_data *ddata) { long len; int err; if (ddata == NULL || cpp_demangle_read_number(ddata, &len) == 0 || len <= 0) return (0); if (len == 12 && (memcmp("_GLOBAL__N_1", ddata->cur, 12) == 0)) err = DEM_PUSH_STR(ddata, "(anonymous namespace)"); else err = cpp_demangle_push_str(ddata, ddata->cur, len); if (err == 0) return (0); assert(ddata->cur_output->size > 0); if (vector_read_cmd_find(&ddata->cmd, READ_TMPL) == NULL) ddata->last_sname = ddata->cur_output->container[ddata->cur_output->size - 1]; ddata->cur += len; return (1); } static int cpp_demangle_read_subst(struct cpp_demangle_data *ddata) { long nth; if (ddata == NULL || *ddata->cur == '\0') return (0); /* abbreviations of the form Sx */ switch (SIMPLE_HASH(*ddata->cur, *(ddata->cur + 1))) { case SIMPLE_HASH('S', 'a'): /* std::allocator */ if (!DEM_PUSH_STR(ddata, "std::allocator")) return (0); ddata->cur += 2; if (*ddata->cur == 'I') return (cpp_demangle_read_subst_stdtmpl(ddata, "std::allocator")); return (1); case SIMPLE_HASH('S', 'b'): /* std::basic_string */ if (!DEM_PUSH_STR(ddata, "std::basic_string")) return (0); ddata->cur += 2; if (*ddata->cur == 'I') return (cpp_demangle_read_subst_stdtmpl(ddata, "std::basic_string")); return (1); case SIMPLE_HASH('S', 'd'): - /* std::basic_iostream > */ + /* std::basic_iostream> */ if (!DEM_PUSH_STR(ddata, "std::basic_iostream >")) + "std::char_traits>")) return (0); ddata->last_sname = "basic_iostream"; ddata->cur += 2; if (*ddata->cur == 'I') return (cpp_demangle_read_subst_stdtmpl(ddata, "std::basic_iostream >")); + ">")); return (1); case SIMPLE_HASH('S', 'i'): - /* std::basic_istream > */ + /* std::basic_istream> */ if (!DEM_PUSH_STR(ddata, "std::basic_istream >")) + "std::char_traits>")) return (0); ddata->last_sname = "basic_istream"; ddata->cur += 2; if (*ddata->cur == 'I') return (cpp_demangle_read_subst_stdtmpl(ddata, "std::basic_istream >")); + ">")); return (1); case SIMPLE_HASH('S', 'o'): - /* std::basic_ostream > */ + /* std::basic_ostream> */ if (!DEM_PUSH_STR(ddata, "std::basic_ostream >")) + "std::char_traits>")) return (0); ddata->last_sname = "basic_ostream"; ddata->cur += 2; if (*ddata->cur == 'I') return (cpp_demangle_read_subst_stdtmpl(ddata, "std::basic_ostream >")); + ">")); return (1); case SIMPLE_HASH('S', 's'): /* - * std::basic_string, - * std::allocator > - * - * a.k.a std::string + * std::string for consistency with libcxxabi */ - if (!DEM_PUSH_STR(ddata, "std::basic_string, std::allocator >")) - return (0); + if (!DEM_PUSH_STR(ddata, "std::string")) + return 0; ddata->last_sname = "string"; ddata->cur += 2; if (*ddata->cur == 'I') - return (cpp_demangle_read_subst_stdtmpl(ddata, - "std::basic_string," - " std::allocator >")); - return (1); + return cpp_demangle_read_subst_stdtmpl(ddata, + "std::string"); + return 1; case SIMPLE_HASH('S', 't'): /* std:: */ return (cpp_demangle_read_subst_std(ddata)); } if (*(++ddata->cur) == '\0') return (0); /* Skip unknown substitution abbreviations. */ if (!(*ddata->cur >= '0' && *ddata->cur <= '9') && !(*ddata->cur >= 'A' && *ddata->cur <= 'Z') && *ddata->cur != '_') { ++ddata->cur; return (1); } /* substitution */ if (*ddata->cur == '_') return (cpp_demangle_get_subst(ddata, 0)); else { errno = 0; /* substitution number is base 36 */ if ((nth = strtol(ddata->cur, (char **) NULL, 36)) == 0 && errno != 0) return (0); /* first was '_', so increase one */ ++nth; while (*ddata->cur != '_') ++ddata->cur; assert(nth > 0); return (cpp_demangle_get_subst(ddata, nth)); } /* NOTREACHED */ return (0); } static int cpp_demangle_read_subst_std(struct cpp_demangle_data *ddata) { struct vector_str *output, v; size_t p_idx, subst_str_len; int rtn; char *subst_str; if (ddata == NULL) return (0); if (!vector_str_init(&v)) return (0); subst_str = NULL; rtn = 0; if (!DEM_PUSH_STR(ddata, "std::")) goto clean; if (!VEC_PUSH_STR(&v, "std::")) goto clean; ddata->cur += 2; output = ddata->cur_output; p_idx = output->size; if (!cpp_demangle_read_uqname(ddata)) goto clean; if ((subst_str = vector_str_substr(output, p_idx, output->size - 1, &subst_str_len)) == NULL) goto clean; if (!vector_str_push(&v, subst_str, subst_str_len)) goto clean; if (!cpp_demangle_push_subst_v(ddata, &v)) goto clean; if (*ddata->cur == 'I') { p_idx = output->size; if (!cpp_demangle_read_tmpl_args(ddata)) goto clean; free(subst_str); if ((subst_str = vector_str_substr(output, p_idx, output->size - 1, &subst_str_len)) == NULL) goto clean; if (!vector_str_push(&v, subst_str, subst_str_len)) goto clean; if (!cpp_demangle_push_subst_v(ddata, &v)) goto clean; } rtn = 1; clean: free(subst_str); vector_str_dest(&v); return (rtn); } static int cpp_demangle_read_subst_stdtmpl(struct cpp_demangle_data *ddata, const char *str) { struct vector_str *output; size_t p_idx, substr_len, len; int rtn; char *subst_str, *substr; if (ddata == NULL || str == NULL) return (0); if ((len = strlen(str)) == 0) return (0); output = ddata->cur_output; p_idx = output->size; substr = NULL; subst_str = NULL; if (!cpp_demangle_read_tmpl_args(ddata)) return (0); if ((substr = vector_str_substr(output, p_idx, output->size - 1, &substr_len)) == NULL) return (0); rtn = 0; if ((subst_str = malloc(sizeof(char) * (substr_len + len + 1))) == NULL) goto clean; memcpy(subst_str, str, len); memcpy(subst_str + len, substr, substr_len); subst_str[substr_len + len] = '\0'; if (!cpp_demangle_push_subst(ddata, subst_str, substr_len + len)) goto clean; rtn = 1; clean: free(subst_str); free(substr); return (rtn); } static int cpp_demangle_read_tmpl_arg(struct cpp_demangle_data *ddata) { if (ddata == NULL || *ddata->cur == '\0') return (0); switch (*ddata->cur) { case 'L': return (cpp_demangle_read_expr_primary(ddata)); case 'X': ++ddata->cur; if (!cpp_demangle_read_expression(ddata)) return (0); return (*ddata->cur++ == 'E'); } return (cpp_demangle_read_type(ddata, NULL)); } static int cpp_demangle_read_tmpl_args(struct cpp_demangle_data *ddata) { struct vector_str *v; - size_t arg_len, idx, limit, size; + size_t arg_len, idx, limit; char *arg; if (ddata == NULL || *ddata->cur == '\0') return (0); ++ddata->cur; if (!vector_read_cmd_push(&ddata->cmd, READ_TMPL, NULL)) return (0); if (!DEM_PUSH_STR(ddata, "<")) return (0); limit = 0; v = ddata->cur_output; for (;;) { idx = v->size; if (!cpp_demangle_read_tmpl_arg(ddata)) return (0); if ((arg = vector_str_substr(v, idx, v->size - 1, &arg_len)) == NULL) return (0); if (!vector_str_find(&ddata->tmpl, arg, arg_len) && !vector_str_push(&ddata->tmpl, arg, arg_len)) { free(arg); return (0); } free(arg); if (*ddata->cur == 'E') { ++ddata->cur; - size = v->size; - assert(size > 0); - if (!strncmp(v->container[size - 1], ">", 1)) { - if (!DEM_PUSH_STR(ddata, " >")) - return (0); - } else if (!DEM_PUSH_STR(ddata, ">")) + if (!DEM_PUSH_STR(ddata, ">")) return (0); ddata->is_tmpl = true; break; } else if (*ddata->cur != 'I' && !DEM_PUSH_STR(ddata, ", ")) return (0); if (limit++ > CPP_DEMANGLE_TRY_LIMIT) return (0); } return (vector_read_cmd_pop(&ddata->cmd)); } /* * Read template parameter that forms in 'T[number]_'. * This function much like to read_subst but only for types. */ static int cpp_demangle_read_tmpl_param(struct cpp_demangle_data *ddata) { long nth; if (ddata == NULL || *ddata->cur != 'T') return (0); ++ddata->cur; if (*ddata->cur == '_') return (cpp_demangle_get_tmpl_param(ddata, 0)); else { errno = 0; if ((nth = strtol(ddata->cur, (char **) NULL, 36)) == 0 && errno != 0) return (0); /* T_ is first */ ++nth; while (*ddata->cur != '_') ++ddata->cur; assert(nth > 0); return (cpp_demangle_get_tmpl_param(ddata, nth)); } /* NOTREACHED */ return (0); } static int cpp_demangle_read_type(struct cpp_demangle_data *ddata, struct type_delimit *td) { struct vector_type_qualifier v; struct vector_str *output, sv; size_t p_idx, type_str_len, subst_str_len; int extern_c, is_builtin; long len; const char *p; char *type_str, *exp_str, *num_str, *subst_str; bool skip_ref_qualifier, omit_void; if (ddata == NULL) return (0); output = ddata->cur_output; if (td) { if (td->paren == false) { if (!DEM_PUSH_STR(ddata, "(")) return (0); if (ddata->output.size < 2) return (0); td->paren = true; } if (!td->firstp) { if (*ddata->cur != 'I') { if (!DEM_PUSH_STR(ddata, ", ")) return (0); } } } assert(output != NULL); /* * [r, V, K] [P, R, O, C, G, U] builtin, function, class-enum, array * pointer-to-member, template-param, template-template-param, subst */ if (!vector_type_qualifier_init(&v)) return (0); extern_c = 0; is_builtin = 1; p_idx = output->size; type_str = exp_str = num_str = NULL; skip_ref_qualifier = false; again: /* Clear ref-qualifier flag */ if (*ddata->cur != 'R' && *ddata->cur != 'O' && *ddata->cur != 'E') ddata->ref_qualifier = false; /* builtin type */ switch (*ddata->cur) { case 'a': /* signed char */ if (!DEM_PUSH_STR(ddata, "signed char")) goto clean; ++ddata->cur; goto rtn; case 'A': /* array type */ if (!cpp_demangle_read_array(ddata)) goto clean; is_builtin = 0; goto rtn; case 'b': /* bool */ if (!DEM_PUSH_STR(ddata, "bool")) goto clean; ++ddata->cur; goto rtn; case 'C': /* complex pair */ if (!vector_type_qualifier_push(&v, TYPE_CMX)) goto clean; ++ddata->cur; if (td) td->firstp = false; goto again; case 'c': /* char */ if (!DEM_PUSH_STR(ddata, "char")) goto clean; ++ddata->cur; goto rtn; case 'd': /* double */ if (!DEM_PUSH_STR(ddata, "double")) goto clean; ++ddata->cur; goto rtn; case 'D': ++ddata->cur; switch (*ddata->cur) { case 'a': /* auto */ if (!DEM_PUSH_STR(ddata, "auto")) goto clean; ++ddata->cur; break; case 'c': /* decltype(auto) */ if (!DEM_PUSH_STR(ddata, "decltype(auto)")) goto clean; ++ddata->cur; break; case 'd': /* IEEE 754r decimal floating point (64 bits) */ if (!DEM_PUSH_STR(ddata, "decimal64")) goto clean; ++ddata->cur; break; case 'e': /* IEEE 754r decimal floating point (128 bits) */ if (!DEM_PUSH_STR(ddata, "decimal128")) goto clean; ++ddata->cur; break; case 'f': /* IEEE 754r decimal floating point (32 bits) */ if (!DEM_PUSH_STR(ddata, "decimal32")) goto clean; ++ddata->cur; break; case 'h': /* IEEE 754r half-precision floating point (16 bits) */ if (!DEM_PUSH_STR(ddata, "half")) goto clean; ++ddata->cur; break; case 'i': /* char32_t */ if (!DEM_PUSH_STR(ddata, "char32_t")) goto clean; ++ddata->cur; break; case 'n': /* std::nullptr_t (i.e., decltype(nullptr)) */ if (!DEM_PUSH_STR(ddata, "decltype(nullptr)")) goto clean; ++ddata->cur; break; case 's': /* char16_t */ if (!DEM_PUSH_STR(ddata, "char16_t")) goto clean; ++ddata->cur; break; case 'v': /* gcc vector_size extension. */ ++ddata->cur; if (*ddata->cur == '_') { ++ddata->cur; if (!cpp_demangle_read_expression_flat(ddata, &exp_str)) goto clean; if (!VEC_PUSH_STR(&v.ext_name, exp_str)) goto clean; } else { if (!cpp_demangle_read_number_as_string(ddata, &num_str)) goto clean; if (!VEC_PUSH_STR(&v.ext_name, num_str)) goto clean; } if (*ddata->cur != '_') goto clean; ++ddata->cur; if (!vector_type_qualifier_push(&v, TYPE_VEC)) goto clean; if (td) td->firstp = false; goto again; default: goto clean; } goto rtn; case 'e': /* long double */ if (!DEM_PUSH_STR(ddata, "long double")) goto clean; ++ddata->cur; goto rtn; case 'E': /* unexpected end except ref-qualifiers */ if (ddata->ref_qualifier && ddata->is_functype) { skip_ref_qualifier = true; /* Pop the delimiter. */ cpp_demangle_pop_str(ddata); goto rtn; } goto clean; case 'f': /* float */ if (!DEM_PUSH_STR(ddata, "float")) goto clean; ++ddata->cur; goto rtn; case 'F': /* function */ if (!cpp_demangle_read_function(ddata, &extern_c, &v)) goto clean; is_builtin = 0; goto rtn; case 'g': /* __float128 */ if (!DEM_PUSH_STR(ddata, "__float128")) goto clean; ++ddata->cur; goto rtn; case 'G': /* imaginary */ if (!vector_type_qualifier_push(&v, TYPE_IMG)) goto clean; ++ddata->cur; if (td) td->firstp = false; goto again; case 'h': /* unsigned char */ if (!DEM_PUSH_STR(ddata, "unsigned char")) goto clean; ++ddata->cur; goto rtn; case 'i': /* int */ if (!DEM_PUSH_STR(ddata, "int")) goto clean; ++ddata->cur; goto rtn; case 'I': /* template args. */ /* handles */ p_idx = output->size; if (!cpp_demangle_read_tmpl_args(ddata)) goto clean; if ((subst_str = vector_str_substr(output, p_idx, output->size - 1, &subst_str_len)) == NULL) goto clean; if (!vector_str_init(&sv)) { free(subst_str); goto clean; } if (!vector_str_push(&sv, subst_str, subst_str_len)) { free(subst_str); vector_str_dest(&sv); goto clean; } free(subst_str); if (!cpp_demangle_push_subst_v(ddata, &sv)) { vector_str_dest(&sv); goto clean; } vector_str_dest(&sv); goto rtn; case 'j': /* unsigned int */ if (!DEM_PUSH_STR(ddata, "unsigned int")) goto clean; ++ddata->cur; goto rtn; case 'K': /* const */ if (!vector_type_qualifier_push(&v, TYPE_CST)) goto clean; ++ddata->cur; if (td) td->firstp = false; goto again; case 'l': /* long */ if (!DEM_PUSH_STR(ddata, "long")) goto clean; ++ddata->cur; goto rtn; case 'm': /* unsigned long */ if (!DEM_PUSH_STR(ddata, "unsigned long")) goto clean; ++ddata->cur; goto rtn; case 'M': /* pointer to member */ if (!cpp_demangle_read_pointer_to_member(ddata, &v)) goto clean; is_builtin = 0; goto rtn; case 'n': /* __int128 */ if (!DEM_PUSH_STR(ddata, "__int128")) goto clean; ++ddata->cur; goto rtn; case 'o': /* unsigned __int128 */ if (!DEM_PUSH_STR(ddata, "unsigned __int128")) goto clean; ++ddata->cur; goto rtn; case 'O': /* rvalue reference */ if (ddata->ref_qualifier) goto clean; if (!vector_type_qualifier_push(&v, TYPE_RREF)) goto clean; ddata->ref_qualifier = true; ddata->ref_qualifier_type = TYPE_RREF; ++ddata->cur; if (td) td->firstp = false; goto again; case 'P': /* pointer */ if (!vector_type_qualifier_push(&v, TYPE_PTR)) goto clean; ++ddata->cur; if (td) td->firstp = false; goto again; case 'r': /* restrict */ if (!vector_type_qualifier_push(&v, TYPE_RST)) goto clean; ++ddata->cur; if (td) td->firstp = false; goto again; case 'R': /* reference */ if (ddata->ref_qualifier) goto clean; if (!vector_type_qualifier_push(&v, TYPE_REF)) goto clean; ddata->ref_qualifier = true; ddata->ref_qualifier_type = TYPE_REF; ++ddata->cur; if (td) td->firstp = false; goto again; case 's': /* short, local string */ if (!DEM_PUSH_STR(ddata, "short")) goto clean; ++ddata->cur; goto rtn; case 'S': /* substitution */ if (!cpp_demangle_read_subst(ddata)) goto clean; is_builtin = 0; goto rtn; case 't': /* unsigned short */ if (!DEM_PUSH_STR(ddata, "unsigned short")) goto clean; ++ddata->cur; goto rtn; case 'T': /* template parameter */ if (!cpp_demangle_read_tmpl_param(ddata)) goto clean; is_builtin = 0; goto rtn; case 'u': /* vendor extended builtin */ ++ddata->cur; if (!cpp_demangle_read_sname(ddata)) goto clean; is_builtin = 0; goto rtn; case 'U': /* vendor extended type qualifier */ ++ddata->cur; if (!cpp_demangle_read_number(ddata, &len)) goto clean; if (len <= 0) goto clean; if (!vector_str_push(&v.ext_name, ddata->cur, len)) goto clean; ddata->cur += len; if (!vector_type_qualifier_push(&v, TYPE_EXT)) goto clean; if (td) td->firstp = false; goto again; case 'v': /* void */ omit_void = false; if (td && td->firstp) { /* * peek into next bytes and see if we should omit * the "void". */ omit_void = true; for (p = ddata->cur + 1; *p != '\0'; p++) { if (*p == 'E') break; if (*p != 'R' && *p != 'O') { omit_void = false; break; } } } if (!omit_void && !DEM_PUSH_STR(ddata, "void")) goto clean; ++ddata->cur; goto rtn; case 'V': /* volatile */ if (!vector_type_qualifier_push(&v, TYPE_VAT)) goto clean; ++ddata->cur; if (td) td->firstp = false; goto again; case 'w': /* wchar_t */ if (!DEM_PUSH_STR(ddata, "wchar_t")) goto clean; ++ddata->cur; goto rtn; case 'x': /* long long */ if (!DEM_PUSH_STR(ddata, "long long")) goto clean; ++ddata->cur; goto rtn; case 'y': /* unsigned long long */ if (!DEM_PUSH_STR(ddata, "unsigned long long")) goto clean; ++ddata->cur; goto rtn; case 'z': /* ellipsis */ if (!DEM_PUSH_STR(ddata, "...")) goto clean; ++ddata->cur; goto rtn; } if (!cpp_demangle_read_name(ddata)) goto clean; is_builtin = 0; rtn: type_str = vector_str_substr(output, p_idx, output->size - 1, &type_str_len); if (is_builtin == 0) { if (!vector_str_find(&ddata->subst, type_str, type_str_len) && !vector_str_push(&ddata->subst, type_str, type_str_len)) goto clean; } if (!skip_ref_qualifier && !cpp_demangle_push_type_qualifier(ddata, &v, type_str)) goto clean; if (td) td->firstp = false; free(type_str); free(exp_str); free(num_str); vector_type_qualifier_dest(&v); return (1); clean: free(type_str); free(exp_str); free(num_str); vector_type_qualifier_dest(&v); return (0); } static int cpp_demangle_read_type_flat(struct cpp_demangle_data *ddata, char **str) { struct vector_str *output; size_t i, p_idx, idx, type_len; char *type; output = ddata->cur_output; p_idx = output->size; if (!cpp_demangle_read_type(ddata, NULL)) return (0); if ((type = vector_str_substr(output, p_idx, output->size - 1, &type_len)) == NULL) return (0); idx = output->size; for (i = p_idx; i < idx; ++i) { if (!vector_str_pop(output)) { free(type); return (0); } } *str = type; return (1); } /* * read unqualified-name, unqualified name are operator-name, ctor-dtor-name, * source-name */ static int cpp_demangle_read_uqname(struct cpp_demangle_data *ddata) { size_t len; if (ddata == NULL || *ddata->cur == '\0') return (0); /* operator name */ switch (SIMPLE_HASH(*ddata->cur, *(ddata->cur + 1))) { case SIMPLE_HASH('a', 'a'): /* operator && */ if (!DEM_PUSH_STR(ddata, "operator&&")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('a', 'd'): /* operator & (unary) */ if (!DEM_PUSH_STR(ddata, "operator&")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('a', 'n'): /* operator & */ if (!DEM_PUSH_STR(ddata, "operator&")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('a', 'N'): /* operator &= */ if (!DEM_PUSH_STR(ddata, "operator&=")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('a', 'S'): /* operator = */ if (!DEM_PUSH_STR(ddata, "operator=")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('c', 'l'): /* operator () */ if (!DEM_PUSH_STR(ddata, "operator()")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('c', 'm'): /* operator , */ if (!DEM_PUSH_STR(ddata, "operator,")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('c', 'o'): /* operator ~ */ if (!DEM_PUSH_STR(ddata, "operator~")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('c', 'v'): /* operator (cast) */ if (!DEM_PUSH_STR(ddata, "operator(cast)")) return (0); ddata->cur += 2; return (cpp_demangle_read_type(ddata, NULL)); case SIMPLE_HASH('d', 'a'): /* operator delete [] */ if (!DEM_PUSH_STR(ddata, "operator delete []")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('d', 'e'): /* operator * (unary) */ if (!DEM_PUSH_STR(ddata, "operator*")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('d', 'l'): /* operator delete */ if (!DEM_PUSH_STR(ddata, "operator delete")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('d', 'v'): /* operator / */ if (!DEM_PUSH_STR(ddata, "operator/")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('d', 'V'): /* operator /= */ if (!DEM_PUSH_STR(ddata, "operator/=")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('e', 'o'): /* operator ^ */ if (!DEM_PUSH_STR(ddata, "operator^")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('e', 'O'): /* operator ^= */ if (!DEM_PUSH_STR(ddata, "operator^=")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('e', 'q'): /* operator == */ if (!DEM_PUSH_STR(ddata, "operator==")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('g', 'e'): /* operator >= */ if (!DEM_PUSH_STR(ddata, "operator>=")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('g', 't'): /* operator > */ if (!DEM_PUSH_STR(ddata, "operator>")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('i', 'x'): /* operator [] */ if (!DEM_PUSH_STR(ddata, "operator[]")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('l', 'e'): /* operator <= */ if (!DEM_PUSH_STR(ddata, "operator<=")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('l', 's'): /* operator << */ if (!DEM_PUSH_STR(ddata, "operator<<")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('l', 'S'): /* operator <<= */ if (!DEM_PUSH_STR(ddata, "operator<<=")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('l', 't'): /* operator < */ if (!DEM_PUSH_STR(ddata, "operator<")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('m', 'i'): /* operator - */ if (!DEM_PUSH_STR(ddata, "operator-")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('m', 'I'): /* operator -= */ if (!DEM_PUSH_STR(ddata, "operator-=")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('m', 'l'): /* operator * */ if (!DEM_PUSH_STR(ddata, "operator*")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('m', 'L'): /* operator *= */ if (!DEM_PUSH_STR(ddata, "operator*=")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('m', 'm'): /* operator -- */ if (!DEM_PUSH_STR(ddata, "operator--")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('n', 'a'): /* operator new[] */ if (!DEM_PUSH_STR(ddata, "operator new []")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('n', 'e'): /* operator != */ if (!DEM_PUSH_STR(ddata, "operator!=")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('n', 'g'): /* operator - (unary) */ if (!DEM_PUSH_STR(ddata, "operator-")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('n', 't'): /* operator ! */ if (!DEM_PUSH_STR(ddata, "operator!")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('n', 'w'): /* operator new */ if (!DEM_PUSH_STR(ddata, "operator new")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('o', 'o'): /* operator || */ if (!DEM_PUSH_STR(ddata, "operator||")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('o', 'r'): /* operator | */ if (!DEM_PUSH_STR(ddata, "operator|")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('o', 'R'): /* operator |= */ if (!DEM_PUSH_STR(ddata, "operator|=")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('p', 'l'): /* operator + */ if (!DEM_PUSH_STR(ddata, "operator+")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('p', 'L'): /* operator += */ if (!DEM_PUSH_STR(ddata, "operator+=")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('p', 'm'): /* operator ->* */ if (!DEM_PUSH_STR(ddata, "operator->*")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('p', 'p'): /* operator ++ */ if (!DEM_PUSH_STR(ddata, "operator++")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('p', 's'): /* operator + (unary) */ if (!DEM_PUSH_STR(ddata, "operator+")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('p', 't'): /* operator -> */ if (!DEM_PUSH_STR(ddata, "operator->")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('q', 'u'): /* operator ? */ if (!DEM_PUSH_STR(ddata, "operator?")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('r', 'm'): /* operator % */ if (!DEM_PUSH_STR(ddata, "operator%")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('r', 'M'): /* operator %= */ if (!DEM_PUSH_STR(ddata, "operator%=")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('r', 's'): /* operator >> */ if (!DEM_PUSH_STR(ddata, "operator>>")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('r', 'S'): /* operator >>= */ if (!DEM_PUSH_STR(ddata, "operator>>=")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('r', 'z'): /* operator sizeof */ if (!DEM_PUSH_STR(ddata, "operator sizeof ")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('s', 'r'): /* scope resolution operator */ if (!DEM_PUSH_STR(ddata, "scope resolution operator ")) return (0); ddata->cur += 2; return (1); case SIMPLE_HASH('s', 'v'): /* operator sizeof */ if (!DEM_PUSH_STR(ddata, "operator sizeof ")) return (0); ddata->cur += 2; return (1); } /* vendor extened operator */ if (*ddata->cur == 'v' && ELFTC_ISDIGIT(*(ddata->cur + 1))) { if (!DEM_PUSH_STR(ddata, "vendor extened operator ")) return (0); if (!cpp_demangle_push_str(ddata, ddata->cur + 1, 1)) return (0); ddata->cur += 2; return (cpp_demangle_read_sname(ddata)); } /* ctor-dtor-name */ switch (SIMPLE_HASH(*ddata->cur, *(ddata->cur + 1))) { case SIMPLE_HASH('C', '1'): case SIMPLE_HASH('C', '2'): case SIMPLE_HASH('C', '3'): if (ddata->last_sname == NULL) return (0); if ((len = strlen(ddata->last_sname)) == 0) return (0); if (!DEM_PUSH_STR(ddata, "::")) return (0); if (!cpp_demangle_push_str(ddata, ddata->last_sname, len)) return (0); ddata->cur +=2; return (1); case SIMPLE_HASH('D', '0'): case SIMPLE_HASH('D', '1'): case SIMPLE_HASH('D', '2'): if (ddata->last_sname == NULL) return (0); if ((len = strlen(ddata->last_sname)) == 0) return (0); if (!DEM_PUSH_STR(ddata, "::~")) return (0); if (!cpp_demangle_push_str(ddata, ddata->last_sname, len)) return (0); ddata->cur +=2; return (1); } /* source name */ if (ELFTC_ISDIGIT(*ddata->cur) != 0) return (cpp_demangle_read_sname(ddata)); /* local source name */ if (*ddata->cur == 'L') return (cpp_demangle_local_source_name(ddata)); return (1); } /* * Read local source name. * * References: * http://gcc.gnu.org/bugzilla/show_bug.cgi?id=31775 * http://gcc.gnu.org/viewcvs?view=rev&revision=124467 */ static int cpp_demangle_local_source_name(struct cpp_demangle_data *ddata) { /* L */ if (ddata == NULL || *ddata->cur != 'L') return (0); ++ddata->cur; /* source name */ if (!cpp_demangle_read_sname(ddata)) return (0); /* discriminator */ if (*ddata->cur == '_') { ++ddata->cur; while (ELFTC_ISDIGIT(*ddata->cur) != 0) ++ddata->cur; } return (1); } static int cpp_demangle_read_v_offset(struct cpp_demangle_data *ddata) { if (ddata == NULL) return (0); if (!DEM_PUSH_STR(ddata, "offset : ")) return (0); if (!cpp_demangle_read_offset_number(ddata)) return (0); if (!DEM_PUSH_STR(ddata, "virtual offset : ")) return (0); return (!cpp_demangle_read_offset_number(ddata)); } /* * Decode floating point representation to string * Return new allocated string or NULL * * Todo * Replace these functions to macro. */ static char * decode_fp_to_double(const char *p, size_t len) { double f; size_t rtn_len, limit, i; int byte; char *rtn; if (p == NULL || len == 0 || len % 2 != 0 || len / 2 > sizeof(double)) return (NULL); memset(&f, 0, sizeof(double)); for (i = 0; i < len / 2; ++i) { byte = hex_to_dec(p[len - i * 2 - 1]) + hex_to_dec(p[len - i * 2 - 2]) * 16; if (byte < 0 || byte > 255) return (NULL); #if ELFTC_BYTE_ORDER == ELFTC_BYTE_ORDER_LITTLE_ENDIAN ((unsigned char *)&f)[i] = (unsigned char)(byte); #else /* ELFTC_BYTE_ORDER != ELFTC_BYTE_ORDER_LITTLE_ENDIAN */ ((unsigned char *)&f)[sizeof(double) - i - 1] = (unsigned char)(byte); #endif /* ELFTC_BYTE_ORDER == ELFTC_BYTE_ORDER_LITTLE_ENDIAN */ } rtn_len = 64; limit = 0; again: if ((rtn = malloc(sizeof(char) * rtn_len)) == NULL) return (NULL); if (snprintf(rtn, rtn_len, "%fld", f) >= (int)rtn_len) { free(rtn); if (limit++ > FLOAT_SPRINTF_TRY_LIMIT) return (NULL); rtn_len *= BUFFER_GROWFACTOR; goto again; } return rtn; } static char * decode_fp_to_float(const char *p, size_t len) { size_t i, rtn_len, limit; float f; int byte; char *rtn; if (p == NULL || len == 0 || len % 2 != 0 || len / 2 > sizeof(float)) return (NULL); memset(&f, 0, sizeof(float)); for (i = 0; i < len / 2; ++i) { byte = hex_to_dec(p[len - i * 2 - 1]) + hex_to_dec(p[len - i * 2 - 2]) * 16; if (byte < 0 || byte > 255) return (NULL); #if ELFTC_BYTE_ORDER == ELFTC_BYTE_ORDER_LITTLE_ENDIAN ((unsigned char *)&f)[i] = (unsigned char)(byte); #else /* ELFTC_BYTE_ORDER != ELFTC_BYTE_ORDER_LITTLE_ENDIAN */ ((unsigned char *)&f)[sizeof(float) - i - 1] = (unsigned char)(byte); #endif /* ELFTC_BYTE_ORDER == ELFTC_BYTE_ORDER_LITTLE_ENDIAN */ } rtn_len = 64; limit = 0; again: if ((rtn = malloc(sizeof(char) * rtn_len)) == NULL) return (NULL); if (snprintf(rtn, rtn_len, "%ff", f) >= (int)rtn_len) { free(rtn); if (limit++ > FLOAT_SPRINTF_TRY_LIMIT) return (NULL); rtn_len *= BUFFER_GROWFACTOR; goto again; } return rtn; } static char * decode_fp_to_float128(const char *p, size_t len) { long double f; size_t rtn_len, limit, i; int byte; unsigned char buf[FLOAT_QUADRUPLE_BYTES]; char *rtn; switch(sizeof(long double)) { case FLOAT_QUADRUPLE_BYTES: return (decode_fp_to_long_double(p, len)); case FLOAT_EXTENED_BYTES: if (p == NULL || len == 0 || len % 2 != 0 || len / 2 > FLOAT_QUADRUPLE_BYTES) return (NULL); memset(buf, 0, FLOAT_QUADRUPLE_BYTES); for (i = 0; i < len / 2; ++i) { byte = hex_to_dec(p[len - i * 2 - 1]) + hex_to_dec(p[len - i * 2 - 2]) * 16; if (byte < 0 || byte > 255) return (NULL); #if ELFTC_BYTE_ORDER == ELFTC_BYTE_ORDER_LITTLE_ENDIAN buf[i] = (unsigned char)(byte); #else /* ELFTC_BYTE_ORDER != ELFTC_BYTE_ORDER_LITTLE_ENDIAN */ buf[FLOAT_QUADRUPLE_BYTES - i -1] = (unsigned char)(byte); #endif /* ELFTC_BYTE_ORDER == ELFTC_BYTE_ORDER_LITTLE_ENDIAN */ } memset(&f, 0, FLOAT_EXTENED_BYTES); #if ELFTC_BYTE_ORDER == ELFTC_BYTE_ORDER_LITTLE_ENDIAN memcpy(&f, buf, FLOAT_EXTENED_BYTES); #else /* ELFTC_BYTE_ORDER != ELFTC_BYTE_ORDER_LITTLE_ENDIAN */ memcpy(&f, buf + 6, FLOAT_EXTENED_BYTES); #endif /* ELFTC_BYTE_ORDER == ELFTC_BYTE_ORDER_LITTLE_ENDIAN */ rtn_len = 256; limit = 0; again: if ((rtn = malloc(sizeof(char) * rtn_len)) == NULL) return (NULL); if (snprintf(rtn, rtn_len, "%Lfd", f) >= (int)rtn_len) { free(rtn); if (limit++ > FLOAT_SPRINTF_TRY_LIMIT) return (NULL); rtn_len *= BUFFER_GROWFACTOR; goto again; } return (rtn); default: return (NULL); } } static char * decode_fp_to_float80(const char *p, size_t len) { long double f; size_t rtn_len, limit, i; int byte; unsigned char buf[FLOAT_EXTENED_BYTES]; char *rtn; switch(sizeof(long double)) { case FLOAT_QUADRUPLE_BYTES: if (p == NULL || len == 0 || len % 2 != 0 || len / 2 > FLOAT_EXTENED_BYTES) return (NULL); memset(buf, 0, FLOAT_EXTENED_BYTES); for (i = 0; i < len / 2; ++i) { byte = hex_to_dec(p[len - i * 2 - 1]) + hex_to_dec(p[len - i * 2 - 2]) * 16; if (byte < 0 || byte > 255) return (NULL); #if ELFTC_BYTE_ORDER == ELFTC_BYTE_ORDER_LITTLE_ENDIAN buf[i] = (unsigned char)(byte); #else /* ELFTC_BYTE_ORDER != ELFTC_BYTE_ORDER_LITTLE_ENDIAN */ buf[FLOAT_EXTENED_BYTES - i -1] = (unsigned char)(byte); #endif /* ELFTC_BYTE_ORDER == ELFTC_BYTE_ORDER_LITTLE_ENDIAN */ } memset(&f, 0, FLOAT_QUADRUPLE_BYTES); #if ELFTC_BYTE_ORDER == ELFTC_BYTE_ORDER_LITTLE_ENDIAN memcpy(&f, buf, FLOAT_EXTENED_BYTES); #else /* ELFTC_BYTE_ORDER != ELFTC_BYTE_ORDER_LITTLE_ENDIAN */ memcpy((unsigned char *)(&f) + 6, buf, FLOAT_EXTENED_BYTES); #endif /* ELFTC_BYTE_ORDER == ELFTC_BYTE_ORDER_LITTLE_ENDIAN */ rtn_len = 256; limit = 0; again: if ((rtn = malloc(sizeof(char) * rtn_len)) == NULL) return (NULL); if (snprintf(rtn, rtn_len, "%Lfd", f) >= (int)rtn_len) { free(rtn); if (limit++ > FLOAT_SPRINTF_TRY_LIMIT) return (NULL); rtn_len *= BUFFER_GROWFACTOR; goto again; } return (rtn); case FLOAT_EXTENED_BYTES: return (decode_fp_to_long_double(p, len)); default: return (NULL); } } static char * decode_fp_to_long_double(const char *p, size_t len) { long double f; size_t rtn_len, limit, i; int byte; char *rtn; if (p == NULL || len == 0 || len % 2 != 0 || len / 2 > sizeof(long double)) return (NULL); memset(&f, 0, sizeof(long double)); for (i = 0; i < len / 2; ++i) { byte = hex_to_dec(p[len - i * 2 - 1]) + hex_to_dec(p[len - i * 2 - 2]) * 16; if (byte < 0 || byte > 255) return (NULL); #if ELFTC_BYTE_ORDER == ELFTC_BYTE_ORDER_LITTLE_ENDIAN ((unsigned char *)&f)[i] = (unsigned char)(byte); #else /* ELFTC_BYTE_ORDER != ELFTC_BYTE_ORDER_LITTLE_ENDIAN */ ((unsigned char *)&f)[sizeof(long double) - i - 1] = (unsigned char)(byte); #endif /* ELFTC_BYTE_ORDER == ELFTC_BYTE_ORDER_LITTLE_ENDIAN */ } rtn_len = 256; limit = 0; again: if ((rtn = malloc(sizeof(char) * rtn_len)) == NULL) return (NULL); if (snprintf(rtn, rtn_len, "%Lfd", f) >= (int)rtn_len) { free(rtn); if (limit++ > FLOAT_SPRINTF_TRY_LIMIT) return (NULL); rtn_len *= BUFFER_GROWFACTOR; goto again; } return (rtn); } /* Simple hex to integer function used by decode_to_* function. */ static int hex_to_dec(char c) { switch (c) { case '0': return (0); case '1': return (1); case '2': return (2); case '3': return (3); case '4': return (4); case '5': return (5); case '6': return (6); case '7': return (7); case '8': return (8); case '9': return (9); case 'a': return (10); case 'b': return (11); case 'c': return (12); case 'd': return (13); case 'e': return (14); case 'f': return (15); default: return (-1); } } /** * @brief Test input string is mangled by IA-64 C++ ABI style. * * Test string heads with "_Z" or "_GLOBAL__I_". * @return Return 0 at false. */ bool is_cpp_mangled_gnu3(const char *org) { size_t len; len = strlen(org); return ((len > 2 && *org == '_' && *(org + 1) == 'Z') || (len > 11 && !strncmp(org, "_GLOBAL__I_", 11))); } static void vector_read_cmd_dest(struct vector_read_cmd *v) { if (v == NULL) return; free(v->r_container); } static struct read_cmd_item * vector_read_cmd_find(struct vector_read_cmd *v, enum read_cmd dst) { int i; if (v == NULL || dst == READ_FAIL) return (NULL); for (i = (int) v->size - 1; i >= 0; i--) if (v->r_container[i].cmd == dst) return (&v->r_container[i]); return (NULL); } static int vector_read_cmd_init(struct vector_read_cmd *v) { if (v == NULL) return (0); v->size = 0; v->capacity = VECTOR_DEF_CAPACITY; if ((v->r_container = malloc(sizeof(*v->r_container) * v->capacity)) == NULL) return (0); return (1); } static int vector_read_cmd_pop(struct vector_read_cmd *v) { if (v == NULL || v->size == 0) return (0); --v->size; v->r_container[v->size].cmd = READ_FAIL; v->r_container[v->size].data = NULL; return (1); } static int vector_read_cmd_push(struct vector_read_cmd *v, enum read_cmd cmd, void *data) { struct read_cmd_item *tmp_r_ctn; size_t tmp_cap; size_t i; if (v == NULL) return (0); if (v->size == v->capacity) { tmp_cap = BUFFER_GROW(v->capacity); if ((tmp_r_ctn = malloc(sizeof(*tmp_r_ctn) * tmp_cap)) == NULL) return (0); for (i = 0; i < v->size; ++i) tmp_r_ctn[i] = v->r_container[i]; free(v->r_container); v->r_container = tmp_r_ctn; v->capacity = tmp_cap; } v->r_container[v->size].cmd = cmd; v->r_container[v->size].data = data; ++v->size; return (1); } static void vector_type_qualifier_dest(struct vector_type_qualifier *v) { if (v == NULL) return; free(v->q_container); vector_str_dest(&v->ext_name); } /* size, capacity, ext_name */ static int vector_type_qualifier_init(struct vector_type_qualifier *v) { if (v == NULL) return (0); v->size = 0; v->capacity = VECTOR_DEF_CAPACITY; if ((v->q_container = malloc(sizeof(enum type_qualifier) * v->capacity)) == NULL) return (0); assert(v->q_container != NULL); if (!vector_str_init(&v->ext_name)) { free(v->q_container); return (0); } return (1); } static int vector_type_qualifier_push(struct vector_type_qualifier *v, enum type_qualifier t) { enum type_qualifier *tmp_ctn; size_t tmp_cap; size_t i; if (v == NULL) return (0); if (v->size == v->capacity) { tmp_cap = BUFFER_GROW(v->capacity); if ((tmp_ctn = malloc(sizeof(enum type_qualifier) * tmp_cap)) == NULL) return (0); for (i = 0; i < v->size; ++i) tmp_ctn[i] = v->q_container[i]; free(v->q_container); v->q_container = tmp_ctn; v->capacity = tmp_cap; } v->q_container[v->size] = t; ++v->size; return (1); } diff --git a/contrib/libcxxrt/memory.cc b/contrib/libcxxrt/memory.cc index 7beb048ae914..0702f63f4527 100644 --- a/contrib/libcxxrt/memory.cc +++ b/contrib/libcxxrt/memory.cc @@ -1,191 +1,189 @@ /* * Copyright 2010-2011 PathScale, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS * IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * memory.cc - Contains stub definition of C++ new/delete operators. * * These definitions are intended to be used for testing and are weak symbols * to allow them to be replaced by definitions from a STL implementation. * These versions simply wrap malloc() and free(), they do not provide a * C++-specific allocator. */ #include #include #include "stdexcept.h" #include "atomic.h" namespace std { struct nothrow_t {}; } /// The type of the function called when allocation fails. typedef void (*new_handler)(); /** * The function to call when allocation fails. By default, there is no * handler and a bad allocation exception is thrown if an allocation fails. */ static atomic new_handl{nullptr}; namespace std { /** * Sets a function to be called when there is a failure in new. */ __attribute__((weak)) new_handler set_new_handler(new_handler handler) { return new_handl.exchange(handler); } __attribute__((weak)) new_handler get_new_handler(void) { return new_handl.load(); } } #if __cplusplus < 201103L -#define NOEXCEPT throw() #define BADALLOC throw(std::bad_alloc) #else -#define NOEXCEPT noexcept #define BADALLOC #endif namespace { /** * Helper for forwarding from no-throw operators to versions that can * return nullptr. Catches any exception and converts it into a nullptr * return. */ template void *noexcept_new(size_t size) { #if !defined(_CXXRT_NO_EXCEPTIONS) try { return New(size); } catch (...) { // nothrow operator new should return NULL in case of // std::bad_alloc exception in new handler return nullptr; } #else return New(size); #endif } } __attribute__((weak)) void* operator new(size_t size) BADALLOC { if (0 == size) { size = 1; } void * mem = malloc(size); while (0 == mem) { new_handler h = std::get_new_handler(); if (0 != h) { h(); } else { #if !defined(_CXXRT_NO_EXCEPTIONS) throw std::bad_alloc(); #else break; #endif } mem = malloc(size); } return mem; } __attribute__((weak)) -void* operator new(size_t size, const std::nothrow_t &) NOEXCEPT +void* operator new(size_t size, const std::nothrow_t &) _LIBCXXRT_NOEXCEPT { return noexcept_new<(::operator new)>(size); } __attribute__((weak)) -void operator delete(void * ptr) NOEXCEPT +void operator delete(void * ptr) _LIBCXXRT_NOEXCEPT { free(ptr); } __attribute__((weak)) void * operator new[](size_t size) BADALLOC { return ::operator new(size); } __attribute__((weak)) -void * operator new[](size_t size, const std::nothrow_t &) NOEXCEPT +void * operator new[](size_t size, const std::nothrow_t &) _LIBCXXRT_NOEXCEPT { return noexcept_new<(::operator new[])>(size); } __attribute__((weak)) -void operator delete[](void * ptr) NOEXCEPT +void operator delete[](void * ptr) _LIBCXXRT_NOEXCEPT { ::operator delete(ptr); } // C++14 additional delete operators #if __cplusplus >= 201402L __attribute__((weak)) -void operator delete(void * ptr, size_t) NOEXCEPT +void operator delete(void * ptr, size_t) _LIBCXXRT_NOEXCEPT { ::operator delete(ptr); } __attribute__((weak)) -void operator delete[](void * ptr, size_t) NOEXCEPT +void operator delete[](void * ptr, size_t) _LIBCXXRT_NOEXCEPT { ::operator delete(ptr); } #endif diff --git a/contrib/libcxxrt/noexception.cc b/contrib/libcxxrt/noexception.cc index 25dac1279684..7d17920c7cf4 100644 --- a/contrib/libcxxrt/noexception.cc +++ b/contrib/libcxxrt/noexception.cc @@ -1,45 +1,45 @@ /* * Copyright 2021 Microsoft. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS * IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace std { /** * Returns whether there are any exceptions currently being thrown that * have not been caught. Without exception support this is always false. */ - bool uncaught_exception() throw() + bool uncaught_exception() _LIBCXXRT_NOEXCEPT { return false; } /** * Returns the number of exceptions currently being thrown that have not * been caught. Without exception support this is always 0. */ - int uncaught_exceptions() throw() + int uncaught_exceptions() _LIBCXXRT_NOEXCEPT { return 0; } } diff --git a/contrib/libcxxrt/stdexcept.cc b/contrib/libcxxrt/stdexcept.cc index c1cea39f6aa6..22c6930dca6b 100644 --- a/contrib/libcxxrt/stdexcept.cc +++ b/contrib/libcxxrt/stdexcept.cc @@ -1,99 +1,99 @@ /* * Copyright 2010-2011 PathScale, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS * IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * stdexcept.cc - provides stub implementations of the exceptions required by the runtime. */ #include "stdexcept.h" namespace std { -exception::exception() throw() {} +exception::exception() _LIBCXXRT_NOEXCEPT {} exception::~exception() {} -exception::exception(const exception&) throw() {} -exception& exception::operator=(const exception&) throw() +exception::exception(const exception&) _LIBCXXRT_NOEXCEPT {} +exception& exception::operator=(const exception&) _LIBCXXRT_NOEXCEPT { return *this; } -const char* exception::what() const throw() +const char* exception::what() const _LIBCXXRT_NOEXCEPT { return "std::exception"; } -bad_alloc::bad_alloc() throw() {} +bad_alloc::bad_alloc() _LIBCXXRT_NOEXCEPT {} bad_alloc::~bad_alloc() {} -bad_alloc::bad_alloc(const bad_alloc&) throw() {} -bad_alloc& bad_alloc::operator=(const bad_alloc&) throw() +bad_alloc::bad_alloc(const bad_alloc&) _LIBCXXRT_NOEXCEPT {} +bad_alloc& bad_alloc::operator=(const bad_alloc&) _LIBCXXRT_NOEXCEPT { return *this; } -const char* bad_alloc::what() const throw() +const char* bad_alloc::what() const _LIBCXXRT_NOEXCEPT { return "cxxrt::bad_alloc"; } -bad_cast::bad_cast() throw() {} +bad_cast::bad_cast() _LIBCXXRT_NOEXCEPT {} bad_cast::~bad_cast() {} -bad_cast::bad_cast(const bad_cast&) throw() {} -bad_cast& bad_cast::operator=(const bad_cast&) throw() +bad_cast::bad_cast(const bad_cast&) _LIBCXXRT_NOEXCEPT {} +bad_cast& bad_cast::operator=(const bad_cast&) _LIBCXXRT_NOEXCEPT { return *this; } -const char* bad_cast::what() const throw() +const char* bad_cast::what() const _LIBCXXRT_NOEXCEPT { return "std::bad_cast"; } -bad_typeid::bad_typeid() throw() {} +bad_typeid::bad_typeid() _LIBCXXRT_NOEXCEPT {} bad_typeid::~bad_typeid() {} -bad_typeid::bad_typeid(const bad_typeid &__rhs) throw() {} -bad_typeid& bad_typeid::operator=(const bad_typeid &__rhs) throw() +bad_typeid::bad_typeid(const bad_typeid &__rhs) _LIBCXXRT_NOEXCEPT {} +bad_typeid& bad_typeid::operator=(const bad_typeid &__rhs) _LIBCXXRT_NOEXCEPT { return *this; } -const char* bad_typeid::what() const throw() +const char* bad_typeid::what() const _LIBCXXRT_NOEXCEPT { return "std::bad_typeid"; } -bad_array_new_length::bad_array_new_length() throw() {} +bad_array_new_length::bad_array_new_length() _LIBCXXRT_NOEXCEPT {} bad_array_new_length::~bad_array_new_length() {} -bad_array_new_length::bad_array_new_length(const bad_array_new_length&) throw() {} -bad_array_new_length& bad_array_new_length::operator=(const bad_array_new_length&) throw() +bad_array_new_length::bad_array_new_length(const bad_array_new_length&) _LIBCXXRT_NOEXCEPT {} +bad_array_new_length& bad_array_new_length::operator=(const bad_array_new_length&) _LIBCXXRT_NOEXCEPT { return *this; } -const char* bad_array_new_length::what() const throw() +const char* bad_array_new_length::what() const _LIBCXXRT_NOEXCEPT { return "std::bad_array_new_length"; } } // namespace std diff --git a/contrib/libcxxrt/stdexcept.h b/contrib/libcxxrt/stdexcept.h index 892039357595..38cd36d8e566 100644 --- a/contrib/libcxxrt/stdexcept.h +++ b/contrib/libcxxrt/stdexcept.h @@ -1,96 +1,98 @@ /* * Copyright 2010-2011 PathScale, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS * IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * stdexcept.h - provides a stub version of , which defines enough * of the exceptions for the runtime to use. */ +#include "cxxabi.h" + namespace std { class exception { public: - exception() throw(); - exception(const exception&) throw(); - exception& operator=(const exception&) throw(); + exception() _LIBCXXRT_NOEXCEPT; + exception(const exception&) _LIBCXXRT_NOEXCEPT; + exception& operator=(const exception&) _LIBCXXRT_NOEXCEPT; virtual ~exception(); - virtual const char* what() const throw(); + virtual const char* what() const _LIBCXXRT_NOEXCEPT; }; /** * Bad allocation exception. Thrown by ::operator new() if it fails. */ class bad_alloc: public exception { public: - bad_alloc() throw(); - bad_alloc(const bad_alloc&) throw(); - bad_alloc& operator=(const bad_alloc&) throw(); + bad_alloc() _LIBCXXRT_NOEXCEPT; + bad_alloc(const bad_alloc&) _LIBCXXRT_NOEXCEPT; + bad_alloc& operator=(const bad_alloc&) _LIBCXXRT_NOEXCEPT; ~bad_alloc(); - virtual const char* what() const throw(); + virtual const char* what() const _LIBCXXRT_NOEXCEPT; }; /** * Bad cast exception. Thrown by the __cxa_bad_cast() helper function. */ class bad_cast: public exception { public: - bad_cast() throw(); - bad_cast(const bad_cast&) throw(); - bad_cast& operator=(const bad_cast&) throw(); + bad_cast() _LIBCXXRT_NOEXCEPT; + bad_cast(const bad_cast&) _LIBCXXRT_NOEXCEPT; + bad_cast& operator=(const bad_cast&) _LIBCXXRT_NOEXCEPT; virtual ~bad_cast(); - virtual const char* what() const throw(); + virtual const char* what() const _LIBCXXRT_NOEXCEPT; }; /** * Bad typeidexception. Thrown by the __cxa_bad_typeid() helper function. */ class bad_typeid: public exception { public: - bad_typeid() throw(); - bad_typeid(const bad_typeid &__rhs) throw(); + bad_typeid() _LIBCXXRT_NOEXCEPT; + bad_typeid(const bad_typeid &__rhs) _LIBCXXRT_NOEXCEPT; virtual ~bad_typeid(); - bad_typeid& operator=(const bad_typeid &__rhs) throw(); - virtual const char* what() const throw(); + bad_typeid& operator=(const bad_typeid &__rhs) _LIBCXXRT_NOEXCEPT; + virtual const char* what() const _LIBCXXRT_NOEXCEPT; }; class bad_array_new_length: public bad_alloc { public: - bad_array_new_length() throw(); - bad_array_new_length(const bad_array_new_length&) throw(); - bad_array_new_length& operator=(const bad_array_new_length&) throw(); + bad_array_new_length() _LIBCXXRT_NOEXCEPT; + bad_array_new_length(const bad_array_new_length&) _LIBCXXRT_NOEXCEPT; + bad_array_new_length& operator=(const bad_array_new_length&) _LIBCXXRT_NOEXCEPT; virtual ~bad_array_new_length(); - virtual const char *what() const throw(); + virtual const char *what() const _LIBCXXRT_NOEXCEPT; }; } // namespace std