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