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