xref: /freebsd/contrib/llvm-project/lld/MachO/InputFiles.cpp (revision 7ef62cebc2f965b0f640263e179276928885e33d)
1 //===- InputFiles.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 // This file contains functions to parse Mach-O object files. In this comment,
10 // we describe the Mach-O file structure and how we parse it.
11 //
12 // Mach-O is not very different from ELF or COFF. The notion of symbols,
13 // sections and relocations exists in Mach-O as it does in ELF and COFF.
14 //
15 // Perhaps the notion that is new to those who know ELF/COFF is "subsections".
16 // In ELF/COFF, sections are an atomic unit of data copied from input files to
17 // output files. When we merge or garbage-collect sections, we treat each
18 // section as an atomic unit. In Mach-O, that's not the case. Sections can
19 // consist of multiple subsections, and subsections are a unit of merging and
20 // garbage-collecting. Therefore, Mach-O's subsections are more similar to
21 // ELF/COFF's sections than Mach-O's sections are.
22 //
23 // A section can have multiple symbols. A symbol that does not have the
24 // N_ALT_ENTRY attribute indicates a beginning of a subsection. Therefore, by
25 // definition, a symbol is always present at the beginning of each subsection. A
26 // symbol with N_ALT_ENTRY attribute does not start a new subsection and can
27 // point to a middle of a subsection.
28 //
29 // The notion of subsections also affects how relocations are represented in
30 // Mach-O. All references within a section need to be explicitly represented as
31 // relocations if they refer to different subsections, because we obviously need
32 // to fix up addresses if subsections are laid out in an output file differently
33 // than they were in object files. To represent that, Mach-O relocations can
34 // refer to an unnamed location via its address. Scattered relocations (those
35 // with the R_SCATTERED bit set) always refer to unnamed locations.
36 // Non-scattered relocations refer to an unnamed location if r_extern is not set
37 // and r_symbolnum is zero.
38 //
39 // Without the above differences, I think you can use your knowledge about ELF
40 // and COFF for Mach-O.
41 //
42 //===----------------------------------------------------------------------===//
43 
44 #include "InputFiles.h"
45 #include "Config.h"
46 #include "Driver.h"
47 #include "Dwarf.h"
48 #include "EhFrame.h"
49 #include "ExportTrie.h"
50 #include "InputSection.h"
51 #include "MachOStructs.h"
52 #include "ObjC.h"
53 #include "OutputSection.h"
54 #include "OutputSegment.h"
55 #include "SymbolTable.h"
56 #include "Symbols.h"
57 #include "SyntheticSections.h"
58 #include "Target.h"
59 
60 #include "lld/Common/CommonLinkerContext.h"
61 #include "lld/Common/DWARF.h"
62 #include "lld/Common/Reproduce.h"
63 #include "llvm/ADT/iterator.h"
64 #include "llvm/BinaryFormat/MachO.h"
65 #include "llvm/LTO/LTO.h"
66 #include "llvm/Support/BinaryStreamReader.h"
67 #include "llvm/Support/Endian.h"
68 #include "llvm/Support/LEB128.h"
69 #include "llvm/Support/MemoryBuffer.h"
70 #include "llvm/Support/Path.h"
71 #include "llvm/Support/TarWriter.h"
72 #include "llvm/Support/TimeProfiler.h"
73 #include "llvm/TextAPI/Architecture.h"
74 #include "llvm/TextAPI/InterfaceFile.h"
75 
76 #include <optional>
77 #include <type_traits>
78 
79 using namespace llvm;
80 using namespace llvm::MachO;
81 using namespace llvm::support::endian;
82 using namespace llvm::sys;
83 using namespace lld;
84 using namespace lld::macho;
85 
86 // Returns "<internal>", "foo.a(bar.o)", or "baz.o".
87 std::string lld::toString(const InputFile *f) {
88   if (!f)
89     return "<internal>";
90 
91   // Multiple dylibs can be defined in one .tbd file.
92   if (auto dylibFile = dyn_cast<DylibFile>(f))
93     if (f->getName().endswith(".tbd"))
94       return (f->getName() + "(" + dylibFile->installName + ")").str();
95 
96   if (f->archiveName.empty())
97     return std::string(f->getName());
98   return (f->archiveName + "(" + path::filename(f->getName()) + ")").str();
99 }
100 
101 std::string lld::toString(const Section &sec) {
102   return (toString(sec.file) + ":(" + sec.name + ")").str();
103 }
104 
105 SetVector<InputFile *> macho::inputFiles;
106 std::unique_ptr<TarWriter> macho::tar;
107 int InputFile::idCount = 0;
108 
109 static VersionTuple decodeVersion(uint32_t version) {
110   unsigned major = version >> 16;
111   unsigned minor = (version >> 8) & 0xffu;
112   unsigned subMinor = version & 0xffu;
113   return VersionTuple(major, minor, subMinor);
114 }
115 
116 static std::vector<PlatformInfo> getPlatformInfos(const InputFile *input) {
117   if (!isa<ObjFile>(input) && !isa<DylibFile>(input))
118     return {};
119 
120   const char *hdr = input->mb.getBufferStart();
121 
122   // "Zippered" object files can have multiple LC_BUILD_VERSION load commands.
123   std::vector<PlatformInfo> platformInfos;
124   for (auto *cmd : findCommands<build_version_command>(hdr, LC_BUILD_VERSION)) {
125     PlatformInfo info;
126     info.target.Platform = static_cast<PlatformType>(cmd->platform);
127     info.minimum = decodeVersion(cmd->minos);
128     platformInfos.emplace_back(std::move(info));
129   }
130   for (auto *cmd : findCommands<version_min_command>(
131            hdr, LC_VERSION_MIN_MACOSX, LC_VERSION_MIN_IPHONEOS,
132            LC_VERSION_MIN_TVOS, LC_VERSION_MIN_WATCHOS)) {
133     PlatformInfo info;
134     switch (cmd->cmd) {
135     case LC_VERSION_MIN_MACOSX:
136       info.target.Platform = PLATFORM_MACOS;
137       break;
138     case LC_VERSION_MIN_IPHONEOS:
139       info.target.Platform = PLATFORM_IOS;
140       break;
141     case LC_VERSION_MIN_TVOS:
142       info.target.Platform = PLATFORM_TVOS;
143       break;
144     case LC_VERSION_MIN_WATCHOS:
145       info.target.Platform = PLATFORM_WATCHOS;
146       break;
147     }
148     info.minimum = decodeVersion(cmd->version);
149     platformInfos.emplace_back(std::move(info));
150   }
151 
152   return platformInfos;
153 }
154 
155 static bool checkCompatibility(const InputFile *input) {
156   std::vector<PlatformInfo> platformInfos = getPlatformInfos(input);
157   if (platformInfos.empty())
158     return true;
159 
160   auto it = find_if(platformInfos, [&](const PlatformInfo &info) {
161     return removeSimulator(info.target.Platform) ==
162            removeSimulator(config->platform());
163   });
164   if (it == platformInfos.end()) {
165     std::string platformNames;
166     raw_string_ostream os(platformNames);
167     interleave(
168         platformInfos, os,
169         [&](const PlatformInfo &info) {
170           os << getPlatformName(info.target.Platform);
171         },
172         "/");
173     error(toString(input) + " has platform " + platformNames +
174           Twine(", which is different from target platform ") +
175           getPlatformName(config->platform()));
176     return false;
177   }
178 
179   if (it->minimum > config->platformInfo.minimum)
180     warn(toString(input) + " has version " + it->minimum.getAsString() +
181          ", which is newer than target minimum of " +
182          config->platformInfo.minimum.getAsString());
183 
184   return true;
185 }
186 
187 // This cache mostly exists to store system libraries (and .tbds) as they're
188 // loaded, rather than the input archives, which are already cached at a higher
189 // level, and other files like the filelist that are only read once.
190 // Theoretically this caching could be more efficient by hoisting it, but that
191 // would require altering many callers to track the state.
192 DenseMap<CachedHashStringRef, MemoryBufferRef> macho::cachedReads;
193 // Open a given file path and return it as a memory-mapped file.
194 std::optional<MemoryBufferRef> macho::readFile(StringRef path) {
195   CachedHashStringRef key(path);
196   auto entry = cachedReads.find(key);
197   if (entry != cachedReads.end())
198     return entry->second;
199 
200   ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr = MemoryBuffer::getFile(path);
201   if (std::error_code ec = mbOrErr.getError()) {
202     error("cannot open " + path + ": " + ec.message());
203     return std::nullopt;
204   }
205 
206   std::unique_ptr<MemoryBuffer> &mb = *mbOrErr;
207   MemoryBufferRef mbref = mb->getMemBufferRef();
208   make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take mb ownership
209 
210   // If this is a regular non-fat file, return it.
211   const char *buf = mbref.getBufferStart();
212   const auto *hdr = reinterpret_cast<const fat_header *>(buf);
213   if (mbref.getBufferSize() < sizeof(uint32_t) ||
214       read32be(&hdr->magic) != FAT_MAGIC) {
215     if (tar)
216       tar->append(relativeToRoot(path), mbref.getBuffer());
217     return cachedReads[key] = mbref;
218   }
219 
220   llvm::BumpPtrAllocator &bAlloc = lld::bAlloc();
221 
222   // Object files and archive files may be fat files, which contain multiple
223   // real files for different CPU ISAs. Here, we search for a file that matches
224   // with the current link target and returns it as a MemoryBufferRef.
225   const auto *arch = reinterpret_cast<const fat_arch *>(buf + sizeof(*hdr));
226   auto getArchName = [](uint32_t cpuType, uint32_t cpuSubtype) {
227     return getArchitectureName(getArchitectureFromCpuType(cpuType, cpuSubtype));
228   };
229 
230   std::vector<StringRef> archs;
231   for (uint32_t i = 0, n = read32be(&hdr->nfat_arch); i < n; ++i) {
232     if (reinterpret_cast<const char *>(arch + i + 1) >
233         buf + mbref.getBufferSize()) {
234       error(path + ": fat_arch struct extends beyond end of file");
235       return std::nullopt;
236     }
237 
238     uint32_t cpuType = read32be(&arch[i].cputype);
239     uint32_t cpuSubtype =
240         read32be(&arch[i].cpusubtype) & ~MachO::CPU_SUBTYPE_MASK;
241 
242     // FIXME: LD64 has a more complex fallback logic here.
243     // Consider implementing that as well?
244     if (cpuType != static_cast<uint32_t>(target->cpuType) ||
245         cpuSubtype != target->cpuSubtype) {
246       archs.emplace_back(getArchName(cpuType, cpuSubtype));
247       continue;
248     }
249 
250     uint32_t offset = read32be(&arch[i].offset);
251     uint32_t size = read32be(&arch[i].size);
252     if (offset + size > mbref.getBufferSize())
253       error(path + ": slice extends beyond end of file");
254     if (tar)
255       tar->append(relativeToRoot(path), mbref.getBuffer());
256     return cachedReads[key] = MemoryBufferRef(StringRef(buf + offset, size),
257                                               path.copy(bAlloc));
258   }
259 
260   auto targetArchName = getArchName(target->cpuType, target->cpuSubtype);
261   warn(path + ": ignoring file because it is universal (" + join(archs, ",") +
262        ") but does not contain the " + targetArchName + " architecture");
263   return std::nullopt;
264 }
265 
266 InputFile::InputFile(Kind kind, const InterfaceFile &interface)
267     : id(idCount++), fileKind(kind), name(saver().save(interface.getPath())) {}
268 
269 // Some sections comprise of fixed-size records, so instead of splitting them at
270 // symbol boundaries, we split them based on size. Records are distinct from
271 // literals in that they may contain references to other sections, instead of
272 // being leaf nodes in the InputSection graph.
273 //
274 // Note that "record" is a term I came up with. In contrast, "literal" is a term
275 // used by the Mach-O format.
276 static std::optional<size_t> getRecordSize(StringRef segname, StringRef name) {
277   if (name == section_names::compactUnwind) {
278     if (segname == segment_names::ld)
279       return target->wordSize == 8 ? 32 : 20;
280   }
281   if (!config->dedupStrings)
282     return {};
283 
284   if (name == section_names::cfString && segname == segment_names::data)
285     return target->wordSize == 8 ? 32 : 16;
286 
287   if (config->icfLevel == ICFLevel::none)
288     return {};
289 
290   if (name == section_names::objcClassRefs && segname == segment_names::data)
291     return target->wordSize;
292 
293   if (name == section_names::objcSelrefs && segname == segment_names::data)
294     return target->wordSize;
295   return {};
296 }
297 
298 static Error parseCallGraph(ArrayRef<uint8_t> data,
299                             std::vector<CallGraphEntry> &callGraph) {
300   TimeTraceScope timeScope("Parsing call graph section");
301   BinaryStreamReader reader(data, support::little);
302   while (!reader.empty()) {
303     uint32_t fromIndex, toIndex;
304     uint64_t count;
305     if (Error err = reader.readInteger(fromIndex))
306       return err;
307     if (Error err = reader.readInteger(toIndex))
308       return err;
309     if (Error err = reader.readInteger(count))
310       return err;
311     callGraph.emplace_back(fromIndex, toIndex, count);
312   }
313   return Error::success();
314 }
315 
316 // Parse the sequence of sections within a single LC_SEGMENT(_64).
317 // Split each section into subsections.
318 template <class SectionHeader>
319 void ObjFile::parseSections(ArrayRef<SectionHeader> sectionHeaders) {
320   sections.reserve(sectionHeaders.size());
321   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
322 
323   for (const SectionHeader &sec : sectionHeaders) {
324     StringRef name =
325         StringRef(sec.sectname, strnlen(sec.sectname, sizeof(sec.sectname)));
326     StringRef segname =
327         StringRef(sec.segname, strnlen(sec.segname, sizeof(sec.segname)));
328     sections.push_back(make<Section>(this, segname, name, sec.flags, sec.addr));
329     if (sec.align >= 32) {
330       error("alignment " + std::to_string(sec.align) + " of section " + name +
331             " is too large");
332       continue;
333     }
334     Section &section = *sections.back();
335     uint32_t align = 1 << sec.align;
336     ArrayRef<uint8_t> data = {isZeroFill(sec.flags) ? nullptr
337                                                     : buf + sec.offset,
338                               static_cast<size_t>(sec.size)};
339 
340     auto splitRecords = [&](size_t recordSize) -> void {
341       if (data.empty())
342         return;
343       Subsections &subsections = section.subsections;
344       subsections.reserve(data.size() / recordSize);
345       for (uint64_t off = 0; off < data.size(); off += recordSize) {
346         auto *isec = make<ConcatInputSection>(
347             section, data.slice(off, std::min(data.size(), recordSize)), align);
348         subsections.push_back({off, isec});
349       }
350       section.doneSplitting = true;
351     };
352 
353     if (sectionType(sec.flags) == S_CSTRING_LITERALS) {
354       if (sec.nreloc)
355         fatal(toString(this) + ": " + sec.segname + "," + sec.sectname +
356               " contains relocations, which is unsupported");
357       bool dedupLiterals =
358           name == section_names::objcMethname || config->dedupStrings;
359       InputSection *isec =
360           make<CStringInputSection>(section, data, align, dedupLiterals);
361       // FIXME: parallelize this?
362       cast<CStringInputSection>(isec)->splitIntoPieces();
363       section.subsections.push_back({0, isec});
364     } else if (isWordLiteralSection(sec.flags)) {
365       if (sec.nreloc)
366         fatal(toString(this) + ": " + sec.segname + "," + sec.sectname +
367               " contains relocations, which is unsupported");
368       InputSection *isec = make<WordLiteralInputSection>(section, data, align);
369       section.subsections.push_back({0, isec});
370     } else if (auto recordSize = getRecordSize(segname, name)) {
371       splitRecords(*recordSize);
372     } else if (name == section_names::ehFrame &&
373                segname == segment_names::text) {
374       splitEhFrames(data, *sections.back());
375     } else if (segname == segment_names::llvm) {
376       if (config->callGraphProfileSort && name == section_names::cgProfile)
377         checkError(parseCallGraph(data, callGraph));
378       // ld64 does not appear to emit contents from sections within the __LLVM
379       // segment. Symbols within those sections point to bitcode metadata
380       // instead of actual symbols. Global symbols within those sections could
381       // have the same name without causing duplicate symbol errors. To avoid
382       // spurious duplicate symbol errors, we do not parse these sections.
383       // TODO: Evaluate whether the bitcode metadata is needed.
384     } else if (name == section_names::objCImageInfo &&
385                segname == segment_names::data) {
386       objCImageInfo = data;
387     } else {
388       if (name == section_names::addrSig)
389         addrSigSection = sections.back();
390 
391       auto *isec = make<ConcatInputSection>(section, data, align);
392       if (isDebugSection(isec->getFlags()) &&
393           isec->getSegName() == segment_names::dwarf) {
394         // Instead of emitting DWARF sections, we emit STABS symbols to the
395         // object files that contain them. We filter them out early to avoid
396         // parsing their relocations unnecessarily.
397         debugSections.push_back(isec);
398       } else {
399         section.subsections.push_back({0, isec});
400       }
401     }
402   }
403 }
404 
405 void ObjFile::splitEhFrames(ArrayRef<uint8_t> data, Section &ehFrameSection) {
406   EhReader reader(this, data, /*dataOff=*/0);
407   size_t off = 0;
408   while (off < reader.size()) {
409     uint64_t frameOff = off;
410     uint64_t length = reader.readLength(&off);
411     if (length == 0)
412       break;
413     uint64_t fullLength = length + (off - frameOff);
414     off += length;
415     // We hard-code an alignment of 1 here because we don't actually want our
416     // EH frames to be aligned to the section alignment. EH frame decoders don't
417     // expect this alignment. Moreover, each EH frame must start where the
418     // previous one ends, and where it ends is indicated by the length field.
419     // Unless we update the length field (troublesome), we should keep the
420     // alignment to 1.
421     // Note that we still want to preserve the alignment of the overall section,
422     // just not of the individual EH frames.
423     ehFrameSection.subsections.push_back(
424         {frameOff, make<ConcatInputSection>(ehFrameSection,
425                                             data.slice(frameOff, fullLength),
426                                             /*align=*/1)});
427   }
428   ehFrameSection.doneSplitting = true;
429 }
430 
431 template <class T>
432 static Section *findContainingSection(const std::vector<Section *> &sections,
433                                       T *offset) {
434   static_assert(std::is_same<uint64_t, T>::value ||
435                     std::is_same<uint32_t, T>::value,
436                 "unexpected type for offset");
437   auto it = std::prev(llvm::upper_bound(
438       sections, *offset,
439       [](uint64_t value, const Section *sec) { return value < sec->addr; }));
440   *offset -= (*it)->addr;
441   return *it;
442 }
443 
444 // Find the subsection corresponding to the greatest section offset that is <=
445 // that of the given offset.
446 //
447 // offset: an offset relative to the start of the original InputSection (before
448 // any subsection splitting has occurred). It will be updated to represent the
449 // same location as an offset relative to the start of the containing
450 // subsection.
451 template <class T>
452 static InputSection *findContainingSubsection(const Section &section,
453                                               T *offset) {
454   static_assert(std::is_same<uint64_t, T>::value ||
455                     std::is_same<uint32_t, T>::value,
456                 "unexpected type for offset");
457   auto it = std::prev(llvm::upper_bound(
458       section.subsections, *offset,
459       [](uint64_t value, Subsection subsec) { return value < subsec.offset; }));
460   *offset -= it->offset;
461   return it->isec;
462 }
463 
464 // Find a symbol at offset `off` within `isec`.
465 static Defined *findSymbolAtOffset(const ConcatInputSection *isec,
466                                    uint64_t off) {
467   auto it = llvm::lower_bound(isec->symbols, off, [](Defined *d, uint64_t off) {
468     return d->value < off;
469   });
470   // The offset should point at the exact address of a symbol (with no addend.)
471   if (it == isec->symbols.end() || (*it)->value != off) {
472     assert(isec->wasCoalesced);
473     return nullptr;
474   }
475   return *it;
476 }
477 
478 template <class SectionHeader>
479 static bool validateRelocationInfo(InputFile *file, const SectionHeader &sec,
480                                    relocation_info rel) {
481   const RelocAttrs &relocAttrs = target->getRelocAttrs(rel.r_type);
482   bool valid = true;
483   auto message = [relocAttrs, file, sec, rel, &valid](const Twine &diagnostic) {
484     valid = false;
485     return (relocAttrs.name + " relocation " + diagnostic + " at offset " +
486             std::to_string(rel.r_address) + " of " + sec.segname + "," +
487             sec.sectname + " in " + toString(file))
488         .str();
489   };
490 
491   if (!relocAttrs.hasAttr(RelocAttrBits::LOCAL) && !rel.r_extern)
492     error(message("must be extern"));
493   if (relocAttrs.hasAttr(RelocAttrBits::PCREL) != rel.r_pcrel)
494     error(message(Twine("must ") + (rel.r_pcrel ? "not " : "") +
495                   "be PC-relative"));
496   if (isThreadLocalVariables(sec.flags) &&
497       !relocAttrs.hasAttr(RelocAttrBits::UNSIGNED))
498     error(message("not allowed in thread-local section, must be UNSIGNED"));
499   if (rel.r_length < 2 || rel.r_length > 3 ||
500       !relocAttrs.hasAttr(static_cast<RelocAttrBits>(1 << rel.r_length))) {
501     static SmallVector<StringRef, 4> widths{"0", "4", "8", "4 or 8"};
502     error(message("has width " + std::to_string(1 << rel.r_length) +
503                   " bytes, but must be " +
504                   widths[(static_cast<int>(relocAttrs.bits) >> 2) & 3] +
505                   " bytes"));
506   }
507   return valid;
508 }
509 
510 template <class SectionHeader>
511 void ObjFile::parseRelocations(ArrayRef<SectionHeader> sectionHeaders,
512                                const SectionHeader &sec, Section &section) {
513   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
514   ArrayRef<relocation_info> relInfos(
515       reinterpret_cast<const relocation_info *>(buf + sec.reloff), sec.nreloc);
516 
517   Subsections &subsections = section.subsections;
518   auto subsecIt = subsections.rbegin();
519   for (size_t i = 0; i < relInfos.size(); i++) {
520     // Paired relocations serve as Mach-O's method for attaching a
521     // supplemental datum to a primary relocation record. ELF does not
522     // need them because the *_RELOC_RELA records contain the extra
523     // addend field, vs. *_RELOC_REL which omit the addend.
524     //
525     // The {X86_64,ARM64}_RELOC_SUBTRACTOR record holds the subtrahend,
526     // and the paired *_RELOC_UNSIGNED record holds the minuend. The
527     // datum for each is a symbolic address. The result is the offset
528     // between two addresses.
529     //
530     // The ARM64_RELOC_ADDEND record holds the addend, and the paired
531     // ARM64_RELOC_BRANCH26 or ARM64_RELOC_PAGE21/PAGEOFF12 holds the
532     // base symbolic address.
533     //
534     // Note: X86 does not use *_RELOC_ADDEND because it can embed an addend into
535     // the instruction stream. On X86, a relocatable address field always
536     // occupies an entire contiguous sequence of byte(s), so there is no need to
537     // merge opcode bits with address bits. Therefore, it's easy and convenient
538     // to store addends in the instruction-stream bytes that would otherwise
539     // contain zeroes. By contrast, RISC ISAs such as ARM64 mix opcode bits with
540     // address bits so that bitwise arithmetic is necessary to extract and
541     // insert them. Storing addends in the instruction stream is possible, but
542     // inconvenient and more costly at link time.
543 
544     relocation_info relInfo = relInfos[i];
545     bool isSubtrahend =
546         target->hasAttr(relInfo.r_type, RelocAttrBits::SUBTRAHEND);
547     int64_t pairedAddend = 0;
548     if (target->hasAttr(relInfo.r_type, RelocAttrBits::ADDEND)) {
549       pairedAddend = SignExtend64<24>(relInfo.r_symbolnum);
550       relInfo = relInfos[++i];
551     }
552     assert(i < relInfos.size());
553     if (!validateRelocationInfo(this, sec, relInfo))
554       continue;
555     if (relInfo.r_address & R_SCATTERED)
556       fatal("TODO: Scattered relocations not supported");
557 
558     int64_t embeddedAddend = target->getEmbeddedAddend(mb, sec.offset, relInfo);
559     assert(!(embeddedAddend && pairedAddend));
560     int64_t totalAddend = pairedAddend + embeddedAddend;
561     Reloc r;
562     r.type = relInfo.r_type;
563     r.pcrel = relInfo.r_pcrel;
564     r.length = relInfo.r_length;
565     r.offset = relInfo.r_address;
566     if (relInfo.r_extern) {
567       r.referent = symbols[relInfo.r_symbolnum];
568       r.addend = isSubtrahend ? 0 : totalAddend;
569     } else {
570       assert(!isSubtrahend);
571       const SectionHeader &referentSecHead =
572           sectionHeaders[relInfo.r_symbolnum - 1];
573       uint64_t referentOffset;
574       if (relInfo.r_pcrel) {
575         // The implicit addend for pcrel section relocations is the pcrel offset
576         // in terms of the addresses in the input file. Here we adjust it so
577         // that it describes the offset from the start of the referent section.
578         // FIXME This logic was written around x86_64 behavior -- ARM64 doesn't
579         // have pcrel section relocations. We may want to factor this out into
580         // the arch-specific .cpp file.
581         assert(target->hasAttr(r.type, RelocAttrBits::BYTE4));
582         referentOffset = sec.addr + relInfo.r_address + 4 + totalAddend -
583                          referentSecHead.addr;
584       } else {
585         // The addend for a non-pcrel relocation is its absolute address.
586         referentOffset = totalAddend - referentSecHead.addr;
587       }
588       r.referent = findContainingSubsection(*sections[relInfo.r_symbolnum - 1],
589                                             &referentOffset);
590       r.addend = referentOffset;
591     }
592 
593     // Find the subsection that this relocation belongs to.
594     // Though not required by the Mach-O format, clang and gcc seem to emit
595     // relocations in order, so let's take advantage of it. However, ld64 emits
596     // unsorted relocations (in `-r` mode), so we have a fallback for that
597     // uncommon case.
598     InputSection *subsec;
599     while (subsecIt != subsections.rend() && subsecIt->offset > r.offset)
600       ++subsecIt;
601     if (subsecIt == subsections.rend() ||
602         subsecIt->offset + subsecIt->isec->getSize() <= r.offset) {
603       subsec = findContainingSubsection(section, &r.offset);
604       // Now that we know the relocs are unsorted, avoid trying the 'fast path'
605       // for the other relocations.
606       subsecIt = subsections.rend();
607     } else {
608       subsec = subsecIt->isec;
609       r.offset -= subsecIt->offset;
610     }
611     subsec->relocs.push_back(r);
612 
613     if (isSubtrahend) {
614       relocation_info minuendInfo = relInfos[++i];
615       // SUBTRACTOR relocations should always be followed by an UNSIGNED one
616       // attached to the same address.
617       assert(target->hasAttr(minuendInfo.r_type, RelocAttrBits::UNSIGNED) &&
618              relInfo.r_address == minuendInfo.r_address);
619       Reloc p;
620       p.type = minuendInfo.r_type;
621       if (minuendInfo.r_extern) {
622         p.referent = symbols[minuendInfo.r_symbolnum];
623         p.addend = totalAddend;
624       } else {
625         uint64_t referentOffset =
626             totalAddend - sectionHeaders[minuendInfo.r_symbolnum - 1].addr;
627         p.referent = findContainingSubsection(
628             *sections[minuendInfo.r_symbolnum - 1], &referentOffset);
629         p.addend = referentOffset;
630       }
631       subsec->relocs.push_back(p);
632     }
633   }
634 }
635 
636 // Symbols with `l` or `L` as a prefix are linker-private and never appear in
637 // the output.
638 static bool isPrivateLabel(StringRef name) {
639   return name.startswith("l") || name.startswith("L");
640 }
641 
642 template <class NList>
643 static macho::Symbol *createDefined(const NList &sym, StringRef name,
644                                     InputSection *isec, uint64_t value,
645                                     uint64_t size, bool forceHidden) {
646   // Symbol scope is determined by sym.n_type & (N_EXT | N_PEXT):
647   // N_EXT: Global symbols. These go in the symbol table during the link,
648   //        and also in the export table of the output so that the dynamic
649   //        linker sees them.
650   // N_EXT | N_PEXT: Linkage unit (think: dylib) scoped. These go in the
651   //                 symbol table during the link so that duplicates are
652   //                 either reported (for non-weak symbols) or merged
653   //                 (for weak symbols), but they do not go in the export
654   //                 table of the output.
655   // N_PEXT: llvm-mc does not emit these, but `ld -r` (wherein ld64 emits
656   //         object files) may produce them. LLD does not yet support -r.
657   //         These are translation-unit scoped, identical to the `0` case.
658   // 0: Translation-unit scoped. These are not in the symbol table during
659   //    link, and not in the export table of the output either.
660   bool isWeakDefCanBeHidden =
661       (sym.n_desc & (N_WEAK_DEF | N_WEAK_REF)) == (N_WEAK_DEF | N_WEAK_REF);
662 
663   if (sym.n_type & N_EXT) {
664     // -load_hidden makes us treat global symbols as linkage unit scoped.
665     // Duplicates are reported but the symbol does not go in the export trie.
666     bool isPrivateExtern = sym.n_type & N_PEXT || forceHidden;
667 
668     // lld's behavior for merging symbols is slightly different from ld64:
669     // ld64 picks the winning symbol based on several criteria (see
670     // pickBetweenRegularAtoms() in ld64's SymbolTable.cpp), while lld
671     // just merges metadata and keeps the contents of the first symbol
672     // with that name (see SymbolTable::addDefined). For:
673     // * inline function F in a TU built with -fvisibility-inlines-hidden
674     // * and inline function F in another TU built without that flag
675     // ld64 will pick the one from the file built without
676     // -fvisibility-inlines-hidden.
677     // lld will instead pick the one listed first on the link command line and
678     // give it visibility as if the function was built without
679     // -fvisibility-inlines-hidden.
680     // If both functions have the same contents, this will have the same
681     // behavior. If not, it won't, but the input had an ODR violation in
682     // that case.
683     //
684     // Similarly, merging a symbol
685     // that's isPrivateExtern and not isWeakDefCanBeHidden with one
686     // that's not isPrivateExtern but isWeakDefCanBeHidden technically
687     // should produce one
688     // that's not isPrivateExtern but isWeakDefCanBeHidden. That matters
689     // with ld64's semantics, because it means the non-private-extern
690     // definition will continue to take priority if more private extern
691     // definitions are encountered. With lld's semantics there's no observable
692     // difference between a symbol that's isWeakDefCanBeHidden(autohide) or one
693     // that's privateExtern -- neither makes it into the dynamic symbol table,
694     // unless the autohide symbol is explicitly exported.
695     // But if a symbol is both privateExtern and autohide then it can't
696     // be exported.
697     // So we nullify the autohide flag when privateExtern is present
698     // and promote the symbol to privateExtern when it is not already.
699     if (isWeakDefCanBeHidden && isPrivateExtern)
700       isWeakDefCanBeHidden = false;
701     else if (isWeakDefCanBeHidden)
702       isPrivateExtern = true;
703     return symtab->addDefined(
704         name, isec->getFile(), isec, value, size, sym.n_desc & N_WEAK_DEF,
705         isPrivateExtern, sym.n_desc & N_ARM_THUMB_DEF,
706         sym.n_desc & REFERENCED_DYNAMICALLY, sym.n_desc & N_NO_DEAD_STRIP,
707         isWeakDefCanBeHidden);
708   }
709   bool includeInSymtab = !isPrivateLabel(name) && !isEhFrameSection(isec);
710   return make<Defined>(
711       name, isec->getFile(), isec, value, size, sym.n_desc & N_WEAK_DEF,
712       /*isExternal=*/false, /*isPrivateExtern=*/false, includeInSymtab,
713       sym.n_desc & N_ARM_THUMB_DEF, sym.n_desc & REFERENCED_DYNAMICALLY,
714       sym.n_desc & N_NO_DEAD_STRIP);
715 }
716 
717 // Absolute symbols are defined symbols that do not have an associated
718 // InputSection. They cannot be weak.
719 template <class NList>
720 static macho::Symbol *createAbsolute(const NList &sym, InputFile *file,
721                                      StringRef name, bool forceHidden) {
722   if (sym.n_type & N_EXT) {
723     bool isPrivateExtern = sym.n_type & N_PEXT || forceHidden;
724     return symtab->addDefined(
725         name, file, nullptr, sym.n_value, /*size=*/0,
726         /*isWeakDef=*/false, isPrivateExtern, sym.n_desc & N_ARM_THUMB_DEF,
727         /*isReferencedDynamically=*/false, sym.n_desc & N_NO_DEAD_STRIP,
728         /*isWeakDefCanBeHidden=*/false);
729   }
730   return make<Defined>(name, file, nullptr, sym.n_value, /*size=*/0,
731                        /*isWeakDef=*/false,
732                        /*isExternal=*/false, /*isPrivateExtern=*/false,
733                        /*includeInSymtab=*/true, sym.n_desc & N_ARM_THUMB_DEF,
734                        /*isReferencedDynamically=*/false,
735                        sym.n_desc & N_NO_DEAD_STRIP);
736 }
737 
738 template <class NList>
739 macho::Symbol *ObjFile::parseNonSectionSymbol(const NList &sym,
740                                               const char *strtab) {
741   StringRef name = StringRef(strtab + sym.n_strx);
742   uint8_t type = sym.n_type & N_TYPE;
743   bool isPrivateExtern = sym.n_type & N_PEXT || forceHidden;
744   switch (type) {
745   case N_UNDF:
746     return sym.n_value == 0
747                ? symtab->addUndefined(name, this, sym.n_desc & N_WEAK_REF)
748                : symtab->addCommon(name, this, sym.n_value,
749                                    1 << GET_COMM_ALIGN(sym.n_desc),
750                                    isPrivateExtern);
751   case N_ABS:
752     return createAbsolute(sym, this, name, forceHidden);
753   case N_INDR: {
754     // Not much point in making local aliases -- relocs in the current file can
755     // just refer to the actual symbol itself. ld64 ignores these symbols too.
756     if (!(sym.n_type & N_EXT))
757       return nullptr;
758     StringRef aliasedName = StringRef(strtab + sym.n_value);
759     // isPrivateExtern is the only symbol flag that has an impact on the final
760     // aliased symbol.
761     auto alias = make<AliasSymbol>(this, name, aliasedName, isPrivateExtern);
762     aliases.push_back(alias);
763     return alias;
764   }
765   case N_PBUD:
766     error("TODO: support symbols of type N_PBUD");
767     return nullptr;
768   case N_SECT:
769     llvm_unreachable(
770         "N_SECT symbols should not be passed to parseNonSectionSymbol");
771   default:
772     llvm_unreachable("invalid symbol type");
773   }
774 }
775 
776 template <class NList> static bool isUndef(const NList &sym) {
777   return (sym.n_type & N_TYPE) == N_UNDF && sym.n_value == 0;
778 }
779 
780 template <class LP>
781 void ObjFile::parseSymbols(ArrayRef<typename LP::section> sectionHeaders,
782                            ArrayRef<typename LP::nlist> nList,
783                            const char *strtab, bool subsectionsViaSymbols) {
784   using NList = typename LP::nlist;
785 
786   // Groups indices of the symbols by the sections that contain them.
787   std::vector<std::vector<uint32_t>> symbolsBySection(sections.size());
788   symbols.resize(nList.size());
789   SmallVector<unsigned, 32> undefineds;
790   for (uint32_t i = 0; i < nList.size(); ++i) {
791     const NList &sym = nList[i];
792 
793     // Ignore debug symbols for now.
794     // FIXME: may need special handling.
795     if (sym.n_type & N_STAB)
796       continue;
797 
798     if ((sym.n_type & N_TYPE) == N_SECT) {
799       Subsections &subsections = sections[sym.n_sect - 1]->subsections;
800       // parseSections() may have chosen not to parse this section.
801       if (subsections.empty())
802         continue;
803       symbolsBySection[sym.n_sect - 1].push_back(i);
804     } else if (isUndef(sym)) {
805       undefineds.push_back(i);
806     } else {
807       symbols[i] = parseNonSectionSymbol(sym, strtab);
808     }
809   }
810 
811   for (size_t i = 0; i < sections.size(); ++i) {
812     Subsections &subsections = sections[i]->subsections;
813     if (subsections.empty())
814       continue;
815     std::vector<uint32_t> &symbolIndices = symbolsBySection[i];
816     uint64_t sectionAddr = sectionHeaders[i].addr;
817     uint32_t sectionAlign = 1u << sectionHeaders[i].align;
818 
819     // Some sections have already been split into subsections during
820     // parseSections(), so we simply need to match Symbols to the corresponding
821     // subsection here.
822     if (sections[i]->doneSplitting) {
823       for (size_t j = 0; j < symbolIndices.size(); ++j) {
824         const uint32_t symIndex = symbolIndices[j];
825         const NList &sym = nList[symIndex];
826         StringRef name = strtab + sym.n_strx;
827         uint64_t symbolOffset = sym.n_value - sectionAddr;
828         InputSection *isec =
829             findContainingSubsection(*sections[i], &symbolOffset);
830         if (symbolOffset != 0) {
831           error(toString(*sections[i]) + ":  symbol " + name +
832                 " at misaligned offset");
833           continue;
834         }
835         symbols[symIndex] =
836             createDefined(sym, name, isec, 0, isec->getSize(), forceHidden);
837       }
838       continue;
839     }
840     sections[i]->doneSplitting = true;
841 
842     auto getSymName = [strtab](const NList& sym) -> StringRef {
843       return StringRef(strtab + sym.n_strx);
844     };
845 
846     // Calculate symbol sizes and create subsections by splitting the sections
847     // along symbol boundaries.
848     // We populate subsections by repeatedly splitting the last (highest
849     // address) subsection.
850     llvm::stable_sort(symbolIndices, [&](uint32_t lhs, uint32_t rhs) {
851       // Put private-label symbols that have no flags after other symbols at the
852       // same address.
853       StringRef lhsName = getSymName(nList[lhs]);
854       StringRef rhsName = getSymName(nList[rhs]);
855       if (nList[lhs].n_value == nList[rhs].n_value) {
856         if (isPrivateLabel(lhsName) && isPrivateLabel(rhsName))
857           return nList[lhs].n_desc > nList[rhs].n_desc;
858         return !isPrivateLabel(lhsName) && isPrivateLabel(rhsName);
859       }
860       return nList[lhs].n_value < nList[rhs].n_value;
861     });
862     for (size_t j = 0; j < symbolIndices.size(); ++j) {
863       const uint32_t symIndex = symbolIndices[j];
864       const NList &sym = nList[symIndex];
865       StringRef name = getSymName(sym);
866       Subsection &subsec = subsections.back();
867       InputSection *isec = subsec.isec;
868 
869       uint64_t subsecAddr = sectionAddr + subsec.offset;
870       size_t symbolOffset = sym.n_value - subsecAddr;
871       uint64_t symbolSize =
872           j + 1 < symbolIndices.size()
873               ? nList[symbolIndices[j + 1]].n_value - sym.n_value
874               : isec->data.size() - symbolOffset;
875       // There are 4 cases where we do not need to create a new subsection:
876       //   1. If the input file does not use subsections-via-symbols.
877       //   2. Multiple symbols at the same address only induce one subsection.
878       //      (The symbolOffset == 0 check covers both this case as well as
879       //      the first loop iteration.)
880       //   3. Alternative entry points do not induce new subsections.
881       //   4. If we have a literal section (e.g. __cstring and __literal4).
882       if (!subsectionsViaSymbols || symbolOffset == 0 ||
883           sym.n_desc & N_ALT_ENTRY || !isa<ConcatInputSection>(isec)) {
884         isec->hasAltEntry = symbolOffset != 0;
885         // If we have an private-label symbol that's an alias, and that alias
886         // doesn't have any flags of its own, then we can just reuse the aliased
887         // symbol. Our sorting step above ensures that any such symbols will
888         // appear after the non-private-label ones. See weak-def-alias-ignored.s
889         // for the motivation behind this.
890         if (symbolOffset == 0 && isPrivateLabel(name) && j != 0 &&
891             sym.n_desc == 0)
892           symbols[symIndex] = symbols[symbolIndices[j - 1]];
893         else
894           symbols[symIndex] = createDefined(sym, name, isec, symbolOffset,
895                                             symbolSize, forceHidden);
896         continue;
897       }
898       auto *concatIsec = cast<ConcatInputSection>(isec);
899 
900       auto *nextIsec = make<ConcatInputSection>(*concatIsec);
901       nextIsec->wasCoalesced = false;
902       if (isZeroFill(isec->getFlags())) {
903         // Zero-fill sections have NULL data.data() non-zero data.size()
904         nextIsec->data = {nullptr, isec->data.size() - symbolOffset};
905         isec->data = {nullptr, symbolOffset};
906       } else {
907         nextIsec->data = isec->data.slice(symbolOffset);
908         isec->data = isec->data.slice(0, symbolOffset);
909       }
910 
911       // By construction, the symbol will be at offset zero in the new
912       // subsection.
913       symbols[symIndex] = createDefined(sym, name, nextIsec, /*value=*/0,
914                                         symbolSize, forceHidden);
915       // TODO: ld64 appears to preserve the original alignment as well as each
916       // subsection's offset from the last aligned address. We should consider
917       // emulating that behavior.
918       nextIsec->align = MinAlign(sectionAlign, sym.n_value);
919       subsections.push_back({sym.n_value - sectionAddr, nextIsec});
920     }
921   }
922 
923   // Undefined symbols can trigger recursive fetch from Archives due to
924   // LazySymbols. Process defined symbols first so that the relative order
925   // between a defined symbol and an undefined symbol does not change the
926   // symbol resolution behavior. In addition, a set of interconnected symbols
927   // will all be resolved to the same file, instead of being resolved to
928   // different files.
929   for (unsigned i : undefineds)
930     symbols[i] = parseNonSectionSymbol(nList[i], strtab);
931 }
932 
933 OpaqueFile::OpaqueFile(MemoryBufferRef mb, StringRef segName,
934                        StringRef sectName)
935     : InputFile(OpaqueKind, mb) {
936   const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
937   ArrayRef<uint8_t> data = {buf, mb.getBufferSize()};
938   sections.push_back(make<Section>(/*file=*/this, segName.take_front(16),
939                                    sectName.take_front(16),
940                                    /*flags=*/0, /*addr=*/0));
941   Section &section = *sections.back();
942   ConcatInputSection *isec = make<ConcatInputSection>(section, data);
943   isec->live = true;
944   section.subsections.push_back({0, isec});
945 }
946 
947 ObjFile::ObjFile(MemoryBufferRef mb, uint32_t modTime, StringRef archiveName,
948                  bool lazy, bool forceHidden)
949     : InputFile(ObjKind, mb, lazy), modTime(modTime), forceHidden(forceHidden) {
950   this->archiveName = std::string(archiveName);
951   if (lazy) {
952     if (target->wordSize == 8)
953       parseLazy<LP64>();
954     else
955       parseLazy<ILP32>();
956   } else {
957     if (target->wordSize == 8)
958       parse<LP64>();
959     else
960       parse<ILP32>();
961   }
962 }
963 
964 template <class LP> void ObjFile::parse() {
965   using Header = typename LP::mach_header;
966   using SegmentCommand = typename LP::segment_command;
967   using SectionHeader = typename LP::section;
968   using NList = typename LP::nlist;
969 
970   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
971   auto *hdr = reinterpret_cast<const Header *>(mb.getBufferStart());
972 
973   uint32_t cpuType;
974   std::tie(cpuType, std::ignore) = getCPUTypeFromArchitecture(config->arch());
975   if (hdr->cputype != cpuType) {
976     Architecture arch =
977         getArchitectureFromCpuType(hdr->cputype, hdr->cpusubtype);
978     auto msg = config->errorForArchMismatch
979                    ? static_cast<void (*)(const Twine &)>(error)
980                    : warn;
981     msg(toString(this) + " has architecture " + getArchitectureName(arch) +
982         " which is incompatible with target architecture " +
983         getArchitectureName(config->arch()));
984     return;
985   }
986 
987   if (!checkCompatibility(this))
988     return;
989 
990   for (auto *cmd : findCommands<linker_option_command>(hdr, LC_LINKER_OPTION)) {
991     StringRef data{reinterpret_cast<const char *>(cmd + 1),
992                    cmd->cmdsize - sizeof(linker_option_command)};
993     parseLCLinkerOption(this, cmd->count, data);
994   }
995 
996   ArrayRef<SectionHeader> sectionHeaders;
997   if (const load_command *cmd = findCommand(hdr, LP::segmentLCType)) {
998     auto *c = reinterpret_cast<const SegmentCommand *>(cmd);
999     sectionHeaders = ArrayRef<SectionHeader>{
1000         reinterpret_cast<const SectionHeader *>(c + 1), c->nsects};
1001     parseSections(sectionHeaders);
1002   }
1003 
1004   // TODO: Error on missing LC_SYMTAB?
1005   if (const load_command *cmd = findCommand(hdr, LC_SYMTAB)) {
1006     auto *c = reinterpret_cast<const symtab_command *>(cmd);
1007     ArrayRef<NList> nList(reinterpret_cast<const NList *>(buf + c->symoff),
1008                           c->nsyms);
1009     const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff;
1010     bool subsectionsViaSymbols = hdr->flags & MH_SUBSECTIONS_VIA_SYMBOLS;
1011     parseSymbols<LP>(sectionHeaders, nList, strtab, subsectionsViaSymbols);
1012   }
1013 
1014   // The relocations may refer to the symbols, so we parse them after we have
1015   // parsed all the symbols.
1016   for (size_t i = 0, n = sections.size(); i < n; ++i)
1017     if (!sections[i]->subsections.empty())
1018       parseRelocations(sectionHeaders, sectionHeaders[i], *sections[i]);
1019 
1020   parseDebugInfo();
1021 
1022   Section *ehFrameSection = nullptr;
1023   Section *compactUnwindSection = nullptr;
1024   for (Section *sec : sections) {
1025     Section **s = StringSwitch<Section **>(sec->name)
1026                       .Case(section_names::compactUnwind, &compactUnwindSection)
1027                       .Case(section_names::ehFrame, &ehFrameSection)
1028                       .Default(nullptr);
1029     if (s)
1030       *s = sec;
1031   }
1032   if (compactUnwindSection)
1033     registerCompactUnwind(*compactUnwindSection);
1034   if (ehFrameSection)
1035     registerEhFrames(*ehFrameSection);
1036 }
1037 
1038 template <class LP> void ObjFile::parseLazy() {
1039   using Header = typename LP::mach_header;
1040   using NList = typename LP::nlist;
1041 
1042   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
1043   auto *hdr = reinterpret_cast<const Header *>(mb.getBufferStart());
1044   const load_command *cmd = findCommand(hdr, LC_SYMTAB);
1045   if (!cmd)
1046     return;
1047   auto *c = reinterpret_cast<const symtab_command *>(cmd);
1048   ArrayRef<NList> nList(reinterpret_cast<const NList *>(buf + c->symoff),
1049                         c->nsyms);
1050   const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff;
1051   symbols.resize(nList.size());
1052   for (const auto &[i, sym] : llvm::enumerate(nList)) {
1053     if ((sym.n_type & N_EXT) && !isUndef(sym)) {
1054       // TODO: Bound checking
1055       StringRef name = strtab + sym.n_strx;
1056       symbols[i] = symtab->addLazyObject(name, *this);
1057       if (!lazy)
1058         break;
1059     }
1060   }
1061 }
1062 
1063 void ObjFile::parseDebugInfo() {
1064   std::unique_ptr<DwarfObject> dObj = DwarfObject::create(this);
1065   if (!dObj)
1066     return;
1067 
1068   // We do not re-use the context from getDwarf() here as that function
1069   // constructs an expensive DWARFCache object.
1070   auto *ctx = make<DWARFContext>(
1071       std::move(dObj), "",
1072       [&](Error err) {
1073         warn(toString(this) + ": " + toString(std::move(err)));
1074       },
1075       [&](Error warning) {
1076         warn(toString(this) + ": " + toString(std::move(warning)));
1077       });
1078 
1079   // TODO: Since object files can contain a lot of DWARF info, we should verify
1080   // that we are parsing just the info we need
1081   const DWARFContext::compile_unit_range &units = ctx->compile_units();
1082   // FIXME: There can be more than one compile unit per object file. See
1083   // PR48637.
1084   auto it = units.begin();
1085   compileUnit = it != units.end() ? it->get() : nullptr;
1086 }
1087 
1088 ArrayRef<data_in_code_entry> ObjFile::getDataInCode() const {
1089   const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
1090   const load_command *cmd = findCommand(buf, LC_DATA_IN_CODE);
1091   if (!cmd)
1092     return {};
1093   const auto *c = reinterpret_cast<const linkedit_data_command *>(cmd);
1094   return {reinterpret_cast<const data_in_code_entry *>(buf + c->dataoff),
1095           c->datasize / sizeof(data_in_code_entry)};
1096 }
1097 
1098 ArrayRef<uint8_t> ObjFile::getOptimizationHints() const {
1099   const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
1100   if (auto *cmd =
1101           findCommand<linkedit_data_command>(buf, LC_LINKER_OPTIMIZATION_HINT))
1102     return {buf + cmd->dataoff, cmd->datasize};
1103   return {};
1104 }
1105 
1106 // Create pointers from symbols to their associated compact unwind entries.
1107 void ObjFile::registerCompactUnwind(Section &compactUnwindSection) {
1108   for (const Subsection &subsection : compactUnwindSection.subsections) {
1109     ConcatInputSection *isec = cast<ConcatInputSection>(subsection.isec);
1110     // Hack!! Each compact unwind entry (CUE) has its UNSIGNED relocations embed
1111     // their addends in its data. Thus if ICF operated naively and compared the
1112     // entire contents of each CUE, entries with identical unwind info but e.g.
1113     // belonging to different functions would never be considered equivalent. To
1114     // work around this problem, we remove some parts of the data containing the
1115     // embedded addends. In particular, we remove the function address and LSDA
1116     // pointers.  Since these locations are at the start and end of the entry,
1117     // we can do this using a simple, efficient slice rather than performing a
1118     // copy.  We are not losing any information here because the embedded
1119     // addends have already been parsed in the corresponding Reloc structs.
1120     //
1121     // Removing these pointers would not be safe if they were pointers to
1122     // absolute symbols. In that case, there would be no corresponding
1123     // relocation. However, (AFAIK) MC cannot emit references to absolute
1124     // symbols for either the function address or the LSDA. However, it *can* do
1125     // so for the personality pointer, so we are not slicing that field away.
1126     //
1127     // Note that we do not adjust the offsets of the corresponding relocations;
1128     // instead, we rely on `relocateCompactUnwind()` to correctly handle these
1129     // truncated input sections.
1130     isec->data = isec->data.slice(target->wordSize, 8 + target->wordSize);
1131     uint32_t encoding = read32le(isec->data.data() + sizeof(uint32_t));
1132     // llvm-mc omits CU entries for functions that need DWARF encoding, but
1133     // `ld -r` doesn't. We can ignore them because we will re-synthesize these
1134     // CU entries from the DWARF info during the output phase.
1135     if ((encoding & static_cast<uint32_t>(UNWIND_MODE_MASK)) ==
1136         target->modeDwarfEncoding)
1137       continue;
1138 
1139     ConcatInputSection *referentIsec;
1140     for (auto it = isec->relocs.begin(); it != isec->relocs.end();) {
1141       Reloc &r = *it;
1142       // CUE::functionAddress is at offset 0. Skip personality & LSDA relocs.
1143       if (r.offset != 0) {
1144         ++it;
1145         continue;
1146       }
1147       uint64_t add = r.addend;
1148       if (auto *sym = cast_or_null<Defined>(r.referent.dyn_cast<Symbol *>())) {
1149         // Check whether the symbol defined in this file is the prevailing one.
1150         // Skip if it is e.g. a weak def that didn't prevail.
1151         if (sym->getFile() != this) {
1152           ++it;
1153           continue;
1154         }
1155         add += sym->value;
1156         referentIsec = cast<ConcatInputSection>(sym->isec);
1157       } else {
1158         referentIsec =
1159             cast<ConcatInputSection>(r.referent.dyn_cast<InputSection *>());
1160       }
1161       // Unwind info lives in __DATA, and finalization of __TEXT will occur
1162       // before finalization of __DATA. Moreover, the finalization of unwind
1163       // info depends on the exact addresses that it references. So it is safe
1164       // for compact unwind to reference addresses in __TEXT, but not addresses
1165       // in any other segment.
1166       if (referentIsec->getSegName() != segment_names::text)
1167         error(isec->getLocation(r.offset) + " references section " +
1168               referentIsec->getName() + " which is not in segment __TEXT");
1169       // The functionAddress relocations are typically section relocations.
1170       // However, unwind info operates on a per-symbol basis, so we search for
1171       // the function symbol here.
1172       Defined *d = findSymbolAtOffset(referentIsec, add);
1173       if (!d) {
1174         ++it;
1175         continue;
1176       }
1177       d->unwindEntry = isec;
1178       // Now that the symbol points to the unwind entry, we can remove the reloc
1179       // that points from the unwind entry back to the symbol.
1180       //
1181       // First, the symbol keeps the unwind entry alive (and not vice versa), so
1182       // this keeps dead-stripping simple.
1183       //
1184       // Moreover, it reduces the work that ICF needs to do to figure out if
1185       // functions with unwind info are foldable.
1186       //
1187       // However, this does make it possible for ICF to fold CUEs that point to
1188       // distinct functions (if the CUEs are otherwise identical).
1189       // UnwindInfoSection takes care of this by re-duplicating the CUEs so that
1190       // each one can hold a distinct functionAddress value.
1191       //
1192       // Given that clang emits relocations in reverse order of address, this
1193       // relocation should be at the end of the vector for most of our input
1194       // object files, so this erase() is typically an O(1) operation.
1195       it = isec->relocs.erase(it);
1196     }
1197   }
1198 }
1199 
1200 struct CIE {
1201   macho::Symbol *personalitySymbol = nullptr;
1202   bool fdesHaveAug = false;
1203   uint8_t lsdaPtrSize = 0; // 0 => no LSDA
1204   uint8_t funcPtrSize = 0;
1205 };
1206 
1207 static uint8_t pointerEncodingToSize(uint8_t enc) {
1208   switch (enc & 0xf) {
1209   case dwarf::DW_EH_PE_absptr:
1210     return target->wordSize;
1211   case dwarf::DW_EH_PE_sdata4:
1212     return 4;
1213   case dwarf::DW_EH_PE_sdata8:
1214     // ld64 doesn't actually support sdata8, but this seems simple enough...
1215     return 8;
1216   default:
1217     return 0;
1218   };
1219 }
1220 
1221 static CIE parseCIE(const InputSection *isec, const EhReader &reader,
1222                     size_t off) {
1223   // Handling the full generality of possible DWARF encodings would be a major
1224   // pain. We instead take advantage of our knowledge of how llvm-mc encodes
1225   // DWARF and handle just that.
1226   constexpr uint8_t expectedPersonalityEnc =
1227       dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_sdata4;
1228 
1229   CIE cie;
1230   uint8_t version = reader.readByte(&off);
1231   if (version != 1 && version != 3)
1232     fatal("Expected CIE version of 1 or 3, got " + Twine(version));
1233   StringRef aug = reader.readString(&off);
1234   reader.skipLeb128(&off); // skip code alignment
1235   reader.skipLeb128(&off); // skip data alignment
1236   reader.skipLeb128(&off); // skip return address register
1237   reader.skipLeb128(&off); // skip aug data length
1238   uint64_t personalityAddrOff = 0;
1239   for (char c : aug) {
1240     switch (c) {
1241     case 'z':
1242       cie.fdesHaveAug = true;
1243       break;
1244     case 'P': {
1245       uint8_t personalityEnc = reader.readByte(&off);
1246       if (personalityEnc != expectedPersonalityEnc)
1247         reader.failOn(off, "unexpected personality encoding 0x" +
1248                                Twine::utohexstr(personalityEnc));
1249       personalityAddrOff = off;
1250       off += 4;
1251       break;
1252     }
1253     case 'L': {
1254       uint8_t lsdaEnc = reader.readByte(&off);
1255       cie.lsdaPtrSize = pointerEncodingToSize(lsdaEnc);
1256       if (cie.lsdaPtrSize == 0)
1257         reader.failOn(off, "unexpected LSDA encoding 0x" +
1258                                Twine::utohexstr(lsdaEnc));
1259       break;
1260     }
1261     case 'R': {
1262       uint8_t pointerEnc = reader.readByte(&off);
1263       cie.funcPtrSize = pointerEncodingToSize(pointerEnc);
1264       if (cie.funcPtrSize == 0 || !(pointerEnc & dwarf::DW_EH_PE_pcrel))
1265         reader.failOn(off, "unexpected pointer encoding 0x" +
1266                                Twine::utohexstr(pointerEnc));
1267       break;
1268     }
1269     default:
1270       break;
1271     }
1272   }
1273   if (personalityAddrOff != 0) {
1274     auto personalityRelocIt =
1275         llvm::find_if(isec->relocs, [=](const macho::Reloc &r) {
1276           return r.offset == personalityAddrOff;
1277         });
1278     if (personalityRelocIt == isec->relocs.end())
1279       reader.failOn(off, "Failed to locate relocation for personality symbol");
1280     cie.personalitySymbol = personalityRelocIt->referent.get<macho::Symbol *>();
1281   }
1282   return cie;
1283 }
1284 
1285 // EH frame target addresses may be encoded as pcrel offsets. However, instead
1286 // of using an actual pcrel reloc, ld64 emits subtractor relocations instead.
1287 // This function recovers the target address from the subtractors, essentially
1288 // performing the inverse operation of EhRelocator.
1289 //
1290 // Concretely, we expect our relocations to write the value of `PC -
1291 // target_addr` to `PC`. `PC` itself is denoted by a minuend relocation that
1292 // points to a symbol plus an addend.
1293 //
1294 // It is important that the minuend relocation point to a symbol within the
1295 // same section as the fixup value, since sections may get moved around.
1296 //
1297 // For example, for arm64, llvm-mc emits relocations for the target function
1298 // address like so:
1299 //
1300 //   ltmp:
1301 //     <CIE start>
1302 //     ...
1303 //     <CIE end>
1304 //     ... multiple FDEs ...
1305 //     <FDE start>
1306 //     <target function address - (ltmp + pcrel offset)>
1307 //     ...
1308 //
1309 // If any of the FDEs in `multiple FDEs` get dead-stripped, then `FDE start`
1310 // will move to an earlier address, and `ltmp + pcrel offset` will no longer
1311 // reflect an accurate pcrel value. To avoid this problem, we "canonicalize"
1312 // our relocation by adding an `EH_Frame` symbol at `FDE start`, and updating
1313 // the reloc to be `target function address - (EH_Frame + new pcrel offset)`.
1314 //
1315 // If `Invert` is set, then we instead expect `target_addr - PC` to be written
1316 // to `PC`.
1317 template <bool Invert = false>
1318 Defined *
1319 targetSymFromCanonicalSubtractor(const InputSection *isec,
1320                                  std::vector<macho::Reloc>::iterator relocIt) {
1321   macho::Reloc &subtrahend = *relocIt;
1322   macho::Reloc &minuend = *std::next(relocIt);
1323   assert(target->hasAttr(subtrahend.type, RelocAttrBits::SUBTRAHEND));
1324   assert(target->hasAttr(minuend.type, RelocAttrBits::UNSIGNED));
1325   // Note: pcSym may *not* be exactly at the PC; there's usually a non-zero
1326   // addend.
1327   auto *pcSym = cast<Defined>(subtrahend.referent.get<macho::Symbol *>());
1328   Defined *target =
1329       cast_or_null<Defined>(minuend.referent.dyn_cast<macho::Symbol *>());
1330   if (!pcSym) {
1331     auto *targetIsec =
1332         cast<ConcatInputSection>(minuend.referent.get<InputSection *>());
1333     target = findSymbolAtOffset(targetIsec, minuend.addend);
1334   }
1335   if (Invert)
1336     std::swap(pcSym, target);
1337   if (pcSym->isec == isec) {
1338     if (pcSym->value - (Invert ? -1 : 1) * minuend.addend != subtrahend.offset)
1339       fatal("invalid FDE relocation in __eh_frame");
1340   } else {
1341     // Ensure the pcReloc points to a symbol within the current EH frame.
1342     // HACK: we should really verify that the original relocation's semantics
1343     // are preserved. In particular, we should have
1344     // `oldSym->value + oldOffset == newSym + newOffset`. However, we don't
1345     // have an easy way to access the offsets from this point in the code; some
1346     // refactoring is needed for that.
1347     macho::Reloc &pcReloc = Invert ? minuend : subtrahend;
1348     pcReloc.referent = isec->symbols[0];
1349     assert(isec->symbols[0]->value == 0);
1350     minuend.addend = pcReloc.offset * (Invert ? 1LL : -1LL);
1351   }
1352   return target;
1353 }
1354 
1355 Defined *findSymbolAtAddress(const std::vector<Section *> &sections,
1356                              uint64_t addr) {
1357   Section *sec = findContainingSection(sections, &addr);
1358   auto *isec = cast<ConcatInputSection>(findContainingSubsection(*sec, &addr));
1359   return findSymbolAtOffset(isec, addr);
1360 }
1361 
1362 // For symbols that don't have compact unwind info, associate them with the more
1363 // general-purpose (and verbose) DWARF unwind info found in __eh_frame.
1364 //
1365 // This requires us to parse the contents of __eh_frame. See EhFrame.h for a
1366 // description of its format.
1367 //
1368 // While parsing, we also look for what MC calls "abs-ified" relocations -- they
1369 // are relocations which are implicitly encoded as offsets in the section data.
1370 // We convert them into explicit Reloc structs so that the EH frames can be
1371 // handled just like a regular ConcatInputSection later in our output phase.
1372 //
1373 // We also need to handle the case where our input object file has explicit
1374 // relocations. This is the case when e.g. it's the output of `ld -r`. We only
1375 // look for the "abs-ified" relocation if an explicit relocation is absent.
1376 void ObjFile::registerEhFrames(Section &ehFrameSection) {
1377   DenseMap<const InputSection *, CIE> cieMap;
1378   for (const Subsection &subsec : ehFrameSection.subsections) {
1379     auto *isec = cast<ConcatInputSection>(subsec.isec);
1380     uint64_t isecOff = subsec.offset;
1381 
1382     // Subtractor relocs require the subtrahend to be a symbol reloc. Ensure
1383     // that all EH frames have an associated symbol so that we can generate
1384     // subtractor relocs that reference them.
1385     if (isec->symbols.size() == 0)
1386       make<Defined>("EH_Frame", isec->getFile(), isec, /*value=*/0,
1387                     isec->getSize(), /*isWeakDef=*/false, /*isExternal=*/false,
1388                     /*isPrivateExtern=*/false, /*includeInSymtab=*/false,
1389                     /*isThumb=*/false, /*isReferencedDynamically=*/false,
1390                     /*noDeadStrip=*/false);
1391     else if (isec->symbols[0]->value != 0)
1392       fatal("found symbol at unexpected offset in __eh_frame");
1393 
1394     EhReader reader(this, isec->data, subsec.offset);
1395     size_t dataOff = 0; // Offset from the start of the EH frame.
1396     reader.skipValidLength(&dataOff); // readLength() already validated this.
1397     // cieOffOff is the offset from the start of the EH frame to the cieOff
1398     // value, which is itself an offset from the current PC to a CIE.
1399     const size_t cieOffOff = dataOff;
1400 
1401     EhRelocator ehRelocator(isec);
1402     auto cieOffRelocIt = llvm::find_if(
1403         isec->relocs, [=](const Reloc &r) { return r.offset == cieOffOff; });
1404     InputSection *cieIsec = nullptr;
1405     if (cieOffRelocIt != isec->relocs.end()) {
1406       // We already have an explicit relocation for the CIE offset.
1407       cieIsec =
1408           targetSymFromCanonicalSubtractor</*Invert=*/true>(isec, cieOffRelocIt)
1409               ->isec;
1410       dataOff += sizeof(uint32_t);
1411     } else {
1412       // If we haven't found a relocation, then the CIE offset is most likely
1413       // embedded in the section data (AKA an "abs-ified" reloc.). Parse that
1414       // and generate a Reloc struct.
1415       uint32_t cieMinuend = reader.readU32(&dataOff);
1416       if (cieMinuend == 0) {
1417         cieIsec = isec;
1418       } else {
1419         uint32_t cieOff = isecOff + dataOff - cieMinuend;
1420         cieIsec = findContainingSubsection(ehFrameSection, &cieOff);
1421         if (cieIsec == nullptr)
1422           fatal("failed to find CIE");
1423       }
1424       if (cieIsec != isec)
1425         ehRelocator.makeNegativePcRel(cieOffOff, cieIsec->symbols[0],
1426                                       /*length=*/2);
1427     }
1428     if (cieIsec == isec) {
1429       cieMap[cieIsec] = parseCIE(isec, reader, dataOff);
1430       continue;
1431     }
1432 
1433     assert(cieMap.count(cieIsec));
1434     const CIE &cie = cieMap[cieIsec];
1435     // Offset of the function address within the EH frame.
1436     const size_t funcAddrOff = dataOff;
1437     uint64_t funcAddr = reader.readPointer(&dataOff, cie.funcPtrSize) +
1438                         ehFrameSection.addr + isecOff + funcAddrOff;
1439     uint32_t funcLength = reader.readPointer(&dataOff, cie.funcPtrSize);
1440     size_t lsdaAddrOff = 0; // Offset of the LSDA address within the EH frame.
1441     std::optional<uint64_t> lsdaAddrOpt;
1442     if (cie.fdesHaveAug) {
1443       reader.skipLeb128(&dataOff);
1444       lsdaAddrOff = dataOff;
1445       if (cie.lsdaPtrSize != 0) {
1446         uint64_t lsdaOff = reader.readPointer(&dataOff, cie.lsdaPtrSize);
1447         if (lsdaOff != 0) // FIXME possible to test this?
1448           lsdaAddrOpt = ehFrameSection.addr + isecOff + lsdaAddrOff + lsdaOff;
1449       }
1450     }
1451 
1452     auto funcAddrRelocIt = isec->relocs.end();
1453     auto lsdaAddrRelocIt = isec->relocs.end();
1454     for (auto it = isec->relocs.begin(); it != isec->relocs.end(); ++it) {
1455       if (it->offset == funcAddrOff)
1456         funcAddrRelocIt = it++; // Found subtrahend; skip over minuend reloc
1457       else if (lsdaAddrOpt && it->offset == lsdaAddrOff)
1458         lsdaAddrRelocIt = it++; // Found subtrahend; skip over minuend reloc
1459     }
1460 
1461     Defined *funcSym;
1462     if (funcAddrRelocIt != isec->relocs.end()) {
1463       funcSym = targetSymFromCanonicalSubtractor(isec, funcAddrRelocIt);
1464       // Canonicalize the symbol. If there are multiple symbols at the same
1465       // address, we want both `registerEhFrame` and `registerCompactUnwind`
1466       // to register the unwind entry under same symbol.
1467       // This is not particularly efficient, but we should run into this case
1468       // infrequently (only when handling the output of `ld -r`).
1469       if (funcSym->isec)
1470         funcSym = findSymbolAtOffset(cast<ConcatInputSection>(funcSym->isec),
1471                                      funcSym->value);
1472     } else {
1473       funcSym = findSymbolAtAddress(sections, funcAddr);
1474       ehRelocator.makePcRel(funcAddrOff, funcSym, target->p2WordSize);
1475     }
1476     // The symbol has been coalesced, or already has a compact unwind entry.
1477     if (!funcSym || funcSym->getFile() != this || funcSym->unwindEntry) {
1478       // We must prune unused FDEs for correctness, so we cannot rely on
1479       // -dead_strip being enabled.
1480       isec->live = false;
1481       continue;
1482     }
1483 
1484     InputSection *lsdaIsec = nullptr;
1485     if (lsdaAddrRelocIt != isec->relocs.end()) {
1486       lsdaIsec = targetSymFromCanonicalSubtractor(isec, lsdaAddrRelocIt)->isec;
1487     } else if (lsdaAddrOpt) {
1488       uint64_t lsdaAddr = *lsdaAddrOpt;
1489       Section *sec = findContainingSection(sections, &lsdaAddr);
1490       lsdaIsec =
1491           cast<ConcatInputSection>(findContainingSubsection(*sec, &lsdaAddr));
1492       ehRelocator.makePcRel(lsdaAddrOff, lsdaIsec, target->p2WordSize);
1493     }
1494 
1495     fdes[isec] = {funcLength, cie.personalitySymbol, lsdaIsec};
1496     funcSym->unwindEntry = isec;
1497     ehRelocator.commit();
1498   }
1499 
1500   // __eh_frame is marked as S_ATTR_LIVE_SUPPORT in input files, because FDEs
1501   // are normally required to be kept alive if they reference a live symbol.
1502   // However, we've explicitly created a dependency from a symbol to its FDE, so
1503   // dead-stripping will just work as usual, and S_ATTR_LIVE_SUPPORT will only
1504   // serve to incorrectly prevent us from dead-stripping duplicate FDEs for a
1505   // live symbol (e.g. if there were multiple weak copies). Remove this flag to
1506   // let dead-stripping proceed correctly.
1507   ehFrameSection.flags &= ~S_ATTR_LIVE_SUPPORT;
1508 }
1509 
1510 std::string ObjFile::sourceFile() const {
1511   SmallString<261> dir(compileUnit->getCompilationDir());
1512   StringRef sep = sys::path::get_separator();
1513   // We don't use `path::append` here because we want an empty `dir` to result
1514   // in an absolute path. `append` would give us a relative path for that case.
1515   if (!dir.endswith(sep))
1516     dir += sep;
1517   return (dir + compileUnit->getUnitDIE().getShortName()).str();
1518 }
1519 
1520 lld::DWARFCache *ObjFile::getDwarf() {
1521   llvm::call_once(initDwarf, [this]() {
1522     auto dwObj = DwarfObject::create(this);
1523     if (!dwObj)
1524       return;
1525     dwarfCache = std::make_unique<DWARFCache>(std::make_unique<DWARFContext>(
1526         std::move(dwObj), "",
1527         [&](Error err) { warn(getName() + ": " + toString(std::move(err))); },
1528         [&](Error warning) {
1529           warn(getName() + ": " + toString(std::move(warning)));
1530         }));
1531   });
1532 
1533   return dwarfCache.get();
1534 }
1535 // The path can point to either a dylib or a .tbd file.
1536 static DylibFile *loadDylib(StringRef path, DylibFile *umbrella) {
1537   std::optional<MemoryBufferRef> mbref = readFile(path);
1538   if (!mbref) {
1539     error("could not read dylib file at " + path);
1540     return nullptr;
1541   }
1542   return loadDylib(*mbref, umbrella);
1543 }
1544 
1545 // TBD files are parsed into a series of TAPI documents (InterfaceFiles), with
1546 // the first document storing child pointers to the rest of them. When we are
1547 // processing a given TBD file, we store that top-level document in
1548 // currentTopLevelTapi. When processing re-exports, we search its children for
1549 // potentially matching documents in the same TBD file. Note that the children
1550 // themselves don't point to further documents, i.e. this is a two-level tree.
1551 //
1552 // Re-exports can either refer to on-disk files, or to documents within .tbd
1553 // files.
1554 static DylibFile *findDylib(StringRef path, DylibFile *umbrella,
1555                             const InterfaceFile *currentTopLevelTapi) {
1556   // Search order:
1557   // 1. Install name basename in -F / -L directories.
1558   {
1559     StringRef stem = path::stem(path);
1560     SmallString<128> frameworkName;
1561     path::append(frameworkName, path::Style::posix, stem + ".framework", stem);
1562     bool isFramework = path.endswith(frameworkName);
1563     if (isFramework) {
1564       for (StringRef dir : config->frameworkSearchPaths) {
1565         SmallString<128> candidate = dir;
1566         path::append(candidate, frameworkName);
1567         if (std::optional<StringRef> dylibPath =
1568                 resolveDylibPath(candidate.str()))
1569           return loadDylib(*dylibPath, umbrella);
1570       }
1571     } else if (std::optional<StringRef> dylibPath = findPathCombination(
1572                    stem, config->librarySearchPaths, {".tbd", ".dylib"}))
1573       return loadDylib(*dylibPath, umbrella);
1574   }
1575 
1576   // 2. As absolute path.
1577   if (path::is_absolute(path, path::Style::posix))
1578     for (StringRef root : config->systemLibraryRoots)
1579       if (std::optional<StringRef> dylibPath =
1580               resolveDylibPath((root + path).str()))
1581         return loadDylib(*dylibPath, umbrella);
1582 
1583   // 3. As relative path.
1584 
1585   // TODO: Handle -dylib_file
1586 
1587   // Replace @executable_path, @loader_path, @rpath prefixes in install name.
1588   SmallString<128> newPath;
1589   if (config->outputType == MH_EXECUTE &&
1590       path.consume_front("@executable_path/")) {
1591     // ld64 allows overriding this with the undocumented flag -executable_path.
1592     // lld doesn't currently implement that flag.
1593     // FIXME: Consider using finalOutput instead of outputFile.
1594     path::append(newPath, path::parent_path(config->outputFile), path);
1595     path = newPath;
1596   } else if (path.consume_front("@loader_path/")) {
1597     fs::real_path(umbrella->getName(), newPath);
1598     path::remove_filename(newPath);
1599     path::append(newPath, path);
1600     path = newPath;
1601   } else if (path.startswith("@rpath/")) {
1602     for (StringRef rpath : umbrella->rpaths) {
1603       newPath.clear();
1604       if (rpath.consume_front("@loader_path/")) {
1605         fs::real_path(umbrella->getName(), newPath);
1606         path::remove_filename(newPath);
1607       }
1608       path::append(newPath, rpath, path.drop_front(strlen("@rpath/")));
1609       if (std::optional<StringRef> dylibPath = resolveDylibPath(newPath.str()))
1610         return loadDylib(*dylibPath, umbrella);
1611     }
1612   }
1613 
1614   // FIXME: Should this be further up?
1615   if (currentTopLevelTapi) {
1616     for (InterfaceFile &child :
1617          make_pointee_range(currentTopLevelTapi->documents())) {
1618       assert(child.documents().empty());
1619       if (path == child.getInstallName()) {
1620         auto file = make<DylibFile>(child, umbrella, /*isBundleLoader=*/false,
1621                                     /*explicitlyLinked=*/false);
1622         file->parseReexports(child);
1623         return file;
1624       }
1625     }
1626   }
1627 
1628   if (std::optional<StringRef> dylibPath = resolveDylibPath(path))
1629     return loadDylib(*dylibPath, umbrella);
1630 
1631   return nullptr;
1632 }
1633 
1634 // If a re-exported dylib is public (lives in /usr/lib or
1635 // /System/Library/Frameworks), then it is considered implicitly linked: we
1636 // should bind to its symbols directly instead of via the re-exporting umbrella
1637 // library.
1638 static bool isImplicitlyLinked(StringRef path) {
1639   if (!config->implicitDylibs)
1640     return false;
1641 
1642   if (path::parent_path(path) == "/usr/lib")
1643     return true;
1644 
1645   // Match /System/Library/Frameworks/$FOO.framework/**/$FOO
1646   if (path.consume_front("/System/Library/Frameworks/")) {
1647     StringRef frameworkName = path.take_until([](char c) { return c == '.'; });
1648     return path::filename(path) == frameworkName;
1649   }
1650 
1651   return false;
1652 }
1653 
1654 void DylibFile::loadReexport(StringRef path, DylibFile *umbrella,
1655                          const InterfaceFile *currentTopLevelTapi) {
1656   DylibFile *reexport = findDylib(path, umbrella, currentTopLevelTapi);
1657   if (!reexport)
1658     error(toString(this) + ": unable to locate re-export with install name " +
1659           path);
1660 }
1661 
1662 DylibFile::DylibFile(MemoryBufferRef mb, DylibFile *umbrella,
1663                      bool isBundleLoader, bool explicitlyLinked)
1664     : InputFile(DylibKind, mb), refState(RefState::Unreferenced),
1665       explicitlyLinked(explicitlyLinked), isBundleLoader(isBundleLoader) {
1666   assert(!isBundleLoader || !umbrella);
1667   if (umbrella == nullptr)
1668     umbrella = this;
1669   this->umbrella = umbrella;
1670 
1671   auto *hdr = reinterpret_cast<const mach_header *>(mb.getBufferStart());
1672 
1673   // Initialize installName.
1674   if (const load_command *cmd = findCommand(hdr, LC_ID_DYLIB)) {
1675     auto *c = reinterpret_cast<const dylib_command *>(cmd);
1676     currentVersion = read32le(&c->dylib.current_version);
1677     compatibilityVersion = read32le(&c->dylib.compatibility_version);
1678     installName =
1679         reinterpret_cast<const char *>(cmd) + read32le(&c->dylib.name);
1680   } else if (!isBundleLoader) {
1681     // macho_executable and macho_bundle don't have LC_ID_DYLIB,
1682     // so it's OK.
1683     error(toString(this) + ": dylib missing LC_ID_DYLIB load command");
1684     return;
1685   }
1686 
1687   if (config->printEachFile)
1688     message(toString(this));
1689   inputFiles.insert(this);
1690 
1691   deadStrippable = hdr->flags & MH_DEAD_STRIPPABLE_DYLIB;
1692 
1693   if (!checkCompatibility(this))
1694     return;
1695 
1696   checkAppExtensionSafety(hdr->flags & MH_APP_EXTENSION_SAFE);
1697 
1698   for (auto *cmd : findCommands<rpath_command>(hdr, LC_RPATH)) {
1699     StringRef rpath{reinterpret_cast<const char *>(cmd) + cmd->path};
1700     rpaths.push_back(rpath);
1701   }
1702 
1703   // Initialize symbols.
1704   exportingFile = isImplicitlyLinked(installName) ? this : this->umbrella;
1705 
1706   const auto *dyldInfo = findCommand<dyld_info_command>(hdr, LC_DYLD_INFO_ONLY);
1707   const auto *exportsTrie =
1708       findCommand<linkedit_data_command>(hdr, LC_DYLD_EXPORTS_TRIE);
1709   if (dyldInfo && exportsTrie) {
1710     // It's unclear what should happen in this case. Maybe we should only error
1711     // out if the two load commands refer to different data?
1712     error(toString(this) +
1713           ": dylib has both LC_DYLD_INFO_ONLY and LC_DYLD_EXPORTS_TRIE");
1714     return;
1715   } else if (dyldInfo) {
1716     parseExportedSymbols(dyldInfo->export_off, dyldInfo->export_size);
1717   } else if (exportsTrie) {
1718     parseExportedSymbols(exportsTrie->dataoff, exportsTrie->datasize);
1719   } else {
1720     error("No LC_DYLD_INFO_ONLY or LC_DYLD_EXPORTS_TRIE found in " +
1721           toString(this));
1722     return;
1723   }
1724 }
1725 
1726 void DylibFile::parseExportedSymbols(uint32_t offset, uint32_t size) {
1727   struct TrieEntry {
1728     StringRef name;
1729     uint64_t flags;
1730   };
1731 
1732   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
1733   std::vector<TrieEntry> entries;
1734   // Find all the $ld$* symbols to process first.
1735   parseTrie(buf + offset, size, [&](const Twine &name, uint64_t flags) {
1736     StringRef savedName = saver().save(name);
1737     if (handleLDSymbol(savedName))
1738       return;
1739     entries.push_back({savedName, flags});
1740   });
1741 
1742   // Process the "normal" symbols.
1743   for (TrieEntry &entry : entries) {
1744     if (exportingFile->hiddenSymbols.contains(CachedHashStringRef(entry.name)))
1745       continue;
1746 
1747     bool isWeakDef = entry.flags & EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION;
1748     bool isTlv = entry.flags & EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL;
1749 
1750     symbols.push_back(
1751         symtab->addDylib(entry.name, exportingFile, isWeakDef, isTlv));
1752   }
1753 }
1754 
1755 void DylibFile::parseLoadCommands(MemoryBufferRef mb) {
1756   auto *hdr = reinterpret_cast<const mach_header *>(mb.getBufferStart());
1757   const uint8_t *p = reinterpret_cast<const uint8_t *>(mb.getBufferStart()) +
1758                      target->headerSize;
1759   for (uint32_t i = 0, n = hdr->ncmds; i < n; ++i) {
1760     auto *cmd = reinterpret_cast<const load_command *>(p);
1761     p += cmd->cmdsize;
1762 
1763     if (!(hdr->flags & MH_NO_REEXPORTED_DYLIBS) &&
1764         cmd->cmd == LC_REEXPORT_DYLIB) {
1765       const auto *c = reinterpret_cast<const dylib_command *>(cmd);
1766       StringRef reexportPath =
1767           reinterpret_cast<const char *>(c) + read32le(&c->dylib.name);
1768       loadReexport(reexportPath, exportingFile, nullptr);
1769     }
1770 
1771     // FIXME: What about LC_LOAD_UPWARD_DYLIB, LC_LAZY_LOAD_DYLIB,
1772     // LC_LOAD_WEAK_DYLIB, LC_REEXPORT_DYLIB (..are reexports from dylibs with
1773     // MH_NO_REEXPORTED_DYLIBS loaded for -flat_namespace)?
1774     if (config->namespaceKind == NamespaceKind::flat &&
1775         cmd->cmd == LC_LOAD_DYLIB) {
1776       const auto *c = reinterpret_cast<const dylib_command *>(cmd);
1777       StringRef dylibPath =
1778           reinterpret_cast<const char *>(c) + read32le(&c->dylib.name);
1779       DylibFile *dylib = findDylib(dylibPath, umbrella, nullptr);
1780       if (!dylib)
1781         error(Twine("unable to locate library '") + dylibPath +
1782               "' loaded from '" + toString(this) + "' for -flat_namespace");
1783     }
1784   }
1785 }
1786 
1787 // Some versions of Xcode ship with .tbd files that don't have the right
1788 // platform settings.
1789 constexpr std::array<StringRef, 3> skipPlatformChecks{
1790     "/usr/lib/system/libsystem_kernel.dylib",
1791     "/usr/lib/system/libsystem_platform.dylib",
1792     "/usr/lib/system/libsystem_pthread.dylib"};
1793 
1794 static bool skipPlatformCheckForCatalyst(const InterfaceFile &interface,
1795                                          bool explicitlyLinked) {
1796   // Catalyst outputs can link against implicitly linked macOS-only libraries.
1797   if (config->platform() != PLATFORM_MACCATALYST || explicitlyLinked)
1798     return false;
1799   return is_contained(interface.targets(),
1800                       MachO::Target(config->arch(), PLATFORM_MACOS));
1801 }
1802 
1803 static bool isArchABICompatible(ArchitectureSet archSet,
1804                                 Architecture targetArch) {
1805   uint32_t cpuType;
1806   uint32_t targetCpuType;
1807   std::tie(targetCpuType, std::ignore) = getCPUTypeFromArchitecture(targetArch);
1808 
1809   return llvm::any_of(archSet, [&](const auto &p) {
1810     std::tie(cpuType, std::ignore) = getCPUTypeFromArchitecture(p);
1811     return cpuType == targetCpuType;
1812   });
1813 }
1814 
1815 static bool isTargetPlatformArchCompatible(
1816     InterfaceFile::const_target_range interfaceTargets, Target target) {
1817   if (is_contained(interfaceTargets, target))
1818     return true;
1819 
1820   if (config->forceExactCpuSubtypeMatch)
1821     return false;
1822 
1823   ArchitectureSet archSet;
1824   for (const auto &p : interfaceTargets)
1825     if (p.Platform == target.Platform)
1826       archSet.set(p.Arch);
1827   if (archSet.empty())
1828     return false;
1829 
1830   return isArchABICompatible(archSet, target.Arch);
1831 }
1832 
1833 DylibFile::DylibFile(const InterfaceFile &interface, DylibFile *umbrella,
1834                      bool isBundleLoader, bool explicitlyLinked)
1835     : InputFile(DylibKind, interface), refState(RefState::Unreferenced),
1836       explicitlyLinked(explicitlyLinked), isBundleLoader(isBundleLoader) {
1837   // FIXME: Add test for the missing TBD code path.
1838 
1839   if (umbrella == nullptr)
1840     umbrella = this;
1841   this->umbrella = umbrella;
1842 
1843   installName = saver().save(interface.getInstallName());
1844   compatibilityVersion = interface.getCompatibilityVersion().rawValue();
1845   currentVersion = interface.getCurrentVersion().rawValue();
1846 
1847   if (config->printEachFile)
1848     message(toString(this));
1849   inputFiles.insert(this);
1850 
1851   if (!is_contained(skipPlatformChecks, installName) &&
1852       !isTargetPlatformArchCompatible(interface.targets(),
1853                                       config->platformInfo.target) &&
1854       !skipPlatformCheckForCatalyst(interface, explicitlyLinked)) {
1855     error(toString(this) + " is incompatible with " +
1856           std::string(config->platformInfo.target));
1857     return;
1858   }
1859 
1860   checkAppExtensionSafety(interface.isApplicationExtensionSafe());
1861 
1862   exportingFile = isImplicitlyLinked(installName) ? this : umbrella;
1863   auto addSymbol = [&](const llvm::MachO::Symbol &symbol,
1864                        const Twine &name) -> void {
1865     StringRef savedName = saver().save(name);
1866     if (exportingFile->hiddenSymbols.contains(CachedHashStringRef(savedName)))
1867       return;
1868 
1869     symbols.push_back(symtab->addDylib(savedName, exportingFile,
1870                                        symbol.isWeakDefined(),
1871                                        symbol.isThreadLocalValue()));
1872   };
1873 
1874   std::vector<const llvm::MachO::Symbol *> normalSymbols;
1875   normalSymbols.reserve(interface.symbolsCount());
1876   for (const auto *symbol : interface.symbols()) {
1877     if (!isArchABICompatible(symbol->getArchitectures(), config->arch()))
1878       continue;
1879     if (handleLDSymbol(symbol->getName()))
1880       continue;
1881 
1882     switch (symbol->getKind()) {
1883     case SymbolKind::GlobalSymbol:
1884     case SymbolKind::ObjectiveCClass:
1885     case SymbolKind::ObjectiveCClassEHType:
1886     case SymbolKind::ObjectiveCInstanceVariable:
1887       normalSymbols.push_back(symbol);
1888     }
1889   }
1890 
1891   // TODO(compnerd) filter out symbols based on the target platform
1892   for (const auto *symbol : normalSymbols) {
1893     switch (symbol->getKind()) {
1894     case SymbolKind::GlobalSymbol:
1895       addSymbol(*symbol, symbol->getName());
1896       break;
1897     case SymbolKind::ObjectiveCClass:
1898       // XXX ld64 only creates these symbols when -ObjC is passed in. We may
1899       // want to emulate that.
1900       addSymbol(*symbol, objc::klass + symbol->getName());
1901       addSymbol(*symbol, objc::metaclass + symbol->getName());
1902       break;
1903     case SymbolKind::ObjectiveCClassEHType:
1904       addSymbol(*symbol, objc::ehtype + symbol->getName());
1905       break;
1906     case SymbolKind::ObjectiveCInstanceVariable:
1907       addSymbol(*symbol, objc::ivar + symbol->getName());
1908       break;
1909     }
1910   }
1911 }
1912 
1913 DylibFile::DylibFile(DylibFile *umbrella)
1914     : InputFile(DylibKind, MemoryBufferRef{}), refState(RefState::Unreferenced),
1915       explicitlyLinked(false), isBundleLoader(false) {
1916   if (umbrella == nullptr)
1917     umbrella = this;
1918   this->umbrella = umbrella;
1919 }
1920 
1921 void DylibFile::parseReexports(const InterfaceFile &interface) {
1922   const InterfaceFile *topLevel =
1923       interface.getParent() == nullptr ? &interface : interface.getParent();
1924   for (const InterfaceFileRef &intfRef : interface.reexportedLibraries()) {
1925     InterfaceFile::const_target_range targets = intfRef.targets();
1926     if (is_contained(skipPlatformChecks, intfRef.getInstallName()) ||
1927         isTargetPlatformArchCompatible(targets, config->platformInfo.target))
1928       loadReexport(intfRef.getInstallName(), exportingFile, topLevel);
1929   }
1930 }
1931 
1932 bool DylibFile::isExplicitlyLinked() const {
1933   if (!explicitlyLinked)
1934     return false;
1935 
1936   // If this dylib was explicitly linked, but at least one of the symbols
1937   // of the synthetic dylibs it created via $ld$previous symbols is
1938   // referenced, then that synthetic dylib fulfils the explicit linkedness
1939   // and we can deadstrip this dylib if it's unreferenced.
1940   for (const auto *dylib : extraDylibs)
1941     if (dylib->isReferenced())
1942       return false;
1943 
1944   return true;
1945 }
1946 
1947 DylibFile *DylibFile::getSyntheticDylib(StringRef installName,
1948                                         uint32_t currentVersion,
1949                                         uint32_t compatVersion) {
1950   for (DylibFile *dylib : extraDylibs)
1951     if (dylib->installName == installName) {
1952       // FIXME: Check what to do if different $ld$previous symbols
1953       // request the same dylib, but with different versions.
1954       return dylib;
1955     }
1956 
1957   auto *dylib = make<DylibFile>(umbrella == this ? nullptr : umbrella);
1958   dylib->installName = saver().save(installName);
1959   dylib->currentVersion = currentVersion;
1960   dylib->compatibilityVersion = compatVersion;
1961   extraDylibs.push_back(dylib);
1962   return dylib;
1963 }
1964 
1965 // $ld$ symbols modify the properties/behavior of the library (e.g. its install
1966 // name, compatibility version or hide/add symbols) for specific target
1967 // versions.
1968 bool DylibFile::handleLDSymbol(StringRef originalName) {
1969   if (!originalName.startswith("$ld$"))
1970     return false;
1971 
1972   StringRef action;
1973   StringRef name;
1974   std::tie(action, name) = originalName.drop_front(strlen("$ld$")).split('$');
1975   if (action == "previous")
1976     handleLDPreviousSymbol(name, originalName);
1977   else if (action == "install_name")
1978     handleLDInstallNameSymbol(name, originalName);
1979   else if (action == "hide")
1980     handleLDHideSymbol(name, originalName);
1981   return true;
1982 }
1983 
1984 void DylibFile::handleLDPreviousSymbol(StringRef name, StringRef originalName) {
1985   // originalName: $ld$ previous $ <installname> $ <compatversion> $
1986   // <platformstr> $ <startversion> $ <endversion> $ <symbol-name> $
1987   StringRef installName;
1988   StringRef compatVersion;
1989   StringRef platformStr;
1990   StringRef startVersion;
1991   StringRef endVersion;
1992   StringRef symbolName;
1993   StringRef rest;
1994 
1995   std::tie(installName, name) = name.split('$');
1996   std::tie(compatVersion, name) = name.split('$');
1997   std::tie(platformStr, name) = name.split('$');
1998   std::tie(startVersion, name) = name.split('$');
1999   std::tie(endVersion, name) = name.split('$');
2000   std::tie(symbolName, rest) = name.rsplit('$');
2001 
2002   // FIXME: Does this do the right thing for zippered files?
2003   unsigned platform;
2004   if (platformStr.getAsInteger(10, platform) ||
2005       platform != static_cast<unsigned>(config->platform()))
2006     return;
2007 
2008   VersionTuple start;
2009   if (start.tryParse(startVersion)) {
2010     warn(toString(this) + ": failed to parse start version, symbol '" +
2011          originalName + "' ignored");
2012     return;
2013   }
2014   VersionTuple end;
2015   if (end.tryParse(endVersion)) {
2016     warn(toString(this) + ": failed to parse end version, symbol '" +
2017          originalName + "' ignored");
2018     return;
2019   }
2020   if (config->platformInfo.minimum < start ||
2021       config->platformInfo.minimum >= end)
2022     return;
2023 
2024   // Initialized to compatibilityVersion for the symbolName branch below.
2025   uint32_t newCompatibilityVersion = compatibilityVersion;
2026   uint32_t newCurrentVersionForSymbol = currentVersion;
2027   if (!compatVersion.empty()) {
2028     VersionTuple cVersion;
2029     if (cVersion.tryParse(compatVersion)) {
2030       warn(toString(this) +
2031            ": failed to parse compatibility version, symbol '" + originalName +
2032            "' ignored");
2033       return;
2034     }
2035     newCompatibilityVersion = encodeVersion(cVersion);
2036     newCurrentVersionForSymbol = newCompatibilityVersion;
2037   }
2038 
2039   if (!symbolName.empty()) {
2040     // A $ld$previous$ symbol with symbol name adds a symbol with that name to
2041     // a dylib with given name and version.
2042     auto *dylib = getSyntheticDylib(installName, newCurrentVersionForSymbol,
2043                                     newCompatibilityVersion);
2044 
2045     // The tbd file usually contains the $ld$previous symbol for an old version,
2046     // and then the symbol itself later, for newer deployment targets, like so:
2047     //    symbols: [
2048     //      '$ld$previous$/Another$$1$3.0$14.0$_zzz$',
2049     //      _zzz,
2050     //    ]
2051     // Since the symbols are sorted, adding them to the symtab in the given
2052     // order means the $ld$previous version of _zzz will prevail, as desired.
2053     dylib->symbols.push_back(symtab->addDylib(
2054         saver().save(symbolName), dylib, /*isWeakDef=*/false, /*isTlv=*/false));
2055     return;
2056   }
2057 
2058   // A $ld$previous$ symbol without symbol name modifies the dylib it's in.
2059   this->installName = saver().save(installName);
2060   this->compatibilityVersion = newCompatibilityVersion;
2061 }
2062 
2063 void DylibFile::handleLDInstallNameSymbol(StringRef name,
2064                                           StringRef originalName) {
2065   // originalName: $ld$ install_name $ os<version> $ install_name
2066   StringRef condition, installName;
2067   std::tie(condition, installName) = name.split('$');
2068   VersionTuple version;
2069   if (!condition.consume_front("os") || version.tryParse(condition))
2070     warn(toString(this) + ": failed to parse os version, symbol '" +
2071          originalName + "' ignored");
2072   else if (version == config->platformInfo.minimum)
2073     this->installName = saver().save(installName);
2074 }
2075 
2076 void DylibFile::handleLDHideSymbol(StringRef name, StringRef originalName) {
2077   StringRef symbolName;
2078   bool shouldHide = true;
2079   if (name.startswith("os")) {
2080     // If it's hidden based on versions.
2081     name = name.drop_front(2);
2082     StringRef minVersion;
2083     std::tie(minVersion, symbolName) = name.split('$');
2084     VersionTuple versionTup;
2085     if (versionTup.tryParse(minVersion)) {
2086       warn(toString(this) + ": failed to parse hidden version, symbol `" + originalName +
2087            "` ignored.");
2088       return;
2089     }
2090     shouldHide = versionTup == config->platformInfo.minimum;
2091   } else {
2092     symbolName = name;
2093   }
2094 
2095   if (shouldHide)
2096     exportingFile->hiddenSymbols.insert(CachedHashStringRef(symbolName));
2097 }
2098 
2099 void DylibFile::checkAppExtensionSafety(bool dylibIsAppExtensionSafe) const {
2100   if (config->applicationExtension && !dylibIsAppExtensionSafe)
2101     warn("using '-application_extension' with unsafe dylib: " + toString(this));
2102 }
2103 
2104 ArchiveFile::ArchiveFile(std::unique_ptr<object::Archive> &&f, bool forceHidden)
2105     : InputFile(ArchiveKind, f->getMemoryBufferRef()), file(std::move(f)),
2106       forceHidden(forceHidden) {}
2107 
2108 void ArchiveFile::addLazySymbols() {
2109   for (const object::Archive::Symbol &sym : file->symbols())
2110     symtab->addLazyArchive(sym.getName(), this, sym);
2111 }
2112 
2113 static Expected<InputFile *>
2114 loadArchiveMember(MemoryBufferRef mb, uint32_t modTime, StringRef archiveName,
2115                   uint64_t offsetInArchive, bool forceHidden) {
2116   if (config->zeroModTime)
2117     modTime = 0;
2118 
2119   switch (identify_magic(mb.getBuffer())) {
2120   case file_magic::macho_object:
2121     return make<ObjFile>(mb, modTime, archiveName, /*lazy=*/false, forceHidden);
2122   case file_magic::bitcode:
2123     return make<BitcodeFile>(mb, archiveName, offsetInArchive, /*lazy=*/false,
2124                              forceHidden);
2125   default:
2126     return createStringError(inconvertibleErrorCode(),
2127                              mb.getBufferIdentifier() +
2128                                  " has unhandled file type");
2129   }
2130 }
2131 
2132 Error ArchiveFile::fetch(const object::Archive::Child &c, StringRef reason) {
2133   if (!seen.insert(c.getChildOffset()).second)
2134     return Error::success();
2135 
2136   Expected<MemoryBufferRef> mb = c.getMemoryBufferRef();
2137   if (!mb)
2138     return mb.takeError();
2139 
2140   // Thin archives refer to .o files, so --reproduce needs the .o files too.
2141   if (tar && c.getParent()->isThin())
2142     tar->append(relativeToRoot(CHECK(c.getFullName(), this)), mb->getBuffer());
2143 
2144   Expected<TimePoint<std::chrono::seconds>> modTime = c.getLastModified();
2145   if (!modTime)
2146     return modTime.takeError();
2147 
2148   Expected<InputFile *> file = loadArchiveMember(
2149       *mb, toTimeT(*modTime), getName(), c.getChildOffset(), forceHidden);
2150 
2151   if (!file)
2152     return file.takeError();
2153 
2154   inputFiles.insert(*file);
2155   printArchiveMemberLoad(reason, *file);
2156   return Error::success();
2157 }
2158 
2159 void ArchiveFile::fetch(const object::Archive::Symbol &sym) {
2160   object::Archive::Child c =
2161       CHECK(sym.getMember(), toString(this) +
2162                                  ": could not get the member defining symbol " +
2163                                  toMachOString(sym));
2164 
2165   // `sym` is owned by a LazySym, which will be replace<>()d by make<ObjFile>
2166   // and become invalid after that call. Copy it to the stack so we can refer
2167   // to it later.
2168   const object::Archive::Symbol symCopy = sym;
2169 
2170   // ld64 doesn't demangle sym here even with -demangle.
2171   // Match that: intentionally don't call toMachOString().
2172   if (Error e = fetch(c, symCopy.getName()))
2173     error(toString(this) + ": could not get the member defining symbol " +
2174           toMachOString(symCopy) + ": " + toString(std::move(e)));
2175 }
2176 
2177 static macho::Symbol *createBitcodeSymbol(const lto::InputFile::Symbol &objSym,
2178                                           BitcodeFile &file) {
2179   StringRef name = saver().save(objSym.getName());
2180 
2181   if (objSym.isUndefined())
2182     return symtab->addUndefined(name, &file, /*isWeakRef=*/objSym.isWeak());
2183 
2184   // TODO: Write a test demonstrating why computing isPrivateExtern before
2185   // LTO compilation is important.
2186   bool isPrivateExtern = false;
2187   switch (objSym.getVisibility()) {
2188   case GlobalValue::HiddenVisibility:
2189     isPrivateExtern = true;
2190     break;
2191   case GlobalValue::ProtectedVisibility:
2192     error(name + " has protected visibility, which is not supported by Mach-O");
2193     break;
2194   case GlobalValue::DefaultVisibility:
2195     break;
2196   }
2197   isPrivateExtern = isPrivateExtern || objSym.canBeOmittedFromSymbolTable() ||
2198                     file.forceHidden;
2199 
2200   if (objSym.isCommon())
2201     return symtab->addCommon(name, &file, objSym.getCommonSize(),
2202                              objSym.getCommonAlignment(), isPrivateExtern);
2203 
2204   return symtab->addDefined(name, &file, /*isec=*/nullptr, /*value=*/0,
2205                             /*size=*/0, objSym.isWeak(), isPrivateExtern,
2206                             /*isThumb=*/false,
2207                             /*isReferencedDynamically=*/false,
2208                             /*noDeadStrip=*/false,
2209                             /*isWeakDefCanBeHidden=*/false);
2210 }
2211 
2212 BitcodeFile::BitcodeFile(MemoryBufferRef mb, StringRef archiveName,
2213                          uint64_t offsetInArchive, bool lazy, bool forceHidden)
2214     : InputFile(BitcodeKind, mb, lazy), forceHidden(forceHidden) {
2215   this->archiveName = std::string(archiveName);
2216   std::string path = mb.getBufferIdentifier().str();
2217   if (config->thinLTOIndexOnly)
2218     path = replaceThinLTOSuffix(mb.getBufferIdentifier());
2219 
2220   // ThinLTO assumes that all MemoryBufferRefs given to it have a unique
2221   // name. If two members with the same name are provided, this causes a
2222   // collision and ThinLTO can't proceed.
2223   // So, we append the archive name to disambiguate two members with the same
2224   // name from multiple different archives, and offset within the archive to
2225   // disambiguate two members of the same name from a single archive.
2226   MemoryBufferRef mbref(mb.getBuffer(),
2227                         saver().save(archiveName.empty()
2228                                          ? path
2229                                          : archiveName +
2230                                                sys::path::filename(path) +
2231                                                utostr(offsetInArchive)));
2232 
2233   obj = check(lto::InputFile::create(mbref));
2234   if (lazy)
2235     parseLazy();
2236   else
2237     parse();
2238 }
2239 
2240 void BitcodeFile::parse() {
2241   // Convert LTO Symbols to LLD Symbols in order to perform resolution. The
2242   // "winning" symbol will then be marked as Prevailing at LTO compilation
2243   // time.
2244   symbols.clear();
2245   for (const lto::InputFile::Symbol &objSym : obj->symbols())
2246     symbols.push_back(createBitcodeSymbol(objSym, *this));
2247 }
2248 
2249 void BitcodeFile::parseLazy() {
2250   symbols.resize(obj->symbols().size());
2251   for (const auto &[i, objSym] : llvm::enumerate(obj->symbols())) {
2252     if (!objSym.isUndefined()) {
2253       symbols[i] = symtab->addLazyObject(saver().save(objSym.getName()), *this);
2254       if (!lazy)
2255         break;
2256     }
2257   }
2258 }
2259 
2260 std::string macho::replaceThinLTOSuffix(StringRef path) {
2261   auto [suffix, repl] = config->thinLTOObjectSuffixReplace;
2262   if (path.consume_back(suffix))
2263     return (path + repl).str();
2264   return std::string(path);
2265 }
2266 
2267 void macho::extract(InputFile &file, StringRef reason) {
2268   if (!file.lazy)
2269     return;
2270   file.lazy = false;
2271 
2272   printArchiveMemberLoad(reason, &file);
2273   if (auto *bitcode = dyn_cast<BitcodeFile>(&file)) {
2274     bitcode->parse();
2275   } else {
2276     auto &f = cast<ObjFile>(file);
2277     if (target->wordSize == 8)
2278       f.parse<LP64>();
2279     else
2280       f.parse<ILP32>();
2281   }
2282 }
2283 
2284 template void ObjFile::parse<LP64>();
2285