forked from llvm/llvm-project
- Notifications
You must be signed in to change notification settings - Fork 339
/
Copy pathObjC.cpp
1512 lines (1232 loc) · 59.5 KB
/
ObjC.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
//===- ObjC.cpp -----------------------------------------------------------===//
//
// 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"ObjC.h"
#include"ConcatOutputSection.h"
#include"InputFiles.h"
#include"InputSection.h"
#include"Layout.h"
#include"OutputSegment.h"
#include"SyntheticSections.h"
#include"Target.h"
#include"lld/Common/ErrorHandler.h"
#include"llvm/ADT/DenseMap.h"
#include"llvm/BinaryFormat/MachO.h"
#include"llvm/Bitcode/BitcodeReader.h"
#include"llvm/Support/TimeProfiler.h"
usingnamespacellvm;
usingnamespacellvm::MachO;
usingnamespacelld;
usingnamespacelld::macho;
template <classLP> staticboolobjectHasObjCSection(MemoryBufferRef mb) {
using SectionHeader = typename LP::section;
auto *hdr =
reinterpret_cast<consttypename LP::mach_header *>(mb.getBufferStart());
if (hdr->magic != LP::magic)
returnfalse;
if (constauto *c =
findCommand<typename LP::segment_command>(hdr, LP::segmentLCType)) {
auto sectionHeaders = ArrayRef<SectionHeader>{
reinterpret_cast<const SectionHeader *>(c + 1), c->nsects};
for (const SectionHeader &secHead : sectionHeaders) {
StringRef sectname(secHead.sectname,
strnlen(secHead.sectname, sizeof(secHead.sectname)));
StringRef segname(secHead.segname,
strnlen(secHead.segname, sizeof(secHead.segname)));
if ((segname == segment_names::data &&
sectname == section_names::objcCatList) ||
(segname == segment_names::text &&
sectname.starts_with(section_names::swift))) {
returntrue;
}
}
}
returnfalse;
}
staticboolobjectHasObjCSection(MemoryBufferRef mb) {
if (target->wordSize == 8)
return ::objectHasObjCSection<LP64>(mb);
else
return ::objectHasObjCSection<ILP32>(mb);
}
boolmacho::hasObjCSection(MemoryBufferRef mb) {
switch (identify_magic(mb.getBuffer())) {
case file_magic::macho_object:
returnobjectHasObjCSection(mb);
case file_magic::bitcode:
returncheck(isBitcodeContainingObjCCategory(mb));
default:
returnfalse;
}
}
namespace {
#defineFOR_EACH_CATEGORY_FIELD(DO) \
DO(Ptr, name) \
DO(Ptr, klass) \
DO(Ptr, instanceMethods) \
DO(Ptr, classMethods) \
DO(Ptr, protocols) \
DO(Ptr, instanceProps) \
DO(Ptr, classProps) \
DO(uint32_t, size)
CREATE_LAYOUT_CLASS(Category, FOR_EACH_CATEGORY_FIELD);
#undef FOR_EACH_CATEGORY_FIELD
#defineFOR_EACH_CLASS_FIELD(DO) \
DO(Ptr, metaClass) \
DO(Ptr, superClass) \
DO(Ptr, methodCache) \
DO(Ptr, vtable) \
DO(Ptr, roData)
CREATE_LAYOUT_CLASS(Class, FOR_EACH_CLASS_FIELD);
#undef FOR_EACH_CLASS_FIELD
#defineFOR_EACH_RO_CLASS_FIELD(DO) \
DO(uint32_t, flags) \
DO(uint32_t, instanceStart) \
DO(Ptr, instanceSize) \
DO(Ptr, ivarLayout) \
DO(Ptr, name) \
DO(Ptr, baseMethods) \
DO(Ptr, baseProtocols) \
DO(Ptr, ivars) \
DO(Ptr, weakIvarLayout) \
DO(Ptr, baseProperties)
CREATE_LAYOUT_CLASS(ROClass, FOR_EACH_RO_CLASS_FIELD);
#undef FOR_EACH_RO_CLASS_FIELD
#defineFOR_EACH_LIST_HEADER(DO) \
DO(uint32_t, structSize) \
DO(uint32_t, structCount)
CREATE_LAYOUT_CLASS(ListHeader, FOR_EACH_LIST_HEADER);
#undef FOR_EACH_LIST_HEADER
#defineFOR_EACH_PROTOCOL_LIST_HEADER(DO) DO(Ptr, protocolCount)
CREATE_LAYOUT_CLASS(ProtocolListHeader, FOR_EACH_PROTOCOL_LIST_HEADER);
#undef FOR_EACH_PROTOCOL_LIST_HEADER
#defineFOR_EACH_METHOD(DO) \
DO(Ptr, name) \
DO(Ptr, type) \
DO(Ptr, impl)
CREATE_LAYOUT_CLASS(Method, FOR_EACH_METHOD);
#undef FOR_EACH_METHOD
enum MethodContainerKind {
MCK_Class,
MCK_Category,
};
structMethodContainer {
MethodContainerKind kind;
const ConcatInputSection *isec;
};
enum MethodKind {
MK_Instance,
MK_Static,
};
structObjcClass {
DenseMap<CachedHashStringRef, MethodContainer> instanceMethods;
DenseMap<CachedHashStringRef, MethodContainer> classMethods;
};
} // namespace
classObjcCategoryChecker {
public:
ObjcCategoryChecker();
voidparseCategory(const ConcatInputSection *catListIsec);
private:
voidparseClass(const Defined *classSym);
voidparseMethods(const ConcatInputSection *methodsIsec,
const Symbol *methodContainer,
const ConcatInputSection *containerIsec,
MethodContainerKind, MethodKind);
CategoryLayout catLayout;
ClassLayout classLayout;
ROClassLayout roClassLayout;
ListHeaderLayout listHeaderLayout;
MethodLayout methodLayout;
DenseMap<const Symbol *, ObjcClass> classMap;
};
ObjcCategoryChecker::ObjcCategoryChecker()
: catLayout(target->wordSize), classLayout(target->wordSize),
roClassLayout(target->wordSize), listHeaderLayout(target->wordSize),
methodLayout(target->wordSize) {}
voidObjcCategoryChecker::parseMethods(const ConcatInputSection *methodsIsec,
const Symbol *methodContainerSym,
const ConcatInputSection *containerIsec,
MethodContainerKind mcKind,
MethodKind mKind) {
ObjcClass &klass = classMap[methodContainerSym];
for (const Reloc &r : methodsIsec->relocs) {
if ((r.offset - listHeaderLayout.totalSize) % methodLayout.totalSize !=
methodLayout.nameOffset)
continue;
CachedHashStringRef methodName(r.getReferentString());
// +load methods are special: all implementations are called by the runtime
// even if they are part of the same class. Thus there is no need to check
// for duplicates.
// NOTE: Instead of specifically checking for this method name, ld64 simply
// checks whether a class / category is present in __objc_nlclslist /
// __objc_nlcatlist respectively. This will be the case if the class /
// category has a +load method. It skips optimizing the categories if there
// are multiple +load methods. Since it does dupe checking as part of the
// optimization process, this avoids spurious dupe messages around +load,
// but it also means that legit dupe issues for other methods are ignored.
if (mKind == MK_Static && methodName.val() == "load")
continue;
auto &methodMap =
mKind == MK_Instance ? klass.instanceMethods : klass.classMethods;
if (methodMap
.try_emplace(methodName, MethodContainer{mcKind, containerIsec})
.second)
continue;
// We have a duplicate; generate a warning message.
constauto &mc = methodMap.lookup(methodName);
const Reloc *nameReloc = nullptr;
if (mc.kind == MCK_Category) {
nameReloc = mc.isec->getRelocAt(catLayout.nameOffset);
} else {
assert(mc.kind == MCK_Class);
constauto *roIsec = mc.isec->getRelocAt(classLayout.roDataOffset)
->getReferentInputSection();
nameReloc = roIsec->getRelocAt(roClassLayout.nameOffset);
}
StringRef containerName = nameReloc->getReferentString();
StringRef methPrefix = mKind == MK_Instance ? "-" : "+";
// We should only ever encounter collisions when parsing category methods
// (since the Class struct is parsed before any of its categories).
assert(mcKind == MCK_Category);
StringRef newCatName =
containerIsec->getRelocAt(catLayout.nameOffset)->getReferentString();
auto formatObjAndSrcFileName = [](const InputSection *section) {
lld::macho::InputFile *inputFile = section->getFile();
std::string result = toString(inputFile);
auto objFile = dyn_cast_or_null<ObjFile>(inputFile);
if (objFile && objFile->compileUnit)
result += " (" + objFile->sourceFile() + ")";
return result;
};
StringRef containerType = mc.kind == MCK_Category ? "category" : "class";
warn("method '" + methPrefix + methodName.val() +
"' has conflicting definitions:\n>>> defined in category " +
newCatName + " from " + formatObjAndSrcFileName(containerIsec) +
"\n>>> defined in " + containerType + "" + containerName + " from " +
formatObjAndSrcFileName(mc.isec));
}
}
voidObjcCategoryChecker::parseCategory(const ConcatInputSection *catIsec) {
auto *classReloc = catIsec->getRelocAt(catLayout.klassOffset);
if (!classReloc)
return;
auto *classSym = cast<Symbol *>(classReloc->referent);
if (auto *d = dyn_cast<Defined>(classSym))
if (!classMap.count(d))
parseClass(d);
if (constauto *r = catIsec->getRelocAt(catLayout.classMethodsOffset)) {
parseMethods(cast<ConcatInputSection>(r->getReferentInputSection()),
classSym, catIsec, MCK_Category, MK_Static);
}
if (constauto *r = catIsec->getRelocAt(catLayout.instanceMethodsOffset)) {
parseMethods(cast<ConcatInputSection>(r->getReferentInputSection()),
classSym, catIsec, MCK_Category, MK_Instance);
}
}
voidObjcCategoryChecker::parseClass(const Defined *classSym) {
// Given a Class struct, get its corresponding Methods struct
auto getMethodsIsec =
[&](const InputSection *classIsec) -> ConcatInputSection * {
if (constauto *r = classIsec->getRelocAt(classLayout.roDataOffset)) {
if (constauto *roIsec =
cast_or_null<ConcatInputSection>(r->getReferentInputSection())) {
if (constauto *r =
roIsec->getRelocAt(roClassLayout.baseMethodsOffset)) {
if (auto *methodsIsec = cast_or_null<ConcatInputSection>(
r->getReferentInputSection()))
return methodsIsec;
}
}
}
returnnullptr;
};
constauto *classIsec = cast<ConcatInputSection>(classSym->isec());
// Parse instance methods.
if (constauto *instanceMethodsIsec = getMethodsIsec(classIsec))
parseMethods(instanceMethodsIsec, classSym, classIsec, MCK_Class,
MK_Instance);
// Class methods are contained in the metaclass.
if (constauto *r = classSym->isec()->getRelocAt(classLayout.metaClassOffset))
if (constauto *classMethodsIsec = getMethodsIsec(
cast<ConcatInputSection>(r->getReferentInputSection())))
parseMethods(classMethodsIsec, classSym, classIsec, MCK_Class, MK_Static);
}
voidobjc::checkCategories() {
TimeTraceScope timeScope("ObjcCategoryChecker");
ObjcCategoryChecker checker;
for (const InputSection *isec : inputSections) {
if (isec->getName() == section_names::objcCatList)
for (const Reloc &r : isec->relocs) {
auto *catIsec = cast<ConcatInputSection>(r.getReferentInputSection());
checker.parseCategory(catIsec);
}
}
}
namespace {
classObjcCategoryMerger {
// In which language was a particular construct originally defined
enum SourceLanguage { Unknown, ObjC, Swift };
// Information about an input category
structInfoInputCategory {
ConcatInputSection *catListIsec;
ConcatInputSection *catBodyIsec;
uint32_t offCatListIsec = 0;
SourceLanguage sourceLanguage = SourceLanguage::Unknown;
bool wasMerged = false;
};
// To write new (merged) categories or classes, we will try make limited
// assumptions about the alignment and the sections the various class/category
// info are stored in and . So we'll just reuse the same sections and
// alignment as already used in existing (input) categories. To do this we
// have InfoCategoryWriter which contains the various sections that the
// generated categories will be written to.
structInfoWriteSection {
bool valid = false; // Data has been successfully collected from input
uint32_t align = 0;
Section *inputSection;
Reloc relocTemplate;
OutputSection *outputSection;
};
structInfoCategoryWriter {
InfoWriteSection catListInfo;
InfoWriteSection catBodyInfo;
InfoWriteSection catNameInfo;
InfoWriteSection catPtrListInfo;
};
// Information about a pointer list in the original categories or class(method
// lists, protocol lists, etc)
structPointerListInfo {
PointerListInfo() = default;
PointerListInfo(const PointerListInfo &) = default;
PointerListInfo(constchar *_categoryPrefix, uint32_t _pointersPerStruct)
: categoryPrefix(_categoryPrefix),
pointersPerStruct(_pointersPerStruct) {}
inlinebooloperator==(const PointerListInfo &cmp) const {
return pointersPerStruct == cmp.pointersPerStruct &&
structSize == cmp.structSize && structCount == cmp.structCount &&
allPtrs == cmp.allPtrs;
}
constchar *categoryPrefix;
uint32_t pointersPerStruct = 0;
uint32_t structSize = 0;
uint32_t structCount = 0;
std::vector<Symbol *> allPtrs;
};
// Full information describing an ObjC class . This will include all the
// additional methods, protocols, and properties that are contained in the
// class and all the categories that extend a particular class.
structClassExtensionInfo {
ClassExtensionInfo(CategoryLayout &_catLayout) : catLayout(_catLayout){};
// Merged names of containers. Ex: base|firstCategory|secondCategory|...
std::string mergedContainerName;
std::string baseClassName;
const Symbol *baseClass = nullptr;
SourceLanguage baseClassSourceLanguage = SourceLanguage::Unknown;
CategoryLayout &catLayout;
// In case we generate new data, mark the new data as belonging to this file
ObjFile *objFileForMergeData = nullptr;
PointerListInfo instanceMethods = {objc::symbol_names::instanceMethods,
/*pointersPerStruct=*/3};
PointerListInfo classMethods = {objc::symbol_names::categoryClassMethods,
/*pointersPerStruct=*/3};
PointerListInfo protocols = {objc::symbol_names::categoryProtocols,
/*pointersPerStruct=*/0};
PointerListInfo instanceProps = {objc::symbol_names::listProprieties,
/*pointersPerStruct=*/2};
PointerListInfo classProps = {objc::symbol_names::klassPropList,
/*pointersPerStruct=*/2};
};
public:
ObjcCategoryMerger(std::vector<ConcatInputSection *> &_allInputSections);
voiddoMerge();
staticvoiddoCleanup();
private:
DenseSet<const Symbol *> collectNlCategories();
voidcollectAndValidateCategoriesData();
bool
mergeCategoriesIntoSingleCategory(std::vector<InfoInputCategory> &categories);
voideraseISec(ConcatInputSection *isec);
voideraseMergedCategories();
voidgenerateCatListForNonErasedCategories(
MapVector<ConcatInputSection *, std::set<uint64_t>>
catListToErasedOffsets);
voidcollectSectionWriteInfoFromIsec(const InputSection *isec,
InfoWriteSection &catWriteInfo);
boolcollectCategoryWriterInfoFromCategory(const InfoInputCategory &catInfo);
boolparseCatInfoToExtInfo(const InfoInputCategory &catInfo,
ClassExtensionInfo &extInfo);
voidparseProtocolListInfo(const ConcatInputSection *isec, uint32_t secOffset,
PointerListInfo &ptrList,
SourceLanguage sourceLang);
PointerListInfo parseProtocolListInfo(const ConcatInputSection *isec,
uint32_t secOffset,
SourceLanguage sourceLang);
boolparsePointerListInfo(const ConcatInputSection *isec, uint32_t secOffset,
PointerListInfo &ptrList);
voidemitAndLinkPointerList(Defined *parentSym, uint32_t linkAtOffset,
const ClassExtensionInfo &extInfo,
const PointerListInfo &ptrList);
Defined *emitAndLinkProtocolList(Defined *parentSym, uint32_t linkAtOffset,
const ClassExtensionInfo &extInfo,
const PointerListInfo &ptrList);
Defined *emitCategory(const ClassExtensionInfo &extInfo);
Defined *emitCatListEntrySec(const std::string &forCategoryName,
const std::string &forBaseClassName,
ObjFile *objFile);
Defined *emitCategoryBody(const std::string &name, const Defined *nameSym,
const Symbol *baseClassSym,
const std::string &baseClassName, ObjFile *objFile);
Defined *emitCategoryName(const std::string &name, ObjFile *objFile);
voidcreateSymbolReference(Defined *refFrom, const Symbol *refTo,
uint32_t offset, const Reloc &relocTemplate);
Defined *tryFindDefinedOnIsec(const InputSection *isec, uint32_t offset);
Symbol *tryGetSymbolAtIsecOffset(const ConcatInputSection *isec,
uint32_t offset);
Defined *tryGetDefinedAtIsecOffset(const ConcatInputSection *isec,
uint32_t offset);
Defined *getClassRo(const Defined *classSym, bool getMetaRo);
SourceLanguage getClassSymSourceLang(const Defined *classSym);
boolmergeCategoriesIntoBaseClass(const Defined *baseClass,
std::vector<InfoInputCategory> &categories);
voideraseSymbolAtIsecOffset(ConcatInputSection *isec, uint32_t offset);
voidtryEraseDefinedAtIsecOffset(const ConcatInputSection *isec,
uint32_t offset);
// Allocate a null-terminated StringRef backed by generatedSectionData
StringRef newStringData(constchar *str);
// Allocate section data, backed by generatedSectionData
SmallVector<uint8_t> &newSectionData(uint32_t size);
CategoryLayout catLayout;
ClassLayout classLayout;
ROClassLayout roClassLayout;
ListHeaderLayout listHeaderLayout;
MethodLayout methodLayout;
ProtocolListHeaderLayout protocolListHeaderLayout;
InfoCategoryWriter infoCategoryWriter;
std::vector<ConcatInputSection *> &allInputSections;
// Map of base class Symbol to list of InfoInputCategory's for it
MapVector<const Symbol *, std::vector<InfoInputCategory>> categoryMap;
// Normally, the binary data comes from the input files, but since we're
// generating binary data ourselves, we use the below array to store it in.
// Need this to be 'static' so the data survives past the ObjcCategoryMerger
// object, as the data will be read by the Writer when the final binary is
// generated.
static SmallVector<std::unique_ptr<SmallVector<uint8_t>>>
generatedSectionData;
};
SmallVector<std::unique_ptr<SmallVector<uint8_t>>>
ObjcCategoryMerger::generatedSectionData;
ObjcCategoryMerger::ObjcCategoryMerger(
std::vector<ConcatInputSection *> &_allInputSections)
: catLayout(target->wordSize), classLayout(target->wordSize),
roClassLayout(target->wordSize), listHeaderLayout(target->wordSize),
methodLayout(target->wordSize),
protocolListHeaderLayout(target->wordSize),
allInputSections(_allInputSections) {}
voidObjcCategoryMerger::collectSectionWriteInfoFromIsec(
const InputSection *isec, InfoWriteSection &catWriteInfo) {
catWriteInfo.inputSection = const_cast<Section *>(&isec->section);
catWriteInfo.align = isec->align;
catWriteInfo.outputSection = isec->parent;
assert(catWriteInfo.outputSection &&
"outputSection may not be null in collectSectionWriteInfoFromIsec.");
if (isec->relocs.size())
catWriteInfo.relocTemplate = isec->relocs[0];
catWriteInfo.valid = true;
}
Symbol *
ObjcCategoryMerger::tryGetSymbolAtIsecOffset(const ConcatInputSection *isec,
uint32_t offset) {
if (!isec)
returnnullptr;
const Reloc *reloc = isec->getRelocAt(offset);
if (!reloc)
returnnullptr;
Symbol *sym = dyn_cast_if_present<Symbol *>(reloc->referent);
if (reloc->addend && sym) {
assert(isa<Defined>(sym) && "Expected defined for non-zero addend");
Defined *definedSym = cast<Defined>(sym);
sym = tryFindDefinedOnIsec(definedSym->isec(),
definedSym->value + reloc->addend);
}
return sym;
}
Defined *ObjcCategoryMerger::tryFindDefinedOnIsec(const InputSection *isec,
uint32_t offset) {
for (Defined *sym : isec->symbols)
if ((sym->value <= offset) && (sym->value + sym->size > offset))
return sym;
returnnullptr;
}
Defined *
ObjcCategoryMerger::tryGetDefinedAtIsecOffset(const ConcatInputSection *isec,
uint32_t offset) {
Symbol *sym = tryGetSymbolAtIsecOffset(isec, offset);
return dyn_cast_or_null<Defined>(sym);
}
// Get the class's ro_data symbol. If getMetaRo is true, then we will return
// the meta-class's ro_data symbol. Otherwise, we will return the class
// (instance) ro_data symbol.
Defined *ObjcCategoryMerger::getClassRo(const Defined *classSym,
bool getMetaRo) {
ConcatInputSection *isec = dyn_cast<ConcatInputSection>(classSym->isec());
if (!isec)
returnnullptr;
if (!getMetaRo)
returntryGetDefinedAtIsecOffset(isec, classLayout.roDataOffset +
classSym->value);
Defined *metaClass = tryGetDefinedAtIsecOffset(
isec, classLayout.metaClassOffset + classSym->value);
if (!metaClass)
returnnullptr;
returntryGetDefinedAtIsecOffset(
dyn_cast<ConcatInputSection>(metaClass->isec()),
classLayout.roDataOffset);
}
// Given an ConcatInputSection or CStringInputSection and an offset, if there is
// a symbol(Defined) at that offset, then erase the symbol (mark it not live)
voidObjcCategoryMerger::tryEraseDefinedAtIsecOffset(
const ConcatInputSection *isec, uint32_t offset) {
const Reloc *reloc = isec->getRelocAt(offset);
if (!reloc)
return;
Defined *sym = dyn_cast_or_null<Defined>(cast<Symbol *>(reloc->referent));
if (!sym)
return;
if (auto *cisec = dyn_cast_or_null<ConcatInputSection>(sym->isec()))
eraseISec(cisec);
elseif (auto *csisec = dyn_cast_or_null<CStringInputSection>(sym->isec())) {
uint32_t totalOffset = sym->value + reloc->addend;
StringPiece &piece = csisec->getStringPiece(totalOffset);
piece.live = false;
} else {
llvm_unreachable("erased symbol has to be Defined or CStringInputSection");
}
}
boolObjcCategoryMerger::collectCategoryWriterInfoFromCategory(
const InfoInputCategory &catInfo) {
if (!infoCategoryWriter.catListInfo.valid)
collectSectionWriteInfoFromIsec(catInfo.catListIsec,
infoCategoryWriter.catListInfo);
if (!infoCategoryWriter.catBodyInfo.valid)
collectSectionWriteInfoFromIsec(catInfo.catBodyIsec,
infoCategoryWriter.catBodyInfo);
if (!infoCategoryWriter.catNameInfo.valid) {
lld::macho::Defined *catNameSym =
tryGetDefinedAtIsecOffset(catInfo.catBodyIsec, catLayout.nameOffset);
if (!catNameSym) {
// This is an unhandeled case where the category name is not a symbol but
// instead points to an CStringInputSection (that doesn't have any symbol)
// TODO: Find a small repro and either fix or add a test case for this
// scenario
returnfalse;
}
collectSectionWriteInfoFromIsec(catNameSym->isec(),
infoCategoryWriter.catNameInfo);
}
// Collect writer info from all the category lists (we're assuming they all
// would provide the same info)
if (!infoCategoryWriter.catPtrListInfo.valid) {
for (uint32_t off = catLayout.instanceMethodsOffset;
off <= catLayout.classPropsOffset; off += target->wordSize) {
if (Defined *ptrList =
tryGetDefinedAtIsecOffset(catInfo.catBodyIsec, off)) {
collectSectionWriteInfoFromIsec(ptrList->isec(),
infoCategoryWriter.catPtrListInfo);
// we've successfully collected data, so we can break
break;
}
}
}
returntrue;
}
// Parse a protocol list that might be linked to ConcatInputSection at a given
// offset. The format of the protocol list is different than other lists (prop
// lists, method lists) so we need to parse it differently
voidObjcCategoryMerger::parseProtocolListInfo(
const ConcatInputSection *isec, uint32_t secOffset,
PointerListInfo &ptrList, [[maybe_unused]] SourceLanguage sourceLang) {
assert((isec && (secOffset + target->wordSize <= isec->data.size())) &&
"Tried to read pointer list beyond protocol section end");
const Reloc *reloc = isec->getRelocAt(secOffset);
if (!reloc)
return;
auto *ptrListSym = dyn_cast_or_null<Defined>(cast<Symbol *>(reloc->referent));
assert(ptrListSym && "Protocol list reloc does not have a valid Defined");
// Theoretically protocol count can be either 32b or 64b, depending on
// platform pointer size, but to simplify implementation we always just read
// the lower 32b which should be good enough.
uint32_t protocolCount = *reinterpret_cast<constuint32_t *>(
ptrListSym->isec()->data.data() + listHeaderLayout.structSizeOffset);
ptrList.structCount += protocolCount;
ptrList.structSize = target->wordSize;
[[maybe_unused]] uint32_t expectedListSize =
(protocolCount * target->wordSize) +
/*header(count)*/ protocolListHeaderLayout.totalSize +
/*extra null value*/ target->wordSize;
// On Swift, the protocol list does not have the extra (unnecessary) null
[[maybe_unused]] uint32_t expectedListSizeSwift =
expectedListSize - target->wordSize;
assert(((expectedListSize == ptrListSym->isec()->data.size() &&
sourceLang == SourceLanguage::ObjC) ||
(expectedListSizeSwift == ptrListSym->isec()->data.size() &&
sourceLang == SourceLanguage::Swift)) &&
"Protocol list does not match expected size");
uint32_t off = protocolListHeaderLayout.totalSize;
for (uint32_t inx = 0; inx < protocolCount; ++inx) {
const Reloc *reloc = ptrListSym->isec()->getRelocAt(off);
assert(reloc && "No reloc found at protocol list offset");
auto *listSym = dyn_cast_or_null<Defined>(cast<Symbol *>(reloc->referent));
assert(listSym && "Protocol list reloc does not have a valid Defined");
ptrList.allPtrs.push_back(listSym);
off += target->wordSize;
}
assert((ptrListSym->isec()->getRelocAt(off) == nullptr) &&
"expected null terminating protocol");
assert(off + /*extra null value*/ target->wordSize == expectedListSize &&
"Protocol list end offset does not match expected size");
}
// Parse a protocol list and return the PointerListInfo for it
ObjcCategoryMerger::PointerListInfo
ObjcCategoryMerger::parseProtocolListInfo(const ConcatInputSection *isec,
uint32_t secOffset,
SourceLanguage sourceLang) {
PointerListInfo ptrList;
parseProtocolListInfo(isec, secOffset, ptrList, sourceLang);
return ptrList;
}
// Parse a pointer list that might be linked to ConcatInputSection at a given
// offset. This can be used for instance methods, class methods, instance props
// and class props since they have the same format.
boolObjcCategoryMerger::parsePointerListInfo(const ConcatInputSection *isec,
uint32_t secOffset,
PointerListInfo &ptrList) {
assert(ptrList.pointersPerStruct == 2 || ptrList.pointersPerStruct == 3);
assert(isec && "Trying to parse pointer list from null isec");
assert(secOffset + target->wordSize <= isec->data.size() &&
"Trying to read pointer list beyond section end");
const Reloc *reloc = isec->getRelocAt(secOffset);
// Empty list is a valid case, return true.
if (!reloc)
returntrue;
auto *ptrListSym = dyn_cast_or_null<Defined>(cast<Symbol *>(reloc->referent));
assert(ptrListSym && "Reloc does not have a valid Defined");
uint32_t thisStructSize = *reinterpret_cast<constuint32_t *>(
ptrListSym->isec()->data.data() + listHeaderLayout.structSizeOffset);
uint32_t thisStructCount = *reinterpret_cast<constuint32_t *>(
ptrListSym->isec()->data.data() + listHeaderLayout.structCountOffset);
assert(thisStructSize == ptrList.pointersPerStruct * target->wordSize);
assert(!ptrList.structSize || (thisStructSize == ptrList.structSize));
ptrList.structCount += thisStructCount;
ptrList.structSize = thisStructSize;
uint32_t expectedListSize =
listHeaderLayout.totalSize + (thisStructSize * thisStructCount);
assert(expectedListSize == ptrListSym->isec()->data.size() &&
"Pointer list does not match expected size");
for (uint32_t off = listHeaderLayout.totalSize; off < expectedListSize;
off += target->wordSize) {
const Reloc *reloc = ptrListSym->isec()->getRelocAt(off);
assert(reloc && "No reloc found at pointer list offset");
auto *listSym =
dyn_cast_or_null<Defined>(reloc->referent.dyn_cast<Symbol *>());
// Sometimes, the reloc points to a StringPiece (InputSection + addend)
// instead of a symbol.
// TODO: Skip these cases for now, but we should fix this.
if (!listSym)
returnfalse;
ptrList.allPtrs.push_back(listSym);
}
returntrue;
}
// Here we parse all the information of an input category (catInfo) and
// append the parsed info into the structure which will contain all the
// information about how a class is extended (extInfo)
boolObjcCategoryMerger::parseCatInfoToExtInfo(const InfoInputCategory &catInfo,
ClassExtensionInfo &extInfo) {
const Reloc *catNameReloc =
catInfo.catBodyIsec->getRelocAt(catLayout.nameOffset);
// Parse name
assert(catNameReloc && "Category does not have a reloc at 'nameOffset'");
// is this the first category we are parsing?
if (extInfo.mergedContainerName.empty())
extInfo.objFileForMergeData =
dyn_cast_or_null<ObjFile>(catInfo.catBodyIsec->getFile());
else
extInfo.mergedContainerName += "|";
assert(extInfo.objFileForMergeData &&
"Expected to already have valid objextInfo.objFileForMergeData");
StringRef catName = catNameReloc->getReferentString();
extInfo.mergedContainerName += catName.str();
// Parse base class
if (!extInfo.baseClass) {
Symbol *classSym =
tryGetSymbolAtIsecOffset(catInfo.catBodyIsec, catLayout.klassOffset);
assert(extInfo.baseClassName.empty());
extInfo.baseClass = classSym;
llvm::StringRef classPrefix(objc::symbol_names::klass);
assert(classSym->getName().starts_with(classPrefix) &&
"Base class symbol does not start with expected prefix");
extInfo.baseClassName = classSym->getName().substr(classPrefix.size());
} else {
assert((extInfo.baseClass ==
tryGetSymbolAtIsecOffset(catInfo.catBodyIsec,
catLayout.klassOffset)) &&
"Trying to parse category info into container with different base "
"class");
}
if (!parsePointerListInfo(catInfo.catBodyIsec,
catLayout.instanceMethodsOffset,
extInfo.instanceMethods))
returnfalse;
if (!parsePointerListInfo(catInfo.catBodyIsec, catLayout.classMethodsOffset,
extInfo.classMethods))
returnfalse;
parseProtocolListInfo(catInfo.catBodyIsec, catLayout.protocolsOffset,
extInfo.protocols, catInfo.sourceLanguage);
if (!parsePointerListInfo(catInfo.catBodyIsec, catLayout.instancePropsOffset,
extInfo.instanceProps))
returnfalse;
if (!parsePointerListInfo(catInfo.catBodyIsec, catLayout.classPropsOffset,
extInfo.classProps))
returnfalse;
returntrue;
}
// Generate a protocol list (including header) and link it into the parent at
// the specified offset.
Defined *ObjcCategoryMerger::emitAndLinkProtocolList(
Defined *parentSym, uint32_t linkAtOffset,
const ClassExtensionInfo &extInfo, const PointerListInfo &ptrList) {
if (ptrList.allPtrs.empty())
returnnullptr;
assert(ptrList.allPtrs.size() == ptrList.structCount);
uint32_t bodySize = (ptrList.structCount * target->wordSize) +
/*header(count)*/ protocolListHeaderLayout.totalSize +
/*extra null value*/ target->wordSize;
llvm::ArrayRef<uint8_t> bodyData = newSectionData(bodySize);
// This theoretically can be either 32b or 64b, but writing just the first 32b
// is good enough
constuint32_t *ptrProtoCount = reinterpret_cast<constuint32_t *>(
bodyData.data() + protocolListHeaderLayout.protocolCountOffset);
*const_cast<uint32_t *>(ptrProtoCount) = ptrList.allPtrs.size();
ConcatInputSection *listSec = make<ConcatInputSection>(
*infoCategoryWriter.catPtrListInfo.inputSection, bodyData,
infoCategoryWriter.catPtrListInfo.align);
listSec->parent = infoCategoryWriter.catPtrListInfo.outputSection;
listSec->live = true;
listSec->parent = infoCategoryWriter.catPtrListInfo.outputSection;
std::string symName = ptrList.categoryPrefix;
symName += extInfo.baseClassName + "(" + extInfo.mergedContainerName + ")";
Defined *ptrListSym = make<Defined>(
newStringData(symName.c_str()), /*file=*/parentSym->getObjectFile(),
listSec, /*value=*/0, bodyData.size(), /*isWeakDef=*/false,
/*isExternal=*/false, /*isPrivateExtern=*/false, /*includeInSymtab=*/true,
/*isReferencedDynamically=*/false, /*noDeadStrip=*/false,
/*isWeakDefCanBeHidden=*/false);
ptrListSym->used = true;
parentSym->getObjectFile()->symbols.push_back(ptrListSym);
addInputSection(listSec);
createSymbolReference(parentSym, ptrListSym, linkAtOffset,
infoCategoryWriter.catBodyInfo.relocTemplate);
uint32_t offset = protocolListHeaderLayout.totalSize;
for (Symbol *symbol : ptrList.allPtrs) {
createSymbolReference(ptrListSym, symbol, offset,
infoCategoryWriter.catPtrListInfo.relocTemplate);
offset += target->wordSize;
}
return ptrListSym;
}
// Generate a pointer list (including header) and link it into the parent at the
// specified offset. This is used for instance and class methods and
// proprieties.
voidObjcCategoryMerger::emitAndLinkPointerList(
Defined *parentSym, uint32_t linkAtOffset,
const ClassExtensionInfo &extInfo, const PointerListInfo &ptrList) {
if (ptrList.allPtrs.empty())
return;
assert(ptrList.allPtrs.size() * target->wordSize ==
ptrList.structCount * ptrList.structSize);
// Generate body
uint32_t bodySize =
listHeaderLayout.totalSize + (ptrList.structSize * ptrList.structCount);
llvm::ArrayRef<uint8_t> bodyData = newSectionData(bodySize);
constuint32_t *ptrStructSize = reinterpret_cast<constuint32_t *>(
bodyData.data() + listHeaderLayout.structSizeOffset);
constuint32_t *ptrStructCount = reinterpret_cast<constuint32_t *>(
bodyData.data() + listHeaderLayout.structCountOffset);
*const_cast<uint32_t *>(ptrStructSize) = ptrList.structSize;
*const_cast<uint32_t *>(ptrStructCount) = ptrList.structCount;
ConcatInputSection *listSec = make<ConcatInputSection>(
*infoCategoryWriter.catPtrListInfo.inputSection, bodyData,
infoCategoryWriter.catPtrListInfo.align);
listSec->parent = infoCategoryWriter.catPtrListInfo.outputSection;
listSec->live = true;
listSec->parent = infoCategoryWriter.catPtrListInfo.outputSection;
std::string symName = ptrList.categoryPrefix;
symName += extInfo.baseClassName + "(" + extInfo.mergedContainerName + ")";
Defined *ptrListSym = make<Defined>(
newStringData(symName.c_str()), /*file=*/parentSym->getObjectFile(),
listSec, /*value=*/0, bodyData.size(), /*isWeakDef=*/false,
/*isExternal=*/false, /*isPrivateExtern=*/false, /*includeInSymtab=*/true,
/*isReferencedDynamically=*/false, /*noDeadStrip=*/false,
/*isWeakDefCanBeHidden=*/false);
ptrListSym->used = true;
parentSym->getObjectFile()->symbols.push_back(ptrListSym);
addInputSection(listSec);
createSymbolReference(parentSym, ptrListSym, linkAtOffset,
infoCategoryWriter.catBodyInfo.relocTemplate);
uint32_t offset = listHeaderLayout.totalSize;
for (Symbol *symbol : ptrList.allPtrs) {
createSymbolReference(ptrListSym, symbol, offset,
infoCategoryWriter.catPtrListInfo.relocTemplate);
offset += target->wordSize;
}
}
// This method creates an __objc_catlist ConcatInputSection with a single slot
Defined *
ObjcCategoryMerger::emitCatListEntrySec(const std::string &forCategoryName,
const std::string &forBaseClassName,
ObjFile *objFile) {
uint32_t sectionSize = target->wordSize;
llvm::ArrayRef<uint8_t> bodyData = newSectionData(sectionSize);
ConcatInputSection *newCatList =
make<ConcatInputSection>(*infoCategoryWriter.catListInfo.inputSection,
bodyData, infoCategoryWriter.catListInfo.align);
newCatList->parent = infoCategoryWriter.catListInfo.outputSection;
newCatList->live = true;
newCatList->parent = infoCategoryWriter.catListInfo.outputSection;
std::string catSymName = "<__objc_catlist slot for merged category ";
catSymName += forBaseClassName + "(" + forCategoryName + ")>";
Defined *catListSym = make<Defined>(
newStringData(catSymName.c_str()), /*file=*/objFile, newCatList,
/*value=*/0, bodyData.size(), /*isWeakDef=*/false, /*isExternal=*/false,
/*isPrivateExtern=*/false, /*includeInSymtab=*/false,
/*isReferencedDynamically=*/false, /*noDeadStrip=*/false,
/*isWeakDefCanBeHidden=*/false);
catListSym->used = true;
objFile->symbols.push_back(catListSym);
addInputSection(newCatList);
return catListSym;
}
// Here we generate the main category body and link the name and base class into
// it. We don't link any other info yet like the protocol and class/instance
// methods/props.