xref: /llvm-project-15.0.7/lld/MachO/Writer.cpp (revision 77f0ea4b)
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/MD5.h"
28 #include "llvm/Support/MathExtras.h"
29 #include "llvm/Support/Path.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(const std::array<uint8_t, 16> &uuid) const {
372     memcpy(uuidBuf, uuid.data(), uuid.size());
373   }
374 
375   mutable uint8_t *uuidBuf;
376 };
377 
378 } // namespace
379 
380 void Writer::scanRelocations() {
381   for (InputSection *isec : inputSections) {
382     // We do not wish to add rebase opcodes for __LD,__compact_unwind, because
383     // it doesn't actually end up in the final binary. TODO: filtering it out
384     // before Writer runs might be cleaner...
385     if (isec->segname == segment_names::ld)
386       continue;
387 
388     for (Reloc &r : isec->relocs) {
389       if (auto *s = r.referent.dyn_cast<lld::macho::Symbol *>()) {
390         if (isa<Undefined>(s))
391           error("undefined symbol " + toString(*s) + ", referenced from " +
392                 toString(isec->file));
393         else
394           target->prepareSymbolRelocation(s, isec, r);
395       } else {
396         assert(r.referent.is<InputSection *>());
397         if (!r.pcrel)
398           in.rebase->addEntry(isec, r.offset);
399       }
400     }
401   }
402 }
403 
404 void Writer::createLoadCommands() {
405   in.header->addLoadCommand(make<LCDyldInfo>(
406       in.rebase, in.binding, in.weakBinding, in.lazyBinding, in.exports));
407   in.header->addLoadCommand(make<LCSymtab>(symtabSection, stringTableSection));
408   in.header->addLoadCommand(
409       make<LCDysymtab>(symtabSection, indirectSymtabSection));
410   for (StringRef path : config->runtimePaths)
411     in.header->addLoadCommand(make<LCRPath>(path));
412 
413   switch (config->outputType) {
414   case MH_EXECUTE:
415     in.header->addLoadCommand(make<LCMain>());
416     in.header->addLoadCommand(make<LCLoadDylinker>());
417     break;
418   case MH_DYLIB:
419     in.header->addLoadCommand(make<LCDylib>(LC_ID_DYLIB, config->installName));
420     break;
421   case MH_BUNDLE:
422     break;
423   default:
424     llvm_unreachable("unhandled output file type");
425   }
426 
427   in.header->addLoadCommand(make<LCBuildVersion>(config->platform));
428 
429   uuidCommand = make<LCUuid>();
430   in.header->addLoadCommand(uuidCommand);
431 
432   uint8_t segIndex = 0;
433   for (OutputSegment *seg : outputSegments) {
434     in.header->addLoadCommand(make<LCSegment>(seg->name, seg));
435     seg->index = segIndex++;
436   }
437 
438   uint64_t dylibOrdinal = 1;
439   for (InputFile *file : inputFiles) {
440     if (auto *dylibFile = dyn_cast<DylibFile>(file)) {
441       // TODO: dylibs that are only referenced by weak refs should also be
442       // loaded via LC_LOAD_WEAK_DYLIB.
443       LoadCommandType lcType =
444           dylibFile->forceWeakImport ? LC_LOAD_WEAK_DYLIB : LC_LOAD_DYLIB;
445       in.header->addLoadCommand(make<LCDylib>(lcType, dylibFile->dylibName));
446       dylibFile->ordinal = dylibOrdinal++;
447 
448       if (dylibFile->reexport)
449         in.header->addLoadCommand(
450             make<LCDylib>(LC_REEXPORT_DYLIB, dylibFile->dylibName));
451     }
452   }
453 
454   const uint32_t MACOS_MAXPATHLEN = 1024;
455   config->headerPad = std::max(
456       config->headerPad, (config->headerPadMaxInstallNames
457                               ? LCDylib::getInstanceCount() * MACOS_MAXPATHLEN
458                               : 0));
459 }
460 
461 static size_t getSymbolPriority(const SymbolPriorityEntry &entry,
462                                 const InputFile &file) {
463   return std::max(entry.objectFiles.lookup(sys::path::filename(file.getName())),
464                   entry.anyObjectFile);
465 }
466 
467 // Each section gets assigned the priority of the highest-priority symbol it
468 // contains.
469 static DenseMap<const InputSection *, size_t> buildInputSectionPriorities() {
470   DenseMap<const InputSection *, size_t> sectionPriorities;
471 
472   if (config->priorities.empty())
473     return sectionPriorities;
474 
475   auto addSym = [&](Defined &sym) {
476     auto it = config->priorities.find(sym.getName());
477     if (it == config->priorities.end())
478       return;
479 
480     SymbolPriorityEntry &entry = it->second;
481     size_t &priority = sectionPriorities[sym.isec];
482     priority = std::max(priority, getSymbolPriority(entry, *sym.isec->file));
483   };
484 
485   // TODO: Make sure this handles weak symbols correctly.
486   for (InputFile *file : inputFiles)
487     if (isa<ObjFile>(file) || isa<ArchiveFile>(file))
488       for (lld::macho::Symbol *sym : file->symbols)
489         if (auto *d = dyn_cast<Defined>(sym))
490           addSym(*d);
491 
492   return sectionPriorities;
493 }
494 
495 static int segmentOrder(OutputSegment *seg) {
496   return StringSwitch<int>(seg->name)
497       .Case(segment_names::pageZero, -2)
498       .Case(segment_names::text, -1)
499       // Make sure __LINKEDIT is the last segment (i.e. all its hidden
500       // sections must be ordered after other sections).
501       .Case(segment_names::linkEdit, std::numeric_limits<int>::max())
502       .Default(0);
503 }
504 
505 static int sectionOrder(OutputSection *osec) {
506   StringRef segname = osec->parent->name;
507   // Sections are uniquely identified by their segment + section name.
508   if (segname == segment_names::text) {
509     return StringSwitch<int>(osec->name)
510         .Case(section_names::header, -1)
511         .Case(section_names::unwindInfo, std::numeric_limits<int>::max() - 1)
512         .Case(section_names::ehFrame, std::numeric_limits<int>::max())
513         .Default(0);
514   } else if (segname == segment_names::linkEdit) {
515     return StringSwitch<int>(osec->name)
516         .Case(section_names::rebase, -8)
517         .Case(section_names::binding, -7)
518         .Case(section_names::weakBinding, -6)
519         .Case(section_names::lazyBinding, -5)
520         .Case(section_names::export_, -4)
521         .Case(section_names::symbolTable, -3)
522         .Case(section_names::indirectSymbolTable, -2)
523         .Case(section_names::stringTable, -1)
524         .Default(0);
525   }
526   // ZeroFill sections must always be the at the end of their segments,
527   // otherwise subsequent sections may get overwritten with zeroes at runtime.
528   if (isZeroFill(osec->flags))
529     return std::numeric_limits<int>::max();
530   return 0;
531 }
532 
533 template <typename T, typename F>
534 static std::function<bool(T, T)> compareByOrder(F ord) {
535   return [=](T a, T b) { return ord(a) < ord(b); };
536 }
537 
538 // Sorting only can happen once all outputs have been collected. Here we sort
539 // segments, output sections within each segment, and input sections within each
540 // output segment.
541 static void sortSegmentsAndSections() {
542   llvm::stable_sort(outputSegments,
543                     compareByOrder<OutputSegment *>(segmentOrder));
544 
545   DenseMap<const InputSection *, size_t> isecPriorities =
546       buildInputSectionPriorities();
547 
548   uint32_t sectionIndex = 0;
549   for (OutputSegment *seg : outputSegments) {
550     seg->sortOutputSections(compareByOrder<OutputSection *>(sectionOrder));
551     for (auto *osec : seg->getSections()) {
552       // Now that the output sections are sorted, assign the final
553       // output section indices.
554       if (!osec->isHidden())
555         osec->index = ++sectionIndex;
556 
557       if (!isecPriorities.empty()) {
558         if (auto *merged = dyn_cast<MergedOutputSection>(osec)) {
559           llvm::stable_sort(merged->inputs,
560                             [&](InputSection *a, InputSection *b) {
561                               return isecPriorities[a] > isecPriorities[b];
562                             });
563         }
564       }
565     }
566   }
567 }
568 
569 void Writer::createOutputSections() {
570   // First, create hidden sections
571   stringTableSection = make<StringTableSection>();
572   unwindInfoSection = make<UnwindInfoSection>(); // TODO(gkm): only when no -r
573   symtabSection = make<SymtabSection>(*stringTableSection);
574   indirectSymtabSection = make<IndirectSymtabSection>();
575 
576   switch (config->outputType) {
577   case MH_EXECUTE:
578     make<PageZeroSection>();
579     break;
580   case MH_DYLIB:
581   case MH_BUNDLE:
582     break;
583   default:
584     llvm_unreachable("unhandled output file type");
585   }
586 
587   // Then merge input sections into output sections.
588   MapVector<std::pair<StringRef, StringRef>, MergedOutputSection *>
589       mergedOutputSections;
590   for (InputSection *isec : inputSections) {
591     // Instead of emitting DWARF sections, we emit STABS symbols to the object
592     // files that contain them.
593     if (isDebugSection(isec->flags) && isec->segname == segment_names::dwarf)
594       continue;
595     MergedOutputSection *&osec =
596         mergedOutputSections[{isec->segname, isec->name}];
597     if (osec == nullptr)
598       osec = make<MergedOutputSection>(isec->name);
599     osec->mergeInput(isec);
600   }
601 
602   for (const auto &it : mergedOutputSections) {
603     StringRef segname = it.first.first;
604     MergedOutputSection *osec = it.second;
605     if (unwindInfoSection && segname == segment_names::ld) {
606       assert(osec->name == section_names::compactUnwind);
607       unwindInfoSection->setCompactUnwindSection(osec);
608     } else {
609       getOrCreateOutputSegment(segname)->addOutputSection(osec);
610     }
611   }
612 
613   for (SyntheticSection *ssec : syntheticSections) {
614     auto it = mergedOutputSections.find({ssec->segname, ssec->name});
615     if (it == mergedOutputSections.end()) {
616       if (ssec->isNeeded())
617         getOrCreateOutputSegment(ssec->segname)->addOutputSection(ssec);
618     } else {
619       error("section from " + toString(it->second->firstSection()->file) +
620             " conflicts with synthetic section " + ssec->segname + "," +
621             ssec->name);
622     }
623   }
624 }
625 
626 void Writer::assignAddresses(OutputSegment *seg) {
627   addr = alignTo(addr, PageSize);
628   fileOff = alignTo(fileOff, PageSize);
629   seg->fileOff = fileOff;
630 
631   for (auto *osec : seg->getSections()) {
632     if (!osec->isNeeded())
633       continue;
634     addr = alignTo(addr, osec->align);
635     fileOff = alignTo(fileOff, osec->align);
636     osec->addr = addr;
637     osec->fileOff = isZeroFill(osec->flags) ? 0 : fileOff;
638     osec->finalize();
639 
640     addr += osec->getSize();
641     fileOff += osec->getFileSize();
642   }
643 }
644 
645 void Writer::openFile() {
646   Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr =
647       FileOutputBuffer::create(config->outputFile, fileOff,
648                                FileOutputBuffer::F_executable);
649 
650   if (!bufferOrErr)
651     error("failed to open " + config->outputFile + ": " +
652           llvm::toString(bufferOrErr.takeError()));
653   else
654     buffer = std::move(*bufferOrErr);
655 }
656 
657 void Writer::writeSections() {
658   uint8_t *buf = buffer->getBufferStart();
659   for (OutputSegment *seg : outputSegments)
660     for (OutputSection *osec : seg->getSections())
661       osec->writeTo(buf + osec->fileOff);
662 }
663 
664 void Writer::writeUuid() {
665   MD5 hash;
666   const auto *bufStart = reinterpret_cast<char *>(buffer->getBufferStart());
667   const auto *bufEnd = reinterpret_cast<char *>(buffer->getBufferEnd());
668   hash.update(StringRef(bufStart, bufEnd - bufStart));
669   MD5::MD5Result result;
670   hash.final(result);
671   // Conform to UUID version 4 & 5 as specified in RFC 4122:
672   // 1. Set the version field to indicate that this is an MD5-based UUID.
673   result.Bytes[6] = (result.Bytes[6] & 0xf) | 0x30;
674   // 2. Set the two MSBs of uuid_t::clock_seq_hi_and_reserved to zero and one.
675   result.Bytes[8] = (result.Bytes[8] & 0x3f) | 0x80;
676   uuidCommand->writeUuid(result.Bytes);
677 }
678 
679 void Writer::run() {
680   // dyld requires __LINKEDIT segment to always exist (even if empty).
681   OutputSegment *linkEditSegment =
682       getOrCreateOutputSegment(segment_names::linkEdit);
683 
684   prepareBranchTarget(config->entry);
685   scanRelocations();
686   if (in.stubHelper->isNeeded())
687     in.stubHelper->setup();
688 
689   for (const macho::Symbol *sym : symtab->getSymbols())
690     if (const auto *defined = dyn_cast<Defined>(sym))
691       if (defined->overridesWeakDef)
692         in.weakBinding->addNonWeakDefinition(defined);
693 
694   // Sort and assign sections to their respective segments. No more sections nor
695   // segments may be created after these methods run.
696   createOutputSections();
697   sortSegmentsAndSections();
698 
699   createLoadCommands();
700 
701   // Ensure that segments (and the sections they contain) are allocated
702   // addresses in ascending order, which dyld requires.
703   //
704   // Note that at this point, __LINKEDIT sections are empty, but we need to
705   // determine addresses of other segments/sections before generating its
706   // contents.
707   for (OutputSegment *seg : outputSegments)
708     if (seg != linkEditSegment)
709       assignAddresses(seg);
710 
711   // Fill __LINKEDIT contents.
712   in.rebase->finalizeContents();
713   in.binding->finalizeContents();
714   in.weakBinding->finalizeContents();
715   in.lazyBinding->finalizeContents();
716   in.exports->finalizeContents();
717   symtabSection->finalizeContents();
718   indirectSymtabSection->finalizeContents();
719 
720   // Now that __LINKEDIT is filled out, do a proper calculation of its
721   // addresses and offsets.
722   assignAddresses(linkEditSegment);
723 
724   openFile();
725   if (errorCount())
726     return;
727 
728   writeSections();
729   writeUuid();
730 
731   if (auto e = buffer->commit())
732     error("failed to write to the output file: " + toString(std::move(e)));
733 }
734 
735 void macho::writeResult() { Writer().run(); }
736 
737 void macho::createSyntheticSections() {
738   in.header = make<MachHeaderSection>();
739   in.rebase = make<RebaseSection>();
740   in.binding = make<BindingSection>();
741   in.weakBinding = make<WeakBindingSection>();
742   in.lazyBinding = make<LazyBindingSection>();
743   in.exports = make<ExportSection>();
744   in.got = make<GotSection>();
745   in.tlvPointers = make<TlvPointerSection>();
746   in.lazyPointers = make<LazyPointerSection>();
747   in.stubs = make<StubsSection>();
748   in.stubHelper = make<StubHelperSection>();
749   in.imageLoaderCache = make<ImageLoaderCacheSection>();
750 }
751