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