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::cfString) {
256     if (config->icfLevel != ICFLevel::none && segname == segment_names::data)
257       return target->wordSize == 8 ? 32 : 16;
258   } else if (name == section_names::compactUnwind) {
259     if (segname == segment_names::ld)
260       return target->wordSize == 8 ? 32 : 20;
261   }
262   return {};
263 }
264 
265 static Error parseCallGraph(ArrayRef<uint8_t> data,
266                             std::vector<CallGraphEntry> &callGraph) {
267   TimeTraceScope timeScope("Parsing call graph section");
268   BinaryStreamReader reader(data, support::little);
269   while (!reader.empty()) {
270     uint32_t fromIndex, toIndex;
271     uint64_t count;
272     if (Error err = reader.readInteger(fromIndex))
273       return err;
274     if (Error err = reader.readInteger(toIndex))
275       return err;
276     if (Error err = reader.readInteger(count))
277       return err;
278     callGraph.emplace_back(fromIndex, toIndex, count);
279   }
280   return Error::success();
281 }
282 
283 // Parse the sequence of sections within a single LC_SEGMENT(_64).
284 // Split each section into subsections.
285 template <class SectionHeader>
286 void ObjFile::parseSections(ArrayRef<SectionHeader> sectionHeaders) {
287   sections.reserve(sectionHeaders.size());
288   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
289 
290   for (const SectionHeader &sec : sectionHeaders) {
291     StringRef name =
292         StringRef(sec.sectname, strnlen(sec.sectname, sizeof(sec.sectname)));
293     StringRef segname =
294         StringRef(sec.segname, strnlen(sec.segname, sizeof(sec.segname)));
295     ArrayRef<uint8_t> data = {isZeroFill(sec.flags) ? nullptr
296                                                     : buf + sec.offset,
297                               static_cast<size_t>(sec.size)};
298     sections.push_back(make<Section>(this, segname, name, sec.flags, sec.addr));
299     if (sec.align >= 32) {
300       error("alignment " + std::to_string(sec.align) + " of section " + name +
301             " is too large");
302       continue;
303     }
304     const Section &section = *sections.back();
305     uint32_t align = 1 << sec.align;
306 
307     auto splitRecords = [&](int recordSize) -> void {
308       if (data.empty())
309         return;
310       Subsections &subsections = sections.back()->subsections;
311       subsections.reserve(data.size() / recordSize);
312       for (uint64_t off = 0; off < data.size(); off += recordSize) {
313         auto *isec = make<ConcatInputSection>(
314             section, data.slice(off, recordSize), align);
315         subsections.push_back({off, isec});
316       }
317     };
318 
319     if (sectionType(sec.flags) == S_CSTRING_LITERALS ||
320         (config->dedupLiterals && isWordLiteralSection(sec.flags))) {
321       if (sec.nreloc && config->dedupLiterals)
322         fatal(toString(this) + " contains relocations in " + sec.segname + "," +
323               sec.sectname +
324               ", so LLD cannot deduplicate literals. Try re-running without "
325               "--deduplicate-literals.");
326 
327       InputSection *isec;
328       if (sectionType(sec.flags) == S_CSTRING_LITERALS) {
329         isec = make<CStringInputSection>(section, data, align);
330         // FIXME: parallelize this?
331         cast<CStringInputSection>(isec)->splitIntoPieces();
332       } else {
333         isec = make<WordLiteralInputSection>(section, data, align);
334       }
335       sections.back()->subsections.push_back({0, isec});
336     } else if (auto recordSize = getRecordSize(segname, name)) {
337       splitRecords(*recordSize);
338       if (name == section_names::compactUnwind)
339         compactUnwindSection = sections.back();
340     } else if (segname == segment_names::llvm) {
341       if (config->callGraphProfileSort && name == section_names::cgProfile)
342         checkError(parseCallGraph(data, callGraph));
343       // ld64 does not appear to emit contents from sections within the __LLVM
344       // segment. Symbols within those sections point to bitcode metadata
345       // instead of actual symbols. Global symbols within those sections could
346       // have the same name without causing duplicate symbol errors. To avoid
347       // spurious duplicate symbol errors, we do not parse these sections.
348       // TODO: Evaluate whether the bitcode metadata is needed.
349     } else {
350       auto *isec = make<ConcatInputSection>(section, data, align);
351       if (isDebugSection(isec->getFlags()) &&
352           isec->getSegName() == segment_names::dwarf) {
353         // Instead of emitting DWARF sections, we emit STABS symbols to the
354         // object files that contain them. We filter them out early to avoid
355         // parsing their relocations unnecessarily.
356         debugSections.push_back(isec);
357       } else {
358         sections.back()->subsections.push_back({0, isec});
359       }
360     }
361   }
362 }
363 
364 // Find the subsection corresponding to the greatest section offset that is <=
365 // that of the given offset.
366 //
367 // offset: an offset relative to the start of the original InputSection (before
368 // any subsection splitting has occurred). It will be updated to represent the
369 // same location as an offset relative to the start of the containing
370 // subsection.
371 template <class T>
372 static InputSection *findContainingSubsection(const Subsections &subsections,
373                                               T *offset) {
374   static_assert(std::is_same<uint64_t, T>::value ||
375                     std::is_same<uint32_t, T>::value,
376                 "unexpected type for offset");
377   auto it = std::prev(llvm::upper_bound(
378       subsections, *offset,
379       [](uint64_t value, Subsection subsec) { return value < subsec.offset; }));
380   *offset -= it->offset;
381   return it->isec;
382 }
383 
384 template <class SectionHeader>
385 static bool validateRelocationInfo(InputFile *file, const SectionHeader &sec,
386                                    relocation_info rel) {
387   const RelocAttrs &relocAttrs = target->getRelocAttrs(rel.r_type);
388   bool valid = true;
389   auto message = [relocAttrs, file, sec, rel, &valid](const Twine &diagnostic) {
390     valid = false;
391     return (relocAttrs.name + " relocation " + diagnostic + " at offset " +
392             std::to_string(rel.r_address) + " of " + sec.segname + "," +
393             sec.sectname + " in " + toString(file))
394         .str();
395   };
396 
397   if (!relocAttrs.hasAttr(RelocAttrBits::LOCAL) && !rel.r_extern)
398     error(message("must be extern"));
399   if (relocAttrs.hasAttr(RelocAttrBits::PCREL) != rel.r_pcrel)
400     error(message(Twine("must ") + (rel.r_pcrel ? "not " : "") +
401                   "be PC-relative"));
402   if (isThreadLocalVariables(sec.flags) &&
403       !relocAttrs.hasAttr(RelocAttrBits::UNSIGNED))
404     error(message("not allowed in thread-local section, must be UNSIGNED"));
405   if (rel.r_length < 2 || rel.r_length > 3 ||
406       !relocAttrs.hasAttr(static_cast<RelocAttrBits>(1 << rel.r_length))) {
407     static SmallVector<StringRef, 4> widths{"0", "4", "8", "4 or 8"};
408     error(message("has width " + std::to_string(1 << rel.r_length) +
409                   " bytes, but must be " +
410                   widths[(static_cast<int>(relocAttrs.bits) >> 2) & 3] +
411                   " bytes"));
412   }
413   return valid;
414 }
415 
416 template <class SectionHeader>
417 void ObjFile::parseRelocations(ArrayRef<SectionHeader> sectionHeaders,
418                                const SectionHeader &sec,
419                                Subsections &subsections) {
420   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
421   ArrayRef<relocation_info> relInfos(
422       reinterpret_cast<const relocation_info *>(buf + sec.reloff), sec.nreloc);
423 
424   auto subsecIt = subsections.rbegin();
425   for (size_t i = 0; i < relInfos.size(); i++) {
426     // Paired relocations serve as Mach-O's method for attaching a
427     // supplemental datum to a primary relocation record. ELF does not
428     // need them because the *_RELOC_RELA records contain the extra
429     // addend field, vs. *_RELOC_REL which omit the addend.
430     //
431     // The {X86_64,ARM64}_RELOC_SUBTRACTOR record holds the subtrahend,
432     // and the paired *_RELOC_UNSIGNED record holds the minuend. The
433     // datum for each is a symbolic address. The result is the offset
434     // between two addresses.
435     //
436     // The ARM64_RELOC_ADDEND record holds the addend, and the paired
437     // ARM64_RELOC_BRANCH26 or ARM64_RELOC_PAGE21/PAGEOFF12 holds the
438     // base symbolic address.
439     //
440     // Note: X86 does not use *_RELOC_ADDEND because it can embed an
441     // addend into the instruction stream. On X86, a relocatable address
442     // field always occupies an entire contiguous sequence of byte(s),
443     // so there is no need to merge opcode bits with address
444     // bits. Therefore, it's easy and convenient to store addends in the
445     // instruction-stream bytes that would otherwise contain zeroes. By
446     // contrast, RISC ISAs such as ARM64 mix opcode bits with with
447     // address bits so that bitwise arithmetic is necessary to extract
448     // and insert them. Storing addends in the instruction stream is
449     // possible, but inconvenient and more costly at link time.
450 
451     relocation_info relInfo = relInfos[i];
452     bool isSubtrahend =
453         target->hasAttr(relInfo.r_type, RelocAttrBits::SUBTRAHEND);
454     if (isSubtrahend && StringRef(sec.sectname) == section_names::ehFrame) {
455       // __TEXT,__eh_frame only has symbols and SUBTRACTOR relocs when ld64 -r
456       // adds local "EH_Frame1" and "func.eh". Ignore them because they have
457       // gone unused by Mac OS since Snow Leopard (10.6), vintage 2009.
458       ++i;
459       continue;
460     }
461     int64_t pairedAddend = 0;
462     if (target->hasAttr(relInfo.r_type, RelocAttrBits::ADDEND)) {
463       pairedAddend = SignExtend64<24>(relInfo.r_symbolnum);
464       relInfo = relInfos[++i];
465     }
466     assert(i < relInfos.size());
467     if (!validateRelocationInfo(this, sec, relInfo))
468       continue;
469     if (relInfo.r_address & R_SCATTERED)
470       fatal("TODO: Scattered relocations not supported");
471 
472     int64_t embeddedAddend = target->getEmbeddedAddend(mb, sec.offset, relInfo);
473     assert(!(embeddedAddend && pairedAddend));
474     int64_t totalAddend = pairedAddend + embeddedAddend;
475     Reloc r;
476     r.type = relInfo.r_type;
477     r.pcrel = relInfo.r_pcrel;
478     r.length = relInfo.r_length;
479     r.offset = relInfo.r_address;
480     if (relInfo.r_extern) {
481       r.referent = symbols[relInfo.r_symbolnum];
482       r.addend = isSubtrahend ? 0 : totalAddend;
483     } else {
484       assert(!isSubtrahend);
485       const SectionHeader &referentSecHead =
486           sectionHeaders[relInfo.r_symbolnum - 1];
487       uint64_t referentOffset;
488       if (relInfo.r_pcrel) {
489         // The implicit addend for pcrel section relocations is the pcrel offset
490         // in terms of the addresses in the input file. Here we adjust it so
491         // that it describes the offset from the start of the referent section.
492         // FIXME This logic was written around x86_64 behavior -- ARM64 doesn't
493         // have pcrel section relocations. We may want to factor this out into
494         // the arch-specific .cpp file.
495         assert(target->hasAttr(r.type, RelocAttrBits::BYTE4));
496         referentOffset = sec.addr + relInfo.r_address + 4 + totalAddend -
497                          referentSecHead.addr;
498       } else {
499         // The addend for a non-pcrel relocation is its absolute address.
500         referentOffset = totalAddend - referentSecHead.addr;
501       }
502       Subsections &referentSubsections =
503           sections[relInfo.r_symbolnum - 1]->subsections;
504       r.referent =
505           findContainingSubsection(referentSubsections, &referentOffset);
506       r.addend = referentOffset;
507     }
508 
509     // Find the subsection that this relocation belongs to.
510     // Though not required by the Mach-O format, clang and gcc seem to emit
511     // relocations in order, so let's take advantage of it. However, ld64 emits
512     // unsorted relocations (in `-r` mode), so we have a fallback for that
513     // uncommon case.
514     InputSection *subsec;
515     while (subsecIt != subsections.rend() && subsecIt->offset > r.offset)
516       ++subsecIt;
517     if (subsecIt == subsections.rend() ||
518         subsecIt->offset + subsecIt->isec->getSize() <= r.offset) {
519       subsec = findContainingSubsection(subsections, &r.offset);
520       // Now that we know the relocs are unsorted, avoid trying the 'fast path'
521       // for the other relocations.
522       subsecIt = subsections.rend();
523     } else {
524       subsec = subsecIt->isec;
525       r.offset -= subsecIt->offset;
526     }
527     subsec->relocs.push_back(r);
528 
529     if (isSubtrahend) {
530       relocation_info minuendInfo = relInfos[++i];
531       // SUBTRACTOR relocations should always be followed by an UNSIGNED one
532       // attached to the same address.
533       assert(target->hasAttr(minuendInfo.r_type, RelocAttrBits::UNSIGNED) &&
534              relInfo.r_address == minuendInfo.r_address);
535       Reloc p;
536       p.type = minuendInfo.r_type;
537       if (minuendInfo.r_extern) {
538         p.referent = symbols[minuendInfo.r_symbolnum];
539         p.addend = totalAddend;
540       } else {
541         uint64_t referentOffset =
542             totalAddend - sectionHeaders[minuendInfo.r_symbolnum - 1].addr;
543         Subsections &referentSubsectVec =
544             sections[minuendInfo.r_symbolnum - 1]->subsections;
545         p.referent =
546             findContainingSubsection(referentSubsectVec, &referentOffset);
547         p.addend = referentOffset;
548       }
549       subsec->relocs.push_back(p);
550     }
551   }
552 }
553 
554 template <class NList>
555 static macho::Symbol *createDefined(const NList &sym, StringRef name,
556                                     InputSection *isec, uint64_t value,
557                                     uint64_t size) {
558   // Symbol scope is determined by sym.n_type & (N_EXT | N_PEXT):
559   // N_EXT: Global symbols. These go in the symbol table during the link,
560   //        and also in the export table of the output so that the dynamic
561   //        linker sees them.
562   // N_EXT | N_PEXT: Linkage unit (think: dylib) scoped. These go in the
563   //                 symbol table during the link so that duplicates are
564   //                 either reported (for non-weak symbols) or merged
565   //                 (for weak symbols), but they do not go in the export
566   //                 table of the output.
567   // N_PEXT: llvm-mc does not emit these, but `ld -r` (wherein ld64 emits
568   //         object files) may produce them. LLD does not yet support -r.
569   //         These are translation-unit scoped, identical to the `0` case.
570   // 0: Translation-unit scoped. These are not in the symbol table during
571   //    link, and not in the export table of the output either.
572   bool isWeakDefCanBeHidden =
573       (sym.n_desc & (N_WEAK_DEF | N_WEAK_REF)) == (N_WEAK_DEF | N_WEAK_REF);
574 
575   if (sym.n_type & N_EXT) {
576     bool isPrivateExtern = sym.n_type & N_PEXT;
577     // lld's behavior for merging symbols is slightly different from ld64:
578     // ld64 picks the winning symbol based on several criteria (see
579     // pickBetweenRegularAtoms() in ld64's SymbolTable.cpp), while lld
580     // just merges metadata and keeps the contents of the first symbol
581     // with that name (see SymbolTable::addDefined). For:
582     // * inline function F in a TU built with -fvisibility-inlines-hidden
583     // * and inline function F in another TU built without that flag
584     // ld64 will pick the one from the file built without
585     // -fvisibility-inlines-hidden.
586     // lld will instead pick the one listed first on the link command line and
587     // give it visibility as if the function was built without
588     // -fvisibility-inlines-hidden.
589     // If both functions have the same contents, this will have the same
590     // behavior. If not, it won't, but the input had an ODR violation in
591     // that case.
592     //
593     // Similarly, merging a symbol
594     // that's isPrivateExtern and not isWeakDefCanBeHidden with one
595     // that's not isPrivateExtern but isWeakDefCanBeHidden technically
596     // should produce one
597     // that's not isPrivateExtern but isWeakDefCanBeHidden. That matters
598     // with ld64's semantics, because it means the non-private-extern
599     // definition will continue to take priority if more private extern
600     // definitions are encountered. With lld's semantics there's no observable
601     // difference between a symbol that's isWeakDefCanBeHidden(autohide) or one
602     // that's privateExtern -- neither makes it into the dynamic symbol table,
603     // unless the autohide symbol is explicitly exported.
604     // But if a symbol is both privateExtern and autohide then it can't
605     // be exported.
606     // So we nullify the autohide flag when privateExtern is present
607     // and promote the symbol to privateExtern when it is not already.
608     if (isWeakDefCanBeHidden && isPrivateExtern)
609       isWeakDefCanBeHidden = false;
610     else if (isWeakDefCanBeHidden)
611       isPrivateExtern = true;
612     return symtab->addDefined(
613         name, isec->getFile(), isec, value, size, sym.n_desc & N_WEAK_DEF,
614         isPrivateExtern, sym.n_desc & N_ARM_THUMB_DEF,
615         sym.n_desc & REFERENCED_DYNAMICALLY, sym.n_desc & N_NO_DEAD_STRIP,
616         isWeakDefCanBeHidden);
617   }
618   assert(!isWeakDefCanBeHidden &&
619          "weak_def_can_be_hidden on already-hidden symbol?");
620   return make<Defined>(
621       name, isec->getFile(), isec, value, size, sym.n_desc & N_WEAK_DEF,
622       /*isExternal=*/false, /*isPrivateExtern=*/false,
623       sym.n_desc & N_ARM_THUMB_DEF, sym.n_desc & REFERENCED_DYNAMICALLY,
624       sym.n_desc & N_NO_DEAD_STRIP);
625 }
626 
627 // Absolute symbols are defined symbols that do not have an associated
628 // InputSection. They cannot be weak.
629 template <class NList>
630 static macho::Symbol *createAbsolute(const NList &sym, InputFile *file,
631                                      StringRef name) {
632   if (sym.n_type & N_EXT) {
633     return symtab->addDefined(
634         name, file, nullptr, sym.n_value, /*size=*/0,
635         /*isWeakDef=*/false, sym.n_type & N_PEXT, sym.n_desc & N_ARM_THUMB_DEF,
636         /*isReferencedDynamically=*/false, sym.n_desc & N_NO_DEAD_STRIP,
637         /*isWeakDefCanBeHidden=*/false);
638   }
639   return make<Defined>(name, file, nullptr, sym.n_value, /*size=*/0,
640                        /*isWeakDef=*/false,
641                        /*isExternal=*/false, /*isPrivateExtern=*/false,
642                        sym.n_desc & N_ARM_THUMB_DEF,
643                        /*isReferencedDynamically=*/false,
644                        sym.n_desc & N_NO_DEAD_STRIP);
645 }
646 
647 template <class NList>
648 macho::Symbol *ObjFile::parseNonSectionSymbol(const NList &sym,
649                                               StringRef name) {
650   uint8_t type = sym.n_type & N_TYPE;
651   switch (type) {
652   case N_UNDF:
653     return sym.n_value == 0
654                ? symtab->addUndefined(name, this, sym.n_desc & N_WEAK_REF)
655                : symtab->addCommon(name, this, sym.n_value,
656                                    1 << GET_COMM_ALIGN(sym.n_desc),
657                                    sym.n_type & N_PEXT);
658   case N_ABS:
659     return createAbsolute(sym, this, name);
660   case N_PBUD:
661   case N_INDR:
662     error("TODO: support symbols of type " + std::to_string(type));
663     return nullptr;
664   case N_SECT:
665     llvm_unreachable(
666         "N_SECT symbols should not be passed to parseNonSectionSymbol");
667   default:
668     llvm_unreachable("invalid symbol type");
669   }
670 }
671 
672 template <class NList> static bool isUndef(const NList &sym) {
673   return (sym.n_type & N_TYPE) == N_UNDF && sym.n_value == 0;
674 }
675 
676 template <class LP>
677 void ObjFile::parseSymbols(ArrayRef<typename LP::section> sectionHeaders,
678                            ArrayRef<typename LP::nlist> nList,
679                            const char *strtab, bool subsectionsViaSymbols) {
680   using NList = typename LP::nlist;
681 
682   // Groups indices of the symbols by the sections that contain them.
683   std::vector<std::vector<uint32_t>> symbolsBySection(sections.size());
684   symbols.resize(nList.size());
685   SmallVector<unsigned, 32> undefineds;
686   for (uint32_t i = 0; i < nList.size(); ++i) {
687     const NList &sym = nList[i];
688 
689     // Ignore debug symbols for now.
690     // FIXME: may need special handling.
691     if (sym.n_type & N_STAB)
692       continue;
693 
694     StringRef name = strtab + sym.n_strx;
695     if ((sym.n_type & N_TYPE) == N_SECT) {
696       Subsections &subsections = sections[sym.n_sect - 1]->subsections;
697       // parseSections() may have chosen not to parse this section.
698       if (subsections.empty())
699         continue;
700       symbolsBySection[sym.n_sect - 1].push_back(i);
701     } else if (isUndef(sym)) {
702       undefineds.push_back(i);
703     } else {
704       symbols[i] = parseNonSectionSymbol(sym, name);
705     }
706   }
707 
708   for (size_t i = 0; i < sections.size(); ++i) {
709     Subsections &subsections = sections[i]->subsections;
710     if (subsections.empty())
711       continue;
712     InputSection *lastIsec = subsections.back().isec;
713     if (lastIsec->getName() == section_names::ehFrame) {
714       // __TEXT,__eh_frame only has symbols and SUBTRACTOR relocs when ld64 -r
715       // adds local "EH_Frame1" and "func.eh". Ignore them because they have
716       // gone unused by Mac OS since Snow Leopard (10.6), vintage 2009.
717       continue;
718     }
719     std::vector<uint32_t> &symbolIndices = symbolsBySection[i];
720     uint64_t sectionAddr = sectionHeaders[i].addr;
721     uint32_t sectionAlign = 1u << sectionHeaders[i].align;
722 
723     // Record-based sections have already been split into subsections during
724     // parseSections(), so we simply need to match Symbols to the corresponding
725     // subsection here.
726     if (getRecordSize(lastIsec->getSegName(), lastIsec->getName())) {
727       for (size_t j = 0; j < symbolIndices.size(); ++j) {
728         uint32_t symIndex = symbolIndices[j];
729         const NList &sym = nList[symIndex];
730         StringRef name = strtab + sym.n_strx;
731         uint64_t symbolOffset = sym.n_value - sectionAddr;
732         InputSection *isec =
733             findContainingSubsection(subsections, &symbolOffset);
734         if (symbolOffset != 0) {
735           error(toString(lastIsec) + ":  symbol " + name +
736                 " at misaligned offset");
737           continue;
738         }
739         symbols[symIndex] = createDefined(sym, name, isec, 0, isec->getSize());
740       }
741       continue;
742     }
743 
744     // Calculate symbol sizes and create subsections by splitting the sections
745     // along symbol boundaries.
746     // We populate subsections by repeatedly splitting the last (highest
747     // address) subsection.
748     llvm::stable_sort(symbolIndices, [&](uint32_t lhs, uint32_t rhs) {
749       return nList[lhs].n_value < nList[rhs].n_value;
750     });
751     for (size_t j = 0; j < symbolIndices.size(); ++j) {
752       uint32_t symIndex = symbolIndices[j];
753       const NList &sym = nList[symIndex];
754       StringRef name = strtab + sym.n_strx;
755       Subsection &subsec = subsections.back();
756       InputSection *isec = subsec.isec;
757 
758       uint64_t subsecAddr = sectionAddr + subsec.offset;
759       size_t symbolOffset = sym.n_value - subsecAddr;
760       uint64_t symbolSize =
761           j + 1 < symbolIndices.size()
762               ? nList[symbolIndices[j + 1]].n_value - sym.n_value
763               : isec->data.size() - symbolOffset;
764       // There are 4 cases where we do not need to create a new subsection:
765       //   1. If the input file does not use subsections-via-symbols.
766       //   2. Multiple symbols at the same address only induce one subsection.
767       //      (The symbolOffset == 0 check covers both this case as well as
768       //      the first loop iteration.)
769       //   3. Alternative entry points do not induce new subsections.
770       //   4. If we have a literal section (e.g. __cstring and __literal4).
771       if (!subsectionsViaSymbols || symbolOffset == 0 ||
772           sym.n_desc & N_ALT_ENTRY || !isa<ConcatInputSection>(isec)) {
773         symbols[symIndex] =
774             createDefined(sym, name, isec, symbolOffset, symbolSize);
775         continue;
776       }
777       auto *concatIsec = cast<ConcatInputSection>(isec);
778 
779       auto *nextIsec = make<ConcatInputSection>(*concatIsec);
780       nextIsec->wasCoalesced = false;
781       if (isZeroFill(isec->getFlags())) {
782         // Zero-fill sections have NULL data.data() non-zero data.size()
783         nextIsec->data = {nullptr, isec->data.size() - symbolOffset};
784         isec->data = {nullptr, symbolOffset};
785       } else {
786         nextIsec->data = isec->data.slice(symbolOffset);
787         isec->data = isec->data.slice(0, symbolOffset);
788       }
789 
790       // By construction, the symbol will be at offset zero in the new
791       // subsection.
792       symbols[symIndex] =
793           createDefined(sym, name, nextIsec, /*value=*/0, symbolSize);
794       // TODO: ld64 appears to preserve the original alignment as well as each
795       // subsection's offset from the last aligned address. We should consider
796       // emulating that behavior.
797       nextIsec->align = MinAlign(sectionAlign, sym.n_value);
798       subsections.push_back({sym.n_value - sectionAddr, nextIsec});
799     }
800   }
801 
802   // Undefined symbols can trigger recursive fetch from Archives due to
803   // LazySymbols. Process defined symbols first so that the relative order
804   // between a defined symbol and an undefined symbol does not change the
805   // symbol resolution behavior. In addition, a set of interconnected symbols
806   // will all be resolved to the same file, instead of being resolved to
807   // different files.
808   for (unsigned i : undefineds) {
809     const NList &sym = nList[i];
810     StringRef name = strtab + sym.n_strx;
811     symbols[i] = parseNonSectionSymbol(sym, name);
812   }
813 }
814 
815 OpaqueFile::OpaqueFile(MemoryBufferRef mb, StringRef segName,
816                        StringRef sectName)
817     : InputFile(OpaqueKind, mb) {
818   const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
819   ArrayRef<uint8_t> data = {buf, mb.getBufferSize()};
820   sections.push_back(make<Section>(/*file=*/this, segName.take_front(16),
821                                    sectName.take_front(16),
822                                    /*flags=*/0, /*addr=*/0));
823   Section &section = *sections.back();
824   ConcatInputSection *isec = make<ConcatInputSection>(section, data);
825   isec->live = true;
826   section.subsections.push_back({0, isec});
827 }
828 
829 ObjFile::ObjFile(MemoryBufferRef mb, uint32_t modTime, StringRef archiveName,
830                  bool lazy)
831     : InputFile(ObjKind, mb, lazy), modTime(modTime) {
832   this->archiveName = std::string(archiveName);
833   if (lazy) {
834     if (target->wordSize == 8)
835       parseLazy<LP64>();
836     else
837       parseLazy<ILP32>();
838   } else {
839     if (target->wordSize == 8)
840       parse<LP64>();
841     else
842       parse<ILP32>();
843   }
844 }
845 
846 template <class LP> void ObjFile::parse() {
847   using Header = typename LP::mach_header;
848   using SegmentCommand = typename LP::segment_command;
849   using SectionHeader = typename LP::section;
850   using NList = typename LP::nlist;
851 
852   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
853   auto *hdr = reinterpret_cast<const Header *>(mb.getBufferStart());
854 
855   Architecture arch = getArchitectureFromCpuType(hdr->cputype, hdr->cpusubtype);
856   if (arch != config->arch()) {
857     auto msg = config->errorForArchMismatch
858                    ? static_cast<void (*)(const Twine &)>(error)
859                    : warn;
860     msg(toString(this) + " has architecture " + getArchitectureName(arch) +
861         " which is incompatible with target architecture " +
862         getArchitectureName(config->arch()));
863     return;
864   }
865 
866   if (!checkCompatibility(this))
867     return;
868 
869   for (auto *cmd : findCommands<linker_option_command>(hdr, LC_LINKER_OPTION)) {
870     StringRef data{reinterpret_cast<const char *>(cmd + 1),
871                    cmd->cmdsize - sizeof(linker_option_command)};
872     parseLCLinkerOption(this, cmd->count, data);
873   }
874 
875   ArrayRef<SectionHeader> sectionHeaders;
876   if (const load_command *cmd = findCommand(hdr, LP::segmentLCType)) {
877     auto *c = reinterpret_cast<const SegmentCommand *>(cmd);
878     sectionHeaders = ArrayRef<SectionHeader>{
879         reinterpret_cast<const SectionHeader *>(c + 1), c->nsects};
880     parseSections(sectionHeaders);
881   }
882 
883   // TODO: Error on missing LC_SYMTAB?
884   if (const load_command *cmd = findCommand(hdr, LC_SYMTAB)) {
885     auto *c = reinterpret_cast<const symtab_command *>(cmd);
886     ArrayRef<NList> nList(reinterpret_cast<const NList *>(buf + c->symoff),
887                           c->nsyms);
888     const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff;
889     bool subsectionsViaSymbols = hdr->flags & MH_SUBSECTIONS_VIA_SYMBOLS;
890     parseSymbols<LP>(sectionHeaders, nList, strtab, subsectionsViaSymbols);
891   }
892 
893   // The relocations may refer to the symbols, so we parse them after we have
894   // parsed all the symbols.
895   for (size_t i = 0, n = sections.size(); i < n; ++i)
896     if (!sections[i]->subsections.empty())
897       parseRelocations(sectionHeaders, sectionHeaders[i],
898                        sections[i]->subsections);
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