xref: /llvm-project-15.0.7/lld/MachO/Writer.cpp (revision d1da3462)
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,
246           uint32_t compatibilityVersion = 0, uint32_t currentVersion = 0)
247       : type(type), path(path), compatibilityVersion(compatibilityVersion),
248         currentVersion(currentVersion) {
249     instanceCount++;
250   }
251 
252   uint32_t getSize() const override {
253     return alignTo(sizeof(dylib_command) + path.size() + 1, 8);
254   }
255 
256   void writeTo(uint8_t *buf) const override {
257     auto *c = reinterpret_cast<dylib_command *>(buf);
258     buf += sizeof(dylib_command);
259 
260     c->cmd = type;
261     c->cmdsize = getSize();
262     c->dylib.name = sizeof(dylib_command);
263     c->dylib.timestamp = 0;
264     c->dylib.compatibility_version = compatibilityVersion;
265     c->dylib.current_version = currentVersion;
266 
267     memcpy(buf, path.data(), path.size());
268     buf[path.size()] = '\0';
269   }
270 
271   static uint32_t getInstanceCount() { return instanceCount; }
272 
273 private:
274   LoadCommandType type;
275   StringRef path;
276   uint32_t compatibilityVersion;
277   uint32_t currentVersion;
278   static uint32_t instanceCount;
279 };
280 
281 uint32_t LCDylib::instanceCount = 0;
282 
283 class LCLoadDylinker : public LoadCommand {
284 public:
285   uint32_t getSize() const override {
286     return alignTo(sizeof(dylinker_command) + path.size() + 1, 8);
287   }
288 
289   void writeTo(uint8_t *buf) const override {
290     auto *c = reinterpret_cast<dylinker_command *>(buf);
291     buf += sizeof(dylinker_command);
292 
293     c->cmd = LC_LOAD_DYLINKER;
294     c->cmdsize = getSize();
295     c->name = sizeof(dylinker_command);
296 
297     memcpy(buf, path.data(), path.size());
298     buf[path.size()] = '\0';
299   }
300 
301 private:
302   // Recent versions of Darwin won't run any binary that has dyld at a
303   // different location.
304   const StringRef path = "/usr/lib/dyld";
305 };
306 
307 class LCRPath : public LoadCommand {
308 public:
309   LCRPath(StringRef path) : path(path) {}
310 
311   uint32_t getSize() const override {
312     return alignTo(sizeof(rpath_command) + path.size() + 1, WordSize);
313   }
314 
315   void writeTo(uint8_t *buf) const override {
316     auto *c = reinterpret_cast<rpath_command *>(buf);
317     buf += sizeof(rpath_command);
318 
319     c->cmd = LC_RPATH;
320     c->cmdsize = getSize();
321     c->path = sizeof(rpath_command);
322 
323     memcpy(buf, path.data(), path.size());
324     buf[path.size()] = '\0';
325   }
326 
327 private:
328   StringRef path;
329 };
330 
331 class LCBuildVersion : public LoadCommand {
332 public:
333   LCBuildVersion(const PlatformInfo &platform) : platform(platform) {}
334 
335   const int ntools = 1;
336 
337   uint32_t getSize() const override {
338     return sizeof(build_version_command) + ntools * sizeof(build_tool_version);
339   }
340 
341   void writeTo(uint8_t *buf) const override {
342     auto *c = reinterpret_cast<build_version_command *>(buf);
343     c->cmd = LC_BUILD_VERSION;
344     c->cmdsize = getSize();
345     c->platform = static_cast<uint32_t>(platform.kind);
346     c->minos = ((platform.minimum.getMajor() << 020) |
347                 (platform.minimum.getMinor().getValueOr(0) << 010) |
348                 platform.minimum.getSubminor().getValueOr(0));
349     c->sdk = ((platform.sdk.getMajor() << 020) |
350               (platform.sdk.getMinor().getValueOr(0) << 010) |
351               platform.sdk.getSubminor().getValueOr(0));
352     c->ntools = ntools;
353     auto *t = reinterpret_cast<build_tool_version *>(&c[1]);
354     t->tool = TOOL_LD;
355     t->version = (LLVM_VERSION_MAJOR << 020) | (LLVM_VERSION_MINOR << 010) |
356                  LLVM_VERSION_PATCH;
357   }
358 
359   const PlatformInfo &platform;
360 };
361 
362 // Stores a unique identifier for the output file based on an MD5 hash of its
363 // contents. In order to hash the contents, we must first write them, but
364 // LC_UUID itself must be part of the written contents in order for all the
365 // offsets to be calculated correctly. We resolve this circular paradox by
366 // first writing an LC_UUID with an all-zero UUID, then updating the UUID with
367 // its real value later.
368 class LCUuid : public LoadCommand {
369 public:
370   uint32_t getSize() const override { return sizeof(uuid_command); }
371 
372   void writeTo(uint8_t *buf) const override {
373     auto *c = reinterpret_cast<uuid_command *>(buf);
374     c->cmd = LC_UUID;
375     c->cmdsize = getSize();
376     uuidBuf = c->uuid;
377   }
378 
379   void writeUuid(uint64_t digest) const {
380     // xxhash only gives us 8 bytes, so put some fixed data in the other half.
381     static_assert(sizeof(uuid_command::uuid) == 16, "unexpected uuid size");
382     memcpy(uuidBuf, "LLD\xa1UU1D", 8);
383     memcpy(uuidBuf + 8, &digest, 8);
384 
385     // RFC 4122 conformance. We need to fix 4 bits in byte 6 and 2 bits in
386     // byte 8. Byte 6 is already fine due to the fixed data we put in. We don't
387     // want to lose bits of the digest in byte 8, so swap that with a byte of
388     // fixed data that happens to have the right bits set.
389     std::swap(uuidBuf[3], uuidBuf[8]);
390 
391     // Claim that this is an MD5-based hash. It isn't, but this signals that
392     // this is not a time-based and not a random hash. MD5 seems like the least
393     // bad lie we can put here.
394     assert((uuidBuf[6] & 0xf0) == 0x30 && "See RFC 4122 Sections 4.2.2, 4.1.3");
395     assert((uuidBuf[8] & 0xc0) == 0x80 && "See RFC 4122 Section 4.2.2");
396   }
397 
398   mutable uint8_t *uuidBuf;
399 };
400 
401 } // namespace
402 
403 void Writer::scanRelocations() {
404   for (InputSection *isec : inputSections) {
405     // We do not wish to add rebase opcodes for __LD,__compact_unwind, because
406     // it doesn't actually end up in the final binary. TODO: filtering it out
407     // before Writer runs might be cleaner...
408     if (isec->segname == segment_names::ld)
409       continue;
410 
411     for (Reloc &r : isec->relocs) {
412       if (auto *s = r.referent.dyn_cast<lld::macho::Symbol *>()) {
413         if (isa<Undefined>(s))
414           error("undefined symbol " + toString(*s) + ", referenced from " +
415                 toString(isec->file));
416         else
417           target->prepareSymbolRelocation(s, isec, r);
418       } else {
419         assert(r.referent.is<InputSection *>());
420         if (!r.pcrel)
421           in.rebase->addEntry(isec, r.offset);
422       }
423     }
424   }
425 }
426 
427 void Writer::createLoadCommands() {
428   in.header->addLoadCommand(make<LCDyldInfo>(
429       in.rebase, in.binding, in.weakBinding, in.lazyBinding, in.exports));
430   in.header->addLoadCommand(make<LCSymtab>(symtabSection, stringTableSection));
431   in.header->addLoadCommand(
432       make<LCDysymtab>(symtabSection, indirectSymtabSection));
433   for (StringRef path : config->runtimePaths)
434     in.header->addLoadCommand(make<LCRPath>(path));
435 
436   switch (config->outputType) {
437   case MH_EXECUTE:
438     in.header->addLoadCommand(make<LCMain>());
439     in.header->addLoadCommand(make<LCLoadDylinker>());
440     break;
441   case MH_DYLIB:
442     in.header->addLoadCommand(make<LCDylib>(LC_ID_DYLIB, config->installName,
443                                             config->dylibCompatibilityVersion,
444                                             config->dylibCurrentVersion));
445     break;
446   case MH_BUNDLE:
447     break;
448   default:
449     llvm_unreachable("unhandled output file type");
450   }
451 
452   in.header->addLoadCommand(make<LCBuildVersion>(config->platform));
453 
454   uuidCommand = make<LCUuid>();
455   in.header->addLoadCommand(uuidCommand);
456 
457   uint8_t segIndex = 0;
458   for (OutputSegment *seg : outputSegments) {
459     in.header->addLoadCommand(make<LCSegment>(seg->name, seg));
460     seg->index = segIndex++;
461   }
462 
463   uint64_t dylibOrdinal = 1;
464   for (InputFile *file : inputFiles) {
465     if (auto *dylibFile = dyn_cast<DylibFile>(file)) {
466       // TODO: dylibs that are only referenced by weak refs should also be
467       // loaded via LC_LOAD_WEAK_DYLIB.
468       LoadCommandType lcType =
469           dylibFile->forceWeakImport ? LC_LOAD_WEAK_DYLIB : LC_LOAD_DYLIB;
470       in.header->addLoadCommand(make<LCDylib>(lcType, dylibFile->dylibName));
471       dylibFile->ordinal = dylibOrdinal++;
472 
473       if (dylibFile->reexport)
474         in.header->addLoadCommand(
475             make<LCDylib>(LC_REEXPORT_DYLIB, dylibFile->dylibName));
476     }
477   }
478 
479   const uint32_t MACOS_MAXPATHLEN = 1024;
480   config->headerPad = std::max(
481       config->headerPad, (config->headerPadMaxInstallNames
482                               ? LCDylib::getInstanceCount() * MACOS_MAXPATHLEN
483                               : 0));
484 }
485 
486 static size_t getSymbolPriority(const SymbolPriorityEntry &entry,
487                                 const InputFile &file) {
488   return std::max(entry.objectFiles.lookup(sys::path::filename(file.getName())),
489                   entry.anyObjectFile);
490 }
491 
492 // Each section gets assigned the priority of the highest-priority symbol it
493 // contains.
494 static DenseMap<const InputSection *, size_t> buildInputSectionPriorities() {
495   DenseMap<const InputSection *, size_t> sectionPriorities;
496 
497   if (config->priorities.empty())
498     return sectionPriorities;
499 
500   auto addSym = [&](Defined &sym) {
501     auto it = config->priorities.find(sym.getName());
502     if (it == config->priorities.end())
503       return;
504 
505     SymbolPriorityEntry &entry = it->second;
506     size_t &priority = sectionPriorities[sym.isec];
507     priority = std::max(priority, getSymbolPriority(entry, *sym.isec->file));
508   };
509 
510   // TODO: Make sure this handles weak symbols correctly.
511   for (InputFile *file : inputFiles)
512     if (isa<ObjFile>(file) || isa<ArchiveFile>(file))
513       for (lld::macho::Symbol *sym : file->symbols)
514         if (auto *d = dyn_cast<Defined>(sym))
515           addSym(*d);
516 
517   return sectionPriorities;
518 }
519 
520 static int segmentOrder(OutputSegment *seg) {
521   return StringSwitch<int>(seg->name)
522       .Case(segment_names::pageZero, -2)
523       .Case(segment_names::text, -1)
524       // Make sure __LINKEDIT is the last segment (i.e. all its hidden
525       // sections must be ordered after other sections).
526       .Case(segment_names::linkEdit, std::numeric_limits<int>::max())
527       .Default(0);
528 }
529 
530 static int sectionOrder(OutputSection *osec) {
531   StringRef segname = osec->parent->name;
532   // Sections are uniquely identified by their segment + section name.
533   if (segname == segment_names::text) {
534     return StringSwitch<int>(osec->name)
535         .Case(section_names::header, -1)
536         .Case(section_names::unwindInfo, std::numeric_limits<int>::max() - 1)
537         .Case(section_names::ehFrame, std::numeric_limits<int>::max())
538         .Default(0);
539   } else if (segname == segment_names::linkEdit) {
540     return StringSwitch<int>(osec->name)
541         .Case(section_names::rebase, -8)
542         .Case(section_names::binding, -7)
543         .Case(section_names::weakBinding, -6)
544         .Case(section_names::lazyBinding, -5)
545         .Case(section_names::export_, -4)
546         .Case(section_names::symbolTable, -3)
547         .Case(section_names::indirectSymbolTable, -2)
548         .Case(section_names::stringTable, -1)
549         .Default(0);
550   }
551   // ZeroFill sections must always be the at the end of their segments,
552   // otherwise subsequent sections may get overwritten with zeroes at runtime.
553   if (isZeroFill(osec->flags))
554     return std::numeric_limits<int>::max();
555   return 0;
556 }
557 
558 template <typename T, typename F>
559 static std::function<bool(T, T)> compareByOrder(F ord) {
560   return [=](T a, T b) { return ord(a) < ord(b); };
561 }
562 
563 // Sorting only can happen once all outputs have been collected. Here we sort
564 // segments, output sections within each segment, and input sections within each
565 // output segment.
566 static void sortSegmentsAndSections() {
567   llvm::stable_sort(outputSegments,
568                     compareByOrder<OutputSegment *>(segmentOrder));
569 
570   DenseMap<const InputSection *, size_t> isecPriorities =
571       buildInputSectionPriorities();
572 
573   uint32_t sectionIndex = 0;
574   for (OutputSegment *seg : outputSegments) {
575     seg->sortOutputSections(compareByOrder<OutputSection *>(sectionOrder));
576     for (auto *osec : seg->getSections()) {
577       // Now that the output sections are sorted, assign the final
578       // output section indices.
579       if (!osec->isHidden())
580         osec->index = ++sectionIndex;
581 
582       if (!isecPriorities.empty()) {
583         if (auto *merged = dyn_cast<MergedOutputSection>(osec)) {
584           llvm::stable_sort(merged->inputs,
585                             [&](InputSection *a, InputSection *b) {
586                               return isecPriorities[a] > isecPriorities[b];
587                             });
588         }
589       }
590     }
591   }
592 }
593 
594 void Writer::createOutputSections() {
595   // First, create hidden sections
596   stringTableSection = make<StringTableSection>();
597   unwindInfoSection = make<UnwindInfoSection>(); // TODO(gkm): only when no -r
598   symtabSection = make<SymtabSection>(*stringTableSection);
599   indirectSymtabSection = make<IndirectSymtabSection>();
600 
601   switch (config->outputType) {
602   case MH_EXECUTE:
603     make<PageZeroSection>();
604     break;
605   case MH_DYLIB:
606   case MH_BUNDLE:
607     break;
608   default:
609     llvm_unreachable("unhandled output file type");
610   }
611 
612   // Then merge input sections into output sections.
613   MapVector<std::pair<StringRef, StringRef>, MergedOutputSection *>
614       mergedOutputSections;
615   for (InputSection *isec : inputSections) {
616     MergedOutputSection *&osec =
617         mergedOutputSections[{isec->segname, isec->name}];
618     if (osec == nullptr)
619       osec = make<MergedOutputSection>(isec->name);
620     osec->mergeInput(isec);
621   }
622 
623   for (const auto &it : mergedOutputSections) {
624     StringRef segname = it.first.first;
625     MergedOutputSection *osec = it.second;
626     if (unwindInfoSection && segname == segment_names::ld) {
627       assert(osec->name == section_names::compactUnwind);
628       unwindInfoSection->setCompactUnwindSection(osec);
629     } else {
630       getOrCreateOutputSegment(segname)->addOutputSection(osec);
631     }
632   }
633 
634   for (SyntheticSection *ssec : syntheticSections) {
635     auto it = mergedOutputSections.find({ssec->segname, ssec->name});
636     if (it == mergedOutputSections.end()) {
637       if (ssec->isNeeded())
638         getOrCreateOutputSegment(ssec->segname)->addOutputSection(ssec);
639     } else {
640       error("section from " + toString(it->second->firstSection()->file) +
641             " conflicts with synthetic section " + ssec->segname + "," +
642             ssec->name);
643     }
644   }
645 }
646 
647 void Writer::assignAddresses(OutputSegment *seg) {
648   addr = alignTo(addr, PageSize);
649   fileOff = alignTo(fileOff, PageSize);
650   seg->fileOff = fileOff;
651 
652   for (auto *osec : seg->getSections()) {
653     if (!osec->isNeeded())
654       continue;
655     addr = alignTo(addr, osec->align);
656     fileOff = alignTo(fileOff, osec->align);
657     osec->addr = addr;
658     osec->fileOff = isZeroFill(osec->flags) ? 0 : fileOff;
659     osec->finalize();
660 
661     addr += osec->getSize();
662     fileOff += osec->getFileSize();
663   }
664 }
665 
666 void Writer::openFile() {
667   Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr =
668       FileOutputBuffer::create(config->outputFile, fileOff,
669                                FileOutputBuffer::F_executable);
670 
671   if (!bufferOrErr)
672     error("failed to open " + config->outputFile + ": " +
673           llvm::toString(bufferOrErr.takeError()));
674   else
675     buffer = std::move(*bufferOrErr);
676 }
677 
678 void Writer::writeSections() {
679   uint8_t *buf = buffer->getBufferStart();
680   for (OutputSegment *seg : outputSegments)
681     for (OutputSection *osec : seg->getSections())
682       osec->writeTo(buf + osec->fileOff);
683 }
684 
685 void Writer::writeUuid() {
686   uint64_t digest =
687       xxHash64({buffer->getBufferStart(), buffer->getBufferEnd()});
688   uuidCommand->writeUuid(digest);
689 }
690 
691 void Writer::run() {
692   // dyld requires __LINKEDIT segment to always exist (even if empty).
693   OutputSegment *linkEditSegment =
694       getOrCreateOutputSegment(segment_names::linkEdit);
695 
696   prepareBranchTarget(config->entry);
697   scanRelocations();
698   if (in.stubHelper->isNeeded())
699     in.stubHelper->setup();
700 
701   for (const macho::Symbol *sym : symtab->getSymbols())
702     if (const auto *defined = dyn_cast<Defined>(sym))
703       if (defined->overridesWeakDef)
704         in.weakBinding->addNonWeakDefinition(defined);
705 
706   // Sort and assign sections to their respective segments. No more sections nor
707   // segments may be created after these methods run.
708   createOutputSections();
709   sortSegmentsAndSections();
710 
711   createLoadCommands();
712 
713   // Ensure that segments (and the sections they contain) are allocated
714   // addresses in ascending order, which dyld requires.
715   //
716   // Note that at this point, __LINKEDIT sections are empty, but we need to
717   // determine addresses of other segments/sections before generating its
718   // contents.
719   for (OutputSegment *seg : outputSegments)
720     if (seg != linkEditSegment)
721       assignAddresses(seg);
722 
723   // Fill __LINKEDIT contents.
724   in.rebase->finalizeContents();
725   in.binding->finalizeContents();
726   in.weakBinding->finalizeContents();
727   in.lazyBinding->finalizeContents();
728   in.exports->finalizeContents();
729   symtabSection->finalizeContents();
730   indirectSymtabSection->finalizeContents();
731 
732   // Now that __LINKEDIT is filled out, do a proper calculation of its
733   // addresses and offsets.
734   assignAddresses(linkEditSegment);
735 
736   openFile();
737   if (errorCount())
738     return;
739 
740   writeSections();
741   writeUuid();
742 
743   if (auto e = buffer->commit())
744     error("failed to write to the output file: " + toString(std::move(e)));
745 }
746 
747 void macho::writeResult() { Writer().run(); }
748 
749 void macho::createSyntheticSections() {
750   in.header = make<MachHeaderSection>();
751   in.rebase = make<RebaseSection>();
752   in.binding = make<BindingSection>();
753   in.weakBinding = make<WeakBindingSection>();
754   in.lazyBinding = make<LazyBindingSection>();
755   in.exports = make<ExportSection>();
756   in.got = make<GotSection>();
757   in.tlvPointers = make<TlvPointerSection>();
758   in.lazyPointers = make<LazyPointerSection>();
759   in.stubs = make<StubsSection>();
760   in.stubHelper = make<StubHelperSection>();
761   in.imageLoaderCache = make<ImageLoaderCacheSection>();
762 }
763