]> git.saurik.com Git - apple/objc4.git/blob - runtime/objc-exception.mm
e9dbf2cef3a27062d4b478b43f395dbf7900086a
[apple/objc4.git] / runtime / objc-exception.mm
1 /*
2 * Copyright (c) 2002-2007 Apple Inc. All rights reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
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
11 * file.
12 *
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.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24 #if !__OBJC2__
25
26 /***********************************************************************
27 * 32-bit implementation
28 **********************************************************************/
29
30 #include "objc-private.h"
31 #include <stdlib.h>
32 #include <setjmp.h>
33 #include <execinfo.h>
34
35 #include "objc-exception.h"
36
37 static objc_exception_functions_t xtab;
38
39 // forward declaration
40 static void set_default_handlers();
41
42
43 /*
44 * Exported functions
45 */
46
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)
51 *table = xtab;
52 }
53
54 // set table
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)
58 xtab = *table;
59 }
60
61 /*
62 * The following functions are
63 * synthesized by the compiler upon encountering language constructs
64 */
65
66 void objc_exception_throw(id exception) {
67 if (!xtab.throw_exc) {
68 set_default_handlers();
69 }
70
71 if (PrintExceptionThrow) {
72 _objc_inform("EXCEPTIONS: throwing %p (%s)",
73 (void*)exception, object_getClassName(exception));
74 void* callstack[500];
75 int frameCount = backtrace(callstack, 500);
76 backtrace_symbols_fd(callstack, frameCount, fileno(stderr));
77 }
78
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");
82 }
83
84 void objc_exception_try_enter(void *localExceptionData) {
85 if (!xtab.throw_exc) {
86 set_default_handlers();
87 }
88 xtab.try_enter(localExceptionData);
89 }
90
91
92 void objc_exception_try_exit(void *localExceptionData) {
93 if (!xtab.throw_exc) {
94 set_default_handlers();
95 }
96 xtab.try_exit(localExceptionData);
97 }
98
99
100 id objc_exception_extract(void *localExceptionData) {
101 if (!xtab.throw_exc) {
102 set_default_handlers();
103 }
104 return xtab.extract(localExceptionData);
105 }
106
107
108 int objc_exception_match(Class exceptionClass, id exception) {
109 if (!xtab.throw_exc) {
110 set_default_handlers();
111 }
112 return xtab.match(exceptionClass, exception);
113 }
114
115
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
120
121
122 extern void _objc_inform(const char *fmt, ...);
123
124 typedef struct { jmp_buf buf; void *pointers[4]; } LocalData_t;
125
126 typedef struct _threadChain {
127 LocalData_t *topHandler;
128 objc_thread_t perThreadID;
129 struct _threadChain *next;
130 }
131 ThreadChainLink_t;
132
133 static ThreadChainLink_t ThreadChainLink;
134
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;
142 continue;
143 }
144 // create a new one
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;
149 walker->next = nil;
150 walker->topHandler = nil;
151 walker->perThreadID = self;
152 }
153 return walker;
154 }
155
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);
162 }
163
164 static void default_throw(id value) {
165 ThreadChainLink_t *chainLink = getChainLink();
166 LocalData_t *led;
167 if (value == nil) {
168 if (PrintExceptions) _objc_inform("EXCEPTIONS: objc_exception_throw with nil value\n");
169 return;
170 }
171 if (chainLink == nil) {
172 if (PrintExceptions) _objc_inform("EXCEPTIONS: No handler in place!\n");
173 return;
174 }
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
180 #if TARGET_OS_WIN32
181 longjmp(led->buf, 1);
182 #else
183 _longjmp(led->buf, 1);
184 #endif
185 }
186
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");
191 return;
192 }
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
196 }
197
198 static id default_extract(void *localExceptionData) {
199 LocalData_t *led = (LocalData_t *)localExceptionData;
200 return (id)led->pointers[0];
201 }
202
203 static int default_match(Class exceptionClass, id exception) {
204 //return [exception isKindOfClass:exceptionClass];
205 Class cls;
206 for (cls = exception->getIsa(); nil != cls; cls = cls->superclass)
207 if (cls == exceptionClass) return 1;
208 return 0;
209 }
210
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 };
214
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);
218 }
219
220
221 void exception_init(void)
222 {
223 // nothing to do
224 }
225
226 void _destroyAltHandlerList(struct alt_handler_list *list)
227 {
228 // nothing to do
229 }
230
231
232 // !__OBJC2__
233 #else
234 // __OBJC2__
235
236 /***********************************************************************
237 * 64-bit implementation.
238 **********************************************************************/
239
240 #include "objc-private.h"
241 #include <objc/objc-exception.h>
242 #include <objc/NSObject.h>
243 #include <execinfo.h>
244
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
248
249 struct _Unwind_Exception;
250 struct _Unwind_Context;
251
252 typedef int _Unwind_Action;
253 enum : _Unwind_Action {
254 _UA_SEARCH_PHASE = 1,
255 _UA_CLEANUP_PHASE = 2,
256 _UA_HANDLER_FRAME = 4,
257 _UA_FORCE_UNWIND = 8
258 };
259
260 typedef int _Unwind_Reason_Code;
261 enum : _Unwind_Reason_Code {
262 _URC_NO_REASON = 0,
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
271 };
272
273 struct dwarf_eh_bases
274 {
275 uintptr_t tbase;
276 uintptr_t dbase;
277 uintptr_t func;
278 };
279
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 *);
283
284
285 // C++ runtime types and functions
286 // copied from cxxabi.h
287
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);
294
295 #if SUPPORT_ZEROCOST_EXCEPTIONS
296 # define CXX_PERSONALITY __gxx_personality_v0
297 #else
298 # define CXX_PERSONALITY __gxx_personality_sj0
299 #endif
300
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);
307
308
309 // objc's internal exception types and data
310
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
315
316 Class cls_unremapped;
317 };
318
319 struct objc_exception {
320 id obj;
321 struct objc_typeinfo tinfo;
322 };
323
324
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);
330 }
331 static void _objc_exception_abort2(void) {
332 _objc_fatal("unexpected call into objc exception typeinfo vtable %d", 2);
333 }
334 static void _objc_exception_abort3(void) {
335 _objc_fatal("unexpected call into objc exception typeinfo vtable %d", 3);
336 }
337 static void _objc_exception_abort4(void) {
338 _objc_fatal("unexpected call into objc exception typeinfo vtable %d", 4);
339 }
340
341 static bool _objc_exception_do_catch(struct objc_typeinfo *catch_tinfo,
342 struct objc_typeinfo *throw_tinfo,
343 void **throw_obj_p,
344 unsigned outer);
345
346 // forward declaration
347 OBJC_EXPORT struct objc_typeinfo OBJC_EHTYPE_id;
348
349 OBJC_EXPORT
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,
364 };
365
366 OBJC_EXPORT
367 struct objc_typeinfo OBJC_EHTYPE_id = {
368 objc_ehtype_vtable+2,
369 "id",
370 nil
371 };
372
373
374
375 /***********************************************************************
376 * Foundation customization
377 **********************************************************************/
378
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)
384 {
385 return exception;
386 }
387 static objc_exception_preprocessor exception_preprocessor = _objc_default_exception_preprocessor;
388
389
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)
395 {
396 Class cls;
397 for (cls = exception->getIsa();
398 cls != nil;
399 cls = cls->superclass)
400 {
401 if (cls == catch_cls) return 1;
402 }
403
404 return 0;
405 }
406 static objc_exception_matcher exception_matcher = _objc_default_exception_matcher;
407
408
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)
414 {
415 }
416 static objc_uncaught_exception_handler uncaught_handler = _objc_default_uncaught_exception_handler;
417
418
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)
426 {
427 objc_exception_preprocessor result = exception_preprocessor;
428 exception_preprocessor = fn;
429 return result;
430 }
431
432
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)
440 {
441 objc_exception_matcher result = exception_matcher;
442 exception_matcher = fn;
443 return result;
444 }
445
446
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)
454 {
455 objc_uncaught_exception_handler result = uncaught_handler;
456 uncaught_handler = fn;
457 return result;
458 }
459
460
461 /***********************************************************************
462 * Exception personality
463 **********************************************************************/
464
465 static void call_alt_handlers(struct _Unwind_Context *ctx);
466
467 _Unwind_Reason_Code
468 __objc_personality_v0(int version,
469 _Unwind_Action actions,
470 uint64_t exceptionClass,
471 struct _Unwind_Exception *exceptionObject,
472 struct _Unwind_Context *context)
473 {
474 bool unwinding = ((actions & _UA_CLEANUP_PHASE) ||
475 (actions & _UA_FORCE_UNWIND));
476
477 if (PrintExceptions) {
478 _objc_inform("EXCEPTIONS: %s through frame [ip=%p sp=%p] "
479 "for exception %p",
480 unwinding ? "unwinding" : "searching",
481 (void*)(_Unwind_GetIP(context)-1),
482 (void*)_Unwind_GetCFA(context), exceptionObject);
483 }
484
485 // If we're executing the unwind, call this frame's alt handlers, if any.
486 if (unwinding) {
487 call_alt_handlers(context);
488 }
489
490 // Let C++ handle the unwind itself.
491 return CXX_PERSONALITY(version, actions, exceptionClass,
492 exceptionObject, context);
493 }
494
495
496 /***********************************************************************
497 * Compiler ABI
498 **********************************************************************/
499
500 static void _objc_exception_destructor(void *exc_gen)
501 {
502 // Release the retain from objc_exception_throw().
503
504 struct objc_exception *exc = (struct objc_exception *)exc_gen;
505 id obj = exc->obj;
506
507 if (PrintExceptions) {
508 _objc_inform("EXCEPTIONS: releasing completed exception %p (object %p, a %s)",
509 exc, obj, object_getClassName(obj));
510 }
511
512 #if SUPPORT_GC
513 if (UseGC) {
514 if (auto_zone_is_valid_pointer(gc_zone, obj)) {
515 auto_zone_release(gc_zone, exc->obj);
516 }
517 }
518 else
519 #endif
520 {
521 [obj release];
522 }
523 }
524
525
526 void objc_exception_throw(id obj)
527 {
528 struct objc_exception *exc = (struct objc_exception *)
529 __cxa_allocate_exception(sizeof(struct objc_exception));
530
531 obj = (*exception_preprocessor)(obj);
532
533 // Retain the exception object during unwinding.
534 // GC: because `exc` is unscanned memory
535 // Non-GC: because otherwise an autorelease pool pop can cause a crash
536 #if SUPPORT_GC
537 if (UseGC) {
538 if (auto_zone_is_valid_pointer(gc_zone, obj)) {
539 auto_zone_retain(gc_zone, obj);
540 }
541 }
542 else
543 #endif
544 {
545 [obj retain];
546 }
547
548 exc->obj = obj;
549 exc->tinfo.vtable = objc_ehtype_vtable+2;
550 exc->tinfo.name = object_getClassName(obj);
551 exc->tinfo.cls_unremapped = obj ? obj->getIsa() : Nil;
552
553 if (PrintExceptions) {
554 _objc_inform("EXCEPTIONS: throwing %p (object %p, a %s)",
555 exc, (void*)obj, object_getClassName(obj));
556 }
557
558 if (PrintExceptionThrow) {
559 if (!PrintExceptions)
560 _objc_inform("EXCEPTIONS: throwing %p (object %p, a %s)",
561 exc, (void*)obj, object_getClassName(obj));
562 void* callstack[500];
563 int frameCount = backtrace(callstack, 500);
564 backtrace_symbols_fd(callstack, frameCount, fileno(stderr));
565 }
566
567 OBJC_RUNTIME_OBJC_EXCEPTION_THROW(obj); // dtrace probe to log throw activity
568 __cxa_throw(exc, &exc->tinfo, &_objc_exception_destructor);
569 __builtin_trap();
570 }
571
572
573 void objc_exception_rethrow(void)
574 {
575 // exception_preprocessor doesn't get another bite of the apple
576 if (PrintExceptions) {
577 _objc_inform("EXCEPTIONS: rethrowing current exception");
578 }
579
580 OBJC_RUNTIME_OBJC_EXCEPTION_RETHROW(); // dtrace probe to log throw activity.
581 __cxa_rethrow();
582 __builtin_trap();
583 }
584
585
586 id objc_begin_catch(void *exc_gen)
587 {
588 if (PrintExceptions) {
589 _objc_inform("EXCEPTIONS: handling exception %p at %p",
590 exc_gen, __builtin_return_address(0));
591 }
592 // NOT actually an id in the catch(...) case!
593 return (id)__cxa_begin_catch(exc_gen);
594 }
595
596
597 void objc_end_catch(void)
598 {
599 if (PrintExceptions) {
600 _objc_inform("EXCEPTIONS: finishing handler");
601 }
602 __cxa_end_catch();
603 }
604
605
606 // `outer` is not passed by the new libcxxabi
607 static bool _objc_exception_do_catch(struct objc_typeinfo *catch_tinfo,
608 struct objc_typeinfo *throw_tinfo,
609 void **throw_obj_p,
610 unsigned outer UNAVAILABLE_ATTRIBUTE)
611 {
612 id exception;
613
614 if (throw_tinfo->vtable != objc_ehtype_vtable+2) {
615 // Only objc types can be caught here.
616 if (PrintExceptions) _objc_inform("EXCEPTIONS: skipping catch(?)");
617 return false;
618 }
619
620 // Adjust exception pointer.
621 // Old libcppabi: we lied about __is_pointer_p() so we have to do it here
622 // New libcxxabi: we have to do it here regardless
623 *throw_obj_p = **(void***)throw_obj_p;
624
625 // `catch (id)` always catches objc types.
626 if (catch_tinfo == &OBJC_EHTYPE_id) {
627 if (PrintExceptions) _objc_inform("EXCEPTIONS: catch(id)");
628 return true;
629 }
630
631 exception = *(id *)throw_obj_p;
632
633 Class handler_cls = _class_remap(catch_tinfo->cls_unremapped);
634 if (!handler_cls) {
635 // catch handler's class is weak-linked and missing. Not a match.
636 }
637 else if ((*exception_matcher)(handler_cls, exception)) {
638 if (PrintExceptions) _objc_inform("EXCEPTIONS: catch(%s)",
639 handler_cls->nameForLogging());
640 return true;
641 }
642
643 if (PrintExceptions) _objc_inform("EXCEPTIONS: skipping catch(%s)",
644 handler_cls->nameForLogging());
645
646 return false;
647 }
648
649
650 /***********************************************************************
651 * _objc_terminate
652 * Custom std::terminate handler.
653 *
654 * The uncaught exception callback is implemented as a std::terminate handler.
655 * 1. Check if there's an active exception
656 * 2. If so, check if it's an Objective-C exception
657 * 3. If so, call our registered callback with the object.
658 * 4. Finally, call the previous terminate handler.
659 **********************************************************************/
660 static void (*old_terminate)(void) = nil;
661 static void _objc_terminate(void)
662 {
663 if (PrintExceptions) {
664 _objc_inform("EXCEPTIONS: terminating");
665 }
666
667 if (! __cxa_current_exception_type()) {
668 // No current exception.
669 (*old_terminate)();
670 }
671 else {
672 // There is a current exception. Check if it's an objc exception.
673 @try {
674 __cxa_rethrow();
675 } @catch (id e) {
676 // It's an objc object. Call Foundation's handler, if any.
677 (*uncaught_handler)((id)e);
678 (*old_terminate)();
679 } @catch (...) {
680 // It's not an objc object. Continue to C++ terminate.
681 (*old_terminate)();
682 }
683 }
684 }
685
686
687 /***********************************************************************
688 * objc_terminate
689 * Calls std::terminate for clients who don't link to C++ themselves.
690 * Called by the compiler if an exception is thrown
691 * from a context where exceptions may not be thrown.
692 **********************************************************************/
693 void objc_terminate(void)
694 {
695 std::terminate();
696 }
697
698
699 /***********************************************************************
700 * alt handler support - zerocost implementation only
701 **********************************************************************/
702
703 #if !SUPPORT_ALT_HANDLERS
704
705 void _destroyAltHandlerList(struct alt_handler_list *list)
706 {
707 }
708
709 static void call_alt_handlers(struct _Unwind_Context *ctx)
710 {
711 // unsupported in sjlj environments
712 }
713
714 #else
715
716 #include <libunwind.h>
717 #include <execinfo.h>
718 #include <dispatch/dispatch.h>
719
720 // Dwarf eh data encodings
721 #define DW_EH_PE_omit 0xff // no data follows
722
723 #define DW_EH_PE_absptr 0x00
724 #define DW_EH_PE_uleb128 0x01
725 #define DW_EH_PE_udata2 0x02
726 #define DW_EH_PE_udata4 0x03
727 #define DW_EH_PE_udata8 0x04
728 #define DW_EH_PE_sleb128 0x09
729 #define DW_EH_PE_sdata2 0x0A
730 #define DW_EH_PE_sdata4 0x0B
731 #define DW_EH_PE_sdata8 0x0C
732
733 #define DW_EH_PE_pcrel 0x10
734 #define DW_EH_PE_textrel 0x20
735 #define DW_EH_PE_datarel 0x30
736 #define DW_EH_PE_funcrel 0x40
737 #define DW_EH_PE_aligned 0x50 // fixme
738
739 #define DW_EH_PE_indirect 0x80 // gcc extension
740
741
742 /***********************************************************************
743 * read_uleb
744 * Read a LEB-encoded unsigned integer from the address stored in *pp.
745 * Increments *pp past the bytes read.
746 * Adapted from DWARF Debugging Information Format 1.1, appendix 4
747 **********************************************************************/
748 static uintptr_t read_uleb(uintptr_t *pp)
749 {
750 uintptr_t result = 0;
751 uintptr_t shift = 0;
752 unsigned char byte;
753 do {
754 byte = *(const unsigned char *)(*pp)++;
755 result |= (byte & 0x7f) << shift;
756 shift += 7;
757 } while (byte & 0x80);
758 return result;
759 }
760
761
762 /***********************************************************************
763 * read_sleb
764 * Read a LEB-encoded signed integer from the address stored in *pp.
765 * Increments *pp past the bytes read.
766 * Adapted from DWARF Debugging Information Format 1.1, appendix 4
767 **********************************************************************/
768 static intptr_t read_sleb(uintptr_t *pp)
769 {
770 uintptr_t result = 0;
771 uintptr_t shift = 0;
772 unsigned char byte;
773 do {
774 byte = *(const unsigned char *)(*pp)++;
775 result |= (byte & 0x7f) << shift;
776 shift += 7;
777 } while (byte & 0x80);
778 if ((shift < 8*sizeof(intptr_t)) && (byte & 0x40)) {
779 result |= ((intptr_t)-1) << shift;
780 }
781 return result;
782 }
783
784
785 /***********************************************************************
786 * read_address
787 * Reads an encoded address from the address stored in *pp.
788 * Increments *pp past the bytes read.
789 * The data is interpreted according to the given dwarf encoding
790 * and base addresses.
791 **********************************************************************/
792 static uintptr_t read_address(uintptr_t *pp,
793 const struct dwarf_eh_bases *bases,
794 unsigned char encoding)
795 {
796 uintptr_t result = 0;
797 uintptr_t oldp = *pp;
798
799 // fixme need DW_EH_PE_aligned?
800
801 #define READ(type) \
802 result = *(type *)(*pp); \
803 *pp += sizeof(type);
804
805 if (encoding == DW_EH_PE_omit) return 0;
806
807 switch (encoding & 0x0f) {
808 case DW_EH_PE_absptr:
809 READ(uintptr_t);
810 break;
811 case DW_EH_PE_uleb128:
812 result = read_uleb(pp);
813 break;
814 case DW_EH_PE_udata2:
815 READ(uint16_t);
816 break;
817 case DW_EH_PE_udata4:
818 READ(uint32_t);
819 break;
820 #if __LP64__
821 case DW_EH_PE_udata8:
822 READ(uint64_t);
823 break;
824 #endif
825 case DW_EH_PE_sleb128:
826 result = read_sleb(pp);
827 break;
828 case DW_EH_PE_sdata2:
829 READ(int16_t);
830 break;
831 case DW_EH_PE_sdata4:
832 READ(int32_t);
833 break;
834 #if __LP64__
835 case DW_EH_PE_sdata8:
836 READ(int64_t);
837 break;
838 #endif
839 default:
840 _objc_inform("unknown DWARF EH encoding 0x%x at %p",
841 encoding, (void *)*pp);
842 break;
843 }
844
845 #undef READ
846
847 if (result) {
848 switch (encoding & 0x70) {
849 case DW_EH_PE_pcrel:
850 // fixme correct?
851 result += (uintptr_t)oldp;
852 break;
853 case DW_EH_PE_textrel:
854 result += bases->tbase;
855 break;
856 case DW_EH_PE_datarel:
857 result += bases->dbase;
858 break;
859 case DW_EH_PE_funcrel:
860 result += bases->func;
861 break;
862 case DW_EH_PE_aligned:
863 _objc_inform("unknown DWARF EH encoding 0x%x at %p",
864 encoding, (void *)*pp);
865 break;
866 default:
867 // no adjustment
868 break;
869 }
870
871 if (encoding & DW_EH_PE_indirect) {
872 result = *(uintptr_t *)result;
873 }
874 }
875
876 return (uintptr_t)result;
877 }
878
879
880 struct frame_ips {
881 uintptr_t start;
882 uintptr_t end;
883 };
884 struct frame_range {
885 uintptr_t ip_start;
886 uintptr_t ip_end;
887 uintptr_t cfa;
888 // precise ranges within ip_start..ip_end; nil or {0,0} terminated
889 frame_ips *ips;
890 };
891
892
893 static bool isObjCExceptionCatcher(uintptr_t lsda, uintptr_t ip,
894 const struct dwarf_eh_bases* bases,
895 struct frame_range *frame)
896 {
897 unsigned char LPStart_enc = *(const unsigned char *)lsda++;
898
899 if (LPStart_enc != DW_EH_PE_omit) {
900 read_address(&lsda, bases, LPStart_enc); // LPStart
901 }
902
903 unsigned char TType_enc = *(const unsigned char *)lsda++;
904 if (TType_enc != DW_EH_PE_omit) {
905 read_uleb(&lsda); // TType
906 }
907
908 unsigned char call_site_enc = *(const unsigned char *)lsda++;
909 uintptr_t length = read_uleb(&lsda);
910 uintptr_t call_site_table = lsda;
911 uintptr_t call_site_table_end = call_site_table + length;
912 uintptr_t action_record_table = call_site_table_end;
913
914 uintptr_t action_record = 0;
915 uintptr_t p = call_site_table;
916
917 uintptr_t try_start;
918 uintptr_t try_end;
919 uintptr_t try_landing_pad;
920
921 while (p < call_site_table_end) {
922 uintptr_t start = read_address(&p, bases, call_site_enc)+bases->func;
923 uintptr_t len = read_address(&p, bases, call_site_enc);
924 uintptr_t pad = read_address(&p, bases, call_site_enc);
925 uintptr_t action = read_uleb(&p);
926
927 if (ip < start) {
928 // no more source ranges
929 return false;
930 }
931 else if (ip < start + len) {
932 // found the range
933 if (!pad) return false; // ...but it has no landing pad
934 // found the landing pad
935 action_record = action ? action_record_table + action - 1 : 0;
936 try_start = start;
937 try_end = start + len;
938 try_landing_pad = pad;
939 break;
940 }
941 }
942
943 if (!action_record) return false; // no catch handlers
944
945 // has handlers, destructors, and/or throws specifications
946 // Use this frame if it has any handlers
947 bool has_handler = false;
948 p = action_record;
949 intptr_t offset;
950 do {
951 intptr_t filter = read_sleb(&p);
952 uintptr_t temp = p;
953 offset = read_sleb(&temp);
954 p += offset;
955
956 if (filter < 0) {
957 // throws specification - ignore
958 } else if (filter == 0) {
959 // destructor - ignore
960 } else /* filter >= 0 */ {
961 // catch handler - use this frame
962 has_handler = true;
963 break;
964 }
965 } while (offset);
966
967 if (!has_handler) return false;
968
969 // Count the number of source ranges with the same landing pad as our match
970 unsigned int range_count = 0;
971 p = call_site_table;
972 while (p < call_site_table_end) {
973 /*start*/ read_address(&p, bases, call_site_enc)/*+bases->func*/;
974 /*len*/ read_address(&p, bases, call_site_enc);
975 uintptr_t pad = read_address(&p, bases, call_site_enc);
976 /*action*/ read_uleb(&p);
977
978 if (pad == try_landing_pad) {
979 range_count++;
980 }
981 }
982
983 if (range_count == 1) {
984 // No other source ranges with the same landing pad. We're done here.
985 frame->ips = nil;
986 }
987 else {
988 // Record all ranges with the same landing pad as our match.
989 frame->ips = (frame_ips *)
990 malloc((range_count + 1) * sizeof(frame->ips[0]));
991 unsigned int r = 0;
992 p = call_site_table;
993 while (p < call_site_table_end) {
994 uintptr_t start = read_address(&p, bases, call_site_enc)+bases->func;
995 uintptr_t len = read_address(&p, bases, call_site_enc);
996 uintptr_t pad = read_address(&p, bases, call_site_enc);
997 /*action*/ read_uleb(&p);
998
999 if (pad == try_landing_pad) {
1000 if (start < try_start) try_start = start;
1001 if (start+len > try_end) try_end = start+len;
1002 frame->ips[r].start = start;
1003 frame->ips[r].end = start+len;
1004 r++;
1005 }
1006 }
1007
1008 frame->ips[r].start = 0;
1009 frame->ips[r].end = 0;
1010 }
1011
1012 frame->ip_start = try_start;
1013 frame->ip_end = try_end;
1014
1015 return true;
1016 }
1017
1018
1019 static struct frame_range findHandler(void)
1020 {
1021 // walk stack looking for frame with objc catch handler
1022 unw_context_t uc;
1023 unw_cursor_t cursor;
1024 unw_proc_info_t info;
1025 unw_getcontext(&uc);
1026 unw_init_local(&cursor, &uc);
1027 while ( (unw_step(&cursor) > 0) && (unw_get_proc_info(&cursor, &info) == UNW_ESUCCESS) ) {
1028 // must use objc personality handler
1029 if ( info.handler != (uintptr_t)__objc_personality_v0 )
1030 continue;
1031 // must have landing pad
1032 if ( info.lsda == 0 )
1033 continue;
1034 // must have landing pad that catches objc exceptions
1035 struct dwarf_eh_bases bases;
1036 bases.tbase = 0; // from unwind-dw2-fde-darwin.c:examine_objects()
1037 bases.dbase = 0; // from unwind-dw2-fde-darwin.c:examine_objects()
1038 bases.func = info.start_ip;
1039 unw_word_t ip;
1040 unw_get_reg(&cursor, UNW_REG_IP, &ip);
1041 ip -= 1;
1042 struct frame_range try_range = {0, 0, 0, 0};
1043 if ( isObjCExceptionCatcher(info.lsda, ip, &bases, &try_range) ) {
1044 unw_word_t cfa;
1045 unw_get_reg(&cursor, UNW_REG_SP, &cfa);
1046 try_range.cfa = cfa;
1047 return try_range;
1048 }
1049 }
1050
1051 return (struct frame_range){0, 0, 0, 0};
1052 }
1053
1054
1055 // This data structure assumes the number of
1056 // active alt handlers per frame is small.
1057
1058 // for OBJC_DEBUG_ALT_HANDLERS, record the call to objc_addExceptionHandler.
1059 #define BACKTRACE_COUNT 46
1060 #define THREADNAME_COUNT 64
1061 struct alt_handler_debug {
1062 uintptr_t token;
1063 int backtraceSize;
1064 void *backtrace[BACKTRACE_COUNT];
1065 char thread[THREADNAME_COUNT];
1066 char queue[THREADNAME_COUNT];
1067 };
1068
1069 struct alt_handler_data {
1070 struct frame_range frame;
1071 objc_exception_handler fn;
1072 void *context;
1073 struct alt_handler_debug *debug;
1074 };
1075
1076 struct alt_handler_list {
1077 unsigned int allocated;
1078 unsigned int used;
1079 struct alt_handler_data *handlers;
1080 struct alt_handler_list *next_DEBUGONLY;
1081 };
1082
1083 static mutex_t DebugLock;
1084 static struct alt_handler_list *DebugLists;
1085 static uintptr_t DebugCounter;
1086
1087 void alt_handler_error(uintptr_t token) __attribute__((noinline));
1088
1089 static struct alt_handler_list *
1090 fetch_handler_list(bool create)
1091 {
1092 _objc_pthread_data *data = _objc_fetch_pthread_data(create);
1093 if (!data) return nil;
1094
1095 struct alt_handler_list *list = data->handlerList;
1096 if (!list) {
1097 if (!create) return nil;
1098 list = (struct alt_handler_list *)calloc(1, sizeof(*list));
1099 data->handlerList = list;
1100
1101 if (DebugAltHandlers) {
1102 // Save this list so the debug code can find it from other threads
1103 mutex_locker_t lock(DebugLock);
1104 list->next_DEBUGONLY = DebugLists;
1105 DebugLists = list;
1106 }
1107 }
1108
1109 return list;
1110 }
1111
1112
1113 void _destroyAltHandlerList(struct alt_handler_list *list)
1114 {
1115 if (list) {
1116 if (DebugAltHandlers) {
1117 // Detach from the list-of-lists.
1118 mutex_locker_t lock(DebugLock);
1119 struct alt_handler_list **listp = &DebugLists;
1120 while (*listp && *listp != list) listp = &(*listp)->next_DEBUGONLY;
1121 if (*listp) *listp = (*listp)->next_DEBUGONLY;
1122 }
1123
1124 if (list->handlers) {
1125 for (unsigned int i = 0; i < list->allocated; i++) {
1126 if (list->handlers[i].frame.ips) {
1127 free(list->handlers[i].frame.ips);
1128 }
1129 }
1130 free(list->handlers);
1131 }
1132 free(list);
1133 }
1134 }
1135
1136
1137 uintptr_t objc_addExceptionHandler(objc_exception_handler fn, void *context)
1138 {
1139 // Find the closest enclosing frame with objc catch handlers
1140 struct frame_range target_frame = findHandler();
1141 if (!target_frame.ip_start) {
1142 // No suitable enclosing handler found.
1143 return 0;
1144 }
1145
1146 // Record this alt handler for the discovered frame.
1147 struct alt_handler_list *list = fetch_handler_list(YES);
1148 unsigned int i = 0;
1149
1150 if (list->used == list->allocated) {
1151 list->allocated = list->allocated*2 ?: 4;
1152 list->handlers = (struct alt_handler_data *)
1153 realloc(list->handlers,
1154 list->allocated * sizeof(list->handlers[0]));
1155 bzero(&list->handlers[list->used], (list->allocated - list->used) * sizeof(list->handlers[0]));
1156 i = list->used;
1157 }
1158 else {
1159 for (i = 0; i < list->allocated; i++) {
1160 if (list->handlers[i].frame.ip_start == 0 &&
1161 list->handlers[i].frame.ip_end == 0 &&
1162 list->handlers[i].frame.cfa == 0)
1163 {
1164 break;
1165 }
1166 }
1167 if (i == list->allocated) {
1168 _objc_fatal("alt handlers in objc runtime are buggy!");
1169 }
1170 }
1171
1172 struct alt_handler_data *data = &list->handlers[i];
1173
1174 data->frame = target_frame;
1175 data->fn = fn;
1176 data->context = context;
1177 list->used++;
1178
1179 uintptr_t token = i+1;
1180
1181 if (DebugAltHandlers) {
1182 // Record backtrace in case this handler is misused later.
1183 mutex_locker_t lock(DebugLock);
1184
1185 token = DebugCounter++;
1186 if (token == 0) token = DebugCounter++;
1187
1188 if (!data->debug) {
1189 data->debug = (struct alt_handler_debug *)
1190 calloc(sizeof(*data->debug), 1);
1191 } else {
1192 bzero(data->debug, sizeof(*data->debug));
1193 }
1194
1195 pthread_getname_np(pthread_self(), data->debug->thread, THREADNAME_COUNT);
1196 strlcpy(data->debug->queue,
1197 dispatch_queue_get_label(dispatch_get_current_queue()),
1198 THREADNAME_COUNT);
1199 data->debug->backtraceSize =
1200 backtrace(data->debug->backtrace, BACKTRACE_COUNT);
1201 data->debug->token = token;
1202 }
1203
1204 if (PrintAltHandlers) {
1205 _objc_inform("ALT HANDLERS: installing alt handler #%lu %p(%p) on "
1206 "frame [ip=%p..%p sp=%p]", (unsigned long)token,
1207 data->fn, data->context, (void *)data->frame.ip_start,
1208 (void *)data->frame.ip_end, (void *)data->frame.cfa);
1209 if (data->frame.ips) {
1210 unsigned int r = 0;
1211 while (1) {
1212 uintptr_t start = data->frame.ips[r].start;
1213 uintptr_t end = data->frame.ips[r].end;
1214 r++;
1215 if (start == 0 && end == 0) break;
1216 _objc_inform("ALT HANDLERS: ip=%p..%p",
1217 (void*)start, (void*)end);
1218 }
1219 }
1220 }
1221
1222 if (list->used > 1000) {
1223 static int warned = 0;
1224 if (!warned) {
1225 _objc_inform("ALT HANDLERS: *** over 1000 alt handlers installed; "
1226 "this is probably a bug");
1227 warned = 1;
1228 }
1229 }
1230
1231 return token;
1232 }
1233
1234
1235 void objc_removeExceptionHandler(uintptr_t token)
1236 {
1237 if (!token) {
1238 // objc_addExceptionHandler failed
1239 return;
1240 }
1241
1242 struct alt_handler_list *list = fetch_handler_list(NO);
1243 if (!list || !list->handlers) {
1244 // no alt handlers active
1245 alt_handler_error(token);
1246 __builtin_trap();
1247 }
1248
1249 uintptr_t i = token-1;
1250
1251 if (DebugAltHandlers) {
1252 // search for the token instead of using token-1
1253 for (i = 0; i < list->allocated; i++) {
1254 struct alt_handler_data *data = &list->handlers[i];
1255 if (data->debug && data->debug->token == token) break;
1256 }
1257 }
1258
1259 if (i >= list->allocated) {
1260 // token out of range
1261 alt_handler_error(token);
1262 __builtin_trap();
1263 }
1264
1265 struct alt_handler_data *data = &list->handlers[i];
1266
1267 if (data->frame.ip_start == 0 && data->frame.ip_end == 0 && data->frame.cfa == 0) {
1268 // token in range, but invalid
1269 alt_handler_error(token);
1270 __builtin_trap();
1271 }
1272
1273 if (PrintAltHandlers) {
1274 _objc_inform("ALT HANDLERS: removing alt handler #%lu %p(%p) on "
1275 "frame [ip=%p..%p sp=%p]", (unsigned long)token,
1276 data->fn, data->context, (void *)data->frame.ip_start,
1277 (void *)data->frame.ip_end, (void *)data->frame.cfa);
1278 }
1279
1280 if (data->debug) free(data->debug);
1281 if (data->frame.ips) free(data->frame.ips);
1282 bzero(data, sizeof(*data));
1283 list->used--;
1284 }
1285
1286 void objc_alt_handler_error(void) __attribute__((noinline));
1287
1288 void alt_handler_error(uintptr_t token)
1289 {
1290 if (!DebugAltHandlers) {
1291 _objc_inform_now_and_on_crash
1292 ("objc_removeExceptionHandler() called with unknown alt handler; "
1293 "this is probably a bug in multithreaded AppKit use. "
1294 "Set environment variable OBJC_DEBUG_ALT_HANDLERS=YES "
1295 "or break in objc_alt_handler_error() to debug.");
1296 objc_alt_handler_error();
1297 }
1298
1299 DebugLock.lock();
1300
1301 // Search other threads' alt handler lists for this handler.
1302 struct alt_handler_list *list;
1303 for (list = DebugLists; list; list = list->next_DEBUGONLY) {
1304 unsigned h;
1305 for (h = 0; h < list->allocated; h++) {
1306 struct alt_handler_data *data = &list->handlers[h];
1307 if (data->debug && data->debug->token == token) {
1308 // found it
1309 int i;
1310
1311 // Build a string from the recorded backtrace
1312 char *symbolString;
1313 char **symbols =
1314 backtrace_symbols(data->debug->backtrace,
1315 data->debug->backtraceSize);
1316 size_t len = 1;
1317 for (i = 0; i < data->debug->backtraceSize; i++){
1318 len += 4 + strlen(symbols[i]) + 1;
1319 }
1320 symbolString = (char *)calloc(len, 1);
1321 for (i = 0; i < data->debug->backtraceSize; i++){
1322 strcat(symbolString, " ");
1323 strcat(symbolString, symbols[i]);
1324 strcat(symbolString, "\n");
1325 }
1326
1327 free(symbols);
1328
1329 _objc_inform_now_and_on_crash
1330 ("objc_removeExceptionHandler() called with "
1331 "unknown alt handler; this is probably a bug in "
1332 "multithreaded AppKit use. \n"
1333 "The matching objc_addExceptionHandler() was called by:\n"
1334 "Thread '%s': Dispatch queue: '%s': \n%s",
1335 data->debug->thread, data->debug->queue, symbolString);
1336
1337 DebugLock.unlock();
1338 free(symbolString);
1339
1340 objc_alt_handler_error();
1341 }
1342 }
1343 }
1344
1345 DebugLock.unlock();
1346
1347 // not found
1348 _objc_inform_now_and_on_crash
1349 ("objc_removeExceptionHandler() called with unknown alt handler; "
1350 "this is probably a bug in multithreaded AppKit use");
1351 objc_alt_handler_error();
1352 }
1353
1354 void objc_alt_handler_error(void)
1355 {
1356 __builtin_trap();
1357 }
1358
1359 // called in order registered, to match 32-bit _NSAddAltHandler2
1360 // fixme reverse registration order matches c++ destructors better
1361 static void call_alt_handlers(struct _Unwind_Context *ctx)
1362 {
1363 uintptr_t ip = _Unwind_GetIP(ctx) - 1;
1364 uintptr_t cfa = _Unwind_GetCFA(ctx);
1365 unsigned int i;
1366
1367 struct alt_handler_list *list = fetch_handler_list(NO);
1368 if (!list || list->used == 0) return;
1369
1370 for (i = 0; i < list->allocated; i++) {
1371 struct alt_handler_data *data = &list->handlers[i];
1372 if (ip >= data->frame.ip_start && ip < data->frame.ip_end && data->frame.cfa == cfa)
1373 {
1374 if (data->frame.ips) {
1375 unsigned int r = 0;
1376 bool found;
1377 while (1) {
1378 uintptr_t start = data->frame.ips[r].start;
1379 uintptr_t end = data->frame.ips[r].end;
1380 r++;
1381 if (start == 0 && end == 0) {
1382 found = false;
1383 break;
1384 }
1385 if (ip >= start && ip < end) {
1386 found = true;
1387 break;
1388 }
1389 }
1390 if (!found) continue;
1391 }
1392
1393 // Copy and clear before the callback, in case the
1394 // callback manipulates the alt handler list.
1395 struct alt_handler_data copy = *data;
1396 bzero(data, sizeof(*data));
1397 list->used--;
1398 if (PrintExceptions || PrintAltHandlers) {
1399 _objc_inform("EXCEPTIONS: calling alt handler %p(%p) from "
1400 "frame [ip=%p..%p sp=%p]", copy.fn, copy.context,
1401 (void *)copy.frame.ip_start,
1402 (void *)copy.frame.ip_end,
1403 (void *)copy.frame.cfa);
1404 }
1405 if (copy.fn) (*copy.fn)(nil, copy.context);
1406 if (copy.frame.ips) free(copy.frame.ips);
1407 }
1408 }
1409 }
1410
1411 // SUPPORT_ALT_HANDLERS
1412 #endif
1413
1414
1415 /***********************************************************************
1416 * exception_init
1417 * Initialize libobjc's exception handling system.
1418 * Called by map_images().
1419 **********************************************************************/
1420 void exception_init(void)
1421 {
1422 old_terminate = std::set_terminate(&_objc_terminate);
1423 }
1424
1425
1426 // __OBJC2__
1427 #endif