exception.cc 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747
  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, called when an object destructor exits due to an
  1407. * exception during stack unwinding.
  1408. *
  1409. * This function does not return.
  1410. */
  1411. extern "C" void __cxa_call_terminate(void*exception) _LIBCXXRT_NOEXCEPT
  1412. {
  1413. std::terminate();
  1414. // Should not be reached.
  1415. abort();
  1416. }
  1417. /**
  1418. * ABI function, returns the adjusted pointer to the exception object.
  1419. */
  1420. extern "C" void *__cxa_get_exception_ptr(void *exceptionObject)
  1421. {
  1422. return exceptionFromPointer(exceptionObject)->adjustedPtr;
  1423. }
  1424. /**
  1425. * As an extension, we provide the ability for the unexpected and terminate
  1426. * handlers to be thread-local. We default to the standards-compliant
  1427. * behaviour where they are global.
  1428. */
  1429. static bool thread_local_handlers = false;
  1430. namespace pathscale
  1431. {
  1432. /**
  1433. * Sets whether unexpected and terminate handlers should be thread-local.
  1434. */
  1435. void set_use_thread_local_handlers(bool flag) _LIBCXXRT_NOEXCEPT
  1436. {
  1437. thread_local_handlers = flag;
  1438. }
  1439. /**
  1440. * Sets a thread-local unexpected handler.
  1441. */
  1442. unexpected_handler set_unexpected(unexpected_handler f) _LIBCXXRT_NOEXCEPT
  1443. {
  1444. static __cxa_thread_info *info = thread_info();
  1445. unexpected_handler old = info->unexpectedHandler;
  1446. info->unexpectedHandler = f;
  1447. return old;
  1448. }
  1449. /**
  1450. * Sets a thread-local terminate handler.
  1451. */
  1452. terminate_handler set_terminate(terminate_handler f) _LIBCXXRT_NOEXCEPT
  1453. {
  1454. static __cxa_thread_info *info = thread_info();
  1455. terminate_handler old = info->terminateHandler;
  1456. info->terminateHandler = f;
  1457. return old;
  1458. }
  1459. }
  1460. namespace std
  1461. {
  1462. /**
  1463. * Sets the function that will be called when an exception specification is
  1464. * violated.
  1465. */
  1466. unexpected_handler set_unexpected(unexpected_handler f) _LIBCXXRT_NOEXCEPT
  1467. {
  1468. if (thread_local_handlers) { return pathscale::set_unexpected(f); }
  1469. return unexpectedHandler.exchange(f);
  1470. }
  1471. /**
  1472. * Sets the function that is called to terminate the program.
  1473. */
  1474. terminate_handler set_terminate(terminate_handler f) _LIBCXXRT_NOEXCEPT
  1475. {
  1476. if (thread_local_handlers) { return pathscale::set_terminate(f); }
  1477. return terminateHandler.exchange(f);
  1478. }
  1479. /**
  1480. * Terminates the program, calling a custom terminate implementation if
  1481. * required.
  1482. */
  1483. void terminate() _LIBCXXRT_NOEXCEPT
  1484. {
  1485. static __cxa_thread_info *info = thread_info();
  1486. if (0 != info && 0 != info->terminateHandler)
  1487. {
  1488. info->terminateHandler();
  1489. // Should not be reached - a terminate handler is not expected to
  1490. // return.
  1491. abort();
  1492. }
  1493. terminateHandler.load()();
  1494. }
  1495. /**
  1496. * Called when an unexpected exception is encountered (i.e. an exception
  1497. * violates an exception specification). This calls abort() unless a
  1498. * custom handler has been set..
  1499. */
  1500. void unexpected()
  1501. {
  1502. static __cxa_thread_info *info = thread_info();
  1503. if (0 != info && 0 != info->unexpectedHandler)
  1504. {
  1505. info->unexpectedHandler();
  1506. // Should not be reached - a terminate handler is not expected to
  1507. // return.
  1508. abort();
  1509. }
  1510. unexpectedHandler.load()();
  1511. }
  1512. /**
  1513. * Returns whether there are any exceptions currently being thrown that
  1514. * have not been caught. This can occur inside a nested catch statement.
  1515. */
  1516. bool uncaught_exception() _LIBCXXRT_NOEXCEPT
  1517. {
  1518. __cxa_thread_info *info = thread_info();
  1519. return info->globals.uncaughtExceptions != 0;
  1520. }
  1521. /**
  1522. * Returns the number of exceptions currently being thrown that have not
  1523. * been caught. This can occur inside a nested catch statement.
  1524. */
  1525. int uncaught_exceptions() _LIBCXXRT_NOEXCEPT
  1526. {
  1527. __cxa_thread_info *info = thread_info();
  1528. return info->globals.uncaughtExceptions;
  1529. }
  1530. /**
  1531. * Returns the current unexpected handler.
  1532. */
  1533. unexpected_handler get_unexpected() _LIBCXXRT_NOEXCEPT
  1534. {
  1535. __cxa_thread_info *info = thread_info();
  1536. if (info->unexpectedHandler)
  1537. {
  1538. return info->unexpectedHandler;
  1539. }
  1540. return unexpectedHandler.load();
  1541. }
  1542. /**
  1543. * Returns the current terminate handler.
  1544. */
  1545. terminate_handler get_terminate() _LIBCXXRT_NOEXCEPT
  1546. {
  1547. __cxa_thread_info *info = thread_info();
  1548. if (info->terminateHandler)
  1549. {
  1550. return info->terminateHandler;
  1551. }
  1552. return terminateHandler.load();
  1553. }
  1554. }
  1555. #if defined(__arm__) && !defined(__ARM_DWARF_EH__)
  1556. extern "C" _Unwind_Exception *__cxa_get_cleanup(void)
  1557. {
  1558. __cxa_thread_info *info = thread_info_fast();
  1559. _Unwind_Exception *exceptionObject = info->currentCleanup;
  1560. if (isCXXException(exceptionObject->exception_class))
  1561. {
  1562. __cxa_exception *ex = exceptionFromPointer(exceptionObject);
  1563. ex->cleanupCount--;
  1564. if (ex->cleanupCount == 0)
  1565. {
  1566. info->currentCleanup = ex->nextCleanup;
  1567. ex->nextCleanup = 0;
  1568. }
  1569. }
  1570. else
  1571. {
  1572. info->currentCleanup = 0;
  1573. }
  1574. return exceptionObject;
  1575. }
  1576. asm (
  1577. ".pushsection .text.__cxa_end_cleanup \n"
  1578. ".global __cxa_end_cleanup \n"
  1579. ".type __cxa_end_cleanup, \"function\" \n"
  1580. "__cxa_end_cleanup: \n"
  1581. " push {r1, r2, r3, r4} \n"
  1582. " mov r4, lr \n"
  1583. " bl __cxa_get_cleanup \n"
  1584. " mov lr, r4 \n"
  1585. " pop {r1, r2, r3, r4} \n"
  1586. " b _Unwind_Resume \n"
  1587. " bl abort \n"
  1588. ".popsection \n"
  1589. );
  1590. #endif