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