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