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