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