xref: /llvm-project-15.0.7/lld/MachO/Writer.cpp (revision b7fd91c8)
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 "CallGraphSort.h"
11 #include "ConcatOutputSection.h"
12 #include "Config.h"
13 #include "InputFiles.h"
14 #include "InputSection.h"
15 #include "MapFile.h"
16 #include "OutputSection.h"
17 #include "OutputSegment.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     c->platform = static_cast<uint32_t>(platformInfo.target.Platform);
462     c->minos = encodeVersion(platformInfo.minimum);
463     c->sdk = encodeVersion(platformInfo.sdk);
464     c->ntools = ntools;
465     auto *t = reinterpret_cast<build_tool_version *>(&c[1]);
466     t->tool = TOOL_LD;
467     t->version = encodeVersion(VersionTuple(
468         LLVM_VERSION_MAJOR, LLVM_VERSION_MINOR, LLVM_VERSION_PATCH));
469   }
470 
471 private:
472   const PlatformInfo &platformInfo;
473 };
474 
475 // Stores a unique identifier for the output file based on an MD5 hash of its
476 // contents. In order to hash the contents, we must first write them, but
477 // LC_UUID itself must be part of the written contents in order for all the
478 // offsets to be calculated correctly. We resolve this circular paradox by
479 // first writing an LC_UUID with an all-zero UUID, then updating the UUID with
480 // its real value later.
481 class LCUuid final : public LoadCommand {
482 public:
483   uint32_t getSize() const override { return sizeof(uuid_command); }
484 
485   void writeTo(uint8_t *buf) const override {
486     auto *c = reinterpret_cast<uuid_command *>(buf);
487     c->cmd = LC_UUID;
488     c->cmdsize = getSize();
489     uuidBuf = c->uuid;
490   }
491 
492   void writeUuid(uint64_t digest) const {
493     // xxhash only gives us 8 bytes, so put some fixed data in the other half.
494     static_assert(sizeof(uuid_command::uuid) == 16, "unexpected uuid size");
495     memcpy(uuidBuf, "LLD\xa1UU1D", 8);
496     memcpy(uuidBuf + 8, &digest, 8);
497 
498     // RFC 4122 conformance. We need to fix 4 bits in byte 6 and 2 bits in
499     // byte 8. Byte 6 is already fine due to the fixed data we put in. We don't
500     // want to lose bits of the digest in byte 8, so swap that with a byte of
501     // fixed data that happens to have the right bits set.
502     std::swap(uuidBuf[3], uuidBuf[8]);
503 
504     // Claim that this is an MD5-based hash. It isn't, but this signals that
505     // this is not a time-based and not a random hash. MD5 seems like the least
506     // bad lie we can put here.
507     assert((uuidBuf[6] & 0xf0) == 0x30 && "See RFC 4122 Sections 4.2.2, 4.1.3");
508     assert((uuidBuf[8] & 0xc0) == 0x80 && "See RFC 4122 Section 4.2.2");
509   }
510 
511   mutable uint8_t *uuidBuf;
512 };
513 
514 template <class LP> class LCEncryptionInfo final : public LoadCommand {
515 public:
516   uint32_t getSize() const override {
517     return sizeof(typename LP::encryption_info_command);
518   }
519 
520   void writeTo(uint8_t *buf) const override {
521     using EncryptionInfo = typename LP::encryption_info_command;
522     auto *c = reinterpret_cast<EncryptionInfo *>(buf);
523     buf += sizeof(EncryptionInfo);
524     c->cmd = LP::encryptionInfoLCType;
525     c->cmdsize = getSize();
526     c->cryptoff = in.header->getSize();
527     auto it = find_if(outputSegments, [](const OutputSegment *seg) {
528       return seg->name == segment_names::text;
529     });
530     assert(it != outputSegments.end());
531     c->cryptsize = (*it)->fileSize - c->cryptoff;
532   }
533 };
534 
535 class LCCodeSignature final : public LoadCommand {
536 public:
537   LCCodeSignature(CodeSignatureSection *section) : section(section) {}
538 
539   uint32_t getSize() const override { return sizeof(linkedit_data_command); }
540 
541   void writeTo(uint8_t *buf) const override {
542     auto *c = reinterpret_cast<linkedit_data_command *>(buf);
543     c->cmd = LC_CODE_SIGNATURE;
544     c->cmdsize = getSize();
545     c->dataoff = static_cast<uint32_t>(section->fileOff);
546     c->datasize = section->getSize();
547   }
548 
549   CodeSignatureSection *section;
550 };
551 
552 } // namespace
553 
554 void Writer::treatSpecialUndefineds() {
555   if (config->entry)
556     if (auto *undefined = dyn_cast<Undefined>(config->entry))
557       treatUndefinedSymbol(*undefined, "the entry point");
558 
559   // FIXME: This prints symbols that are undefined both in input files and
560   // via -u flag twice.
561   for (const Symbol *sym : config->explicitUndefineds) {
562     if (const auto *undefined = dyn_cast<Undefined>(sym))
563       treatUndefinedSymbol(*undefined, "-u");
564   }
565   // Literal exported-symbol names must be defined, but glob
566   // patterns need not match.
567   for (const CachedHashStringRef &cachedName :
568        config->exportedSymbols.literals) {
569     if (const Symbol *sym = symtab->find(cachedName))
570       if (const auto *undefined = dyn_cast<Undefined>(sym))
571         treatUndefinedSymbol(*undefined, "-exported_symbol(s_list)");
572   }
573 }
574 
575 // Add stubs and bindings where necessary (e.g. if the symbol is a
576 // DylibSymbol.)
577 static void prepareBranchTarget(Symbol *sym) {
578   if (auto *dysym = dyn_cast<DylibSymbol>(sym)) {
579     if (in.stubs->addEntry(dysym)) {
580       if (sym->isWeakDef()) {
581         in.binding->addEntry(dysym, in.lazyPointers->isec,
582                              sym->stubsIndex * target->wordSize);
583         in.weakBinding->addEntry(sym, in.lazyPointers->isec,
584                                  sym->stubsIndex * target->wordSize);
585       } else {
586         in.lazyBinding->addEntry(dysym);
587       }
588     }
589   } else if (auto *defined = dyn_cast<Defined>(sym)) {
590     if (defined->isExternalWeakDef()) {
591       if (in.stubs->addEntry(sym)) {
592         in.rebase->addEntry(in.lazyPointers->isec,
593                             sym->stubsIndex * target->wordSize);
594         in.weakBinding->addEntry(sym, in.lazyPointers->isec,
595                                  sym->stubsIndex * target->wordSize);
596       }
597     }
598   } else {
599     llvm_unreachable("invalid branch target symbol type");
600   }
601 }
602 
603 // Can a symbol's address can only be resolved at runtime?
604 static bool needsBinding(const Symbol *sym) {
605   if (isa<DylibSymbol>(sym))
606     return true;
607   if (const auto *defined = dyn_cast<Defined>(sym))
608     return defined->isExternalWeakDef();
609   return false;
610 }
611 
612 static void prepareSymbolRelocation(Symbol *sym, const InputSection *isec,
613                                     const lld::macho::Reloc &r) {
614   assert(sym->isLive());
615   const RelocAttrs &relocAttrs = target->getRelocAttrs(r.type);
616 
617   if (relocAttrs.hasAttr(RelocAttrBits::BRANCH)) {
618     prepareBranchTarget(sym);
619   } else if (relocAttrs.hasAttr(RelocAttrBits::GOT)) {
620     if (relocAttrs.hasAttr(RelocAttrBits::POINTER) || needsBinding(sym))
621       in.got->addEntry(sym);
622   } else if (relocAttrs.hasAttr(RelocAttrBits::TLV)) {
623     if (needsBinding(sym))
624       in.tlvPointers->addEntry(sym);
625   } else if (relocAttrs.hasAttr(RelocAttrBits::UNSIGNED)) {
626     // References from thread-local variable sections are treated as offsets
627     // relative to the start of the referent section, and therefore have no
628     // need of rebase opcodes.
629     if (!(isThreadLocalVariables(isec->getFlags()) && isa<Defined>(sym)))
630       addNonLazyBindingEntries(sym, isec, r.offset, r.addend);
631   }
632 }
633 
634 void Writer::scanRelocations() {
635   TimeTraceScope timeScope("Scan relocations");
636 
637   // This can't use a for-each loop: It calls treatUndefinedSymbol(), which can
638   // add to inputSections, which invalidates inputSections's iterators.
639   for (size_t i = 0; i < inputSections.size(); ++i) {
640     ConcatInputSection *isec = inputSections[i];
641 
642     if (isec->shouldOmitFromOutput())
643       continue;
644 
645     for (auto it = isec->relocs.begin(); it != isec->relocs.end(); ++it) {
646       lld::macho::Reloc &r = *it;
647       if (target->hasAttr(r.type, RelocAttrBits::SUBTRAHEND)) {
648         // Skip over the following UNSIGNED relocation -- it's just there as the
649         // minuend, and doesn't have the usual UNSIGNED semantics. We don't want
650         // to emit rebase opcodes for it.
651         it++;
652         continue;
653       }
654       if (auto *sym = r.referent.dyn_cast<Symbol *>()) {
655         if (auto *undefined = dyn_cast<Undefined>(sym))
656           treatUndefinedSymbol(*undefined);
657         // treatUndefinedSymbol() can replace sym with a DylibSymbol; re-check.
658         if (!isa<Undefined>(sym) && validateSymbolRelocation(sym, isec, r))
659           prepareSymbolRelocation(sym, isec, r);
660       } else {
661         // Canonicalize the referent so that later accesses in Writer won't
662         // have to worry about it. Perhaps we should do this for Defined::isec
663         // too...
664         auto *referentIsec = r.referent.get<InputSection *>();
665         r.referent = referentIsec->canonical();
666         if (!r.pcrel)
667           in.rebase->addEntry(isec, r.offset);
668       }
669     }
670   }
671 
672   in.unwindInfo->prepareRelocations();
673 }
674 
675 void Writer::scanSymbols() {
676   TimeTraceScope timeScope("Scan symbols");
677   for (Symbol *sym : symtab->getSymbols()) {
678     if (auto *defined = dyn_cast<Defined>(sym)) {
679       if (!defined->isLive())
680         continue;
681       defined->canonicalize();
682       if (defined->overridesWeakDef)
683         in.weakBinding->addNonWeakDefinition(defined);
684       if (!defined->isAbsolute() && isCodeSection(defined->isec))
685         in.unwindInfo->addSymbol(defined);
686     } else if (const auto *dysym = dyn_cast<DylibSymbol>(sym)) {
687       // This branch intentionally doesn't check isLive().
688       if (dysym->isDynamicLookup())
689         continue;
690       dysym->getFile()->refState =
691           std::max(dysym->getFile()->refState, dysym->getRefState());
692     }
693   }
694 
695   for (const InputFile *file : inputFiles) {
696     if (auto *objFile = dyn_cast<ObjFile>(file))
697       for (Symbol *sym : objFile->symbols) {
698         if (auto *defined = dyn_cast_or_null<Defined>(sym)) {
699           if (!defined->isLive())
700             continue;
701           defined->canonicalize();
702           if (!defined->isExternal() && !defined->isAbsolute() &&
703               isCodeSection(defined->isec))
704             in.unwindInfo->addSymbol(defined);
705         }
706       }
707   }
708 }
709 
710 // TODO: ld64 enforces the old load commands in a few other cases.
711 static bool useLCBuildVersion(const PlatformInfo &platformInfo) {
712   static const std::vector<std::pair<PlatformType, VersionTuple>> minVersion = {
713       {PLATFORM_MACOS, VersionTuple(10, 14)},
714       {PLATFORM_IOS, VersionTuple(12, 0)},
715       {PLATFORM_IOSSIMULATOR, VersionTuple(13, 0)},
716       {PLATFORM_TVOS, VersionTuple(12, 0)},
717       {PLATFORM_TVOSSIMULATOR, VersionTuple(13, 0)},
718       {PLATFORM_WATCHOS, VersionTuple(5, 0)},
719       {PLATFORM_WATCHOSSIMULATOR, VersionTuple(6, 0)}};
720   auto it = llvm::find_if(minVersion, [&](const auto &p) {
721     return p.first == platformInfo.target.Platform;
722   });
723   return it == minVersion.end() ? true : platformInfo.minimum >= it->second;
724 }
725 
726 template <class LP> void Writer::createLoadCommands() {
727   uint8_t segIndex = 0;
728   for (OutputSegment *seg : outputSegments) {
729     in.header->addLoadCommand(make<LCSegment<LP>>(seg->name, seg));
730     seg->index = segIndex++;
731   }
732 
733   in.header->addLoadCommand(make<LCDyldInfo>(
734       in.rebase, in.binding, in.weakBinding, in.lazyBinding, in.exports));
735   in.header->addLoadCommand(make<LCSymtab>(symtabSection, stringTableSection));
736   in.header->addLoadCommand(
737       make<LCDysymtab>(symtabSection, indirectSymtabSection));
738   if (!config->umbrella.empty())
739     in.header->addLoadCommand(make<LCSubFramework>(config->umbrella));
740   if (config->emitEncryptionInfo)
741     in.header->addLoadCommand(make<LCEncryptionInfo<LP>>());
742   for (StringRef path : config->runtimePaths)
743     in.header->addLoadCommand(make<LCRPath>(path));
744 
745   switch (config->outputType) {
746   case MH_EXECUTE:
747     in.header->addLoadCommand(make<LCLoadDylinker>());
748     break;
749   case MH_DYLIB:
750     in.header->addLoadCommand(make<LCDylib>(LC_ID_DYLIB, config->installName,
751                                             config->dylibCompatibilityVersion,
752                                             config->dylibCurrentVersion));
753     break;
754   case MH_BUNDLE:
755     break;
756   default:
757     llvm_unreachable("unhandled output file type");
758   }
759 
760   uuidCommand = make<LCUuid>();
761   in.header->addLoadCommand(uuidCommand);
762 
763   if (useLCBuildVersion(config->platformInfo))
764     in.header->addLoadCommand(make<LCBuildVersion>(config->platformInfo));
765   else
766     in.header->addLoadCommand(make<LCMinVersion>(config->platformInfo));
767 
768   // This is down here to match ld64's load command order.
769   if (config->outputType == MH_EXECUTE)
770     in.header->addLoadCommand(make<LCMain>());
771 
772   int64_t dylibOrdinal = 1;
773   DenseMap<StringRef, int64_t> ordinalForInstallName;
774   for (InputFile *file : inputFiles) {
775     if (auto *dylibFile = dyn_cast<DylibFile>(file)) {
776       if (dylibFile->isBundleLoader) {
777         dylibFile->ordinal = BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE;
778         // Shortcut since bundle-loader does not re-export the symbols.
779 
780         dylibFile->reexport = false;
781         continue;
782       }
783 
784       // Don't emit load commands for a dylib that is not referenced if:
785       // - it was added implicitly (via a reexport, an LC_LOAD_DYLINKER --
786       //   if it's on the linker command line, it's explicit)
787       // - or it's marked MH_DEAD_STRIPPABLE_DYLIB
788       // - or the flag -dead_strip_dylibs is used
789       // FIXME: `isReferenced()` is currently computed before dead code
790       // stripping, so references from dead code keep a dylib alive. This
791       // matches ld64, but it's something we should do better.
792       if (!dylibFile->isReferenced() && !dylibFile->forceNeeded &&
793           (!dylibFile->explicitlyLinked || dylibFile->deadStrippable ||
794            config->deadStripDylibs))
795         continue;
796 
797       // Several DylibFiles can have the same installName. Only emit a single
798       // load command for that installName and give all these DylibFiles the
799       // same ordinal.
800       // This can happen in several cases:
801       // - a new framework could change its installName to an older
802       //   framework name via an $ld$ symbol depending on platform_version
803       // - symlinks (for example, libpthread.tbd is a symlink to libSystem.tbd;
804       //   Foo.framework/Foo.tbd is usually a symlink to
805       //   Foo.framework/Versions/Current/Foo.tbd, where
806       //   Foo.framework/Versions/Current is usually a symlink to
807       //   Foo.framework/Versions/A)
808       // - a framework can be linked both explicitly on the linker
809       //   command line and implicitly as a reexport from a different
810       //   framework. The re-export will usually point to the tbd file
811       //   in Foo.framework/Versions/A/Foo.tbd, while the explicit link will
812       //   usually find Foo.framework/Foo.tbd. These are usually symlinks,
813       //   but in a --reproduce archive they will be identical but distinct
814       //   files.
815       // In the first case, *semantically distinct* DylibFiles will have the
816       // same installName.
817       int64_t &ordinal = ordinalForInstallName[dylibFile->installName];
818       if (ordinal) {
819         dylibFile->ordinal = ordinal;
820         continue;
821       }
822 
823       ordinal = dylibFile->ordinal = dylibOrdinal++;
824       LoadCommandType lcType =
825           dylibFile->forceWeakImport || dylibFile->refState == RefState::Weak
826               ? LC_LOAD_WEAK_DYLIB
827               : LC_LOAD_DYLIB;
828       in.header->addLoadCommand(make<LCDylib>(lcType, dylibFile->installName,
829                                               dylibFile->compatibilityVersion,
830                                               dylibFile->currentVersion));
831 
832       if (dylibFile->reexport)
833         in.header->addLoadCommand(
834             make<LCDylib>(LC_REEXPORT_DYLIB, dylibFile->installName));
835     }
836   }
837 
838   if (functionStartsSection)
839     in.header->addLoadCommand(make<LCFunctionStarts>(functionStartsSection));
840   if (dataInCodeSection)
841     in.header->addLoadCommand(make<LCDataInCode>(dataInCodeSection));
842   if (codeSignatureSection)
843     in.header->addLoadCommand(make<LCCodeSignature>(codeSignatureSection));
844 
845   const uint32_t MACOS_MAXPATHLEN = 1024;
846   config->headerPad = std::max(
847       config->headerPad, (config->headerPadMaxInstallNames
848                               ? LCDylib::getInstanceCount() * MACOS_MAXPATHLEN
849                               : 0));
850 }
851 
852 static size_t getSymbolPriority(const SymbolPriorityEntry &entry,
853                                 const InputFile *f) {
854   // We don't use toString(InputFile *) here because it returns the full path
855   // for object files, and we only want the basename.
856   StringRef filename;
857   if (f->archiveName.empty())
858     filename = path::filename(f->getName());
859   else
860     filename = saver().save(path::filename(f->archiveName) + "(" +
861                             path::filename(f->getName()) + ")");
862   return std::max(entry.objectFiles.lookup(filename), entry.anyObjectFile);
863 }
864 
865 // Each section gets assigned the priority of the highest-priority symbol it
866 // contains.
867 static DenseMap<const InputSection *, size_t> buildInputSectionPriorities() {
868   if (config->callGraphProfileSort)
869     return computeCallGraphProfileOrder();
870   DenseMap<const InputSection *, size_t> sectionPriorities;
871 
872   if (config->priorities.empty())
873     return sectionPriorities;
874 
875   auto addSym = [&](Defined &sym) {
876     if (sym.isAbsolute())
877       return;
878 
879     auto it = config->priorities.find(sym.getName());
880     if (it == config->priorities.end())
881       return;
882 
883     SymbolPriorityEntry &entry = it->second;
884     size_t &priority = sectionPriorities[sym.isec];
885     priority =
886         std::max(priority, getSymbolPriority(entry, sym.isec->getFile()));
887   };
888 
889   // TODO: Make sure this handles weak symbols correctly.
890   for (const InputFile *file : inputFiles) {
891     if (isa<ObjFile>(file))
892       for (Symbol *sym : file->symbols)
893         if (auto *d = dyn_cast_or_null<Defined>(sym))
894           addSym(*d);
895   }
896 
897   return sectionPriorities;
898 }
899 
900 // Sorting only can happen once all outputs have been collected. Here we sort
901 // segments, output sections within each segment, and input sections within each
902 // output segment.
903 static void sortSegmentsAndSections() {
904   TimeTraceScope timeScope("Sort segments and sections");
905   sortOutputSegments();
906 
907   DenseMap<const InputSection *, size_t> isecPriorities =
908       buildInputSectionPriorities();
909 
910   uint32_t sectionIndex = 0;
911   for (OutputSegment *seg : outputSegments) {
912     seg->sortOutputSections();
913     // References from thread-local variable sections are treated as offsets
914     // relative to the start of the thread-local data memory area, which
915     // is initialized via copying all the TLV data sections (which are all
916     // contiguous). If later data sections require a greater alignment than
917     // earlier ones, the offsets of data within those sections won't be
918     // guaranteed to aligned unless we normalize alignments. We therefore use
919     // the largest alignment for all TLV data sections.
920     uint32_t tlvAlign = 0;
921     for (const OutputSection *osec : seg->getSections())
922       if (isThreadLocalData(osec->flags) && osec->align > tlvAlign)
923         tlvAlign = osec->align;
924 
925     for (OutputSection *osec : seg->getSections()) {
926       // Now that the output sections are sorted, assign the final
927       // output section indices.
928       if (!osec->isHidden())
929         osec->index = ++sectionIndex;
930       if (isThreadLocalData(osec->flags)) {
931         if (!firstTLVDataSection)
932           firstTLVDataSection = osec;
933         osec->align = tlvAlign;
934       }
935 
936       if (!isecPriorities.empty()) {
937         if (auto *merged = dyn_cast<ConcatOutputSection>(osec)) {
938           llvm::stable_sort(merged->inputs,
939                             [&](InputSection *a, InputSection *b) {
940                               return isecPriorities[a] > isecPriorities[b];
941                             });
942         }
943       }
944     }
945   }
946 }
947 
948 template <class LP> void Writer::createOutputSections() {
949   TimeTraceScope timeScope("Create output sections");
950   // First, create hidden sections
951   stringTableSection = make<StringTableSection>();
952   symtabSection = makeSymtabSection<LP>(*stringTableSection);
953   indirectSymtabSection = make<IndirectSymtabSection>();
954   if (config->adhocCodesign)
955     codeSignatureSection = make<CodeSignatureSection>();
956   if (config->emitDataInCodeInfo)
957     dataInCodeSection = make<DataInCodeSection>();
958   if (config->emitFunctionStarts)
959     functionStartsSection = make<FunctionStartsSection>();
960   if (config->emitBitcodeBundle)
961     make<BitcodeBundleSection>();
962 
963   switch (config->outputType) {
964   case MH_EXECUTE:
965     make<PageZeroSection>();
966     break;
967   case MH_DYLIB:
968   case MH_BUNDLE:
969     break;
970   default:
971     llvm_unreachable("unhandled output file type");
972   }
973 
974   // Then add input sections to output sections.
975   for (ConcatInputSection *isec : inputSections) {
976     if (isec->shouldOmitFromOutput())
977       continue;
978     ConcatOutputSection *osec = cast<ConcatOutputSection>(isec->parent);
979     osec->addInput(isec);
980     osec->inputOrder =
981         std::min(osec->inputOrder, static_cast<int>(isec->outSecOff));
982   }
983 
984   // Once all the inputs are added, we can finalize the output section
985   // properties and create the corresponding output segments.
986   for (const auto &it : concatOutputSections) {
987     StringRef segname = it.first.first;
988     ConcatOutputSection *osec = it.second;
989     assert(segname != segment_names::ld);
990     if (osec->isNeeded())
991       getOrCreateOutputSegment(segname)->addOutputSection(osec);
992   }
993 
994   for (SyntheticSection *ssec : syntheticSections) {
995     auto it = concatOutputSections.find({ssec->segname, ssec->name});
996     // We add all LinkEdit sections here because we don't know if they are
997     // needed until their finalizeContents() methods get called later. While
998     // this means that we add some redundant sections to __LINKEDIT, there is
999     // is no redundancy in the output, as we do not emit section headers for
1000     // any LinkEdit sections.
1001     if (ssec->isNeeded() || ssec->segname == segment_names::linkEdit) {
1002       if (it == concatOutputSections.end()) {
1003         getOrCreateOutputSegment(ssec->segname)->addOutputSection(ssec);
1004       } else {
1005         fatal("section from " +
1006               toString(it->second->firstSection()->getFile()) +
1007               " conflicts with synthetic section " + ssec->segname + "," +
1008               ssec->name);
1009       }
1010     }
1011   }
1012 
1013   // dyld requires __LINKEDIT segment to always exist (even if empty).
1014   linkEditSegment = getOrCreateOutputSegment(segment_names::linkEdit);
1015 }
1016 
1017 void Writer::finalizeAddresses() {
1018   TimeTraceScope timeScope("Finalize addresses");
1019   uint64_t pageSize = target->getPageSize();
1020   // Ensure that segments (and the sections they contain) are allocated
1021   // addresses in ascending order, which dyld requires.
1022   //
1023   // Note that at this point, __LINKEDIT sections are empty, but we need to
1024   // determine addresses of other segments/sections before generating its
1025   // contents.
1026   for (OutputSegment *seg : outputSegments) {
1027     if (seg == linkEditSegment)
1028       continue;
1029     seg->addr = addr;
1030     assignAddresses(seg);
1031     // codesign / libstuff checks for segment ordering by verifying that
1032     // `fileOff + fileSize == next segment fileOff`. So we call alignTo() before
1033     // (instead of after) computing fileSize to ensure that the segments are
1034     // contiguous. We handle addr / vmSize similarly for the same reason.
1035     fileOff = alignTo(fileOff, pageSize);
1036     addr = alignTo(addr, pageSize);
1037     seg->vmSize = addr - seg->addr;
1038     seg->fileSize = fileOff - seg->fileOff;
1039     seg->assignAddressesToStartEndSymbols();
1040   }
1041 }
1042 
1043 void Writer::finalizeLinkEditSegment() {
1044   TimeTraceScope timeScope("Finalize __LINKEDIT segment");
1045   // Fill __LINKEDIT contents.
1046   std::vector<LinkEditSection *> linkEditSections{
1047       in.rebase,
1048       in.binding,
1049       in.weakBinding,
1050       in.lazyBinding,
1051       in.exports,
1052       symtabSection,
1053       indirectSymtabSection,
1054       dataInCodeSection,
1055       functionStartsSection,
1056   };
1057   SmallVector<std::shared_future<void>> threadFutures;
1058   threadFutures.reserve(linkEditSections.size());
1059   for (LinkEditSection *osec : linkEditSections)
1060     if (osec)
1061       threadFutures.emplace_back(threadPool.async(
1062           [](LinkEditSection *osec) { osec->finalizeContents(); }, osec));
1063   for (std::shared_future<void> &future : threadFutures)
1064     future.wait();
1065 
1066   // Now that __LINKEDIT is filled out, do a proper calculation of its
1067   // addresses and offsets.
1068   linkEditSegment->addr = addr;
1069   assignAddresses(linkEditSegment);
1070   // No need to page-align fileOff / addr here since this is the last segment.
1071   linkEditSegment->vmSize = addr - linkEditSegment->addr;
1072   linkEditSegment->fileSize = fileOff - linkEditSegment->fileOff;
1073 }
1074 
1075 void Writer::assignAddresses(OutputSegment *seg) {
1076   seg->fileOff = fileOff;
1077 
1078   for (OutputSection *osec : seg->getSections()) {
1079     if (!osec->isNeeded())
1080       continue;
1081     addr = alignTo(addr, osec->align);
1082     fileOff = alignTo(fileOff, osec->align);
1083     osec->addr = addr;
1084     osec->fileOff = isZeroFill(osec->flags) ? 0 : fileOff;
1085     osec->finalize();
1086     osec->assignAddressesToStartEndSymbols();
1087 
1088     addr += osec->getSize();
1089     fileOff += osec->getFileSize();
1090   }
1091 }
1092 
1093 void Writer::openFile() {
1094   Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr =
1095       FileOutputBuffer::create(config->outputFile, fileOff,
1096                                FileOutputBuffer::F_executable);
1097 
1098   if (!bufferOrErr)
1099     error("failed to open " + config->outputFile + ": " +
1100           llvm::toString(bufferOrErr.takeError()));
1101   else
1102     buffer = std::move(*bufferOrErr);
1103 }
1104 
1105 void Writer::writeSections() {
1106   uint8_t *buf = buffer->getBufferStart();
1107   for (const OutputSegment *seg : outputSegments)
1108     for (const OutputSection *osec : seg->getSections())
1109       osec->writeTo(buf + osec->fileOff);
1110 }
1111 
1112 // In order to utilize multiple cores, we first split the buffer into chunks,
1113 // compute a hash for each chunk, and then compute a hash value of the hash
1114 // values.
1115 void Writer::writeUuid() {
1116   TimeTraceScope timeScope("Computing UUID");
1117 
1118   ArrayRef<uint8_t> data{buffer->getBufferStart(), buffer->getBufferEnd()};
1119   unsigned chunkCount = parallel::strategy.compute_thread_count() * 10;
1120   // Round-up integer division
1121   size_t chunkSize = (data.size() + chunkCount - 1) / chunkCount;
1122   std::vector<ArrayRef<uint8_t>> chunks = split(data, chunkSize);
1123   std::vector<uint64_t> hashes(chunks.size());
1124   SmallVector<std::shared_future<void>> threadFutures;
1125   threadFutures.reserve(chunks.size());
1126   for (size_t i = 0; i < chunks.size(); ++i)
1127     threadFutures.emplace_back(threadPool.async(
1128         [&](size_t j) { hashes[j] = xxHash64(chunks[j]); }, i));
1129   for (std::shared_future<void> &future : threadFutures)
1130     future.wait();
1131 
1132   uint64_t digest = xxHash64({reinterpret_cast<uint8_t *>(hashes.data()),
1133                               hashes.size() * sizeof(uint64_t)});
1134   uuidCommand->writeUuid(digest);
1135 }
1136 
1137 void Writer::writeCodeSignature() {
1138   if (codeSignatureSection)
1139     codeSignatureSection->writeHashes(buffer->getBufferStart());
1140 }
1141 
1142 void Writer::writeOutputFile() {
1143   TimeTraceScope timeScope("Write output file");
1144   openFile();
1145   if (errorCount())
1146     return;
1147   writeSections();
1148   writeUuid();
1149   writeCodeSignature();
1150 
1151   if (auto e = buffer->commit())
1152     error("failed to write to the output file: " + toString(std::move(e)));
1153 }
1154 
1155 template <class LP> void Writer::run() {
1156   treatSpecialUndefineds();
1157   if (config->entry && !isa<Undefined>(config->entry))
1158     prepareBranchTarget(config->entry);
1159   // Canonicalization of all pointers to InputSections should be handled by
1160   // these two methods.
1161   scanSymbols();
1162   scanRelocations();
1163 
1164   // Do not proceed if there was an undefined symbol.
1165   if (errorCount())
1166     return;
1167 
1168   if (in.stubHelper->isNeeded())
1169     in.stubHelper->setup();
1170   createOutputSections<LP>();
1171 
1172   // After this point, we create no new segments; HOWEVER, we might
1173   // yet create branch-range extension thunks for architectures whose
1174   // hardware call instructions have limited range, e.g., ARM(64).
1175   // The thunks are created as InputSections interspersed among
1176   // the ordinary __TEXT,_text InputSections.
1177   sortSegmentsAndSections();
1178   createLoadCommands<LP>();
1179   finalizeAddresses();
1180   threadPool.async([&] {
1181     if (LLVM_ENABLE_THREADS && config->timeTraceEnabled)
1182       timeTraceProfilerInitialize(config->timeTraceGranularity, "writeMapFile");
1183     writeMapFile();
1184     if (LLVM_ENABLE_THREADS && config->timeTraceEnabled)
1185       timeTraceProfilerFinishThread();
1186   });
1187   finalizeLinkEditSegment();
1188   writeOutputFile();
1189 }
1190 
1191 template <class LP> void macho::writeResult() { Writer().run<LP>(); }
1192 
1193 void macho::resetWriter() { LCDylib::resetInstanceCount(); }
1194 
1195 void macho::createSyntheticSections() {
1196   in.header = make<MachHeaderSection>();
1197   if (config->dedupLiterals) {
1198     in.cStringSection = make<DeduplicatedCStringSection>();
1199   } else {
1200     in.cStringSection = make<CStringSection>();
1201   }
1202   in.wordLiteralSection =
1203       config->dedupLiterals ? make<WordLiteralSection>() : nullptr;
1204   in.rebase = make<RebaseSection>();
1205   in.binding = make<BindingSection>();
1206   in.weakBinding = make<WeakBindingSection>();
1207   in.lazyBinding = make<LazyBindingSection>();
1208   in.exports = make<ExportSection>();
1209   in.got = make<GotSection>();
1210   in.tlvPointers = make<TlvPointerSection>();
1211   in.lazyPointers = make<LazyPointerSection>();
1212   in.stubs = make<StubsSection>();
1213   in.stubHelper = make<StubHelperSection>();
1214   in.unwindInfo = makeUnwindInfoSection();
1215 
1216   // This section contains space for just a single word, and will be used by
1217   // dyld to cache an address to the image loader it uses.
1218   uint8_t *arr = bAlloc().Allocate<uint8_t>(target->wordSize);
1219   memset(arr, 0, target->wordSize);
1220   in.imageLoaderCache = make<ConcatInputSection>(
1221       segment_names::data, section_names::data, /*file=*/nullptr,
1222       ArrayRef<uint8_t>{arr, target->wordSize},
1223       /*align=*/target->wordSize, /*flags=*/S_REGULAR);
1224   // References from dyld are not visible to us, so ensure this section is
1225   // always treated as live.
1226   in.imageLoaderCache->live = true;
1227 }
1228 
1229 OutputSection *macho::firstTLVDataSection = nullptr;
1230 
1231 template void macho::writeResult<LP64>();
1232 template void macho::writeResult<ILP32>();
1233