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