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