xref: /llvm-project-15.0.7/lld/MachO/Writer.cpp (revision 3bc88eb3)
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 "MapFile.h"
14 #include "MergedOutputSection.h"
15 #include "OutputSection.h"
16 #include "OutputSegment.h"
17 #include "SymbolTable.h"
18 #include "Symbols.h"
19 #include "SyntheticSections.h"
20 #include "Target.h"
21 #include "UnwindInfoSection.h"
22 
23 #include "lld/Common/Arrays.h"
24 #include "lld/Common/ErrorHandler.h"
25 #include "lld/Common/Memory.h"
26 #include "llvm/BinaryFormat/MachO.h"
27 #include "llvm/Config/llvm-config.h"
28 #include "llvm/Support/LEB128.h"
29 #include "llvm/Support/MathExtras.h"
30 #include "llvm/Support/Parallel.h"
31 #include "llvm/Support/Path.h"
32 #include "llvm/Support/TimeProfiler.h"
33 #include "llvm/Support/xxhash.h"
34 
35 #include <algorithm>
36 
37 using namespace llvm;
38 using namespace llvm::MachO;
39 using namespace llvm::sys;
40 using namespace lld;
41 using namespace lld::macho;
42 
43 namespace {
44 class LCUuid;
45 
46 class Writer {
47 public:
48   Writer() : buffer(errorHandler().outputBuffer) {}
49 
50   void scanRelocations();
51   void scanSymbols();
52   template <class LP> void createOutputSections();
53   template <class LP> void createLoadCommands();
54   void finalizeAddresses();
55   void finalizeLinkEditSegment();
56   void assignAddresses(OutputSegment *);
57 
58   void openFile();
59   void writeSections();
60   void writeUuid();
61   void writeCodeSignature();
62   void writeOutputFile();
63 
64   template <class LP> void run();
65 
66   std::unique_ptr<FileOutputBuffer> &buffer;
67   uint64_t addr = 0;
68   uint64_t fileOff = 0;
69   MachHeaderSection *header = nullptr;
70   StringTableSection *stringTableSection = nullptr;
71   SymtabSection *symtabSection = nullptr;
72   IndirectSymtabSection *indirectSymtabSection = nullptr;
73   CodeSignatureSection *codeSignatureSection = nullptr;
74   UnwindInfoSection *unwindInfoSection = nullptr;
75   FunctionStartsSection *functionStartsSection = nullptr;
76 
77   LCUuid *uuidCommand = nullptr;
78   OutputSegment *linkEditSegment = nullptr;
79 };
80 
81 // LC_DYLD_INFO_ONLY stores the offsets of symbol import/export information.
82 class LCDyldInfo : public LoadCommand {
83 public:
84   LCDyldInfo(RebaseSection *rebaseSection, BindingSection *bindingSection,
85              WeakBindingSection *weakBindingSection,
86              LazyBindingSection *lazyBindingSection,
87              ExportSection *exportSection)
88       : rebaseSection(rebaseSection), bindingSection(bindingSection),
89         weakBindingSection(weakBindingSection),
90         lazyBindingSection(lazyBindingSection), exportSection(exportSection) {}
91 
92   uint32_t getSize() const override { return sizeof(dyld_info_command); }
93 
94   void writeTo(uint8_t *buf) const override {
95     auto *c = reinterpret_cast<dyld_info_command *>(buf);
96     c->cmd = LC_DYLD_INFO_ONLY;
97     c->cmdsize = getSize();
98     if (rebaseSection->isNeeded()) {
99       c->rebase_off = rebaseSection->fileOff;
100       c->rebase_size = rebaseSection->getFileSize();
101     }
102     if (bindingSection->isNeeded()) {
103       c->bind_off = bindingSection->fileOff;
104       c->bind_size = bindingSection->getFileSize();
105     }
106     if (weakBindingSection->isNeeded()) {
107       c->weak_bind_off = weakBindingSection->fileOff;
108       c->weak_bind_size = weakBindingSection->getFileSize();
109     }
110     if (lazyBindingSection->isNeeded()) {
111       c->lazy_bind_off = lazyBindingSection->fileOff;
112       c->lazy_bind_size = lazyBindingSection->getFileSize();
113     }
114     if (exportSection->isNeeded()) {
115       c->export_off = exportSection->fileOff;
116       c->export_size = exportSection->getFileSize();
117     }
118   }
119 
120   RebaseSection *rebaseSection;
121   BindingSection *bindingSection;
122   WeakBindingSection *weakBindingSection;
123   LazyBindingSection *lazyBindingSection;
124   ExportSection *exportSection;
125 };
126 
127 class LCFunctionStarts : public LoadCommand {
128 public:
129   explicit LCFunctionStarts(FunctionStartsSection *functionStartsSection)
130       : functionStartsSection(functionStartsSection) {}
131 
132   uint32_t getSize() const override { return sizeof(linkedit_data_command); }
133 
134   void writeTo(uint8_t *buf) const override {
135     auto *c = reinterpret_cast<linkedit_data_command *>(buf);
136     c->cmd = LC_FUNCTION_STARTS;
137     c->cmdsize = getSize();
138     c->dataoff = functionStartsSection->fileOff;
139     c->datasize = functionStartsSection->getFileSize();
140   }
141 
142 private:
143   FunctionStartsSection *functionStartsSection;
144 };
145 
146 class LCDysymtab : public LoadCommand {
147 public:
148   LCDysymtab(SymtabSection *symtabSection,
149              IndirectSymtabSection *indirectSymtabSection)
150       : symtabSection(symtabSection),
151         indirectSymtabSection(indirectSymtabSection) {}
152 
153   uint32_t getSize() const override { return sizeof(dysymtab_command); }
154 
155   void writeTo(uint8_t *buf) const override {
156     auto *c = reinterpret_cast<dysymtab_command *>(buf);
157     c->cmd = LC_DYSYMTAB;
158     c->cmdsize = getSize();
159 
160     c->ilocalsym = 0;
161     c->iextdefsym = c->nlocalsym = symtabSection->getNumLocalSymbols();
162     c->nextdefsym = symtabSection->getNumExternalSymbols();
163     c->iundefsym = c->iextdefsym + c->nextdefsym;
164     c->nundefsym = symtabSection->getNumUndefinedSymbols();
165 
166     c->indirectsymoff = indirectSymtabSection->fileOff;
167     c->nindirectsyms = indirectSymtabSection->getNumSymbols();
168   }
169 
170   SymtabSection *symtabSection;
171   IndirectSymtabSection *indirectSymtabSection;
172 };
173 
174 template <class LP> class LCSegment : public LoadCommand {
175 public:
176   LCSegment(StringRef name, OutputSegment *seg) : name(name), seg(seg) {}
177 
178   uint32_t getSize() const override {
179     return sizeof(typename LP::segment_command) +
180            seg->numNonHiddenSections() * sizeof(typename LP::section);
181   }
182 
183   void writeTo(uint8_t *buf) const override {
184     using SegmentCommand = typename LP::segment_command;
185     using Section = typename LP::section;
186 
187     auto *c = reinterpret_cast<SegmentCommand *>(buf);
188     buf += sizeof(SegmentCommand);
189 
190     c->cmd = LP::segmentLCType;
191     c->cmdsize = getSize();
192     memcpy(c->segname, name.data(), name.size());
193     c->fileoff = seg->fileOff;
194     c->maxprot = seg->maxProt;
195     c->initprot = seg->initProt;
196 
197     if (seg->getSections().empty())
198       return;
199 
200     c->vmaddr = seg->firstSection()->addr;
201     c->vmsize =
202         seg->lastSection()->addr + seg->lastSection()->getSize() - c->vmaddr;
203     c->nsects = seg->numNonHiddenSections();
204 
205     for (const OutputSection *osec : seg->getSections()) {
206       if (!isZeroFill(osec->flags)) {
207         assert(osec->fileOff >= seg->fileOff);
208         c->filesize = std::max<uint64_t>(
209             c->filesize, osec->fileOff + osec->getFileSize() - seg->fileOff);
210       }
211 
212       if (osec->isHidden())
213         continue;
214 
215       auto *sectHdr = reinterpret_cast<Section *>(buf);
216       buf += sizeof(Section);
217 
218       memcpy(sectHdr->sectname, osec->name.data(), osec->name.size());
219       memcpy(sectHdr->segname, name.data(), name.size());
220 
221       sectHdr->addr = osec->addr;
222       sectHdr->offset = osec->fileOff;
223       sectHdr->align = Log2_32(osec->align);
224       sectHdr->flags = osec->flags;
225       sectHdr->size = osec->getSize();
226       sectHdr->reserved1 = osec->reserved1;
227       sectHdr->reserved2 = osec->reserved2;
228     }
229   }
230 
231 private:
232   StringRef name;
233   OutputSegment *seg;
234 };
235 
236 class LCMain : public LoadCommand {
237   uint32_t getSize() const override {
238     return sizeof(structs::entry_point_command);
239   }
240 
241   void writeTo(uint8_t *buf) const override {
242     auto *c = reinterpret_cast<structs::entry_point_command *>(buf);
243     c->cmd = LC_MAIN;
244     c->cmdsize = getSize();
245 
246     if (config->entry->isInStubs())
247       c->entryoff =
248           in.stubs->fileOff + config->entry->stubsIndex * target->stubSize;
249     else
250       c->entryoff = config->entry->getFileOffset();
251 
252     c->stacksize = 0;
253   }
254 };
255 
256 class LCSymtab : public LoadCommand {
257 public:
258   LCSymtab(SymtabSection *symtabSection, StringTableSection *stringTableSection)
259       : symtabSection(symtabSection), stringTableSection(stringTableSection) {}
260 
261   uint32_t getSize() const override { return sizeof(symtab_command); }
262 
263   void writeTo(uint8_t *buf) const override {
264     auto *c = reinterpret_cast<symtab_command *>(buf);
265     c->cmd = LC_SYMTAB;
266     c->cmdsize = getSize();
267     c->symoff = symtabSection->fileOff;
268     c->nsyms = symtabSection->getNumSymbols();
269     c->stroff = stringTableSection->fileOff;
270     c->strsize = stringTableSection->getFileSize();
271   }
272 
273   SymtabSection *symtabSection = nullptr;
274   StringTableSection *stringTableSection = nullptr;
275 };
276 
277 // There are several dylib load commands that share the same structure:
278 //   * LC_LOAD_DYLIB
279 //   * LC_ID_DYLIB
280 //   * LC_REEXPORT_DYLIB
281 class LCDylib : public LoadCommand {
282 public:
283   LCDylib(LoadCommandType type, StringRef path,
284           uint32_t compatibilityVersion = 0, uint32_t currentVersion = 0)
285       : type(type), path(path), compatibilityVersion(compatibilityVersion),
286         currentVersion(currentVersion) {
287     instanceCount++;
288   }
289 
290   uint32_t getSize() const override {
291     return alignTo(sizeof(dylib_command) + path.size() + 1, 8);
292   }
293 
294   void writeTo(uint8_t *buf) const override {
295     auto *c = reinterpret_cast<dylib_command *>(buf);
296     buf += sizeof(dylib_command);
297 
298     c->cmd = type;
299     c->cmdsize = getSize();
300     c->dylib.name = sizeof(dylib_command);
301     c->dylib.timestamp = 0;
302     c->dylib.compatibility_version = compatibilityVersion;
303     c->dylib.current_version = currentVersion;
304 
305     memcpy(buf, path.data(), path.size());
306     buf[path.size()] = '\0';
307   }
308 
309   static uint32_t getInstanceCount() { return instanceCount; }
310 
311 private:
312   LoadCommandType type;
313   StringRef path;
314   uint32_t compatibilityVersion;
315   uint32_t currentVersion;
316   static uint32_t instanceCount;
317 };
318 
319 uint32_t LCDylib::instanceCount = 0;
320 
321 class LCLoadDylinker : public LoadCommand {
322 public:
323   uint32_t getSize() const override {
324     return alignTo(sizeof(dylinker_command) + path.size() + 1, 8);
325   }
326 
327   void writeTo(uint8_t *buf) const override {
328     auto *c = reinterpret_cast<dylinker_command *>(buf);
329     buf += sizeof(dylinker_command);
330 
331     c->cmd = LC_LOAD_DYLINKER;
332     c->cmdsize = getSize();
333     c->name = sizeof(dylinker_command);
334 
335     memcpy(buf, path.data(), path.size());
336     buf[path.size()] = '\0';
337   }
338 
339 private:
340   // Recent versions of Darwin won't run any binary that has dyld at a
341   // different location.
342   const StringRef path = "/usr/lib/dyld";
343 };
344 
345 class LCRPath : public LoadCommand {
346 public:
347   LCRPath(StringRef path) : path(path) {}
348 
349   uint32_t getSize() const override {
350     return alignTo(sizeof(rpath_command) + path.size() + 1, target->wordSize);
351   }
352 
353   void writeTo(uint8_t *buf) const override {
354     auto *c = reinterpret_cast<rpath_command *>(buf);
355     buf += sizeof(rpath_command);
356 
357     c->cmd = LC_RPATH;
358     c->cmdsize = getSize();
359     c->path = sizeof(rpath_command);
360 
361     memcpy(buf, path.data(), path.size());
362     buf[path.size()] = '\0';
363   }
364 
365 private:
366   StringRef path;
367 };
368 
369 class LCBuildVersion : public LoadCommand {
370 public:
371   LCBuildVersion(PlatformKind platform, const PlatformInfo &platformInfo)
372       : platform(platform), platformInfo(platformInfo) {}
373 
374   const int ntools = 1;
375 
376   uint32_t getSize() const override {
377     return sizeof(build_version_command) + ntools * sizeof(build_tool_version);
378   }
379 
380   void writeTo(uint8_t *buf) const override {
381     auto *c = reinterpret_cast<build_version_command *>(buf);
382     c->cmd = LC_BUILD_VERSION;
383     c->cmdsize = getSize();
384     c->platform = static_cast<uint32_t>(platform);
385     c->minos = ((platformInfo.minimum.getMajor() << 020) |
386                 (platformInfo.minimum.getMinor().getValueOr(0) << 010) |
387                 platformInfo.minimum.getSubminor().getValueOr(0));
388     c->sdk = ((platformInfo.sdk.getMajor() << 020) |
389               (platformInfo.sdk.getMinor().getValueOr(0) << 010) |
390               platformInfo.sdk.getSubminor().getValueOr(0));
391     c->ntools = ntools;
392     auto *t = reinterpret_cast<build_tool_version *>(&c[1]);
393     t->tool = TOOL_LD;
394     t->version = (LLVM_VERSION_MAJOR << 020) | (LLVM_VERSION_MINOR << 010) |
395                  LLVM_VERSION_PATCH;
396   }
397 
398   PlatformKind platform;
399   const PlatformInfo &platformInfo;
400 };
401 
402 // Stores a unique identifier for the output file based on an MD5 hash of its
403 // contents. In order to hash the contents, we must first write them, but
404 // LC_UUID itself must be part of the written contents in order for all the
405 // offsets to be calculated correctly. We resolve this circular paradox by
406 // first writing an LC_UUID with an all-zero UUID, then updating the UUID with
407 // its real value later.
408 class LCUuid : public LoadCommand {
409 public:
410   uint32_t getSize() const override { return sizeof(uuid_command); }
411 
412   void writeTo(uint8_t *buf) const override {
413     auto *c = reinterpret_cast<uuid_command *>(buf);
414     c->cmd = LC_UUID;
415     c->cmdsize = getSize();
416     uuidBuf = c->uuid;
417   }
418 
419   void writeUuid(uint64_t digest) const {
420     // xxhash only gives us 8 bytes, so put some fixed data in the other half.
421     static_assert(sizeof(uuid_command::uuid) == 16, "unexpected uuid size");
422     memcpy(uuidBuf, "LLD\xa1UU1D", 8);
423     memcpy(uuidBuf + 8, &digest, 8);
424 
425     // RFC 4122 conformance. We need to fix 4 bits in byte 6 and 2 bits in
426     // byte 8. Byte 6 is already fine due to the fixed data we put in. We don't
427     // want to lose bits of the digest in byte 8, so swap that with a byte of
428     // fixed data that happens to have the right bits set.
429     std::swap(uuidBuf[3], uuidBuf[8]);
430 
431     // Claim that this is an MD5-based hash. It isn't, but this signals that
432     // this is not a time-based and not a random hash. MD5 seems like the least
433     // bad lie we can put here.
434     assert((uuidBuf[6] & 0xf0) == 0x30 && "See RFC 4122 Sections 4.2.2, 4.1.3");
435     assert((uuidBuf[8] & 0xc0) == 0x80 && "See RFC 4122 Section 4.2.2");
436   }
437 
438   mutable uint8_t *uuidBuf;
439 };
440 
441 class LCCodeSignature : public LoadCommand {
442 public:
443   LCCodeSignature(CodeSignatureSection *section) : section(section) {}
444 
445   uint32_t getSize() const override { return sizeof(linkedit_data_command); }
446 
447   void writeTo(uint8_t *buf) const override {
448     auto *c = reinterpret_cast<linkedit_data_command *>(buf);
449     c->cmd = LC_CODE_SIGNATURE;
450     c->cmdsize = getSize();
451     c->dataoff = static_cast<uint32_t>(section->fileOff);
452     c->datasize = section->getSize();
453   }
454 
455   CodeSignatureSection *section;
456 };
457 
458 } // namespace
459 
460 // Adds stubs and bindings where necessary (e.g. if the symbol is a
461 // DylibSymbol.)
462 static void prepareBranchTarget(Symbol *sym) {
463   if (auto *dysym = dyn_cast<DylibSymbol>(sym)) {
464     if (in.stubs->addEntry(dysym)) {
465       if (sym->isWeakDef()) {
466         in.binding->addEntry(dysym, in.lazyPointers->isec,
467                              sym->stubsIndex * target->wordSize);
468         in.weakBinding->addEntry(sym, in.lazyPointers->isec,
469                                  sym->stubsIndex * target->wordSize);
470       } else {
471         in.lazyBinding->addEntry(dysym);
472       }
473     }
474   } else if (auto *defined = dyn_cast<Defined>(sym)) {
475     if (defined->isExternalWeakDef()) {
476       if (in.stubs->addEntry(sym)) {
477         in.rebase->addEntry(in.lazyPointers->isec,
478                             sym->stubsIndex * target->wordSize);
479         in.weakBinding->addEntry(sym, in.lazyPointers->isec,
480                                  sym->stubsIndex * target->wordSize);
481       }
482     }
483   }
484 }
485 
486 // Can a symbol's address can only be resolved at runtime?
487 static bool needsBinding(const Symbol *sym) {
488   if (isa<DylibSymbol>(sym))
489     return true;
490   if (const auto *defined = dyn_cast<Defined>(sym))
491     return defined->isExternalWeakDef();
492   return false;
493 }
494 
495 static void prepareSymbolRelocation(Symbol *sym, const InputSection *isec,
496                                     const Reloc &r) {
497   const RelocAttrs &relocAttrs = target->getRelocAttrs(r.type);
498 
499   if (relocAttrs.hasAttr(RelocAttrBits::BRANCH)) {
500     prepareBranchTarget(sym);
501   } else if (relocAttrs.hasAttr(RelocAttrBits::GOT)) {
502     if (relocAttrs.hasAttr(RelocAttrBits::POINTER) || needsBinding(sym))
503       in.got->addEntry(sym);
504   } else if (relocAttrs.hasAttr(RelocAttrBits::TLV)) {
505     if (needsBinding(sym))
506       in.tlvPointers->addEntry(sym);
507   } else if (relocAttrs.hasAttr(RelocAttrBits::UNSIGNED)) {
508     // References from thread-local variable sections are treated as offsets
509     // relative to the start of the referent section, and therefore have no
510     // need of rebase opcodes.
511     if (!(isThreadLocalVariables(isec->flags) && isa<Defined>(sym)))
512       addNonLazyBindingEntries(sym, isec, r.offset, r.addend);
513   }
514 }
515 
516 void Writer::scanRelocations() {
517   TimeTraceScope timeScope("Scan relocations");
518   for (InputSection *isec : inputSections) {
519     if (isec->segname == segment_names::ld) {
520       prepareCompactUnwind(isec);
521       continue;
522     }
523 
524     for (auto it = isec->relocs.begin(); it != isec->relocs.end(); ++it) {
525       Reloc &r = *it;
526       if (target->hasAttr(r.type, RelocAttrBits::SUBTRAHEND)) {
527         // Skip over the following UNSIGNED relocation -- it's just there as the
528         // minuend, and doesn't have the usual UNSIGNED semantics. We don't want
529         // to emit rebase opcodes for it.
530         it = std::next(it);
531         assert(isa<Defined>(it->referent.dyn_cast<Symbol *>()));
532         continue;
533       }
534       if (auto *sym = r.referent.dyn_cast<Symbol *>()) {
535         if (auto *undefined = dyn_cast<Undefined>(sym))
536           treatUndefinedSymbol(*undefined);
537         // treatUndefinedSymbol() can replace sym with a DylibSymbol; re-check.
538         if (!isa<Undefined>(sym) && validateSymbolRelocation(sym, isec, r))
539           prepareSymbolRelocation(sym, isec, r);
540       } else {
541         assert(r.referent.is<InputSection *>());
542         if (!r.pcrel)
543           in.rebase->addEntry(isec, r.offset);
544       }
545     }
546   }
547 }
548 
549 void Writer::scanSymbols() {
550   TimeTraceScope timeScope("Scan symbols");
551   for (const Symbol *sym : symtab->getSymbols()) {
552     if (const auto *defined = dyn_cast<Defined>(sym)) {
553       if (defined->overridesWeakDef)
554         in.weakBinding->addNonWeakDefinition(defined);
555     } else if (const auto *dysym = dyn_cast<DylibSymbol>(sym)) {
556       if (dysym->isDynamicLookup())
557         continue;
558       dysym->getFile()->refState =
559           std::max(dysym->getFile()->refState, dysym->refState);
560     }
561   }
562 }
563 
564 template <class LP> void Writer::createLoadCommands() {
565   uint8_t segIndex = 0;
566   for (OutputSegment *seg : outputSegments) {
567     in.header->addLoadCommand(make<LCSegment<LP>>(seg->name, seg));
568     seg->index = segIndex++;
569   }
570 
571   in.header->addLoadCommand(make<LCDyldInfo>(
572       in.rebase, in.binding, in.weakBinding, in.lazyBinding, in.exports));
573   in.header->addLoadCommand(make<LCSymtab>(symtabSection, stringTableSection));
574   in.header->addLoadCommand(
575       make<LCDysymtab>(symtabSection, indirectSymtabSection));
576   if (functionStartsSection)
577     in.header->addLoadCommand(make<LCFunctionStarts>(functionStartsSection));
578   for (StringRef path : config->runtimePaths)
579     in.header->addLoadCommand(make<LCRPath>(path));
580 
581   switch (config->outputType) {
582   case MH_EXECUTE:
583     in.header->addLoadCommand(make<LCLoadDylinker>());
584     in.header->addLoadCommand(make<LCMain>());
585     break;
586   case MH_DYLIB:
587     in.header->addLoadCommand(make<LCDylib>(LC_ID_DYLIB, config->installName,
588                                             config->dylibCompatibilityVersion,
589                                             config->dylibCurrentVersion));
590     break;
591   case MH_BUNDLE:
592     break;
593   default:
594     llvm_unreachable("unhandled output file type");
595   }
596 
597   uuidCommand = make<LCUuid>();
598   in.header->addLoadCommand(uuidCommand);
599 
600   in.header->addLoadCommand(
601       make<LCBuildVersion>(config->target.Platform, config->platformInfo));
602 
603   int64_t dylibOrdinal = 1;
604   for (InputFile *file : inputFiles) {
605     if (auto *dylibFile = dyn_cast<DylibFile>(file)) {
606       if (dylibFile->isBundleLoader) {
607         dylibFile->ordinal = BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE;
608         // Shortcut since bundle-loader does not re-export the symbols.
609 
610         dylibFile->reexport = false;
611         continue;
612       }
613 
614       dylibFile->ordinal = dylibOrdinal++;
615       LoadCommandType lcType =
616           dylibFile->forceWeakImport || dylibFile->refState == RefState::Weak
617               ? LC_LOAD_WEAK_DYLIB
618               : LC_LOAD_DYLIB;
619       in.header->addLoadCommand(make<LCDylib>(lcType, dylibFile->dylibName,
620                                               dylibFile->compatibilityVersion,
621                                               dylibFile->currentVersion));
622 
623       if (dylibFile->reexport)
624         in.header->addLoadCommand(
625             make<LCDylib>(LC_REEXPORT_DYLIB, dylibFile->dylibName));
626     }
627   }
628 
629   if (codeSignatureSection)
630     in.header->addLoadCommand(make<LCCodeSignature>(codeSignatureSection));
631 
632   const uint32_t MACOS_MAXPATHLEN = 1024;
633   config->headerPad = std::max(
634       config->headerPad, (config->headerPadMaxInstallNames
635                               ? LCDylib::getInstanceCount() * MACOS_MAXPATHLEN
636                               : 0));
637 }
638 
639 static size_t getSymbolPriority(const SymbolPriorityEntry &entry,
640                                 const InputFile *f) {
641   // We don't use toString(InputFile *) here because it returns the full path
642   // for object files, and we only want the basename.
643   StringRef filename;
644   if (f->archiveName.empty())
645     filename = path::filename(f->getName());
646   else
647     filename = saver.save(path::filename(f->archiveName) + "(" +
648                           path::filename(f->getName()) + ")");
649   return std::max(entry.objectFiles.lookup(filename), entry.anyObjectFile);
650 }
651 
652 // Each section gets assigned the priority of the highest-priority symbol it
653 // contains.
654 static DenseMap<const InputSection *, size_t> buildInputSectionPriorities() {
655   DenseMap<const InputSection *, size_t> sectionPriorities;
656 
657   if (config->priorities.empty())
658     return sectionPriorities;
659 
660   auto addSym = [&](Defined &sym) {
661     auto it = config->priorities.find(sym.getName());
662     if (it == config->priorities.end())
663       return;
664 
665     SymbolPriorityEntry &entry = it->second;
666     size_t &priority = sectionPriorities[sym.isec];
667     priority = std::max(priority, getSymbolPriority(entry, sym.isec->file));
668   };
669 
670   // TODO: Make sure this handles weak symbols correctly.
671   for (const InputFile *file : inputFiles) {
672     if (isa<ObjFile>(file))
673       for (Symbol *sym : file->symbols)
674         if (auto *d = dyn_cast<Defined>(sym))
675           addSym(*d);
676   }
677 
678   return sectionPriorities;
679 }
680 
681 static int segmentOrder(OutputSegment *seg) {
682   return StringSwitch<int>(seg->name)
683       .Case(segment_names::pageZero, -4)
684       .Case(segment_names::text, -3)
685       .Case(segment_names::dataConst, -2)
686       .Case(segment_names::data, -1)
687       // Make sure __LINKEDIT is the last segment (i.e. all its hidden
688       // sections must be ordered after other sections).
689       .Case(segment_names::linkEdit, std::numeric_limits<int>::max())
690       .Default(0);
691 }
692 
693 static int sectionOrder(OutputSection *osec) {
694   StringRef segname = osec->parent->name;
695   // Sections are uniquely identified by their segment + section name.
696   if (segname == segment_names::text) {
697     return StringSwitch<int>(osec->name)
698         .Case(section_names::header, -4)
699         .Case(section_names::text, -3)
700         .Case(section_names::stubs, -2)
701         .Case(section_names::stubHelper, -1)
702         .Case(section_names::unwindInfo, std::numeric_limits<int>::max() - 1)
703         .Case(section_names::ehFrame, std::numeric_limits<int>::max())
704         .Default(0);
705   } else if (segname == segment_names::data) {
706     // For each thread spawned, dyld will initialize its TLVs by copying the
707     // address range from the start of the first thread-local data section to
708     // the end of the last one. We therefore arrange these sections contiguously
709     // to minimize the amount of memory used. Additionally, since zerofill
710     // sections must be at the end of their segments, and since TLV data
711     // sections can be zerofills, we end up putting all TLV data sections at the
712     // end of the segment.
713     switch (sectionType(osec->flags)) {
714     case S_THREAD_LOCAL_REGULAR:
715       return std::numeric_limits<int>::max() - 2;
716     case S_THREAD_LOCAL_ZEROFILL:
717       return std::numeric_limits<int>::max() - 1;
718     case S_ZEROFILL:
719       return std::numeric_limits<int>::max();
720     default:
721       return StringSwitch<int>(osec->name)
722           .Case(section_names::laSymbolPtr, -2)
723           .Case(section_names::data, -1)
724           .Default(0);
725     }
726   } else if (segname == segment_names::linkEdit) {
727     return StringSwitch<int>(osec->name)
728         .Case(section_names::rebase, -9)
729         .Case(section_names::binding, -8)
730         .Case(section_names::weakBinding, -7)
731         .Case(section_names::lazyBinding, -6)
732         .Case(section_names::export_, -5)
733         .Case(section_names::functionStarts, -4)
734         .Case(section_names::symbolTable, -3)
735         .Case(section_names::indirectSymbolTable, -2)
736         .Case(section_names::stringTable, -1)
737         .Case(section_names::codeSignature, std::numeric_limits<int>::max())
738         .Default(0);
739   }
740   // ZeroFill sections must always be the at the end of their segments,
741   // otherwise subsequent sections may get overwritten with zeroes at runtime.
742   if (sectionType(osec->flags) == S_ZEROFILL)
743     return std::numeric_limits<int>::max();
744   return 0;
745 }
746 
747 template <typename T, typename F>
748 static std::function<bool(T, T)> compareByOrder(F ord) {
749   return [=](T a, T b) { return ord(a) < ord(b); };
750 }
751 
752 // Sorting only can happen once all outputs have been collected. Here we sort
753 // segments, output sections within each segment, and input sections within each
754 // output segment.
755 static void sortSegmentsAndSections() {
756   TimeTraceScope timeScope("Sort segments and sections");
757 
758   llvm::stable_sort(outputSegments,
759                     compareByOrder<OutputSegment *>(segmentOrder));
760 
761   DenseMap<const InputSection *, size_t> isecPriorities =
762       buildInputSectionPriorities();
763 
764   uint32_t sectionIndex = 0;
765   for (OutputSegment *seg : outputSegments) {
766     seg->sortOutputSections(compareByOrder<OutputSection *>(sectionOrder));
767     for (OutputSection *osec : seg->getSections()) {
768       // Now that the output sections are sorted, assign the final
769       // output section indices.
770       if (!osec->isHidden())
771         osec->index = ++sectionIndex;
772       if (!firstTLVDataSection && isThreadLocalData(osec->flags))
773         firstTLVDataSection = osec;
774 
775       if (!isecPriorities.empty()) {
776         if (auto *merged = dyn_cast<MergedOutputSection>(osec)) {
777           llvm::stable_sort(merged->inputs,
778                             [&](InputSection *a, InputSection *b) {
779                               return isecPriorities[a] > isecPriorities[b];
780                             });
781         }
782       }
783     }
784   }
785 }
786 
787 static NamePair maybeRenameSection(NamePair key) {
788   auto newNames = config->sectionRenameMap.find(key);
789   if (newNames != config->sectionRenameMap.end())
790     return newNames->second;
791   auto newName = config->segmentRenameMap.find(key.first);
792   if (newName != config->segmentRenameMap.end())
793     return std::make_pair(newName->second, key.second);
794   return key;
795 }
796 
797 template <class LP> void Writer::createOutputSections() {
798   TimeTraceScope timeScope("Create output sections");
799   // First, create hidden sections
800   stringTableSection = make<StringTableSection>();
801   unwindInfoSection = make<UnwindInfoSection>(); // TODO(gkm): only when no -r
802   symtabSection = makeSymtabSection<LP>(*stringTableSection);
803   indirectSymtabSection = make<IndirectSymtabSection>();
804   if (config->adhocCodesign)
805     codeSignatureSection = make<CodeSignatureSection>();
806   if (config->emitFunctionStarts)
807     functionStartsSection = make<FunctionStartsSection>();
808 
809   switch (config->outputType) {
810   case MH_EXECUTE:
811     make<PageZeroSection>();
812     break;
813   case MH_DYLIB:
814   case MH_BUNDLE:
815     break;
816   default:
817     llvm_unreachable("unhandled output file type");
818   }
819 
820   // Then merge input sections into output sections.
821   MapVector<NamePair, MergedOutputSection *> mergedOutputSections;
822   for (InputSection *isec : inputSections) {
823     NamePair names = maybeRenameSection({isec->segname, isec->name});
824     MergedOutputSection *&osec = mergedOutputSections[names];
825     if (osec == nullptr)
826       osec = make<MergedOutputSection>(names.second);
827     osec->mergeInput(isec);
828   }
829 
830   for (const auto &it : mergedOutputSections) {
831     StringRef segname = it.first.first;
832     MergedOutputSection *osec = it.second;
833     if (unwindInfoSection && segname == segment_names::ld) {
834       assert(osec->name == section_names::compactUnwind);
835       unwindInfoSection->setCompactUnwindSection(osec);
836     } else {
837       getOrCreateOutputSegment(segname)->addOutputSection(osec);
838     }
839   }
840 
841   for (SyntheticSection *ssec : syntheticSections) {
842     auto it = mergedOutputSections.find({ssec->segname, ssec->name});
843     if (it == mergedOutputSections.end()) {
844       if (ssec->isNeeded())
845         getOrCreateOutputSegment(ssec->segname)->addOutputSection(ssec);
846     } else {
847       error("section from " + toString(it->second->firstSection()->file) +
848             " conflicts with synthetic section " + ssec->segname + "," +
849             ssec->name);
850     }
851   }
852 
853   // dyld requires __LINKEDIT segment to always exist (even if empty).
854   linkEditSegment = getOrCreateOutputSegment(segment_names::linkEdit);
855 }
856 
857 void Writer::finalizeAddresses() {
858   TimeTraceScope timeScope("Finalize addresses");
859   // Ensure that segments (and the sections they contain) are allocated
860   // addresses in ascending order, which dyld requires.
861   //
862   // Note that at this point, __LINKEDIT sections are empty, but we need to
863   // determine addresses of other segments/sections before generating its
864   // contents.
865   for (OutputSegment *seg : outputSegments)
866     if (seg != linkEditSegment)
867       assignAddresses(seg);
868 
869   // FIXME(gkm): create branch-extension thunks here, then adjust addresses
870 }
871 
872 void Writer::finalizeLinkEditSegment() {
873   TimeTraceScope timeScope("Finalize __LINKEDIT segment");
874   // Fill __LINKEDIT contents.
875   std::vector<LinkEditSection *> linkEditSections{
876       in.rebase,  in.binding,    in.weakBinding,        in.lazyBinding,
877       in.exports, symtabSection, indirectSymtabSection, functionStartsSection,
878   };
879   parallelForEach(linkEditSections, [](LinkEditSection *osec) {
880     if (osec)
881       osec->finalizeContents();
882   });
883 
884   // Now that __LINKEDIT is filled out, do a proper calculation of its
885   // addresses and offsets.
886   assignAddresses(linkEditSegment);
887 }
888 
889 void Writer::assignAddresses(OutputSegment *seg) {
890   uint64_t pageSize = target->getPageSize();
891   addr = alignTo(addr, pageSize);
892   fileOff = alignTo(fileOff, pageSize);
893   seg->fileOff = fileOff;
894 
895   for (OutputSection *osec : seg->getSections()) {
896     if (!osec->isNeeded())
897       continue;
898     addr = alignTo(addr, osec->align);
899     fileOff = alignTo(fileOff, osec->align);
900     osec->addr = addr;
901     osec->fileOff = isZeroFill(osec->flags) ? 0 : fileOff;
902     osec->finalize();
903 
904     addr += osec->getSize();
905     fileOff += osec->getFileSize();
906   }
907   seg->fileSize = fileOff - seg->fileOff;
908 }
909 
910 void Writer::openFile() {
911   Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr =
912       FileOutputBuffer::create(config->outputFile, fileOff,
913                                FileOutputBuffer::F_executable);
914 
915   if (!bufferOrErr)
916     error("failed to open " + config->outputFile + ": " +
917           llvm::toString(bufferOrErr.takeError()));
918   else
919     buffer = std::move(*bufferOrErr);
920 }
921 
922 void Writer::writeSections() {
923   uint8_t *buf = buffer->getBufferStart();
924   for (const OutputSegment *seg : outputSegments)
925     for (const OutputSection *osec : seg->getSections())
926       osec->writeTo(buf + osec->fileOff);
927 }
928 
929 // In order to utilize multiple cores, we first split the buffer into chunks,
930 // compute a hash for each chunk, and then compute a hash value of the hash
931 // values.
932 void Writer::writeUuid() {
933   TimeTraceScope timeScope("Computing UUID");
934   ArrayRef<uint8_t> data{buffer->getBufferStart(), buffer->getBufferEnd()};
935   unsigned chunkCount = parallel::strategy.compute_thread_count() * 10;
936   // Round-up integer division
937   size_t chunkSize = (data.size() + chunkCount - 1) / chunkCount;
938   std::vector<ArrayRef<uint8_t>> chunks = split(data, chunkSize);
939   std::vector<uint64_t> hashes(chunks.size());
940   parallelForEachN(0, chunks.size(),
941                    [&](size_t i) { hashes[i] = xxHash64(chunks[i]); });
942   uint64_t digest = xxHash64({reinterpret_cast<uint8_t *>(hashes.data()),
943                               hashes.size() * sizeof(uint64_t)});
944   uuidCommand->writeUuid(digest);
945 }
946 
947 void Writer::writeCodeSignature() {
948   if (codeSignatureSection)
949     codeSignatureSection->writeHashes(buffer->getBufferStart());
950 }
951 
952 void Writer::writeOutputFile() {
953   TimeTraceScope timeScope("Write output file");
954   openFile();
955   if (errorCount())
956     return;
957   writeSections();
958   writeUuid();
959   writeCodeSignature();
960 
961   if (auto e = buffer->commit())
962     error("failed to write to the output file: " + toString(std::move(e)));
963 }
964 
965 template <class LP> void Writer::run() {
966   prepareBranchTarget(config->entry);
967   scanRelocations();
968   if (in.stubHelper->isNeeded())
969     in.stubHelper->setup();
970   scanSymbols();
971   createOutputSections<LP>();
972   // No more sections nor segments are created beyond this point.
973   sortSegmentsAndSections();
974   createLoadCommands<LP>();
975   finalizeAddresses();
976   finalizeLinkEditSegment();
977   writeMapFile();
978   writeOutputFile();
979 }
980 
981 template <class LP> void macho::writeResult() { Writer().run<LP>(); }
982 
983 template <class LP> void macho::createSyntheticSections() {
984   in.header = makeMachHeaderSection<LP>();
985   in.rebase = make<RebaseSection>();
986   in.binding = make<BindingSection>();
987   in.weakBinding = make<WeakBindingSection>();
988   in.lazyBinding = make<LazyBindingSection>();
989   in.exports = make<ExportSection>();
990   in.got = make<GotSection>();
991   in.tlvPointers = make<TlvPointerSection>();
992   in.lazyPointers = make<LazyPointerSection>();
993   in.stubs = make<StubsSection>();
994   in.stubHelper = make<StubHelperSection>();
995   in.imageLoaderCache = make<ImageLoaderCacheSection>();
996 }
997 
998 OutputSection *macho::firstTLVDataSection = nullptr;
999 
1000 template void macho::writeResult<LP64>();
1001 template void macho::writeResult<ILP32>();
1002 template void macho::createSyntheticSections<LP64>();
1003 template void macho::createSyntheticSections<ILP32>();
1004