exception.cc 52 KB

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