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