1//===- ObjC.cpp -----------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "ObjC.h"
10#include "ConcatOutputSection.h"
11#include "InputFiles.h"
12#include "InputSection.h"
13#include "Layout.h"
14#include "OutputSegment.h"
15#include "SyntheticSections.h"
16#include "Target.h"
17
18#include "lld/Common/ErrorHandler.h"
19#include "llvm/ADT/DenseMap.h"
20#include "llvm/Bitcode/BitcodeReader.h"
21#include "llvm/Support/TimeProfiler.h"
22
23using namespace llvm;
24using namespace llvm::MachO;
25using namespace lld;
26using namespace lld::macho;
27
28template <class LP> static bool objectHasObjCSection(MemoryBufferRef mb) {
29 using SectionHeader = typename LP::section;
30
31 auto *hdr =
32 reinterpret_cast<const typename LP::mach_header *>(mb.getBufferStart());
33 if (hdr->magic != LP::magic)
34 return false;
35
36 if (const auto *c =
37 findCommand<typename LP::segment_command>(hdr, LP::segmentLCType)) {
38 auto sectionHeaders = ArrayRef<SectionHeader>{
39 reinterpret_cast<const SectionHeader *>(c + 1), c->nsects};
40 for (const SectionHeader &secHead : sectionHeaders) {
41 StringRef sectname(secHead.sectname,
42 strnlen(secHead.sectname, sizeof(secHead.sectname)));
43 StringRef segname(secHead.segname,
44 strnlen(secHead.segname, sizeof(secHead.segname)));
45 if ((segname == segment_names::data &&
46 sectname == section_names::objcCatList) ||
47 (segname == segment_names::text &&
48 sectname.starts_with(Prefix: section_names::swift))) {
49 return true;
50 }
51 }
52 }
53 return false;
54}
55
56static bool objectHasObjCSection(MemoryBufferRef mb) {
57 if (target->wordSize == 8)
58 return ::objectHasObjCSection<LP64>(mb);
59 else
60 return ::objectHasObjCSection<ILP32>(mb);
61}
62
63bool macho::hasObjCSection(MemoryBufferRef mb) {
64 switch (identify_magic(magic: mb.getBuffer())) {
65 case file_magic::macho_object:
66 return objectHasObjCSection(mb);
67 case file_magic::bitcode:
68 return check(e: isBitcodeContainingObjCCategory(Buffer: mb));
69 default:
70 return false;
71 }
72}
73
74namespace {
75
76#define FOR_EACH_CATEGORY_FIELD(DO) \
77 DO(Ptr, name) \
78 DO(Ptr, klass) \
79 DO(Ptr, instanceMethods) \
80 DO(Ptr, classMethods) \
81 DO(Ptr, protocols) \
82 DO(Ptr, instanceProps) \
83 DO(Ptr, classProps) \
84 DO(uint32_t, size)
85
86CREATE_LAYOUT_CLASS(Category, FOR_EACH_CATEGORY_FIELD);
87
88#undef FOR_EACH_CATEGORY_FIELD
89
90#define FOR_EACH_CLASS_FIELD(DO) \
91 DO(Ptr, metaClass) \
92 DO(Ptr, superClass) \
93 DO(Ptr, methodCache) \
94 DO(Ptr, vtable) \
95 DO(Ptr, roData)
96
97CREATE_LAYOUT_CLASS(Class, FOR_EACH_CLASS_FIELD);
98
99#undef FOR_EACH_CLASS_FIELD
100
101#define FOR_EACH_RO_CLASS_FIELD(DO) \
102 DO(uint32_t, flags) \
103 DO(uint32_t, instanceStart) \
104 DO(Ptr, instanceSize) \
105 DO(Ptr, ivarLayout) \
106 DO(Ptr, name) \
107 DO(Ptr, baseMethods) \
108 DO(Ptr, baseProtocols) \
109 DO(Ptr, ivars) \
110 DO(Ptr, weakIvarLayout) \
111 DO(Ptr, baseProperties)
112
113CREATE_LAYOUT_CLASS(ROClass, FOR_EACH_RO_CLASS_FIELD);
114
115#undef FOR_EACH_RO_CLASS_FIELD
116
117#define FOR_EACH_LIST_HEADER(DO) \
118 DO(uint32_t, structSize) \
119 DO(uint32_t, structCount)
120
121CREATE_LAYOUT_CLASS(ListHeader, FOR_EACH_LIST_HEADER);
122
123#undef FOR_EACH_LIST_HEADER
124
125#define FOR_EACH_PROTOCOL_LIST_HEADER(DO) DO(Ptr, protocolCount)
126
127CREATE_LAYOUT_CLASS(ProtocolListHeader, FOR_EACH_PROTOCOL_LIST_HEADER);
128
129#undef FOR_EACH_PROTOCOL_LIST_HEADER
130
131#define FOR_EACH_METHOD(DO) \
132 DO(Ptr, name) \
133 DO(Ptr, type) \
134 DO(Ptr, impl)
135
136CREATE_LAYOUT_CLASS(Method, FOR_EACH_METHOD);
137
138#undef FOR_EACH_METHOD
139
140enum MethodContainerKind {
141 MCK_Class,
142 MCK_Category,
143};
144
145struct MethodContainer {
146 MethodContainerKind kind;
147 const ConcatInputSection *isec;
148};
149
150enum MethodKind {
151 MK_Instance,
152 MK_Static,
153};
154
155struct ObjcClass {
156 DenseMap<CachedHashStringRef, MethodContainer> instanceMethods;
157 DenseMap<CachedHashStringRef, MethodContainer> classMethods;
158};
159
160} // namespace
161
162class ObjcCategoryChecker {
163public:
164 ObjcCategoryChecker();
165 void parseCategory(const ConcatInputSection *catListIsec);
166
167private:
168 void parseClass(const Defined *classSym);
169 void parseMethods(const ConcatInputSection *methodsIsec,
170 const Symbol *methodContainer,
171 const ConcatInputSection *containerIsec,
172 MethodContainerKind, MethodKind);
173
174 CategoryLayout catLayout;
175 ClassLayout classLayout;
176 ROClassLayout roClassLayout;
177 ListHeaderLayout listHeaderLayout;
178 MethodLayout methodLayout;
179
180 DenseMap<const Symbol *, ObjcClass> classMap;
181};
182
183ObjcCategoryChecker::ObjcCategoryChecker()
184 : catLayout(target->wordSize), classLayout(target->wordSize),
185 roClassLayout(target->wordSize), listHeaderLayout(target->wordSize),
186 methodLayout(target->wordSize) {}
187
188void ObjcCategoryChecker::parseMethods(const ConcatInputSection *methodsIsec,
189 const Symbol *methodContainerSym,
190 const ConcatInputSection *containerIsec,
191 MethodContainerKind mcKind,
192 MethodKind mKind) {
193 ObjcClass &klass = classMap[methodContainerSym];
194 for (const Relocation &r : methodsIsec->relocs) {
195 if ((r.offset - listHeaderLayout.totalSize) % methodLayout.totalSize !=
196 methodLayout.nameOffset)
197 continue;
198
199 CachedHashStringRef methodName(r.getReferentString());
200 // +load methods are special: all implementations are called by the runtime
201 // even if they are part of the same class. Thus there is no need to check
202 // for duplicates.
203 // NOTE: Instead of specifically checking for this method name, ld64 simply
204 // checks whether a class / category is present in __objc_nlclslist /
205 // __objc_nlcatlist respectively. This will be the case if the class /
206 // category has a +load method. It skips optimizing the categories if there
207 // are multiple +load methods. Since it does dupe checking as part of the
208 // optimization process, this avoids spurious dupe messages around +load,
209 // but it also means that legit dupe issues for other methods are ignored.
210 if (mKind == MK_Static && methodName.val() == "load")
211 continue;
212
213 auto &methodMap =
214 mKind == MK_Instance ? klass.instanceMethods : klass.classMethods;
215 if (methodMap
216 .try_emplace(Key: methodName, Args: MethodContainer{.kind: mcKind, .isec: containerIsec})
217 .second)
218 continue;
219
220 // We have a duplicate; generate a warning message.
221 const auto &mc = methodMap.lookup(Val: methodName);
222 const Relocation *nameReloc = nullptr;
223 if (mc.kind == MCK_Category) {
224 nameReloc = mc.isec->getRelocAt(off: catLayout.nameOffset);
225 } else {
226 assert(mc.kind == MCK_Class);
227 const auto *roIsec = mc.isec->getRelocAt(off: classLayout.roDataOffset)
228 ->getReferentInputSection();
229 nameReloc = roIsec->getRelocAt(off: roClassLayout.nameOffset);
230 }
231 StringRef containerName = nameReloc->getReferentString();
232 StringRef methPrefix = mKind == MK_Instance ? "-" : "+";
233
234 // We should only ever encounter collisions when parsing category methods
235 // (since the Class struct is parsed before any of its categories).
236 assert(mcKind == MCK_Category);
237 StringRef newCatName =
238 containerIsec->getRelocAt(off: catLayout.nameOffset)->getReferentString();
239
240 auto formatObjAndSrcFileName = [](const InputSection *section) {
241 lld::macho::InputFile *inputFile = section->getFile();
242 std::string result = toString(file: inputFile);
243
244 auto objFile = dyn_cast_or_null<ObjFile>(Val: inputFile);
245 if (objFile && objFile->compileUnit)
246 result += " (" + objFile->sourceFile() + ")";
247
248 return result;
249 };
250
251 StringRef containerType = mc.kind == MCK_Category ? "category" : "class";
252 warn(msg: "method '" + methPrefix + methodName.val() +
253 "' has conflicting definitions:\n>>> defined in category " +
254 newCatName + " from " + formatObjAndSrcFileName(containerIsec) +
255 "\n>>> defined in " + containerType + " " + containerName + " from " +
256 formatObjAndSrcFileName(mc.isec));
257 }
258}
259
260void ObjcCategoryChecker::parseCategory(const ConcatInputSection *catIsec) {
261 auto *classReloc = catIsec->getRelocAt(off: catLayout.klassOffset);
262 if (!classReloc)
263 return;
264
265 auto *classSym = cast<Symbol *>(Val: classReloc->referent);
266 if (auto *d = dyn_cast<Defined>(Val: classSym))
267 if (!classMap.contains(Val: d))
268 parseClass(classSym: d);
269
270 if (const auto *r = catIsec->getRelocAt(off: catLayout.classMethodsOffset)) {
271 parseMethods(methodsIsec: cast<ConcatInputSection>(Val: r->getReferentInputSection()),
272 methodContainerSym: classSym, containerIsec: catIsec, mcKind: MCK_Category, mKind: MK_Static);
273 }
274
275 if (const auto *r = catIsec->getRelocAt(off: catLayout.instanceMethodsOffset)) {
276 parseMethods(methodsIsec: cast<ConcatInputSection>(Val: r->getReferentInputSection()),
277 methodContainerSym: classSym, containerIsec: catIsec, mcKind: MCK_Category, mKind: MK_Instance);
278 }
279}
280
281void ObjcCategoryChecker::parseClass(const Defined *classSym) {
282 // Given a Class struct, get its corresponding Methods struct
283 auto getMethodsIsec =
284 [&](const InputSection *classIsec) -> ConcatInputSection * {
285 if (const auto *r = classIsec->getRelocAt(off: classLayout.roDataOffset)) {
286 if (const auto *roIsec =
287 cast_or_null<ConcatInputSection>(Val: r->getReferentInputSection())) {
288 if (const auto *r =
289 roIsec->getRelocAt(off: roClassLayout.baseMethodsOffset)) {
290 if (auto *methodsIsec = cast_or_null<ConcatInputSection>(
291 Val: r->getReferentInputSection()))
292 return methodsIsec;
293 }
294 }
295 }
296 return nullptr;
297 };
298
299 const auto *classIsec = cast<ConcatInputSection>(Val: classSym->isec());
300
301 // Parse instance methods.
302 if (const auto *instanceMethodsIsec = getMethodsIsec(classIsec))
303 parseMethods(methodsIsec: instanceMethodsIsec, methodContainerSym: classSym, containerIsec: classIsec, mcKind: MCK_Class,
304 mKind: MK_Instance);
305
306 // Class methods are contained in the metaclass.
307 if (const auto *r = classSym->isec()->getRelocAt(off: classLayout.metaClassOffset))
308 if (const auto *classMethodsIsec = getMethodsIsec(
309 cast<ConcatInputSection>(Val: r->getReferentInputSection())))
310 parseMethods(methodsIsec: classMethodsIsec, methodContainerSym: classSym, containerIsec: classIsec, mcKind: MCK_Class, mKind: MK_Static);
311}
312
313void objc::checkCategories() {
314 TimeTraceScope timeScope("ObjcCategoryChecker");
315
316 ObjcCategoryChecker checker;
317 for (const InputSection *isec : inputSections) {
318 if (isec->getName() == section_names::objcCatList)
319 for (const Relocation &r : isec->relocs) {
320 auto *catIsec = cast<ConcatInputSection>(Val: r.getReferentInputSection());
321 checker.parseCategory(catIsec);
322 }
323 }
324}
325
326namespace {
327
328class ObjcCategoryMerger {
329 // Information about an input category
330 struct InfoInputCategory {
331 ConcatInputSection *catListIsec;
332 ConcatInputSection *catBodyIsec;
333 uint32_t offCatListIsec = 0;
334
335 bool wasMerged = false;
336 };
337
338 // To write new (merged) categories or classes, we will try make limited
339 // assumptions about the alignment and the sections the various class/category
340 // info are stored in and . So we'll just reuse the same sections and
341 // alignment as already used in existing (input) categories. To do this we
342 // have InfoCategoryWriter which contains the various sections that the
343 // generated categories will be written to.
344 struct InfoWriteSection {
345 bool valid = false; // Data has been successfully collected from input
346 uint32_t align = 0;
347 Section *inputSection;
348 Relocation relocTemplate;
349 OutputSection *outputSection;
350 };
351
352 struct InfoCategoryWriter {
353 InfoWriteSection catListInfo;
354 InfoWriteSection catBodyInfo;
355 InfoWriteSection catNameInfo;
356 InfoWriteSection catPtrListInfo;
357 };
358
359 // Information about a pointer list in the original categories or class(method
360 // lists, protocol lists, etc)
361 struct PointerListInfo {
362 PointerListInfo() = default;
363 PointerListInfo(const PointerListInfo &) = default;
364 PointerListInfo(const char *_categoryPrefix, uint32_t _pointersPerStruct)
365 : categoryPrefix(_categoryPrefix),
366 pointersPerStruct(_pointersPerStruct) {}
367
368 inline bool operator==(const PointerListInfo &cmp) const {
369 return pointersPerStruct == cmp.pointersPerStruct &&
370 structSize == cmp.structSize && structCount == cmp.structCount &&
371 allPtrs == cmp.allPtrs;
372 }
373
374 const char *categoryPrefix;
375
376 uint32_t pointersPerStruct = 0;
377
378 uint32_t structSize = 0;
379 uint32_t structCount = 0;
380
381 std::vector<Symbol *> allPtrs;
382 };
383
384 // Full information describing an ObjC class . This will include all the
385 // additional methods, protocols, and properties that are contained in the
386 // class and all the categories that extend a particular class.
387 struct ClassExtensionInfo {
388 ClassExtensionInfo(CategoryLayout &_catLayout) : catLayout(_catLayout){};
389
390 // Merged names of containers. Ex: base|firstCategory|secondCategory|...
391 std::string mergedContainerName;
392 std::string baseClassName;
393 const Symbol *baseClass = nullptr;
394 int64_t baseClassAddend = 0;
395
396 void setBaseClass(const Symbol *sym, int64_t addend) {
397 assert(!baseClass && baseClassName.empty());
398 baseClass = sym;
399 baseClassAddend = addend;
400 StringRef name = sym->getName();
401 name.consume_front(Prefix: objc::symbol_names::klass);
402 baseClassName = name.str();
403 }
404
405 CategoryLayout &catLayout;
406
407 // In case we generate new data, mark the new data as belonging to this file
408 ObjFile *objFileForMergeData = nullptr;
409
410 PointerListInfo instanceMethods = {objc::symbol_names::instanceMethods,
411 /*pointersPerStruct=*/3};
412 PointerListInfo classMethods = {objc::symbol_names::categoryClassMethods,
413 /*pointersPerStruct=*/3};
414 PointerListInfo protocols = {objc::symbol_names::categoryProtocols,
415 /*pointersPerStruct=*/0};
416 PointerListInfo instanceProps = {objc::symbol_names::listProprieties,
417 /*pointersPerStruct=*/2};
418 PointerListInfo classProps = {objc::symbol_names::klassPropList,
419 /*pointersPerStruct=*/2};
420 };
421
422public:
423 ObjcCategoryMerger(std::vector<ConcatInputSection *> &_allInputSections);
424 void doMerge();
425 static void doCleanup();
426
427private:
428 DenseSet<const Symbol *> collectNlCategories();
429 void collectAndValidateCategoriesData();
430 bool
431 mergeCategoriesIntoSingleCategory(std::vector<InfoInputCategory> &categories);
432
433 void eraseISec(ConcatInputSection *isec);
434 void eraseMergedCategories();
435
436 void generateCatListForNonErasedCategories(
437 MapVector<ConcatInputSection *, std::set<uint64_t>>
438 catListToErasedOffsets);
439 void collectSectionWriteInfoFromIsec(const InputSection *isec,
440 InfoWriteSection &catWriteInfo);
441 bool collectCategoryWriterInfoFromCategory(const InfoInputCategory &catInfo);
442 bool parseCatInfoToExtInfo(const InfoInputCategory &catInfo,
443 ClassExtensionInfo &extInfo);
444
445 void parseProtocolListInfo(const ConcatInputSection *isec, uint32_t secOffset,
446 PointerListInfo &ptrList);
447
448 PointerListInfo parseProtocolListInfo(const ConcatInputSection *isec,
449 uint32_t secOffset);
450
451 bool parsePointerListInfo(const ConcatInputSection *isec, uint32_t secOffset,
452 PointerListInfo &ptrList);
453
454 void emitAndLinkPointerList(Defined *parentSym, uint32_t linkAtOffset,
455 const ClassExtensionInfo &extInfo,
456 const PointerListInfo &ptrList);
457
458 Defined *emitAndLinkProtocolList(Defined *parentSym, uint32_t linkAtOffset,
459 const ClassExtensionInfo &extInfo,
460 const PointerListInfo &ptrList);
461
462 Defined *emitCategory(const ClassExtensionInfo &extInfo);
463 Defined *emitCatListEntrySec(const std::string &forCategoryName,
464 const std::string &forBaseClassName,
465 ObjFile *objFile);
466 Defined *emitCategoryBody(const std::string &name, const Defined *nameSym,
467 const Symbol *baseClassSym, int64_t baseClassAddend,
468 const std::string &baseClassName, ObjFile *objFile);
469 Defined *emitCategoryName(const std::string &name, ObjFile *objFile);
470 void createSymbolReference(Defined *refFrom, const Symbol *refTo,
471 uint32_t offset, const Relocation &relocTemplate,
472 int64_t addend = 0);
473 Defined *tryFindDefinedOnIsec(const InputSection *isec, uint32_t offset);
474 std::pair<Symbol *, int64_t>
475 tryGetSymbolReferenceAtIsecOffset(const ConcatInputSection *isec,
476 uint32_t offset);
477 Symbol *tryGetSymbolAtIsecOffset(const ConcatInputSection *isec,
478 uint32_t offset);
479 Defined *tryGetDefinedAtIsecOffset(const ConcatInputSection *isec,
480 uint32_t offset);
481 Defined *getClassRo(const Defined *classSym, int64_t classAddend,
482 bool getMetaRo);
483 bool mergeCategoriesIntoBaseClass(const Defined *baseClass,
484 int64_t baseClassAddend,
485 std::vector<InfoInputCategory> &categories);
486 void eraseSymbolAtIsecOffset(ConcatInputSection *isec, uint32_t offset);
487 void tryEraseDefinedAtIsecOffset(const ConcatInputSection *isec,
488 uint32_t offset);
489
490 // Allocate a null-terminated StringRef backed by generatedSectionData
491 StringRef newStringData(const char *str);
492 // Allocate section data, backed by generatedSectionData
493 SmallVector<uint8_t> &newSectionData(uint32_t size);
494
495 CategoryLayout catLayout;
496 ClassLayout classLayout;
497 ROClassLayout roClassLayout;
498 ListHeaderLayout listHeaderLayout;
499 MethodLayout methodLayout;
500 ProtocolListHeaderLayout protocolListHeaderLayout;
501
502 InfoCategoryWriter infoCategoryWriter;
503 std::vector<ConcatInputSection *> &allInputSections;
504 // Map of base class Symbol + residual addend to its categories. Swift class
505 // address points can be interior to a larger metadata symbol after LTO.
506 MapVector<std::pair<const Symbol *, int64_t>, std::vector<InfoInputCategory>>
507 categoryMap;
508
509 // Normally, the binary data comes from the input files, but since we're
510 // generating binary data ourselves, we use the below array to store it in.
511 // Need this to be 'static' so the data survives past the ObjcCategoryMerger
512 // object, as the data will be read by the Writer when the final binary is
513 // generated.
514 static SmallVector<std::unique_ptr<SmallVector<uint8_t>>>
515 generatedSectionData;
516};
517
518SmallVector<std::unique_ptr<SmallVector<uint8_t>>>
519 ObjcCategoryMerger::generatedSectionData;
520
521ObjcCategoryMerger::ObjcCategoryMerger(
522 std::vector<ConcatInputSection *> &_allInputSections)
523 : catLayout(target->wordSize), classLayout(target->wordSize),
524 roClassLayout(target->wordSize), listHeaderLayout(target->wordSize),
525 methodLayout(target->wordSize),
526 protocolListHeaderLayout(target->wordSize),
527 allInputSections(_allInputSections) {}
528
529void ObjcCategoryMerger::collectSectionWriteInfoFromIsec(
530 const InputSection *isec, InfoWriteSection &catWriteInfo) {
531
532 catWriteInfo.inputSection = const_cast<Section *>(&isec->section);
533 catWriteInfo.align = isec->align;
534 catWriteInfo.outputSection = isec->parent;
535
536 assert(catWriteInfo.outputSection &&
537 "outputSection may not be null in collectSectionWriteInfoFromIsec.");
538
539 if (isec->relocs.size())
540 catWriteInfo.relocTemplate = isec->relocs[0];
541
542 catWriteInfo.valid = true;
543}
544
545std::pair<Symbol *, int64_t>
546ObjcCategoryMerger::tryGetSymbolReferenceAtIsecOffset(
547 const ConcatInputSection *isec, uint32_t offset) {
548 if (!isec)
549 return {nullptr, 0};
550 const Relocation *reloc = isec->getRelocAt(off: offset);
551
552 if (!reloc)
553 return {nullptr, 0};
554
555 Symbol *sym = dyn_cast_if_present<Symbol *>(Val: reloc->referent);
556
557 if (reloc->getAddend() && sym) {
558 assert(isa<Defined>(sym) && "Expected defined for non-zero addend");
559 Defined *definedSym = cast<Defined>(Val: sym);
560 uint64_t targetOffset = definedSym->value + reloc->getAddend();
561 if (Defined *targetSym =
562 tryFindDefinedOnIsec(isec: definedSym->isec(), offset: targetOffset))
563 return {targetSym, targetOffset - targetSym->value};
564 }
565
566 return {sym, reloc->getAddend()};
567}
568
569Symbol *
570ObjcCategoryMerger::tryGetSymbolAtIsecOffset(const ConcatInputSection *isec,
571 uint32_t offset) {
572 return tryGetSymbolReferenceAtIsecOffset(isec, offset).first;
573}
574
575Defined *ObjcCategoryMerger::tryFindDefinedOnIsec(const InputSection *isec,
576 uint32_t offset) {
577 Defined *containing = nullptr;
578 for (Defined *sym : isec->symbols) {
579 if (sym->value == offset)
580 return sym;
581 if (sym->value < offset && sym->value + sym->size > offset &&
582 (!containing || sym->value > containing->value))
583 containing = sym;
584 }
585
586 return containing;
587}
588
589Defined *
590ObjcCategoryMerger::tryGetDefinedAtIsecOffset(const ConcatInputSection *isec,
591 uint32_t offset) {
592 Symbol *sym = tryGetSymbolAtIsecOffset(isec, offset);
593 return dyn_cast_or_null<Defined>(Val: sym);
594}
595
596// Get the class's ro_data symbol. If getMetaRo is true, then we will return
597// the meta-class's ro_data symbol. Otherwise, we will return the class
598// (instance) ro_data symbol.
599Defined *ObjcCategoryMerger::getClassRo(const Defined *classSym,
600 int64_t classAddend, bool getMetaRo) {
601 ConcatInputSection *isec = dyn_cast<ConcatInputSection>(Val: classSym->isec());
602 if (!isec)
603 return nullptr;
604
605 uint64_t classOffset = classSym->value + classAddend;
606 if (!getMetaRo)
607 return tryGetDefinedAtIsecOffset(isec,
608 offset: classLayout.roDataOffset + classOffset);
609
610 auto [metaClassSym, metaClassAddend] = tryGetSymbolReferenceAtIsecOffset(
611 isec, offset: classLayout.metaClassOffset + classOffset);
612 Defined *metaClass = dyn_cast_or_null<Defined>(Val: metaClassSym);
613 if (!metaClass)
614 return nullptr;
615
616 return tryGetDefinedAtIsecOffset(
617 isec: dyn_cast<ConcatInputSection>(Val: metaClass->isec()),
618 offset: classLayout.roDataOffset + metaClass->value + metaClassAddend);
619}
620
621// Given an ConcatInputSection or CStringInputSection and an offset, if there is
622// a symbol(Defined) at that offset, then erase the symbol (mark it not live)
623void ObjcCategoryMerger::tryEraseDefinedAtIsecOffset(
624 const ConcatInputSection *isec, uint32_t offset) {
625 const Relocation *reloc = isec->getRelocAt(off: offset);
626
627 if (!reloc)
628 return;
629
630 Defined *sym = dyn_cast_or_null<Defined>(Val: cast<Symbol *>(Val: reloc->referent));
631 if (!sym)
632 return;
633
634 if (auto *cisec = dyn_cast_or_null<ConcatInputSection>(Val: sym->isec()))
635 eraseISec(isec: cisec);
636 else if (auto *csisec = dyn_cast_or_null<CStringInputSection>(Val: sym->isec())) {
637 uint32_t totalOffset = sym->value + reloc->getAddend();
638 StringPiece &piece = csisec->getStringPiece(off: totalOffset);
639 piece.live = false;
640 } else {
641 llvm_unreachable("erased symbol has to be Defined or CStringInputSection");
642 }
643}
644
645bool ObjcCategoryMerger::collectCategoryWriterInfoFromCategory(
646 const InfoInputCategory &catInfo) {
647
648 if (!infoCategoryWriter.catListInfo.valid)
649 collectSectionWriteInfoFromIsec(isec: catInfo.catListIsec,
650 catWriteInfo&: infoCategoryWriter.catListInfo);
651 if (!infoCategoryWriter.catBodyInfo.valid)
652 collectSectionWriteInfoFromIsec(isec: catInfo.catBodyIsec,
653 catWriteInfo&: infoCategoryWriter.catBodyInfo);
654
655 if (!infoCategoryWriter.catNameInfo.valid) {
656 lld::macho::Defined *catNameSym =
657 tryGetDefinedAtIsecOffset(isec: catInfo.catBodyIsec, offset: catLayout.nameOffset);
658
659 if (!catNameSym) {
660 // This is an unhandled case where the category name is not a symbol but
661 // instead points to an CStringInputSection (that doesn't have any symbol)
662 // TODO: Find a small repro and either fix or add a test case for this
663 // scenario
664 return false;
665 }
666
667 collectSectionWriteInfoFromIsec(isec: catNameSym->isec(),
668 catWriteInfo&: infoCategoryWriter.catNameInfo);
669 }
670
671 // Collect writer info from all the category lists (we're assuming they all
672 // would provide the same info)
673 if (!infoCategoryWriter.catPtrListInfo.valid) {
674 for (uint32_t off = catLayout.instanceMethodsOffset;
675 off <= catLayout.classPropsOffset; off += target->wordSize) {
676 if (Defined *ptrList =
677 tryGetDefinedAtIsecOffset(isec: catInfo.catBodyIsec, offset: off)) {
678 collectSectionWriteInfoFromIsec(isec: ptrList->isec(),
679 catWriteInfo&: infoCategoryWriter.catPtrListInfo);
680 // we've successfully collected data, so we can break
681 break;
682 }
683 }
684 }
685
686 return true;
687}
688
689// Parse a protocol list that might be linked to ConcatInputSection at a given
690// offset. The format of the protocol list is different than other lists (prop
691// lists, method lists) so we need to parse it differently
692void ObjcCategoryMerger::parseProtocolListInfo(const ConcatInputSection *isec,
693 uint32_t secOffset,
694 PointerListInfo &ptrList) {
695 assert((isec && (secOffset + target->wordSize <= isec->data.size())) &&
696 "Tried to read pointer list beyond protocol section end");
697
698 const Relocation *reloc = isec->getRelocAt(off: secOffset);
699 if (!reloc)
700 return;
701
702 auto *ptrListSym = dyn_cast_or_null<Defined>(Val: cast<Symbol *>(Val: reloc->referent));
703 assert(ptrListSym && "Protocol list reloc does not have a valid Defined");
704
705 // Theoretically protocol count can be either 32b or 64b, depending on
706 // platform pointer size, but to simplify implementation we always just read
707 // the lower 32b which should be good enough.
708 uint32_t protocolCount = *reinterpret_cast<const uint32_t *>(
709 ptrListSym->isec()->data.data() + listHeaderLayout.structSizeOffset);
710
711 ptrList.structCount += protocolCount;
712 ptrList.structSize = target->wordSize;
713
714 [[maybe_unused]] uint32_t expectedListSize =
715 (protocolCount * target->wordSize) +
716 /*header(count)*/ protocolListHeaderLayout.totalSize +
717 /*extra null value*/ target->wordSize;
718
719 uint32_t off = protocolListHeaderLayout.totalSize;
720 for (uint32_t inx = 0; inx < protocolCount; ++inx) {
721 const Relocation *reloc = ptrListSym->isec()->getRelocAt(off);
722 assert(reloc && "No reloc found at protocol list offset");
723
724 auto *listSym = dyn_cast_or_null<Defined>(Val: cast<Symbol *>(Val: reloc->referent));
725 assert(listSym && "Protocol list reloc does not have a valid Defined");
726
727 ptrList.allPtrs.push_back(x: listSym);
728 off += target->wordSize;
729 }
730 assert((ptrListSym->isec()->getRelocAt(off) == nullptr) &&
731 "expected null terminating protocol");
732 assert(off + /*extra null value*/ target->wordSize == expectedListSize &&
733 "Protocol list end offset does not match expected size");
734}
735
736// Parse a protocol list and return the PointerListInfo for it
737ObjcCategoryMerger::PointerListInfo
738ObjcCategoryMerger::parseProtocolListInfo(const ConcatInputSection *isec,
739 uint32_t secOffset) {
740 PointerListInfo ptrList;
741 parseProtocolListInfo(isec, secOffset, ptrList);
742 return ptrList;
743}
744
745// Parse a pointer list that might be linked to ConcatInputSection at a given
746// offset. This can be used for instance methods, class methods, instance props
747// and class props since they have the same format.
748bool ObjcCategoryMerger::parsePointerListInfo(const ConcatInputSection *isec,
749 uint32_t secOffset,
750 PointerListInfo &ptrList) {
751 assert(ptrList.pointersPerStruct == 2 || ptrList.pointersPerStruct == 3);
752 assert(isec && "Trying to parse pointer list from null isec");
753 assert(secOffset + target->wordSize <= isec->data.size() &&
754 "Trying to read pointer list beyond section end");
755
756 const Relocation *reloc = isec->getRelocAt(off: secOffset);
757 // Empty list is a valid case, return true.
758 if (!reloc)
759 return true;
760
761 auto *ptrListSym = dyn_cast_or_null<Defined>(Val: cast<Symbol *>(Val: reloc->referent));
762 assert(ptrListSym && "Reloc does not have a valid Defined");
763
764 uint32_t thisStructSize = *reinterpret_cast<const uint32_t *>(
765 ptrListSym->isec()->data.data() + listHeaderLayout.structSizeOffset);
766 uint32_t thisStructCount = *reinterpret_cast<const uint32_t *>(
767 ptrListSym->isec()->data.data() + listHeaderLayout.structCountOffset);
768 assert(thisStructSize == ptrList.pointersPerStruct * target->wordSize);
769
770 assert(!ptrList.structSize || (thisStructSize == ptrList.structSize));
771
772 ptrList.structCount += thisStructCount;
773 ptrList.structSize = thisStructSize;
774
775 uint32_t expectedListSize =
776 listHeaderLayout.totalSize + (thisStructSize * thisStructCount);
777 assert(expectedListSize == ptrListSym->isec()->data.size() &&
778 "Pointer list does not match expected size");
779
780 for (uint32_t off = listHeaderLayout.totalSize; off < expectedListSize;
781 off += target->wordSize) {
782 const Relocation *reloc = ptrListSym->isec()->getRelocAt(off);
783 assert(reloc && "No reloc found at pointer list offset");
784
785 auto *listSym = dyn_cast_or_null<Defined>(
786 Val: dyn_cast_if_present<Symbol *>(Val: reloc->referent));
787 // Sometimes, the reloc points to a StringPiece (InputSection + addend)
788 // instead of a symbol.
789 // TODO: Skip these cases for now, but we should fix this.
790 if (!listSym)
791 return false;
792
793 ptrList.allPtrs.push_back(x: listSym);
794 }
795
796 return true;
797}
798
799// Here we parse all the information of an input category (catInfo) and
800// append the parsed info into the structure which will contain all the
801// information about how a class is extended (extInfo)
802bool ObjcCategoryMerger::parseCatInfoToExtInfo(const InfoInputCategory &catInfo,
803 ClassExtensionInfo &extInfo) {
804 const Relocation *catNameReloc =
805 catInfo.catBodyIsec->getRelocAt(off: catLayout.nameOffset);
806
807 // Parse name
808 assert(catNameReloc && "Category does not have a reloc at 'nameOffset'");
809
810 // is this the first category we are parsing?
811 if (extInfo.mergedContainerName.empty())
812 extInfo.objFileForMergeData =
813 dyn_cast_or_null<ObjFile>(Val: catInfo.catBodyIsec->getFile());
814 else
815 extInfo.mergedContainerName += "|";
816
817 assert(extInfo.objFileForMergeData &&
818 "Expected to already have valid objextInfo.objFileForMergeData");
819
820 StringRef catName = catNameReloc->getReferentString();
821 extInfo.mergedContainerName += catName.str();
822
823 // Parse base class
824 if (!extInfo.baseClass) {
825 auto [classSym, classAddend] = tryGetSymbolReferenceAtIsecOffset(
826 isec: catInfo.catBodyIsec, offset: catLayout.klassOffset);
827 extInfo.setBaseClass(sym: classSym, addend: classAddend);
828 } else {
829 [[maybe_unused]] auto [classSym, classAddend] =
830 tryGetSymbolReferenceAtIsecOffset(isec: catInfo.catBodyIsec,
831 offset: catLayout.klassOffset);
832 assert(!extInfo.baseClassName.empty());
833 assert((extInfo.baseClass == classSym &&
834 extInfo.baseClassAddend == classAddend) &&
835 "Trying to parse category info into container with different base "
836 "class");
837 }
838
839 if (!parsePointerListInfo(isec: catInfo.catBodyIsec,
840 secOffset: catLayout.instanceMethodsOffset,
841 ptrList&: extInfo.instanceMethods))
842 return false;
843
844 if (!parsePointerListInfo(isec: catInfo.catBodyIsec, secOffset: catLayout.classMethodsOffset,
845 ptrList&: extInfo.classMethods))
846 return false;
847
848 parseProtocolListInfo(isec: catInfo.catBodyIsec, secOffset: catLayout.protocolsOffset,
849 ptrList&: extInfo.protocols);
850
851 if (!parsePointerListInfo(isec: catInfo.catBodyIsec, secOffset: catLayout.instancePropsOffset,
852 ptrList&: extInfo.instanceProps))
853 return false;
854
855 if (!parsePointerListInfo(isec: catInfo.catBodyIsec, secOffset: catLayout.classPropsOffset,
856 ptrList&: extInfo.classProps))
857 return false;
858
859 return true;
860}
861
862// Generate a protocol list (including header) and link it into the parent at
863// the specified offset.
864Defined *ObjcCategoryMerger::emitAndLinkProtocolList(
865 Defined *parentSym, uint32_t linkAtOffset,
866 const ClassExtensionInfo &extInfo, const PointerListInfo &ptrList) {
867 if (ptrList.allPtrs.empty())
868 return nullptr;
869
870 assert(ptrList.allPtrs.size() == ptrList.structCount);
871
872 uint32_t bodySize = (ptrList.structCount * target->wordSize) +
873 /*header(count)*/ protocolListHeaderLayout.totalSize +
874 /*extra null value*/ target->wordSize;
875 llvm::ArrayRef<uint8_t> bodyData = newSectionData(size: bodySize);
876
877 // This theoretically can be either 32b or 64b, but writing just the first 32b
878 // is good enough
879 const uint32_t *ptrProtoCount = reinterpret_cast<const uint32_t *>(
880 bodyData.data() + protocolListHeaderLayout.protocolCountOffset);
881
882 *const_cast<uint32_t *>(ptrProtoCount) = ptrList.allPtrs.size();
883
884 ConcatInputSection *listSec = make<ConcatInputSection>(
885 args&: *infoCategoryWriter.catPtrListInfo.inputSection, args&: bodyData,
886 args&: infoCategoryWriter.catPtrListInfo.align);
887 listSec->parent = infoCategoryWriter.catPtrListInfo.outputSection;
888 listSec->live = true;
889
890 listSec->parent = infoCategoryWriter.catPtrListInfo.outputSection;
891
892 std::string symName = ptrList.categoryPrefix;
893 symName += extInfo.baseClassName + "(" + extInfo.mergedContainerName + ")";
894
895 Defined *ptrListSym = make<Defined>(
896 args: newStringData(str: symName.c_str()), /*file=*/args: parentSym->getObjectFile(),
897 args&: listSec, /*value=*/args: 0, args: bodyData.size(), /*isWeakDef=*/args: false,
898 /*isExternal=*/args: false, /*isPrivateExtern=*/args: false, /*includeInSymtab=*/args: true,
899 /*isReferencedDynamically=*/args: false, /*noDeadStrip=*/args: false,
900 /*isWeakDefCanBeHidden=*/args: false);
901
902 ptrListSym->used = true;
903 parentSym->getObjectFile()->symbols.push_back(x: ptrListSym);
904 addInputSection(inputSection: listSec);
905
906 createSymbolReference(refFrom: parentSym, refTo: ptrListSym, offset: linkAtOffset,
907 relocTemplate: infoCategoryWriter.catBodyInfo.relocTemplate);
908
909 uint32_t offset = protocolListHeaderLayout.totalSize;
910 for (Symbol *symbol : ptrList.allPtrs) {
911 createSymbolReference(refFrom: ptrListSym, refTo: symbol, offset,
912 relocTemplate: infoCategoryWriter.catPtrListInfo.relocTemplate);
913 offset += target->wordSize;
914 }
915
916 return ptrListSym;
917}
918
919// Generate a pointer list (including header) and link it into the parent at the
920// specified offset. This is used for instance and class methods and
921// proprieties.
922void ObjcCategoryMerger::emitAndLinkPointerList(
923 Defined *parentSym, uint32_t linkAtOffset,
924 const ClassExtensionInfo &extInfo, const PointerListInfo &ptrList) {
925 if (ptrList.allPtrs.empty())
926 return;
927
928 assert(ptrList.allPtrs.size() * target->wordSize ==
929 ptrList.structCount * ptrList.structSize);
930
931 // Generate body
932 uint32_t bodySize =
933 listHeaderLayout.totalSize + (ptrList.structSize * ptrList.structCount);
934 llvm::ArrayRef<uint8_t> bodyData = newSectionData(size: bodySize);
935
936 const uint32_t *ptrStructSize = reinterpret_cast<const uint32_t *>(
937 bodyData.data() + listHeaderLayout.structSizeOffset);
938 const uint32_t *ptrStructCount = reinterpret_cast<const uint32_t *>(
939 bodyData.data() + listHeaderLayout.structCountOffset);
940
941 *const_cast<uint32_t *>(ptrStructSize) = ptrList.structSize;
942 *const_cast<uint32_t *>(ptrStructCount) = ptrList.structCount;
943
944 ConcatInputSection *listSec = make<ConcatInputSection>(
945 args&: *infoCategoryWriter.catPtrListInfo.inputSection, args&: bodyData,
946 args&: infoCategoryWriter.catPtrListInfo.align);
947 listSec->parent = infoCategoryWriter.catPtrListInfo.outputSection;
948 listSec->live = true;
949
950 listSec->parent = infoCategoryWriter.catPtrListInfo.outputSection;
951
952 std::string symName = ptrList.categoryPrefix;
953 symName += extInfo.baseClassName + "(" + extInfo.mergedContainerName + ")";
954
955 Defined *ptrListSym = make<Defined>(
956 args: newStringData(str: symName.c_str()), /*file=*/args: parentSym->getObjectFile(),
957 args&: listSec, /*value=*/args: 0, args: bodyData.size(), /*isWeakDef=*/args: false,
958 /*isExternal=*/args: false, /*isPrivateExtern=*/args: false, /*includeInSymtab=*/args: true,
959 /*isReferencedDynamically=*/args: false, /*noDeadStrip=*/args: false,
960 /*isWeakDefCanBeHidden=*/args: false);
961
962 ptrListSym->used = true;
963 parentSym->getObjectFile()->symbols.push_back(x: ptrListSym);
964 addInputSection(inputSection: listSec);
965
966 createSymbolReference(refFrom: parentSym, refTo: ptrListSym, offset: linkAtOffset,
967 relocTemplate: infoCategoryWriter.catBodyInfo.relocTemplate);
968
969 uint32_t offset = listHeaderLayout.totalSize;
970 for (Symbol *symbol : ptrList.allPtrs) {
971 createSymbolReference(refFrom: ptrListSym, refTo: symbol, offset,
972 relocTemplate: infoCategoryWriter.catPtrListInfo.relocTemplate);
973 offset += target->wordSize;
974 }
975}
976
977// This method creates an __objc_catlist ConcatInputSection with a single slot
978Defined *
979ObjcCategoryMerger::emitCatListEntrySec(const std::string &forCategoryName,
980 const std::string &forBaseClassName,
981 ObjFile *objFile) {
982 uint32_t sectionSize = target->wordSize;
983 llvm::ArrayRef<uint8_t> bodyData = newSectionData(size: sectionSize);
984
985 ConcatInputSection *newCatList =
986 make<ConcatInputSection>(args&: *infoCategoryWriter.catListInfo.inputSection,
987 args&: bodyData, args&: infoCategoryWriter.catListInfo.align);
988 newCatList->parent = infoCategoryWriter.catListInfo.outputSection;
989 newCatList->live = true;
990
991 newCatList->parent = infoCategoryWriter.catListInfo.outputSection;
992
993 std::string catSymName = "<__objc_catlist slot for merged category ";
994 catSymName += forBaseClassName + "(" + forCategoryName + ")>";
995
996 Defined *catListSym = make<Defined>(
997 args: newStringData(str: catSymName.c_str()), /*file=*/args&: objFile, args&: newCatList,
998 /*value=*/args: 0, args: bodyData.size(), /*isWeakDef=*/args: false, /*isExternal=*/args: false,
999 /*isPrivateExtern=*/args: false, /*includeInSymtab=*/args: false,
1000 /*isReferencedDynamically=*/args: false, /*noDeadStrip=*/args: false,
1001 /*isWeakDefCanBeHidden=*/args: false);
1002
1003 catListSym->used = true;
1004 objFile->symbols.push_back(x: catListSym);
1005 addInputSection(inputSection: newCatList);
1006 return catListSym;
1007}
1008
1009// Here we generate the main category body and link the name and base class into
1010// it. We don't link any other info yet like the protocol and class/instance
1011// methods/props.
1012Defined *ObjcCategoryMerger::emitCategoryBody(const std::string &name,
1013 const Defined *nameSym,
1014 const Symbol *baseClassSym,
1015 int64_t baseClassAddend,
1016 const std::string &baseClassName,
1017 ObjFile *objFile) {
1018 llvm::ArrayRef<uint8_t> bodyData = newSectionData(size: catLayout.totalSize);
1019
1020 uint32_t *ptrSize = (uint32_t *)(const_cast<uint8_t *>(bodyData.data()) +
1021 catLayout.sizeOffset);
1022 *ptrSize = catLayout.totalSize;
1023
1024 ConcatInputSection *newBodySec =
1025 make<ConcatInputSection>(args&: *infoCategoryWriter.catBodyInfo.inputSection,
1026 args&: bodyData, args&: infoCategoryWriter.catBodyInfo.align);
1027 newBodySec->parent = infoCategoryWriter.catBodyInfo.outputSection;
1028 newBodySec->live = true;
1029
1030 std::string symName =
1031 objc::symbol_names::category + baseClassName + "(" + name + ")";
1032 Defined *catBodySym = make<Defined>(
1033 args: newStringData(str: symName.c_str()), /*file=*/args&: objFile, args&: newBodySec,
1034 /*value=*/args: 0, args: bodyData.size(), /*isWeakDef=*/args: false, /*isExternal=*/args: false,
1035 /*isPrivateExtern=*/args: false, /*includeInSymtab=*/args: true,
1036 /*isReferencedDynamically=*/args: false, /*noDeadStrip=*/args: false,
1037 /*isWeakDefCanBeHidden=*/args: false);
1038
1039 catBodySym->used = true;
1040 objFile->symbols.push_back(x: catBodySym);
1041 addInputSection(inputSection: newBodySec);
1042
1043 createSymbolReference(refFrom: catBodySym, refTo: nameSym, offset: catLayout.nameOffset,
1044 relocTemplate: infoCategoryWriter.catBodyInfo.relocTemplate);
1045
1046 // Create a reloc to the base class (either external or internal)
1047 createSymbolReference(refFrom: catBodySym, refTo: baseClassSym, offset: catLayout.klassOffset,
1048 relocTemplate: infoCategoryWriter.catBodyInfo.relocTemplate,
1049 addend: baseClassAddend);
1050
1051 return catBodySym;
1052}
1053
1054// This writes the new category name (for the merged category) into the binary
1055// and returns the sybmol for it.
1056Defined *ObjcCategoryMerger::emitCategoryName(const std::string &name,
1057 ObjFile *objFile) {
1058 StringRef nameStrData = newStringData(str: name.c_str());
1059 // We use +1 below to include the null terminator
1060 llvm::ArrayRef<uint8_t> nameData(
1061 reinterpret_cast<const uint8_t *>(nameStrData.data()),
1062 nameStrData.size() + 1);
1063
1064 auto *parentSection = infoCategoryWriter.catNameInfo.inputSection;
1065 CStringInputSection *newStringSec = make<CStringInputSection>(
1066 args&: *infoCategoryWriter.catNameInfo.inputSection, args&: nameData,
1067 args&: infoCategoryWriter.catNameInfo.align, /*dedupLiterals=*/args: true);
1068
1069 parentSection->subsections.push_back(x: {.offset: 0, .isec: newStringSec});
1070
1071 newStringSec->splitIntoPieces();
1072 newStringSec->pieces[0].live = true;
1073 newStringSec->parent = infoCategoryWriter.catNameInfo.outputSection;
1074 in.cStringSection->addInput(newStringSec);
1075 assert(newStringSec->pieces.size() == 1);
1076
1077 Defined *catNameSym = make<Defined>(
1078 args: "<merged category name>", /*file=*/args&: objFile, args&: newStringSec,
1079 /*value=*/args: 0, args: nameData.size(),
1080 /*isWeakDef=*/args: false, /*isExternal=*/args: false, /*isPrivateExtern=*/args: false,
1081 /*includeInSymtab=*/args: false, /*isReferencedDynamically=*/args: false,
1082 /*noDeadStrip=*/args: false, /*isWeakDefCanBeHidden=*/args: false);
1083
1084 catNameSym->used = true;
1085 objFile->symbols.push_back(x: catNameSym);
1086 return catNameSym;
1087}
1088
1089// This method fully creates a new category from the given ClassExtensionInfo.
1090// It creates the category name, body and method/protocol/prop lists and links
1091// them all together. Then it creates a new __objc_catlist entry and adds the
1092// category to it. Calling this method will fully generate a category which will
1093// be available in the final binary.
1094Defined *ObjcCategoryMerger::emitCategory(const ClassExtensionInfo &extInfo) {
1095 Defined *catNameSym = emitCategoryName(name: extInfo.mergedContainerName,
1096 objFile: extInfo.objFileForMergeData);
1097
1098 Defined *catBodySym =
1099 emitCategoryBody(name: extInfo.mergedContainerName, nameSym: catNameSym,
1100 baseClassSym: extInfo.baseClass, baseClassAddend: extInfo.baseClassAddend,
1101 baseClassName: extInfo.baseClassName, objFile: extInfo.objFileForMergeData);
1102
1103 Defined *catListSym =
1104 emitCatListEntrySec(forCategoryName: extInfo.mergedContainerName, forBaseClassName: extInfo.baseClassName,
1105 objFile: extInfo.objFileForMergeData);
1106
1107 // Add the single category body to the category list at the offset 0.
1108 createSymbolReference(refFrom: catListSym, refTo: catBodySym, /*offset=*/0,
1109 relocTemplate: infoCategoryWriter.catListInfo.relocTemplate);
1110
1111 emitAndLinkPointerList(parentSym: catBodySym, linkAtOffset: catLayout.instanceMethodsOffset, extInfo,
1112 ptrList: extInfo.instanceMethods);
1113
1114 emitAndLinkPointerList(parentSym: catBodySym, linkAtOffset: catLayout.classMethodsOffset, extInfo,
1115 ptrList: extInfo.classMethods);
1116
1117 emitAndLinkProtocolList(parentSym: catBodySym, linkAtOffset: catLayout.protocolsOffset, extInfo,
1118 ptrList: extInfo.protocols);
1119
1120 emitAndLinkPointerList(parentSym: catBodySym, linkAtOffset: catLayout.instancePropsOffset, extInfo,
1121 ptrList: extInfo.instanceProps);
1122
1123 emitAndLinkPointerList(parentSym: catBodySym, linkAtOffset: catLayout.classPropsOffset, extInfo,
1124 ptrList: extInfo.classProps);
1125
1126 return catBodySym;
1127}
1128
1129// This method merges all the categories (sharing a base class) into a single
1130// category.
1131bool ObjcCategoryMerger::mergeCategoriesIntoSingleCategory(
1132 std::vector<InfoInputCategory> &categories) {
1133 assert(categories.size() > 1 && "Expected at least 2 categories");
1134
1135 ClassExtensionInfo extInfo(catLayout);
1136
1137 for (auto &catInfo : categories)
1138 if (!parseCatInfoToExtInfo(catInfo, extInfo))
1139 return false;
1140
1141 Defined *newCatDef = emitCategory(extInfo);
1142 assert(newCatDef && "Failed to create a new category");
1143
1144 // Suppress unsuded var warning
1145 (void)newCatDef;
1146
1147 for (auto &catInfo : categories)
1148 catInfo.wasMerged = true;
1149
1150 return true;
1151}
1152
1153void ObjcCategoryMerger::createSymbolReference(Defined *refFrom,
1154 const Symbol *refTo,
1155 uint32_t offset,
1156 const Relocation &relocTemplate,
1157 int64_t addend) {
1158 Relocation r = relocTemplate;
1159 r.offset = offset;
1160 r.setAddend(addend);
1161 r.referent = const_cast<Symbol *>(refTo);
1162 refFrom->isec()->relocs.push_back(x: r);
1163}
1164
1165// Get the list of categories in the '__objc_nlcatlist' section. We can't
1166// optimize these as they have a '+load' method that has to be called at
1167// runtime.
1168DenseSet<const Symbol *> ObjcCategoryMerger::collectNlCategories() {
1169 DenseSet<const Symbol *> nlCategories;
1170
1171 for (InputSection *sec : allInputSections) {
1172 if (sec->getName() != section_names::objcNonLazyCatList)
1173 continue;
1174
1175 for (auto &r : sec->relocs) {
1176 const Symbol *sym = dyn_cast_if_present<Symbol *>(Val&: r.referent);
1177 nlCategories.insert(V: sym);
1178 }
1179 }
1180 return nlCategories;
1181}
1182
1183void ObjcCategoryMerger::collectAndValidateCategoriesData() {
1184 auto nlCategories = collectNlCategories();
1185
1186 for (InputSection *sec : allInputSections) {
1187 if (sec->getName() != section_names::objcCatList)
1188 continue;
1189 ConcatInputSection *catListCisec = dyn_cast<ConcatInputSection>(Val: sec);
1190 assert(catListCisec &&
1191 "__objc_catList InputSection is not a ConcatInputSection");
1192
1193 for (uint32_t off = 0; off < catListCisec->getSize();
1194 off += target->wordSize) {
1195 Defined *categorySym = tryGetDefinedAtIsecOffset(isec: catListCisec, offset: off);
1196 assert(categorySym &&
1197 "Failed to get a valid category at __objc_catlit offset");
1198
1199 if (nlCategories.contains(V: categorySym))
1200 continue;
1201
1202 auto *catBodyIsec = dyn_cast<ConcatInputSection>(Val: categorySym->isec());
1203 assert(catBodyIsec &&
1204 "Category data section is not an ConcatInputSection");
1205
1206 InfoInputCategory catInputInfo{.catListIsec: catListCisec, .catBodyIsec: catBodyIsec, .offCatListIsec: off};
1207
1208 // Check that the category has a reloc at 'klassOffset' (which is
1209 // a pointer to the class symbol)
1210
1211 auto [classSym, classAddend] =
1212 tryGetSymbolReferenceAtIsecOffset(isec: catBodyIsec, offset: catLayout.klassOffset);
1213 assert(classSym && "Category does not have a valid base class");
1214
1215 if (!collectCategoryWriterInfoFromCategory(catInfo: catInputInfo))
1216 continue;
1217
1218 categoryMap[{classSym, classAddend}].push_back(x: catInputInfo);
1219 }
1220 }
1221}
1222
1223// In the input we have multiple __objc_catlist InputSection, each of which may
1224// contain links to multiple categories. Of these categories, we will merge (and
1225// erase) only some. There will be some categories that will remain untouched
1226// (not erased). For these not erased categories, we generate new __objc_catlist
1227// entries since the parent __objc_catlist entry will be erased
1228void ObjcCategoryMerger::generateCatListForNonErasedCategories(
1229 const MapVector<ConcatInputSection *, std::set<uint64_t>>
1230 catListToErasedOffsets) {
1231
1232 // Go through all offsets of all __objc_catlist's that we process and if there
1233 // are categories that we didn't process - generate a new __objc_catlist for
1234 // each.
1235 for (auto &mapEntry : catListToErasedOffsets) {
1236 ConcatInputSection *catListIsec = mapEntry.first;
1237 for (uint32_t catListIsecOffset = 0;
1238 catListIsecOffset < catListIsec->data.size();
1239 catListIsecOffset += target->wordSize) {
1240 // This slot was erased, we can just skip it
1241 if (mapEntry.second.count(x: catListIsecOffset))
1242 continue;
1243
1244 Defined *nonErasedCatBody =
1245 tryGetDefinedAtIsecOffset(isec: catListIsec, offset: catListIsecOffset);
1246 assert(nonErasedCatBody && "Failed to relocate non-deleted category");
1247
1248 // Allocate data for the new __objc_catlist slot
1249 llvm::ArrayRef<uint8_t> bodyData = newSectionData(size: target->wordSize);
1250
1251 // We mark the __objc_catlist slot as belonging to the same file as the
1252 // category
1253 ObjFile *objFile = dyn_cast<ObjFile>(Val: nonErasedCatBody->getFile());
1254
1255 ConcatInputSection *listSec = make<ConcatInputSection>(
1256 args&: *infoCategoryWriter.catListInfo.inputSection, args&: bodyData,
1257 args&: infoCategoryWriter.catListInfo.align);
1258 listSec->parent = infoCategoryWriter.catListInfo.outputSection;
1259 listSec->live = true;
1260
1261 std::string slotSymName = "<__objc_catlist slot for category ";
1262 slotSymName += nonErasedCatBody->getName();
1263 slotSymName += ">";
1264
1265 Defined *catListSlotSym = make<Defined>(
1266 args: newStringData(str: slotSymName.c_str()), /*file=*/args&: objFile, args&: listSec,
1267 /*value=*/args: 0, args: bodyData.size(),
1268 /*isWeakDef=*/args: false, /*isExternal=*/args: false, /*isPrivateExtern=*/args: false,
1269 /*includeInSymtab=*/args: false, /*isReferencedDynamically=*/args: false,
1270 /*noDeadStrip=*/args: false, /*isWeakDefCanBeHidden=*/args: false);
1271
1272 catListSlotSym->used = true;
1273 objFile->symbols.push_back(x: catListSlotSym);
1274 addInputSection(inputSection: listSec);
1275
1276 // Now link the category body into the newly created slot
1277 createSymbolReference(refFrom: catListSlotSym, refTo: nonErasedCatBody, offset: 0,
1278 relocTemplate: infoCategoryWriter.catListInfo.relocTemplate);
1279 }
1280 }
1281}
1282
1283void ObjcCategoryMerger::eraseISec(ConcatInputSection *isec) {
1284 isec->live = false;
1285 for (auto &sym : isec->symbols)
1286 sym->used = false;
1287}
1288
1289// This fully erases the merged categories, including their body, their names,
1290// their method/protocol/prop lists and the __objc_catlist entries that link to
1291// them.
1292void ObjcCategoryMerger::eraseMergedCategories() {
1293 // Map of InputSection to a set of offsets of the categories that were merged
1294 MapVector<ConcatInputSection *, std::set<uint64_t>> catListToErasedOffsets;
1295
1296 for (auto &mapEntry : categoryMap) {
1297 for (InfoInputCategory &catInfo : mapEntry.second) {
1298 if (catInfo.wasMerged) {
1299 eraseISec(isec: catInfo.catListIsec);
1300 catListToErasedOffsets[catInfo.catListIsec].insert(
1301 x: catInfo.offCatListIsec);
1302 }
1303 }
1304 }
1305
1306 // If there were categories that we did not erase, we need to generate a new
1307 // __objc_catList that contains only the un-merged categories, and get rid of
1308 // the references to the ones we merged.
1309 generateCatListForNonErasedCategories(catListToErasedOffsets);
1310
1311 // Erase the old method lists & names of the categories that were merged
1312 for (auto &mapEntry : categoryMap) {
1313 for (InfoInputCategory &catInfo : mapEntry.second) {
1314 if (!catInfo.wasMerged)
1315 continue;
1316
1317 eraseISec(isec: catInfo.catBodyIsec);
1318
1319 // We can't erase 'catLayout.nameOffset' for either Swift or ObjC
1320 // categories because the name will sometimes also be used for other
1321 // purposes.
1322 // For Swift, see usages of 'l_.str.11.SimpleClass' in
1323 // objc-category-merging-swift.s
1324 // For ObjC, see usages of 'l_OBJC_CLASS_NAME_.1' in
1325 // objc-category-merging-erase-objc-name-test.s
1326 // TODO: handle the above in a smarter way
1327
1328 tryEraseDefinedAtIsecOffset(isec: catInfo.catBodyIsec,
1329 offset: catLayout.instanceMethodsOffset);
1330 tryEraseDefinedAtIsecOffset(isec: catInfo.catBodyIsec,
1331 offset: catLayout.classMethodsOffset);
1332 tryEraseDefinedAtIsecOffset(isec: catInfo.catBodyIsec,
1333 offset: catLayout.protocolsOffset);
1334 tryEraseDefinedAtIsecOffset(isec: catInfo.catBodyIsec,
1335 offset: catLayout.classPropsOffset);
1336 tryEraseDefinedAtIsecOffset(isec: catInfo.catBodyIsec,
1337 offset: catLayout.instancePropsOffset);
1338 }
1339 }
1340}
1341
1342void ObjcCategoryMerger::doMerge() {
1343 collectAndValidateCategoriesData();
1344
1345 for (auto &[baseClassRef, catInfos] : categoryMap) {
1346 const auto &[baseClass, baseClassAddend] = baseClassRef;
1347 bool merged = false;
1348 if (auto *baseClassDef = dyn_cast<Defined>(Val: baseClass)) {
1349 // Merge all categories into the base class
1350 merged =
1351 mergeCategoriesIntoBaseClass(baseClass: baseClassDef, baseClassAddend, categories&: catInfos);
1352 } else if (catInfos.size() > 1) {
1353 // Merge all categories into a new, single category
1354 merged = mergeCategoriesIntoSingleCategory(categories&: catInfos);
1355 }
1356 if (!merged)
1357 warn(msg: "ObjC category merging skipped for class symbol' " +
1358 baseClass->getName().str() + "'\n");
1359 }
1360
1361 // Erase all categories that were merged
1362 eraseMergedCategories();
1363}
1364
1365void ObjcCategoryMerger::doCleanup() { generatedSectionData.clear(); }
1366
1367StringRef ObjcCategoryMerger::newStringData(const char *str) {
1368 uint32_t len = strlen(s: str);
1369 uint32_t bufSize = len + 1;
1370 SmallVector<uint8_t> &data = newSectionData(size: bufSize);
1371 char *strData = reinterpret_cast<char *>(data.data());
1372 // Copy the string chars and null-terminator
1373 memcpy(dest: strData, src: str, n: bufSize);
1374 return StringRef(strData, len);
1375}
1376
1377SmallVector<uint8_t> &ObjcCategoryMerger::newSectionData(uint32_t size) {
1378 generatedSectionData.push_back(
1379 Elt: std::make_unique<SmallVector<uint8_t>>(args&: size, args: 0));
1380 return *generatedSectionData.back();
1381}
1382
1383} // namespace
1384
1385void objc::mergeCategories() {
1386 TimeTraceScope timeScope("ObjcCategoryMerger");
1387
1388 ObjcCategoryMerger merger(inputSections);
1389 merger.doMerge();
1390}
1391
1392void objc::doCleanup() { ObjcCategoryMerger::doCleanup(); }
1393
1394bool ObjcCategoryMerger::mergeCategoriesIntoBaseClass(
1395 const Defined *baseClass, int64_t baseClassAddend,
1396 std::vector<InfoInputCategory> &categories) {
1397 assert(categories.size() >= 1 && "Expected at least one category to merge");
1398
1399 // Collect all the info from the categories
1400 ClassExtensionInfo extInfo(catLayout);
1401 extInfo.setBaseClass(sym: baseClass, addend: baseClassAddend);
1402
1403 for (auto &catInfo : categories)
1404 if (!parseCatInfoToExtInfo(catInfo, extInfo))
1405 return false;
1406
1407 // Get metadata for the base class
1408 Defined *metaRo = getClassRo(classSym: baseClass, classAddend: baseClassAddend, /*getMetaRo=*/true);
1409 Defined *classRo =
1410 getClassRo(classSym: baseClass, classAddend: baseClassAddend, /*getMetaRo=*/false);
1411 if (!metaRo || !classRo)
1412 return false;
1413
1414 ConcatInputSection *metaIsec = dyn_cast<ConcatInputSection>(Val: metaRo->isec());
1415 ConcatInputSection *classIsec = dyn_cast<ConcatInputSection>(Val: classRo->isec());
1416 if (!metaIsec || !classIsec)
1417 return false;
1418
1419 // Now collect the info from the base class from the various lists in the
1420 // class metadata
1421
1422 // Protocol lists are a special case - the same protocol list is in classRo
1423 // and metaRo, so we only need to parse it once
1424 parseProtocolListInfo(isec: classIsec, secOffset: roClassLayout.baseProtocolsOffset,
1425 ptrList&: extInfo.protocols);
1426
1427 // Check that the classRo and metaRo protocol lists are identical
1428 assert(
1429 parseProtocolListInfo(classIsec, roClassLayout.baseProtocolsOffset) ==
1430 parseProtocolListInfo(metaIsec, roClassLayout.baseProtocolsOffset) &&
1431 "Category merger expects classRo and metaRo to have the same protocol "
1432 "list");
1433
1434 parsePointerListInfo(isec: metaIsec, secOffset: roClassLayout.baseMethodsOffset,
1435 ptrList&: extInfo.classMethods);
1436 parsePointerListInfo(isec: classIsec, secOffset: roClassLayout.baseMethodsOffset,
1437 ptrList&: extInfo.instanceMethods);
1438
1439 parsePointerListInfo(isec: metaIsec, secOffset: roClassLayout.basePropertiesOffset,
1440 ptrList&: extInfo.classProps);
1441 parsePointerListInfo(isec: classIsec, secOffset: roClassLayout.basePropertiesOffset,
1442 ptrList&: extInfo.instanceProps);
1443
1444 // Erase the old lists - these will be generated and replaced
1445 eraseSymbolAtIsecOffset(isec: metaIsec, offset: roClassLayout.baseMethodsOffset);
1446 eraseSymbolAtIsecOffset(isec: metaIsec, offset: roClassLayout.baseProtocolsOffset);
1447 eraseSymbolAtIsecOffset(isec: metaIsec, offset: roClassLayout.basePropertiesOffset);
1448 eraseSymbolAtIsecOffset(isec: classIsec, offset: roClassLayout.baseMethodsOffset);
1449 eraseSymbolAtIsecOffset(isec: classIsec, offset: roClassLayout.baseProtocolsOffset);
1450 eraseSymbolAtIsecOffset(isec: classIsec, offset: roClassLayout.basePropertiesOffset);
1451
1452 // Emit the newly merged lists - first into the meta RO then into the class RO
1453 // First we emit and link the protocol list into the meta RO. Then we link it
1454 // in the classRo as well (they're supposed to be identical)
1455 if (Defined *protoListSym =
1456 emitAndLinkProtocolList(parentSym: metaRo, linkAtOffset: roClassLayout.baseProtocolsOffset,
1457 extInfo, ptrList: extInfo.protocols)) {
1458 createSymbolReference(refFrom: classRo, refTo: protoListSym,
1459 offset: roClassLayout.baseProtocolsOffset,
1460 relocTemplate: infoCategoryWriter.catBodyInfo.relocTemplate);
1461 }
1462
1463 emitAndLinkPointerList(parentSym: metaRo, linkAtOffset: roClassLayout.baseMethodsOffset, extInfo,
1464 ptrList: extInfo.classMethods);
1465 emitAndLinkPointerList(parentSym: classRo, linkAtOffset: roClassLayout.baseMethodsOffset, extInfo,
1466 ptrList: extInfo.instanceMethods);
1467
1468 emitAndLinkPointerList(parentSym: metaRo, linkAtOffset: roClassLayout.basePropertiesOffset, extInfo,
1469 ptrList: extInfo.classProps);
1470
1471 emitAndLinkPointerList(parentSym: classRo, linkAtOffset: roClassLayout.basePropertiesOffset, extInfo,
1472 ptrList: extInfo.instanceProps);
1473
1474 // Mark all the categories as merged - this will be used to erase them later
1475 for (auto &catInfo : categories)
1476 catInfo.wasMerged = true;
1477
1478 return true;
1479}
1480
1481// Erase the symbol at a given offset in an InputSection
1482void ObjcCategoryMerger::eraseSymbolAtIsecOffset(ConcatInputSection *isec,
1483 uint32_t offset) {
1484 Defined *sym = tryGetDefinedAtIsecOffset(isec, offset);
1485 if (!sym)
1486 return;
1487
1488 // Remove the symbol from isec->symbols
1489 assert(isa<Defined>(sym) && "Can only erase a Defined");
1490 llvm::erase(C&: isec->symbols, V: sym);
1491
1492 // Remove the relocs that refer to this symbol
1493 auto removeAtOff = [offset](Relocation const &r) {
1494 return r.offset == offset;
1495 };
1496 llvm::erase_if(C&: isec->relocs, P: removeAtOff);
1497
1498 // Now, if the symbol fully occupies a ConcatInputSection, we can also erase
1499 // the whole ConcatInputSection
1500 if (ConcatInputSection *cisec = dyn_cast<ConcatInputSection>(Val: sym->isec()))
1501 if (cisec->data.size() == sym->size)
1502 eraseISec(isec: cisec);
1503}
1504