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