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