xref: /llvm-project-15.0.7/lld/MachO/Writer.cpp (revision 9dfbccf0)
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 "ConcatOutputSection.h"
11 #include "Config.h"
12 #include "InputFiles.h"
13 #include "InputSection.h"
14 #include "MapFile.h"
15 #include "OutputSection.h"
16 #include "OutputSegment.h"
17 #include "SectionPriorities.h"
18 #include "SymbolTable.h"
19 #include "Symbols.h"
20 #include "SyntheticSections.h"
21 #include "Target.h"
22 #include "UnwindInfoSection.h"
23 
24 #include "lld/Common/Arrays.h"
25 #include "lld/Common/CommonLinkerContext.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/ThreadPool.h"
33 #include "llvm/Support/TimeProfiler.h"
34 #include "llvm/Support/xxhash.h"
35 
36 #include <algorithm>
37 
38 using namespace llvm;
39 using namespace llvm::MachO;
40 using namespace llvm::sys;
41 using namespace lld;
42 using namespace lld::macho;
43 
44 namespace {
45 class LCUuid;
46 
47 class Writer {
48 public:
49   Writer() : buffer(errorHandler().outputBuffer) {}
50 
51   void treatSpecialUndefineds();
52   void scanRelocations();
53   void scanSymbols();
54   template <class LP> void createOutputSections();
55   template <class LP> void createLoadCommands();
56   void finalizeAddresses();
57   void finalizeLinkEditSegment();
58   void assignAddresses(OutputSegment *);
59 
60   void openFile();
61   void writeSections();
62   void writeUuid();
63   void writeCodeSignature();
64   void writeOutputFile();
65 
66   template <class LP> void run();
67 
68   ThreadPool threadPool;
69   std::unique_ptr<FileOutputBuffer> &buffer;
70   uint64_t addr = 0;
71   uint64_t fileOff = 0;
72   MachHeaderSection *header = nullptr;
73   StringTableSection *stringTableSection = nullptr;
74   SymtabSection *symtabSection = nullptr;
75   IndirectSymtabSection *indirectSymtabSection = nullptr;
76   CodeSignatureSection *codeSignatureSection = nullptr;
77   DataInCodeSection *dataInCodeSection = nullptr;
78   FunctionStartsSection *functionStartsSection = nullptr;
79 
80   LCUuid *uuidCommand = nullptr;
81   OutputSegment *linkEditSegment = nullptr;
82 };
83 
84 // LC_DYLD_INFO_ONLY stores the offsets of symbol import/export information.
85 class LCDyldInfo final : public LoadCommand {
86 public:
87   LCDyldInfo(RebaseSection *rebaseSection, BindingSection *bindingSection,
88              WeakBindingSection *weakBindingSection,
89              LazyBindingSection *lazyBindingSection,
90              ExportSection *exportSection)
91       : rebaseSection(rebaseSection), bindingSection(bindingSection),
92         weakBindingSection(weakBindingSection),
93         lazyBindingSection(lazyBindingSection), exportSection(exportSection) {}
94 
95   uint32_t getSize() const override { return sizeof(dyld_info_command); }
96 
97   void writeTo(uint8_t *buf) const override {
98     auto *c = reinterpret_cast<dyld_info_command *>(buf);
99     c->cmd = LC_DYLD_INFO_ONLY;
100     c->cmdsize = getSize();
101     if (rebaseSection->isNeeded()) {
102       c->rebase_off = rebaseSection->fileOff;
103       c->rebase_size = rebaseSection->getFileSize();
104     }
105     if (bindingSection->isNeeded()) {
106       c->bind_off = bindingSection->fileOff;
107       c->bind_size = bindingSection->getFileSize();
108     }
109     if (weakBindingSection->isNeeded()) {
110       c->weak_bind_off = weakBindingSection->fileOff;
111       c->weak_bind_size = weakBindingSection->getFileSize();
112     }
113     if (lazyBindingSection->isNeeded()) {
114       c->lazy_bind_off = lazyBindingSection->fileOff;
115       c->lazy_bind_size = lazyBindingSection->getFileSize();
116     }
117     if (exportSection->isNeeded()) {
118       c->export_off = exportSection->fileOff;
119       c->export_size = exportSection->getFileSize();
120     }
121   }
122 
123   RebaseSection *rebaseSection;
124   BindingSection *bindingSection;
125   WeakBindingSection *weakBindingSection;
126   LazyBindingSection *lazyBindingSection;
127   ExportSection *exportSection;
128 };
129 
130 class LCSubFramework final : public LoadCommand {
131 public:
132   LCSubFramework(StringRef umbrella) : umbrella(umbrella) {}
133 
134   uint32_t getSize() const override {
135     return alignTo(sizeof(sub_framework_command) + umbrella.size() + 1,
136                    target->wordSize);
137   }
138 
139   void writeTo(uint8_t *buf) const override {
140     auto *c = reinterpret_cast<sub_framework_command *>(buf);
141     buf += sizeof(sub_framework_command);
142 
143     c->cmd = LC_SUB_FRAMEWORK;
144     c->cmdsize = getSize();
145     c->umbrella = sizeof(sub_framework_command);
146 
147     memcpy(buf, umbrella.data(), umbrella.size());
148     buf[umbrella.size()] = '\0';
149   }
150 
151 private:
152   const StringRef umbrella;
153 };
154 
155 class LCFunctionStarts final : public LoadCommand {
156 public:
157   explicit LCFunctionStarts(FunctionStartsSection *functionStartsSection)
158       : functionStartsSection(functionStartsSection) {}
159 
160   uint32_t getSize() const override { return sizeof(linkedit_data_command); }
161 
162   void writeTo(uint8_t *buf) const override {
163     auto *c = reinterpret_cast<linkedit_data_command *>(buf);
164     c->cmd = LC_FUNCTION_STARTS;
165     c->cmdsize = getSize();
166     c->dataoff = functionStartsSection->fileOff;
167     c->datasize = functionStartsSection->getFileSize();
168   }
169 
170 private:
171   FunctionStartsSection *functionStartsSection;
172 };
173 
174 class LCDataInCode final : public LoadCommand {
175 public:
176   explicit LCDataInCode(DataInCodeSection *dataInCodeSection)
177       : dataInCodeSection(dataInCodeSection) {}
178 
179   uint32_t getSize() const override { return sizeof(linkedit_data_command); }
180 
181   void writeTo(uint8_t *buf) const override {
182     auto *c = reinterpret_cast<linkedit_data_command *>(buf);
183     c->cmd = LC_DATA_IN_CODE;
184     c->cmdsize = getSize();
185     c->dataoff = dataInCodeSection->fileOff;
186     c->datasize = dataInCodeSection->getFileSize();
187   }
188 
189 private:
190   DataInCodeSection *dataInCodeSection;
191 };
192 
193 class LCDysymtab final : public LoadCommand {
194 public:
195   LCDysymtab(SymtabSection *symtabSection,
196              IndirectSymtabSection *indirectSymtabSection)
197       : symtabSection(symtabSection),
198         indirectSymtabSection(indirectSymtabSection) {}
199 
200   uint32_t getSize() const override { return sizeof(dysymtab_command); }
201 
202   void writeTo(uint8_t *buf) const override {
203     auto *c = reinterpret_cast<dysymtab_command *>(buf);
204     c->cmd = LC_DYSYMTAB;
205     c->cmdsize = getSize();
206 
207     c->ilocalsym = 0;
208     c->iextdefsym = c->nlocalsym = symtabSection->getNumLocalSymbols();
209     c->nextdefsym = symtabSection->getNumExternalSymbols();
210     c->iundefsym = c->iextdefsym + c->nextdefsym;
211     c->nundefsym = symtabSection->getNumUndefinedSymbols();
212 
213     c->indirectsymoff = indirectSymtabSection->fileOff;
214     c->nindirectsyms = indirectSymtabSection->getNumSymbols();
215   }
216 
217   SymtabSection *symtabSection;
218   IndirectSymtabSection *indirectSymtabSection;
219 };
220 
221 template <class LP> class LCSegment final : public LoadCommand {
222 public:
223   LCSegment(StringRef name, OutputSegment *seg) : name(name), seg(seg) {}
224 
225   uint32_t getSize() const override {
226     return sizeof(typename LP::segment_command) +
227            seg->numNonHiddenSections() * sizeof(typename LP::section);
228   }
229 
230   void writeTo(uint8_t *buf) const override {
231     using SegmentCommand = typename LP::segment_command;
232     using SectionHeader = typename LP::section;
233 
234     auto *c = reinterpret_cast<SegmentCommand *>(buf);
235     buf += sizeof(SegmentCommand);
236 
237     c->cmd = LP::segmentLCType;
238     c->cmdsize = getSize();
239     memcpy(c->segname, name.data(), name.size());
240     c->fileoff = seg->fileOff;
241     c->maxprot = seg->maxProt;
242     c->initprot = seg->initProt;
243 
244     c->vmaddr = seg->addr;
245     c->vmsize = seg->vmSize;
246     c->filesize = seg->fileSize;
247     c->nsects = seg->numNonHiddenSections();
248 
249     for (const OutputSection *osec : seg->getSections()) {
250       if (osec->isHidden())
251         continue;
252 
253       auto *sectHdr = reinterpret_cast<SectionHeader *>(buf);
254       buf += sizeof(SectionHeader);
255 
256       memcpy(sectHdr->sectname, osec->name.data(), osec->name.size());
257       memcpy(sectHdr->segname, name.data(), name.size());
258 
259       sectHdr->addr = osec->addr;
260       sectHdr->offset = osec->fileOff;
261       sectHdr->align = Log2_32(osec->align);
262       sectHdr->flags = osec->flags;
263       sectHdr->size = osec->getSize();
264       sectHdr->reserved1 = osec->reserved1;
265       sectHdr->reserved2 = osec->reserved2;
266     }
267   }
268 
269 private:
270   StringRef name;
271   OutputSegment *seg;
272 };
273 
274 class LCMain final : public LoadCommand {
275   uint32_t getSize() const override {
276     return sizeof(structs::entry_point_command);
277   }
278 
279   void writeTo(uint8_t *buf) const override {
280     auto *c = reinterpret_cast<structs::entry_point_command *>(buf);
281     c->cmd = LC_MAIN;
282     c->cmdsize = getSize();
283 
284     if (config->entry->isInStubs())
285       c->entryoff =
286           in.stubs->fileOff + config->entry->stubsIndex * target->stubSize;
287     else
288       c->entryoff = config->entry->getVA() - in.header->addr;
289 
290     c->stacksize = 0;
291   }
292 };
293 
294 class LCSymtab final : public LoadCommand {
295 public:
296   LCSymtab(SymtabSection *symtabSection, StringTableSection *stringTableSection)
297       : symtabSection(symtabSection), stringTableSection(stringTableSection) {}
298 
299   uint32_t getSize() const override { return sizeof(symtab_command); }
300 
301   void writeTo(uint8_t *buf) const override {
302     auto *c = reinterpret_cast<symtab_command *>(buf);
303     c->cmd = LC_SYMTAB;
304     c->cmdsize = getSize();
305     c->symoff = symtabSection->fileOff;
306     c->nsyms = symtabSection->getNumSymbols();
307     c->stroff = stringTableSection->fileOff;
308     c->strsize = stringTableSection->getFileSize();
309   }
310 
311   SymtabSection *symtabSection = nullptr;
312   StringTableSection *stringTableSection = nullptr;
313 };
314 
315 // There are several dylib load commands that share the same structure:
316 //   * LC_LOAD_DYLIB
317 //   * LC_ID_DYLIB
318 //   * LC_REEXPORT_DYLIB
319 class LCDylib final : public LoadCommand {
320 public:
321   LCDylib(LoadCommandType type, StringRef path,
322           uint32_t compatibilityVersion = 0, uint32_t currentVersion = 0)
323       : type(type), path(path), compatibilityVersion(compatibilityVersion),
324         currentVersion(currentVersion) {
325     instanceCount++;
326   }
327 
328   uint32_t getSize() const override {
329     return alignTo(sizeof(dylib_command) + path.size() + 1, 8);
330   }
331 
332   void writeTo(uint8_t *buf) const override {
333     auto *c = reinterpret_cast<dylib_command *>(buf);
334     buf += sizeof(dylib_command);
335 
336     c->cmd = type;
337     c->cmdsize = getSize();
338     c->dylib.name = sizeof(dylib_command);
339     c->dylib.timestamp = 0;
340     c->dylib.compatibility_version = compatibilityVersion;
341     c->dylib.current_version = currentVersion;
342 
343     memcpy(buf, path.data(), path.size());
344     buf[path.size()] = '\0';
345   }
346 
347   static uint32_t getInstanceCount() { return instanceCount; }
348   static void resetInstanceCount() { instanceCount = 0; }
349 
350 private:
351   LoadCommandType type;
352   StringRef path;
353   uint32_t compatibilityVersion;
354   uint32_t currentVersion;
355   static uint32_t instanceCount;
356 };
357 
358 uint32_t LCDylib::instanceCount = 0;
359 
360 class LCLoadDylinker final : public LoadCommand {
361 public:
362   uint32_t getSize() const override {
363     return alignTo(sizeof(dylinker_command) + path.size() + 1, 8);
364   }
365 
366   void writeTo(uint8_t *buf) const override {
367     auto *c = reinterpret_cast<dylinker_command *>(buf);
368     buf += sizeof(dylinker_command);
369 
370     c->cmd = LC_LOAD_DYLINKER;
371     c->cmdsize = getSize();
372     c->name = sizeof(dylinker_command);
373 
374     memcpy(buf, path.data(), path.size());
375     buf[path.size()] = '\0';
376   }
377 
378 private:
379   // Recent versions of Darwin won't run any binary that has dyld at a
380   // different location.
381   const StringRef path = "/usr/lib/dyld";
382 };
383 
384 class LCRPath final : public LoadCommand {
385 public:
386   explicit LCRPath(StringRef path) : path(path) {}
387 
388   uint32_t getSize() const override {
389     return alignTo(sizeof(rpath_command) + path.size() + 1, target->wordSize);
390   }
391 
392   void writeTo(uint8_t *buf) const override {
393     auto *c = reinterpret_cast<rpath_command *>(buf);
394     buf += sizeof(rpath_command);
395 
396     c->cmd = LC_RPATH;
397     c->cmdsize = getSize();
398     c->path = sizeof(rpath_command);
399 
400     memcpy(buf, path.data(), path.size());
401     buf[path.size()] = '\0';
402   }
403 
404 private:
405   StringRef path;
406 };
407 
408 class LCMinVersion final : public LoadCommand {
409 public:
410   explicit LCMinVersion(const PlatformInfo &platformInfo)
411       : platformInfo(platformInfo) {}
412 
413   uint32_t getSize() const override { return sizeof(version_min_command); }
414 
415   void writeTo(uint8_t *buf) const override {
416     auto *c = reinterpret_cast<version_min_command *>(buf);
417     switch (platformInfo.target.Platform) {
418     case PLATFORM_MACOS:
419       c->cmd = LC_VERSION_MIN_MACOSX;
420       break;
421     case PLATFORM_IOS:
422     case PLATFORM_IOSSIMULATOR:
423       c->cmd = LC_VERSION_MIN_IPHONEOS;
424       break;
425     case PLATFORM_TVOS:
426     case PLATFORM_TVOSSIMULATOR:
427       c->cmd = LC_VERSION_MIN_TVOS;
428       break;
429     case PLATFORM_WATCHOS:
430     case PLATFORM_WATCHOSSIMULATOR:
431       c->cmd = LC_VERSION_MIN_WATCHOS;
432       break;
433     default:
434       llvm_unreachable("invalid platform");
435       break;
436     }
437     c->cmdsize = getSize();
438     c->version = encodeVersion(platformInfo.minimum);
439     c->sdk = encodeVersion(platformInfo.sdk);
440   }
441 
442 private:
443   const PlatformInfo &platformInfo;
444 };
445 
446 class LCBuildVersion final : public LoadCommand {
447 public:
448   explicit LCBuildVersion(const PlatformInfo &platformInfo)
449       : platformInfo(platformInfo) {}
450 
451   const int ntools = 1;
452 
453   uint32_t getSize() const override {
454     return sizeof(build_version_command) + ntools * sizeof(build_tool_version);
455   }
456 
457   void writeTo(uint8_t *buf) const override {
458     auto *c = reinterpret_cast<build_version_command *>(buf);
459     c->cmd = LC_BUILD_VERSION;
460     c->cmdsize = getSize();
461 
462     c->platform = static_cast<uint32_t>(platformInfo.target.Platform);
463     c->minos = encodeVersion(platformInfo.minimum);
464     c->sdk = encodeVersion(platformInfo.sdk);
465 
466     c->ntools = ntools;
467     auto *t = reinterpret_cast<build_tool_version *>(&c[1]);
468     t->tool = TOOL_LD;
469     t->version = encodeVersion(VersionTuple(
470         LLVM_VERSION_MAJOR, LLVM_VERSION_MINOR, LLVM_VERSION_PATCH));
471   }
472 
473 private:
474   const PlatformInfo &platformInfo;
475 };
476 
477 // Stores a unique identifier for the output file based on an MD5 hash of its
478 // contents. In order to hash the contents, we must first write them, but
479 // LC_UUID itself must be part of the written contents in order for all the
480 // offsets to be calculated correctly. We resolve this circular paradox by
481 // first writing an LC_UUID with an all-zero UUID, then updating the UUID with
482 // its real value later.
483 class LCUuid final : public LoadCommand {
484 public:
485   uint32_t getSize() const override { return sizeof(uuid_command); }
486 
487   void writeTo(uint8_t *buf) const override {
488     auto *c = reinterpret_cast<uuid_command *>(buf);
489     c->cmd = LC_UUID;
490     c->cmdsize = getSize();
491     uuidBuf = c->uuid;
492   }
493 
494   void writeUuid(uint64_t digest) const {
495     // xxhash only gives us 8 bytes, so put some fixed data in the other half.
496     static_assert(sizeof(uuid_command::uuid) == 16, "unexpected uuid size");
497     memcpy(uuidBuf, "LLD\xa1UU1D", 8);
498     memcpy(uuidBuf + 8, &digest, 8);
499 
500     // RFC 4122 conformance. We need to fix 4 bits in byte 6 and 2 bits in
501     // byte 8. Byte 6 is already fine due to the fixed data we put in. We don't
502     // want to lose bits of the digest in byte 8, so swap that with a byte of
503     // fixed data that happens to have the right bits set.
504     std::swap(uuidBuf[3], uuidBuf[8]);
505 
506     // Claim that this is an MD5-based hash. It isn't, but this signals that
507     // this is not a time-based and not a random hash. MD5 seems like the least
508     // bad lie we can put here.
509     assert((uuidBuf[6] & 0xf0) == 0x30 && "See RFC 4122 Sections 4.2.2, 4.1.3");
510     assert((uuidBuf[8] & 0xc0) == 0x80 && "See RFC 4122 Section 4.2.2");
511   }
512 
513   mutable uint8_t *uuidBuf;
514 };
515 
516 template <class LP> class LCEncryptionInfo final : public LoadCommand {
517 public:
518   uint32_t getSize() const override {
519     return sizeof(typename LP::encryption_info_command);
520   }
521 
522   void writeTo(uint8_t *buf) const override {
523     using EncryptionInfo = typename LP::encryption_info_command;
524     auto *c = reinterpret_cast<EncryptionInfo *>(buf);
525     buf += sizeof(EncryptionInfo);
526     c->cmd = LP::encryptionInfoLCType;
527     c->cmdsize = getSize();
528     c->cryptoff = in.header->getSize();
529     auto it = find_if(outputSegments, [](const OutputSegment *seg) {
530       return seg->name == segment_names::text;
531     });
532     assert(it != outputSegments.end());
533     c->cryptsize = (*it)->fileSize - c->cryptoff;
534   }
535 };
536 
537 class LCCodeSignature final : public LoadCommand {
538 public:
539   LCCodeSignature(CodeSignatureSection *section) : section(section) {}
540 
541   uint32_t getSize() const override { return sizeof(linkedit_data_command); }
542 
543   void writeTo(uint8_t *buf) const override {
544     auto *c = reinterpret_cast<linkedit_data_command *>(buf);
545     c->cmd = LC_CODE_SIGNATURE;
546     c->cmdsize = getSize();
547     c->dataoff = static_cast<uint32_t>(section->fileOff);
548     c->datasize = section->getSize();
549   }
550 
551   CodeSignatureSection *section;
552 };
553 
554 } // namespace
555 
556 void Writer::treatSpecialUndefineds() {
557   if (config->entry)
558     if (auto *undefined = dyn_cast<Undefined>(config->entry))
559       treatUndefinedSymbol(*undefined, "the entry point");
560 
561   // FIXME: This prints symbols that are undefined both in input files and
562   // via -u flag twice.
563   for (const Symbol *sym : config->explicitUndefineds) {
564     if (const auto *undefined = dyn_cast<Undefined>(sym))
565       treatUndefinedSymbol(*undefined, "-u");
566   }
567   // Literal exported-symbol names must be defined, but glob
568   // patterns need not match.
569   for (const CachedHashStringRef &cachedName :
570        config->exportedSymbols.literals) {
571     if (const Symbol *sym = symtab->find(cachedName))
572       if (const auto *undefined = dyn_cast<Undefined>(sym))
573         treatUndefinedSymbol(*undefined, "-exported_symbol(s_list)");
574   }
575 }
576 
577 // Add stubs and bindings where necessary (e.g. if the symbol is a
578 // DylibSymbol.)
579 static void prepareBranchTarget(Symbol *sym) {
580   if (auto *dysym = dyn_cast<DylibSymbol>(sym)) {
581     if (in.stubs->addEntry(dysym)) {
582       if (sym->isWeakDef()) {
583         in.binding->addEntry(dysym, in.lazyPointers->isec,
584                              sym->stubsIndex * target->wordSize);
585         in.weakBinding->addEntry(sym, in.lazyPointers->isec,
586                                  sym->stubsIndex * target->wordSize);
587       } else {
588         in.lazyBinding->addEntry(dysym);
589       }
590     }
591   } else if (auto *defined = dyn_cast<Defined>(sym)) {
592     if (defined->isExternalWeakDef()) {
593       if (in.stubs->addEntry(sym)) {
594         in.rebase->addEntry(in.lazyPointers->isec,
595                             sym->stubsIndex * target->wordSize);
596         in.weakBinding->addEntry(sym, in.lazyPointers->isec,
597                                  sym->stubsIndex * target->wordSize);
598       }
599     } else if (defined->interposable) {
600       if (in.stubs->addEntry(sym))
601         in.lazyBinding->addEntry(sym);
602     }
603   } else {
604     llvm_unreachable("invalid branch target symbol type");
605   }
606 }
607 
608 // Can a symbol's address can only be resolved at runtime?
609 static bool needsBinding(const Symbol *sym) {
610   if (isa<DylibSymbol>(sym))
611     return true;
612   if (const auto *defined = dyn_cast<Defined>(sym))
613     return defined->isExternalWeakDef() || defined->interposable;
614   return false;
615 }
616 
617 static void prepareSymbolRelocation(Symbol *sym, const InputSection *isec,
618                                     const lld::macho::Reloc &r) {
619   assert(sym->isLive());
620   const RelocAttrs &relocAttrs = target->getRelocAttrs(r.type);
621 
622   if (relocAttrs.hasAttr(RelocAttrBits::BRANCH)) {
623     prepareBranchTarget(sym);
624   } else if (relocAttrs.hasAttr(RelocAttrBits::GOT)) {
625     if (relocAttrs.hasAttr(RelocAttrBits::POINTER) || needsBinding(sym))
626       in.got->addEntry(sym);
627   } else if (relocAttrs.hasAttr(RelocAttrBits::TLV)) {
628     if (needsBinding(sym))
629       in.tlvPointers->addEntry(sym);
630   } else if (relocAttrs.hasAttr(RelocAttrBits::UNSIGNED)) {
631     // References from thread-local variable sections are treated as offsets
632     // relative to the start of the referent section, and therefore have no
633     // need of rebase opcodes.
634     if (!(isThreadLocalVariables(isec->getFlags()) && isa<Defined>(sym)))
635       addNonLazyBindingEntries(sym, isec, r.offset, r.addend);
636   }
637 }
638 
639 void Writer::scanRelocations() {
640   TimeTraceScope timeScope("Scan relocations");
641 
642   // This can't use a for-each loop: It calls treatUndefinedSymbol(), which can
643   // add to inputSections, which invalidates inputSections's iterators.
644   for (size_t i = 0; i < inputSections.size(); ++i) {
645     ConcatInputSection *isec = inputSections[i];
646 
647     if (isec->shouldOmitFromOutput())
648       continue;
649 
650     for (auto it = isec->relocs.begin(); it != isec->relocs.end(); ++it) {
651       lld::macho::Reloc &r = *it;
652       if (target->hasAttr(r.type, RelocAttrBits::SUBTRAHEND)) {
653         // Skip over the following UNSIGNED relocation -- it's just there as the
654         // minuend, and doesn't have the usual UNSIGNED semantics. We don't want
655         // to emit rebase opcodes for it.
656         it++;
657         continue;
658       }
659       if (auto *sym = r.referent.dyn_cast<Symbol *>()) {
660         if (auto *undefined = dyn_cast<Undefined>(sym))
661           treatUndefinedSymbol(*undefined);
662         // treatUndefinedSymbol() can replace sym with a DylibSymbol; re-check.
663         if (!isa<Undefined>(sym) && validateSymbolRelocation(sym, isec, r))
664           prepareSymbolRelocation(sym, isec, r);
665       } else {
666         // Canonicalize the referent so that later accesses in Writer won't
667         // have to worry about it. Perhaps we should do this for Defined::isec
668         // too...
669         auto *referentIsec = r.referent.get<InputSection *>();
670         r.referent = referentIsec->canonical();
671         if (!r.pcrel)
672           in.rebase->addEntry(isec, r.offset);
673       }
674     }
675   }
676 
677   in.unwindInfo->prepareRelocations();
678 }
679 
680 void Writer::scanSymbols() {
681   TimeTraceScope timeScope("Scan symbols");
682   for (Symbol *sym : symtab->getSymbols()) {
683     if (auto *defined = dyn_cast<Defined>(sym)) {
684       if (!defined->isLive())
685         continue;
686       defined->canonicalize();
687       if (defined->overridesWeakDef)
688         in.weakBinding->addNonWeakDefinition(defined);
689       if (!defined->isAbsolute() && isCodeSection(defined->isec))
690         in.unwindInfo->addSymbol(defined);
691     } else if (const auto *dysym = dyn_cast<DylibSymbol>(sym)) {
692       // This branch intentionally doesn't check isLive().
693       if (dysym->isDynamicLookup())
694         continue;
695       dysym->getFile()->refState =
696           std::max(dysym->getFile()->refState, dysym->getRefState());
697     }
698   }
699 
700   for (const InputFile *file : inputFiles) {
701     if (auto *objFile = dyn_cast<ObjFile>(file))
702       for (Symbol *sym : objFile->symbols) {
703         if (auto *defined = dyn_cast_or_null<Defined>(sym)) {
704           if (!defined->isLive())
705             continue;
706           defined->canonicalize();
707           if (!defined->isExternal() && !defined->isAbsolute() &&
708               isCodeSection(defined->isec))
709             in.unwindInfo->addSymbol(defined);
710         }
711       }
712   }
713 }
714 
715 // TODO: ld64 enforces the old load commands in a few other cases.
716 static bool useLCBuildVersion(const PlatformInfo &platformInfo) {
717   static const std::vector<std::pair<PlatformType, VersionTuple>> minVersion = {
718       {PLATFORM_MACOS, VersionTuple(10, 14)},
719       {PLATFORM_IOS, VersionTuple(12, 0)},
720       {PLATFORM_IOSSIMULATOR, VersionTuple(13, 0)},
721       {PLATFORM_TVOS, VersionTuple(12, 0)},
722       {PLATFORM_TVOSSIMULATOR, VersionTuple(13, 0)},
723       {PLATFORM_WATCHOS, VersionTuple(5, 0)},
724       {PLATFORM_WATCHOSSIMULATOR, VersionTuple(6, 0)}};
725   auto it = llvm::find_if(minVersion, [&](const auto &p) {
726     return p.first == platformInfo.target.Platform;
727   });
728   return it == minVersion.end() ? true : platformInfo.minimum >= it->second;
729 }
730 
731 template <class LP> void Writer::createLoadCommands() {
732   uint8_t segIndex = 0;
733   for (OutputSegment *seg : outputSegments) {
734     in.header->addLoadCommand(make<LCSegment<LP>>(seg->name, seg));
735     seg->index = segIndex++;
736   }
737 
738   in.header->addLoadCommand(make<LCDyldInfo>(
739       in.rebase, in.binding, in.weakBinding, in.lazyBinding, in.exports));
740   in.header->addLoadCommand(make<LCSymtab>(symtabSection, stringTableSection));
741   in.header->addLoadCommand(
742       make<LCDysymtab>(symtabSection, indirectSymtabSection));
743   if (!config->umbrella.empty())
744     in.header->addLoadCommand(make<LCSubFramework>(config->umbrella));
745   if (config->emitEncryptionInfo)
746     in.header->addLoadCommand(make<LCEncryptionInfo<LP>>());
747   for (StringRef path : config->runtimePaths)
748     in.header->addLoadCommand(make<LCRPath>(path));
749 
750   switch (config->outputType) {
751   case MH_EXECUTE:
752     in.header->addLoadCommand(make<LCLoadDylinker>());
753     break;
754   case MH_DYLIB:
755     in.header->addLoadCommand(make<LCDylib>(LC_ID_DYLIB, config->installName,
756                                             config->dylibCompatibilityVersion,
757                                             config->dylibCurrentVersion));
758     break;
759   case MH_BUNDLE:
760     break;
761   default:
762     llvm_unreachable("unhandled output file type");
763   }
764 
765   uuidCommand = make<LCUuid>();
766   in.header->addLoadCommand(uuidCommand);
767 
768   if (useLCBuildVersion(config->platformInfo))
769     in.header->addLoadCommand(make<LCBuildVersion>(config->platformInfo));
770   else
771     in.header->addLoadCommand(make<LCMinVersion>(config->platformInfo));
772 
773   if (config->secondaryPlatformInfo) {
774     in.header->addLoadCommand(
775         make<LCBuildVersion>(*config->secondaryPlatformInfo));
776   }
777 
778   // This is down here to match ld64's load command order.
779   if (config->outputType == MH_EXECUTE)
780     in.header->addLoadCommand(make<LCMain>());
781 
782   int64_t dylibOrdinal = 1;
783   DenseMap<StringRef, int64_t> ordinalForInstallName;
784   for (InputFile *file : inputFiles) {
785     if (auto *dylibFile = dyn_cast<DylibFile>(file)) {
786       if (dylibFile->isBundleLoader) {
787         dylibFile->ordinal = BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE;
788         // Shortcut since bundle-loader does not re-export the symbols.
789 
790         dylibFile->reexport = false;
791         continue;
792       }
793 
794       // Don't emit load commands for a dylib that is not referenced if:
795       // - it was added implicitly (via a reexport, an LC_LOAD_DYLINKER --
796       //   if it's on the linker command line, it's explicit)
797       // - or it's marked MH_DEAD_STRIPPABLE_DYLIB
798       // - or the flag -dead_strip_dylibs is used
799       // FIXME: `isReferenced()` is currently computed before dead code
800       // stripping, so references from dead code keep a dylib alive. This
801       // matches ld64, but it's something we should do better.
802       if (!dylibFile->isReferenced() && !dylibFile->forceNeeded &&
803           (!dylibFile->explicitlyLinked || dylibFile->deadStrippable ||
804            config->deadStripDylibs))
805         continue;
806 
807       // Several DylibFiles can have the same installName. Only emit a single
808       // load command for that installName and give all these DylibFiles the
809       // same ordinal.
810       // This can happen in several cases:
811       // - a new framework could change its installName to an older
812       //   framework name via an $ld$ symbol depending on platform_version
813       // - symlinks (for example, libpthread.tbd is a symlink to libSystem.tbd;
814       //   Foo.framework/Foo.tbd is usually a symlink to
815       //   Foo.framework/Versions/Current/Foo.tbd, where
816       //   Foo.framework/Versions/Current is usually a symlink to
817       //   Foo.framework/Versions/A)
818       // - a framework can be linked both explicitly on the linker
819       //   command line and implicitly as a reexport from a different
820       //   framework. The re-export will usually point to the tbd file
821       //   in Foo.framework/Versions/A/Foo.tbd, while the explicit link will
822       //   usually find Foo.framework/Foo.tbd. These are usually symlinks,
823       //   but in a --reproduce archive they will be identical but distinct
824       //   files.
825       // In the first case, *semantically distinct* DylibFiles will have the
826       // same installName.
827       int64_t &ordinal = ordinalForInstallName[dylibFile->installName];
828       if (ordinal) {
829         dylibFile->ordinal = ordinal;
830         continue;
831       }
832 
833       ordinal = dylibFile->ordinal = dylibOrdinal++;
834       LoadCommandType lcType =
835           dylibFile->forceWeakImport || dylibFile->refState == RefState::Weak
836               ? LC_LOAD_WEAK_DYLIB
837               : LC_LOAD_DYLIB;
838       in.header->addLoadCommand(make<LCDylib>(lcType, dylibFile->installName,
839                                               dylibFile->compatibilityVersion,
840                                               dylibFile->currentVersion));
841 
842       if (dylibFile->reexport)
843         in.header->addLoadCommand(
844             make<LCDylib>(LC_REEXPORT_DYLIB, dylibFile->installName));
845     }
846   }
847 
848   if (functionStartsSection)
849     in.header->addLoadCommand(make<LCFunctionStarts>(functionStartsSection));
850   if (dataInCodeSection)
851     in.header->addLoadCommand(make<LCDataInCode>(dataInCodeSection));
852   if (codeSignatureSection)
853     in.header->addLoadCommand(make<LCCodeSignature>(codeSignatureSection));
854 
855   const uint32_t MACOS_MAXPATHLEN = 1024;
856   config->headerPad = std::max(
857       config->headerPad, (config->headerPadMaxInstallNames
858                               ? LCDylib::getInstanceCount() * MACOS_MAXPATHLEN
859                               : 0));
860 }
861 
862 // Sorting only can happen once all outputs have been collected. Here we sort
863 // segments, output sections within each segment, and input sections within each
864 // output segment.
865 static void sortSegmentsAndSections() {
866   TimeTraceScope timeScope("Sort segments and sections");
867   sortOutputSegments();
868 
869   DenseMap<const InputSection *, size_t> isecPriorities =
870       priorityBuilder.buildInputSectionPriorities();
871 
872   uint32_t sectionIndex = 0;
873   for (OutputSegment *seg : outputSegments) {
874     seg->sortOutputSections();
875     // References from thread-local variable sections are treated as offsets
876     // relative to the start of the thread-local data memory area, which
877     // is initialized via copying all the TLV data sections (which are all
878     // contiguous). If later data sections require a greater alignment than
879     // earlier ones, the offsets of data within those sections won't be
880     // guaranteed to aligned unless we normalize alignments. We therefore use
881     // the largest alignment for all TLV data sections.
882     uint32_t tlvAlign = 0;
883     for (const OutputSection *osec : seg->getSections())
884       if (isThreadLocalData(osec->flags) && osec->align > tlvAlign)
885         tlvAlign = osec->align;
886 
887     for (OutputSection *osec : seg->getSections()) {
888       // Now that the output sections are sorted, assign the final
889       // output section indices.
890       if (!osec->isHidden())
891         osec->index = ++sectionIndex;
892       if (isThreadLocalData(osec->flags)) {
893         if (!firstTLVDataSection)
894           firstTLVDataSection = osec;
895         osec->align = tlvAlign;
896       }
897 
898       if (!isecPriorities.empty()) {
899         if (auto *merged = dyn_cast<ConcatOutputSection>(osec)) {
900           llvm::stable_sort(merged->inputs,
901                             [&](InputSection *a, InputSection *b) {
902                               return isecPriorities[a] > isecPriorities[b];
903                             });
904         }
905       }
906     }
907   }
908 }
909 
910 template <class LP> void Writer::createOutputSections() {
911   TimeTraceScope timeScope("Create output sections");
912   // First, create hidden sections
913   stringTableSection = make<StringTableSection>();
914   symtabSection = makeSymtabSection<LP>(*stringTableSection);
915   indirectSymtabSection = make<IndirectSymtabSection>();
916   if (config->adhocCodesign)
917     codeSignatureSection = make<CodeSignatureSection>();
918   if (config->emitDataInCodeInfo)
919     dataInCodeSection = make<DataInCodeSection>();
920   if (config->emitFunctionStarts)
921     functionStartsSection = make<FunctionStartsSection>();
922   if (config->emitBitcodeBundle)
923     make<BitcodeBundleSection>();
924 
925   switch (config->outputType) {
926   case MH_EXECUTE:
927     make<PageZeroSection>();
928     break;
929   case MH_DYLIB:
930   case MH_BUNDLE:
931     break;
932   default:
933     llvm_unreachable("unhandled output file type");
934   }
935 
936   // Then add input sections to output sections.
937   for (ConcatInputSection *isec : inputSections) {
938     if (isec->shouldOmitFromOutput())
939       continue;
940     ConcatOutputSection *osec = cast<ConcatOutputSection>(isec->parent);
941     osec->addInput(isec);
942     osec->inputOrder =
943         std::min(osec->inputOrder, static_cast<int>(isec->outSecOff));
944   }
945 
946   // Once all the inputs are added, we can finalize the output section
947   // properties and create the corresponding output segments.
948   for (const auto &it : concatOutputSections) {
949     StringRef segname = it.first.first;
950     ConcatOutputSection *osec = it.second;
951     assert(segname != segment_names::ld);
952     if (osec->isNeeded())
953       getOrCreateOutputSegment(segname)->addOutputSection(osec);
954   }
955 
956   for (SyntheticSection *ssec : syntheticSections) {
957     auto it = concatOutputSections.find({ssec->segname, ssec->name});
958     // We add all LinkEdit sections here because we don't know if they are
959     // needed until their finalizeContents() methods get called later. While
960     // this means that we add some redundant sections to __LINKEDIT, there is
961     // is no redundancy in the output, as we do not emit section headers for
962     // any LinkEdit sections.
963     if (ssec->isNeeded() || ssec->segname == segment_names::linkEdit) {
964       if (it == concatOutputSections.end()) {
965         getOrCreateOutputSegment(ssec->segname)->addOutputSection(ssec);
966       } else {
967         fatal("section from " +
968               toString(it->second->firstSection()->getFile()) +
969               " conflicts with synthetic section " + ssec->segname + "," +
970               ssec->name);
971       }
972     }
973   }
974 
975   // dyld requires __LINKEDIT segment to always exist (even if empty).
976   linkEditSegment = getOrCreateOutputSegment(segment_names::linkEdit);
977 }
978 
979 void Writer::finalizeAddresses() {
980   TimeTraceScope timeScope("Finalize addresses");
981   uint64_t pageSize = target->getPageSize();
982 
983   // We could parallelize this loop, but local benchmarking indicates it is
984   // faster to do it all in the main thread.
985   for (OutputSegment *seg : outputSegments) {
986     if (seg == linkEditSegment)
987       continue;
988     for (OutputSection *osec : seg->getSections()) {
989       if (!osec->isNeeded())
990         continue;
991       // Other kinds of OutputSections have already been finalized.
992       if (auto concatOsec = dyn_cast<ConcatOutputSection>(osec))
993           concatOsec->finalizeContents();
994     }
995   }
996 
997   // Ensure that segments (and the sections they contain) are allocated
998   // addresses in ascending order, which dyld requires.
999   //
1000   // Note that at this point, __LINKEDIT sections are empty, but we need to
1001   // determine addresses of other segments/sections before generating its
1002   // contents.
1003   for (OutputSegment *seg : outputSegments) {
1004     if (seg == linkEditSegment)
1005       continue;
1006     seg->addr = addr;
1007     assignAddresses(seg);
1008     // codesign / libstuff checks for segment ordering by verifying that
1009     // `fileOff + fileSize == next segment fileOff`. So we call alignTo() before
1010     // (instead of after) computing fileSize to ensure that the segments are
1011     // contiguous. We handle addr / vmSize similarly for the same reason.
1012     fileOff = alignTo(fileOff, pageSize);
1013     addr = alignTo(addr, pageSize);
1014     seg->vmSize = addr - seg->addr;
1015     seg->fileSize = fileOff - seg->fileOff;
1016     seg->assignAddressesToStartEndSymbols();
1017   }
1018 }
1019 
1020 void Writer::finalizeLinkEditSegment() {
1021   TimeTraceScope timeScope("Finalize __LINKEDIT segment");
1022   // Fill __LINKEDIT contents.
1023   std::vector<LinkEditSection *> linkEditSections{
1024       in.rebase,
1025       in.binding,
1026       in.weakBinding,
1027       in.lazyBinding,
1028       in.exports,
1029       symtabSection,
1030       indirectSymtabSection,
1031       dataInCodeSection,
1032       functionStartsSection,
1033   };
1034   SmallVector<std::shared_future<void>> threadFutures;
1035   threadFutures.reserve(linkEditSections.size());
1036   for (LinkEditSection *osec : linkEditSections)
1037     if (osec)
1038       threadFutures.emplace_back(threadPool.async(
1039           [](LinkEditSection *osec) { osec->finalizeContents(); }, osec));
1040   for (std::shared_future<void> &future : threadFutures)
1041     future.wait();
1042 
1043   // Now that __LINKEDIT is filled out, do a proper calculation of its
1044   // addresses and offsets.
1045   linkEditSegment->addr = addr;
1046   assignAddresses(linkEditSegment);
1047   // No need to page-align fileOff / addr here since this is the last segment.
1048   linkEditSegment->vmSize = addr - linkEditSegment->addr;
1049   linkEditSegment->fileSize = fileOff - linkEditSegment->fileOff;
1050 }
1051 
1052 void Writer::assignAddresses(OutputSegment *seg) {
1053   seg->fileOff = fileOff;
1054 
1055   for (OutputSection *osec : seg->getSections()) {
1056     if (!osec->isNeeded())
1057       continue;
1058     addr = alignTo(addr, osec->align);
1059     fileOff = alignTo(fileOff, osec->align);
1060     osec->addr = addr;
1061     osec->fileOff = isZeroFill(osec->flags) ? 0 : fileOff;
1062     osec->finalize();
1063     osec->assignAddressesToStartEndSymbols();
1064 
1065     addr += osec->getSize();
1066     fileOff += osec->getFileSize();
1067   }
1068 }
1069 
1070 void Writer::openFile() {
1071   Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr =
1072       FileOutputBuffer::create(config->outputFile, fileOff,
1073                                FileOutputBuffer::F_executable);
1074 
1075   if (!bufferOrErr)
1076     fatal("failed to open " + config->outputFile + ": " +
1077           llvm::toString(bufferOrErr.takeError()));
1078   buffer = std::move(*bufferOrErr);
1079   in.bufferStart = buffer->getBufferStart();
1080 }
1081 
1082 void Writer::writeSections() {
1083   uint8_t *buf = buffer->getBufferStart();
1084   for (const OutputSegment *seg : outputSegments)
1085     for (const OutputSection *osec : seg->getSections())
1086       osec->writeTo(buf + osec->fileOff);
1087 }
1088 
1089 // In order to utilize multiple cores, we first split the buffer into chunks,
1090 // compute a hash for each chunk, and then compute a hash value of the hash
1091 // values.
1092 void Writer::writeUuid() {
1093   TimeTraceScope timeScope("Computing UUID");
1094 
1095   ArrayRef<uint8_t> data{buffer->getBufferStart(), buffer->getBufferEnd()};
1096   unsigned chunkCount = parallel::strategy.compute_thread_count() * 10;
1097   // Round-up integer division
1098   size_t chunkSize = (data.size() + chunkCount - 1) / chunkCount;
1099   std::vector<ArrayRef<uint8_t>> chunks = split(data, chunkSize);
1100   // Leave one slot for filename
1101   std::vector<uint64_t> hashes(chunks.size() + 1);
1102   SmallVector<std::shared_future<void>> threadFutures;
1103   threadFutures.reserve(chunks.size());
1104   for (size_t i = 0; i < chunks.size(); ++i)
1105     threadFutures.emplace_back(threadPool.async(
1106         [&](size_t j) { hashes[j] = xxHash64(chunks[j]); }, i));
1107   for (std::shared_future<void> &future : threadFutures)
1108     future.wait();
1109   // Append the output filename so that identical binaries with different names
1110   // don't get the same UUID.
1111   hashes[chunks.size()] = xxHash64(sys::path::filename(config->finalOutput));
1112   uint64_t digest = xxHash64({reinterpret_cast<uint8_t *>(hashes.data()),
1113                               hashes.size() * sizeof(uint64_t)});
1114   uuidCommand->writeUuid(digest);
1115 }
1116 
1117 void Writer::writeCodeSignature() {
1118   if (codeSignatureSection)
1119     codeSignatureSection->writeHashes(buffer->getBufferStart());
1120 }
1121 
1122 void Writer::writeOutputFile() {
1123   TimeTraceScope timeScope("Write output file");
1124   openFile();
1125   if (errorCount())
1126     return;
1127   writeSections();
1128   writeUuid();
1129   writeCodeSignature();
1130 
1131   if (auto e = buffer->commit())
1132     error("failed to write to the output file: " + toString(std::move(e)));
1133 }
1134 
1135 template <class LP> void Writer::run() {
1136   treatSpecialUndefineds();
1137   if (config->entry && !isa<Undefined>(config->entry))
1138     prepareBranchTarget(config->entry);
1139 
1140   // Canonicalization of all pointers to InputSections should be handled by
1141   // these two scan* methods. I.e. from this point onward, for all live
1142   // InputSections, we should have `isec->canonical() == isec`.
1143   scanSymbols();
1144   scanRelocations();
1145 
1146   // Do not proceed if there was an undefined symbol.
1147   if (errorCount())
1148     return;
1149 
1150   if (in.stubHelper->isNeeded())
1151     in.stubHelper->setup();
1152   // At this point, we should know exactly which output sections are needed,
1153   // courtesy of scanSymbols() and scanRelocations().
1154   createOutputSections<LP>();
1155 
1156   // After this point, we create no new segments; HOWEVER, we might
1157   // yet create branch-range extension thunks for architectures whose
1158   // hardware call instructions have limited range, e.g., ARM(64).
1159   // The thunks are created as InputSections interspersed among
1160   // the ordinary __TEXT,_text InputSections.
1161   sortSegmentsAndSections();
1162   createLoadCommands<LP>();
1163   finalizeAddresses();
1164   threadPool.async([&] {
1165     if (LLVM_ENABLE_THREADS && config->timeTraceEnabled)
1166       timeTraceProfilerInitialize(config->timeTraceGranularity, "writeMapFile");
1167     writeMapFile();
1168     if (LLVM_ENABLE_THREADS && config->timeTraceEnabled)
1169       timeTraceProfilerFinishThread();
1170   });
1171   finalizeLinkEditSegment();
1172   writeOutputFile();
1173 }
1174 
1175 template <class LP> void macho::writeResult() { Writer().run<LP>(); }
1176 
1177 void macho::resetWriter() { LCDylib::resetInstanceCount(); }
1178 
1179 void macho::createSyntheticSections() {
1180   in.header = make<MachHeaderSection>();
1181   if (config->dedupLiterals)
1182     in.cStringSection = make<DeduplicatedCStringSection>();
1183   else
1184     in.cStringSection = make<CStringSection>();
1185   in.wordLiteralSection =
1186       config->dedupLiterals ? make<WordLiteralSection>() : nullptr;
1187   in.rebase = make<RebaseSection>();
1188   in.binding = make<BindingSection>();
1189   in.weakBinding = make<WeakBindingSection>();
1190   in.lazyBinding = make<LazyBindingSection>();
1191   in.exports = make<ExportSection>();
1192   in.got = make<GotSection>();
1193   in.tlvPointers = make<TlvPointerSection>();
1194   in.lazyPointers = make<LazyPointerSection>();
1195   in.stubs = make<StubsSection>();
1196   in.stubHelper = make<StubHelperSection>();
1197   in.unwindInfo = makeUnwindInfoSection();
1198 
1199   // This section contains space for just a single word, and will be used by
1200   // dyld to cache an address to the image loader it uses.
1201   uint8_t *arr = bAlloc().Allocate<uint8_t>(target->wordSize);
1202   memset(arr, 0, target->wordSize);
1203   in.imageLoaderCache = makeSyntheticInputSection(
1204       segment_names::data, section_names::data, S_REGULAR,
1205       ArrayRef<uint8_t>{arr, target->wordSize},
1206       /*align=*/target->wordSize);
1207   // References from dyld are not visible to us, so ensure this section is
1208   // always treated as live.
1209   in.imageLoaderCache->live = true;
1210 }
1211 
1212 OutputSection *macho::firstTLVDataSection = nullptr;
1213 
1214 template void macho::writeResult<LP64>();
1215 template void macho::writeResult<ILP32>();
1216