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