-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathobjc-exception.mm
1434 lines (1198 loc) · 43.9 KB
/
objc-exception.mm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2002-2007 Apple Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
#if !__OBJC2__
/***********************************************************************
* 32-bit implementation
**********************************************************************/
#include "objc-private.h"
#include <stdlib.h>
#include <setjmp.h>
#include <execinfo.h>
#include "objc-exception.h"
static objc_exception_functions_t xtab;
// forward declaration
static void set_default_handlers();
/*
* Exported functions
*/
// get table; version tells how many
void objc_exception_get_functions(objc_exception_functions_t *table) {
// only version 0 supported at this point
if (table && table->version == 0)
*table = xtab;
}
// set table
void objc_exception_set_functions(objc_exception_functions_t *table) {
// only version 0 supported at this point
if (table && table->version == 0)
xtab = *table;
}
/*
* The following functions are
* synthesized by the compiler upon encountering language constructs
*/
void objc_exception_throw(id exception) {
if (!xtab.throw_exc) {
set_default_handlers();
}
if (PrintExceptionThrow) {
_objc_inform("EXCEPTIONS: throwing %p (%s)",
(void*)exception, object_getClassName(exception));
void* callstack[500];
int frameCount = backtrace(callstack, 500);
backtrace_symbols_fd(callstack, frameCount, fileno(stderr));
}
OBJC_RUNTIME_OBJC_EXCEPTION_THROW(exception); // dtrace probe to log throw activity.
xtab.throw_exc(exception);
_objc_fatal("objc_exception_throw failed");
}
void objc_exception_try_enter(void *localExceptionData) {
if (!xtab.throw_exc) {
set_default_handlers();
}
xtab.try_enter(localExceptionData);
}
void objc_exception_try_exit(void *localExceptionData) {
if (!xtab.throw_exc) {
set_default_handlers();
}
xtab.try_exit(localExceptionData);
}
id objc_exception_extract(void *localExceptionData) {
if (!xtab.throw_exc) {
set_default_handlers();
}
return xtab.extract(localExceptionData);
}
int objc_exception_match(Class exceptionClass, id exception) {
if (!xtab.throw_exc) {
set_default_handlers();
}
return xtab.match(exceptionClass, exception);
}
// quick and dirty exception handling code
// default implementation - mostly a toy for use outside/before Foundation
// provides its implementation
// Perhaps the default implementation should just complain loudly and quit
extern void _objc_inform(const char *fmt, ...);
typedef struct { jmp_buf buf; void *pointers[4]; } LocalData_t;
typedef struct _threadChain {
LocalData_t *topHandler;
objc_thread_t perThreadID;
struct _threadChain *next;
}
ThreadChainLink_t;
static ThreadChainLink_t ThreadChainLink;
static ThreadChainLink_t *getChainLink() {
// follow links until thread_self() found (someday) XXX
objc_thread_t self = thread_self();
ThreadChainLink_t *walker = &ThreadChainLink;
while (walker->perThreadID != self) {
if (walker->next != nil) {
walker = walker->next;
continue;
}
// create a new one
// XXX not thread safe (!)
// XXX Also, we don't register to deallocate on thread death
walker->next = (ThreadChainLink_t *)malloc(sizeof(ThreadChainLink_t));
walker = walker->next;
walker->next = nil;
walker->topHandler = nil;
walker->perThreadID = self;
}
return walker;
}
static void default_try_enter(void *localExceptionData) {
LocalData_t *data = (LocalData_t *)localExceptionData;
ThreadChainLink_t *chainLink = getChainLink();
data->pointers[1] = chainLink->topHandler;
chainLink->topHandler = data;
if (PrintExceptions) _objc_inform("EXCEPTIONS: entered try block %p\n", chainLink->topHandler);
}
static void default_throw(id value) {
ThreadChainLink_t *chainLink = getChainLink();
LocalData_t *led;
if (value == nil) {
if (PrintExceptions) _objc_inform("EXCEPTIONS: objc_exception_throw with nil value\n");
return;
}
if (chainLink == nil) {
if (PrintExceptions) _objc_inform("EXCEPTIONS: No handler in place!\n");
return;
}
if (PrintExceptions) _objc_inform("EXCEPTIONS: exception thrown, going to handler block %p\n", chainLink->topHandler);
led = chainLink->topHandler;
chainLink->topHandler = (LocalData_t *)
led->pointers[1]; // pop top handler
led->pointers[0] = value; // store exception that is thrown
#if TARGET_OS_WIN32
longjmp(led->buf, 1);
#else
_longjmp(led->buf, 1);
#endif
}
static void default_try_exit(void *led) {
ThreadChainLink_t *chainLink = getChainLink();
if (!chainLink || led != chainLink->topHandler) {
if (PrintExceptions) _objc_inform("EXCEPTIONS: *** mismatched try block exit handlers\n");
return;
}
if (PrintExceptions) _objc_inform("EXCEPTIONS: removing try block handler %p\n", chainLink->topHandler);
chainLink->topHandler = (LocalData_t *)
chainLink->topHandler->pointers[1]; // pop top handler
}
static id default_extract(void *localExceptionData) {
LocalData_t *led = (LocalData_t *)localExceptionData;
return (id)led->pointers[0];
}
static int default_match(Class exceptionClass, id exception) {
//return [exception isKindOfClass:exceptionClass];
Class cls;
for (cls = exception->getIsa(); nil != cls; cls = cls->superclass)
if (cls == exceptionClass) return 1;
return 0;
}
static void set_default_handlers() {
objc_exception_functions_t default_functions = {
0, default_throw, default_try_enter, default_try_exit, default_extract, default_match };
// should this always print?
if (PrintExceptions) _objc_inform("EXCEPTIONS: *** Setting default (non-Foundation) exception mechanism\n");
objc_exception_set_functions(&default_functions);
}
void exception_init(void)
{
// nothing to do
}
void _destroyAltHandlerList(struct alt_handler_list *list)
{
// nothing to do
}
// !__OBJC2__
#else
// __OBJC2__
/***********************************************************************
* 64-bit implementation.
**********************************************************************/
#include "objc-private.h"
#include <objc/objc-abi.h>
#include <objc/objc-exception.h>
#include <objc/NSObject.h>
#include <execinfo.h>
// unwind library types and functions
// Mostly adapted from Itanium C++ ABI: Exception Handling
// http://www.codesourcery.com/cxx-abi/abi-eh.html
struct _Unwind_Exception;
struct _Unwind_Context;
typedef int _Unwind_Action;
enum : _Unwind_Action {
_UA_SEARCH_PHASE = 1,
_UA_CLEANUP_PHASE = 2,
_UA_HANDLER_FRAME = 4,
_UA_FORCE_UNWIND = 8
};
typedef int _Unwind_Reason_Code;
enum : _Unwind_Reason_Code {
_URC_NO_REASON = 0,
_URC_FOREIGN_EXCEPTION_CAUGHT = 1,
_URC_FATAL_PHASE2_ERROR = 2,
_URC_FATAL_PHASE1_ERROR = 3,
_URC_NORMAL_STOP = 4,
_URC_END_OF_STACK = 5,
_URC_HANDLER_FOUND = 6,
_URC_INSTALL_CONTEXT = 7,
_URC_CONTINUE_UNWIND = 8
};
struct dwarf_eh_bases
{
uintptr_t tbase;
uintptr_t dbase;
uintptr_t func;
};
OBJC_EXTERN uintptr_t _Unwind_GetIP (struct _Unwind_Context *);
OBJC_EXTERN uintptr_t _Unwind_GetCFA (struct _Unwind_Context *);
OBJC_EXTERN uintptr_t _Unwind_GetLanguageSpecificData(struct _Unwind_Context *);
// C++ runtime types and functions
// copied from cxxabi.h
OBJC_EXTERN void *__cxa_allocate_exception(size_t thrown_size);
OBJC_EXTERN void __cxa_throw(void *exc, void *typeinfo, void (*destructor)(void *)) __attribute__((noreturn));
OBJC_EXTERN void *__cxa_begin_catch(void *exc);
OBJC_EXTERN void __cxa_end_catch(void);
OBJC_EXTERN void __cxa_rethrow(void);
OBJC_EXTERN void *__cxa_current_exception_type(void);
#if SUPPORT_ZEROCOST_EXCEPTIONS
# define CXX_PERSONALITY __gxx_personality_v0
#else
# define CXX_PERSONALITY __gxx_personality_sj0
#endif
OBJC_EXTERN _Unwind_Reason_Code
CXX_PERSONALITY(int version,
_Unwind_Action actions,
uint64_t exceptionClass,
struct _Unwind_Exception *exceptionObject,
struct _Unwind_Context *context);
// objc's internal exception types and data
struct objc_typeinfo {
// Position of vtable and name fields must match C++ typeinfo object
const void ** __ptrauth_cxx_vtable_pointer vtable; // objc_ehtype_vtable+2
const char *name; // c++ typeinfo string
Class cls_unremapped;
};
struct objc_exception {
id obj;
struct objc_typeinfo tinfo;
};
extern "C" void _objc_exception_noop(void) { }
extern "C" bool _objc_exception_false(void) { return 0; }
// extern "C" bool _objc_exception_true(void) { return 1; }
extern "C" void _objc_exception_abort1(void) {
_objc_fatal("unexpected call into objc exception typeinfo vtable %d", 1);
}
extern "C" void _objc_exception_abort2(void) {
_objc_fatal("unexpected call into objc exception typeinfo vtable %d", 2);
}
extern "C" void _objc_exception_abort3(void) {
_objc_fatal("unexpected call into objc exception typeinfo vtable %d", 3);
}
extern "C" void _objc_exception_abort4(void) {
_objc_fatal("unexpected call into objc exception typeinfo vtable %d", 4);
}
extern "C" bool _objc_exception_do_catch(struct objc_typeinfo *catch_tinfo,
struct objc_typeinfo *throw_tinfo,
void **throw_obj_p,
unsigned outer);
// C++ pointers to vtables are signed with no extra data.
// C++ vtable entries are signed with a number derived from the function name.
// For this fake vtable, we hardcode number as deciphered from the
// assembly output during libc++abi's build.
#if __has_feature(ptrauth_calls)
# define VTABLE_PTR_AUTH "@AUTH(da, 0)"
# define VTABLE_ENTRY_AUTH(x) "@AUTH(ia," #x ",addr)"
#else
# define VTABLE_PTR_AUTH ""
# define VTABLE_ENTRY_AUTH(x) ""
#endif
#if __LP64__
# define PTR ".quad "
# define TWOPTRSIZE "16"
#else
# define PTR ".long "
# define TWOPTRSIZE "8"
#endif
// Hand-built vtable for objc exception typeinfo.
// "OLD" is GNU libcpp, "NEW" is libc++abi.
asm(
"\n .cstring"
"\n l_.id_str: .asciz \"id\""
"\n .section __DATA,__const"
"\n .globl _OBJC_EHTYPE_id"
"\n .globl _objc_ehtype_vtable"
"\n .p2align 4"
"\n _OBJC_EHTYPE_id:"
"\n " PTR "(_objc_ehtype_vtable+" TWOPTRSIZE ") " VTABLE_PTR_AUTH
"\n " PTR "l_.id_str"
"\n " PTR "0"
"\n _objc_ehtype_vtable:"
"\n " PTR "0"
// typeinfo's typeinfo - fixme hack
"\n " PTR "_OBJC_EHTYPE_id"
// destructor and in-place destructor
"\n " PTR "__objc_exception_noop" VTABLE_ENTRY_AUTH(52634)
"\n " PTR "__objc_exception_noop" VTABLE_ENTRY_AUTH(10344)
// OLD __is_pointer_p
"\n " PTR "__objc_exception_noop" VTABLE_ENTRY_AUTH(6889)
// OLD __is_function_p
"\n " PTR "__objc_exception_noop" VTABLE_ENTRY_AUTH(23080)
// OLD __do_catch, NEW can_catch
"\n " PTR "__objc_exception_do_catch" VTABLE_ENTRY_AUTH(27434)
// OLD __do_upcast, NEW search_above_dst
"\n " PTR "__objc_exception_false" VTABLE_ENTRY_AUTH(48481)
// NEW search_below_dst
"\n " PTR "__objc_exception_false" VTABLE_ENTRY_AUTH(41165)
// NEW has_unambiguous_public_base (fixme need this?)
"\n " PTR "__objc_exception_abort1" VTABLE_ENTRY_AUTH(14357)
// paranoia: die if libcxxabi adds anything else
"\n " PTR "__objc_exception_abort2"
"\n " PTR "__objc_exception_abort3"
"\n " PTR "__objc_exception_abort4"
);
/***********************************************************************
* Foundation customization
**********************************************************************/
/***********************************************************************
* _objc_default_exception_preprocessor
* Default exception preprocessor. Expected to be overridden by Foundation.
**********************************************************************/
static id _objc_default_exception_preprocessor(id exception)
{
return exception;
}
static objc_exception_preprocessor exception_preprocessor = _objc_default_exception_preprocessor;
/***********************************************************************
* _objc_default_exception_matcher
* Default exception matcher. Expected to be overridden by Foundation.
**********************************************************************/
static int _objc_default_exception_matcher(Class catch_cls, id exception)
{
Class cls;
for (cls = exception->getIsa();
cls != nil;
cls = cls->superclass)
{
if (cls == catch_cls) return 1;
}
return 0;
}
static objc_exception_matcher exception_matcher = _objc_default_exception_matcher;
/***********************************************************************
* _objc_default_uncaught_exception_handler
* Default uncaught exception handler. Expected to be overridden by Foundation.
**********************************************************************/
static void _objc_default_uncaught_exception_handler(id exception)
{
}
static objc_uncaught_exception_handler uncaught_handler = _objc_default_uncaught_exception_handler;
/***********************************************************************
* objc_setExceptionPreprocessor
* Set a handler for preprocessing Objective-C exceptions.
* Returns the previous handler.
**********************************************************************/
objc_exception_preprocessor
objc_setExceptionPreprocessor(objc_exception_preprocessor fn)
{
objc_exception_preprocessor result = exception_preprocessor;
exception_preprocessor = fn;
return result;
}
/***********************************************************************
* objc_setExceptionMatcher
* Set a handler for matching Objective-C exceptions.
* Returns the previous handler.
**********************************************************************/
objc_exception_matcher
objc_setExceptionMatcher(objc_exception_matcher fn)
{
objc_exception_matcher result = exception_matcher;
exception_matcher = fn;
return result;
}
/***********************************************************************
* objc_setUncaughtExceptionHandler
* Set a handler for uncaught Objective-C exceptions.
* Returns the previous handler.
**********************************************************************/
objc_uncaught_exception_handler
objc_setUncaughtExceptionHandler(objc_uncaught_exception_handler fn)
{
objc_uncaught_exception_handler result = uncaught_handler;
uncaught_handler = fn;
return result;
}
/***********************************************************************
* Exception personality
**********************************************************************/
static void call_alt_handlers(struct _Unwind_Context *ctx);
_Unwind_Reason_Code
__objc_personality_v0(int version,
_Unwind_Action actions,
uint64_t exceptionClass,
struct _Unwind_Exception *exceptionObject,
struct _Unwind_Context *context)
{
bool unwinding = ((actions & _UA_CLEANUP_PHASE) ||
(actions & _UA_FORCE_UNWIND));
if (PrintExceptions) {
_objc_inform("EXCEPTIONS: %s through frame [ip=%p sp=%p] "
"for exception %p",
unwinding ? "unwinding" : "searching",
(void*)(_Unwind_GetIP(context)-1),
(void*)_Unwind_GetCFA(context), exceptionObject);
}
// If we're executing the unwind, call this frame's alt handlers, if any.
if (unwinding) {
call_alt_handlers(context);
}
// Let C++ handle the unwind itself.
return CXX_PERSONALITY(version, actions, exceptionClass,
exceptionObject, context);
}
/***********************************************************************
* Compiler ABI
**********************************************************************/
static void _objc_exception_destructor(void *exc_gen)
{
// Release the retain from objc_exception_throw().
struct objc_exception *exc = (struct objc_exception *)exc_gen;
id obj = exc->obj;
if (PrintExceptions) {
_objc_inform("EXCEPTIONS: releasing completed exception %p (object %p, a %s)",
exc, obj, object_getClassName(obj));
}
[obj release];
}
void objc_exception_throw(id obj)
{
struct objc_exception *exc = (struct objc_exception *)
__cxa_allocate_exception(sizeof(struct objc_exception));
obj = (*exception_preprocessor)(obj);
// Retain the exception object during unwinding
// because otherwise an autorelease pool pop can cause a crash
[obj retain];
exc->obj = obj;
exc->tinfo.vtable = objc_ehtype_vtable+2;
exc->tinfo.name = object_getClassName(obj);
exc->tinfo.cls_unremapped = obj ? obj->getIsa() : Nil;
if (PrintExceptions) {
_objc_inform("EXCEPTIONS: throwing %p (object %p, a %s)",
exc, (void*)obj, object_getClassName(obj));
}
if (PrintExceptionThrow) {
if (!PrintExceptions)
_objc_inform("EXCEPTIONS: throwing %p (object %p, a %s)",
exc, (void*)obj, object_getClassName(obj));
void* callstack[500];
int frameCount = backtrace(callstack, 500);
backtrace_symbols_fd(callstack, frameCount, fileno(stderr));
}
OBJC_RUNTIME_OBJC_EXCEPTION_THROW(obj); // dtrace probe to log throw activity
__cxa_throw(exc, &exc->tinfo, &_objc_exception_destructor);
// __builtin_trap();
}
void objc_exception_rethrow(void)
{
// exception_preprocessor doesn't get another bite of the apple
if (PrintExceptions) {
_objc_inform("EXCEPTIONS: rethrowing current exception");
}
OBJC_RUNTIME_OBJC_EXCEPTION_RETHROW(); // dtrace probe to log throw activity.
__cxa_rethrow();
__builtin_trap();
}
id objc_begin_catch(void *exc_gen)
{
if (PrintExceptions) {
_objc_inform("EXCEPTIONS: handling exception %p at %p",
exc_gen, __builtin_return_address(0));
}
// NOT actually an id in the catch(...) case!
return (id)__cxa_begin_catch(exc_gen);
}
void objc_end_catch(void)
{
if (PrintExceptions) {
_objc_inform("EXCEPTIONS: finishing handler");
}
__cxa_end_catch();
}
// `outer` is not passed by the new libcxxabi
bool _objc_exception_do_catch(struct objc_typeinfo *catch_tinfo,
struct objc_typeinfo *throw_tinfo,
void **throw_obj_p,
unsigned outer UNAVAILABLE_ATTRIBUTE)
{
id exception;
if (throw_tinfo->vtable != objc_ehtype_vtable+2) {
// Only objc types can be caught here.
if (PrintExceptions) _objc_inform("EXCEPTIONS: skipping catch(?)");
return false;
}
// Adjust exception pointer.
// Old libcppabi: we lied about __is_pointer_p() so we have to do it here
// New libcxxabi: we have to do it here regardless
*throw_obj_p = **(void***)throw_obj_p;
// `catch (id)` always catches objc types.
if (catch_tinfo == &OBJC_EHTYPE_id) {
if (PrintExceptions) _objc_inform("EXCEPTIONS: catch(id)");
return true;
}
exception = *(id *)throw_obj_p;
Class handler_cls = _class_remap(catch_tinfo->cls_unremapped);
if (!handler_cls) {
// catch handler's class is weak-linked and missing. Not a match.
}
else if ((*exception_matcher)(handler_cls, exception)) {
if (PrintExceptions) _objc_inform("EXCEPTIONS: catch(%s)",
handler_cls->nameForLogging());
return true;
}
if (PrintExceptions) _objc_inform("EXCEPTIONS: skipping catch(%s)",
handler_cls->nameForLogging());
return false;
}
/***********************************************************************
* _objc_terminate
* Custom std::terminate handler.
*
* The uncaught exception callback is implemented as a std::terminate handler.
* 1. Check if there's an active exception
* 2. If so, check if it's an Objective-C exception
* 3. If so, call our registered callback with the object.
* 4. Finally, call the previous terminate handler.
**********************************************************************/
static void (*old_terminate)(void) = nil;
static void _objc_terminate(void)
{
if (PrintExceptions) {
_objc_inform("EXCEPTIONS: terminating");
}
if (! __cxa_current_exception_type()) {
// No current exception.
(*old_terminate)();
}
else {
// There is a current exception. Check if it's an objc exception.
@try {
__cxa_rethrow();
} @catch (id e) {
// It's an objc object. Call Foundation's handler, if any.
(*uncaught_handler)((id)e);
(*old_terminate)();
} @catch (...) {
// It's not an objc object. Continue to C++ terminate.
(*old_terminate)();
}
}
}
/***********************************************************************
* objc_terminate
* Calls std::terminate for clients who don't link to C++ themselves.
* Called by the compiler if an exception is thrown
* from a context where exceptions may not be thrown.
**********************************************************************/
void objc_terminate(void)
{
std::terminate();
}
/***********************************************************************
* alt handler support - zerocost implementation only
**********************************************************************/
#if !SUPPORT_ALT_HANDLERS
void _destroyAltHandlerList(struct alt_handler_list *list)
{
}
static void call_alt_handlers(struct _Unwind_Context *ctx)
{
// unsupported in sjlj environments
}
#else
#include <libunwind.h>
#include <execinfo.h>
#include <dispatch/dispatch.h>
// Dwarf eh data encodings
#define DW_EH_PE_omit 0xff // no data follows
#define DW_EH_PE_absptr 0x00
#define DW_EH_PE_uleb128 0x01
#define DW_EH_PE_udata2 0x02
#define DW_EH_PE_udata4 0x03
#define DW_EH_PE_udata8 0x04
#define DW_EH_PE_sleb128 0x09
#define DW_EH_PE_sdata2 0x0A
#define DW_EH_PE_sdata4 0x0B
#define DW_EH_PE_sdata8 0x0C
#define DW_EH_PE_pcrel 0x10
#define DW_EH_PE_textrel 0x20
#define DW_EH_PE_datarel 0x30
#define DW_EH_PE_funcrel 0x40
#define DW_EH_PE_aligned 0x50 // fixme
#define DW_EH_PE_indirect 0x80 // gcc extension
/***********************************************************************
* read_uleb
* Read a LEB-encoded unsigned integer from the address stored in *pp.
* Increments *pp past the bytes read.
* Adapted from DWARF Debugging Information Format 1.1, appendix 4
**********************************************************************/
static uintptr_t read_uleb(uintptr_t *pp)
{
uintptr_t result = 0;
uintptr_t shift = 0;
unsigned char byte;
do {
byte = *(const unsigned char *)(*pp)++;
result |= (byte & 0x7f) << shift;
shift += 7;
} while (byte & 0x80);
return result;
}
/***********************************************************************
* read_sleb
* Read a LEB-encoded signed integer from the address stored in *pp.
* Increments *pp past the bytes read.
* Adapted from DWARF Debugging Information Format 1.1, appendix 4
**********************************************************************/
static intptr_t read_sleb(uintptr_t *pp)
{
uintptr_t result = 0;
uintptr_t shift = 0;
unsigned char byte;
do {
byte = *(const unsigned char *)(*pp)++;
result |= (byte & 0x7f) << shift;
shift += 7;
} while (byte & 0x80);
if ((shift < 8*sizeof(intptr_t)) && (byte & 0x40)) {
result |= ((intptr_t)-1) << shift;
}
return result;
}
/***********************************************************************
* read_address
* Reads an encoded address from the address stored in *pp.
* Increments *pp past the bytes read.
* The data is interpreted according to the given dwarf encoding
* and base addresses.
**********************************************************************/
static uintptr_t read_address(uintptr_t *pp,
const struct dwarf_eh_bases *bases,
unsigned char encoding)
{
uintptr_t result = 0;
uintptr_t oldp = *pp;
// fixme need DW_EH_PE_aligned?
#define READ(type) \
result = *(type *)(*pp); \
*pp += sizeof(type);
if (encoding == DW_EH_PE_omit) return 0;
switch (encoding & 0x0f) {
case DW_EH_PE_absptr:
READ(uintptr_t);
break;
case DW_EH_PE_uleb128:
result = read_uleb(pp);
break;
case DW_EH_PE_udata2:
READ(uint16_t);
break;
case DW_EH_PE_udata4:
READ(uint32_t);
break;
#if __LP64__
case DW_EH_PE_udata8:
READ(uint64_t);
break;
#endif
case DW_EH_PE_sleb128:
result = read_sleb(pp);
break;
case DW_EH_PE_sdata2:
READ(int16_t);
break;
case DW_EH_PE_sdata4:
READ(int32_t);
break;
#if __LP64__
case DW_EH_PE_sdata8:
READ(int64_t);
break;
#endif
default:
_objc_inform("unknown DWARF EH encoding 0x%x at %p",
encoding, (void *)*pp);
break;
}
#undef READ
if (result) {
switch (encoding & 0x70) {
case DW_EH_PE_pcrel:
// fixme correct?
result += (uintptr_t)oldp;
break;
case DW_EH_PE_textrel:
result += bases->tbase;
break;
case DW_EH_PE_datarel:
result += bases->dbase;
break;
case DW_EH_PE_funcrel:
result += bases->func;
break;
case DW_EH_PE_aligned:
_objc_inform("unknown DWARF EH encoding 0x%x at %p",
encoding, (void *)*pp);
break;
default:
// no adjustment
break;
}
if (encoding & DW_EH_PE_indirect) {
result = *(uintptr_t *)result;
}
}
return (uintptr_t)result;
}
struct frame_ips {
uintptr_t start;
uintptr_t end;
};
struct frame_range {
uintptr_t ip_start;
uintptr_t ip_end;
uintptr_t cfa;
// precise ranges within ip_start..ip_end; nil or {0,0} terminated
frame_ips *ips;
};
static bool isObjCExceptionCatcher(uintptr_t lsda, uintptr_t ip,
const struct dwarf_eh_bases* bases,
struct frame_range *frame)
{
unsigned char LPStart_enc = *(const unsigned char *)lsda++;
if (LPStart_enc != DW_EH_PE_omit) {
read_address(&lsda, bases, LPStart_enc); // LPStart
}
unsigned char TType_enc = *(const unsigned char *)lsda++;
if (TType_enc != DW_EH_PE_omit) {
read_uleb(&lsda); // TType
}
unsigned char call_site_enc = *(const unsigned char *)lsda++;
uintptr_t length = read_uleb(&lsda);
uintptr_t call_site_table = lsda;
uintptr_t call_site_table_end = call_site_table + length;
uintptr_t action_record_table = call_site_table_end;
uintptr_t action_record = 0;
uintptr_t p = call_site_table;
uintptr_t try_start;
uintptr_t try_end;
uintptr_t try_landing_pad;
while (p < call_site_table_end) {
uintptr_t start = read_address(&p, bases, call_site_enc)+bases->func;
uintptr_t len = read_address(&p, bases, call_site_enc);
uintptr_t pad = read_address(&p, bases, call_site_enc);
uintptr_t action = read_uleb(&p);
if (ip < start) {
// no more source ranges
return false;
}
else if (ip < start + len) {
// found the range
if (!pad) return false; // ...but it has no landing pad
// found the landing pad
action_record = action ? action_record_table + action - 1 : 0;
try_start = start;
try_end = start + len;
try_landing_pad = pad;
break;
}
}
if (!action_record) return false; // no catch handlers
// has handlers, destructors, and/or throws specifications
// Use this frame if it has any handlers
bool has_handler = false;
p = action_record;
intptr_t offset;
do {
intptr_t filter = read_sleb(&p);
uintptr_t temp = p;
offset = read_sleb(&temp);
p += offset;
if (filter < 0) {
// throws specification - ignore
} else if (filter == 0) {
// destructor - ignore
} else /* filter >= 0 */ {
// catch handler - use this frame
has_handler = true;
break;
}
} while (offset);
if (!has_handler) return false;
// Count the number of source ranges with the same landing pad as our match
unsigned int range_count = 0;
p = call_site_table;
while (p < call_site_table_end) {
/*start*/ read_address(&p, bases, call_site_enc)/*+bases->func*/;
/*len*/ read_address(&p, bases, call_site_enc);
uintptr_t pad = read_address(&p, bases, call_site_enc);
/*action*/ read_uleb(&p);
if (pad == try_landing_pad) {
range_count++;
}
}
if (range_count == 1) {
// No other source ranges with the same landing pad. We're done here.
frame->ips = nil;