-
Notifications
You must be signed in to change notification settings - Fork 11.6k
/
AppleObjCRuntimeV2.cpp
2696 lines (2293 loc) · 96.8 KB
/
AppleObjCRuntimeV2.cpp
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
//===-- AppleObjCRuntimeV2.cpp ----------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include <stdint.h>
#include <memory>
#include <string>
#include <vector>
#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclObjC.h"
#include "lldb/Core/ClangForward.h"
#include "lldb/Host/OptionParser.h"
#include "lldb/Symbol/CompilerType.h"
#include "lldb/lldb-enumerations.h"
#include "lldb/Core/ClangForward.h"
#include "lldb/Core/Debugger.h"
#include "lldb/Core/Module.h"
#include "lldb/Core/PluginManager.h"
#include "lldb/Core/Section.h"
#include "lldb/Core/ValueObjectConstResult.h"
#include "lldb/Core/ValueObjectVariable.h"
#include "lldb/Expression/DiagnosticManager.h"
#include "lldb/Expression/FunctionCaller.h"
#include "lldb/Expression/UtilityFunction.h"
#include "lldb/Interpreter/CommandObject.h"
#include "lldb/Interpreter/CommandObjectMultiword.h"
#include "lldb/Interpreter/CommandReturnObject.h"
#include "lldb/Interpreter/OptionArgParser.h"
#include "lldb/Interpreter/OptionValueBoolean.h"
#include "lldb/Symbol/ClangASTContext.h"
#include "lldb/Symbol/ObjectFile.h"
#include "lldb/Symbol/Symbol.h"
#include "lldb/Symbol/TypeList.h"
#include "lldb/Symbol/VariableList.h"
#include "lldb/Target/ABI.h"
#include "lldb/Target/ExecutionContext.h"
#include "lldb/Target/Platform.h"
#include "lldb/Target/Process.h"
#include "lldb/Target/RegisterContext.h"
#include "lldb/Target/StackFrameRecognizer.h"
#include "lldb/Target/Target.h"
#include "lldb/Target/Thread.h"
#include "lldb/Utility/ConstString.h"
#include "lldb/Utility/Log.h"
#include "lldb/Utility/Scalar.h"
#include "lldb/Utility/Status.h"
#include "lldb/Utility/Stream.h"
#include "lldb/Utility/StreamString.h"
#include "lldb/Utility/Timer.h"
#include "AppleObjCClassDescriptorV2.h"
#include "AppleObjCDeclVendor.h"
#include "AppleObjCRuntimeV2.h"
#include "AppleObjCTrampolineHandler.h"
#include "AppleObjCTypeEncodingParser.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclObjC.h"
#include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h"
#include <vector>
using namespace lldb;
using namespace lldb_private;
char AppleObjCRuntimeV2::ID = 0;
static const char *g_get_dynamic_class_info_name =
"__lldb_apple_objc_v2_get_dynamic_class_info";
// Testing using the new C++11 raw string literals. If this breaks GCC then we
// will need to revert to the code above...
static const char *g_get_dynamic_class_info_body = R"(
extern "C"
{
size_t strlen(const char *);
char *strncpy (char * s1, const char * s2, size_t n);
int printf(const char * format, ...);
}
#define DEBUG_PRINTF(fmt, ...) if (should_log) printf(fmt, ## __VA_ARGS__)
typedef struct _NXMapTable {
void *prototype;
unsigned num_classes;
unsigned num_buckets_minus_one;
void *buckets;
} NXMapTable;
#define NX_MAPNOTAKEY ((void *)(-1))
typedef struct BucketInfo
{
const char *name_ptr;
Class isa;
} BucketInfo;
struct ClassInfo
{
Class isa;
uint32_t hash;
} __attribute__((__packed__));
uint32_t
__lldb_apple_objc_v2_get_dynamic_class_info (void *gdb_objc_realized_classes_ptr,
void *class_infos_ptr,
uint32_t class_infos_byte_size,
uint32_t should_log)
{
DEBUG_PRINTF ("gdb_objc_realized_classes_ptr = %p\n", gdb_objc_realized_classes_ptr);
DEBUG_PRINTF ("class_infos_ptr = %p\n", class_infos_ptr);
DEBUG_PRINTF ("class_infos_byte_size = %u\n", class_infos_byte_size);
const NXMapTable *grc = (const NXMapTable *)gdb_objc_realized_classes_ptr;
if (grc)
{
const unsigned num_classes = grc->num_classes;
if (class_infos_ptr)
{
const size_t max_class_infos = class_infos_byte_size/sizeof(ClassInfo);
ClassInfo *class_infos = (ClassInfo *)class_infos_ptr;
BucketInfo *buckets = (BucketInfo *)grc->buckets;
uint32_t idx = 0;
for (unsigned i=0; i<=grc->num_buckets_minus_one; ++i)
{
if (buckets[i].name_ptr != NX_MAPNOTAKEY)
{
if (idx < max_class_infos)
{
const char *s = buckets[i].name_ptr;
uint32_t h = 5381;
for (unsigned char c = *s; c; c = *++s)
h = ((h << 5) + h) + c;
class_infos[idx].hash = h;
class_infos[idx].isa = buckets[i].isa;
}
++idx;
}
}
if (idx < max_class_infos)
{
class_infos[idx].isa = NULL;
class_infos[idx].hash = 0;
}
}
return num_classes;
}
return 0;
}
)";
// We'll substitute in class_getName or class_getNameRaw depending
// on which is present.
static const char *g_shared_cache_class_name_funcptr = R"(
extern "C"
{
const char *%s(void *objc_class);
const char *(*class_name_lookup_func)(void *) = %s;
}
)";
static const char *g_get_shared_cache_class_info_name =
"__lldb_apple_objc_v2_get_shared_cache_class_info";
// Testing using the new C++11 raw string literals. If this breaks GCC then we
// will need to revert to the code above...
static const char *g_get_shared_cache_class_info_body = R"(
extern "C"
{
size_t strlen(const char *);
char *strncpy (char * s1, const char * s2, size_t n);
int printf(const char * format, ...);
}
#define DEBUG_PRINTF(fmt, ...) if (should_log) printf(fmt, ## __VA_ARGS__)
struct objc_classheader_t {
int32_t clsOffset;
int32_t hiOffset;
};
struct objc_clsopt_t {
uint32_t capacity;
uint32_t occupied;
uint32_t shift;
uint32_t mask;
uint32_t zero;
uint32_t unused;
uint64_t salt;
uint32_t scramble[256];
uint8_t tab[0]; // tab[mask+1]
// uint8_t checkbytes[capacity];
// int32_t offset[capacity];
// objc_classheader_t clsOffsets[capacity];
// uint32_t duplicateCount;
// objc_classheader_t duplicateOffsets[duplicateCount];
};
struct objc_opt_t {
uint32_t version;
int32_t selopt_offset;
int32_t headeropt_offset;
int32_t clsopt_offset;
};
struct objc_opt_v14_t {
uint32_t version;
uint32_t flags;
int32_t selopt_offset;
int32_t headeropt_offset;
int32_t clsopt_offset;
};
struct ClassInfo
{
Class isa;
uint32_t hash;
} __attribute__((__packed__));
uint32_t
__lldb_apple_objc_v2_get_shared_cache_class_info (void *objc_opt_ro_ptr,
void *class_infos_ptr,
uint32_t class_infos_byte_size,
uint32_t should_log)
{
uint32_t idx = 0;
DEBUG_PRINTF ("objc_opt_ro_ptr = %p\n", objc_opt_ro_ptr);
DEBUG_PRINTF ("class_infos_ptr = %p\n", class_infos_ptr);
DEBUG_PRINTF ("class_infos_byte_size = %u (%llu class infos)\n", class_infos_byte_size, (uint64_t)(class_infos_byte_size/sizeof(ClassInfo)));
if (objc_opt_ro_ptr)
{
const objc_opt_t *objc_opt = (objc_opt_t *)objc_opt_ro_ptr;
const objc_opt_v14_t* objc_opt_v14 = (objc_opt_v14_t*)objc_opt_ro_ptr;
const bool is_v14_format = objc_opt->version >= 14;
if (is_v14_format)
{
DEBUG_PRINTF ("objc_opt->version = %u\n", objc_opt_v14->version);
DEBUG_PRINTF ("objc_opt->flags = %u\n", objc_opt_v14->flags);
DEBUG_PRINTF ("objc_opt->selopt_offset = %d\n", objc_opt_v14->selopt_offset);
DEBUG_PRINTF ("objc_opt->headeropt_offset = %d\n", objc_opt_v14->headeropt_offset);
DEBUG_PRINTF ("objc_opt->clsopt_offset = %d\n", objc_opt_v14->clsopt_offset);
}
else
{
DEBUG_PRINTF ("objc_opt->version = %u\n", objc_opt->version);
DEBUG_PRINTF ("objc_opt->selopt_offset = %d\n", objc_opt->selopt_offset);
DEBUG_PRINTF ("objc_opt->headeropt_offset = %d\n", objc_opt->headeropt_offset);
DEBUG_PRINTF ("objc_opt->clsopt_offset = %d\n", objc_opt->clsopt_offset);
}
if (objc_opt->version == 12 || objc_opt->version == 13 || objc_opt->version == 14 || objc_opt->version == 15)
{
const objc_clsopt_t* clsopt = NULL;
if (is_v14_format)
clsopt = (const objc_clsopt_t*)((uint8_t *)objc_opt_v14 + objc_opt_v14->clsopt_offset);
else
clsopt = (const objc_clsopt_t*)((uint8_t *)objc_opt + objc_opt->clsopt_offset);
const size_t max_class_infos = class_infos_byte_size/sizeof(ClassInfo);
DEBUG_PRINTF("max_class_infos = %llu\n", (uint64_t)max_class_infos);
ClassInfo *class_infos = (ClassInfo *)class_infos_ptr;
int32_t invalidEntryOffset = 0;
// this is safe to do because the version field order is invariant
if (objc_opt->version == 12)
invalidEntryOffset = 16;
const uint8_t *checkbytes = &clsopt->tab[clsopt->mask+1];
const int32_t *offsets = (const int32_t *)(checkbytes + clsopt->capacity);
const objc_classheader_t *classOffsets = (const objc_classheader_t *)(offsets + clsopt->capacity);
DEBUG_PRINTF ("clsopt->capacity = %u\n", clsopt->capacity);
DEBUG_PRINTF ("clsopt->mask = 0x%8.8x\n", clsopt->mask);
DEBUG_PRINTF ("classOffsets = %p\n", classOffsets);
DEBUG_PRINTF("invalidEntryOffset = %d\n", invalidEntryOffset);
for (uint32_t i=0; i<clsopt->capacity; ++i)
{
const int32_t clsOffset = classOffsets[i].clsOffset;
DEBUG_PRINTF("clsOffset[%u] = %u\n", i, clsOffset);
if (clsOffset & 1)
{
DEBUG_PRINTF("clsOffset & 1\n");
continue; // duplicate
}
else if (clsOffset == invalidEntryOffset)
{
DEBUG_PRINTF("clsOffset == invalidEntryOffset\n");
continue; // invalid offset
}
if (class_infos && idx < max_class_infos)
{
class_infos[idx].isa = (Class)((uint8_t *)clsopt + clsOffset);
const char *name = class_name_lookup_func (class_infos[idx].isa);
DEBUG_PRINTF ("[%u] isa = %8p %s\n", idx, class_infos[idx].isa, name);
// Hash the class name so we don't have to read it
const char *s = name;
uint32_t h = 5381;
for (unsigned char c = *s; c; c = *++s)
{
// class_getName demangles swift names and the hash must
// be calculated on the mangled name. hash==0 means lldb
// will fetch the mangled name and compute the hash in
// ParseClassInfoArray.
if (c == '.')
{
h = 0;
break;
}
h = ((h << 5) + h) + c;
}
class_infos[idx].hash = h;
}
else
{
DEBUG_PRINTF("not(class_infos && idx < max_class_infos)\n");
}
++idx;
}
const uint32_t *duplicate_count_ptr = (uint32_t *)&classOffsets[clsopt->capacity];
const uint32_t duplicate_count = *duplicate_count_ptr;
const objc_classheader_t *duplicateClassOffsets = (const objc_classheader_t *)(&duplicate_count_ptr[1]);
DEBUG_PRINTF ("duplicate_count = %u\n", duplicate_count);
DEBUG_PRINTF ("duplicateClassOffsets = %p\n", duplicateClassOffsets);
for (uint32_t i=0; i<duplicate_count; ++i)
{
const int32_t clsOffset = duplicateClassOffsets[i].clsOffset;
if (clsOffset & 1)
continue; // duplicate
else if (clsOffset == invalidEntryOffset)
continue; // invalid offset
if (class_infos && idx < max_class_infos)
{
class_infos[idx].isa = (Class)((uint8_t *)clsopt + clsOffset);
const char *name = class_name_lookup_func (class_infos[idx].isa);
DEBUG_PRINTF ("[%u] isa = %8p %s\n", idx, class_infos[idx].isa, name);
// Hash the class name so we don't have to read it
const char *s = name;
uint32_t h = 5381;
for (unsigned char c = *s; c; c = *++s)
{
// class_getName demangles swift names and the hash must
// be calculated on the mangled name. hash==0 means lldb
// will fetch the mangled name and compute the hash in
// ParseClassInfoArray.
if (c == '.')
{
h = 0;
break;
}
h = ((h << 5) + h) + c;
}
class_infos[idx].hash = h;
}
++idx;
}
}
DEBUG_PRINTF ("%u class_infos\n", idx);
DEBUG_PRINTF ("done\n");
}
return idx;
}
)";
static uint64_t
ExtractRuntimeGlobalSymbol(Process *process, ConstString name,
const ModuleSP &module_sp, Status &error,
bool read_value = true, uint8_t byte_size = 0,
uint64_t default_value = LLDB_INVALID_ADDRESS,
SymbolType sym_type = lldb::eSymbolTypeData) {
if (!process) {
error.SetErrorString("no process");
return default_value;
}
if (!module_sp) {
error.SetErrorString("no module");
return default_value;
}
if (!byte_size)
byte_size = process->GetAddressByteSize();
const Symbol *symbol =
module_sp->FindFirstSymbolWithNameAndType(name, lldb::eSymbolTypeData);
if (symbol && symbol->ValueIsAddress()) {
lldb::addr_t symbol_load_addr =
symbol->GetAddressRef().GetLoadAddress(&process->GetTarget());
if (symbol_load_addr != LLDB_INVALID_ADDRESS) {
if (read_value)
return process->ReadUnsignedIntegerFromMemory(
symbol_load_addr, byte_size, default_value, error);
else
return symbol_load_addr;
} else {
error.SetErrorString("symbol address invalid");
return default_value;
}
} else {
error.SetErrorString("no symbol");
return default_value;
}
}
static void RegisterObjCExceptionRecognizer();
AppleObjCRuntimeV2::AppleObjCRuntimeV2(Process *process,
const ModuleSP &objc_module_sp)
: AppleObjCRuntime(process), m_get_class_info_code(),
m_get_class_info_args(LLDB_INVALID_ADDRESS),
m_get_class_info_args_mutex(), m_get_shared_cache_class_info_code(),
m_get_shared_cache_class_info_args(LLDB_INVALID_ADDRESS),
m_get_shared_cache_class_info_args_mutex(), m_decl_vendor_up(),
m_tagged_pointer_obfuscator(LLDB_INVALID_ADDRESS),
m_isa_hash_table_ptr(LLDB_INVALID_ADDRESS), m_hash_signature(),
m_has_object_getClass(false), m_loaded_objc_opt(false),
m_non_pointer_isa_cache_up(
NonPointerISACache::CreateInstance(*this, objc_module_sp)),
m_tagged_pointer_vendor_up(
TaggedPointerVendorV2::CreateInstance(*this, objc_module_sp)),
m_encoding_to_type_sp(), m_noclasses_warning_emitted(false),
m_CFBoolean_values() {
static const ConstString g_gdb_object_getClass("gdb_object_getClass");
m_has_object_getClass =
(objc_module_sp->FindFirstSymbolWithNameAndType(
g_gdb_object_getClass, eSymbolTypeCode) != nullptr);
RegisterObjCExceptionRecognizer();
}
bool AppleObjCRuntimeV2::GetDynamicTypeAndAddress(
ValueObject &in_value, lldb::DynamicValueType use_dynamic,
TypeAndOrName &class_type_or_name, Address &address,
Value::ValueType &value_type) {
// We should never get here with a null process...
assert(m_process != nullptr);
// The Runtime is attached to a particular process, you shouldn't pass in a
// value from another process. Note, however, the process might be NULL (e.g.
// if the value was made with SBTarget::EvaluateExpression...) in which case
// it is sufficient if the target's match:
Process *process = in_value.GetProcessSP().get();
if (process)
assert(process == m_process);
else
assert(in_value.GetTargetSP().get() == m_process->CalculateTarget().get());
class_type_or_name.Clear();
value_type = Value::ValueType::eValueTypeScalar;
// Make sure we can have a dynamic value before starting...
if (CouldHaveDynamicValue(in_value)) {
// First job, pull out the address at 0 offset from the object That will
// be the ISA pointer.
ClassDescriptorSP objc_class_sp(GetNonKVOClassDescriptor(in_value));
if (objc_class_sp) {
const addr_t object_ptr = in_value.GetPointerValue();
address.SetRawAddress(object_ptr);
ConstString class_name(objc_class_sp->GetClassName());
class_type_or_name.SetName(class_name);
TypeSP type_sp(objc_class_sp->GetType());
if (type_sp)
class_type_or_name.SetTypeSP(type_sp);
else {
type_sp = LookupInCompleteClassCache(class_name);
if (type_sp) {
objc_class_sp->SetType(type_sp);
class_type_or_name.SetTypeSP(type_sp);
} else {
// try to go for a CompilerType at least
if (auto *vendor = GetDeclVendor()) {
auto types = vendor->FindTypes(class_name, /*max_matches*/ 1);
if (!types.empty())
class_type_or_name.SetCompilerType(types.front());
}
}
}
}
}
return !class_type_or_name.IsEmpty();
}
// Static Functions
LanguageRuntime *AppleObjCRuntimeV2::CreateInstance(Process *process,
LanguageType language) {
// FIXME: This should be a MacOS or iOS process, and we need to look for the
// OBJC section to make
// sure we aren't using the V1 runtime.
if (language == eLanguageTypeObjC) {
ModuleSP objc_module_sp;
if (AppleObjCRuntime::GetObjCVersion(process, objc_module_sp) ==
ObjCRuntimeVersions::eAppleObjC_V2)
return new AppleObjCRuntimeV2(process, objc_module_sp);
else
return nullptr;
} else
return nullptr;
}
static constexpr OptionDefinition g_objc_classtable_dump_options[] = {
{LLDB_OPT_SET_ALL, false, "verbose", 'v', OptionParser::eNoArgument,
nullptr, {}, 0, eArgTypeNone,
"Print ivar and method information in detail"}};
class CommandObjectObjC_ClassTable_Dump : public CommandObjectParsed {
public:
class CommandOptions : public Options {
public:
CommandOptions() : Options(), m_verbose(false, false) {}
~CommandOptions() override = default;
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
ExecutionContext *execution_context) override {
Status error;
const int short_option = m_getopt_table[option_idx].val;
switch (short_option) {
case 'v':
m_verbose.SetCurrentValue(true);
m_verbose.SetOptionWasSet();
break;
default:
error.SetErrorStringWithFormat("unrecognized short option '%c'",
short_option);
break;
}
return error;
}
void OptionParsingStarting(ExecutionContext *execution_context) override {
m_verbose.Clear();
}
llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
return llvm::makeArrayRef(g_objc_classtable_dump_options);
}
OptionValueBoolean m_verbose;
};
CommandObjectObjC_ClassTable_Dump(CommandInterpreter &interpreter)
: CommandObjectParsed(
interpreter, "dump", "Dump information on Objective-C classes "
"known to the current process.",
"language objc class-table dump",
eCommandRequiresProcess | eCommandProcessMustBeLaunched |
eCommandProcessMustBePaused),
m_options() {
CommandArgumentEntry arg;
CommandArgumentData index_arg;
// Define the first (and only) variant of this arg.
index_arg.arg_type = eArgTypeRegularExpression;
index_arg.arg_repetition = eArgRepeatOptional;
// There is only one variant this argument could be; put it into the
// argument entry.
arg.push_back(index_arg);
// Push the data for the first argument into the m_arguments vector.
m_arguments.push_back(arg);
}
~CommandObjectObjC_ClassTable_Dump() override = default;
Options *GetOptions() override { return &m_options; }
protected:
bool DoExecute(Args &command, CommandReturnObject &result) override {
std::unique_ptr<RegularExpression> regex_up;
switch (command.GetArgumentCount()) {
case 0:
break;
case 1: {
regex_up.reset(new RegularExpression(
llvm::StringRef::withNullAsEmpty(command.GetArgumentAtIndex(0))));
if (!regex_up->IsValid()) {
result.AppendError(
"invalid argument - please provide a valid regular expression");
result.SetStatus(lldb::eReturnStatusFailed);
return false;
}
break;
}
default: {
result.AppendError("please provide 0 or 1 arguments");
result.SetStatus(lldb::eReturnStatusFailed);
return false;
}
}
Process *process = m_exe_ctx.GetProcessPtr();
ObjCLanguageRuntime *objc_runtime = ObjCLanguageRuntime::Get(*process);
if (objc_runtime) {
auto iterators_pair = objc_runtime->GetDescriptorIteratorPair();
auto iterator = iterators_pair.first;
auto &std_out = result.GetOutputStream();
for (; iterator != iterators_pair.second; iterator++) {
if (iterator->second) {
const char *class_name =
iterator->second->GetClassName().AsCString("<unknown>");
if (regex_up && class_name &&
!regex_up->Execute(llvm::StringRef(class_name)))
continue;
std_out.Printf("isa = 0x%" PRIx64, iterator->first);
std_out.Printf(" name = %s", class_name);
std_out.Printf(" instance size = %" PRIu64,
iterator->second->GetInstanceSize());
std_out.Printf(" num ivars = %" PRIuPTR,
(uintptr_t)iterator->second->GetNumIVars());
if (auto superclass = iterator->second->GetSuperclass()) {
std_out.Printf(" superclass = %s",
superclass->GetClassName().AsCString("<unknown>"));
}
std_out.Printf("\n");
if (m_options.m_verbose) {
for (size_t i = 0; i < iterator->second->GetNumIVars(); i++) {
auto ivar = iterator->second->GetIVarAtIndex(i);
std_out.Printf(
" ivar name = %s type = %s size = %" PRIu64
" offset = %" PRId32 "\n",
ivar.m_name.AsCString("<unknown>"),
ivar.m_type.GetDisplayTypeName().AsCString("<unknown>"),
ivar.m_size, ivar.m_offset);
}
iterator->second->Describe(
nullptr,
[&std_out](const char *name, const char *type) -> bool {
std_out.Printf(" instance method name = %s type = %s\n",
name, type);
return false;
},
[&std_out](const char *name, const char *type) -> bool {
std_out.Printf(" class method name = %s type = %s\n", name,
type);
return false;
},
nullptr);
}
} else {
if (regex_up && !regex_up->Execute(llvm::StringRef()))
continue;
std_out.Printf("isa = 0x%" PRIx64 " has no associated class.\n",
iterator->first);
}
}
result.SetStatus(lldb::eReturnStatusSuccessFinishResult);
return true;
} else {
result.AppendError("current process has no Objective-C runtime loaded");
result.SetStatus(lldb::eReturnStatusFailed);
return false;
}
}
CommandOptions m_options;
};
class CommandObjectMultiwordObjC_TaggedPointer_Info
: public CommandObjectParsed {
public:
CommandObjectMultiwordObjC_TaggedPointer_Info(CommandInterpreter &interpreter)
: CommandObjectParsed(
interpreter, "info", "Dump information on a tagged pointer.",
"language objc tagged-pointer info",
eCommandRequiresProcess | eCommandProcessMustBeLaunched |
eCommandProcessMustBePaused) {
CommandArgumentEntry arg;
CommandArgumentData index_arg;
// Define the first (and only) variant of this arg.
index_arg.arg_type = eArgTypeAddress;
index_arg.arg_repetition = eArgRepeatPlus;
// There is only one variant this argument could be; put it into the
// argument entry.
arg.push_back(index_arg);
// Push the data for the first argument into the m_arguments vector.
m_arguments.push_back(arg);
}
~CommandObjectMultiwordObjC_TaggedPointer_Info() override = default;
protected:
bool DoExecute(Args &command, CommandReturnObject &result) override {
if (command.GetArgumentCount() == 0) {
result.AppendError("this command requires arguments");
result.SetStatus(lldb::eReturnStatusFailed);
return false;
}
Process *process = m_exe_ctx.GetProcessPtr();
ExecutionContext exe_ctx(process);
ObjCLanguageRuntime *objc_runtime = ObjCLanguageRuntime::Get(*process);
if (objc_runtime) {
ObjCLanguageRuntime::TaggedPointerVendor *tagged_ptr_vendor =
objc_runtime->GetTaggedPointerVendor();
if (tagged_ptr_vendor) {
for (size_t i = 0; i < command.GetArgumentCount(); i++) {
const char *arg_str = command.GetArgumentAtIndex(i);
if (!arg_str)
continue;
Status error;
lldb::addr_t arg_addr = OptionArgParser::ToAddress(
&exe_ctx, arg_str, LLDB_INVALID_ADDRESS, &error);
if (arg_addr == 0 || arg_addr == LLDB_INVALID_ADDRESS || error.Fail())
continue;
auto descriptor_sp = tagged_ptr_vendor->GetClassDescriptor(arg_addr);
if (!descriptor_sp)
continue;
uint64_t info_bits = 0;
uint64_t value_bits = 0;
uint64_t payload = 0;
if (descriptor_sp->GetTaggedPointerInfo(&info_bits, &value_bits,
&payload)) {
result.GetOutputStream().Printf(
"0x%" PRIx64 " is tagged.\n\tpayload = 0x%" PRIx64
"\n\tvalue = 0x%" PRIx64 "\n\tinfo bits = 0x%" PRIx64
"\n\tclass = %s\n",
(uint64_t)arg_addr, payload, value_bits, info_bits,
descriptor_sp->GetClassName().AsCString("<unknown>"));
} else {
result.GetOutputStream().Printf("0x%" PRIx64 " is not tagged.\n",
(uint64_t)arg_addr);
}
}
} else {
result.AppendError("current process has no tagged pointer support");
result.SetStatus(lldb::eReturnStatusFailed);
return false;
}
result.SetStatus(lldb::eReturnStatusSuccessFinishResult);
return true;
} else {
result.AppendError("current process has no Objective-C runtime loaded");
result.SetStatus(lldb::eReturnStatusFailed);
return false;
}
}
};
class CommandObjectMultiwordObjC_ClassTable : public CommandObjectMultiword {
public:
CommandObjectMultiwordObjC_ClassTable(CommandInterpreter &interpreter)
: CommandObjectMultiword(
interpreter, "class-table",
"Commands for operating on the Objective-C class table.",
"class-table <subcommand> [<subcommand-options>]") {
LoadSubCommand(
"dump",
CommandObjectSP(new CommandObjectObjC_ClassTable_Dump(interpreter)));
}
~CommandObjectMultiwordObjC_ClassTable() override = default;
};
class CommandObjectMultiwordObjC_TaggedPointer : public CommandObjectMultiword {
public:
CommandObjectMultiwordObjC_TaggedPointer(CommandInterpreter &interpreter)
: CommandObjectMultiword(
interpreter, "tagged-pointer",
"Commands for operating on Objective-C tagged pointers.",
"class-table <subcommand> [<subcommand-options>]") {
LoadSubCommand(
"info",
CommandObjectSP(
new CommandObjectMultiwordObjC_TaggedPointer_Info(interpreter)));
}
~CommandObjectMultiwordObjC_TaggedPointer() override = default;
};
class CommandObjectMultiwordObjC : public CommandObjectMultiword {
public:
CommandObjectMultiwordObjC(CommandInterpreter &interpreter)
: CommandObjectMultiword(
interpreter, "objc",
"Commands for operating on the Objective-C language runtime.",
"objc <subcommand> [<subcommand-options>]") {
LoadSubCommand("class-table",
CommandObjectSP(
new CommandObjectMultiwordObjC_ClassTable(interpreter)));
LoadSubCommand("tagged-pointer",
CommandObjectSP(new CommandObjectMultiwordObjC_TaggedPointer(
interpreter)));
}
~CommandObjectMultiwordObjC() override = default;
};
void AppleObjCRuntimeV2::Initialize() {
PluginManager::RegisterPlugin(
GetPluginNameStatic(), "Apple Objective-C Language Runtime - Version 2",
CreateInstance,
[](CommandInterpreter &interpreter) -> lldb::CommandObjectSP {
return CommandObjectSP(new CommandObjectMultiwordObjC(interpreter));
},
GetBreakpointExceptionPrecondition);
}
void AppleObjCRuntimeV2::Terminate() {
PluginManager::UnregisterPlugin(CreateInstance);
}
lldb_private::ConstString AppleObjCRuntimeV2::GetPluginNameStatic() {
static ConstString g_name("apple-objc-v2");
return g_name;
}
// PluginInterface protocol
lldb_private::ConstString AppleObjCRuntimeV2::GetPluginName() {
return GetPluginNameStatic();
}
uint32_t AppleObjCRuntimeV2::GetPluginVersion() { return 1; }
BreakpointResolverSP
AppleObjCRuntimeV2::CreateExceptionResolver(Breakpoint *bkpt, bool catch_bp,
bool throw_bp) {
BreakpointResolverSP resolver_sp;
if (throw_bp)
resolver_sp = std::make_shared<BreakpointResolverName>(
bkpt, std::get<1>(GetExceptionThrowLocation()).AsCString(),
eFunctionNameTypeBase, eLanguageTypeUnknown, Breakpoint::Exact, 0,
eLazyBoolNo);
// FIXME: We don't do catch breakpoints for ObjC yet.
// Should there be some way for the runtime to specify what it can do in this
// regard?
return resolver_sp;
}
UtilityFunction *AppleObjCRuntimeV2::CreateObjectChecker(const char *name) {
char check_function_code[2048];
int len = 0;
if (m_has_object_getClass) {
len = ::snprintf(check_function_code, sizeof(check_function_code), R"(
extern "C" void *gdb_object_getClass(void *);
extern "C" int printf(const char *format, ...);
extern "C" void
%s(void *$__lldb_arg_obj, void *$__lldb_arg_selector) {
if ($__lldb_arg_obj == (void *)0)
return; // nil is ok
if (!gdb_object_getClass($__lldb_arg_obj)) {
*((volatile int *)0) = 'ocgc';
} else if ($__lldb_arg_selector != (void *)0) {
signed char $responds = (signed char)
[(id)$__lldb_arg_obj respondsToSelector:
(void *) $__lldb_arg_selector];
if ($responds == (signed char) 0)
*((volatile int *)0) = 'ocgc';
}
})", name);
} else {
len = ::snprintf(check_function_code, sizeof(check_function_code), R"(
extern "C" void *gdb_class_getClass(void *);
extern "C" int printf(const char *format, ...);
extern "C" void
%s(void *$__lldb_arg_obj, void *$__lldb_arg_selector) {
if ($__lldb_arg_obj == (void *)0)
return; // nil is ok
void **$isa_ptr = (void **)$__lldb_arg_obj;
if (*$isa_ptr == (void *)0 ||
!gdb_class_getClass(*$isa_ptr))
*((volatile int *)0) = 'ocgc';
else if ($__lldb_arg_selector != (void *)0) {
signed char $responds = (signed char)
[(id)$__lldb_arg_obj respondsToSelector:
(void *) $__lldb_arg_selector];
if ($responds == (signed char) 0)
*((volatile int *)0) = 'ocgc';
}
})", name);
}
assert(len < (int)sizeof(check_function_code));
UNUSED_IF_ASSERT_DISABLED(len);
Status error;
return GetTargetRef().GetUtilityFunctionForLanguage(
check_function_code, eLanguageTypeObjC, name, error);
}
size_t AppleObjCRuntimeV2::GetByteOffsetForIvar(CompilerType &parent_ast_type,
const char *ivar_name) {
uint32_t ivar_offset = LLDB_INVALID_IVAR_OFFSET;
const char *class_name = parent_ast_type.GetConstTypeName().AsCString();
if (class_name && class_name[0] && ivar_name && ivar_name[0]) {
// Make the objective C V2 mangled name for the ivar offset from the class
// name and ivar name
std::string buffer("OBJC_IVAR_$_");
buffer.append(class_name);
buffer.push_back('.');
buffer.append(ivar_name);
ConstString ivar_const_str(buffer.c_str());
// Try to get the ivar offset address from the symbol table first using the
// name we created above
SymbolContextList sc_list;
Target &target = m_process->GetTarget();
target.GetImages().FindSymbolsWithNameAndType(ivar_const_str,
eSymbolTypeObjCIVar, sc_list);
addr_t ivar_offset_address = LLDB_INVALID_ADDRESS;
Status error;
SymbolContext ivar_offset_symbol;
if (sc_list.GetSize() == 1 &&
sc_list.GetContextAtIndex(0, ivar_offset_symbol)) {
if (ivar_offset_symbol.symbol)
ivar_offset_address =
ivar_offset_symbol.symbol->GetLoadAddress(&target);
}
// If we didn't get the ivar offset address from the symbol table, fall
// back to getting it from the runtime
if (ivar_offset_address == LLDB_INVALID_ADDRESS)
ivar_offset_address = LookupRuntimeSymbol(ivar_const_str);
if (ivar_offset_address != LLDB_INVALID_ADDRESS)
ivar_offset = m_process->ReadUnsignedIntegerFromMemory(
ivar_offset_address, 4, LLDB_INVALID_IVAR_OFFSET, error);
}
return ivar_offset;
}
// tagged pointers are special not-a-real-pointer values that contain both type
// and value information this routine attempts to check with as little
// computational effort as possible whether something could possibly be a
// tagged pointer - false positives are possible but false negatives shouldn't
bool AppleObjCRuntimeV2::IsTaggedPointer(addr_t ptr) {
if (!m_tagged_pointer_vendor_up)
return false;
return m_tagged_pointer_vendor_up->IsPossibleTaggedPointer(ptr);
}
class RemoteNXMapTable {
public:
RemoteNXMapTable()
: m_count(0), m_num_buckets_minus_one(0),
m_buckets_ptr(LLDB_INVALID_ADDRESS), m_process(nullptr),
m_end_iterator(*this, -1), m_load_addr(LLDB_INVALID_ADDRESS),
m_map_pair_size(0), m_invalid_key(0) {}
void Dump() {
printf("RemoteNXMapTable.m_load_addr = 0x%" PRIx64 "\n", m_load_addr);
printf("RemoteNXMapTable.m_count = %u\n", m_count);
printf("RemoteNXMapTable.m_num_buckets_minus_one = %u\n",
m_num_buckets_minus_one);
printf("RemoteNXMapTable.m_buckets_ptr = 0x%" PRIX64 "\n", m_buckets_ptr);
}
bool ParseHeader(Process *process, lldb::addr_t load_addr) {
m_process = process;
m_load_addr = load_addr;
m_map_pair_size = m_process->GetAddressByteSize() * 2;
m_invalid_key =
m_process->GetAddressByteSize() == 8 ? UINT64_MAX : UINT32_MAX;
Status err;
// This currently holds true for all platforms we support, but we might
// need to change this to use get the actually byte size of "unsigned" from
// the target AST...
const uint32_t unsigned_byte_size = sizeof(uint32_t);
// Skip the prototype as we don't need it (const struct
// +NXMapTablePrototype *prototype)
bool success = true;
if (load_addr == LLDB_INVALID_ADDRESS)
success = false;
else {
lldb::addr_t cursor = load_addr + m_process->GetAddressByteSize();
// unsigned count;
m_count = m_process->ReadUnsignedIntegerFromMemory(
cursor, unsigned_byte_size, 0, err);
if (m_count) {
cursor += unsigned_byte_size;
// unsigned nbBucketsMinusOne;
m_num_buckets_minus_one = m_process->ReadUnsignedIntegerFromMemory(
cursor, unsigned_byte_size, 0, err);
cursor += unsigned_byte_size;
// void *buckets;
m_buckets_ptr = m_process->ReadPointerFromMemory(cursor, err);