exception.cc 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419
  1. /*
  2. * Copyright 2010-2011 PathScale, Inc. All rights reserved.
  3. *
  4. * Redistribution and use in source and binary forms, with or without
  5. * modification, are permitted provided that the following conditions are met:
  6. *
  7. * 1. Redistributions of source code must retain the above copyright notice,
  8. * this list of conditions and the following disclaimer.
  9. *
  10. * 2. Redistributions in binary form must reproduce the above copyright notice,
  11. * this list of conditions and the following disclaimer in the documentation
  12. * and/or other materials provided with the distribution.
  13. *
  14. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS
  15. * IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
  16. * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  17. * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
  18. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  19. * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  20. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
  21. * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  22. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
  23. * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  24. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <stdlib.h>
  27. #include <stdio.h>
  28. #include <string.h>
  29. #include <stdint.h>
  30. #include <new>
  31. #include "pthread_compat.h"
  32. #include "typeinfo.h"
  33. #include "dwarf_eh.h"
  34. #include "atomic.h"
  35. #include "cxxabi.h"
  36. #include "thread_data.h"
  37. #include "se_cdefs.h"
  38. // access the version varible to add a version to tstdcxx lib
  39. SGX_ACCESS_VERSION(tstdcxx, 1)
  40. using namespace ABI_NAMESPACE;
  41. /**
  42. * Saves the result of the landing pad that we have found. For ARM, this is
  43. * stored in the generic unwind structure, while on other platforms it is
  44. * stored in the C++ exception.
  45. */
  46. static void saveLandingPad(struct _Unwind_Context *context,
  47. struct _Unwind_Exception *ucb,
  48. struct __cxa_exception *ex,
  49. int selector,
  50. dw_eh_ptr_t landingPad)
  51. {
  52. #ifdef __arm__
  53. // On ARM, we store the saved exception in the generic part of the structure
  54. ucb->barrier_cache.sp = _Unwind_GetGR(context, 13);
  55. ucb->barrier_cache.bitpattern[1] = (uint32_t)selector;
  56. ucb->barrier_cache.bitpattern[3] = (uint32_t)landingPad;
  57. #endif
  58. // Cache the results for the phase 2 unwind, if we found a handler
  59. // and this is not a foreign exception.
  60. if (ex)
  61. {
  62. ex->handlerSwitchValue = selector;
  63. ex->catchTemp = landingPad;
  64. }
  65. }
  66. /**
  67. * Loads the saved landing pad. Returns 1 on success, 0 on failure.
  68. */
  69. static int loadLandingPad(struct _Unwind_Context *context,
  70. struct _Unwind_Exception *ucb,
  71. struct __cxa_exception *ex,
  72. unsigned long *selector,
  73. dw_eh_ptr_t *landingPad)
  74. {
  75. #ifdef __arm__
  76. *selector = ucb->barrier_cache.bitpattern[1];
  77. *landingPad = (dw_eh_ptr_t)ucb->barrier_cache.bitpattern[3];
  78. return 1;
  79. #else
  80. if (ex)
  81. {
  82. *selector = ex->handlerSwitchValue;
  83. *landingPad = (dw_eh_ptr_t)ex->catchTemp;
  84. return 0;
  85. }
  86. return 0;
  87. #endif
  88. }
  89. static inline _Unwind_Reason_Code continueUnwinding(struct _Unwind_Exception *ex,
  90. struct _Unwind_Context *context)
  91. {
  92. #ifdef __arm__
  93. if (__gnu_unwind_frame(ex, context) != _URC_OK) { return _URC_FAILURE; }
  94. #endif
  95. return _URC_CONTINUE_UNWIND;
  96. }
  97. extern "C" void __cxa_free_exception(void *thrown_exception);
  98. extern "C" void __cxa_free_dependent_exception(void *thrown_exception);
  99. extern "C" void* __dynamic_cast(const void *sub,
  100. const __class_type_info *src,
  101. const __class_type_info *dst,
  102. ptrdiff_t src2dst_offset);
  103. /**
  104. * The type of a handler that has been found.
  105. */
  106. typedef enum
  107. {
  108. /** No handler. */
  109. handler_none,
  110. /**
  111. * A cleanup - the exception will propagate through this frame, but code
  112. * must be run when this happens.
  113. */
  114. handler_cleanup,
  115. /**
  116. * A catch statement. The exception will not propagate past this frame
  117. * (without an explicit rethrow).
  118. */
  119. handler_catch
  120. } handler_type;
  121. /**
  122. * Per-thread info required by the runtime. We store a single structure
  123. * pointer in thread-local storage, because this tends to be a scarce resource
  124. * and it's impolite to steal all of it and not leave any for the rest of the
  125. * program.
  126. *
  127. * Instances of this structure are allocated lazily - at most one per thread -
  128. * and are destroyed on thread termination.
  129. */
  130. struct __cxa_thread_info
  131. {
  132. /** The termination handler for this thread. */
  133. terminate_handler terminateHandler;
  134. /** The unexpected exception handler for this thread. */
  135. unexpected_handler unexpectedHandler;
  136. /**
  137. * The number of emergency buffers held by this thread. This is 0 in
  138. * normal operation - the emergency buffers are only used when malloc()
  139. * fails to return memory for allocating an exception. Threads are not
  140. * permitted to hold more than 4 emergency buffers (as per recommendation
  141. * in ABI spec [3.3.1]).
  142. */
  143. int emergencyBuffersHeld;
  144. /**
  145. * The exception currently running in a cleanup.
  146. */
  147. _Unwind_Exception *currentCleanup;
  148. /**
  149. * The public part of this structure, accessible from outside of this
  150. * module.
  151. */
  152. __cxa_eh_globals globals;
  153. };
  154. /**
  155. * Dependent exception. This
  156. */
  157. struct __cxa_dependent_exception
  158. {
  159. #if __LP64__
  160. void *primaryException;
  161. #endif
  162. std::type_info *exceptionType;
  163. void (*exceptionDestructor) (void *);
  164. unexpected_handler unexpectedHandler;
  165. terminate_handler terminateHandler;
  166. __cxa_exception *nextException;
  167. int handlerCount;
  168. #ifdef __arm__
  169. _Unwind_Exception *nextCleanup;
  170. int cleanupCount;
  171. #endif
  172. int handlerSwitchValue;
  173. const char *actionRecord;
  174. const char *languageSpecificData;
  175. void *catchTemp;
  176. void *adjustedPtr;
  177. #if !__LP64__
  178. void *primaryException;
  179. #endif
  180. _Unwind_Exception unwindHeader;
  181. };
  182. namespace std
  183. {
  184. void unexpected();
  185. #if 0
  186. class exception
  187. {
  188. public:
  189. virtual ~exception() throw();
  190. virtual const char* what() const throw();
  191. };
  192. #endif
  193. }
  194. extern "C" std::type_info *__cxa_current_exception_type();
  195. /**
  196. * Class of exceptions to distinguish between this and other exception types.
  197. *
  198. * The first four characters are the vendor ID. Currently, we use GNUC,
  199. * because we aim for ABI-compatibility with the GNU implementation, and
  200. * various checks may test for equality of the class, which is incorrect.
  201. */
  202. static const uint64_t exception_class =
  203. EXCEPTION_CLASS('G', 'N', 'U', 'C', 'C', '+', '+', '\0');
  204. /**
  205. * Class used for dependent exceptions.
  206. */
  207. static const uint64_t dependent_exception_class =
  208. EXCEPTION_CLASS('G', 'N', 'U', 'C', 'C', '+', '+', '\x01');
  209. /**
  210. * The low four bytes of the exception class, indicating that we conform to the
  211. * Itanium C++ ABI. This is currently unused, but should be used in the future
  212. * if we change our exception class, to allow this library and libsupc++ to be
  213. * linked to the same executable and both to interoperate.
  214. */
  215. static const uint32_t abi_exception_class =
  216. GENERIC_EXCEPTION_CLASS('C', '+', '+', '\0');
  217. static bool isCXXException(uint64_t cls)
  218. {
  219. return (cls == exception_class) || (cls == dependent_exception_class);
  220. }
  221. static bool isDependentException(uint64_t cls)
  222. {
  223. return cls == dependent_exception_class;
  224. }
  225. static __cxa_exception *exceptionFromPointer(void *ex)
  226. {
  227. return (__cxa_exception*)((char*)ex -
  228. offsetof(struct __cxa_exception, unwindHeader));
  229. }
  230. static __cxa_exception *realExceptionFromException(__cxa_exception *ex)
  231. {
  232. if (!isDependentException(ex->unwindHeader.exception_class)) { return ex; }
  233. return ((__cxa_exception*)(((__cxa_dependent_exception*)ex)->primaryException))-1;
  234. }
  235. namespace std
  236. {
  237. // Forward declaration of standard library terminate() function used to
  238. // abort execution.
  239. void terminate(void);
  240. }
  241. using namespace ABI_NAMESPACE;
  242. /** The global termination handler. */
  243. static terminate_handler terminateHandler = abort;
  244. /** The global unexpected exception handler. */
  245. static unexpected_handler unexpectedHandler = std::terminate;
  246. /**
  247. * Cleanup function, allowing foreign exception handlers to correctly destroy
  248. * this exception if they catch it.
  249. */
  250. static void exception_cleanup(_Unwind_Reason_Code reason,
  251. struct _Unwind_Exception *ex)
  252. {
  253. __cxa_free_exception((void*)ex);
  254. }
  255. static void dependent_exception_cleanup(_Unwind_Reason_Code reason,
  256. struct _Unwind_Exception *ex)
  257. {
  258. __cxa_free_dependent_exception((void*)ex);
  259. }
  260. /**
  261. * Recursively walk a list of exceptions and delete them all in post-order.
  262. */
  263. static void free_exception_list(__cxa_exception *ex)
  264. {
  265. if (0 != ex->nextException)
  266. {
  267. free_exception_list(ex->nextException);
  268. }
  269. // __cxa_free_exception() expects to be passed the thrown object, which
  270. // immediately follows the exception, not the exception itself
  271. __cxa_free_exception(ex+1);
  272. }
  273. /**
  274. * We may not be linked against a full pthread implementation. If we're not,
  275. * then we need to fake the thread-local storage by storing 'thread-local'
  276. * things in a global.
  277. */
  278. static __cxa_thread_info* __get_thread_info_ptr()
  279. {
  280. thread_data_t* td = get_thread_data();
  281. return (__cxa_thread_info *)td->cxx_thread_info;
  282. }
  283. /**
  284. * Returns the thread info structure, creating it if it is not already created.
  285. */
  286. static __cxa_thread_info *thread_info()
  287. {
  288. return __get_thread_info_ptr();
  289. }
  290. /**
  291. * Fast version of thread_info(). May fail if thread_info() is not called on
  292. * this thread at least once already.
  293. */
  294. static __cxa_thread_info *thread_info_fast()
  295. {
  296. return __get_thread_info_ptr();
  297. }
  298. /**
  299. * ABI function returning the __cxa_eh_globals structure.
  300. */
  301. extern "C" __cxa_eh_globals *ABI_NAMESPACE::__cxa_get_globals(void)
  302. {
  303. return &(thread_info()->globals);
  304. }
  305. /**
  306. * Version of __cxa_get_globals() assuming that __cxa_get_globals() has already
  307. * been called at least once by this thread.
  308. */
  309. extern "C" __cxa_eh_globals *ABI_NAMESPACE::__cxa_get_globals_fast(void)
  310. {
  311. return &(thread_info_fast()->globals);
  312. }
  313. /**
  314. * An emergency allocation reserved for when malloc fails. This is treated as
  315. * 16 buffers of 1KB each.
  316. */
  317. static char emergency_buffer[16384];
  318. /**
  319. * Flag indicating whether each buffer is allocated.
  320. */
  321. static bool buffer_allocated[16];
  322. /**
  323. * Lock used to protect emergency allocation.
  324. */
  325. static pthread_mutex_t emergency_malloc_lock = PTHREAD_MUTEX_INITIALIZER;
  326. /**
  327. * Indicate whether there is chunk in `emergency_buffer available'.
  328. * This variable is also protected by `emergency_malloc_lock'.
  329. */
  330. static volatile bool buffer_available = true;
  331. /**
  332. * Allocates size bytes from the emergency allocation mechanism, if possible.
  333. * This function will fail if size is over 1KB or if this thread already has 4
  334. * emergency buffers. If all emergency buffers are allocated, it will wait
  335. * until one becomes available.
  336. */
  337. static char *emergency_malloc(size_t size)
  338. {
  339. if (size > 1024) { return 0; }
  340. __cxa_thread_info *info = thread_info();
  341. // Only 4 emergency buffers allowed per thread!
  342. if (info->emergencyBuffersHeld > 3) { return 0; }
  343. pthread_mutex_lock(&emergency_malloc_lock);
  344. int buffer = -1;
  345. while (buffer < 0)
  346. {
  347. // While we were sleeping on the lock, another thread might have free'd
  348. // enough memory for us to use, so try the allocation again - no point
  349. // using the emergency buffer if there is some real memory that we can
  350. // use...
  351. void *m = calloc(1, size);
  352. if (0 != m)
  353. {
  354. pthread_mutex_unlock(&emergency_malloc_lock);
  355. return (char*)m;
  356. }
  357. for (int i=0 ; i<16 ; i++)
  358. {
  359. if (!buffer_allocated[i])
  360. {
  361. buffer = i;
  362. buffer_allocated[i] = true;
  363. break;
  364. }
  365. }
  366. // If there still isn't a buffer available ...
  367. if (buffer < 0)
  368. {
  369. // No buffer available, unlock and waiting on `buffer_available'.
  370. buffer_available = false;
  371. pthread_mutex_unlock(&emergency_malloc_lock);
  372. while (!buffer_available) continue;
  373. // Try to acquire the lock again.
  374. pthread_mutex_lock(&emergency_malloc_lock);
  375. }
  376. }
  377. pthread_mutex_unlock(&emergency_malloc_lock);
  378. info->emergencyBuffersHeld++;
  379. return emergency_buffer + (1024 * buffer);
  380. }
  381. /**
  382. * Frees a buffer returned by emergency_malloc().
  383. *
  384. * Note: Neither this nor emergency_malloc() is particularly efficient. This
  385. * should not matter, because neither will be called in normal operation - they
  386. * are only used when the program runs out of memory, which should not happen
  387. * often.
  388. */
  389. static void emergency_malloc_free(char *ptr)
  390. {
  391. int buffer = -1;
  392. // Find the buffer corresponding to this pointer.
  393. for (int i=0 ; i<16 ; i++)
  394. {
  395. if (ptr == (void*)(emergency_buffer + (1024 * i)))
  396. {
  397. buffer = i;
  398. break;
  399. }
  400. }
  401. assert(buffer >= 0 &&
  402. "Trying to free something that is not an emergency buffer!");
  403. // emergency_malloc() is expected to return 0-initialized data. We don't
  404. // zero the buffer when allocating it, because the static buffers will
  405. // begin life containing 0 values.
  406. memset((void*)ptr, 0, 1024);
  407. pthread_mutex_lock(&emergency_malloc_lock);
  408. // In theory, we don't need to do this with the lock held. In practice,
  409. // our array of bools will probably be updated using 32-bit or 64-bit
  410. // memory operations, so this update may clobber adjacent values.
  411. if (buffer != -1)
  412. {
  413. buffer_allocated[buffer] = false;
  414. buffer_available = true;
  415. }
  416. pthread_mutex_unlock(&emergency_malloc_lock);
  417. }
  418. static char *alloc_or_die(size_t size)
  419. {
  420. char *buffer = (char*)calloc(1, size);
  421. // If calloc() doesn't want to give us any memory, try using an emergency
  422. // buffer.
  423. if (0 == buffer)
  424. {
  425. buffer = emergency_malloc(size);
  426. // This is only reached if the allocation is greater than 1KB, and
  427. // anyone throwing objects that big really should know better.
  428. if (0 == buffer)
  429. {
  430. //fprintf(stderr, "Out of memory attempting to allocate exception\n");
  431. std::terminate();
  432. }
  433. }
  434. return buffer;
  435. }
  436. static void free_exception(char *e)
  437. {
  438. // If this allocation is within the address range of the emergency buffer,
  439. // don't call free() because it was not allocated with malloc()
  440. if ((e >= emergency_buffer) &&
  441. (e < (emergency_buffer + sizeof(emergency_buffer))))
  442. {
  443. emergency_malloc_free(e);
  444. }
  445. else
  446. {
  447. free(e);
  448. }
  449. }
  450. /**
  451. * Allocates an exception structure. Returns a pointer to the space that can
  452. * be used to store an object of thrown_size bytes. This function will use an
  453. * emergency buffer if malloc() fails, and may block if there are no such
  454. * buffers available.
  455. */
  456. extern "C" void *__cxa_allocate_exception(size_t thrown_size)
  457. {
  458. size_t size = thrown_size + sizeof(__cxa_exception);
  459. char *buffer = alloc_or_die(size);
  460. return buffer+sizeof(__cxa_exception);
  461. }
  462. extern "C" void *__cxa_allocate_dependent_exception(void)
  463. {
  464. size_t size = sizeof(__cxa_dependent_exception);
  465. char *buffer = alloc_or_die(size);
  466. return buffer+sizeof(__cxa_dependent_exception);
  467. }
  468. /**
  469. * __cxa_free_exception() is called when an exception was thrown in between
  470. * calling __cxa_allocate_exception() and actually throwing the exception.
  471. * This happens when the object's copy constructor throws an exception.
  472. *
  473. * In this implementation, it is also called by __cxa_end_catch() and during
  474. * thread cleanup.
  475. */
  476. extern "C" void __cxa_free_exception(void *thrown_exception)
  477. {
  478. __cxa_exception *ex = ((__cxa_exception*)thrown_exception) - 1;
  479. // Free the object that was thrown, calling its destructor
  480. if (0 != ex->exceptionDestructor)
  481. {
  482. try
  483. {
  484. ex->exceptionDestructor(thrown_exception);
  485. }
  486. catch(...)
  487. {
  488. // FIXME: Check that this is really what the spec says to do.
  489. std::terminate();
  490. }
  491. }
  492. free_exception((char*)ex);
  493. }
  494. static void releaseException(__cxa_exception *exception)
  495. {
  496. if (isDependentException(exception->unwindHeader.exception_class))
  497. {
  498. __cxa_free_dependent_exception(exception+1);
  499. return;
  500. }
  501. if (__sync_sub_and_fetch(&exception->referenceCount, 1) == 0)
  502. {
  503. // __cxa_free_exception() expects to be passed the thrown object,
  504. // which immediately follows the exception, not the exception
  505. // itself
  506. __cxa_free_exception(exception+1);
  507. }
  508. }
  509. void __cxa_free_dependent_exception(void *thrown_exception)
  510. {
  511. __cxa_dependent_exception *ex = ((__cxa_dependent_exception*)thrown_exception) - 1;
  512. assert(isDependentException(ex->unwindHeader.exception_class));
  513. if (ex->primaryException)
  514. {
  515. releaseException(realExceptionFromException((__cxa_exception*)ex));
  516. }
  517. free_exception((char*)ex);
  518. }
  519. /**
  520. * Callback function used with _Unwind_Backtrace().
  521. *
  522. * Prints a stack trace. Used only for debugging help.
  523. *
  524. * Note: As of FreeBSD 8.1, dladd() still doesn't work properly, so this only
  525. * correctly prints function names from public, relocatable, symbols.
  526. */
  527. static _Unwind_Reason_Code trace(struct _Unwind_Context *context, void *c)
  528. {
  529. #if 0
  530. Dl_info myinfo;
  531. int mylookup =
  532. dladdr((void*)(uintptr_t)__cxa_current_exception_type, &myinfo);
  533. void *ip = (void*)_Unwind_GetIP(context);
  534. Dl_info info;
  535. if (dladdr(ip, &info) != 0)
  536. {
  537. if (mylookup == 0 || strcmp(info.dli_fname, myinfo.dli_fname) != 0)
  538. {
  539. printf("%p:%s() in %s\n", ip, info.dli_sname, info.dli_fname);
  540. }
  541. }
  542. #endif
  543. return _URC_CONTINUE_UNWIND;
  544. }
  545. /**
  546. * Report a failure that occurred when attempting to throw an exception.
  547. *
  548. * If the failure happened by falling off the end of the stack without finding
  549. * a handler, prints a back trace before aborting.
  550. */
  551. static void report_failure(_Unwind_Reason_Code err, __cxa_exception *thrown_exception)
  552. {
  553. switch (err)
  554. {
  555. default: break;
  556. case _URC_FATAL_PHASE1_ERROR:
  557. //fprintf(stderr, "Fatal error during phase 1 unwinding\n");
  558. break;
  559. #ifndef __arm__
  560. case _URC_FATAL_PHASE2_ERROR:
  561. //fprintf(stderr, "Fatal error during phase 2 unwinding\n");
  562. break;
  563. #endif
  564. case _URC_END_OF_STACK:
  565. //fprintf(stderr, "Terminating due to uncaught exception %p",
  566. // (void*)thrown_exception);
  567. thrown_exception = realExceptionFromException(thrown_exception);
  568. static const __class_type_info *e_ti =
  569. static_cast<const __class_type_info*>(&typeid(std::exception));
  570. const __class_type_info *throw_ti =
  571. dynamic_cast<const __class_type_info*>(thrown_exception->exceptionType);
  572. if (throw_ti)
  573. {
  574. std::exception *e =
  575. (std::exception*)e_ti->cast_to((void*)(thrown_exception+1),
  576. throw_ti);
  577. if (e)
  578. {
  579. //fprintf(stderr, " '%s'", e->what());
  580. }
  581. }
  582. #if 0
  583. size_t bufferSize = 128;
  584. char *demangled = (char*)malloc(bufferSize);
  585. const char *mangled = thrown_exception->exceptionType->name();
  586. int status;
  587. demangled = __cxa_demangle(mangled, demangled, &bufferSize, &status);
  588. //fprintf(stderr, " of type %s\n",
  589. // status == 0 ? (const char*)demangled : mangled);
  590. if (status == 0) { free(demangled); }
  591. #endif
  592. // Print a back trace if no handler is found.
  593. // TODO: Make this optional
  594. _Unwind_Backtrace(trace, 0);
  595. break;
  596. }
  597. std::terminate();
  598. }
  599. static void throw_exception(__cxa_exception *ex)
  600. {
  601. __cxa_thread_info *info = thread_info();
  602. ex->unexpectedHandler = info->unexpectedHandler;
  603. if (0 == ex->unexpectedHandler)
  604. {
  605. ex->unexpectedHandler = unexpectedHandler;
  606. }
  607. ex->terminateHandler = info->terminateHandler;
  608. if (0 == ex->terminateHandler)
  609. {
  610. ex->terminateHandler = terminateHandler;
  611. }
  612. info->globals.uncaughtExceptions++;
  613. _Unwind_Reason_Code err = _Unwind_RaiseException(&ex->unwindHeader);
  614. // The _Unwind_RaiseException() function should not return, it should
  615. // unwind the stack past this function. If it does return, then something
  616. // has gone wrong.
  617. report_failure(err, ex);
  618. }
  619. /**
  620. * ABI function for throwing an exception. Takes the object to be thrown (the
  621. * pointer returned by __cxa_allocate_exception()), the type info for the
  622. * pointee, and the destructor (if there is one) as arguments.
  623. */
  624. extern "C" void __cxa_throw(void *thrown_exception,
  625. std::type_info *tinfo,
  626. void(*dest)(void*))
  627. {
  628. __cxa_exception *ex = ((__cxa_exception*)thrown_exception) - 1;
  629. ex->referenceCount = 1;
  630. ex->exceptionType = tinfo;
  631. ex->exceptionDestructor = dest;
  632. ex->unwindHeader.exception_class = exception_class;
  633. ex->unwindHeader.exception_cleanup = exception_cleanup;
  634. throw_exception(ex);
  635. }
  636. extern "C" void __cxa_rethrow_primary_exception(void* thrown_exception)
  637. {
  638. if (NULL == thrown_exception) { return; }
  639. __cxa_exception *original = exceptionFromPointer(thrown_exception);
  640. __cxa_dependent_exception *ex = ((__cxa_dependent_exception*)__cxa_allocate_dependent_exception())-1;
  641. ex->primaryException = thrown_exception;
  642. __cxa_increment_exception_refcount(thrown_exception);
  643. ex->exceptionType = original->exceptionType;
  644. ex->unwindHeader.exception_class = dependent_exception_class;
  645. ex->unwindHeader.exception_cleanup = dependent_exception_cleanup;
  646. throw_exception((__cxa_exception*)ex);
  647. }
  648. extern "C" void *__cxa_current_primary_exception(void)
  649. {
  650. __cxa_eh_globals* globals = __cxa_get_globals();
  651. __cxa_exception *ex = globals->caughtExceptions;
  652. if (0 == ex) { return NULL; }
  653. ex = realExceptionFromException(ex);
  654. __sync_fetch_and_add(&ex->referenceCount, 1);
  655. return ex + 1;
  656. }
  657. extern "C" void __cxa_increment_exception_refcount(void* thrown_exception)
  658. {
  659. if (NULL == thrown_exception) { return; }
  660. __cxa_exception *ex = ((__cxa_exception*)thrown_exception) - 1;
  661. if (isDependentException(ex->unwindHeader.exception_class)) { return; }
  662. __sync_fetch_and_add(&ex->referenceCount, 1);
  663. }
  664. extern "C" void __cxa_decrement_exception_refcount(void* thrown_exception)
  665. {
  666. if (NULL == thrown_exception) { return; }
  667. __cxa_exception *ex = ((__cxa_exception*)thrown_exception) - 1;
  668. releaseException(ex);
  669. }
  670. /**
  671. * ABI function. Rethrows the current exception. Does not remove the
  672. * exception from the stack or decrement its handler count - the compiler is
  673. * expected to set the landing pad for this function to the end of the catch
  674. * block, and then call _Unwind_Resume() to continue unwinding once
  675. * __cxa_end_catch() has been called and any cleanup code has been run.
  676. */
  677. extern "C" void __cxa_rethrow()
  678. {
  679. __cxa_eh_globals *globals = __cxa_get_globals();
  680. // Note: We don't remove this from the caught list here, because
  681. // __cxa_end_catch will be called when we unwind out of the try block. We
  682. // could probably make this faster by providing an alternative rethrow
  683. // function and ensuring that all cleanup code is run before calling it, so
  684. // we can skip the top stack frame when unwinding.
  685. __cxa_exception *ex = globals->caughtExceptions;
  686. if (0 == ex)
  687. {
  688. //fprintf(stderr,
  689. // "Attempting to rethrow an exception that doesn't exist!\n");
  690. std::terminate();
  691. }
  692. assert(ex->handlerCount > 0 && "Rethrowing uncaught exception!");
  693. globals->uncaughtExceptions++;
  694. // ex->handlerCount will be decremented in __cxa_end_catch in enclosing
  695. // catch block
  696. // Make handler count negative. This will tell __cxa_end_catch that
  697. // exception was rethrown and exception object should not be destroyed
  698. // when handler count become zero
  699. ex->handlerCount = -ex->handlerCount;
  700. // Continue unwinding the stack with this exception. This should unwind to
  701. // the place in the caller where __cxa_end_catch() is called. The caller
  702. // will then run cleanup code and bounce the exception back with
  703. // _Unwind_Resume().
  704. _Unwind_Reason_Code err = _Unwind_Resume_or_Rethrow(&ex->unwindHeader);
  705. report_failure(err, ex);
  706. }
  707. /**
  708. * Returns the type_info object corresponding to the filter.
  709. */
  710. static std::type_info *get_type_info_entry(_Unwind_Context *context,
  711. dwarf_eh_lsda *lsda,
  712. int filter)
  713. {
  714. // Get the address of the record in the table.
  715. dw_eh_ptr_t record = lsda->type_table -
  716. dwarf_size_of_fixed_size_field(lsda->type_table_encoding)*filter;
  717. //record -= 4;
  718. dw_eh_ptr_t start = record;
  719. // Read the value, but it's probably an indirect reference...
  720. int64_t offset = read_value(lsda->type_table_encoding, &record);
  721. // (If the entry is 0, don't try to dereference it. That would be bad.)
  722. if (offset == 0) { return 0; }
  723. // ...so we need to resolve it
  724. return (std::type_info*)resolve_indirect_value(context,
  725. lsda->type_table_encoding, offset, start);
  726. }
  727. /**
  728. * Checks the type signature found in a handler against the type of the thrown
  729. * object. If ex is 0 then it is assumed to be a foreign exception and only
  730. * matches cleanups.
  731. */
  732. static bool check_type_signature(__cxa_exception *ex,
  733. const std::type_info *type,
  734. void *&adjustedPtr)
  735. {
  736. void *exception_ptr = (void*)(ex+1);
  737. const std::type_info *ex_type = NULL;
  738. if (ex)
  739. {
  740. ex_type = ex->exceptionType;
  741. bool is_ptr = ex_type->__is_pointer_p();
  742. if (is_ptr)
  743. {
  744. exception_ptr = *(void**)exception_ptr;
  745. }
  746. }
  747. // Always match a catchall, even with a foreign exception
  748. //
  749. // Note: A 0 here is a catchall, not a cleanup, so we return true to
  750. // indicate that we found a catch.
  751. if (0 == type)
  752. {
  753. if (ex)
  754. {
  755. adjustedPtr = exception_ptr;
  756. }
  757. return true;
  758. }
  759. if (0 == ex) { return false; }
  760. // If the types are the same, no casting is needed.
  761. if (*type == *ex_type)
  762. {
  763. adjustedPtr = exception_ptr;
  764. return true;
  765. }
  766. if (type->__do_catch(ex_type, &exception_ptr, 1))
  767. {
  768. adjustedPtr = exception_ptr;
  769. return true;
  770. }
  771. return false;
  772. }
  773. /**
  774. * Checks whether the exception matches the type specifiers in this action
  775. * record. If the exception only matches cleanups, then this returns false.
  776. * If it matches a catch (including a catchall) then it returns true.
  777. *
  778. * The selector argument is used to return the selector that is passed in the
  779. * second exception register when installing the context.
  780. */
  781. static handler_type check_action_record(_Unwind_Context *context,
  782. dwarf_eh_lsda *lsda,
  783. dw_eh_ptr_t action_record,
  784. __cxa_exception *ex,
  785. unsigned long *selector,
  786. void *&adjustedPtr)
  787. {
  788. if (!action_record) { return handler_cleanup; }
  789. handler_type found = handler_none;
  790. while (action_record)
  791. {
  792. int filter = read_sleb128(&action_record);
  793. dw_eh_ptr_t action_record_offset_base = action_record;
  794. int displacement = read_sleb128(&action_record);
  795. action_record = displacement ?
  796. action_record_offset_base + displacement : 0;
  797. // We only check handler types for C++ exceptions - foreign exceptions
  798. // are only allowed for cleanup.
  799. if (filter > 0 && 0 != ex)
  800. {
  801. std::type_info *handler_type = get_type_info_entry(context, lsda, filter);
  802. if (check_type_signature(ex, handler_type, adjustedPtr))
  803. {
  804. *selector = filter;
  805. return handler_catch;
  806. }
  807. }
  808. else if (filter < 0 && 0 != ex)
  809. {
  810. bool matched = false;
  811. if (found == handler_none) *selector = filter;
  812. #ifdef __arm__
  813. filter++;
  814. std::type_info *handler_type = get_type_info_entry(context, lsda, filter--);
  815. while (handler_type)
  816. {
  817. if (check_type_signature(ex, handler_type, adjustedPtr))
  818. {
  819. matched = true;
  820. break;
  821. }
  822. handler_type = get_type_info_entry(context, lsda, filter--);
  823. }
  824. #else
  825. unsigned char *type_index = ((unsigned char*)lsda->type_table - filter - 1);
  826. while (*type_index)
  827. {
  828. std::type_info *handler_type = get_type_info_entry(context, lsda, *(type_index++));
  829. // If the exception spec matches a permitted throw type for
  830. // this function, don't report a handler - we are allowed to
  831. // propagate this exception out.
  832. if (check_type_signature(ex, handler_type, adjustedPtr))
  833. {
  834. matched = true;
  835. break;
  836. }
  837. }
  838. #endif
  839. if (matched) { continue; }
  840. // If we don't find an allowed exception spec, we need to install
  841. // the context for this action. The landing pad will then call the
  842. // unexpected exception function. Treat this as a catch
  843. return handler_catch;
  844. }
  845. else if (filter == 0)
  846. {
  847. *selector = filter;
  848. found = handler_cleanup;
  849. }
  850. }
  851. return found;
  852. }
  853. static void pushCleanupException(_Unwind_Exception *exceptionObject,
  854. __cxa_exception *ex)
  855. {
  856. #ifdef __arm__
  857. __cxa_thread_info *info = thread_info_fast();
  858. if (ex)
  859. {
  860. ex->cleanupCount++;
  861. if (ex->cleanupCount > 1)
  862. {
  863. assert(exceptionObject == info->currentCleanup);
  864. return;
  865. }
  866. ex->nextCleanup = info->currentCleanup;
  867. }
  868. info->currentCleanup = exceptionObject;
  869. #endif
  870. }
  871. /**
  872. * The exception personality function. This is referenced in the unwinding
  873. * DWARF metadata and is called by the unwind library for each C++ stack frame
  874. * containing catch or cleanup code.
  875. */
  876. extern "C"
  877. BEGIN_PERSONALITY_FUNCTION(__gxx_personality_v0)
  878. // This personality function is for version 1 of the ABI. If you use it
  879. // with a future version of the ABI, it won't know what to do, so it
  880. // reports a fatal error and give up before it breaks anything.
  881. if (1 != version)
  882. {
  883. return _URC_FATAL_PHASE1_ERROR;
  884. }
  885. __cxa_exception *ex = 0;
  886. __cxa_exception *realEx = 0;
  887. // If this exception is throw by something else then we can't make any
  888. // assumptions about its layout beyond the fields declared in
  889. // _Unwind_Exception.
  890. bool foreignException = !isCXXException(exceptionClass);
  891. // If this isn't a foreign exception, then we have a C++ exception structure
  892. if (!foreignException)
  893. {
  894. ex = exceptionFromPointer(exceptionObject);
  895. realEx = realExceptionFromException(ex);
  896. }
  897. unsigned char *lsda_addr =
  898. (unsigned char*)_Unwind_GetLanguageSpecificData(context);
  899. // No LSDA implies no landing pads - try the next frame
  900. if (0 == lsda_addr) { return continueUnwinding(exceptionObject, context); }
  901. // These two variables define how the exception will be handled.
  902. dwarf_eh_action action = {0};
  903. unsigned long selector = 0;
  904. // During the search phase, we do a complete lookup. If we return
  905. // _URC_HANDLER_FOUND, then the phase 2 unwind will call this function with
  906. // a _UA_HANDLER_FRAME action, telling us to install the handler frame. If
  907. // we return _URC_CONTINUE_UNWIND, we may be called again later with a
  908. // _UA_CLEANUP_PHASE action for this frame.
  909. //
  910. // The point of the two-stage unwind allows us to entirely avoid any stack
  911. // unwinding if there is no handler. If there are just cleanups found,
  912. // then we can just panic call an abort function.
  913. //
  914. // Matching a handler is much more expensive than matching a cleanup,
  915. // because we don't need to bother doing type comparisons (or looking at
  916. // the type table at all) for a cleanup. This means that there is no need
  917. // to cache the result of finding a cleanup, because it's (quite) quick to
  918. // look it up again from the action table.
  919. if (actions & _UA_SEARCH_PHASE)
  920. {
  921. struct dwarf_eh_lsda lsda = parse_lsda(context, lsda_addr);
  922. if (!dwarf_eh_find_callsite(context, &lsda, &action))
  923. {
  924. // EH range not found. This happens if exception is thrown and not
  925. // caught inside a cleanup (destructor). We should call
  926. // terminate() in this case. The catchTemp (landing pad) field of
  927. // exception object will contain null when personality function is
  928. // called with _UA_HANDLER_FRAME action for phase 2 unwinding.
  929. return _URC_HANDLER_FOUND;
  930. }
  931. handler_type found_handler = check_action_record(context, &lsda,
  932. action.action_record, realEx, &selector, ex->adjustedPtr);
  933. // If there's no action record, we've only found a cleanup, so keep
  934. // searching for something real
  935. if (found_handler == handler_catch)
  936. {
  937. // Cache the results for the phase 2 unwind, if we found a handler
  938. // and this is not a foreign exception.
  939. if (ex)
  940. {
  941. saveLandingPad(context, exceptionObject, ex, selector, action.landing_pad);
  942. ex->languageSpecificData = (const char*)lsda_addr;
  943. ex->actionRecord = (const char*)action.action_record;
  944. // ex->adjustedPtr is set when finding the action record.
  945. }
  946. return _URC_HANDLER_FOUND;
  947. }
  948. return continueUnwinding(exceptionObject, context);
  949. }
  950. // If this is a foreign exception, we didn't have anywhere to cache the
  951. // lookup stuff, so we need to do it again. If this is either a forced
  952. // unwind, a foreign exception, or a cleanup, then we just install the
  953. // context for a cleanup.
  954. if (!(actions & _UA_HANDLER_FRAME))
  955. {
  956. // cleanup
  957. struct dwarf_eh_lsda lsda = parse_lsda(context, lsda_addr);
  958. dwarf_eh_find_callsite(context, &lsda, &action);
  959. if (0 == action.landing_pad) { return continueUnwinding(exceptionObject, context); }
  960. handler_type found_handler = check_action_record(context, &lsda,
  961. action.action_record, realEx, &selector, ex->adjustedPtr);
  962. // Ignore handlers this time.
  963. if (found_handler != handler_cleanup) { return continueUnwinding(exceptionObject, context); }
  964. pushCleanupException(exceptionObject, ex);
  965. }
  966. else if (foreignException)
  967. {
  968. struct dwarf_eh_lsda lsda = parse_lsda(context, lsda_addr);
  969. dwarf_eh_find_callsite(context, &lsda, &action);
  970. check_action_record(context, &lsda, action.action_record, realEx,
  971. &selector, ex->adjustedPtr);
  972. }
  973. else if (ex->catchTemp == 0)
  974. {
  975. // Uncaught exception in cleanup, calling terminate
  976. std::terminate();
  977. }
  978. else
  979. {
  980. // Restore the saved info if we saved some last time.
  981. loadLandingPad(context, exceptionObject, ex, &selector, &action.landing_pad);
  982. ex->catchTemp = 0;
  983. ex->handlerSwitchValue = 0;
  984. }
  985. _Unwind_SetIP(context, (unsigned long)action.landing_pad);
  986. _Unwind_SetGR(context, __builtin_eh_return_data_regno(0),
  987. (unsigned long)exceptionObject);
  988. _Unwind_SetGR(context, __builtin_eh_return_data_regno(1), selector);
  989. return _URC_INSTALL_CONTEXT;
  990. }
  991. /**
  992. * ABI function called when entering a catch statement. The argument is the
  993. * pointer passed out of the personality function. This is always the start of
  994. * the _Unwind_Exception object. The return value for this function is the
  995. * pointer to the caught exception, which is either the adjusted pointer (for
  996. * C++ exceptions) of the unadjusted pointer (for foreign exceptions).
  997. */
  998. #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4)
  999. extern "C" void *__cxa_begin_catch(void *e) throw()
  1000. #else
  1001. extern "C" void *__cxa_begin_catch(void *e)
  1002. #endif
  1003. {
  1004. // Decrement the uncaught exceptions count
  1005. __cxa_eh_globals *globals = __cxa_get_globals();
  1006. globals->uncaughtExceptions--;
  1007. _Unwind_Exception *exceptionObject = (_Unwind_Exception*)e;
  1008. if (isCXXException(exceptionObject->exception_class))
  1009. {
  1010. __cxa_exception *ex = exceptionFromPointer(exceptionObject);
  1011. if (ex->handlerCount == 0)
  1012. {
  1013. // Add this to the front of the list of exceptions being handled
  1014. // and increment its handler count so that it won't be deleted
  1015. // prematurely.
  1016. ex->nextException = globals->caughtExceptions;
  1017. globals->caughtExceptions = ex;
  1018. }
  1019. if (ex->handlerCount < 0)
  1020. {
  1021. // Rethrown exception is catched before end of catch block.
  1022. // Clear the rethrow flag (make value positive) - we are allowed
  1023. // to delete this exception at the end of the catch block, as long
  1024. // as it isn't thrown again later.
  1025. // Code pattern:
  1026. //
  1027. // try {
  1028. // throw x;
  1029. // }
  1030. // catch() {
  1031. // try {
  1032. // throw;
  1033. // }
  1034. // catch() {
  1035. // __cxa_begin_catch() <- we are here
  1036. // }
  1037. // }
  1038. ex->handlerCount = -ex->handlerCount + 1;
  1039. }
  1040. else
  1041. {
  1042. ex->handlerCount++;
  1043. }
  1044. return ex->adjustedPtr;
  1045. }
  1046. // exceptionObject is the pointer to the _Unwind_Exception within the
  1047. // __cxa_exception. The throw object is after this
  1048. return ((char*)exceptionObject + sizeof(_Unwind_Exception));
  1049. }
  1050. /**
  1051. * ABI function called when exiting a catch block. This will free the current
  1052. * exception if it is no longer referenced in other catch blocks.
  1053. */
  1054. extern "C" void __cxa_end_catch()
  1055. {
  1056. // We can call the fast version here because the slow version is called in
  1057. // __cxa_throw(), which must have been called before we end a catch block
  1058. __cxa_eh_globals *globals = __cxa_get_globals_fast();
  1059. __cxa_exception *ex = globals->caughtExceptions;
  1060. assert(0 != ex && "Ending catch when no exception is on the stack!");
  1061. bool deleteException = true;
  1062. if (ex->handlerCount < 0)
  1063. {
  1064. // exception was rethrown. Exception should not be deleted even if
  1065. // handlerCount become zero.
  1066. // Code pattern:
  1067. // try {
  1068. // throw x;
  1069. // }
  1070. // catch() {
  1071. // {
  1072. // throw;
  1073. // }
  1074. // cleanup {
  1075. // __cxa_end_catch(); <- we are here
  1076. // }
  1077. // }
  1078. //
  1079. ex->handlerCount++;
  1080. deleteException = false;
  1081. }
  1082. else
  1083. {
  1084. ex->handlerCount--;
  1085. }
  1086. if (ex->handlerCount == 0)
  1087. {
  1088. globals->caughtExceptions = ex->nextException;
  1089. if (deleteException)
  1090. {
  1091. releaseException(ex);
  1092. }
  1093. }
  1094. }
  1095. /**
  1096. * ABI function. Returns the type of the current exception.
  1097. */
  1098. extern "C" std::type_info *__cxa_current_exception_type()
  1099. {
  1100. __cxa_eh_globals *globals = __cxa_get_globals();
  1101. __cxa_exception *ex = globals->caughtExceptions;
  1102. return ex ? ex->exceptionType : 0;
  1103. }
  1104. /**
  1105. * ABI function, called when an exception specification is violated.
  1106. *
  1107. * This function does not return.
  1108. */
  1109. extern "C" void __cxa_call_unexpected(void*exception)
  1110. {
  1111. _Unwind_Exception *exceptionObject = (_Unwind_Exception*)exception;
  1112. if (exceptionObject->exception_class == exception_class)
  1113. {
  1114. __cxa_exception *ex = exceptionFromPointer(exceptionObject);
  1115. if (ex->unexpectedHandler)
  1116. {
  1117. ex->unexpectedHandler();
  1118. // Should not be reached.
  1119. abort();
  1120. }
  1121. }
  1122. std::unexpected();
  1123. // Should not be reached.
  1124. abort();
  1125. }
  1126. /**
  1127. * ABI function, returns the adjusted pointer to the exception object.
  1128. */
  1129. extern "C" void *__cxa_get_exception_ptr(void *exceptionObject)
  1130. {
  1131. return exceptionFromPointer(exceptionObject)->adjustedPtr;
  1132. }
  1133. /**
  1134. * As an extension, we provide the ability for the unexpected and terminate
  1135. * handlers to be thread-local. We default to the standards-compliant
  1136. * behaviour where they are global.
  1137. */
  1138. static bool thread_local_handlers = false;
  1139. namespace pathscale
  1140. {
  1141. /**
  1142. * Sets whether unexpected and terminate handlers should be thread-local.
  1143. */
  1144. void set_use_thread_local_handlers(bool flag) throw()
  1145. {
  1146. thread_local_handlers = flag;
  1147. }
  1148. /**
  1149. * Sets a thread-local unexpected handler.
  1150. */
  1151. unexpected_handler set_unexpected(unexpected_handler f) throw()
  1152. {
  1153. static __cxa_thread_info *info = thread_info();
  1154. unexpected_handler old = info->unexpectedHandler;
  1155. info->unexpectedHandler = f;
  1156. return old;
  1157. }
  1158. /**
  1159. * Sets a thread-local terminate handler.
  1160. */
  1161. terminate_handler set_terminate(terminate_handler f) throw()
  1162. {
  1163. static __cxa_thread_info *info = thread_info();
  1164. terminate_handler old = info->terminateHandler;
  1165. info->terminateHandler = f;
  1166. return old;
  1167. }
  1168. }
  1169. namespace std
  1170. {
  1171. /**
  1172. * Sets the function that will be called when an exception specification is
  1173. * violated.
  1174. */
  1175. unexpected_handler set_unexpected(unexpected_handler f) throw()
  1176. {
  1177. if (thread_local_handlers) { return pathscale::set_unexpected(f); }
  1178. return ATOMIC_SWAP(&unexpectedHandler, f);
  1179. }
  1180. /**
  1181. * Sets the function that is called to terminate the program.
  1182. */
  1183. terminate_handler set_terminate(terminate_handler f) throw()
  1184. {
  1185. if (thread_local_handlers) { return pathscale::set_terminate(f); }
  1186. return ATOMIC_SWAP(&terminateHandler, f);
  1187. }
  1188. /**
  1189. * Terminates the program, calling a custom terminate implementation if
  1190. * required.
  1191. */
  1192. void terminate()
  1193. {
  1194. // Note, if there is a HW exception raised in the `term_handler',
  1195. // the abort() function might possibly be bypassed.
  1196. //
  1197. // On the other hand, if we disable ECALL before calling into
  1198. // the `term_handler', then the user can do only one OCALL in
  1199. // the handler (and it will fail when ORET).
  1200. #define force_abort(term_handler) do { \
  1201. try { term_handler (); abort(); } \
  1202. catch (...) { abort(); } \
  1203. } while (0)
  1204. static __cxa_thread_info *info = thread_info_fast();
  1205. if (0 != info && 0 != info->terminateHandler)
  1206. {
  1207. force_abort(info->terminateHandler);
  1208. // Should not be reached - a terminate handler is not expected to
  1209. // return.
  1210. }
  1211. force_abort(terminateHandler);
  1212. #undef force_abort
  1213. }
  1214. /**
  1215. * Called when an unexpected exception is encountered (i.e. an exception
  1216. * violates an exception specification). This calls abort() unless a
  1217. * custom handler has been set..
  1218. */
  1219. void unexpected()
  1220. {
  1221. static __cxa_thread_info *info = thread_info_fast();
  1222. if (0 != info && 0 != info->unexpectedHandler)
  1223. {
  1224. info->unexpectedHandler();
  1225. // Should not be reached - a terminate handler is not expected to
  1226. // return.
  1227. abort();
  1228. }
  1229. unexpectedHandler();
  1230. }
  1231. /**
  1232. * Returns whether there are any exceptions currently being thrown that
  1233. * have not been caught. This can occur inside a nested catch statement.
  1234. */
  1235. bool uncaught_exception() throw()
  1236. {
  1237. __cxa_thread_info *info = thread_info();
  1238. return info->globals.uncaughtExceptions != 0;
  1239. }
  1240. /**
  1241. * Returns the current unexpected handler.
  1242. */
  1243. unexpected_handler get_unexpected() throw()
  1244. {
  1245. __cxa_thread_info *info = thread_info();
  1246. if (info->unexpectedHandler)
  1247. {
  1248. return info->unexpectedHandler;
  1249. }
  1250. return ATOMIC_LOAD(&unexpectedHandler);
  1251. }
  1252. /**
  1253. * Returns the current terminate handler.
  1254. */
  1255. terminate_handler get_terminate() throw()
  1256. {
  1257. __cxa_thread_info *info = thread_info();
  1258. if (info->terminateHandler)
  1259. {
  1260. return info->terminateHandler;
  1261. }
  1262. return ATOMIC_LOAD(&terminateHandler);
  1263. }
  1264. }
  1265. #ifdef __arm__
  1266. extern "C" _Unwind_Exception *__cxa_get_cleanup(void)
  1267. {
  1268. __cxa_thread_info *info = thread_info_fast();
  1269. _Unwind_Exception *exceptionObject = info->currentCleanup;
  1270. if (isCXXException(exceptionObject->exception_class))
  1271. {
  1272. __cxa_exception *ex = exceptionFromPointer(exceptionObject);
  1273. ex->cleanupCount--;
  1274. if (ex->cleanupCount == 0)
  1275. {
  1276. info->currentCleanup = ex->nextCleanup;
  1277. ex->nextCleanup = 0;
  1278. }
  1279. }
  1280. else
  1281. {
  1282. info->currentCleanup = 0;
  1283. }
  1284. return exceptionObject;
  1285. }
  1286. asm (
  1287. ".pushsection .text.__cxa_end_cleanup \n"
  1288. ".global __cxa_end_cleanup \n"
  1289. ".type __cxa_end_cleanup, \"function\" \n"
  1290. "__cxa_end_cleanup: \n"
  1291. " push {r1, r2, r3, r4} \n"
  1292. " bl __cxa_get_cleanup \n"
  1293. " push {r1, r2, r3, r4} \n"
  1294. " b _Unwind_Resume \n"
  1295. " bl abort \n"
  1296. ".popsection \n"
  1297. );
  1298. #endif