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