xref: /llvm-project-15.0.7/lld/MachO/Writer.cpp (revision 14324fa4)
1 //===- Writer.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 "Writer.h"
10 #include "ConcatOutputSection.h"
11 #include "Config.h"
12 #include "InputFiles.h"
13 #include "InputSection.h"
14 #include "MapFile.h"
15 #include "OutputSection.h"
16 #include "OutputSegment.h"
17 #include "SectionPriorities.h"
18 #include "SymbolTable.h"
19 #include "Symbols.h"
20 #include "SyntheticSections.h"
21 #include "Target.h"
22 #include "UnwindInfoSection.h"
23 
24 #include "lld/Common/Arrays.h"
25 #include "lld/Common/CommonLinkerContext.h"
26 #include "llvm/BinaryFormat/MachO.h"
27 #include "llvm/Config/llvm-config.h"
28 #include "llvm/Support/LEB128.h"
29 #include "llvm/Support/MathExtras.h"
30 #include "llvm/Support/Parallel.h"
31 #include "llvm/Support/Path.h"
32 #include "llvm/Support/ThreadPool.h"
33 #include "llvm/Support/TimeProfiler.h"
34 #include "llvm/Support/xxhash.h"
35 
36 #include <algorithm>
37 
38 using namespace llvm;
39 using namespace llvm::MachO;
40 using namespace llvm::sys;
41 using namespace lld;
42 using namespace lld::macho;
43 
44 namespace {
45 class LCUuid;
46 
47 class Writer {
48 public:
49   Writer() : buffer(errorHandler().outputBuffer) {}
50 
51   void treatSpecialUndefineds();
52   void scanRelocations();
53   void scanSymbols();
54   template <class LP> void createOutputSections();
55   template <class LP> void createLoadCommands();
56   void finalizeAddresses();
57   void finalizeLinkEditSegment();
58   void assignAddresses(OutputSegment *);
59 
60   void openFile();
61   void writeSections();
62   void writeUuid();
63   void writeCodeSignature();
64   void writeOutputFile();
65 
66   template <class LP> void run();
67 
68   ThreadPool threadPool;
69   std::unique_ptr<FileOutputBuffer> &buffer;
70   uint64_t addr = 0;
71   uint64_t fileOff = 0;
72   MachHeaderSection *header = nullptr;
73   StringTableSection *stringTableSection = nullptr;
74   SymtabSection *symtabSection = nullptr;
75   IndirectSymtabSection *indirectSymtabSection = nullptr;
76   CodeSignatureSection *codeSignatureSection = nullptr;
77   DataInCodeSection *dataInCodeSection = nullptr;
78   FunctionStartsSection *functionStartsSection = nullptr;
79 
80   LCUuid *uuidCommand = nullptr;
81   OutputSegment *linkEditSegment = nullptr;
82 };
83 
84 // LC_DYLD_INFO_ONLY stores the offsets of symbol import/export information.
85 class LCDyldInfo final : public LoadCommand {
86 public:
87   LCDyldInfo(RebaseSection *rebaseSection, BindingSection *bindingSection,
88              WeakBindingSection *weakBindingSection,
89              LazyBindingSection *lazyBindingSection,
90              ExportSection *exportSection)
91       : rebaseSection(rebaseSection), bindingSection(bindingSection),
92         weakBindingSection(weakBindingSection),
93         lazyBindingSection(lazyBindingSection), exportSection(exportSection) {}
94 
95   uint32_t getSize() const override { return sizeof(dyld_info_command); }
96 
97   void writeTo(uint8_t *buf) const override {
98     auto *c = reinterpret_cast<dyld_info_command *>(buf);
99     c->cmd = LC_DYLD_INFO_ONLY;
100     c->cmdsize = getSize();
101     if (rebaseSection->isNeeded()) {
102       c->rebase_off = rebaseSection->fileOff;
103       c->rebase_size = rebaseSection->getFileSize();
104     }
105     if (bindingSection->isNeeded()) {
106       c->bind_off = bindingSection->fileOff;
107       c->bind_size = bindingSection->getFileSize();
108     }
109     if (weakBindingSection->isNeeded()) {
110       c->weak_bind_off = weakBindingSection->fileOff;
111       c->weak_bind_size = weakBindingSection->getFileSize();
112     }
113     if (lazyBindingSection->isNeeded()) {
114       c->lazy_bind_off = lazyBindingSection->fileOff;
115       c->lazy_bind_size = lazyBindingSection->getFileSize();
116     }
117     if (exportSection->isNeeded()) {
118       c->export_off = exportSection->fileOff;
119       c->export_size = exportSection->getFileSize();
120     }
121   }
122 
123   RebaseSection *rebaseSection;
124   BindingSection *bindingSection;
125   WeakBindingSection *weakBindingSection;
126   LazyBindingSection *lazyBindingSection;
127   ExportSection *exportSection;
128 };
129 
130 class LCSubFramework final : public LoadCommand {
131 public:
132   LCSubFramework(StringRef umbrella) : umbrella(umbrella) {}
133 
134   uint32_t getSize() const override {
135     return alignTo(sizeof(sub_framework_command) + umbrella.size() + 1,
136                    target->wordSize);
137   }
138 
139   void writeTo(uint8_t *buf) const override {
140     auto *c = reinterpret_cast<sub_framework_command *>(buf);
141     buf += sizeof(sub_framework_command);
142 
143     c->cmd = LC_SUB_FRAMEWORK;
144     c->cmdsize = getSize();
145     c->umbrella = sizeof(sub_framework_command);
146 
147     memcpy(buf, umbrella.data(), umbrella.size());
148     buf[umbrella.size()] = '\0';
149   }
150 
151 private:
152   const StringRef umbrella;
153 };
154 
155 class LCFunctionStarts final : public LoadCommand {
156 public:
157   explicit LCFunctionStarts(FunctionStartsSection *functionStartsSection)
158       : functionStartsSection(functionStartsSection) {}
159 
160   uint32_t getSize() const override { return sizeof(linkedit_data_command); }
161 
162   void writeTo(uint8_t *buf) const override {
163     auto *c = reinterpret_cast<linkedit_data_command *>(buf);
164     c->cmd = LC_FUNCTION_STARTS;
165     c->cmdsize = getSize();
166     c->dataoff = functionStartsSection->fileOff;
167     c->datasize = functionStartsSection->getFileSize();
168   }
169 
170 private:
171   FunctionStartsSection *functionStartsSection;
172 };
173 
174 class LCDataInCode final : public LoadCommand {
175 public:
176   explicit LCDataInCode(DataInCodeSection *dataInCodeSection)
177       : dataInCodeSection(dataInCodeSection) {}
178 
179   uint32_t getSize() const override { return sizeof(linkedit_data_command); }
180 
181   void writeTo(uint8_t *buf) const override {
182     auto *c = reinterpret_cast<linkedit_data_command *>(buf);
183     c->cmd = LC_DATA_IN_CODE;
184     c->cmdsize = getSize();
185     c->dataoff = dataInCodeSection->fileOff;
186     c->datasize = dataInCodeSection->getFileSize();
187   }
188 
189 private:
190   DataInCodeSection *dataInCodeSection;
191 };
192 
193 class LCDysymtab final : public LoadCommand {
194 public:
195   LCDysymtab(SymtabSection *symtabSection,
196              IndirectSymtabSection *indirectSymtabSection)
197       : symtabSection(symtabSection),
198         indirectSymtabSection(indirectSymtabSection) {}
199 
200   uint32_t getSize() const override { return sizeof(dysymtab_command); }
201 
202   void writeTo(uint8_t *buf) const override {
203     auto *c = reinterpret_cast<dysymtab_command *>(buf);
204     c->cmd = LC_DYSYMTAB;
205     c->cmdsize = getSize();
206 
207     c->ilocalsym = 0;
208     c->iextdefsym = c->nlocalsym = symtabSection->getNumLocalSymbols();
209     c->nextdefsym = symtabSection->getNumExternalSymbols();
210     c->iundefsym = c->iextdefsym + c->nextdefsym;
211     c->nundefsym = symtabSection->getNumUndefinedSymbols();
212 
213     c->indirectsymoff = indirectSymtabSection->fileOff;
214     c->nindirectsyms = indirectSymtabSection->getNumSymbols();
215   }
216 
217   SymtabSection *symtabSection;
218   IndirectSymtabSection *indirectSymtabSection;
219 };
220 
221 template <class LP> class LCSegment final : public LoadCommand {
222 public:
223   LCSegment(StringRef name, OutputSegment *seg) : name(name), seg(seg) {}
224 
225   uint32_t getSize() const override {
226     return sizeof(typename LP::segment_command) +
227            seg->numNonHiddenSections() * sizeof(typename LP::section);
228   }
229 
230   void writeTo(uint8_t *buf) const override {
231     using SegmentCommand = typename LP::segment_command;
232     using SectionHeader = typename LP::section;
233 
234     auto *c = reinterpret_cast<SegmentCommand *>(buf);
235     buf += sizeof(SegmentCommand);
236 
237     c->cmd = LP::segmentLCType;
238     c->cmdsize = getSize();
239     memcpy(c->segname, name.data(), name.size());
240     c->fileoff = seg->fileOff;
241     c->maxprot = seg->maxProt;
242     c->initprot = seg->initProt;
243 
244     c->vmaddr = seg->addr;
245     c->vmsize = seg->vmSize;
246     c->filesize = seg->fileSize;
247     c->nsects = seg->numNonHiddenSections();
248 
249     for (const OutputSection *osec : seg->getSections()) {
250       if (osec->isHidden())
251         continue;
252 
253       auto *sectHdr = reinterpret_cast<SectionHeader *>(buf);
254       buf += sizeof(SectionHeader);
255 
256       memcpy(sectHdr->sectname, osec->name.data(), osec->name.size());
257       memcpy(sectHdr->segname, name.data(), name.size());
258 
259       sectHdr->addr = osec->addr;
260       sectHdr->offset = osec->fileOff;
261       sectHdr->align = Log2_32(osec->align);
262       sectHdr->flags = osec->flags;
263       sectHdr->size = osec->getSize();
264       sectHdr->reserved1 = osec->reserved1;
265       sectHdr->reserved2 = osec->reserved2;
266     }
267   }
268 
269 private:
270   StringRef name;
271   OutputSegment *seg;
272 };
273 
274 class LCMain final : public LoadCommand {
275   uint32_t getSize() const override {
276     return sizeof(structs::entry_point_command);
277   }
278 
279   void writeTo(uint8_t *buf) const override {
280     auto *c = reinterpret_cast<structs::entry_point_command *>(buf);
281     c->cmd = LC_MAIN;
282     c->cmdsize = getSize();
283 
284     if (config->entry->isInStubs())
285       c->entryoff =
286           in.stubs->fileOff + config->entry->stubsIndex * target->stubSize;
287     else
288       c->entryoff = config->entry->getVA() - in.header->addr;
289 
290     c->stacksize = 0;
291   }
292 };
293 
294 class LCSymtab final : public LoadCommand {
295 public:
296   LCSymtab(SymtabSection *symtabSection, StringTableSection *stringTableSection)
297       : symtabSection(symtabSection), stringTableSection(stringTableSection) {}
298 
299   uint32_t getSize() const override { return sizeof(symtab_command); }
300 
301   void writeTo(uint8_t *buf) const override {
302     auto *c = reinterpret_cast<symtab_command *>(buf);
303     c->cmd = LC_SYMTAB;
304     c->cmdsize = getSize();
305     c->symoff = symtabSection->fileOff;
306     c->nsyms = symtabSection->getNumSymbols();
307     c->stroff = stringTableSection->fileOff;
308     c->strsize = stringTableSection->getFileSize();
309   }
310 
311   SymtabSection *symtabSection = nullptr;
312   StringTableSection *stringTableSection = nullptr;
313 };
314 
315 // There are several dylib load commands that share the same structure:
316 //   * LC_LOAD_DYLIB
317 //   * LC_ID_DYLIB
318 //   * LC_REEXPORT_DYLIB
319 class LCDylib final : public LoadCommand {
320 public:
321   LCDylib(LoadCommandType type, StringRef path,
322           uint32_t compatibilityVersion = 0, uint32_t currentVersion = 0)
323       : type(type), path(path), compatibilityVersion(compatibilityVersion),
324         currentVersion(currentVersion) {
325     instanceCount++;
326   }
327 
328   uint32_t getSize() const override {
329     return alignTo(sizeof(dylib_command) + path.size() + 1, 8);
330   }
331 
332   void writeTo(uint8_t *buf) const override {
333     auto *c = reinterpret_cast<dylib_command *>(buf);
334     buf += sizeof(dylib_command);
335 
336     c->cmd = type;
337     c->cmdsize = getSize();
338     c->dylib.name = sizeof(dylib_command);
339     c->dylib.timestamp = 0;
340     c->dylib.compatibility_version = compatibilityVersion;
341     c->dylib.current_version = currentVersion;
342 
343     memcpy(buf, path.data(), path.size());
344     buf[path.size()] = '\0';
345   }
346 
347   static uint32_t getInstanceCount() { return instanceCount; }
348   static void resetInstanceCount() { instanceCount = 0; }
349 
350 private:
351   LoadCommandType type;
352   StringRef path;
353   uint32_t compatibilityVersion;
354   uint32_t currentVersion;
355   static uint32_t instanceCount;
356 };
357 
358 uint32_t LCDylib::instanceCount = 0;
359 
360 class LCLoadDylinker final : public LoadCommand {
361 public:
362   uint32_t getSize() const override {
363     return alignTo(sizeof(dylinker_command) + path.size() + 1, 8);
364   }
365 
366   void writeTo(uint8_t *buf) const override {
367     auto *c = reinterpret_cast<dylinker_command *>(buf);
368     buf += sizeof(dylinker_command);
369 
370     c->cmd = LC_LOAD_DYLINKER;
371     c->cmdsize = getSize();
372     c->name = sizeof(dylinker_command);
373 
374     memcpy(buf, path.data(), path.size());
375     buf[path.size()] = '\0';
376   }
377 
378 private:
379   // Recent versions of Darwin won't run any binary that has dyld at a
380   // different location.
381   const StringRef path = "/usr/lib/dyld";
382 };
383 
384 class LCRPath final : public LoadCommand {
385 public:
386   explicit LCRPath(StringRef path) : path(path) {}
387 
388   uint32_t getSize() const override {
389     return alignTo(sizeof(rpath_command) + path.size() + 1, target->wordSize);
390   }
391 
392   void writeTo(uint8_t *buf) const override {
393     auto *c = reinterpret_cast<rpath_command *>(buf);
394     buf += sizeof(rpath_command);
395 
396     c->cmd = LC_RPATH;
397     c->cmdsize = getSize();
398     c->path = sizeof(rpath_command);
399 
400     memcpy(buf, path.data(), path.size());
401     buf[path.size()] = '\0';
402   }
403 
404 private:
405   StringRef path;
406 };
407 
408 class LCMinVersion final : public LoadCommand {
409 public:
410   explicit LCMinVersion(const PlatformInfo &platformInfo)
411       : platformInfo(platformInfo) {}
412 
413   uint32_t getSize() const override { return sizeof(version_min_command); }
414 
415   void writeTo(uint8_t *buf) const override {
416     auto *c = reinterpret_cast<version_min_command *>(buf);
417     switch (platformInfo.target.Platform) {
418     case PLATFORM_MACOS:
419       c->cmd = LC_VERSION_MIN_MACOSX;
420       break;
421     case PLATFORM_IOS:
422     case PLATFORM_IOSSIMULATOR:
423       c->cmd = LC_VERSION_MIN_IPHONEOS;
424       break;
425     case PLATFORM_TVOS:
426     case PLATFORM_TVOSSIMULATOR:
427       c->cmd = LC_VERSION_MIN_TVOS;
428       break;
429     case PLATFORM_WATCHOS:
430     case PLATFORM_WATCHOSSIMULATOR:
431       c->cmd = LC_VERSION_MIN_WATCHOS;
432       break;
433     default:
434       llvm_unreachable("invalid platform");
435       break;
436     }
437     c->cmdsize = getSize();
438     c->version = encodeVersion(platformInfo.minimum);
439     c->sdk = encodeVersion(platformInfo.sdk);
440   }
441 
442 private:
443   const PlatformInfo &platformInfo;
444 };
445 
446 class LCBuildVersion final : public LoadCommand {
447 public:
448   explicit LCBuildVersion(const PlatformInfo &platformInfo)
449       : platformInfo(platformInfo) {}
450 
451   const int ntools = 1;
452 
453   uint32_t getSize() const override {
454     return sizeof(build_version_command) + ntools * sizeof(build_tool_version);
455   }
456 
457   void writeTo(uint8_t *buf) const override {
458     auto *c = reinterpret_cast<build_version_command *>(buf);
459     c->cmd = LC_BUILD_VERSION;
460     c->cmdsize = getSize();
461     c->platform = static_cast<uint32_t>(platformInfo.target.Platform);
462     c->minos = encodeVersion(platformInfo.minimum);
463     c->sdk = encodeVersion(platformInfo.sdk);
464     c->ntools = ntools;
465     auto *t = reinterpret_cast<build_tool_version *>(&c[1]);
466     t->tool = TOOL_LD;
467     t->version = encodeVersion(VersionTuple(
468         LLVM_VERSION_MAJOR, LLVM_VERSION_MINOR, LLVM_VERSION_PATCH));
469   }
470 
471 private:
472   const PlatformInfo &platformInfo;
473 };
474 
475 // Stores a unique identifier for the output file based on an MD5 hash of its
476 // contents. In order to hash the contents, we must first write them, but
477 // LC_UUID itself must be part of the written contents in order for all the
478 // offsets to be calculated correctly. We resolve this circular paradox by
479 // first writing an LC_UUID with an all-zero UUID, then updating the UUID with
480 // its real value later.
481 class LCUuid final : public LoadCommand {
482 public:
483   uint32_t getSize() const override { return sizeof(uuid_command); }
484 
485   void writeTo(uint8_t *buf) const override {
486     auto *c = reinterpret_cast<uuid_command *>(buf);
487     c->cmd = LC_UUID;
488     c->cmdsize = getSize();
489     uuidBuf = c->uuid;
490   }
491 
492   void writeUuid(uint64_t digest) const {
493     // xxhash only gives us 8 bytes, so put some fixed data in the other half.
494     static_assert(sizeof(uuid_command::uuid) == 16, "unexpected uuid size");
495     memcpy(uuidBuf, "LLD\xa1UU1D", 8);
496     memcpy(uuidBuf + 8, &digest, 8);
497 
498     // RFC 4122 conformance. We need to fix 4 bits in byte 6 and 2 bits in
499     // byte 8. Byte 6 is already fine due to the fixed data we put in. We don't
500     // want to lose bits of the digest in byte 8, so swap that with a byte of
501     // fixed data that happens to have the right bits set.
502     std::swap(uuidBuf[3], uuidBuf[8]);
503 
504     // Claim that this is an MD5-based hash. It isn't, but this signals that
505     // this is not a time-based and not a random hash. MD5 seems like the least
506     // bad lie we can put here.
507     assert((uuidBuf[6] & 0xf0) == 0x30 && "See RFC 4122 Sections 4.2.2, 4.1.3");
508     assert((uuidBuf[8] & 0xc0) == 0x80 && "See RFC 4122 Section 4.2.2");
509   }
510 
511   mutable uint8_t *uuidBuf;
512 };
513 
514 template <class LP> class LCEncryptionInfo final : public LoadCommand {
515 public:
516   uint32_t getSize() const override {
517     return sizeof(typename LP::encryption_info_command);
518   }
519 
520   void writeTo(uint8_t *buf) const override {
521     using EncryptionInfo = typename LP::encryption_info_command;
522     auto *c = reinterpret_cast<EncryptionInfo *>(buf);
523     buf += sizeof(EncryptionInfo);
524     c->cmd = LP::encryptionInfoLCType;
525     c->cmdsize = getSize();
526     c->cryptoff = in.header->getSize();
527     auto it = find_if(outputSegments, [](const OutputSegment *seg) {
528       return seg->name == segment_names::text;
529     });
530     assert(it != outputSegments.end());
531     c->cryptsize = (*it)->fileSize - c->cryptoff;
532   }
533 };
534 
535 class LCCodeSignature final : public LoadCommand {
536 public:
537   LCCodeSignature(CodeSignatureSection *section) : section(section) {}
538 
539   uint32_t getSize() const override { return sizeof(linkedit_data_command); }
540 
541   void writeTo(uint8_t *buf) const override {
542     auto *c = reinterpret_cast<linkedit_data_command *>(buf);
543     c->cmd = LC_CODE_SIGNATURE;
544     c->cmdsize = getSize();
545     c->dataoff = static_cast<uint32_t>(section->fileOff);
546     c->datasize = section->getSize();
547   }
548 
549   CodeSignatureSection *section;
550 };
551 
552 } // namespace
553 
554 void Writer::treatSpecialUndefineds() {
555   if (config->entry)
556     if (auto *undefined = dyn_cast<Undefined>(config->entry))
557       treatUndefinedSymbol(*undefined, "the entry point");
558 
559   // FIXME: This prints symbols that are undefined both in input files and
560   // via -u flag twice.
561   for (const Symbol *sym : config->explicitUndefineds) {
562     if (const auto *undefined = dyn_cast<Undefined>(sym))
563       treatUndefinedSymbol(*undefined, "-u");
564   }
565   // Literal exported-symbol names must be defined, but glob
566   // patterns need not match.
567   for (const CachedHashStringRef &cachedName :
568        config->exportedSymbols.literals) {
569     if (const Symbol *sym = symtab->find(cachedName))
570       if (const auto *undefined = dyn_cast<Undefined>(sym))
571         treatUndefinedSymbol(*undefined, "-exported_symbol(s_list)");
572   }
573 }
574 
575 // Add stubs and bindings where necessary (e.g. if the symbol is a
576 // DylibSymbol.)
577 static void prepareBranchTarget(Symbol *sym) {
578   if (auto *dysym = dyn_cast<DylibSymbol>(sym)) {
579     if (in.stubs->addEntry(dysym)) {
580       if (sym->isWeakDef()) {
581         in.binding->addEntry(dysym, in.lazyPointers->isec,
582                              sym->stubsIndex * target->wordSize);
583         in.weakBinding->addEntry(sym, in.lazyPointers->isec,
584                                  sym->stubsIndex * target->wordSize);
585       } else {
586         in.lazyBinding->addEntry(dysym);
587       }
588     }
589   } else if (auto *defined = dyn_cast<Defined>(sym)) {
590     if (defined->isExternalWeakDef()) {
591       if (in.stubs->addEntry(sym)) {
592         in.rebase->addEntry(in.lazyPointers->isec,
593                             sym->stubsIndex * target->wordSize);
594         in.weakBinding->addEntry(sym, in.lazyPointers->isec,
595                                  sym->stubsIndex * target->wordSize);
596       }
597     } else if (defined->interposable) {
598       if (in.stubs->addEntry(sym))
599         in.lazyBinding->addEntry(sym);
600     }
601   } else {
602     llvm_unreachable("invalid branch target symbol type");
603   }
604 }
605 
606 // Can a symbol's address can only be resolved at runtime?
607 static bool needsBinding(const Symbol *sym) {
608   if (isa<DylibSymbol>(sym))
609     return true;
610   if (const auto *defined = dyn_cast<Defined>(sym))
611     return defined->isExternalWeakDef() || defined->interposable;
612   return false;
613 }
614 
615 static void prepareSymbolRelocation(Symbol *sym, const InputSection *isec,
616                                     const lld::macho::Reloc &r) {
617   assert(sym->isLive());
618   const RelocAttrs &relocAttrs = target->getRelocAttrs(r.type);
619 
620   if (relocAttrs.hasAttr(RelocAttrBits::BRANCH)) {
621     prepareBranchTarget(sym);
622   } else if (relocAttrs.hasAttr(RelocAttrBits::GOT)) {
623     if (relocAttrs.hasAttr(RelocAttrBits::POINTER) || needsBinding(sym))
624       in.got->addEntry(sym);
625   } else if (relocAttrs.hasAttr(RelocAttrBits::TLV)) {
626     if (needsBinding(sym))
627       in.tlvPointers->addEntry(sym);
628   } else if (relocAttrs.hasAttr(RelocAttrBits::UNSIGNED)) {
629     // References from thread-local variable sections are treated as offsets
630     // relative to the start of the referent section, and therefore have no
631     // need of rebase opcodes.
632     if (!(isThreadLocalVariables(isec->getFlags()) && isa<Defined>(sym)))
633       addNonLazyBindingEntries(sym, isec, r.offset, r.addend);
634   }
635 }
636 
637 void Writer::scanRelocations() {
638   TimeTraceScope timeScope("Scan relocations");
639 
640   // This can't use a for-each loop: It calls treatUndefinedSymbol(), which can
641   // add to inputSections, which invalidates inputSections's iterators.
642   for (size_t i = 0; i < inputSections.size(); ++i) {
643     ConcatInputSection *isec = inputSections[i];
644 
645     if (isec->shouldOmitFromOutput())
646       continue;
647 
648     for (auto it = isec->relocs.begin(); it != isec->relocs.end(); ++it) {
649       lld::macho::Reloc &r = *it;
650       if (target->hasAttr(r.type, RelocAttrBits::SUBTRAHEND)) {
651         // Skip over the following UNSIGNED relocation -- it's just there as the
652         // minuend, and doesn't have the usual UNSIGNED semantics. We don't want
653         // to emit rebase opcodes for it.
654         it++;
655         continue;
656       }
657       if (auto *sym = r.referent.dyn_cast<Symbol *>()) {
658         if (auto *undefined = dyn_cast<Undefined>(sym))
659           treatUndefinedSymbol(*undefined);
660         // treatUndefinedSymbol() can replace sym with a DylibSymbol; re-check.
661         if (!isa<Undefined>(sym) && validateSymbolRelocation(sym, isec, r))
662           prepareSymbolRelocation(sym, isec, r);
663       } else {
664         // Canonicalize the referent so that later accesses in Writer won't
665         // have to worry about it. Perhaps we should do this for Defined::isec
666         // too...
667         auto *referentIsec = r.referent.get<InputSection *>();
668         r.referent = referentIsec->canonical();
669         if (!r.pcrel)
670           in.rebase->addEntry(isec, r.offset);
671       }
672     }
673   }
674 
675   in.unwindInfo->prepareRelocations();
676 }
677 
678 void Writer::scanSymbols() {
679   TimeTraceScope timeScope("Scan symbols");
680   for (Symbol *sym : symtab->getSymbols()) {
681     if (auto *defined = dyn_cast<Defined>(sym)) {
682       if (!defined->isLive())
683         continue;
684       defined->canonicalize();
685       if (defined->overridesWeakDef)
686         in.weakBinding->addNonWeakDefinition(defined);
687       if (!defined->isAbsolute() && isCodeSection(defined->isec))
688         in.unwindInfo->addSymbol(defined);
689     } else if (const auto *dysym = dyn_cast<DylibSymbol>(sym)) {
690       // This branch intentionally doesn't check isLive().
691       if (dysym->isDynamicLookup())
692         continue;
693       dysym->getFile()->refState =
694           std::max(dysym->getFile()->refState, dysym->getRefState());
695     }
696   }
697 
698   for (const InputFile *file : inputFiles) {
699     if (auto *objFile = dyn_cast<ObjFile>(file))
700       for (Symbol *sym : objFile->symbols) {
701         if (auto *defined = dyn_cast_or_null<Defined>(sym)) {
702           if (!defined->isLive())
703             continue;
704           defined->canonicalize();
705           if (!defined->isExternal() && !defined->isAbsolute() &&
706               isCodeSection(defined->isec))
707             in.unwindInfo->addSymbol(defined);
708         }
709       }
710   }
711 }
712 
713 // TODO: ld64 enforces the old load commands in a few other cases.
714 static bool useLCBuildVersion(const PlatformInfo &platformInfo) {
715   static const std::vector<std::pair<PlatformType, VersionTuple>> minVersion = {
716       {PLATFORM_MACOS, VersionTuple(10, 14)},
717       {PLATFORM_IOS, VersionTuple(12, 0)},
718       {PLATFORM_IOSSIMULATOR, VersionTuple(13, 0)},
719       {PLATFORM_TVOS, VersionTuple(12, 0)},
720       {PLATFORM_TVOSSIMULATOR, VersionTuple(13, 0)},
721       {PLATFORM_WATCHOS, VersionTuple(5, 0)},
722       {PLATFORM_WATCHOSSIMULATOR, VersionTuple(6, 0)}};
723   auto it = llvm::find_if(minVersion, [&](const auto &p) {
724     return p.first == platformInfo.target.Platform;
725   });
726   return it == minVersion.end() ? true : platformInfo.minimum >= it->second;
727 }
728 
729 template <class LP> void Writer::createLoadCommands() {
730   uint8_t segIndex = 0;
731   for (OutputSegment *seg : outputSegments) {
732     in.header->addLoadCommand(make<LCSegment<LP>>(seg->name, seg));
733     seg->index = segIndex++;
734   }
735 
736   in.header->addLoadCommand(make<LCDyldInfo>(
737       in.rebase, in.binding, in.weakBinding, in.lazyBinding, in.exports));
738   in.header->addLoadCommand(make<LCSymtab>(symtabSection, stringTableSection));
739   in.header->addLoadCommand(
740       make<LCDysymtab>(symtabSection, indirectSymtabSection));
741   if (!config->umbrella.empty())
742     in.header->addLoadCommand(make<LCSubFramework>(config->umbrella));
743   if (config->emitEncryptionInfo)
744     in.header->addLoadCommand(make<LCEncryptionInfo<LP>>());
745   for (StringRef path : config->runtimePaths)
746     in.header->addLoadCommand(make<LCRPath>(path));
747 
748   switch (config->outputType) {
749   case MH_EXECUTE:
750     in.header->addLoadCommand(make<LCLoadDylinker>());
751     break;
752   case MH_DYLIB:
753     in.header->addLoadCommand(make<LCDylib>(LC_ID_DYLIB, config->installName,
754                                             config->dylibCompatibilityVersion,
755                                             config->dylibCurrentVersion));
756     break;
757   case MH_BUNDLE:
758     break;
759   default:
760     llvm_unreachable("unhandled output file type");
761   }
762 
763   uuidCommand = make<LCUuid>();
764   in.header->addLoadCommand(uuidCommand);
765 
766   if (useLCBuildVersion(config->platformInfo))
767     in.header->addLoadCommand(make<LCBuildVersion>(config->platformInfo));
768   else
769     in.header->addLoadCommand(make<LCMinVersion>(config->platformInfo));
770 
771   // This is down here to match ld64's load command order.
772   if (config->outputType == MH_EXECUTE)
773     in.header->addLoadCommand(make<LCMain>());
774 
775   int64_t dylibOrdinal = 1;
776   DenseMap<StringRef, int64_t> ordinalForInstallName;
777   for (InputFile *file : inputFiles) {
778     if (auto *dylibFile = dyn_cast<DylibFile>(file)) {
779       if (dylibFile->isBundleLoader) {
780         dylibFile->ordinal = BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE;
781         // Shortcut since bundle-loader does not re-export the symbols.
782 
783         dylibFile->reexport = false;
784         continue;
785       }
786 
787       // Don't emit load commands for a dylib that is not referenced if:
788       // - it was added implicitly (via a reexport, an LC_LOAD_DYLINKER --
789       //   if it's on the linker command line, it's explicit)
790       // - or it's marked MH_DEAD_STRIPPABLE_DYLIB
791       // - or the flag -dead_strip_dylibs is used
792       // FIXME: `isReferenced()` is currently computed before dead code
793       // stripping, so references from dead code keep a dylib alive. This
794       // matches ld64, but it's something we should do better.
795       if (!dylibFile->isReferenced() && !dylibFile->forceNeeded &&
796           (!dylibFile->explicitlyLinked || dylibFile->deadStrippable ||
797            config->deadStripDylibs))
798         continue;
799 
800       // Several DylibFiles can have the same installName. Only emit a single
801       // load command for that installName and give all these DylibFiles the
802       // same ordinal.
803       // This can happen in several cases:
804       // - a new framework could change its installName to an older
805       //   framework name via an $ld$ symbol depending on platform_version
806       // - symlinks (for example, libpthread.tbd is a symlink to libSystem.tbd;
807       //   Foo.framework/Foo.tbd is usually a symlink to
808       //   Foo.framework/Versions/Current/Foo.tbd, where
809       //   Foo.framework/Versions/Current is usually a symlink to
810       //   Foo.framework/Versions/A)
811       // - a framework can be linked both explicitly on the linker
812       //   command line and implicitly as a reexport from a different
813       //   framework. The re-export will usually point to the tbd file
814       //   in Foo.framework/Versions/A/Foo.tbd, while the explicit link will
815       //   usually find Foo.framework/Foo.tbd. These are usually symlinks,
816       //   but in a --reproduce archive they will be identical but distinct
817       //   files.
818       // In the first case, *semantically distinct* DylibFiles will have the
819       // same installName.
820       int64_t &ordinal = ordinalForInstallName[dylibFile->installName];
821       if (ordinal) {
822         dylibFile->ordinal = ordinal;
823         continue;
824       }
825 
826       ordinal = dylibFile->ordinal = dylibOrdinal++;
827       LoadCommandType lcType =
828           dylibFile->forceWeakImport || dylibFile->refState == RefState::Weak
829               ? LC_LOAD_WEAK_DYLIB
830               : LC_LOAD_DYLIB;
831       in.header->addLoadCommand(make<LCDylib>(lcType, dylibFile->installName,
832                                               dylibFile->compatibilityVersion,
833                                               dylibFile->currentVersion));
834 
835       if (dylibFile->reexport)
836         in.header->addLoadCommand(
837             make<LCDylib>(LC_REEXPORT_DYLIB, dylibFile->installName));
838     }
839   }
840 
841   if (functionStartsSection)
842     in.header->addLoadCommand(make<LCFunctionStarts>(functionStartsSection));
843   if (dataInCodeSection)
844     in.header->addLoadCommand(make<LCDataInCode>(dataInCodeSection));
845   if (codeSignatureSection)
846     in.header->addLoadCommand(make<LCCodeSignature>(codeSignatureSection));
847 
848   const uint32_t MACOS_MAXPATHLEN = 1024;
849   config->headerPad = std::max(
850       config->headerPad, (config->headerPadMaxInstallNames
851                               ? LCDylib::getInstanceCount() * MACOS_MAXPATHLEN
852                               : 0));
853 }
854 
855 // Sorting only can happen once all outputs have been collected. Here we sort
856 // segments, output sections within each segment, and input sections within each
857 // output segment.
858 static void sortSegmentsAndSections() {
859   TimeTraceScope timeScope("Sort segments and sections");
860   sortOutputSegments();
861 
862   DenseMap<const InputSection *, size_t> isecPriorities =
863       buildInputSectionPriorities();
864 
865   uint32_t sectionIndex = 0;
866   for (OutputSegment *seg : outputSegments) {
867     seg->sortOutputSections();
868     // References from thread-local variable sections are treated as offsets
869     // relative to the start of the thread-local data memory area, which
870     // is initialized via copying all the TLV data sections (which are all
871     // contiguous). If later data sections require a greater alignment than
872     // earlier ones, the offsets of data within those sections won't be
873     // guaranteed to aligned unless we normalize alignments. We therefore use
874     // the largest alignment for all TLV data sections.
875     uint32_t tlvAlign = 0;
876     for (const OutputSection *osec : seg->getSections())
877       if (isThreadLocalData(osec->flags) && osec->align > tlvAlign)
878         tlvAlign = osec->align;
879 
880     for (OutputSection *osec : seg->getSections()) {
881       // Now that the output sections are sorted, assign the final
882       // output section indices.
883       if (!osec->isHidden())
884         osec->index = ++sectionIndex;
885       if (isThreadLocalData(osec->flags)) {
886         if (!firstTLVDataSection)
887           firstTLVDataSection = osec;
888         osec->align = tlvAlign;
889       }
890 
891       if (!isecPriorities.empty()) {
892         if (auto *merged = dyn_cast<ConcatOutputSection>(osec)) {
893           llvm::stable_sort(merged->inputs,
894                             [&](InputSection *a, InputSection *b) {
895                               return isecPriorities[a] > isecPriorities[b];
896                             });
897         }
898       }
899     }
900   }
901 }
902 
903 template <class LP> void Writer::createOutputSections() {
904   TimeTraceScope timeScope("Create output sections");
905   // First, create hidden sections
906   stringTableSection = make<StringTableSection>();
907   symtabSection = makeSymtabSection<LP>(*stringTableSection);
908   indirectSymtabSection = make<IndirectSymtabSection>();
909   if (config->adhocCodesign)
910     codeSignatureSection = make<CodeSignatureSection>();
911   if (config->emitDataInCodeInfo)
912     dataInCodeSection = make<DataInCodeSection>();
913   if (config->emitFunctionStarts)
914     functionStartsSection = make<FunctionStartsSection>();
915   if (config->emitBitcodeBundle)
916     make<BitcodeBundleSection>();
917 
918   switch (config->outputType) {
919   case MH_EXECUTE:
920     make<PageZeroSection>();
921     break;
922   case MH_DYLIB:
923   case MH_BUNDLE:
924     break;
925   default:
926     llvm_unreachable("unhandled output file type");
927   }
928 
929   // Then add input sections to output sections.
930   for (ConcatInputSection *isec : inputSections) {
931     if (isec->shouldOmitFromOutput())
932       continue;
933     ConcatOutputSection *osec = cast<ConcatOutputSection>(isec->parent);
934     osec->addInput(isec);
935     osec->inputOrder =
936         std::min(osec->inputOrder, static_cast<int>(isec->outSecOff));
937   }
938 
939   // Once all the inputs are added, we can finalize the output section
940   // properties and create the corresponding output segments.
941   for (const auto &it : concatOutputSections) {
942     StringRef segname = it.first.first;
943     ConcatOutputSection *osec = it.second;
944     assert(segname != segment_names::ld);
945     if (osec->isNeeded())
946       getOrCreateOutputSegment(segname)->addOutputSection(osec);
947   }
948 
949   for (SyntheticSection *ssec : syntheticSections) {
950     auto it = concatOutputSections.find({ssec->segname, ssec->name});
951     // We add all LinkEdit sections here because we don't know if they are
952     // needed until their finalizeContents() methods get called later. While
953     // this means that we add some redundant sections to __LINKEDIT, there is
954     // is no redundancy in the output, as we do not emit section headers for
955     // any LinkEdit sections.
956     if (ssec->isNeeded() || ssec->segname == segment_names::linkEdit) {
957       if (it == concatOutputSections.end()) {
958         getOrCreateOutputSegment(ssec->segname)->addOutputSection(ssec);
959       } else {
960         fatal("section from " +
961               toString(it->second->firstSection()->getFile()) +
962               " conflicts with synthetic section " + ssec->segname + "," +
963               ssec->name);
964       }
965     }
966   }
967 
968   // dyld requires __LINKEDIT segment to always exist (even if empty).
969   linkEditSegment = getOrCreateOutputSegment(segment_names::linkEdit);
970 }
971 
972 void Writer::finalizeAddresses() {
973   TimeTraceScope timeScope("Finalize addresses");
974   uint64_t pageSize = target->getPageSize();
975   // Ensure that segments (and the sections they contain) are allocated
976   // addresses in ascending order, which dyld requires.
977   //
978   // Note that at this point, __LINKEDIT sections are empty, but we need to
979   // determine addresses of other segments/sections before generating its
980   // contents.
981   for (OutputSegment *seg : outputSegments) {
982     if (seg == linkEditSegment)
983       continue;
984     seg->addr = addr;
985     assignAddresses(seg);
986     // codesign / libstuff checks for segment ordering by verifying that
987     // `fileOff + fileSize == next segment fileOff`. So we call alignTo() before
988     // (instead of after) computing fileSize to ensure that the segments are
989     // contiguous. We handle addr / vmSize similarly for the same reason.
990     fileOff = alignTo(fileOff, pageSize);
991     addr = alignTo(addr, pageSize);
992     seg->vmSize = addr - seg->addr;
993     seg->fileSize = fileOff - seg->fileOff;
994     seg->assignAddressesToStartEndSymbols();
995   }
996 }
997 
998 void Writer::finalizeLinkEditSegment() {
999   TimeTraceScope timeScope("Finalize __LINKEDIT segment");
1000   // Fill __LINKEDIT contents.
1001   std::vector<LinkEditSection *> linkEditSections{
1002       in.rebase,
1003       in.binding,
1004       in.weakBinding,
1005       in.lazyBinding,
1006       in.exports,
1007       symtabSection,
1008       indirectSymtabSection,
1009       dataInCodeSection,
1010       functionStartsSection,
1011   };
1012   SmallVector<std::shared_future<void>> threadFutures;
1013   threadFutures.reserve(linkEditSections.size());
1014   for (LinkEditSection *osec : linkEditSections)
1015     if (osec)
1016       threadFutures.emplace_back(threadPool.async(
1017           [](LinkEditSection *osec) { osec->finalizeContents(); }, osec));
1018   for (std::shared_future<void> &future : threadFutures)
1019     future.wait();
1020 
1021   // Now that __LINKEDIT is filled out, do a proper calculation of its
1022   // addresses and offsets.
1023   linkEditSegment->addr = addr;
1024   assignAddresses(linkEditSegment);
1025   // No need to page-align fileOff / addr here since this is the last segment.
1026   linkEditSegment->vmSize = addr - linkEditSegment->addr;
1027   linkEditSegment->fileSize = fileOff - linkEditSegment->fileOff;
1028 }
1029 
1030 void Writer::assignAddresses(OutputSegment *seg) {
1031   seg->fileOff = fileOff;
1032 
1033   for (OutputSection *osec : seg->getSections()) {
1034     if (!osec->isNeeded())
1035       continue;
1036     addr = alignTo(addr, osec->align);
1037     fileOff = alignTo(fileOff, osec->align);
1038     osec->addr = addr;
1039     osec->fileOff = isZeroFill(osec->flags) ? 0 : fileOff;
1040     osec->finalize();
1041     osec->assignAddressesToStartEndSymbols();
1042 
1043     addr += osec->getSize();
1044     fileOff += osec->getFileSize();
1045   }
1046 }
1047 
1048 void Writer::openFile() {
1049   Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr =
1050       FileOutputBuffer::create(config->outputFile, fileOff,
1051                                FileOutputBuffer::F_executable);
1052 
1053   if (!bufferOrErr)
1054     fatal("failed to open " + config->outputFile + ": " +
1055           llvm::toString(bufferOrErr.takeError()));
1056   buffer = std::move(*bufferOrErr);
1057   in.bufferStart = buffer->getBufferStart();
1058 }
1059 
1060 void Writer::writeSections() {
1061   uint8_t *buf = buffer->getBufferStart();
1062   for (const OutputSegment *seg : outputSegments)
1063     for (const OutputSection *osec : seg->getSections())
1064       osec->writeTo(buf + osec->fileOff);
1065 }
1066 
1067 // In order to utilize multiple cores, we first split the buffer into chunks,
1068 // compute a hash for each chunk, and then compute a hash value of the hash
1069 // values.
1070 void Writer::writeUuid() {
1071   TimeTraceScope timeScope("Computing UUID");
1072 
1073   ArrayRef<uint8_t> data{buffer->getBufferStart(), buffer->getBufferEnd()};
1074   unsigned chunkCount = parallel::strategy.compute_thread_count() * 10;
1075   // Round-up integer division
1076   size_t chunkSize = (data.size() + chunkCount - 1) / chunkCount;
1077   std::vector<ArrayRef<uint8_t>> chunks = split(data, chunkSize);
1078   std::vector<uint64_t> hashes(chunks.size());
1079   SmallVector<std::shared_future<void>> threadFutures;
1080   threadFutures.reserve(chunks.size());
1081   for (size_t i = 0; i < chunks.size(); ++i)
1082     threadFutures.emplace_back(threadPool.async(
1083         [&](size_t j) { hashes[j] = xxHash64(chunks[j]); }, i));
1084   for (std::shared_future<void> &future : threadFutures)
1085     future.wait();
1086 
1087   uint64_t digest = xxHash64({reinterpret_cast<uint8_t *>(hashes.data()),
1088                               hashes.size() * sizeof(uint64_t)});
1089   uuidCommand->writeUuid(digest);
1090 }
1091 
1092 void Writer::writeCodeSignature() {
1093   if (codeSignatureSection)
1094     codeSignatureSection->writeHashes(buffer->getBufferStart());
1095 }
1096 
1097 void Writer::writeOutputFile() {
1098   TimeTraceScope timeScope("Write output file");
1099   openFile();
1100   if (errorCount())
1101     return;
1102   writeSections();
1103   writeUuid();
1104   writeCodeSignature();
1105 
1106   if (auto e = buffer->commit())
1107     error("failed to write to the output file: " + toString(std::move(e)));
1108 }
1109 
1110 template <class LP> void Writer::run() {
1111   treatSpecialUndefineds();
1112   if (config->entry && !isa<Undefined>(config->entry))
1113     prepareBranchTarget(config->entry);
1114 
1115   // Canonicalization of all pointers to InputSections should be handled by
1116   // these two scan* methods. I.e. from this point onward, for all live
1117   // InputSections, we should have `isec->canonical() == isec`.
1118   scanSymbols();
1119   scanRelocations();
1120 
1121   // Do not proceed if there was an undefined symbol.
1122   if (errorCount())
1123     return;
1124 
1125   if (in.stubHelper->isNeeded())
1126     in.stubHelper->setup();
1127   // At this point, we should know exactly which output sections are needed,
1128   // courtesy of scanSymbols() and scanRelocations().
1129   createOutputSections<LP>();
1130 
1131   // After this point, we create no new segments; HOWEVER, we might
1132   // yet create branch-range extension thunks for architectures whose
1133   // hardware call instructions have limited range, e.g., ARM(64).
1134   // The thunks are created as InputSections interspersed among
1135   // the ordinary __TEXT,_text InputSections.
1136   sortSegmentsAndSections();
1137   createLoadCommands<LP>();
1138   finalizeAddresses();
1139   threadPool.async([&] {
1140     if (LLVM_ENABLE_THREADS && config->timeTraceEnabled)
1141       timeTraceProfilerInitialize(config->timeTraceGranularity, "writeMapFile");
1142     writeMapFile();
1143     if (LLVM_ENABLE_THREADS && config->timeTraceEnabled)
1144       timeTraceProfilerFinishThread();
1145   });
1146   finalizeLinkEditSegment();
1147   writeOutputFile();
1148 }
1149 
1150 template <class LP> void macho::writeResult() { Writer().run<LP>(); }
1151 
1152 void macho::resetWriter() { LCDylib::resetInstanceCount(); }
1153 
1154 void macho::createSyntheticSections() {
1155   in.header = make<MachHeaderSection>();
1156   if (config->dedupLiterals)
1157     in.cStringSection = make<DeduplicatedCStringSection>();
1158   else
1159     in.cStringSection = make<CStringSection>();
1160   in.wordLiteralSection =
1161       config->dedupLiterals ? make<WordLiteralSection>() : nullptr;
1162   in.rebase = make<RebaseSection>();
1163   in.binding = make<BindingSection>();
1164   in.weakBinding = make<WeakBindingSection>();
1165   in.lazyBinding = make<LazyBindingSection>();
1166   in.exports = make<ExportSection>();
1167   in.got = make<GotSection>();
1168   in.tlvPointers = make<TlvPointerSection>();
1169   in.lazyPointers = make<LazyPointerSection>();
1170   in.stubs = make<StubsSection>();
1171   in.stubHelper = make<StubHelperSection>();
1172   in.unwindInfo = makeUnwindInfoSection();
1173 
1174   // This section contains space for just a single word, and will be used by
1175   // dyld to cache an address to the image loader it uses.
1176   uint8_t *arr = bAlloc().Allocate<uint8_t>(target->wordSize);
1177   memset(arr, 0, target->wordSize);
1178   in.imageLoaderCache = makeSyntheticInputSection(
1179       segment_names::data, section_names::data, S_REGULAR,
1180       ArrayRef<uint8_t>{arr, target->wordSize},
1181       /*align=*/target->wordSize);
1182   // References from dyld are not visible to us, so ensure this section is
1183   // always treated as live.
1184   in.imageLoaderCache->live = true;
1185 }
1186 
1187 OutputSection *macho::firstTLVDataSection = nullptr;
1188 
1189 template void macho::writeResult<LP64>();
1190 template void macho::writeResult<ILP32>();
1191