2 * Copyright (c) 2002-2007 Apple Inc. All rights reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
21 * @APPLE_LICENSE_HEADER_END@
26 /***********************************************************************
27 * 32-bit implementation
28 **********************************************************************/
30 #include "objc-private.h"
35 #include "objc-exception.h"
37 static objc_exception_functions_t xtab;
39 // forward declaration
40 static void set_default_handlers();
47 // get table; version tells how many
48 void objc_exception_get_functions(objc_exception_functions_t *table) {
49 // only version 0 supported at this point
50 if (table && table->version == 0)
55 void objc_exception_set_functions(objc_exception_functions_t *table) {
56 // only version 0 supported at this point
57 if (table && table->version == 0)
62 * The following functions are
63 * synthesized by the compiler upon encountering language constructs
66 void objc_exception_throw(id exception) {
67 if (!xtab.throw_exc) {
68 set_default_handlers();
71 if (PrintExceptionThrow) {
72 _objc_inform("EXCEPTIONS: throwing %p (%s)",
73 (void*)exception, object_getClassName(exception));
75 int frameCount = backtrace(callstack, 500);
76 backtrace_symbols_fd(callstack, frameCount, fileno(stderr));
79 OBJC_RUNTIME_OBJC_EXCEPTION_THROW(exception); // dtrace probe to log throw activity.
80 xtab.throw_exc(exception);
81 _objc_fatal("objc_exception_throw failed");
84 void objc_exception_try_enter(void *localExceptionData) {
85 if (!xtab.throw_exc) {
86 set_default_handlers();
88 xtab.try_enter(localExceptionData);
92 void objc_exception_try_exit(void *localExceptionData) {
93 if (!xtab.throw_exc) {
94 set_default_handlers();
96 xtab.try_exit(localExceptionData);
100 id objc_exception_extract(void *localExceptionData) {
101 if (!xtab.throw_exc) {
102 set_default_handlers();
104 return xtab.extract(localExceptionData);
108 int objc_exception_match(Class exceptionClass, id exception) {
109 if (!xtab.throw_exc) {
110 set_default_handlers();
112 return xtab.match(exceptionClass, exception);
116 // quick and dirty exception handling code
117 // default implementation - mostly a toy for use outside/before Foundation
118 // provides its implementation
119 // Perhaps the default implementation should just complain loudly and quit
122 extern void _objc_inform(const char *fmt, ...);
124 typedef struct { jmp_buf buf; void *pointers[4]; } LocalData_t;
126 typedef struct _threadChain {
127 LocalData_t *topHandler;
128 objc_thread_t perThreadID;
129 struct _threadChain *next;
133 static ThreadChainLink_t ThreadChainLink;
135 static ThreadChainLink_t *getChainLink() {
136 // follow links until thread_self() found (someday) XXX
137 objc_thread_t self = thread_self();
138 ThreadChainLink_t *walker = &ThreadChainLink;
139 while (walker->perThreadID != self) {
140 if (walker->next != nil) {
141 walker = walker->next;
145 // XXX not thread safe (!)
146 // XXX Also, we don't register to deallocate on thread death
147 walker->next = (ThreadChainLink_t *)malloc(sizeof(ThreadChainLink_t));
148 walker = walker->next;
150 walker->topHandler = nil;
151 walker->perThreadID = self;
156 static void default_try_enter(void *localExceptionData) {
157 LocalData_t *data = (LocalData_t *)localExceptionData;
158 ThreadChainLink_t *chainLink = getChainLink();
159 data->pointers[1] = chainLink->topHandler;
160 chainLink->topHandler = data;
161 if (PrintExceptions) _objc_inform("EXCEPTIONS: entered try block %p\n", chainLink->topHandler);
164 static void default_throw(id value) {
165 ThreadChainLink_t *chainLink = getChainLink();
168 if (PrintExceptions) _objc_inform("EXCEPTIONS: objc_exception_throw with nil value\n");
171 if (chainLink == nil) {
172 if (PrintExceptions) _objc_inform("EXCEPTIONS: No handler in place!\n");
175 if (PrintExceptions) _objc_inform("EXCEPTIONS: exception thrown, going to handler block %p\n", chainLink->topHandler);
176 led = chainLink->topHandler;
177 chainLink->topHandler = (LocalData_t *)
178 led->pointers[1]; // pop top handler
179 led->pointers[0] = value; // store exception that is thrown
181 longjmp(led->buf, 1);
183 _longjmp(led->buf, 1);
187 static void default_try_exit(void *led) {
188 ThreadChainLink_t *chainLink = getChainLink();
189 if (!chainLink || led != chainLink->topHandler) {
190 if (PrintExceptions) _objc_inform("EXCEPTIONS: *** mismatched try block exit handlers\n");
193 if (PrintExceptions) _objc_inform("EXCEPTIONS: removing try block handler %p\n", chainLink->topHandler);
194 chainLink->topHandler = (LocalData_t *)
195 chainLink->topHandler->pointers[1]; // pop top handler
198 static id default_extract(void *localExceptionData) {
199 LocalData_t *led = (LocalData_t *)localExceptionData;
200 return (id)led->pointers[0];
203 static int default_match(Class exceptionClass, id exception) {
204 //return [exception isKindOfClass:exceptionClass];
206 for (cls = exception->getIsa(); nil != cls; cls = cls->superclass)
207 if (cls == exceptionClass) return 1;
211 static void set_default_handlers() {
212 objc_exception_functions_t default_functions = {
213 0, default_throw, default_try_enter, default_try_exit, default_extract, default_match };
215 // should this always print?
216 if (PrintExceptions) _objc_inform("EXCEPTIONS: *** Setting default (non-Foundation) exception mechanism\n");
217 objc_exception_set_functions(&default_functions);
221 void exception_init(void)
226 void _destroyAltHandlerList(struct alt_handler_list *list)
236 /***********************************************************************
237 * 64-bit implementation.
238 **********************************************************************/
240 #include "objc-private.h"
241 #include <objc/objc-exception.h>
242 #include <objc/NSObject.h>
243 #include <execinfo.h>
245 // unwind library types and functions
246 // Mostly adapted from Itanium C++ ABI: Exception Handling
247 // http://www.codesourcery.com/cxx-abi/abi-eh.html
249 struct _Unwind_Exception;
250 struct _Unwind_Context;
252 typedef int _Unwind_Action;
253 enum : _Unwind_Action {
254 _UA_SEARCH_PHASE = 1,
255 _UA_CLEANUP_PHASE = 2,
256 _UA_HANDLER_FRAME = 4,
260 typedef int _Unwind_Reason_Code;
261 enum : _Unwind_Reason_Code {
263 _URC_FOREIGN_EXCEPTION_CAUGHT = 1,
264 _URC_FATAL_PHASE2_ERROR = 2,
265 _URC_FATAL_PHASE1_ERROR = 3,
266 _URC_NORMAL_STOP = 4,
267 _URC_END_OF_STACK = 5,
268 _URC_HANDLER_FOUND = 6,
269 _URC_INSTALL_CONTEXT = 7,
270 _URC_CONTINUE_UNWIND = 8
273 struct dwarf_eh_bases
280 OBJC_EXTERN uintptr_t _Unwind_GetIP (struct _Unwind_Context *);
281 OBJC_EXTERN uintptr_t _Unwind_GetCFA (struct _Unwind_Context *);
282 OBJC_EXTERN uintptr_t _Unwind_GetLanguageSpecificData(struct _Unwind_Context *);
285 // C++ runtime types and functions
286 // copied from cxxabi.h
288 OBJC_EXTERN void *__cxa_allocate_exception(size_t thrown_size);
289 OBJC_EXTERN void __cxa_throw(void *exc, void *typeinfo, void (*destructor)(void *)) __attribute__((noreturn));
290 OBJC_EXTERN void *__cxa_begin_catch(void *exc);
291 OBJC_EXTERN void __cxa_end_catch(void);
292 OBJC_EXTERN void __cxa_rethrow(void);
293 OBJC_EXTERN void *__cxa_current_exception_type(void);
295 #if SUPPORT_ZEROCOST_EXCEPTIONS
296 # define CXX_PERSONALITY __gxx_personality_v0
298 # define CXX_PERSONALITY __gxx_personality_sj0
301 OBJC_EXTERN _Unwind_Reason_Code
302 CXX_PERSONALITY(int version,
303 _Unwind_Action actions,
304 uint64_t exceptionClass,
305 struct _Unwind_Exception *exceptionObject,
306 struct _Unwind_Context *context);
309 // objc's internal exception types and data
311 struct objc_typeinfo {
312 // Position of vtable and name fields must match C++ typeinfo object
313 const void **vtable; // always objc_ehtype_vtable+2
314 const char *name; // c++ typeinfo string
316 Class cls_unremapped;
319 struct objc_exception {
321 struct objc_typeinfo tinfo;
325 static void _objc_exception_noop(void) { }
326 static bool _objc_exception_false(void) { return 0; }
327 // static bool _objc_exception_true(void) { return 1; }
328 static void _objc_exception_abort1(void) {
329 _objc_fatal("unexpected call into objc exception typeinfo vtable %d", 1);
331 static void _objc_exception_abort2(void) {
332 _objc_fatal("unexpected call into objc exception typeinfo vtable %d", 2);
334 static void _objc_exception_abort3(void) {
335 _objc_fatal("unexpected call into objc exception typeinfo vtable %d", 3);
337 static void _objc_exception_abort4(void) {
338 _objc_fatal("unexpected call into objc exception typeinfo vtable %d", 4);
341 static bool _objc_exception_do_catch(struct objc_typeinfo *catch_tinfo,
342 struct objc_typeinfo *throw_tinfo,
346 // forward declaration
347 OBJC_EXPORT struct objc_typeinfo OBJC_EHTYPE_id;
350 const void *objc_ehtype_vtable[] = {
351 nil, // typeinfo's vtable? - fixme
352 (void*)&OBJC_EHTYPE_id, // typeinfo's typeinfo - hack
353 (void*)_objc_exception_noop, // in-place destructor?
354 (void*)_objc_exception_noop, // destructor?
355 (void*)_objc_exception_false, // OLD __is_pointer_p
356 (void*)_objc_exception_false, // OLD __is_function_p
357 (void*)_objc_exception_do_catch, // OLD __do_catch, NEW can_catch
358 (void*)_objc_exception_false, // OLD __do_upcast, NEW search_above_dst
359 (void*)_objc_exception_false, // NEW search_below_dst
360 (void*)_objc_exception_abort1, // paranoia: blow up if libc++abi
361 (void*)_objc_exception_abort2, // adds something new
362 (void*)_objc_exception_abort3,
363 (void*)_objc_exception_abort4,
367 struct objc_typeinfo OBJC_EHTYPE_id = {
368 objc_ehtype_vtable+2,
375 /***********************************************************************
376 * Foundation customization
377 **********************************************************************/
379 /***********************************************************************
380 * _objc_default_exception_preprocessor
381 * Default exception preprocessor. Expected to be overridden by Foundation.
382 **********************************************************************/
383 static id _objc_default_exception_preprocessor(id exception)
387 static objc_exception_preprocessor exception_preprocessor = _objc_default_exception_preprocessor;
390 /***********************************************************************
391 * _objc_default_exception_matcher
392 * Default exception matcher. Expected to be overridden by Foundation.
393 **********************************************************************/
394 static int _objc_default_exception_matcher(Class catch_cls, id exception)
397 for (cls = exception->getIsa();
399 cls = cls->superclass)
401 if (cls == catch_cls) return 1;
406 static objc_exception_matcher exception_matcher = _objc_default_exception_matcher;
409 /***********************************************************************
410 * _objc_default_uncaught_exception_handler
411 * Default uncaught exception handler. Expected to be overridden by Foundation.
412 **********************************************************************/
413 static void _objc_default_uncaught_exception_handler(id exception)
416 static objc_uncaught_exception_handler uncaught_handler = _objc_default_uncaught_exception_handler;
419 /***********************************************************************
420 * objc_setExceptionPreprocessor
421 * Set a handler for preprocessing Objective-C exceptions.
422 * Returns the previous handler.
423 **********************************************************************/
424 objc_exception_preprocessor
425 objc_setExceptionPreprocessor(objc_exception_preprocessor fn)
427 objc_exception_preprocessor result = exception_preprocessor;
428 exception_preprocessor = fn;
433 /***********************************************************************
434 * objc_setExceptionMatcher
435 * Set a handler for matching Objective-C exceptions.
436 * Returns the previous handler.
437 **********************************************************************/
438 objc_exception_matcher
439 objc_setExceptionMatcher(objc_exception_matcher fn)
441 objc_exception_matcher result = exception_matcher;
442 exception_matcher = fn;
447 /***********************************************************************
448 * objc_setUncaughtExceptionHandler
449 * Set a handler for uncaught Objective-C exceptions.
450 * Returns the previous handler.
451 **********************************************************************/
452 objc_uncaught_exception_handler
453 objc_setUncaughtExceptionHandler(objc_uncaught_exception_handler fn)
455 objc_uncaught_exception_handler result = uncaught_handler;
456 uncaught_handler = fn;
461 /***********************************************************************
462 * Exception personality
463 **********************************************************************/
465 static void call_alt_handlers(struct _Unwind_Context *ctx);
468 __objc_personality_v0(int version,
469 _Unwind_Action actions,
470 uint64_t exceptionClass,
471 struct _Unwind_Exception *exceptionObject,
472 struct _Unwind_Context *context)
474 bool unwinding = ((actions & _UA_CLEANUP_PHASE) ||
475 (actions & _UA_FORCE_UNWIND));
477 if (PrintExceptions) {
478 _objc_inform("EXCEPTIONS: %s through frame [ip=%p sp=%p] "
480 unwinding ? "unwinding" : "searching",
481 (void*)(_Unwind_GetIP(context)-1),
482 (void*)_Unwind_GetCFA(context), exceptionObject);
485 // If we're executing the unwind, call this frame's alt handlers, if any.
487 call_alt_handlers(context);
490 // Let C++ handle the unwind itself.
491 return CXX_PERSONALITY(version, actions, exceptionClass,
492 exceptionObject, context);
496 /***********************************************************************
498 **********************************************************************/
500 static void _objc_exception_destructor(void *exc_gen)
502 // Release the retain from objc_exception_throw().
504 struct objc_exception *exc = (struct objc_exception *)exc_gen;
507 if (PrintExceptions) {
508 _objc_inform("EXCEPTIONS: releasing completed exception %p (object %p, a %s)",
509 exc, obj, object_getClassName(obj));
516 void objc_exception_throw(id obj)
518 struct objc_exception *exc = (struct objc_exception *)
519 __cxa_allocate_exception(sizeof(struct objc_exception));
521 obj = (*exception_preprocessor)(obj);
523 // Retain the exception object during unwinding
524 // because otherwise an autorelease pool pop can cause a crash
528 exc->tinfo.vtable = objc_ehtype_vtable+2;
529 exc->tinfo.name = object_getClassName(obj);
530 exc->tinfo.cls_unremapped = obj ? obj->getIsa() : Nil;
532 if (PrintExceptions) {
533 _objc_inform("EXCEPTIONS: throwing %p (object %p, a %s)",
534 exc, (void*)obj, object_getClassName(obj));
537 if (PrintExceptionThrow) {
538 if (!PrintExceptions)
539 _objc_inform("EXCEPTIONS: throwing %p (object %p, a %s)",
540 exc, (void*)obj, object_getClassName(obj));
541 void* callstack[500];
542 int frameCount = backtrace(callstack, 500);
543 backtrace_symbols_fd(callstack, frameCount, fileno(stderr));
546 OBJC_RUNTIME_OBJC_EXCEPTION_THROW(obj); // dtrace probe to log throw activity
547 __cxa_throw(exc, &exc->tinfo, &_objc_exception_destructor);
552 void objc_exception_rethrow(void)
554 // exception_preprocessor doesn't get another bite of the apple
555 if (PrintExceptions) {
556 _objc_inform("EXCEPTIONS: rethrowing current exception");
559 OBJC_RUNTIME_OBJC_EXCEPTION_RETHROW(); // dtrace probe to log throw activity.
565 id objc_begin_catch(void *exc_gen)
567 if (PrintExceptions) {
568 _objc_inform("EXCEPTIONS: handling exception %p at %p",
569 exc_gen, __builtin_return_address(0));
571 // NOT actually an id in the catch(...) case!
572 return (id)__cxa_begin_catch(exc_gen);
576 void objc_end_catch(void)
578 if (PrintExceptions) {
579 _objc_inform("EXCEPTIONS: finishing handler");
585 // `outer` is not passed by the new libcxxabi
586 static bool _objc_exception_do_catch(struct objc_typeinfo *catch_tinfo,
587 struct objc_typeinfo *throw_tinfo,
589 unsigned outer UNAVAILABLE_ATTRIBUTE)
593 if (throw_tinfo->vtable != objc_ehtype_vtable+2) {
594 // Only objc types can be caught here.
595 if (PrintExceptions) _objc_inform("EXCEPTIONS: skipping catch(?)");
599 // Adjust exception pointer.
600 // Old libcppabi: we lied about __is_pointer_p() so we have to do it here
601 // New libcxxabi: we have to do it here regardless
602 *throw_obj_p = **(void***)throw_obj_p;
604 // `catch (id)` always catches objc types.
605 if (catch_tinfo == &OBJC_EHTYPE_id) {
606 if (PrintExceptions) _objc_inform("EXCEPTIONS: catch(id)");
610 exception = *(id *)throw_obj_p;
612 Class handler_cls = _class_remap(catch_tinfo->cls_unremapped);
614 // catch handler's class is weak-linked and missing. Not a match.
616 else if ((*exception_matcher)(handler_cls, exception)) {
617 if (PrintExceptions) _objc_inform("EXCEPTIONS: catch(%s)",
618 handler_cls->nameForLogging());
622 if (PrintExceptions) _objc_inform("EXCEPTIONS: skipping catch(%s)",
623 handler_cls->nameForLogging());
629 /***********************************************************************
631 * Custom std::terminate handler.
633 * The uncaught exception callback is implemented as a std::terminate handler.
634 * 1. Check if there's an active exception
635 * 2. If so, check if it's an Objective-C exception
636 * 3. If so, call our registered callback with the object.
637 * 4. Finally, call the previous terminate handler.
638 **********************************************************************/
639 static void (*old_terminate)(void) = nil;
640 static void _objc_terminate(void)
642 if (PrintExceptions) {
643 _objc_inform("EXCEPTIONS: terminating");
646 if (! __cxa_current_exception_type()) {
647 // No current exception.
651 // There is a current exception. Check if it's an objc exception.
655 // It's an objc object. Call Foundation's handler, if any.
656 (*uncaught_handler)((id)e);
659 // It's not an objc object. Continue to C++ terminate.
666 /***********************************************************************
668 * Calls std::terminate for clients who don't link to C++ themselves.
669 * Called by the compiler if an exception is thrown
670 * from a context where exceptions may not be thrown.
671 **********************************************************************/
672 void objc_terminate(void)
678 /***********************************************************************
679 * alt handler support - zerocost implementation only
680 **********************************************************************/
682 #if !SUPPORT_ALT_HANDLERS
684 void _destroyAltHandlerList(struct alt_handler_list *list)
688 static void call_alt_handlers(struct _Unwind_Context *ctx)
690 // unsupported in sjlj environments
695 #include <libunwind.h>
696 #include <execinfo.h>
697 #include <dispatch/dispatch.h>
699 // Dwarf eh data encodings
700 #define DW_EH_PE_omit 0xff // no data follows
702 #define DW_EH_PE_absptr 0x00
703 #define DW_EH_PE_uleb128 0x01
704 #define DW_EH_PE_udata2 0x02
705 #define DW_EH_PE_udata4 0x03
706 #define DW_EH_PE_udata8 0x04
707 #define DW_EH_PE_sleb128 0x09
708 #define DW_EH_PE_sdata2 0x0A
709 #define DW_EH_PE_sdata4 0x0B
710 #define DW_EH_PE_sdata8 0x0C
712 #define DW_EH_PE_pcrel 0x10
713 #define DW_EH_PE_textrel 0x20
714 #define DW_EH_PE_datarel 0x30
715 #define DW_EH_PE_funcrel 0x40
716 #define DW_EH_PE_aligned 0x50 // fixme
718 #define DW_EH_PE_indirect 0x80 // gcc extension
721 /***********************************************************************
723 * Read a LEB-encoded unsigned integer from the address stored in *pp.
724 * Increments *pp past the bytes read.
725 * Adapted from DWARF Debugging Information Format 1.1, appendix 4
726 **********************************************************************/
727 static uintptr_t read_uleb(uintptr_t *pp)
729 uintptr_t result = 0;
733 byte = *(const unsigned char *)(*pp)++;
734 result |= (byte & 0x7f) << shift;
736 } while (byte & 0x80);
741 /***********************************************************************
743 * Read a LEB-encoded signed integer from the address stored in *pp.
744 * Increments *pp past the bytes read.
745 * Adapted from DWARF Debugging Information Format 1.1, appendix 4
746 **********************************************************************/
747 static intptr_t read_sleb(uintptr_t *pp)
749 uintptr_t result = 0;
753 byte = *(const unsigned char *)(*pp)++;
754 result |= (byte & 0x7f) << shift;
756 } while (byte & 0x80);
757 if ((shift < 8*sizeof(intptr_t)) && (byte & 0x40)) {
758 result |= ((intptr_t)-1) << shift;
764 /***********************************************************************
766 * Reads an encoded address from the address stored in *pp.
767 * Increments *pp past the bytes read.
768 * The data is interpreted according to the given dwarf encoding
769 * and base addresses.
770 **********************************************************************/
771 static uintptr_t read_address(uintptr_t *pp,
772 const struct dwarf_eh_bases *bases,
773 unsigned char encoding)
775 uintptr_t result = 0;
776 uintptr_t oldp = *pp;
778 // fixme need DW_EH_PE_aligned?
781 result = *(type *)(*pp); \
784 if (encoding == DW_EH_PE_omit) return 0;
786 switch (encoding & 0x0f) {
787 case DW_EH_PE_absptr:
790 case DW_EH_PE_uleb128:
791 result = read_uleb(pp);
793 case DW_EH_PE_udata2:
796 case DW_EH_PE_udata4:
800 case DW_EH_PE_udata8:
804 case DW_EH_PE_sleb128:
805 result = read_sleb(pp);
807 case DW_EH_PE_sdata2:
810 case DW_EH_PE_sdata4:
814 case DW_EH_PE_sdata8:
819 _objc_inform("unknown DWARF EH encoding 0x%x at %p",
820 encoding, (void *)*pp);
827 switch (encoding & 0x70) {
830 result += (uintptr_t)oldp;
832 case DW_EH_PE_textrel:
833 result += bases->tbase;
835 case DW_EH_PE_datarel:
836 result += bases->dbase;
838 case DW_EH_PE_funcrel:
839 result += bases->func;
841 case DW_EH_PE_aligned:
842 _objc_inform("unknown DWARF EH encoding 0x%x at %p",
843 encoding, (void *)*pp);
850 if (encoding & DW_EH_PE_indirect) {
851 result = *(uintptr_t *)result;
855 return (uintptr_t)result;
867 // precise ranges within ip_start..ip_end; nil or {0,0} terminated
872 static bool isObjCExceptionCatcher(uintptr_t lsda, uintptr_t ip,
873 const struct dwarf_eh_bases* bases,
874 struct frame_range *frame)
876 unsigned char LPStart_enc = *(const unsigned char *)lsda++;
878 if (LPStart_enc != DW_EH_PE_omit) {
879 read_address(&lsda, bases, LPStart_enc); // LPStart
882 unsigned char TType_enc = *(const unsigned char *)lsda++;
883 if (TType_enc != DW_EH_PE_omit) {
884 read_uleb(&lsda); // TType
887 unsigned char call_site_enc = *(const unsigned char *)lsda++;
888 uintptr_t length = read_uleb(&lsda);
889 uintptr_t call_site_table = lsda;
890 uintptr_t call_site_table_end = call_site_table + length;
891 uintptr_t action_record_table = call_site_table_end;
893 uintptr_t action_record = 0;
894 uintptr_t p = call_site_table;
898 uintptr_t try_landing_pad;
900 while (p < call_site_table_end) {
901 uintptr_t start = read_address(&p, bases, call_site_enc)+bases->func;
902 uintptr_t len = read_address(&p, bases, call_site_enc);
903 uintptr_t pad = read_address(&p, bases, call_site_enc);
904 uintptr_t action = read_uleb(&p);
907 // no more source ranges
910 else if (ip < start + len) {
912 if (!pad) return false; // ...but it has no landing pad
913 // found the landing pad
914 action_record = action ? action_record_table + action - 1 : 0;
916 try_end = start + len;
917 try_landing_pad = pad;
922 if (!action_record) return false; // no catch handlers
924 // has handlers, destructors, and/or throws specifications
925 // Use this frame if it has any handlers
926 bool has_handler = false;
930 intptr_t filter = read_sleb(&p);
932 offset = read_sleb(&temp);
936 // throws specification - ignore
937 } else if (filter == 0) {
938 // destructor - ignore
939 } else /* filter >= 0 */ {
940 // catch handler - use this frame
946 if (!has_handler) return false;
948 // Count the number of source ranges with the same landing pad as our match
949 unsigned int range_count = 0;
951 while (p < call_site_table_end) {
952 /*start*/ read_address(&p, bases, call_site_enc)/*+bases->func*/;
953 /*len*/ read_address(&p, bases, call_site_enc);
954 uintptr_t pad = read_address(&p, bases, call_site_enc);
955 /*action*/ read_uleb(&p);
957 if (pad == try_landing_pad) {
962 if (range_count == 1) {
963 // No other source ranges with the same landing pad. We're done here.
967 // Record all ranges with the same landing pad as our match.
968 frame->ips = (frame_ips *)
969 malloc((range_count + 1) * sizeof(frame->ips[0]));
972 while (p < call_site_table_end) {
973 uintptr_t start = read_address(&p, bases, call_site_enc)+bases->func;
974 uintptr_t len = read_address(&p, bases, call_site_enc);
975 uintptr_t pad = read_address(&p, bases, call_site_enc);
976 /*action*/ read_uleb(&p);
978 if (pad == try_landing_pad) {
979 if (start < try_start) try_start = start;
980 if (start+len > try_end) try_end = start+len;
981 frame->ips[r].start = start;
982 frame->ips[r].end = start+len;
987 frame->ips[r].start = 0;
988 frame->ips[r].end = 0;
991 frame->ip_start = try_start;
992 frame->ip_end = try_end;
998 static struct frame_range findHandler(void)
1000 // walk stack looking for frame with objc catch handler
1002 unw_cursor_t cursor;
1003 unw_proc_info_t info;
1004 unw_getcontext(&uc);
1005 unw_init_local(&cursor, &uc);
1006 while ( (unw_step(&cursor) > 0) && (unw_get_proc_info(&cursor, &info) == UNW_ESUCCESS) ) {
1007 // must use objc personality handler
1008 if ( info.handler != (uintptr_t)__objc_personality_v0 )
1010 // must have landing pad
1011 if ( info.lsda == 0 )
1013 // must have landing pad that catches objc exceptions
1014 struct dwarf_eh_bases bases;
1015 bases.tbase = 0; // from unwind-dw2-fde-darwin.c:examine_objects()
1016 bases.dbase = 0; // from unwind-dw2-fde-darwin.c:examine_objects()
1017 bases.func = info.start_ip;
1019 unw_get_reg(&cursor, UNW_REG_IP, &ip);
1021 struct frame_range try_range = {0, 0, 0, 0};
1022 if ( isObjCExceptionCatcher(info.lsda, ip, &bases, &try_range) ) {
1024 unw_get_reg(&cursor, UNW_REG_SP, &cfa);
1025 try_range.cfa = cfa;
1030 return (struct frame_range){0, 0, 0, 0};
1034 // This data structure assumes the number of
1035 // active alt handlers per frame is small.
1037 // for OBJC_DEBUG_ALT_HANDLERS, record the call to objc_addExceptionHandler.
1038 #define BACKTRACE_COUNT 46
1039 #define THREADNAME_COUNT 64
1040 struct alt_handler_debug {
1043 void *backtrace[BACKTRACE_COUNT];
1044 char thread[THREADNAME_COUNT];
1045 char queue[THREADNAME_COUNT];
1048 struct alt_handler_data {
1049 struct frame_range frame;
1050 objc_exception_handler fn;
1052 struct alt_handler_debug *debug;
1055 struct alt_handler_list {
1056 unsigned int allocated;
1058 struct alt_handler_data *handlers;
1059 struct alt_handler_list *next_DEBUGONLY;
1062 static mutex_t DebugLock;
1063 static struct alt_handler_list *DebugLists;
1064 static uintptr_t DebugCounter;
1066 __attribute__((noinline, noreturn))
1067 void alt_handler_error(uintptr_t token);
1069 static struct alt_handler_list *
1070 fetch_handler_list(bool create)
1072 _objc_pthread_data *data = _objc_fetch_pthread_data(create);
1073 if (!data) return nil;
1075 struct alt_handler_list *list = data->handlerList;
1077 if (!create) return nil;
1078 list = (struct alt_handler_list *)calloc(1, sizeof(*list));
1079 data->handlerList = list;
1081 if (DebugAltHandlers) {
1082 // Save this list so the debug code can find it from other threads
1083 mutex_locker_t lock(DebugLock);
1084 list->next_DEBUGONLY = DebugLists;
1093 void _destroyAltHandlerList(struct alt_handler_list *list)
1096 if (DebugAltHandlers) {
1097 // Detach from the list-of-lists.
1098 mutex_locker_t lock(DebugLock);
1099 struct alt_handler_list **listp = &DebugLists;
1100 while (*listp && *listp != list) listp = &(*listp)->next_DEBUGONLY;
1101 if (*listp) *listp = (*listp)->next_DEBUGONLY;
1104 if (list->handlers) {
1105 for (unsigned int i = 0; i < list->allocated; i++) {
1106 if (list->handlers[i].frame.ips) {
1107 free(list->handlers[i].frame.ips);
1110 free(list->handlers);
1117 uintptr_t objc_addExceptionHandler(objc_exception_handler fn, void *context)
1119 // Find the closest enclosing frame with objc catch handlers
1120 struct frame_range target_frame = findHandler();
1121 if (!target_frame.ip_start) {
1122 // No suitable enclosing handler found.
1126 // Record this alt handler for the discovered frame.
1127 struct alt_handler_list *list = fetch_handler_list(YES);
1130 if (list->used == list->allocated) {
1131 list->allocated = list->allocated*2 ?: 4;
1132 list->handlers = (struct alt_handler_data *)
1133 realloc(list->handlers,
1134 list->allocated * sizeof(list->handlers[0]));
1135 bzero(&list->handlers[list->used], (list->allocated - list->used) * sizeof(list->handlers[0]));
1139 for (i = 0; i < list->allocated; i++) {
1140 if (list->handlers[i].frame.ip_start == 0 &&
1141 list->handlers[i].frame.ip_end == 0 &&
1142 list->handlers[i].frame.cfa == 0)
1147 if (i == list->allocated) {
1148 _objc_fatal("alt handlers in objc runtime are buggy!");
1152 struct alt_handler_data *data = &list->handlers[i];
1154 data->frame = target_frame;
1156 data->context = context;
1159 uintptr_t token = i+1;
1161 if (DebugAltHandlers) {
1162 // Record backtrace in case this handler is misused later.
1163 mutex_locker_t lock(DebugLock);
1165 token = DebugCounter++;
1166 if (token == 0) token = DebugCounter++;
1169 data->debug = (struct alt_handler_debug *)
1170 calloc(sizeof(*data->debug), 1);
1172 bzero(data->debug, sizeof(*data->debug));
1175 pthread_getname_np(pthread_self(), data->debug->thread, THREADNAME_COUNT);
1176 strlcpy(data->debug->queue,
1177 dispatch_queue_get_label(dispatch_get_current_queue()),
1179 data->debug->backtraceSize =
1180 backtrace(data->debug->backtrace, BACKTRACE_COUNT);
1181 data->debug->token = token;
1184 if (PrintAltHandlers) {
1185 _objc_inform("ALT HANDLERS: installing alt handler #%lu %p(%p) on "
1186 "frame [ip=%p..%p sp=%p]", (unsigned long)token,
1187 data->fn, data->context, (void *)data->frame.ip_start,
1188 (void *)data->frame.ip_end, (void *)data->frame.cfa);
1189 if (data->frame.ips) {
1192 uintptr_t start = data->frame.ips[r].start;
1193 uintptr_t end = data->frame.ips[r].end;
1195 if (start == 0 && end == 0) break;
1196 _objc_inform("ALT HANDLERS: ip=%p..%p",
1197 (void*)start, (void*)end);
1202 if (list->used > 1000) {
1203 static int warned = 0;
1205 _objc_inform("ALT HANDLERS: *** over 1000 alt handlers installed; "
1206 "this is probably a bug");
1215 void objc_removeExceptionHandler(uintptr_t token)
1218 // objc_addExceptionHandler failed
1222 struct alt_handler_list *list = fetch_handler_list(NO);
1223 if (!list || !list->handlers) {
1224 // no alt handlers active
1225 alt_handler_error(token);
1228 uintptr_t i = token-1;
1230 if (DebugAltHandlers) {
1231 // search for the token instead of using token-1
1232 for (i = 0; i < list->allocated; i++) {
1233 struct alt_handler_data *data = &list->handlers[i];
1234 if (data->debug && data->debug->token == token) break;
1238 if (i >= list->allocated) {
1239 // token out of range
1240 alt_handler_error(token);
1243 struct alt_handler_data *data = &list->handlers[i];
1245 if (data->frame.ip_start == 0 && data->frame.ip_end == 0 && data->frame.cfa == 0) {
1246 // token in range, but invalid
1247 alt_handler_error(token);
1250 if (PrintAltHandlers) {
1251 _objc_inform("ALT HANDLERS: removing alt handler #%lu %p(%p) on "
1252 "frame [ip=%p..%p sp=%p]", (unsigned long)token,
1253 data->fn, data->context, (void *)data->frame.ip_start,
1254 (void *)data->frame.ip_end, (void *)data->frame.cfa);
1257 if (data->debug) free(data->debug);
1258 if (data->frame.ips) free(data->frame.ips);
1259 bzero(data, sizeof(*data));
1264 BREAKPOINT_FUNCTION(
1265 void objc_alt_handler_error(void));
1267 __attribute__((noinline, noreturn))
1268 void alt_handler_error(uintptr_t token)
1271 ("objc_removeExceptionHandler() called with unknown alt handler; "
1272 "this is probably a bug in multithreaded AppKit use. "
1273 "Set environment variable OBJC_DEBUG_ALT_HANDLERS=YES "
1274 "or break in objc_alt_handler_error() to debug.");
1276 if (DebugAltHandlers) {
1279 // Search other threads' alt handler lists for this handler.
1280 struct alt_handler_list *list;
1281 for (list = DebugLists; list; list = list->next_DEBUGONLY) {
1283 for (h = 0; h < list->allocated; h++) {
1284 struct alt_handler_data *data = &list->handlers[h];
1285 if (data->debug && data->debug->token == token) {
1289 // Build a string from the recorded backtrace
1292 backtrace_symbols(data->debug->backtrace,
1293 data->debug->backtraceSize);
1295 for (i = 0; i < data->debug->backtraceSize; i++){
1296 len += 4 + strlen(symbols[i]) + 1;
1298 symbolString = (char *)calloc(len, 1);
1299 for (i = 0; i < data->debug->backtraceSize; i++){
1300 strcat(symbolString, " ");
1301 strcat(symbolString, symbols[i]);
1302 strcat(symbolString, "\n");
1307 _objc_inform_now_and_on_crash
1308 ("The matching objc_addExceptionHandler() was called "
1309 "by:\nThread '%s': Dispatch queue: '%s': \n%s",
1310 data->debug->thread, data->debug->queue, symbolString);
1321 objc_alt_handler_error();
1324 ("objc_removeExceptionHandler() called with unknown alt handler; "
1325 "this is probably a bug in multithreaded AppKit use. ");
1328 // called in order registered, to match 32-bit _NSAddAltHandler2
1329 // fixme reverse registration order matches c++ destructors better
1330 static void call_alt_handlers(struct _Unwind_Context *ctx)
1332 uintptr_t ip = _Unwind_GetIP(ctx) - 1;
1333 uintptr_t cfa = _Unwind_GetCFA(ctx);
1336 struct alt_handler_list *list = fetch_handler_list(NO);
1337 if (!list || list->used == 0) return;
1339 for (i = 0; i < list->allocated; i++) {
1340 struct alt_handler_data *data = &list->handlers[i];
1341 if (ip >= data->frame.ip_start && ip < data->frame.ip_end && data->frame.cfa == cfa)
1343 if (data->frame.ips) {
1347 uintptr_t start = data->frame.ips[r].start;
1348 uintptr_t end = data->frame.ips[r].end;
1350 if (start == 0 && end == 0) {
1354 if (ip >= start && ip < end) {
1359 if (!found) continue;
1362 // Copy and clear before the callback, in case the
1363 // callback manipulates the alt handler list.
1364 struct alt_handler_data copy = *data;
1365 bzero(data, sizeof(*data));
1367 if (PrintExceptions || PrintAltHandlers) {
1368 _objc_inform("EXCEPTIONS: calling alt handler %p(%p) from "
1369 "frame [ip=%p..%p sp=%p]", copy.fn, copy.context,
1370 (void *)copy.frame.ip_start,
1371 (void *)copy.frame.ip_end,
1372 (void *)copy.frame.cfa);
1374 if (copy.fn) (*copy.fn)(nil, copy.context);
1375 if (copy.frame.ips) free(copy.frame.ips);
1380 // SUPPORT_ALT_HANDLERS
1384 /***********************************************************************
1386 * Initialize libobjc's exception handling system.
1387 * Called by map_images().
1388 **********************************************************************/
1389 void exception_init(void)
1391 old_terminate = std::set_terminate(&_objc_terminate);