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 "ExportTrie.h"
49 #include "InputSection.h"
50 #include "MachOStructs.h"
51 #include "ObjC.h"
52 #include "OutputSection.h"
53 #include "OutputSegment.h"
54 #include "SymbolTable.h"
55 #include "Symbols.h"
56 #include "SyntheticSections.h"
57 #include "Target.h"
58 
59 #include "lld/Common/CommonLinkerContext.h"
60 #include "lld/Common/DWARF.h"
61 #include "lld/Common/Reproduce.h"
62 #include "llvm/ADT/iterator.h"
63 #include "llvm/BinaryFormat/MachO.h"
64 #include "llvm/LTO/LTO.h"
65 #include "llvm/Support/BinaryStreamReader.h"
66 #include "llvm/Support/Endian.h"
67 #include "llvm/Support/MemoryBuffer.h"
68 #include "llvm/Support/Path.h"
69 #include "llvm/Support/TarWriter.h"
70 #include "llvm/Support/TimeProfiler.h"
71 #include "llvm/TextAPI/Architecture.h"
72 #include "llvm/TextAPI/InterfaceFile.h"
73 
74 #include <type_traits>
75 
76 using namespace llvm;
77 using namespace llvm::MachO;
78 using namespace llvm::support::endian;
79 using namespace llvm::sys;
80 using namespace lld;
81 using namespace lld::macho;
82 
83 // Returns "<internal>", "foo.a(bar.o)", or "baz.o".
84 std::string lld::toString(const InputFile *f) {
85   if (!f)
86     return "<internal>";
87 
88   // Multiple dylibs can be defined in one .tbd file.
89   if (auto dylibFile = dyn_cast<DylibFile>(f))
90     if (f->getName().endswith(".tbd"))
91       return (f->getName() + "(" + dylibFile->installName + ")").str();
92 
93   if (f->archiveName.empty())
94     return std::string(f->getName());
95   return (f->archiveName + "(" + path::filename(f->getName()) + ")").str();
96 }
97 
98 std::string lld::toString(const Section &sec) {
99   return (toString(sec.file) + ":(" + sec.name + ")").str();
100 }
101 
102 SetVector<InputFile *> macho::inputFiles;
103 std::unique_ptr<TarWriter> macho::tar;
104 int InputFile::idCount = 0;
105 
106 static VersionTuple decodeVersion(uint32_t version) {
107   unsigned major = version >> 16;
108   unsigned minor = (version >> 8) & 0xffu;
109   unsigned subMinor = version & 0xffu;
110   return VersionTuple(major, minor, subMinor);
111 }
112 
113 static std::vector<PlatformInfo> getPlatformInfos(const InputFile *input) {
114   if (!isa<ObjFile>(input) && !isa<DylibFile>(input))
115     return {};
116 
117   const char *hdr = input->mb.getBufferStart();
118 
119   // "Zippered" object files can have multiple LC_BUILD_VERSION load commands.
120   std::vector<PlatformInfo> platformInfos;
121   for (auto *cmd : findCommands<build_version_command>(hdr, LC_BUILD_VERSION)) {
122     PlatformInfo info;
123     info.target.Platform = static_cast<PlatformType>(cmd->platform);
124     info.minimum = decodeVersion(cmd->minos);
125     platformInfos.emplace_back(std::move(info));
126   }
127   for (auto *cmd : findCommands<version_min_command>(
128            hdr, LC_VERSION_MIN_MACOSX, LC_VERSION_MIN_IPHONEOS,
129            LC_VERSION_MIN_TVOS, LC_VERSION_MIN_WATCHOS)) {
130     PlatformInfo info;
131     switch (cmd->cmd) {
132     case LC_VERSION_MIN_MACOSX:
133       info.target.Platform = PLATFORM_MACOS;
134       break;
135     case LC_VERSION_MIN_IPHONEOS:
136       info.target.Platform = PLATFORM_IOS;
137       break;
138     case LC_VERSION_MIN_TVOS:
139       info.target.Platform = PLATFORM_TVOS;
140       break;
141     case LC_VERSION_MIN_WATCHOS:
142       info.target.Platform = PLATFORM_WATCHOS;
143       break;
144     }
145     info.minimum = decodeVersion(cmd->version);
146     platformInfos.emplace_back(std::move(info));
147   }
148 
149   return platformInfos;
150 }
151 
152 static bool checkCompatibility(const InputFile *input) {
153   std::vector<PlatformInfo> platformInfos = getPlatformInfos(input);
154   if (platformInfos.empty())
155     return true;
156 
157   auto it = find_if(platformInfos, [&](const PlatformInfo &info) {
158     return removeSimulator(info.target.Platform) ==
159            removeSimulator(config->platform());
160   });
161   if (it == platformInfos.end()) {
162     std::string platformNames;
163     raw_string_ostream os(platformNames);
164     interleave(
165         platformInfos, os,
166         [&](const PlatformInfo &info) {
167           os << getPlatformName(info.target.Platform);
168         },
169         "/");
170     error(toString(input) + " has platform " + platformNames +
171           Twine(", which is different from target platform ") +
172           getPlatformName(config->platform()));
173     return false;
174   }
175 
176   if (it->minimum > config->platformInfo.minimum)
177     warn(toString(input) + " has version " + it->minimum.getAsString() +
178          ", which is newer than target minimum of " +
179          config->platformInfo.minimum.getAsString());
180 
181   return true;
182 }
183 
184 // This cache mostly exists to store system libraries (and .tbds) as they're
185 // loaded, rather than the input archives, which are already cached at a higher
186 // level, and other files like the filelist that are only read once.
187 // Theoretically this caching could be more efficient by hoisting it, but that
188 // would require altering many callers to track the state.
189 DenseMap<CachedHashStringRef, MemoryBufferRef> macho::cachedReads;
190 // Open a given file path and return it as a memory-mapped file.
191 Optional<MemoryBufferRef> macho::readFile(StringRef path) {
192   CachedHashStringRef key(path);
193   auto entry = cachedReads.find(key);
194   if (entry != cachedReads.end())
195     return entry->second;
196 
197   ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr = MemoryBuffer::getFile(path);
198   if (std::error_code ec = mbOrErr.getError()) {
199     error("cannot open " + path + ": " + ec.message());
200     return None;
201   }
202 
203   std::unique_ptr<MemoryBuffer> &mb = *mbOrErr;
204   MemoryBufferRef mbref = mb->getMemBufferRef();
205   make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take mb ownership
206 
207   // If this is a regular non-fat file, return it.
208   const char *buf = mbref.getBufferStart();
209   const auto *hdr = reinterpret_cast<const fat_header *>(buf);
210   if (mbref.getBufferSize() < sizeof(uint32_t) ||
211       read32be(&hdr->magic) != FAT_MAGIC) {
212     if (tar)
213       tar->append(relativeToRoot(path), mbref.getBuffer());
214     return cachedReads[key] = mbref;
215   }
216 
217   llvm::BumpPtrAllocator &bAlloc = lld::bAlloc();
218 
219   // Object files and archive files may be fat files, which contain multiple
220   // real files for different CPU ISAs. Here, we search for a file that matches
221   // with the current link target and returns it as a MemoryBufferRef.
222   const auto *arch = reinterpret_cast<const fat_arch *>(buf + sizeof(*hdr));
223 
224   for (uint32_t i = 0, n = read32be(&hdr->nfat_arch); i < n; ++i) {
225     if (reinterpret_cast<const char *>(arch + i + 1) >
226         buf + mbref.getBufferSize()) {
227       error(path + ": fat_arch struct extends beyond end of file");
228       return None;
229     }
230 
231     if (read32be(&arch[i].cputype) != static_cast<uint32_t>(target->cpuType) ||
232         read32be(&arch[i].cpusubtype) != target->cpuSubtype)
233       continue;
234 
235     uint32_t offset = read32be(&arch[i].offset);
236     uint32_t size = read32be(&arch[i].size);
237     if (offset + size > mbref.getBufferSize())
238       error(path + ": slice extends beyond end of file");
239     if (tar)
240       tar->append(relativeToRoot(path), mbref.getBuffer());
241     return cachedReads[key] = MemoryBufferRef(StringRef(buf + offset, size),
242                                               path.copy(bAlloc));
243   }
244 
245   error("unable to find matching architecture in " + path);
246   return None;
247 }
248 
249 InputFile::InputFile(Kind kind, const InterfaceFile &interface)
250     : id(idCount++), fileKind(kind), name(saver().save(interface.getPath())) {}
251 
252 // Some sections comprise of fixed-size records, so instead of splitting them at
253 // symbol boundaries, we split them based on size. Records are distinct from
254 // literals in that they may contain references to other sections, instead of
255 // being leaf nodes in the InputSection graph.
256 //
257 // Note that "record" is a term I came up with. In contrast, "literal" is a term
258 // used by the Mach-O format.
259 static Optional<size_t> getRecordSize(StringRef segname, StringRef name) {
260   if (name == section_names::compactUnwind) {
261       if (segname == segment_names::ld)
262         return target->wordSize == 8 ? 32 : 20;
263   }
264   if (config->icfLevel == ICFLevel::none)
265     return {};
266 
267   if (name == section_names::cfString && segname == segment_names::data)
268     return target->wordSize == 8 ? 32 : 16;
269   if (name == section_names::objcClassRefs && segname == segment_names::data)
270     return target->wordSize;
271   return {};
272 }
273 
274 static Error parseCallGraph(ArrayRef<uint8_t> data,
275                             std::vector<CallGraphEntry> &callGraph) {
276   TimeTraceScope timeScope("Parsing call graph section");
277   BinaryStreamReader reader(data, support::little);
278   while (!reader.empty()) {
279     uint32_t fromIndex, toIndex;
280     uint64_t count;
281     if (Error err = reader.readInteger(fromIndex))
282       return err;
283     if (Error err = reader.readInteger(toIndex))
284       return err;
285     if (Error err = reader.readInteger(count))
286       return err;
287     callGraph.emplace_back(fromIndex, toIndex, count);
288   }
289   return Error::success();
290 }
291 
292 // Parse the sequence of sections within a single LC_SEGMENT(_64).
293 // Split each section into subsections.
294 template <class SectionHeader>
295 void ObjFile::parseSections(ArrayRef<SectionHeader> sectionHeaders) {
296   sections.reserve(sectionHeaders.size());
297   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
298 
299   for (const SectionHeader &sec : sectionHeaders) {
300     StringRef name =
301         StringRef(sec.sectname, strnlen(sec.sectname, sizeof(sec.sectname)));
302     StringRef segname =
303         StringRef(sec.segname, strnlen(sec.segname, sizeof(sec.segname)));
304     sections.push_back(make<Section>(this, segname, name, sec.flags, sec.addr));
305     if (sec.align >= 32) {
306       error("alignment " + std::to_string(sec.align) + " of section " + name +
307             " is too large");
308       continue;
309     }
310     Section &section = *sections.back();
311     uint32_t align = 1 << sec.align;
312     ArrayRef<uint8_t> data = {isZeroFill(sec.flags) ? nullptr
313                                                     : buf + sec.offset,
314                               static_cast<size_t>(sec.size)};
315 
316     auto splitRecords = [&](int recordSize) -> void {
317       if (data.empty())
318         return;
319       Subsections &subsections = section.subsections;
320       subsections.reserve(data.size() / recordSize);
321       for (uint64_t off = 0; off < data.size(); off += recordSize) {
322         auto *isec = make<ConcatInputSection>(
323             section, data.slice(off, recordSize), align);
324         subsections.push_back({off, isec});
325       }
326     };
327 
328     if (sectionType(sec.flags) == S_CSTRING_LITERALS ||
329         (config->dedupLiterals && isWordLiteralSection(sec.flags))) {
330       if (sec.nreloc && config->dedupLiterals)
331         fatal(toString(this) + " contains relocations in " + sec.segname + "," +
332               sec.sectname +
333               ", so LLD cannot deduplicate literals. Try re-running without "
334               "--deduplicate-literals.");
335 
336       InputSection *isec;
337       if (sectionType(sec.flags) == S_CSTRING_LITERALS) {
338         isec = make<CStringInputSection>(section, data, align);
339         // FIXME: parallelize this?
340         cast<CStringInputSection>(isec)->splitIntoPieces();
341       } else {
342         isec = make<WordLiteralInputSection>(section, data, align);
343       }
344       section.subsections.push_back({0, isec});
345     } else if (auto recordSize = getRecordSize(segname, name)) {
346       splitRecords(*recordSize);
347     } else if (segname == segment_names::llvm) {
348       if (config->callGraphProfileSort && name == section_names::cgProfile)
349         checkError(parseCallGraph(data, callGraph));
350       // ld64 does not appear to emit contents from sections within the __LLVM
351       // segment. Symbols within those sections point to bitcode metadata
352       // instead of actual symbols. Global symbols within those sections could
353       // have the same name without causing duplicate symbol errors. To avoid
354       // spurious duplicate symbol errors, we do not parse these sections.
355       // TODO: Evaluate whether the bitcode metadata is needed.
356     } else {
357       if (name == section_names::addrSig)
358         addrSigSection = sections.back();
359 
360       auto *isec = make<ConcatInputSection>(section, data, align);
361       if (isDebugSection(isec->getFlags()) &&
362           isec->getSegName() == segment_names::dwarf) {
363         // Instead of emitting DWARF sections, we emit STABS symbols to the
364         // object files that contain them. We filter them out early to avoid
365         // parsing their relocations unnecessarily.
366         debugSections.push_back(isec);
367       } else {
368         section.subsections.push_back({0, isec});
369       }
370     }
371   }
372 }
373 
374 // Find the subsection corresponding to the greatest section offset that is <=
375 // that of the given offset.
376 //
377 // offset: an offset relative to the start of the original InputSection (before
378 // any subsection splitting has occurred). It will be updated to represent the
379 // same location as an offset relative to the start of the containing
380 // subsection.
381 template <class T>
382 static InputSection *findContainingSubsection(const Section &section,
383                                               T *offset) {
384   static_assert(std::is_same<uint64_t, T>::value ||
385                     std::is_same<uint32_t, T>::value,
386                 "unexpected type for offset");
387   auto it = std::prev(llvm::upper_bound(
388       section.subsections, *offset,
389       [](uint64_t value, Subsection subsec) { return value < subsec.offset; }));
390   *offset -= it->offset;
391   return it->isec;
392 }
393 
394 // Find a symbol at offset `off` within `isec`.
395 static Defined *findSymbolAtOffset(const ConcatInputSection *isec,
396                                    uint64_t off) {
397   auto it = llvm::lower_bound(isec->symbols, off, [](Defined *d, uint64_t off) {
398     return d->value < off;
399   });
400   // The offset should point at the exact address of a symbol (with no addend.)
401   if (it == isec->symbols.end() || (*it)->value != off) {
402     assert(isec->wasCoalesced);
403     return nullptr;
404   }
405   return *it;
406 }
407 
408 template <class SectionHeader>
409 static bool validateRelocationInfo(InputFile *file, const SectionHeader &sec,
410                                    relocation_info rel) {
411   const RelocAttrs &relocAttrs = target->getRelocAttrs(rel.r_type);
412   bool valid = true;
413   auto message = [relocAttrs, file, sec, rel, &valid](const Twine &diagnostic) {
414     valid = false;
415     return (relocAttrs.name + " relocation " + diagnostic + " at offset " +
416             std::to_string(rel.r_address) + " of " + sec.segname + "," +
417             sec.sectname + " in " + toString(file))
418         .str();
419   };
420 
421   if (!relocAttrs.hasAttr(RelocAttrBits::LOCAL) && !rel.r_extern)
422     error(message("must be extern"));
423   if (relocAttrs.hasAttr(RelocAttrBits::PCREL) != rel.r_pcrel)
424     error(message(Twine("must ") + (rel.r_pcrel ? "not " : "") +
425                   "be PC-relative"));
426   if (isThreadLocalVariables(sec.flags) &&
427       !relocAttrs.hasAttr(RelocAttrBits::UNSIGNED))
428     error(message("not allowed in thread-local section, must be UNSIGNED"));
429   if (rel.r_length < 2 || rel.r_length > 3 ||
430       !relocAttrs.hasAttr(static_cast<RelocAttrBits>(1 << rel.r_length))) {
431     static SmallVector<StringRef, 4> widths{"0", "4", "8", "4 or 8"};
432     error(message("has width " + std::to_string(1 << rel.r_length) +
433                   " bytes, but must be " +
434                   widths[(static_cast<int>(relocAttrs.bits) >> 2) & 3] +
435                   " bytes"));
436   }
437   return valid;
438 }
439 
440 template <class SectionHeader>
441 void ObjFile::parseRelocations(ArrayRef<SectionHeader> sectionHeaders,
442                                const SectionHeader &sec,
443                                Section &section) {
444   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
445   ArrayRef<relocation_info> relInfos(
446       reinterpret_cast<const relocation_info *>(buf + sec.reloff), sec.nreloc);
447 
448   Subsections &subsections = section.subsections;
449   auto subsecIt = subsections.rbegin();
450   for (size_t i = 0; i < relInfos.size(); i++) {
451     // Paired relocations serve as Mach-O's method for attaching a
452     // supplemental datum to a primary relocation record. ELF does not
453     // need them because the *_RELOC_RELA records contain the extra
454     // addend field, vs. *_RELOC_REL which omit the addend.
455     //
456     // The {X86_64,ARM64}_RELOC_SUBTRACTOR record holds the subtrahend,
457     // and the paired *_RELOC_UNSIGNED record holds the minuend. The
458     // datum for each is a symbolic address. The result is the offset
459     // between two addresses.
460     //
461     // The ARM64_RELOC_ADDEND record holds the addend, and the paired
462     // ARM64_RELOC_BRANCH26 or ARM64_RELOC_PAGE21/PAGEOFF12 holds the
463     // base symbolic address.
464     //
465     // Note: X86 does not use *_RELOC_ADDEND because it can embed an
466     // addend into the instruction stream. On X86, a relocatable address
467     // field always occupies an entire contiguous sequence of byte(s),
468     // so there is no need to merge opcode bits with address
469     // bits. Therefore, it's easy and convenient to store addends in the
470     // instruction-stream bytes that would otherwise contain zeroes. By
471     // contrast, RISC ISAs such as ARM64 mix opcode bits with with
472     // address bits so that bitwise arithmetic is necessary to extract
473     // and insert them. Storing addends in the instruction stream is
474     // possible, but inconvenient and more costly at link time.
475 
476     relocation_info relInfo = relInfos[i];
477     bool isSubtrahend =
478         target->hasAttr(relInfo.r_type, RelocAttrBits::SUBTRAHEND);
479     if (isSubtrahend && StringRef(sec.sectname) == section_names::ehFrame) {
480       // __TEXT,__eh_frame only has symbols and SUBTRACTOR relocs when ld64 -r
481       // adds local "EH_Frame1" and "func.eh". Ignore them because they have
482       // gone unused by Mac OS since Snow Leopard (10.6), vintage 2009.
483       ++i;
484       continue;
485     }
486     int64_t pairedAddend = 0;
487     if (target->hasAttr(relInfo.r_type, RelocAttrBits::ADDEND)) {
488       pairedAddend = SignExtend64<24>(relInfo.r_symbolnum);
489       relInfo = relInfos[++i];
490     }
491     assert(i < relInfos.size());
492     if (!validateRelocationInfo(this, sec, relInfo))
493       continue;
494     if (relInfo.r_address & R_SCATTERED)
495       fatal("TODO: Scattered relocations not supported");
496 
497     int64_t embeddedAddend = target->getEmbeddedAddend(mb, sec.offset, relInfo);
498     assert(!(embeddedAddend && pairedAddend));
499     int64_t totalAddend = pairedAddend + embeddedAddend;
500     Reloc r;
501     r.type = relInfo.r_type;
502     r.pcrel = relInfo.r_pcrel;
503     r.length = relInfo.r_length;
504     r.offset = relInfo.r_address;
505     if (relInfo.r_extern) {
506       r.referent = symbols[relInfo.r_symbolnum];
507       r.addend = isSubtrahend ? 0 : totalAddend;
508     } else {
509       assert(!isSubtrahend);
510       const SectionHeader &referentSecHead =
511           sectionHeaders[relInfo.r_symbolnum - 1];
512       uint64_t referentOffset;
513       if (relInfo.r_pcrel) {
514         // The implicit addend for pcrel section relocations is the pcrel offset
515         // in terms of the addresses in the input file. Here we adjust it so
516         // that it describes the offset from the start of the referent section.
517         // FIXME This logic was written around x86_64 behavior -- ARM64 doesn't
518         // have pcrel section relocations. We may want to factor this out into
519         // the arch-specific .cpp file.
520         assert(target->hasAttr(r.type, RelocAttrBits::BYTE4));
521         referentOffset = sec.addr + relInfo.r_address + 4 + totalAddend -
522                          referentSecHead.addr;
523       } else {
524         // The addend for a non-pcrel relocation is its absolute address.
525         referentOffset = totalAddend - referentSecHead.addr;
526       }
527       r.referent = findContainingSubsection(*sections[relInfo.r_symbolnum - 1],
528                                             &referentOffset);
529       r.addend = referentOffset;
530     }
531 
532     // Find the subsection that this relocation belongs to.
533     // Though not required by the Mach-O format, clang and gcc seem to emit
534     // relocations in order, so let's take advantage of it. However, ld64 emits
535     // unsorted relocations (in `-r` mode), so we have a fallback for that
536     // uncommon case.
537     InputSection *subsec;
538     while (subsecIt != subsections.rend() && subsecIt->offset > r.offset)
539       ++subsecIt;
540     if (subsecIt == subsections.rend() ||
541         subsecIt->offset + subsecIt->isec->getSize() <= r.offset) {
542       subsec = findContainingSubsection(section, &r.offset);
543       // Now that we know the relocs are unsorted, avoid trying the 'fast path'
544       // for the other relocations.
545       subsecIt = subsections.rend();
546     } else {
547       subsec = subsecIt->isec;
548       r.offset -= subsecIt->offset;
549     }
550     subsec->relocs.push_back(r);
551 
552     if (isSubtrahend) {
553       relocation_info minuendInfo = relInfos[++i];
554       // SUBTRACTOR relocations should always be followed by an UNSIGNED one
555       // attached to the same address.
556       assert(target->hasAttr(minuendInfo.r_type, RelocAttrBits::UNSIGNED) &&
557              relInfo.r_address == minuendInfo.r_address);
558       Reloc p;
559       p.type = minuendInfo.r_type;
560       if (minuendInfo.r_extern) {
561         p.referent = symbols[minuendInfo.r_symbolnum];
562         p.addend = totalAddend;
563       } else {
564         uint64_t referentOffset =
565             totalAddend - sectionHeaders[minuendInfo.r_symbolnum - 1].addr;
566         p.referent = findContainingSubsection(
567             *sections[minuendInfo.r_symbolnum - 1], &referentOffset);
568         p.addend = referentOffset;
569       }
570       subsec->relocs.push_back(p);
571     }
572   }
573 }
574 
575 template <class NList>
576 static macho::Symbol *createDefined(const NList &sym, StringRef name,
577                                     InputSection *isec, uint64_t value,
578                                     uint64_t size) {
579   // Symbol scope is determined by sym.n_type & (N_EXT | N_PEXT):
580   // N_EXT: Global symbols. These go in the symbol table during the link,
581   //        and also in the export table of the output so that the dynamic
582   //        linker sees them.
583   // N_EXT | N_PEXT: Linkage unit (think: dylib) scoped. These go in the
584   //                 symbol table during the link so that duplicates are
585   //                 either reported (for non-weak symbols) or merged
586   //                 (for weak symbols), but they do not go in the export
587   //                 table of the output.
588   // N_PEXT: llvm-mc does not emit these, but `ld -r` (wherein ld64 emits
589   //         object files) may produce them. LLD does not yet support -r.
590   //         These are translation-unit scoped, identical to the `0` case.
591   // 0: Translation-unit scoped. These are not in the symbol table during
592   //    link, and not in the export table of the output either.
593   bool isWeakDefCanBeHidden =
594       (sym.n_desc & (N_WEAK_DEF | N_WEAK_REF)) == (N_WEAK_DEF | N_WEAK_REF);
595 
596   if (sym.n_type & N_EXT) {
597     bool isPrivateExtern = sym.n_type & N_PEXT;
598     // lld's behavior for merging symbols is slightly different from ld64:
599     // ld64 picks the winning symbol based on several criteria (see
600     // pickBetweenRegularAtoms() in ld64's SymbolTable.cpp), while lld
601     // just merges metadata and keeps the contents of the first symbol
602     // with that name (see SymbolTable::addDefined). For:
603     // * inline function F in a TU built with -fvisibility-inlines-hidden
604     // * and inline function F in another TU built without that flag
605     // ld64 will pick the one from the file built without
606     // -fvisibility-inlines-hidden.
607     // lld will instead pick the one listed first on the link command line and
608     // give it visibility as if the function was built without
609     // -fvisibility-inlines-hidden.
610     // If both functions have the same contents, this will have the same
611     // behavior. If not, it won't, but the input had an ODR violation in
612     // that case.
613     //
614     // Similarly, merging a symbol
615     // that's isPrivateExtern and not isWeakDefCanBeHidden with one
616     // that's not isPrivateExtern but isWeakDefCanBeHidden technically
617     // should produce one
618     // that's not isPrivateExtern but isWeakDefCanBeHidden. That matters
619     // with ld64's semantics, because it means the non-private-extern
620     // definition will continue to take priority if more private extern
621     // definitions are encountered. With lld's semantics there's no observable
622     // difference between a symbol that's isWeakDefCanBeHidden(autohide) or one
623     // that's privateExtern -- neither makes it into the dynamic symbol table,
624     // unless the autohide symbol is explicitly exported.
625     // But if a symbol is both privateExtern and autohide then it can't
626     // be exported.
627     // So we nullify the autohide flag when privateExtern is present
628     // and promote the symbol to privateExtern when it is not already.
629     if (isWeakDefCanBeHidden && isPrivateExtern)
630       isWeakDefCanBeHidden = false;
631     else if (isWeakDefCanBeHidden)
632       isPrivateExtern = true;
633     return symtab->addDefined(
634         name, isec->getFile(), isec, value, size, sym.n_desc & N_WEAK_DEF,
635         isPrivateExtern, sym.n_desc & N_ARM_THUMB_DEF,
636         sym.n_desc & REFERENCED_DYNAMICALLY, sym.n_desc & N_NO_DEAD_STRIP,
637         isWeakDefCanBeHidden);
638   }
639   assert(!isWeakDefCanBeHidden &&
640          "weak_def_can_be_hidden on already-hidden symbol?");
641   bool includeInSymtab = !name.startswith("l") && !name.startswith("L");
642   return make<Defined>(
643       name, isec->getFile(), isec, value, size, sym.n_desc & N_WEAK_DEF,
644       /*isExternal=*/false, /*isPrivateExtern=*/false, includeInSymtab,
645       sym.n_desc & N_ARM_THUMB_DEF, sym.n_desc & REFERENCED_DYNAMICALLY,
646       sym.n_desc & N_NO_DEAD_STRIP);
647 }
648 
649 // Absolute symbols are defined symbols that do not have an associated
650 // InputSection. They cannot be weak.
651 template <class NList>
652 static macho::Symbol *createAbsolute(const NList &sym, InputFile *file,
653                                      StringRef name) {
654   if (sym.n_type & N_EXT) {
655     return symtab->addDefined(
656         name, file, nullptr, sym.n_value, /*size=*/0,
657         /*isWeakDef=*/false, sym.n_type & N_PEXT, sym.n_desc & N_ARM_THUMB_DEF,
658         /*isReferencedDynamically=*/false, sym.n_desc & N_NO_DEAD_STRIP,
659         /*isWeakDefCanBeHidden=*/false);
660   }
661   return make<Defined>(name, file, nullptr, sym.n_value, /*size=*/0,
662                        /*isWeakDef=*/false,
663                        /*isExternal=*/false, /*isPrivateExtern=*/false,
664                        /*includeInSymtab=*/true, sym.n_desc & N_ARM_THUMB_DEF,
665                        /*isReferencedDynamically=*/false,
666                        sym.n_desc & N_NO_DEAD_STRIP);
667 }
668 
669 template <class NList>
670 macho::Symbol *ObjFile::parseNonSectionSymbol(const NList &sym,
671                                               StringRef name) {
672   uint8_t type = sym.n_type & N_TYPE;
673   switch (type) {
674   case N_UNDF:
675     return sym.n_value == 0
676                ? symtab->addUndefined(name, this, sym.n_desc & N_WEAK_REF)
677                : symtab->addCommon(name, this, sym.n_value,
678                                    1 << GET_COMM_ALIGN(sym.n_desc),
679                                    sym.n_type & N_PEXT);
680   case N_ABS:
681     return createAbsolute(sym, this, name);
682   case N_PBUD:
683   case N_INDR:
684     error("TODO: support symbols of type " + std::to_string(type));
685     return nullptr;
686   case N_SECT:
687     llvm_unreachable(
688         "N_SECT symbols should not be passed to parseNonSectionSymbol");
689   default:
690     llvm_unreachable("invalid symbol type");
691   }
692 }
693 
694 template <class NList> static bool isUndef(const NList &sym) {
695   return (sym.n_type & N_TYPE) == N_UNDF && sym.n_value == 0;
696 }
697 
698 template <class LP>
699 void ObjFile::parseSymbols(ArrayRef<typename LP::section> sectionHeaders,
700                            ArrayRef<typename LP::nlist> nList,
701                            const char *strtab, bool subsectionsViaSymbols) {
702   using NList = typename LP::nlist;
703 
704   // Groups indices of the symbols by the sections that contain them.
705   std::vector<std::vector<uint32_t>> symbolsBySection(sections.size());
706   symbols.resize(nList.size());
707   SmallVector<unsigned, 32> undefineds;
708   for (uint32_t i = 0; i < nList.size(); ++i) {
709     const NList &sym = nList[i];
710 
711     // Ignore debug symbols for now.
712     // FIXME: may need special handling.
713     if (sym.n_type & N_STAB)
714       continue;
715 
716     StringRef name = strtab + sym.n_strx;
717     if ((sym.n_type & N_TYPE) == N_SECT) {
718       Subsections &subsections = sections[sym.n_sect - 1]->subsections;
719       // parseSections() may have chosen not to parse this section.
720       if (subsections.empty())
721         continue;
722       symbolsBySection[sym.n_sect - 1].push_back(i);
723     } else if (isUndef(sym)) {
724       undefineds.push_back(i);
725     } else {
726       symbols[i] = parseNonSectionSymbol(sym, name);
727     }
728   }
729 
730   for (size_t i = 0; i < sections.size(); ++i) {
731     Subsections &subsections = sections[i]->subsections;
732     if (subsections.empty())
733       continue;
734     if (sections[i]->name == section_names::ehFrame) {
735       // __TEXT,__eh_frame only has symbols and SUBTRACTOR relocs when ld64 -r
736       // adds local "EH_Frame1" and "func.eh". Ignore them because they have
737       // gone unused by Mac OS since Snow Leopard (10.6), vintage 2009.
738       continue;
739     }
740     std::vector<uint32_t> &symbolIndices = symbolsBySection[i];
741     uint64_t sectionAddr = sectionHeaders[i].addr;
742     uint32_t sectionAlign = 1u << sectionHeaders[i].align;
743 
744     // Record-based sections have already been split into subsections during
745     // parseSections(), so we simply need to match Symbols to the corresponding
746     // subsection here.
747     if (getRecordSize(sections[i]->segname, sections[i]->name)) {
748       for (size_t j = 0; j < symbolIndices.size(); ++j) {
749         uint32_t symIndex = symbolIndices[j];
750         const NList &sym = nList[symIndex];
751         StringRef name = strtab + sym.n_strx;
752         uint64_t symbolOffset = sym.n_value - sectionAddr;
753         InputSection *isec =
754             findContainingSubsection(*sections[i], &symbolOffset);
755         if (symbolOffset != 0) {
756           error(toString(*sections[i]) + ":  symbol " + name +
757                 " at misaligned offset");
758           continue;
759         }
760         symbols[symIndex] = createDefined(sym, name, isec, 0, isec->getSize());
761       }
762       continue;
763     }
764 
765     // Calculate symbol sizes and create subsections by splitting the sections
766     // along symbol boundaries.
767     // We populate subsections by repeatedly splitting the last (highest
768     // address) subsection.
769     llvm::stable_sort(symbolIndices, [&](uint32_t lhs, uint32_t rhs) {
770       return nList[lhs].n_value < nList[rhs].n_value;
771     });
772     for (size_t j = 0; j < symbolIndices.size(); ++j) {
773       uint32_t symIndex = symbolIndices[j];
774       const NList &sym = nList[symIndex];
775       StringRef name = strtab + sym.n_strx;
776       Subsection &subsec = subsections.back();
777       InputSection *isec = subsec.isec;
778 
779       uint64_t subsecAddr = sectionAddr + subsec.offset;
780       size_t symbolOffset = sym.n_value - subsecAddr;
781       uint64_t symbolSize =
782           j + 1 < symbolIndices.size()
783               ? nList[symbolIndices[j + 1]].n_value - sym.n_value
784               : isec->data.size() - symbolOffset;
785       // There are 4 cases where we do not need to create a new subsection:
786       //   1. If the input file does not use subsections-via-symbols.
787       //   2. Multiple symbols at the same address only induce one subsection.
788       //      (The symbolOffset == 0 check covers both this case as well as
789       //      the first loop iteration.)
790       //   3. Alternative entry points do not induce new subsections.
791       //   4. If we have a literal section (e.g. __cstring and __literal4).
792       if (!subsectionsViaSymbols || symbolOffset == 0 ||
793           sym.n_desc & N_ALT_ENTRY || !isa<ConcatInputSection>(isec)) {
794         symbols[symIndex] =
795             createDefined(sym, name, isec, symbolOffset, symbolSize);
796         continue;
797       }
798       auto *concatIsec = cast<ConcatInputSection>(isec);
799 
800       auto *nextIsec = make<ConcatInputSection>(*concatIsec);
801       nextIsec->wasCoalesced = false;
802       if (isZeroFill(isec->getFlags())) {
803         // Zero-fill sections have NULL data.data() non-zero data.size()
804         nextIsec->data = {nullptr, isec->data.size() - symbolOffset};
805         isec->data = {nullptr, symbolOffset};
806       } else {
807         nextIsec->data = isec->data.slice(symbolOffset);
808         isec->data = isec->data.slice(0, symbolOffset);
809       }
810 
811       // By construction, the symbol will be at offset zero in the new
812       // subsection.
813       symbols[symIndex] =
814           createDefined(sym, name, nextIsec, /*value=*/0, symbolSize);
815       // TODO: ld64 appears to preserve the original alignment as well as each
816       // subsection's offset from the last aligned address. We should consider
817       // emulating that behavior.
818       nextIsec->align = MinAlign(sectionAlign, sym.n_value);
819       subsections.push_back({sym.n_value - sectionAddr, nextIsec});
820     }
821   }
822 
823   // Undefined symbols can trigger recursive fetch from Archives due to
824   // LazySymbols. Process defined symbols first so that the relative order
825   // between a defined symbol and an undefined symbol does not change the
826   // symbol resolution behavior. In addition, a set of interconnected symbols
827   // will all be resolved to the same file, instead of being resolved to
828   // different files.
829   for (unsigned i : undefineds) {
830     const NList &sym = nList[i];
831     StringRef name = strtab + sym.n_strx;
832     symbols[i] = parseNonSectionSymbol(sym, name);
833   }
834 }
835 
836 OpaqueFile::OpaqueFile(MemoryBufferRef mb, StringRef segName,
837                        StringRef sectName)
838     : InputFile(OpaqueKind, mb) {
839   const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
840   ArrayRef<uint8_t> data = {buf, mb.getBufferSize()};
841   sections.push_back(make<Section>(/*file=*/this, segName.take_front(16),
842                                    sectName.take_front(16),
843                                    /*flags=*/0, /*addr=*/0));
844   Section &section = *sections.back();
845   ConcatInputSection *isec = make<ConcatInputSection>(section, data);
846   isec->live = true;
847   section.subsections.push_back({0, isec});
848 }
849 
850 ObjFile::ObjFile(MemoryBufferRef mb, uint32_t modTime, StringRef archiveName,
851                  bool lazy)
852     : InputFile(ObjKind, mb, lazy), modTime(modTime) {
853   this->archiveName = std::string(archiveName);
854   if (lazy) {
855     if (target->wordSize == 8)
856       parseLazy<LP64>();
857     else
858       parseLazy<ILP32>();
859   } else {
860     if (target->wordSize == 8)
861       parse<LP64>();
862     else
863       parse<ILP32>();
864   }
865 }
866 
867 template <class LP> void ObjFile::parse() {
868   using Header = typename LP::mach_header;
869   using SegmentCommand = typename LP::segment_command;
870   using SectionHeader = typename LP::section;
871   using NList = typename LP::nlist;
872 
873   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
874   auto *hdr = reinterpret_cast<const Header *>(mb.getBufferStart());
875 
876   Architecture arch = getArchitectureFromCpuType(hdr->cputype, hdr->cpusubtype);
877   if (arch != config->arch()) {
878     auto msg = config->errorForArchMismatch
879                    ? static_cast<void (*)(const Twine &)>(error)
880                    : warn;
881     msg(toString(this) + " has architecture " + getArchitectureName(arch) +
882         " which is incompatible with target architecture " +
883         getArchitectureName(config->arch()));
884     return;
885   }
886 
887   if (!checkCompatibility(this))
888     return;
889 
890   for (auto *cmd : findCommands<linker_option_command>(hdr, LC_LINKER_OPTION)) {
891     StringRef data{reinterpret_cast<const char *>(cmd + 1),
892                    cmd->cmdsize - sizeof(linker_option_command)};
893     parseLCLinkerOption(this, cmd->count, data);
894   }
895 
896   ArrayRef<SectionHeader> sectionHeaders;
897   if (const load_command *cmd = findCommand(hdr, LP::segmentLCType)) {
898     auto *c = reinterpret_cast<const SegmentCommand *>(cmd);
899     sectionHeaders = ArrayRef<SectionHeader>{
900         reinterpret_cast<const SectionHeader *>(c + 1), c->nsects};
901     parseSections(sectionHeaders);
902   }
903 
904   // TODO: Error on missing LC_SYMTAB?
905   if (const load_command *cmd = findCommand(hdr, LC_SYMTAB)) {
906     auto *c = reinterpret_cast<const symtab_command *>(cmd);
907     ArrayRef<NList> nList(reinterpret_cast<const NList *>(buf + c->symoff),
908                           c->nsyms);
909     const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff;
910     bool subsectionsViaSymbols = hdr->flags & MH_SUBSECTIONS_VIA_SYMBOLS;
911     parseSymbols<LP>(sectionHeaders, nList, strtab, subsectionsViaSymbols);
912   }
913 
914   // The relocations may refer to the symbols, so we parse them after we have
915   // parsed all the symbols.
916   for (size_t i = 0, n = sections.size(); i < n; ++i)
917     if (!sections[i]->subsections.empty())
918       parseRelocations(sectionHeaders, sectionHeaders[i], *sections[i]);
919 
920   parseDebugInfo();
921 
922   Section *ehFrameSection = nullptr;
923   Section *compactUnwindSection = nullptr;
924   for (Section *sec : sections) {
925     Section **s = StringSwitch<Section **>(sec->name)
926                       .Case(section_names::compactUnwind, &compactUnwindSection)
927                       .Case(section_names::ehFrame, &ehFrameSection)
928                       .Default(nullptr);
929     if (s)
930       *s = sec;
931   }
932   if (compactUnwindSection)
933     registerCompactUnwind(*compactUnwindSection);
934 }
935 
936 template <class LP> void ObjFile::parseLazy() {
937   using Header = typename LP::mach_header;
938   using NList = typename LP::nlist;
939 
940   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
941   auto *hdr = reinterpret_cast<const Header *>(mb.getBufferStart());
942   const load_command *cmd = findCommand(hdr, LC_SYMTAB);
943   if (!cmd)
944     return;
945   auto *c = reinterpret_cast<const symtab_command *>(cmd);
946   ArrayRef<NList> nList(reinterpret_cast<const NList *>(buf + c->symoff),
947                         c->nsyms);
948   const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff;
949   symbols.resize(nList.size());
950   for (auto it : llvm::enumerate(nList)) {
951     const NList &sym = it.value();
952     if ((sym.n_type & N_EXT) && !isUndef(sym)) {
953       // TODO: Bound checking
954       StringRef name = strtab + sym.n_strx;
955       symbols[it.index()] = symtab->addLazyObject(name, *this);
956       if (!lazy)
957         break;
958     }
959   }
960 }
961 
962 void ObjFile::parseDebugInfo() {
963   std::unique_ptr<DwarfObject> dObj = DwarfObject::create(this);
964   if (!dObj)
965     return;
966 
967   auto *ctx = make<DWARFContext>(
968       std::move(dObj), "",
969       [&](Error err) {
970         warn(toString(this) + ": " + toString(std::move(err)));
971       },
972       [&](Error warning) {
973         warn(toString(this) + ": " + toString(std::move(warning)));
974       });
975 
976   // TODO: Since object files can contain a lot of DWARF info, we should verify
977   // that we are parsing just the info we need
978   const DWARFContext::compile_unit_range &units = ctx->compile_units();
979   // FIXME: There can be more than one compile unit per object file. See
980   // PR48637.
981   auto it = units.begin();
982   compileUnit = it->get();
983 }
984 
985 ArrayRef<data_in_code_entry> ObjFile::getDataInCode() const {
986   const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
987   const load_command *cmd = findCommand(buf, LC_DATA_IN_CODE);
988   if (!cmd)
989     return {};
990   const auto *c = reinterpret_cast<const linkedit_data_command *>(cmd);
991   return {reinterpret_cast<const data_in_code_entry *>(buf + c->dataoff),
992           c->datasize / sizeof(data_in_code_entry)};
993 }
994 
995 // Create pointers from symbols to their associated compact unwind entries.
996 void ObjFile::registerCompactUnwind(Section &compactUnwindSection) {
997   for (const Subsection &subsection : compactUnwindSection.subsections) {
998     ConcatInputSection *isec = cast<ConcatInputSection>(subsection.isec);
999     // Hack!! Since each CUE contains a different function address, if ICF
1000     // operated naively and compared the entire contents of each CUE, entries
1001     // with identical unwind info but belonging to different functions would
1002     // never be considered equivalent. To work around this problem, we slice
1003     // away the function address here. (Note that we do not adjust the offsets
1004     // of the corresponding relocations.) We rely on `relocateCompactUnwind()`
1005     // to correctly handle these truncated input sections.
1006     isec->data = isec->data.slice(target->wordSize);
1007 
1008     ConcatInputSection *referentIsec;
1009     for (auto it = isec->relocs.begin(); it != isec->relocs.end();) {
1010       Reloc &r = *it;
1011       // CUE::functionAddress is at offset 0. Skip personality & LSDA relocs.
1012       if (r.offset != 0) {
1013         ++it;
1014         continue;
1015       }
1016       uint64_t add = r.addend;
1017       if (auto *sym = cast_or_null<Defined>(r.referent.dyn_cast<Symbol *>())) {
1018         // Check whether the symbol defined in this file is the prevailing one.
1019         // Skip if it is e.g. a weak def that didn't prevail.
1020         if (sym->getFile() != this) {
1021           ++it;
1022           continue;
1023         }
1024         add += sym->value;
1025         referentIsec = cast<ConcatInputSection>(sym->isec);
1026       } else {
1027         referentIsec =
1028             cast<ConcatInputSection>(r.referent.dyn_cast<InputSection *>());
1029       }
1030       // Unwind info lives in __DATA, and finalization of __TEXT will occur
1031       // before finalization of __DATA. Moreover, the finalization of unwind
1032       // info depends on the exact addresses that it references. So it is safe
1033       // for compact unwind to reference addresses in __TEXT, but not addresses
1034       // in any other segment.
1035       if (referentIsec->getSegName() != segment_names::text)
1036         error(isec->getLocation(r.offset) + " references section " +
1037               referentIsec->getName() + " which is not in segment __TEXT");
1038       // The functionAddress relocations are typically section relocations.
1039       // However, unwind info operates on a per-symbol basis, so we search for
1040       // the function symbol here.
1041       Defined *d = findSymbolAtOffset(referentIsec, add);
1042       if (!d) {
1043         ++it;
1044         continue;
1045       }
1046       d->unwindEntry = isec;
1047       // Since we've sliced away the functionAddress, we should remove the
1048       // corresponding relocation too. Given that clang emits relocations in
1049       // reverse order of address, this relocation should be at the end of the
1050       // vector for most of our input object files, so this is typically an O(1)
1051       // operation.
1052       it = isec->relocs.erase(it);
1053     }
1054   }
1055 }
1056 
1057 // The path can point to either a dylib or a .tbd file.
1058 static DylibFile *loadDylib(StringRef path, DylibFile *umbrella) {
1059   Optional<MemoryBufferRef> mbref = readFile(path);
1060   if (!mbref) {
1061     error("could not read dylib file at " + path);
1062     return nullptr;
1063   }
1064   return loadDylib(*mbref, umbrella);
1065 }
1066 
1067 // TBD files are parsed into a series of TAPI documents (InterfaceFiles), with
1068 // the first document storing child pointers to the rest of them. When we are
1069 // processing a given TBD file, we store that top-level document in
1070 // currentTopLevelTapi. When processing re-exports, we search its children for
1071 // potentially matching documents in the same TBD file. Note that the children
1072 // themselves don't point to further documents, i.e. this is a two-level tree.
1073 //
1074 // Re-exports can either refer to on-disk files, or to documents within .tbd
1075 // files.
1076 static DylibFile *findDylib(StringRef path, DylibFile *umbrella,
1077                             const InterfaceFile *currentTopLevelTapi) {
1078   // Search order:
1079   // 1. Install name basename in -F / -L directories.
1080   {
1081     StringRef stem = path::stem(path);
1082     SmallString<128> frameworkName;
1083     path::append(frameworkName, path::Style::posix, stem + ".framework", stem);
1084     bool isFramework = path.endswith(frameworkName);
1085     if (isFramework) {
1086       for (StringRef dir : config->frameworkSearchPaths) {
1087         SmallString<128> candidate = dir;
1088         path::append(candidate, frameworkName);
1089         if (Optional<StringRef> dylibPath = resolveDylibPath(candidate.str()))
1090           return loadDylib(*dylibPath, umbrella);
1091       }
1092     } else if (Optional<StringRef> dylibPath = findPathCombination(
1093                    stem, config->librarySearchPaths, {".tbd", ".dylib"}))
1094       return loadDylib(*dylibPath, umbrella);
1095   }
1096 
1097   // 2. As absolute path.
1098   if (path::is_absolute(path, path::Style::posix))
1099     for (StringRef root : config->systemLibraryRoots)
1100       if (Optional<StringRef> dylibPath = resolveDylibPath((root + path).str()))
1101         return loadDylib(*dylibPath, umbrella);
1102 
1103   // 3. As relative path.
1104 
1105   // TODO: Handle -dylib_file
1106 
1107   // Replace @executable_path, @loader_path, @rpath prefixes in install name.
1108   SmallString<128> newPath;
1109   if (config->outputType == MH_EXECUTE &&
1110       path.consume_front("@executable_path/")) {
1111     // ld64 allows overriding this with the undocumented flag -executable_path.
1112     // lld doesn't currently implement that flag.
1113     // FIXME: Consider using finalOutput instead of outputFile.
1114     path::append(newPath, path::parent_path(config->outputFile), path);
1115     path = newPath;
1116   } else if (path.consume_front("@loader_path/")) {
1117     fs::real_path(umbrella->getName(), newPath);
1118     path::remove_filename(newPath);
1119     path::append(newPath, path);
1120     path = newPath;
1121   } else if (path.startswith("@rpath/")) {
1122     for (StringRef rpath : umbrella->rpaths) {
1123       newPath.clear();
1124       if (rpath.consume_front("@loader_path/")) {
1125         fs::real_path(umbrella->getName(), newPath);
1126         path::remove_filename(newPath);
1127       }
1128       path::append(newPath, rpath, path.drop_front(strlen("@rpath/")));
1129       if (Optional<StringRef> dylibPath = resolveDylibPath(newPath.str()))
1130         return loadDylib(*dylibPath, umbrella);
1131     }
1132   }
1133 
1134   // FIXME: Should this be further up?
1135   if (currentTopLevelTapi) {
1136     for (InterfaceFile &child :
1137          make_pointee_range(currentTopLevelTapi->documents())) {
1138       assert(child.documents().empty());
1139       if (path == child.getInstallName()) {
1140         auto file = make<DylibFile>(child, umbrella, /*isBundleLoader=*/false,
1141                                     /*explicitlyLinked=*/false);
1142         file->parseReexports(child);
1143         return file;
1144       }
1145     }
1146   }
1147 
1148   if (Optional<StringRef> dylibPath = resolveDylibPath(path))
1149     return loadDylib(*dylibPath, umbrella);
1150 
1151   return nullptr;
1152 }
1153 
1154 // If a re-exported dylib is public (lives in /usr/lib or
1155 // /System/Library/Frameworks), then it is considered implicitly linked: we
1156 // should bind to its symbols directly instead of via the re-exporting umbrella
1157 // library.
1158 static bool isImplicitlyLinked(StringRef path) {
1159   if (!config->implicitDylibs)
1160     return false;
1161 
1162   if (path::parent_path(path) == "/usr/lib")
1163     return true;
1164 
1165   // Match /System/Library/Frameworks/$FOO.framework/**/$FOO
1166   if (path.consume_front("/System/Library/Frameworks/")) {
1167     StringRef frameworkName = path.take_until([](char c) { return c == '.'; });
1168     return path::filename(path) == frameworkName;
1169   }
1170 
1171   return false;
1172 }
1173 
1174 static void loadReexport(StringRef path, DylibFile *umbrella,
1175                          const InterfaceFile *currentTopLevelTapi) {
1176   DylibFile *reexport = findDylib(path, umbrella, currentTopLevelTapi);
1177   if (!reexport)
1178     error("unable to locate re-export with install name " + path);
1179 }
1180 
1181 DylibFile::DylibFile(MemoryBufferRef mb, DylibFile *umbrella,
1182                      bool isBundleLoader, bool explicitlyLinked)
1183     : InputFile(DylibKind, mb), refState(RefState::Unreferenced),
1184       explicitlyLinked(explicitlyLinked), isBundleLoader(isBundleLoader) {
1185   assert(!isBundleLoader || !umbrella);
1186   if (umbrella == nullptr)
1187     umbrella = this;
1188   this->umbrella = umbrella;
1189 
1190   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
1191   auto *hdr = reinterpret_cast<const mach_header *>(mb.getBufferStart());
1192 
1193   // Initialize installName.
1194   if (const load_command *cmd = findCommand(hdr, LC_ID_DYLIB)) {
1195     auto *c = reinterpret_cast<const dylib_command *>(cmd);
1196     currentVersion = read32le(&c->dylib.current_version);
1197     compatibilityVersion = read32le(&c->dylib.compatibility_version);
1198     installName =
1199         reinterpret_cast<const char *>(cmd) + read32le(&c->dylib.name);
1200   } else if (!isBundleLoader) {
1201     // macho_executable and macho_bundle don't have LC_ID_DYLIB,
1202     // so it's OK.
1203     error("dylib " + toString(this) + " missing LC_ID_DYLIB load command");
1204     return;
1205   }
1206 
1207   if (config->printEachFile)
1208     message(toString(this));
1209   inputFiles.insert(this);
1210 
1211   deadStrippable = hdr->flags & MH_DEAD_STRIPPABLE_DYLIB;
1212 
1213   if (!checkCompatibility(this))
1214     return;
1215 
1216   checkAppExtensionSafety(hdr->flags & MH_APP_EXTENSION_SAFE);
1217 
1218   for (auto *cmd : findCommands<rpath_command>(hdr, LC_RPATH)) {
1219     StringRef rpath{reinterpret_cast<const char *>(cmd) + cmd->path};
1220     rpaths.push_back(rpath);
1221   }
1222 
1223   // Initialize symbols.
1224   exportingFile = isImplicitlyLinked(installName) ? this : this->umbrella;
1225   if (const load_command *cmd = findCommand(hdr, LC_DYLD_INFO_ONLY)) {
1226     auto *c = reinterpret_cast<const dyld_info_command *>(cmd);
1227     struct TrieEntry {
1228       StringRef name;
1229       uint64_t flags;
1230     };
1231 
1232     std::vector<TrieEntry> entries;
1233     // Find all the $ld$* symbols to process first.
1234     parseTrie(buf + c->export_off, c->export_size,
1235               [&](const Twine &name, uint64_t flags) {
1236                 StringRef savedName = saver().save(name);
1237                 if (handleLDSymbol(savedName))
1238                   return;
1239                 entries.push_back({savedName, flags});
1240               });
1241 
1242     // Process the "normal" symbols.
1243     for (TrieEntry &entry : entries) {
1244       if (exportingFile->hiddenSymbols.contains(
1245               CachedHashStringRef(entry.name)))
1246         continue;
1247 
1248       bool isWeakDef = entry.flags & EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION;
1249       bool isTlv = entry.flags & EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL;
1250 
1251       symbols.push_back(
1252           symtab->addDylib(entry.name, exportingFile, isWeakDef, isTlv));
1253     }
1254 
1255   } else {
1256     error("LC_DYLD_INFO_ONLY not found in " + toString(this));
1257     return;
1258   }
1259 }
1260 
1261 void DylibFile::parseLoadCommands(MemoryBufferRef mb) {
1262   auto *hdr = reinterpret_cast<const mach_header *>(mb.getBufferStart());
1263   const uint8_t *p = reinterpret_cast<const uint8_t *>(mb.getBufferStart()) +
1264                      target->headerSize;
1265   for (uint32_t i = 0, n = hdr->ncmds; i < n; ++i) {
1266     auto *cmd = reinterpret_cast<const load_command *>(p);
1267     p += cmd->cmdsize;
1268 
1269     if (!(hdr->flags & MH_NO_REEXPORTED_DYLIBS) &&
1270         cmd->cmd == LC_REEXPORT_DYLIB) {
1271       const auto *c = reinterpret_cast<const dylib_command *>(cmd);
1272       StringRef reexportPath =
1273           reinterpret_cast<const char *>(c) + read32le(&c->dylib.name);
1274       loadReexport(reexportPath, exportingFile, nullptr);
1275     }
1276 
1277     // FIXME: What about LC_LOAD_UPWARD_DYLIB, LC_LAZY_LOAD_DYLIB,
1278     // LC_LOAD_WEAK_DYLIB, LC_REEXPORT_DYLIB (..are reexports from dylibs with
1279     // MH_NO_REEXPORTED_DYLIBS loaded for -flat_namespace)?
1280     if (config->namespaceKind == NamespaceKind::flat &&
1281         cmd->cmd == LC_LOAD_DYLIB) {
1282       const auto *c = reinterpret_cast<const dylib_command *>(cmd);
1283       StringRef dylibPath =
1284           reinterpret_cast<const char *>(c) + read32le(&c->dylib.name);
1285       DylibFile *dylib = findDylib(dylibPath, umbrella, nullptr);
1286       if (!dylib)
1287         error(Twine("unable to locate library '") + dylibPath +
1288               "' loaded from '" + toString(this) + "' for -flat_namespace");
1289     }
1290   }
1291 }
1292 
1293 // Some versions of Xcode ship with .tbd files that don't have the right
1294 // platform settings.
1295 constexpr std::array<StringRef, 3> skipPlatformChecks{
1296     "/usr/lib/system/libsystem_kernel.dylib",
1297     "/usr/lib/system/libsystem_platform.dylib",
1298     "/usr/lib/system/libsystem_pthread.dylib"};
1299 
1300 static bool skipPlatformCheckForCatalyst(const InterfaceFile &interface,
1301                                          bool explicitlyLinked) {
1302   // Catalyst outputs can link against implicitly linked macOS-only libraries.
1303   if (config->platform() != PLATFORM_MACCATALYST || explicitlyLinked)
1304     return false;
1305   return is_contained(interface.targets(),
1306                       MachO::Target(config->arch(), PLATFORM_MACOS));
1307 }
1308 
1309 DylibFile::DylibFile(const InterfaceFile &interface, DylibFile *umbrella,
1310                      bool isBundleLoader, bool explicitlyLinked)
1311     : InputFile(DylibKind, interface), refState(RefState::Unreferenced),
1312       explicitlyLinked(explicitlyLinked), isBundleLoader(isBundleLoader) {
1313   // FIXME: Add test for the missing TBD code path.
1314 
1315   if (umbrella == nullptr)
1316     umbrella = this;
1317   this->umbrella = umbrella;
1318 
1319   installName = saver().save(interface.getInstallName());
1320   compatibilityVersion = interface.getCompatibilityVersion().rawValue();
1321   currentVersion = interface.getCurrentVersion().rawValue();
1322 
1323   if (config->printEachFile)
1324     message(toString(this));
1325   inputFiles.insert(this);
1326 
1327   if (!is_contained(skipPlatformChecks, installName) &&
1328       !is_contained(interface.targets(), config->platformInfo.target) &&
1329       !skipPlatformCheckForCatalyst(interface, explicitlyLinked)) {
1330     error(toString(this) + " is incompatible with " +
1331           std::string(config->platformInfo.target));
1332     return;
1333   }
1334 
1335   checkAppExtensionSafety(interface.isApplicationExtensionSafe());
1336 
1337   exportingFile = isImplicitlyLinked(installName) ? this : umbrella;
1338   auto addSymbol = [&](const Twine &name) -> void {
1339     StringRef savedName = saver().save(name);
1340     if (exportingFile->hiddenSymbols.contains(CachedHashStringRef(savedName)))
1341       return;
1342 
1343     symbols.push_back(symtab->addDylib(savedName, exportingFile,
1344                                        /*isWeakDef=*/false,
1345                                        /*isTlv=*/false));
1346   };
1347 
1348   std::vector<const llvm::MachO::Symbol *> normalSymbols;
1349   normalSymbols.reserve(interface.symbolsCount());
1350   for (const auto *symbol : interface.symbols()) {
1351     if (!symbol->getArchitectures().has(config->arch()))
1352       continue;
1353     if (handleLDSymbol(symbol->getName()))
1354       continue;
1355 
1356     switch (symbol->getKind()) {
1357     case SymbolKind::GlobalSymbol:               // Fallthrough
1358     case SymbolKind::ObjectiveCClass:            // Fallthrough
1359     case SymbolKind::ObjectiveCClassEHType:      // Fallthrough
1360     case SymbolKind::ObjectiveCInstanceVariable: // Fallthrough
1361       normalSymbols.push_back(symbol);
1362     }
1363   }
1364 
1365   // TODO(compnerd) filter out symbols based on the target platform
1366   // TODO: handle weak defs, thread locals
1367   for (const auto *symbol : normalSymbols) {
1368     switch (symbol->getKind()) {
1369     case SymbolKind::GlobalSymbol:
1370       addSymbol(symbol->getName());
1371       break;
1372     case SymbolKind::ObjectiveCClass:
1373       // XXX ld64 only creates these symbols when -ObjC is passed in. We may
1374       // want to emulate that.
1375       addSymbol(objc::klass + symbol->getName());
1376       addSymbol(objc::metaclass + symbol->getName());
1377       break;
1378     case SymbolKind::ObjectiveCClassEHType:
1379       addSymbol(objc::ehtype + symbol->getName());
1380       break;
1381     case SymbolKind::ObjectiveCInstanceVariable:
1382       addSymbol(objc::ivar + symbol->getName());
1383       break;
1384     }
1385   }
1386 }
1387 
1388 void DylibFile::parseReexports(const InterfaceFile &interface) {
1389   const InterfaceFile *topLevel =
1390       interface.getParent() == nullptr ? &interface : interface.getParent();
1391   for (const InterfaceFileRef &intfRef : interface.reexportedLibraries()) {
1392     InterfaceFile::const_target_range targets = intfRef.targets();
1393     if (is_contained(skipPlatformChecks, intfRef.getInstallName()) ||
1394         is_contained(targets, config->platformInfo.target))
1395       loadReexport(intfRef.getInstallName(), exportingFile, topLevel);
1396   }
1397 }
1398 
1399 // $ld$ symbols modify the properties/behavior of the library (e.g. its install
1400 // name, compatibility version or hide/add symbols) for specific target
1401 // versions.
1402 bool DylibFile::handleLDSymbol(StringRef originalName) {
1403   if (!originalName.startswith("$ld$"))
1404     return false;
1405 
1406   StringRef action;
1407   StringRef name;
1408   std::tie(action, name) = originalName.drop_front(strlen("$ld$")).split('$');
1409   if (action == "previous")
1410     handleLDPreviousSymbol(name, originalName);
1411   else if (action == "install_name")
1412     handleLDInstallNameSymbol(name, originalName);
1413   else if (action == "hide")
1414     handleLDHideSymbol(name, originalName);
1415   return true;
1416 }
1417 
1418 void DylibFile::handleLDPreviousSymbol(StringRef name, StringRef originalName) {
1419   // originalName: $ld$ previous $ <installname> $ <compatversion> $
1420   // <platformstr> $ <startversion> $ <endversion> $ <symbol-name> $
1421   StringRef installName;
1422   StringRef compatVersion;
1423   StringRef platformStr;
1424   StringRef startVersion;
1425   StringRef endVersion;
1426   StringRef symbolName;
1427   StringRef rest;
1428 
1429   std::tie(installName, name) = name.split('$');
1430   std::tie(compatVersion, name) = name.split('$');
1431   std::tie(platformStr, name) = name.split('$');
1432   std::tie(startVersion, name) = name.split('$');
1433   std::tie(endVersion, name) = name.split('$');
1434   std::tie(symbolName, rest) = name.split('$');
1435   // TODO: ld64 contains some logic for non-empty symbolName as well.
1436   if (!symbolName.empty())
1437     return;
1438   unsigned platform;
1439   if (platformStr.getAsInteger(10, platform) ||
1440       platform != static_cast<unsigned>(config->platform()))
1441     return;
1442 
1443   VersionTuple start;
1444   if (start.tryParse(startVersion)) {
1445     warn("failed to parse start version, symbol '" + originalName +
1446          "' ignored");
1447     return;
1448   }
1449   VersionTuple end;
1450   if (end.tryParse(endVersion)) {
1451     warn("failed to parse end version, symbol '" + originalName + "' ignored");
1452     return;
1453   }
1454   if (config->platformInfo.minimum < start ||
1455       config->platformInfo.minimum >= end)
1456     return;
1457 
1458   this->installName = saver().save(installName);
1459 
1460   if (!compatVersion.empty()) {
1461     VersionTuple cVersion;
1462     if (cVersion.tryParse(compatVersion)) {
1463       warn("failed to parse compatibility version, symbol '" + originalName +
1464            "' ignored");
1465       return;
1466     }
1467     compatibilityVersion = encodeVersion(cVersion);
1468   }
1469 }
1470 
1471 void DylibFile::handleLDInstallNameSymbol(StringRef name,
1472                                           StringRef originalName) {
1473   // originalName: $ld$ install_name $ os<version> $ install_name
1474   StringRef condition, installName;
1475   std::tie(condition, installName) = name.split('$');
1476   VersionTuple version;
1477   if (!condition.consume_front("os") || version.tryParse(condition))
1478     warn("failed to parse os version, symbol '" + originalName + "' ignored");
1479   else if (version == config->platformInfo.minimum)
1480     this->installName = saver().save(installName);
1481 }
1482 
1483 void DylibFile::handleLDHideSymbol(StringRef name, StringRef originalName) {
1484   StringRef symbolName;
1485   bool shouldHide = true;
1486   if (name.startswith("os")) {
1487     // If it's hidden based on versions.
1488     name = name.drop_front(2);
1489     StringRef minVersion;
1490     std::tie(minVersion, symbolName) = name.split('$');
1491     VersionTuple versionTup;
1492     if (versionTup.tryParse(minVersion)) {
1493       warn("Failed to parse hidden version, symbol `" + originalName +
1494            "` ignored.");
1495       return;
1496     }
1497     shouldHide = versionTup == config->platformInfo.minimum;
1498   } else {
1499     symbolName = name;
1500   }
1501 
1502   if (shouldHide)
1503     exportingFile->hiddenSymbols.insert(CachedHashStringRef(symbolName));
1504 }
1505 
1506 void DylibFile::checkAppExtensionSafety(bool dylibIsAppExtensionSafe) const {
1507   if (config->applicationExtension && !dylibIsAppExtensionSafe)
1508     warn("using '-application_extension' with unsafe dylib: " + toString(this));
1509 }
1510 
1511 ArchiveFile::ArchiveFile(std::unique_ptr<object::Archive> &&f)
1512     : InputFile(ArchiveKind, f->getMemoryBufferRef()), file(std::move(f)) {}
1513 
1514 void ArchiveFile::addLazySymbols() {
1515   for (const object::Archive::Symbol &sym : file->symbols())
1516     symtab->addLazyArchive(sym.getName(), this, sym);
1517 }
1518 
1519 static Expected<InputFile *> loadArchiveMember(MemoryBufferRef mb,
1520                                                uint32_t modTime,
1521                                                StringRef archiveName,
1522                                                uint64_t offsetInArchive) {
1523   if (config->zeroModTime)
1524     modTime = 0;
1525 
1526   switch (identify_magic(mb.getBuffer())) {
1527   case file_magic::macho_object:
1528     return make<ObjFile>(mb, modTime, archiveName);
1529   case file_magic::bitcode:
1530     return make<BitcodeFile>(mb, archiveName, offsetInArchive);
1531   default:
1532     return createStringError(inconvertibleErrorCode(),
1533                              mb.getBufferIdentifier() +
1534                                  " has unhandled file type");
1535   }
1536 }
1537 
1538 Error ArchiveFile::fetch(const object::Archive::Child &c, StringRef reason) {
1539   if (!seen.insert(c.getChildOffset()).second)
1540     return Error::success();
1541 
1542   Expected<MemoryBufferRef> mb = c.getMemoryBufferRef();
1543   if (!mb)
1544     return mb.takeError();
1545 
1546   // Thin archives refer to .o files, so --reproduce needs the .o files too.
1547   if (tar && c.getParent()->isThin())
1548     tar->append(relativeToRoot(CHECK(c.getFullName(), this)), mb->getBuffer());
1549 
1550   Expected<TimePoint<std::chrono::seconds>> modTime = c.getLastModified();
1551   if (!modTime)
1552     return modTime.takeError();
1553 
1554   Expected<InputFile *> file =
1555       loadArchiveMember(*mb, toTimeT(*modTime), getName(), c.getChildOffset());
1556 
1557   if (!file)
1558     return file.takeError();
1559 
1560   inputFiles.insert(*file);
1561   printArchiveMemberLoad(reason, *file);
1562   return Error::success();
1563 }
1564 
1565 void ArchiveFile::fetch(const object::Archive::Symbol &sym) {
1566   object::Archive::Child c =
1567       CHECK(sym.getMember(), toString(this) +
1568                                  ": could not get the member defining symbol " +
1569                                  toMachOString(sym));
1570 
1571   // `sym` is owned by a LazySym, which will be replace<>()d by make<ObjFile>
1572   // and become invalid after that call. Copy it to the stack so we can refer
1573   // to it later.
1574   const object::Archive::Symbol symCopy = sym;
1575 
1576   // ld64 doesn't demangle sym here even with -demangle.
1577   // Match that: intentionally don't call toMachOString().
1578   if (Error e = fetch(c, symCopy.getName()))
1579     error(toString(this) + ": could not get the member defining symbol " +
1580           toMachOString(symCopy) + ": " + toString(std::move(e)));
1581 }
1582 
1583 static macho::Symbol *createBitcodeSymbol(const lto::InputFile::Symbol &objSym,
1584                                           BitcodeFile &file) {
1585   StringRef name = saver().save(objSym.getName());
1586 
1587   if (objSym.isUndefined())
1588     return symtab->addUndefined(name, &file, /*isWeakRef=*/objSym.isWeak());
1589 
1590   // TODO: Write a test demonstrating why computing isPrivateExtern before
1591   // LTO compilation is important.
1592   bool isPrivateExtern = false;
1593   switch (objSym.getVisibility()) {
1594   case GlobalValue::HiddenVisibility:
1595     isPrivateExtern = true;
1596     break;
1597   case GlobalValue::ProtectedVisibility:
1598     error(name + " has protected visibility, which is not supported by Mach-O");
1599     break;
1600   case GlobalValue::DefaultVisibility:
1601     break;
1602   }
1603   isPrivateExtern = isPrivateExtern || objSym.canBeOmittedFromSymbolTable();
1604 
1605   if (objSym.isCommon())
1606     return symtab->addCommon(name, &file, objSym.getCommonSize(),
1607                              objSym.getCommonAlignment(), isPrivateExtern);
1608 
1609   return symtab->addDefined(name, &file, /*isec=*/nullptr, /*value=*/0,
1610                             /*size=*/0, objSym.isWeak(), isPrivateExtern,
1611                             /*isThumb=*/false,
1612                             /*isReferencedDynamically=*/false,
1613                             /*noDeadStrip=*/false,
1614                             /*isWeakDefCanBeHidden=*/false);
1615 }
1616 
1617 BitcodeFile::BitcodeFile(MemoryBufferRef mb, StringRef archiveName,
1618                          uint64_t offsetInArchive, bool lazy)
1619     : InputFile(BitcodeKind, mb, lazy) {
1620   this->archiveName = std::string(archiveName);
1621   std::string path = mb.getBufferIdentifier().str();
1622   // ThinLTO assumes that all MemoryBufferRefs given to it have a unique
1623   // name. If two members with the same name are provided, this causes a
1624   // collision and ThinLTO can't proceed.
1625   // So, we append the archive name to disambiguate two members with the same
1626   // name from multiple different archives, and offset within the archive to
1627   // disambiguate two members of the same name from a single archive.
1628   MemoryBufferRef mbref(mb.getBuffer(),
1629                         saver().save(archiveName.empty()
1630                                          ? path
1631                                          : archiveName +
1632                                                sys::path::filename(path) +
1633                                                utostr(offsetInArchive)));
1634 
1635   obj = check(lto::InputFile::create(mbref));
1636   if (lazy)
1637     parseLazy();
1638   else
1639     parse();
1640 }
1641 
1642 void BitcodeFile::parse() {
1643   // Convert LTO Symbols to LLD Symbols in order to perform resolution. The
1644   // "winning" symbol will then be marked as Prevailing at LTO compilation
1645   // time.
1646   symbols.clear();
1647   for (const lto::InputFile::Symbol &objSym : obj->symbols())
1648     symbols.push_back(createBitcodeSymbol(objSym, *this));
1649 }
1650 
1651 void BitcodeFile::parseLazy() {
1652   symbols.resize(obj->symbols().size());
1653   for (auto it : llvm::enumerate(obj->symbols())) {
1654     const lto::InputFile::Symbol &objSym = it.value();
1655     if (!objSym.isUndefined()) {
1656       symbols[it.index()] =
1657           symtab->addLazyObject(saver().save(objSym.getName()), *this);
1658       if (!lazy)
1659         break;
1660     }
1661   }
1662 }
1663 
1664 void macho::extract(InputFile &file, StringRef reason) {
1665   assert(file.lazy);
1666   file.lazy = false;
1667   printArchiveMemberLoad(reason, &file);
1668   if (auto *bitcode = dyn_cast<BitcodeFile>(&file)) {
1669     bitcode->parse();
1670   } else {
1671     auto &f = cast<ObjFile>(file);
1672     if (target->wordSize == 8)
1673       f.parse<LP64>();
1674     else
1675       f.parse<ILP32>();
1676   }
1677 }
1678 
1679 template void ObjFile::parse<LP64>();
1680