-
Notifications
You must be signed in to change notification settings - Fork 281
Expand file tree
/
Copy pathobjc.cpp
More file actions
1992 lines (1777 loc) · 66.9 KB
/
objc.cpp
File metadata and controls
1992 lines (1777 loc) · 66.9 KB
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
#include "objc.h"
#include "inttypes.h"
#include <optional>
#include <string>
#include <type_traits>
#define RELEASE_ASSERT(condition) ((condition) ? (void)0 : (std::abort(), (void)0))
using namespace BinaryNinja;
namespace {
// ScopedSingleton is a thread-local singleton that allows for scoped
// instantiation and destruction of an object. It is useful for managing
// resources that should only exist during a specific scope, but where it
// would be inconvenient to pass the object around explicitly.
//
// Calling `Make` initializes the thread-local singleton and returns a `Guard`
// object. When the `Guard` object goes out of scope, the singleton is destroyed.
template <typename T>
class ScopedSingleton
{
static thread_local T* current;
public:
class Guard
{
friend class ScopedSingleton;
Guard() = default;
public:
~Guard()
{
delete current;
current = nullptr;
}
Guard(Guard&&) = default;
Guard(const Guard&) = delete;
Guard& operator=(const Guard&) = delete;
};
static T& Get()
{
RELEASE_ASSERT(current);
return *current;
}
static Guard Make()
{
RELEASE_ASSERT(!current);
current = new T();
return Guard {};
}
};
template <typename T>
thread_local T* ScopedSingleton<T>::current = nullptr;
using ScopedSymbolQueue = ScopedSingleton<SymbolQueue>;
// Attempt to recover an Objective-C class name from the symbol's name.
// Note: classes defined in the current image should be looked up in m_classes
// rather than using this function.
std::optional<std::string> ClassNameFromSymbolName(const Ref<Symbol>& symbol)
{
std::string_view symbolName = symbol->GetFullNameRef();
// Symbols named `_OBJC_CLASS_$_` are references to external classes.
if (symbolName.size() > 14 && symbolName.rfind("_OBJC_CLASS_$_", 0) == 0)
return std::string(symbolName.substr(14));
// Symbols named `cls_` are classes defined in a loaded image other than
// the image currently being analyzed.
if (symbolName.size() > 4 && symbolName.rfind("cls_", 0) == 0)
return std::string(symbolName.substr(4));
return std::nullopt;
}
// Given a selector component such as `initWithPath' and a prefix of `initWith`, returns `path`.
std::optional<std::string> SelectorComponentWithoutPrefix(std::string_view prefix, std::string_view component)
{
if (component.size() <= prefix.size() || component.rfind(prefix.data(), 0) != 0
|| !isupper(component[prefix.size()]))
{
return std::nullopt;
}
std::string result(component.substr(prefix.size()));
// Lowercase the first character if the second character is not also uppercase.
// This ensures we leave initialisms such as `URL` alone.
if (result.size() > 1 && islower(result[1]))
result[0] = tolower(result[0]);
return result;
}
std::string ArgumentNameFromSelectorComponent(std::string component)
{
// TODO: Handle other common patterns such as <do some action>With<arg>: and <do some action>For<arg>:
for (const auto& prefix : {"initWith", "with", "and", "using", "set", "read", "to", "for"})
{
if (auto argumentName = SelectorComponentWithoutPrefix(prefix, component); argumentName.has_value())
return std::move(*argumentName);
}
return component;
}
Ref<Type> NamedType(const std::string& name)
{
NamedTypeReferenceBuilder builder;
builder.SetName(QualifiedName(name));
return Type::NamedType(builder.Finalize());
}
} // namespace
Ref<Metadata> ObjCProcessor::SerializeMethod(uint64_t loc, const Method& method)
{
std::map<std::string, Ref<Metadata>> methodMeta;
methodMeta["loc"] = new Metadata(loc);
methodMeta["name"] = new Metadata(method.name);
methodMeta["types"] = new Metadata(method.types);
methodMeta["imp"] = new Metadata(method.imp);
return new Metadata(methodMeta);
}
Ref<Metadata> ObjCProcessor::SerializeClass(uint64_t loc, const Class& cls)
{
std::map<std::string, Ref<Metadata>> clsMeta;
clsMeta["loc"] = new Metadata(loc);
clsMeta["name"] = new Metadata(cls.name);
clsMeta["typeName"] = new Metadata(cls.associatedName.GetString());
std::vector<uint64_t> instanceMethods;
std::vector<uint64_t> classMethods;
instanceMethods.reserve(cls.instanceClass.methodList.size());
classMethods.reserve(cls.metaClass.methodList.size());
for (const auto& [location, _] : cls.instanceClass.methodList)
instanceMethods.push_back(location);
clsMeta["instanceMethods"] = new Metadata(instanceMethods);
clsMeta["classMethods"] = new Metadata(classMethods);
return new Metadata(clsMeta);
}
Ref<Metadata> ObjCProcessor::SerializeMetadata()
{
std::map<std::string, Ref<Metadata>> viewMeta;
viewMeta["version"] = new Metadata((uint64_t)1);
std::vector<Ref<Metadata>> classes;
classes.reserve(m_classes.size());
std::vector<Ref<Metadata>> categories;
categories.reserve(m_categories.size());
std::vector<Ref<Metadata>> methods;
methods.reserve(m_localMethods.size());
for (const auto& [clsLoc, cls] : m_classes)
classes.push_back(SerializeClass(clsLoc, cls));
viewMeta["classes"] = new Metadata(classes);
for (const auto& [catLoc, cat] : m_categories)
categories.push_back(SerializeClass(catLoc, cat));
viewMeta["categories"] = new Metadata(categories);
for (const auto& [methodLoc, method] : m_localMethods)
methods.push_back(SerializeMethod(methodLoc, method));
viewMeta["methods"] = new Metadata(methods);
// Required for workflow_objc type guessing, should be removed when that is no longer a thing.
std::vector<Ref<Metadata>> selRefToImps;
selRefToImps.reserve(m_selRefToImplementations.size());
for (const auto& [selRef, imps] : m_selRefToImplementations)
{
std::vector<Ref<Metadata>> mapBase = {new Metadata(selRef), new Metadata(imps)};
Ref<Metadata> mapObject = new Metadata(mapBase);
selRefToImps.push_back(mapObject);
}
viewMeta["selRefImplementations"] = new Metadata(selRefToImps);
std::vector<Ref<Metadata>> selToImps;
selToImps.reserve(m_selToImplementations.size());
for (const auto& [selRef, imps] : m_selToImplementations)
{
std::vector<Ref<Metadata>> mapBase = {new Metadata(selRef), new Metadata(imps)};
Ref<Metadata> mapObject = new Metadata(mapBase);
selToImps.push_back(mapObject);
}
viewMeta["selImplementations"] = new Metadata(selToImps);
std::vector<Ref<Metadata>> selRefToName;
selRefToName.reserve(m_selRefToName.size());
for (const auto& [selRef, name] : m_selRefToName)
{
std::vector<Ref<Metadata>> mapBase = {new Metadata(selRef), new Metadata(name)};
Ref<Metadata> mapObject = new Metadata(mapBase);
selRefToName.push_back(mapObject);
}
viewMeta["selRefToName"] = new Metadata(selRefToName);
// ---
return new Metadata(viewMeta);
}
std::vector<QualifiedNameOrType> ObjCProcessor::ParseEncodedType(const std::string& encodedType)
{
std::vector<QualifiedNameOrType> result;
int pointerDepth = 0;
bool readingNamedType = false;
std::string namedType;
int readingStructDepth = 0;
std::string structType;
char last = 0;
for (char c : encodedType)
{
if (readingNamedType && c != '"')
{
namedType.push_back(c);
last = c;
continue;
}
else if (readingStructDepth > 0 && c != '{' && c != '}')
{
structType.push_back(c);
last = c;
continue;
}
if (std::isdigit(c))
continue;
QualifiedNameOrType nameOrType;
std::string qualifiedName;
switch (c)
{
case '^':
pointerDepth++;
last = c;
continue;
case '"':
if (!readingNamedType)
{
readingNamedType = true;
if (last == '@')
result.pop_back(); // We added an 'id' in the last cycle, remove it
last = c;
continue;
}
else
{
readingNamedType = false;
nameOrType.name = QualifiedName(namedType);
nameOrType.ptrCount = 1;
break;
}
case '{':
readingStructDepth++;
last = c;
continue;
case '}':
readingStructDepth--;
if (readingStructDepth < 0)
return {}; // seriously malformed type.
if (readingStructDepth == 0)
{
// TODO: Emit real struct types
nameOrType.type = Type::PointerType(m_data->GetAddressSize(), Type::VoidType());
break;
}
last = c;
continue;
case 'v':
nameOrType.type = Type::VoidType();
break;
case 'c':
nameOrType.type = Type::IntegerType(1, true);
break;
case 'A':
case 'C':
nameOrType.type = Type::IntegerType(1, false);
break;
case 's':
nameOrType.type = Type::IntegerType(2, true);
break;
case 'S':
nameOrType.type = Type::IntegerType(2, false);
break;
case 'i':
nameOrType.type = Type::IntegerType(4, true);
break;
case 'I':
nameOrType.type = Type::IntegerType(4, false);
break;
case 'l':
nameOrType.type = Type::IntegerType(4, true);
break;
case 'L':
nameOrType.type = Type::IntegerType(4, false);
break;
case 'q':
nameOrType.type = Type::IntegerType(8, true);
break;
case 'Q':
nameOrType.type = Type::IntegerType(8, false);
break;
case 'f':
nameOrType.type = Type::FloatType(4);
break;
case 'd':
nameOrType.type = Type::FloatType(8);
break;
case 'b':
case 'B':
nameOrType.type = Type::BoolType();
break;
case '*':
nameOrType.type = Type::PointerType(m_data->GetAddressSize(), Type::IntegerType(1, true));
break;
case '@':
nameOrType.type = m_types.id;
// There can be a type after this, like @"NSString", that overrides this
// The handler for " will catch it and drop this "id" entry.
break;
case ':':
nameOrType.type = m_types.sel;
break;
case '#':
qualifiedName = "objc_class_t";
break;
case '?':
if (last == '@')
{
// A pointer to a Clang block is encoded as `@?`. For now we continue to represent this
// as `id` as we cannot represent block types.
last = c;
continue;
}
[[fallthrough]];
case 'T':
nameOrType.type = Type::PointerType(8, Type::VoidType());
break;
default:
// BNLogWarn("Unknown type specifier %c", c);
last = c;
continue;
}
while (pointerDepth)
{
if (nameOrType.type)
nameOrType.type = Type::PointerType(8, nameOrType.type);
else
nameOrType.ptrCount++;
pointerDepth--;
}
if (!qualifiedName.empty())
nameOrType.name = QualifiedName(qualifiedName);
if (nameOrType.type == nullptr && nameOrType.name.IsEmpty())
{
nameOrType.type = Type::VoidType();
}
result.push_back(nameOrType);
last = c;
}
return result;
}
void ObjCProcessor::DefineObjCSymbol(
BNSymbolType type, QualifiedName typeName, const std::string& name, uint64_t addr, bool deferred)
{
DefineObjCSymbol(type, m_data->GetTypeByName(typeName), name, addr, deferred);
}
void ObjCProcessor::DefineObjCSymbol(
BNSymbolType type, Ref<Type> typeRef, const std::string& name, uint64_t addr, bool deferred)
{
if (name.size() == 0 || addr == 0)
return;
auto process = [=, this]() {
NameSpace nameSpace = m_data->GetInternalNameSpace();
if (type == ExternalSymbol)
{
nameSpace = m_data->GetExternalNameSpace();
}
std::string shortName = name;
std::string fullName = name;
QualifiedName varName;
return std::pair<Ref<Symbol>, Ref<Type>>(
new Symbol(type, shortName, fullName, name, addr, LocalBinding, nameSpace), typeRef);
};
auto defineSymbol = [this](Ref<Symbol> symbol, const Confidence<Ref<Type>>& type) {
uint64_t symbolAddress = symbol->GetAddress();
// Armv7/Thumb: This will rewrite the symbol's address.
// e.g. We pass in 0xc001, it will rewrite it to 0xc000 and create the function w/ the "thumb2" arch.
if (Ref<Symbol> existingSymbol = m_data->GetSymbolByAddress(symbolAddress))
m_data->UndefineAutoSymbol(existingSymbol);
Ref<Platform> targetPlatform = m_data->GetDefaultPlatform()->GetAssociatedPlatformByAddress(symbolAddress);
if (symbol->GetType() == FunctionSymbol)
{
// For thumb2 we want to get the adjusted address, we can do that using the target function.
Ref<Function> targetFunction = m_data->GetAnalysisFunction(targetPlatform, symbolAddress);
if (targetFunction && type.GetValue())
targetFunction->ApplyAutoDiscoveredType(type.GetValue());
auto adjustedSym = new Symbol(FunctionSymbol, symbol->GetShortName(), symbol->GetFullName(), symbol->GetRawName(), symbolAddress);
m_data->DefineAutoSymbol(adjustedSym);
}
else
{
// Other symbol types can just use this, they don't need to worry about linear sweep removing them.
m_data->DefineAutoSymbolAndVariableOrFunction(targetPlatform, symbol, type);
}
};
if (!deferred)
{
ScopedSymbolQueue::Get().Append(process, defineSymbol);
}
else
{
auto [symbol, type] = process();
defineSymbol(symbol, type);
}
}
void ObjCProcessor::LoadClasses(ObjCReader* reader, Ref<Section> classPtrSection)
{
if (!classPtrSection)
return;
auto size = classPtrSection->GetEnd() - classPtrSection->GetStart();
if (size == 0)
return;
auto ptrSize = m_data->GetAddressSize();
auto ptrCount = size / ptrSize;
auto classPtrSectionStart = classPtrSection->GetStart();
for (size_t i = 0; i < ptrCount; i++)
{
Class cls;
view_ptr_t classPtr;
class_t clsStruct;
class_ro_t classRO;
bool hasValidMetaClass = false;
bool hasValidMetaClassRO = false;
class_t metaClsStruct;
class_ro_t metaClassRO;
view_ptr_t classPointerLocation = classPtrSectionStart + (i * m_data->GetAddressSize());
reader->Seek(classPointerLocation);
classPtr = ReadPointerAccountingForRelocations(reader);
reader->Seek(classPtr);
try
{
clsStruct.isa = ReadPointerAccountingForRelocations(reader);
clsStruct.super = reader->ReadPointer();
clsStruct.cache = reader->ReadPointer();
clsStruct.vtable = reader->ReadPointer();
clsStruct.data = ReadPointerAccountingForRelocations(reader);
}
catch (...)
{
m_logger->LogError("Failed to read class data at 0x%llx pointed to by @ 0x%llx", reader->GetOffset(),
classPointerLocation);
continue;
}
if (clsStruct.data & 1)
{
m_logger->LogInfo("Skipping class at 0x%llx as it contains swift types", classPtr);
continue;
}
// unset first two bits
view_ptr_t classROPtr = clsStruct.data & ~3;
reader->Seek(classROPtr);
try
{
classRO.flags = reader->Read32();
classRO.instanceStart = reader->Read32();
classRO.instanceSize = reader->Read32();
if (m_data->GetAddressSize() == 8)
classRO.reserved = reader->Read32();
classRO.ivarLayout = ReadPointerAccountingForRelocations(reader);
classRO.name = ReadPointerAccountingForRelocations(reader);
classRO.baseMethods = ReadPointerAccountingForRelocations(reader);
classRO.baseProtocols = ReadPointerAccountingForRelocations(reader);
classRO.ivars = ReadPointerAccountingForRelocations(reader);
classRO.weakIvarLayout = ReadPointerAccountingForRelocations(reader);
classRO.baseProperties = ReadPointerAccountingForRelocations(reader);
}
catch (...)
{
m_logger->LogError("Failed to read class RO data at 0x%llx. 0x%llx, objc_class_t @ 0x%llx",
reader->GetOffset(), classPointerLocation, classROPtr);
continue;
}
auto namePtr = classRO.name;
std::string name;
reader->Seek(namePtr);
try
{
name = reader->ReadCString();
}
catch (...)
{
m_logger->LogWarn(
"Failed to read class name at 0x%llx. Class has been given the placeholder name \"0x%llx\" ", namePtr,
classPtr);
char hexString[9];
hexString[8] = 0;
snprintf(hexString, sizeof(hexString), "%" PRIx64, classPtr);
name = "0x" + std::string(hexString);
}
cls.name = name;
DefineObjCSymbol(BNSymbolType::DataSymbol,
Type::PointerType(m_data->GetAddressSize(), m_data->GetTypeByName(m_typeNames.cls)), "clsPtr_" + name,
classPointerLocation, true);
DefineObjCSymbol(BNSymbolType::DataSymbol, m_typeNames.cls, "cls_" + name, classPtr, true);
DefineObjCSymbol(BNSymbolType::DataSymbol, m_typeNames.classRO, "cls_ro_" + name, classROPtr, true);
DefineObjCSymbol(BNSymbolType::DataSymbol, Type::ArrayType(Type::IntegerType(1, true), name.size() + 1),
"clsName_" + name, classRO.name, true);
if (classRO.baseProtocols && !m_skipClassBaseProtocols)
{
DefineObjCSymbol(BNSymbolType::DataSymbol, Type::NamedType(m_data, m_typeNames.protocolList),
"clsProtocols_" + name, classRO.baseProtocols, true);
reader->Seek(classRO.baseProtocols);
uint32_t count = reader->Read64();
view_ptr_t addr = reader->GetOffset();
for (uint32_t j = 0; j < count; j++)
{
m_data->DefineDataVariable(
addr, Type::PointerType(ptrSize, Type::NamedType(m_data, m_typeNames.protocol)));
addr += ptrSize;
}
}
if (clsStruct.isa)
{
reader->Seek(clsStruct.isa);
try
{
metaClsStruct.isa = ReadPointerAccountingForRelocations(reader);
metaClsStruct.super = reader->ReadPointer();
metaClsStruct.cache = reader->ReadPointer();
metaClsStruct.vtable = reader->ReadPointer();
metaClsStruct.data = ReadPointerAccountingForRelocations(reader) & ~1;
DefineObjCSymbol(BNSymbolType::DataSymbol, m_typeNames.cls, "metacls_" + name, clsStruct.isa, true);
hasValidMetaClass = true;
}
catch (...)
{
m_logger->LogWarn("Failed to read metaclass data at 0x%llx pointed to by objc_class_t @ 0x%llx",
reader->GetOffset(), classPtr);
}
}
if (hasValidMetaClass && (metaClsStruct.data & 1))
{
m_logger->LogInfo("Skipping metaclass at 0x%llx as it contains swift types", classPtr);
hasValidMetaClass = false;
}
if (hasValidMetaClass)
{
reader->Seek(metaClsStruct.data);
try
{
metaClassRO.flags = reader->Read32();
metaClassRO.instanceStart = reader->Read32();
metaClassRO.instanceSize = reader->Read32();
if (m_data->GetAddressSize() == 8)
metaClassRO.reserved = reader->Read32();
metaClassRO.ivarLayout = ReadPointerAccountingForRelocations(reader);
metaClassRO.name = ReadPointerAccountingForRelocations(reader);
metaClassRO.baseMethods = ReadPointerAccountingForRelocations(reader);
metaClassRO.baseProtocols = ReadPointerAccountingForRelocations(reader);
metaClassRO.ivars = ReadPointerAccountingForRelocations(reader);
metaClassRO.weakIvarLayout = ReadPointerAccountingForRelocations(reader);
metaClassRO.baseProperties = ReadPointerAccountingForRelocations(reader);
DefineObjCSymbol(
BNSymbolType::DataSymbol, m_typeNames.classRO, "metacls_ro_" + name, metaClsStruct.data, true);
hasValidMetaClassRO = true;
}
catch (...)
{
m_logger->LogWarn("Failed to read metaclass RO data at 0x%llx pointed to by meta objc_class_t @ 0x%llx",
reader->GetOffset(), clsStruct.isa);
}
}
if (classRO.baseMethods)
{
try
{
ReadMethodList(reader, cls.instanceClass, name, classRO.baseMethods);
}
catch (...)
{
m_logger->LogError("Failed to read the method list for class pointed to by 0x%llx", clsStruct.data);
}
}
if (hasValidMetaClassRO && metaClassRO.baseMethods)
{
try
{
ReadMethodList(reader, cls.metaClass, name, metaClassRO.baseMethods);
}
catch (...)
{
m_logger->LogError("Failed to read the method list for metaclass pointed to by 0x%llx", clsStruct.data);
}
}
if (classRO.ivars)
{
try
{
ReadIvarList(reader, cls.instanceClass, name, classRO.ivars);
}
catch (...)
{
m_logger->LogError("Failed to process ivars for class at 0x%llx", clsStruct.data);
}
}
m_classes[classPtr] = cls;
}
}
std::optional<std::string> ObjCProcessor::ClassNameForTargetOfPointerAt(ObjCReader* reader, uint64_t offset)
{
auto savedOffset = reader->GetOffset();
reader->Seek(offset);
auto target = ReadPointerAccountingForRelocations(reader);
reader->Seek(savedOffset);
if (target) {
// Classes defined in the current image must be looked up in m_classes
// as adding their symbol may be deferred.
if (auto it = m_classes.find(target); it != m_classes.end())
return it->second.name;
// Classes defined in other images are looked up by their symbol name.
// This is common for cross-image references in the shared cache.
if (auto symbol = GetSymbol(target))
{
if (auto className = ClassNameFromSymbolName(symbol))
return *className;
}
}
// If there's no target, or we can't find a symbol for it, check whether the pointer has a relocation
// that contains a symbol. This is the case for cross-image references outside of the shared cache.
for (const auto& relocation : m_data->GetRelocationsAt(offset))
{
if (auto symbol = relocation->GetSymbol())
return ClassNameFromSymbolName(symbol);
}
return std::nullopt;
}
void ObjCProcessor::LoadCategories(ObjCReader* reader, Ref<Section> classPtrSection)
{
if (!classPtrSection)
return;
auto size = classPtrSection->GetEnd() - classPtrSection->GetStart();
if (size == 0)
return;
auto ptrSize = m_data->GetAddressSize();
auto classPtrSectionStart = classPtrSection->GetStart();
auto classPtrSectionEnd = classPtrSection->GetEnd();
auto catType = Type::NamedType(m_data, m_typeNames.category);
auto ptrType = Type::PointerType(m_data->GetDefaultArchitecture(), catType);
for (size_t i = classPtrSectionStart; i < classPtrSectionEnd; i += ptrSize)
{
Class category;
category_t cat;
reader->Seek(i);
auto catLocation = ReadPointerAccountingForRelocations(reader);
reader->Seek(catLocation);
try
{
cat.name = ReadPointerAccountingForRelocations(reader);
cat.cls = ReadPointerAccountingForRelocations(reader);
cat.instanceMethods = ReadPointerAccountingForRelocations(reader);
cat.classMethods = ReadPointerAccountingForRelocations(reader);
cat.protocols = ReadPointerAccountingForRelocations(reader);
cat.instanceProperties = ReadPointerAccountingForRelocations(reader);
}
catch (...)
{
m_logger->LogError("Failed to read category pointed to by 0x%llx", i);
continue;
}
std::string categoryAdditionsName;
std::string categoryBaseClassName =
ClassNameForTargetOfPointerAt(reader, catLocation + ptrSize).value_or(std::string());
if (categoryBaseClassName.empty())
{
m_logger->LogInfo("Using base address as stand-in classname for category at 0x%llx", catLocation);
categoryBaseClassName = fmt::format("{:x}", catLocation);
}
try
{
reader->Seek(cat.name);
categoryAdditionsName = reader->ReadCString();
}
catch (...)
{
m_logger->LogWarn(
"Failed to read category name for category at 0x%llx. Using base address as stand-in category name",
catLocation);
categoryAdditionsName = fmt::format("{:x}", catLocation);
}
category.name = categoryBaseClassName + " (" + categoryAdditionsName + ")";
DefineObjCSymbol(BNSymbolType::DataSymbol, ptrType, "categoryPtr_" + category.name, i, true);
DefineObjCSymbol(BNSymbolType::DataSymbol, catType, "category_" + category.name, catLocation, true);
if (cat.instanceMethods)
{
try
{
ReadMethodList(reader, category.instanceClass, category.name, cat.instanceMethods);
}
catch (...)
{
m_logger->LogError(
"Failed to read the instance method list for category pointed to by 0x%llx", catLocation);
}
}
if (cat.classMethods)
{
try
{
ReadMethodList(reader, category.metaClass, category.name, cat.classMethods);
}
catch (...)
{
m_logger->LogError(
"Failed to read the class method list for category pointed to by 0x%llx", catLocation);
}
}
m_categories[catLocation] = category;
}
}
void ObjCProcessor::LoadProtocols(ObjCReader* reader, Ref<Section> listSection)
{
if (!listSection)
return;
auto size = listSection->GetEnd() - listSection->GetStart();
if (size == 0)
return;
auto ptrSize = m_data->GetAddressSize();
auto listSectionStart = listSection->GetStart();
auto listSectionEnd = listSection->GetEnd();
auto protocolType = Type::NamedType(m_data, m_typeNames.protocol);
auto ptrType = Type::PointerType(m_data->GetDefaultArchitecture(), protocolType);
for (size_t i = listSectionStart; i < listSectionEnd; i += ptrSize)
{
protocol_t protocol;
reader->Seek(i);
auto protocolLocation = ReadPointerAccountingForRelocations(reader);
reader->Seek(protocolLocation);
try
{
protocol.isa = ReadPointerAccountingForRelocations(reader);
protocol.mangledName = ReadPointerAccountingForRelocations(reader);
protocol.protocols = ReadPointerAccountingForRelocations(reader);
protocol.instanceMethods = ReadPointerAccountingForRelocations(reader);
protocol.classMethods = ReadPointerAccountingForRelocations(reader);
protocol.optionalInstanceMethods = ReadPointerAccountingForRelocations(reader);
protocol.optionalClassMethods = ReadPointerAccountingForRelocations(reader);
protocol.instanceProperties = ReadPointerAccountingForRelocations(reader);
}
catch (...)
{
m_logger->LogError("Failed to read protocol pointed to by 0x%llx", i);
continue;
}
std::string protocolName;
try
{
reader->Seek(protocol.mangledName);
protocolName = reader->ReadCString();
DefineObjCSymbol(BNSymbolType::DataSymbol,
Type::ArrayType(Type::IntegerType(1, true), protocolName.size() + 1), "protocolName_" + protocolName,
protocol.mangledName, true);
}
catch (...)
{
m_logger->LogError(
"Failed to read protocol name for protocol at 0x%llx. Using base address as stand-in protocol name",
protocolLocation);
protocolName = fmt::format("{:x}", protocolLocation);
}
Protocol protocolClass;
protocolClass.name = protocolName;
DefineObjCSymbol(BNSymbolType::DataSymbol, ptrType, "protocolPtr_" + protocolName, i, true);
DefineObjCSymbol(BNSymbolType::DataSymbol, protocolType, "protocol_" + protocolName, protocolLocation, true);
if (protocol.protocols)
{
DefineObjCSymbol(BNSymbolType::DataSymbol, Type::NamedType(m_data, m_typeNames.protocolList),
"protoProtocols_" + protocolName, protocol.protocols, true);
reader->Seek(protocol.protocols);
uint32_t count = reader->Read64();
view_ptr_t addr = reader->GetOffset();
for (uint32_t j = 0; j < count; j++)
{
m_data->DefineDataVariable(
addr, Type::PointerType(ptrSize, Type::NamedType(m_data, m_typeNames.protocol)));
addr += ptrSize;
}
}
if (protocol.instanceMethods)
{
try
{
ReadMethodList(reader, protocolClass.instanceMethods, protocolName, protocol.instanceMethods);
}
catch (...)
{
m_logger->LogError(
"Failed to read the instance method list for protocol pointed to by 0x%llx", protocolLocation);
}
}
if (protocol.classMethods)
{
try
{
ReadMethodList(reader, protocolClass.classMethods, protocolName, protocol.classMethods);
}
catch (...)
{
m_logger->LogError(
"Failed to read the class method list for protocol pointed to by 0x%llx", protocolLocation);
}
}
if (protocol.optionalInstanceMethods)
{
try
{
ReadMethodList(
reader, protocolClass.optionalInstanceMethods, protocolName, protocol.optionalInstanceMethods);
}
catch (...)
{
m_logger->LogError("Failed to read the optional instance method list for protocol pointed to by 0x%llx",
protocolLocation);
}
}
if (protocol.optionalClassMethods)
{
try
{
ReadMethodList(reader, protocolClass.optionalClassMethods, protocolName, protocol.optionalClassMethods);
}
catch (...)
{
m_logger->LogError("Failed to read the optional class method list for protocol pointed to by 0x%llx",
protocolLocation);
}
}
m_protocols[protocolLocation] = protocolClass;
}
}
void ObjCProcessor::GetRelativeMethod(ObjCReader* reader, method_t& meth)
{
uint64_t offset = reader->GetOffset();
meth.name = offset + reader->ReadS32();
offset += sizeof(int32_t);
meth.types = offset + reader->ReadS32();
offset += sizeof(int32_t);
meth.imp = offset + reader->ReadS32();
}
void ObjCProcessor::ReadListOfMethodLists(ObjCReader* reader, ClassBase& cls, std::string_view name, view_ptr_t start)
{
reader->Seek(start);
method_list_t head;
head.entsizeAndFlags = reader->Read32();
head.count = reader->Read32();
if (head.count > 0x1000)
{
m_logger->LogError("List of method lists at 0x%llx has an invalid count of 0x%x", start, head.count);
return;
}
for (size_t i = 0; i < head.count; ++i) {
relative_list_list_entry_t list_entry;
reader->Read(&list_entry, sizeof(list_entry));
ReadMethodList(reader, cls, name, reader->GetOffset() - sizeof(list_entry) + list_entry.listOffset);
// Reset the cursor to immediately past the list entry.
reader->Seek(start + sizeof(method_list_t) + ((i + 1) * sizeof(relative_list_list_entry_t)));
}
}
void ObjCProcessor::ReadMethodList(ObjCReader* reader, ClassBase& cls, std::string_view name, view_ptr_t start)
{
// Lower two bits indicate the type of method list.
switch (start & 0b11) {
case 0:
break;
case 1:
return ReadListOfMethodLists(reader, cls, name, start - 1);
default:
m_logger->LogDebug("ReadMethodList: Unknown method list type at 0x%llx: %d", start, start & 0x3);
return;
}
reader->Seek(start);
method_list_t head;
head.entsizeAndFlags = reader->Read32();
head.count = reader->Read32();
if (head.count > 0x1000)
{
m_logger->LogError("Method list at 0x%llx has an invalid count of 0x%x", start, head.count);
return;
}
uint64_t pointerSize = m_data->GetAddressSize();
bool relativeOffsets = (head.entsizeAndFlags & 0xFFFF0000) & 0x80000000;
bool directSelectors = (head.entsizeAndFlags & 0xFFFF0000) & 0x40000000;
auto methodSize = relativeOffsets ? 12 : pointerSize * 3;
DefineObjCSymbol(DataSymbol, m_typeNames.methodList, "method_list_" + std::string(name), start, true);
for (unsigned i = 0; i < head.count; i++)
{
try
{
Method method;
auto cursor = start + sizeof(method_list_t) + (i * methodSize);
reader->Seek(cursor);
method_t meth;
// workflow_objc support
uint64_t selRefAddr = 0;
uint64_t selAddr = 0;
// --
if (relativeOffsets)
{
GetRelativeMethod(reader, meth);
}
else
{
meth.name = ReadPointerAccountingForRelocations(reader);
meth.types = ReadPointerAccountingForRelocations(reader);
meth.imp = ReadPointerAccountingForRelocations(reader);
}
if (!relativeOffsets || directSelectors)
{
reader->Seek(meth.name);
selAddr = meth.name;
method.name = reader->ReadCString();
reader->Seek(meth.types);
method.types = reader->ReadCString();
DefineObjCSymbol(DataSymbol, Type::ArrayType(Type::IntegerType(1, true), method.name.size() + 1),