xref: /llvm-project-15.0.7/lld/MachO/Writer.cpp (revision 34c697c8)
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 "Config.h"
11 #include "InputFiles.h"
12 #include "InputSection.h"
13 #include "MapFile.h"
14 #include "MergedOutputSection.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   UnwindInfoSection *unwindInfoSection = nullptr;
75   FunctionStartsSection *functionStartsSection = nullptr;
76 
77   LCUuid *uuidCommand = nullptr;
78   OutputSegment *linkEditSegment = nullptr;
79 };
80 
81 // LC_DYLD_INFO_ONLY stores the offsets of symbol import/export information.
82 class LCDyldInfo : public LoadCommand {
83 public:
84   LCDyldInfo(RebaseSection *rebaseSection, BindingSection *bindingSection,
85              WeakBindingSection *weakBindingSection,
86              LazyBindingSection *lazyBindingSection,
87              ExportSection *exportSection)
88       : rebaseSection(rebaseSection), bindingSection(bindingSection),
89         weakBindingSection(weakBindingSection),
90         lazyBindingSection(lazyBindingSection), exportSection(exportSection) {}
91 
92   uint32_t getSize() const override { return sizeof(dyld_info_command); }
93 
94   void writeTo(uint8_t *buf) const override {
95     auto *c = reinterpret_cast<dyld_info_command *>(buf);
96     c->cmd = LC_DYLD_INFO_ONLY;
97     c->cmdsize = getSize();
98     if (rebaseSection->isNeeded()) {
99       c->rebase_off = rebaseSection->fileOff;
100       c->rebase_size = rebaseSection->getFileSize();
101     }
102     if (bindingSection->isNeeded()) {
103       c->bind_off = bindingSection->fileOff;
104       c->bind_size = bindingSection->getFileSize();
105     }
106     if (weakBindingSection->isNeeded()) {
107       c->weak_bind_off = weakBindingSection->fileOff;
108       c->weak_bind_size = weakBindingSection->getFileSize();
109     }
110     if (lazyBindingSection->isNeeded()) {
111       c->lazy_bind_off = lazyBindingSection->fileOff;
112       c->lazy_bind_size = lazyBindingSection->getFileSize();
113     }
114     if (exportSection->isNeeded()) {
115       c->export_off = exportSection->fileOff;
116       c->export_size = exportSection->getFileSize();
117     }
118   }
119 
120   RebaseSection *rebaseSection;
121   BindingSection *bindingSection;
122   WeakBindingSection *weakBindingSection;
123   LazyBindingSection *lazyBindingSection;
124   ExportSection *exportSection;
125 };
126 
127 class LCFunctionStarts : public LoadCommand {
128 public:
129   explicit LCFunctionStarts(FunctionStartsSection *functionStartsSection)
130       : functionStartsSection(functionStartsSection) {}
131 
132   uint32_t getSize() const override { return sizeof(linkedit_data_command); }
133 
134   void writeTo(uint8_t *buf) const override {
135     auto *c = reinterpret_cast<linkedit_data_command *>(buf);
136     c->cmd = LC_FUNCTION_STARTS;
137     c->cmdsize = getSize();
138     c->dataoff = functionStartsSection->fileOff;
139     c->datasize = functionStartsSection->getFileSize();
140   }
141 
142 private:
143   FunctionStartsSection *functionStartsSection;
144 };
145 
146 class LCDysymtab : public LoadCommand {
147 public:
148   LCDysymtab(SymtabSection *symtabSection,
149              IndirectSymtabSection *indirectSymtabSection)
150       : symtabSection(symtabSection),
151         indirectSymtabSection(indirectSymtabSection) {}
152 
153   uint32_t getSize() const override { return sizeof(dysymtab_command); }
154 
155   void writeTo(uint8_t *buf) const override {
156     auto *c = reinterpret_cast<dysymtab_command *>(buf);
157     c->cmd = LC_DYSYMTAB;
158     c->cmdsize = getSize();
159 
160     c->ilocalsym = 0;
161     c->iextdefsym = c->nlocalsym = symtabSection->getNumLocalSymbols();
162     c->nextdefsym = symtabSection->getNumExternalSymbols();
163     c->iundefsym = c->iextdefsym + c->nextdefsym;
164     c->nundefsym = symtabSection->getNumUndefinedSymbols();
165 
166     c->indirectsymoff = indirectSymtabSection->fileOff;
167     c->nindirectsyms = indirectSymtabSection->getNumSymbols();
168   }
169 
170   SymtabSection *symtabSection;
171   IndirectSymtabSection *indirectSymtabSection;
172 };
173 
174 template <class LP> class LCSegment : public LoadCommand {
175 public:
176   LCSegment(StringRef name, OutputSegment *seg) : name(name), seg(seg) {}
177 
178   uint32_t getSize() const override {
179     return sizeof(typename LP::segment_command) +
180            seg->numNonHiddenSections() * sizeof(typename LP::section);
181   }
182 
183   void writeTo(uint8_t *buf) const override {
184     using SegmentCommand = typename LP::segment_command;
185     using Section = typename LP::section;
186 
187     auto *c = reinterpret_cast<SegmentCommand *>(buf);
188     buf += sizeof(SegmentCommand);
189 
190     c->cmd = LP::segmentLCType;
191     c->cmdsize = getSize();
192     memcpy(c->segname, name.data(), name.size());
193     c->fileoff = seg->fileOff;
194     c->maxprot = seg->maxProt;
195     c->initprot = seg->initProt;
196 
197     if (seg->getSections().empty())
198       return;
199 
200     c->vmaddr = seg->firstSection()->addr;
201     c->vmsize =
202         seg->lastSection()->addr + seg->lastSection()->getSize() - c->vmaddr;
203     c->nsects = seg->numNonHiddenSections();
204 
205     for (const OutputSection *osec : seg->getSections()) {
206       if (!isZeroFill(osec->flags)) {
207         assert(osec->fileOff >= seg->fileOff);
208         c->filesize = std::max<uint64_t>(
209             c->filesize, osec->fileOff + osec->getFileSize() - seg->fileOff);
210       }
211 
212       if (osec->isHidden())
213         continue;
214 
215       auto *sectHdr = reinterpret_cast<Section *>(buf);
216       buf += sizeof(Section);
217 
218       memcpy(sectHdr->sectname, osec->name.data(), osec->name.size());
219       memcpy(sectHdr->segname, name.data(), name.size());
220 
221       sectHdr->addr = osec->addr;
222       sectHdr->offset = osec->fileOff;
223       sectHdr->align = Log2_32(osec->align);
224       sectHdr->flags = osec->flags;
225       sectHdr->size = osec->getSize();
226       sectHdr->reserved1 = osec->reserved1;
227       sectHdr->reserved2 = osec->reserved2;
228     }
229   }
230 
231 private:
232   StringRef name;
233   OutputSegment *seg;
234 };
235 
236 class LCMain : public LoadCommand {
237   uint32_t getSize() const override { return sizeof(entry_point_command); }
238 
239   void writeTo(uint8_t *buf) const override {
240     auto *c = reinterpret_cast<entry_point_command *>(buf);
241     c->cmd = LC_MAIN;
242     c->cmdsize = getSize();
243 
244     if (config->entry->isInStubs())
245       c->entryoff =
246           in.stubs->fileOff + config->entry->stubsIndex * target->stubSize;
247     else
248       c->entryoff = config->entry->getFileOffset();
249 
250     c->stacksize = 0;
251   }
252 };
253 
254 class LCSymtab : public LoadCommand {
255 public:
256   LCSymtab(SymtabSection *symtabSection, StringTableSection *stringTableSection)
257       : symtabSection(symtabSection), stringTableSection(stringTableSection) {}
258 
259   uint32_t getSize() const override { return sizeof(symtab_command); }
260 
261   void writeTo(uint8_t *buf) const override {
262     auto *c = reinterpret_cast<symtab_command *>(buf);
263     c->cmd = LC_SYMTAB;
264     c->cmdsize = getSize();
265     c->symoff = symtabSection->fileOff;
266     c->nsyms = symtabSection->getNumSymbols();
267     c->stroff = stringTableSection->fileOff;
268     c->strsize = stringTableSection->getFileSize();
269   }
270 
271   SymtabSection *symtabSection = nullptr;
272   StringTableSection *stringTableSection = nullptr;
273 };
274 
275 // There are several dylib load commands that share the same structure:
276 //   * LC_LOAD_DYLIB
277 //   * LC_ID_DYLIB
278 //   * LC_REEXPORT_DYLIB
279 class LCDylib : public LoadCommand {
280 public:
281   LCDylib(LoadCommandType type, StringRef path,
282           uint32_t compatibilityVersion = 0, uint32_t currentVersion = 0)
283       : type(type), path(path), compatibilityVersion(compatibilityVersion),
284         currentVersion(currentVersion) {
285     instanceCount++;
286   }
287 
288   uint32_t getSize() const override {
289     return alignTo(sizeof(dylib_command) + path.size() + 1, 8);
290   }
291 
292   void writeTo(uint8_t *buf) const override {
293     auto *c = reinterpret_cast<dylib_command *>(buf);
294     buf += sizeof(dylib_command);
295 
296     c->cmd = type;
297     c->cmdsize = getSize();
298     c->dylib.name = sizeof(dylib_command);
299     c->dylib.timestamp = 0;
300     c->dylib.compatibility_version = compatibilityVersion;
301     c->dylib.current_version = currentVersion;
302 
303     memcpy(buf, path.data(), path.size());
304     buf[path.size()] = '\0';
305   }
306 
307   static uint32_t getInstanceCount() { return instanceCount; }
308 
309 private:
310   LoadCommandType type;
311   StringRef path;
312   uint32_t compatibilityVersion;
313   uint32_t currentVersion;
314   static uint32_t instanceCount;
315 };
316 
317 uint32_t LCDylib::instanceCount = 0;
318 
319 class LCLoadDylinker : public LoadCommand {
320 public:
321   uint32_t getSize() const override {
322     return alignTo(sizeof(dylinker_command) + path.size() + 1, 8);
323   }
324 
325   void writeTo(uint8_t *buf) const override {
326     auto *c = reinterpret_cast<dylinker_command *>(buf);
327     buf += sizeof(dylinker_command);
328 
329     c->cmd = LC_LOAD_DYLINKER;
330     c->cmdsize = getSize();
331     c->name = sizeof(dylinker_command);
332 
333     memcpy(buf, path.data(), path.size());
334     buf[path.size()] = '\0';
335   }
336 
337 private:
338   // Recent versions of Darwin won't run any binary that has dyld at a
339   // different location.
340   const StringRef path = "/usr/lib/dyld";
341 };
342 
343 class LCRPath : public LoadCommand {
344 public:
345   LCRPath(StringRef path) : path(path) {}
346 
347   uint32_t getSize() const override {
348     return alignTo(sizeof(rpath_command) + path.size() + 1, target->wordSize);
349   }
350 
351   void writeTo(uint8_t *buf) const override {
352     auto *c = reinterpret_cast<rpath_command *>(buf);
353     buf += sizeof(rpath_command);
354 
355     c->cmd = LC_RPATH;
356     c->cmdsize = getSize();
357     c->path = sizeof(rpath_command);
358 
359     memcpy(buf, path.data(), path.size());
360     buf[path.size()] = '\0';
361   }
362 
363 private:
364   StringRef path;
365 };
366 
367 class LCBuildVersion : public LoadCommand {
368 public:
369   LCBuildVersion(PlatformKind platform, const PlatformInfo &platformInfo)
370       : platform(platform), platformInfo(platformInfo) {}
371 
372   const int ntools = 1;
373 
374   uint32_t getSize() const override {
375     return sizeof(build_version_command) + ntools * sizeof(build_tool_version);
376   }
377 
378   void writeTo(uint8_t *buf) const override {
379     auto *c = reinterpret_cast<build_version_command *>(buf);
380     c->cmd = LC_BUILD_VERSION;
381     c->cmdsize = getSize();
382     c->platform = static_cast<uint32_t>(platform);
383     c->minos = ((platformInfo.minimum.getMajor() << 020) |
384                 (platformInfo.minimum.getMinor().getValueOr(0) << 010) |
385                 platformInfo.minimum.getSubminor().getValueOr(0));
386     c->sdk = ((platformInfo.sdk.getMajor() << 020) |
387               (platformInfo.sdk.getMinor().getValueOr(0) << 010) |
388               platformInfo.sdk.getSubminor().getValueOr(0));
389     c->ntools = ntools;
390     auto *t = reinterpret_cast<build_tool_version *>(&c[1]);
391     t->tool = TOOL_LD;
392     t->version = (LLVM_VERSION_MAJOR << 020) | (LLVM_VERSION_MINOR << 010) |
393                  LLVM_VERSION_PATCH;
394   }
395 
396   PlatformKind platform;
397   const PlatformInfo &platformInfo;
398 };
399 
400 // Stores a unique identifier for the output file based on an MD5 hash of its
401 // contents. In order to hash the contents, we must first write them, but
402 // LC_UUID itself must be part of the written contents in order for all the
403 // offsets to be calculated correctly. We resolve this circular paradox by
404 // first writing an LC_UUID with an all-zero UUID, then updating the UUID with
405 // its real value later.
406 class LCUuid : public LoadCommand {
407 public:
408   uint32_t getSize() const override { return sizeof(uuid_command); }
409 
410   void writeTo(uint8_t *buf) const override {
411     auto *c = reinterpret_cast<uuid_command *>(buf);
412     c->cmd = LC_UUID;
413     c->cmdsize = getSize();
414     uuidBuf = c->uuid;
415   }
416 
417   void writeUuid(uint64_t digest) const {
418     // xxhash only gives us 8 bytes, so put some fixed data in the other half.
419     static_assert(sizeof(uuid_command::uuid) == 16, "unexpected uuid size");
420     memcpy(uuidBuf, "LLD\xa1UU1D", 8);
421     memcpy(uuidBuf + 8, &digest, 8);
422 
423     // RFC 4122 conformance. We need to fix 4 bits in byte 6 and 2 bits in
424     // byte 8. Byte 6 is already fine due to the fixed data we put in. We don't
425     // want to lose bits of the digest in byte 8, so swap that with a byte of
426     // fixed data that happens to have the right bits set.
427     std::swap(uuidBuf[3], uuidBuf[8]);
428 
429     // Claim that this is an MD5-based hash. It isn't, but this signals that
430     // this is not a time-based and not a random hash. MD5 seems like the least
431     // bad lie we can put here.
432     assert((uuidBuf[6] & 0xf0) == 0x30 && "See RFC 4122 Sections 4.2.2, 4.1.3");
433     assert((uuidBuf[8] & 0xc0) == 0x80 && "See RFC 4122 Section 4.2.2");
434   }
435 
436   mutable uint8_t *uuidBuf;
437 };
438 
439 class LCCodeSignature : public LoadCommand {
440 public:
441   LCCodeSignature(CodeSignatureSection *section) : section(section) {}
442 
443   uint32_t getSize() const override { return sizeof(linkedit_data_command); }
444 
445   void writeTo(uint8_t *buf) const override {
446     auto *c = reinterpret_cast<linkedit_data_command *>(buf);
447     c->cmd = LC_CODE_SIGNATURE;
448     c->cmdsize = getSize();
449     c->dataoff = static_cast<uint32_t>(section->fileOff);
450     c->datasize = section->getSize();
451   }
452 
453   CodeSignatureSection *section;
454 };
455 
456 } // namespace
457 
458 // Adds stubs and bindings where necessary (e.g. if the symbol is a
459 // DylibSymbol.)
460 static void prepareBranchTarget(Symbol *sym) {
461   if (auto *dysym = dyn_cast<DylibSymbol>(sym)) {
462     if (in.stubs->addEntry(dysym)) {
463       if (sym->isWeakDef()) {
464         in.binding->addEntry(dysym, in.lazyPointers->isec,
465                              sym->stubsIndex * target->wordSize);
466         in.weakBinding->addEntry(sym, in.lazyPointers->isec,
467                                  sym->stubsIndex * target->wordSize);
468       } else {
469         in.lazyBinding->addEntry(dysym);
470       }
471     }
472   } else if (auto *defined = dyn_cast<Defined>(sym)) {
473     if (defined->isExternalWeakDef()) {
474       if (in.stubs->addEntry(sym)) {
475         in.rebase->addEntry(in.lazyPointers->isec,
476                             sym->stubsIndex * target->wordSize);
477         in.weakBinding->addEntry(sym, in.lazyPointers->isec,
478                                  sym->stubsIndex * target->wordSize);
479       }
480     }
481   }
482 }
483 
484 // Can a symbol's address can only be resolved at runtime?
485 static bool needsBinding(const Symbol *sym) {
486   if (isa<DylibSymbol>(sym))
487     return true;
488   if (const auto *defined = dyn_cast<Defined>(sym))
489     return defined->isExternalWeakDef();
490   return false;
491 }
492 
493 static void prepareSymbolRelocation(Symbol *sym, const InputSection *isec,
494                                     const Reloc &r) {
495   const RelocAttrs &relocAttrs = target->getRelocAttrs(r.type);
496 
497   if (relocAttrs.hasAttr(RelocAttrBits::BRANCH)) {
498     prepareBranchTarget(sym);
499   } else if (relocAttrs.hasAttr(RelocAttrBits::GOT)) {
500     if (relocAttrs.hasAttr(RelocAttrBits::POINTER) || needsBinding(sym))
501       in.got->addEntry(sym);
502   } else if (relocAttrs.hasAttr(RelocAttrBits::TLV)) {
503     if (needsBinding(sym))
504       in.tlvPointers->addEntry(sym);
505   } else if (relocAttrs.hasAttr(RelocAttrBits::UNSIGNED)) {
506     // References from thread-local variable sections are treated as offsets
507     // relative to the start of the referent section, and therefore have no
508     // need of rebase opcodes.
509     if (!(isThreadLocalVariables(isec->flags) && isa<Defined>(sym)))
510       addNonLazyBindingEntries(sym, isec, r.offset, r.addend);
511   }
512 }
513 
514 void Writer::scanRelocations() {
515   TimeTraceScope timeScope("Scan relocations");
516   for (InputSection *isec : inputSections) {
517     if (isec->segname == segment_names::ld) {
518       prepareCompactUnwind(isec);
519       continue;
520     }
521 
522     for (auto it = isec->relocs.begin(); it != isec->relocs.end(); ++it) {
523       Reloc &r = *it;
524       if (target->hasAttr(r.type, RelocAttrBits::SUBTRAHEND)) {
525         // Skip over the following UNSIGNED relocation -- it's just there as the
526         // minuend, and doesn't have the usual UNSIGNED semantics. We don't want
527         // to emit rebase opcodes for it.
528         it = std::next(it);
529         assert(isa<Defined>(it->referent.dyn_cast<Symbol *>()));
530         continue;
531       }
532       if (auto *sym = r.referent.dyn_cast<Symbol *>()) {
533         if (auto *undefined = dyn_cast<Undefined>(sym))
534           treatUndefinedSymbol(*undefined);
535         // treatUndefinedSymbol() can replace sym with a DylibSymbol; re-check.
536         if (!isa<Undefined>(sym) && validateSymbolRelocation(sym, isec, r))
537           prepareSymbolRelocation(sym, isec, r);
538       } else {
539         assert(r.referent.is<InputSection *>());
540         if (!r.pcrel)
541           in.rebase->addEntry(isec, r.offset);
542       }
543     }
544   }
545 }
546 
547 void Writer::scanSymbols() {
548   TimeTraceScope timeScope("Scan symbols");
549   for (const Symbol *sym : symtab->getSymbols()) {
550     if (const auto *defined = dyn_cast<Defined>(sym)) {
551       if (defined->overridesWeakDef)
552         in.weakBinding->addNonWeakDefinition(defined);
553     } else if (const auto *dysym = dyn_cast<DylibSymbol>(sym)) {
554       if (dysym->isDynamicLookup())
555         continue;
556       dysym->getFile()->refState =
557           std::max(dysym->getFile()->refState, dysym->refState);
558     }
559   }
560 }
561 
562 template <class LP> void Writer::createLoadCommands() {
563   uint8_t segIndex = 0;
564   for (OutputSegment *seg : outputSegments) {
565     in.header->addLoadCommand(make<LCSegment<LP>>(seg->name, seg));
566     seg->index = segIndex++;
567   }
568 
569   in.header->addLoadCommand(make<LCDyldInfo>(
570       in.rebase, in.binding, in.weakBinding, in.lazyBinding, in.exports));
571   in.header->addLoadCommand(make<LCSymtab>(symtabSection, stringTableSection));
572   in.header->addLoadCommand(
573       make<LCDysymtab>(symtabSection, indirectSymtabSection));
574   if (functionStartsSection)
575     in.header->addLoadCommand(make<LCFunctionStarts>(functionStartsSection));
576   for (StringRef path : config->runtimePaths)
577     in.header->addLoadCommand(make<LCRPath>(path));
578 
579   switch (config->outputType) {
580   case MH_EXECUTE:
581     in.header->addLoadCommand(make<LCLoadDylinker>());
582     in.header->addLoadCommand(make<LCMain>());
583     break;
584   case MH_DYLIB:
585     in.header->addLoadCommand(make<LCDylib>(LC_ID_DYLIB, config->installName,
586                                             config->dylibCompatibilityVersion,
587                                             config->dylibCurrentVersion));
588     break;
589   case MH_BUNDLE:
590     break;
591   default:
592     llvm_unreachable("unhandled output file type");
593   }
594 
595   uuidCommand = make<LCUuid>();
596   in.header->addLoadCommand(uuidCommand);
597 
598   in.header->addLoadCommand(
599       make<LCBuildVersion>(config->target.Platform, config->platformInfo));
600 
601   int64_t dylibOrdinal = 1;
602   for (InputFile *file : inputFiles) {
603     if (auto *dylibFile = dyn_cast<DylibFile>(file)) {
604       if (dylibFile->isBundleLoader) {
605         dylibFile->ordinal = BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE;
606         // Shortcut since bundle-loader does not re-export the symbols.
607 
608         dylibFile->reexport = false;
609         continue;
610       }
611 
612       dylibFile->ordinal = dylibOrdinal++;
613       LoadCommandType lcType =
614           dylibFile->forceWeakImport || dylibFile->refState == RefState::Weak
615               ? LC_LOAD_WEAK_DYLIB
616               : LC_LOAD_DYLIB;
617       in.header->addLoadCommand(make<LCDylib>(lcType, dylibFile->dylibName,
618                                               dylibFile->compatibilityVersion,
619                                               dylibFile->currentVersion));
620 
621       if (dylibFile->reexport)
622         in.header->addLoadCommand(
623             make<LCDylib>(LC_REEXPORT_DYLIB, dylibFile->dylibName));
624     }
625   }
626 
627   if (codeSignatureSection)
628     in.header->addLoadCommand(make<LCCodeSignature>(codeSignatureSection));
629 
630   const uint32_t MACOS_MAXPATHLEN = 1024;
631   config->headerPad = std::max(
632       config->headerPad, (config->headerPadMaxInstallNames
633                               ? LCDylib::getInstanceCount() * MACOS_MAXPATHLEN
634                               : 0));
635 }
636 
637 static size_t getSymbolPriority(const SymbolPriorityEntry &entry,
638                                 const InputFile *f) {
639   // We don't use toString(InputFile *) here because it returns the full path
640   // for object files, and we only want the basename.
641   StringRef filename;
642   if (f->archiveName.empty())
643     filename = path::filename(f->getName());
644   else
645     filename = saver.save(path::filename(f->archiveName) + "(" +
646                           path::filename(f->getName()) + ")");
647   return std::max(entry.objectFiles.lookup(filename), entry.anyObjectFile);
648 }
649 
650 // Each section gets assigned the priority of the highest-priority symbol it
651 // contains.
652 static DenseMap<const InputSection *, size_t> buildInputSectionPriorities() {
653   DenseMap<const InputSection *, size_t> sectionPriorities;
654 
655   if (config->priorities.empty())
656     return sectionPriorities;
657 
658   auto addSym = [&](Defined &sym) {
659     auto it = config->priorities.find(sym.getName());
660     if (it == config->priorities.end())
661       return;
662 
663     SymbolPriorityEntry &entry = it->second;
664     size_t &priority = sectionPriorities[sym.isec];
665     priority = std::max(priority, getSymbolPriority(entry, sym.isec->file));
666   };
667 
668   // TODO: Make sure this handles weak symbols correctly.
669   for (const InputFile *file : inputFiles) {
670     if (isa<ObjFile>(file))
671       for (Symbol *sym : file->symbols)
672         if (auto *d = dyn_cast<Defined>(sym))
673           addSym(*d);
674   }
675 
676   return sectionPriorities;
677 }
678 
679 static int segmentOrder(OutputSegment *seg) {
680   return StringSwitch<int>(seg->name)
681       .Case(segment_names::pageZero, -4)
682       .Case(segment_names::text, -3)
683       .Case(segment_names::dataConst, -2)
684       .Case(segment_names::data, -1)
685       // Make sure __LINKEDIT is the last segment (i.e. all its hidden
686       // sections must be ordered after other sections).
687       .Case(segment_names::linkEdit, std::numeric_limits<int>::max())
688       .Default(0);
689 }
690 
691 static int sectionOrder(OutputSection *osec) {
692   StringRef segname = osec->parent->name;
693   // Sections are uniquely identified by their segment + section name.
694   if (segname == segment_names::text) {
695     return StringSwitch<int>(osec->name)
696         .Case(section_names::header, -4)
697         .Case(section_names::text, -3)
698         .Case(section_names::stubs, -2)
699         .Case(section_names::stubHelper, -1)
700         .Case(section_names::unwindInfo, std::numeric_limits<int>::max() - 1)
701         .Case(section_names::ehFrame, std::numeric_limits<int>::max())
702         .Default(0);
703   } else if (segname == segment_names::data) {
704     // For each thread spawned, dyld will initialize its TLVs by copying the
705     // address range from the start of the first thread-local data section to
706     // the end of the last one. We therefore arrange these sections contiguously
707     // to minimize the amount of memory used. Additionally, since zerofill
708     // sections must be at the end of their segments, and since TLV data
709     // sections can be zerofills, we end up putting all TLV data sections at the
710     // end of the segment.
711     switch (sectionType(osec->flags)) {
712     case S_THREAD_LOCAL_REGULAR:
713       return std::numeric_limits<int>::max() - 2;
714     case S_THREAD_LOCAL_ZEROFILL:
715       return std::numeric_limits<int>::max() - 1;
716     case S_ZEROFILL:
717       return std::numeric_limits<int>::max();
718     default:
719       return StringSwitch<int>(osec->name)
720           .Case(section_names::laSymbolPtr, -2)
721           .Case(section_names::data, -1)
722           .Default(0);
723     }
724   } else if (segname == segment_names::linkEdit) {
725     return StringSwitch<int>(osec->name)
726         .Case(section_names::rebase, -9)
727         .Case(section_names::binding, -8)
728         .Case(section_names::weakBinding, -7)
729         .Case(section_names::lazyBinding, -6)
730         .Case(section_names::export_, -5)
731         .Case(section_names::functionStarts, -4)
732         .Case(section_names::symbolTable, -3)
733         .Case(section_names::indirectSymbolTable, -2)
734         .Case(section_names::stringTable, -1)
735         .Case(section_names::codeSignature, std::numeric_limits<int>::max())
736         .Default(0);
737   }
738   // ZeroFill sections must always be the at the end of their segments,
739   // otherwise subsequent sections may get overwritten with zeroes at runtime.
740   if (sectionType(osec->flags) == S_ZEROFILL)
741     return std::numeric_limits<int>::max();
742   return 0;
743 }
744 
745 template <typename T, typename F>
746 static std::function<bool(T, T)> compareByOrder(F ord) {
747   return [=](T a, T b) { return ord(a) < ord(b); };
748 }
749 
750 // Sorting only can happen once all outputs have been collected. Here we sort
751 // segments, output sections within each segment, and input sections within each
752 // output segment.
753 static void sortSegmentsAndSections() {
754   TimeTraceScope timeScope("Sort segments and sections");
755 
756   llvm::stable_sort(outputSegments,
757                     compareByOrder<OutputSegment *>(segmentOrder));
758 
759   DenseMap<const InputSection *, size_t> isecPriorities =
760       buildInputSectionPriorities();
761 
762   uint32_t sectionIndex = 0;
763   for (OutputSegment *seg : outputSegments) {
764     seg->sortOutputSections(compareByOrder<OutputSection *>(sectionOrder));
765     for (OutputSection *osec : seg->getSections()) {
766       // Now that the output sections are sorted, assign the final
767       // output section indices.
768       if (!osec->isHidden())
769         osec->index = ++sectionIndex;
770       if (!firstTLVDataSection && isThreadLocalData(osec->flags))
771         firstTLVDataSection = osec;
772 
773       if (!isecPriorities.empty()) {
774         if (auto *merged = dyn_cast<MergedOutputSection>(osec)) {
775           llvm::stable_sort(merged->inputs,
776                             [&](InputSection *a, InputSection *b) {
777                               return isecPriorities[a] > isecPriorities[b];
778                             });
779         }
780       }
781     }
782   }
783 }
784 
785 static NamePair maybeRenameSection(NamePair key) {
786   auto newNames = config->sectionRenameMap.find(key);
787   if (newNames != config->sectionRenameMap.end())
788     return newNames->second;
789   auto newName = config->segmentRenameMap.find(key.first);
790   if (newName != config->segmentRenameMap.end())
791     return std::make_pair(newName->second, key.second);
792   return key;
793 }
794 
795 template <class LP> void Writer::createOutputSections() {
796   TimeTraceScope timeScope("Create output sections");
797   // First, create hidden sections
798   stringTableSection = make<StringTableSection>();
799   unwindInfoSection = make<UnwindInfoSection>(); // TODO(gkm): only when no -r
800   symtabSection = makeSymtabSection<LP>(*stringTableSection);
801   indirectSymtabSection = make<IndirectSymtabSection>();
802   if (config->adhocCodesign)
803     codeSignatureSection = make<CodeSignatureSection>();
804   if (config->emitFunctionStarts)
805     functionStartsSection = make<FunctionStartsSection>();
806 
807   switch (config->outputType) {
808   case MH_EXECUTE:
809     make<PageZeroSection>();
810     break;
811   case MH_DYLIB:
812   case MH_BUNDLE:
813     break;
814   default:
815     llvm_unreachable("unhandled output file type");
816   }
817 
818   // Then merge input sections into output sections.
819   MapVector<NamePair, MergedOutputSection *> mergedOutputSections;
820   for (InputSection *isec : inputSections) {
821     NamePair names = maybeRenameSection({isec->segname, isec->name});
822     MergedOutputSection *&osec = mergedOutputSections[names];
823     if (osec == nullptr)
824       osec = make<MergedOutputSection>(names.second);
825     osec->mergeInput(isec);
826   }
827 
828   for (const auto &it : mergedOutputSections) {
829     StringRef segname = it.first.first;
830     MergedOutputSection *osec = it.second;
831     if (unwindInfoSection && segname == segment_names::ld) {
832       assert(osec->name == section_names::compactUnwind);
833       unwindInfoSection->setCompactUnwindSection(osec);
834     } else {
835       getOrCreateOutputSegment(segname)->addOutputSection(osec);
836     }
837   }
838 
839   for (SyntheticSection *ssec : syntheticSections) {
840     auto it = mergedOutputSections.find({ssec->segname, ssec->name});
841     if (it == mergedOutputSections.end()) {
842       if (ssec->isNeeded())
843         getOrCreateOutputSegment(ssec->segname)->addOutputSection(ssec);
844     } else {
845       error("section from " + toString(it->second->firstSection()->file) +
846             " conflicts with synthetic section " + ssec->segname + "," +
847             ssec->name);
848     }
849   }
850 
851   // dyld requires __LINKEDIT segment to always exist (even if empty).
852   linkEditSegment = getOrCreateOutputSegment(segment_names::linkEdit);
853 }
854 
855 void Writer::finalizeAddresses() {
856   TimeTraceScope timeScope("Finalize addresses");
857   // Ensure that segments (and the sections they contain) are allocated
858   // addresses in ascending order, which dyld requires.
859   //
860   // Note that at this point, __LINKEDIT sections are empty, but we need to
861   // determine addresses of other segments/sections before generating its
862   // contents.
863   for (OutputSegment *seg : outputSegments)
864     if (seg != linkEditSegment)
865       assignAddresses(seg);
866 
867   // FIXME(gkm): create branch-extension thunks here, then adjust addresses
868 }
869 
870 void Writer::finalizeLinkEditSegment() {
871   TimeTraceScope timeScope("Finalize __LINKEDIT segment");
872   // Fill __LINKEDIT contents.
873   std::vector<LinkEditSection *> linkEditSections{
874       in.rebase,  in.binding,    in.weakBinding,        in.lazyBinding,
875       in.exports, symtabSection, indirectSymtabSection, functionStartsSection,
876   };
877   parallelForEach(linkEditSections, [](LinkEditSection *osec) {
878     if (osec)
879       osec->finalizeContents();
880   });
881 
882   // Now that __LINKEDIT is filled out, do a proper calculation of its
883   // addresses and offsets.
884   assignAddresses(linkEditSegment);
885 }
886 
887 void Writer::assignAddresses(OutputSegment *seg) {
888   uint64_t pageSize = target->getPageSize();
889   addr = alignTo(addr, pageSize);
890   fileOff = alignTo(fileOff, pageSize);
891   seg->fileOff = fileOff;
892 
893   for (OutputSection *osec : seg->getSections()) {
894     if (!osec->isNeeded())
895       continue;
896     addr = alignTo(addr, osec->align);
897     fileOff = alignTo(fileOff, osec->align);
898     osec->addr = addr;
899     osec->fileOff = isZeroFill(osec->flags) ? 0 : fileOff;
900     osec->finalize();
901 
902     addr += osec->getSize();
903     fileOff += osec->getFileSize();
904   }
905   seg->fileSize = fileOff - seg->fileOff;
906 }
907 
908 void Writer::openFile() {
909   Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr =
910       FileOutputBuffer::create(config->outputFile, fileOff,
911                                FileOutputBuffer::F_executable);
912 
913   if (!bufferOrErr)
914     error("failed to open " + config->outputFile + ": " +
915           llvm::toString(bufferOrErr.takeError()));
916   else
917     buffer = std::move(*bufferOrErr);
918 }
919 
920 void Writer::writeSections() {
921   uint8_t *buf = buffer->getBufferStart();
922   for (const OutputSegment *seg : outputSegments)
923     for (const OutputSection *osec : seg->getSections())
924       osec->writeTo(buf + osec->fileOff);
925 }
926 
927 // In order to utilize multiple cores, we first split the buffer into chunks,
928 // compute a hash for each chunk, and then compute a hash value of the hash
929 // values.
930 void Writer::writeUuid() {
931   TimeTraceScope timeScope("Computing UUID");
932   ArrayRef<uint8_t> data{buffer->getBufferStart(), buffer->getBufferEnd()};
933   unsigned chunkCount = parallel::strategy.compute_thread_count() * 10;
934   // Round-up integer division
935   size_t chunkSize = (data.size() + chunkCount - 1) / chunkCount;
936   std::vector<ArrayRef<uint8_t>> chunks = split(data, chunkSize);
937   std::vector<uint64_t> hashes(chunks.size());
938   parallelForEachN(0, chunks.size(),
939                    [&](size_t i) { hashes[i] = xxHash64(chunks[i]); });
940   uint64_t digest = xxHash64({reinterpret_cast<uint8_t *>(hashes.data()),
941                               hashes.size() * sizeof(uint64_t)});
942   uuidCommand->writeUuid(digest);
943 }
944 
945 void Writer::writeCodeSignature() {
946   if (codeSignatureSection)
947     codeSignatureSection->writeHashes(buffer->getBufferStart());
948 }
949 
950 void Writer::writeOutputFile() {
951   TimeTraceScope timeScope("Write output file");
952   openFile();
953   if (errorCount())
954     return;
955   writeSections();
956   writeUuid();
957   writeCodeSignature();
958 
959   if (auto e = buffer->commit())
960     error("failed to write to the output file: " + toString(std::move(e)));
961 }
962 
963 template <class LP> void Writer::run() {
964   prepareBranchTarget(config->entry);
965   scanRelocations();
966   if (in.stubHelper->isNeeded())
967     in.stubHelper->setup();
968   scanSymbols();
969   createOutputSections<LP>();
970   // No more sections nor segments are created beyond this point.
971   sortSegmentsAndSections();
972   createLoadCommands<LP>();
973   finalizeAddresses();
974   finalizeLinkEditSegment();
975   writeMapFile();
976   writeOutputFile();
977 }
978 
979 template <class LP> void macho::writeResult() { Writer().run<LP>(); }
980 
981 template <class LP> void macho::createSyntheticSections() {
982   in.header = makeMachHeaderSection<LP>();
983   in.rebase = make<RebaseSection>();
984   in.binding = make<BindingSection>();
985   in.weakBinding = make<WeakBindingSection>();
986   in.lazyBinding = make<LazyBindingSection>();
987   in.exports = make<ExportSection>();
988   in.got = make<GotSection>();
989   in.tlvPointers = make<TlvPointerSection>();
990   in.lazyPointers = make<LazyPointerSection>();
991   in.stubs = make<StubsSection>();
992   in.stubHelper = make<StubHelperSection>();
993   in.imageLoaderCache = make<ImageLoaderCacheSection>();
994 }
995 
996 OutputSection *macho::firstTLVDataSection = nullptr;
997 
998 template void macho::writeResult<LP64>();
999 template void macho::writeResult<ILP32>();
1000 template void macho::createSyntheticSections<LP64>();
1001 template void macho::createSyntheticSections<ILP32>();
1002