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