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