exception.cc 53 KB

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