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 "EhFrame.h"
49 #include "ExportTrie.h"
50 #include "InputSection.h"
51 #include "MachOStructs.h"
52 #include "ObjC.h"
53 #include "OutputSection.h"
54 #include "OutputSegment.h"
55 #include "SymbolTable.h"
56 #include "Symbols.h"
57 #include "SyntheticSections.h"
58 #include "Target.h"
59 
60 #include "lld/Common/CommonLinkerContext.h"
61 #include "lld/Common/DWARF.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 std::string lld::toString(const Section &sec) {
100   return (toString(sec.file) + ":(" + sec.name + ")").str();
101 }
102 
103 SetVector<InputFile *> macho::inputFiles;
104 std::unique_ptr<TarWriter> macho::tar;
105 int InputFile::idCount = 0;
106 
107 static VersionTuple decodeVersion(uint32_t version) {
108   unsigned major = version >> 16;
109   unsigned minor = (version >> 8) & 0xffu;
110   unsigned subMinor = version & 0xffu;
111   return VersionTuple(major, minor, subMinor);
112 }
113 
114 static std::vector<PlatformInfo> getPlatformInfos(const InputFile *input) {
115   if (!isa<ObjFile>(input) && !isa<DylibFile>(input))
116     return {};
117 
118   const char *hdr = input->mb.getBufferStart();
119 
120   // "Zippered" object files can have multiple LC_BUILD_VERSION load commands.
121   std::vector<PlatformInfo> platformInfos;
122   for (auto *cmd : findCommands<build_version_command>(hdr, LC_BUILD_VERSION)) {
123     PlatformInfo info;
124     info.target.Platform = static_cast<PlatformType>(cmd->platform);
125     info.minimum = decodeVersion(cmd->minos);
126     platformInfos.emplace_back(std::move(info));
127   }
128   for (auto *cmd : findCommands<version_min_command>(
129            hdr, LC_VERSION_MIN_MACOSX, LC_VERSION_MIN_IPHONEOS,
130            LC_VERSION_MIN_TVOS, LC_VERSION_MIN_WATCHOS)) {
131     PlatformInfo info;
132     switch (cmd->cmd) {
133     case LC_VERSION_MIN_MACOSX:
134       info.target.Platform = PLATFORM_MACOS;
135       break;
136     case LC_VERSION_MIN_IPHONEOS:
137       info.target.Platform = PLATFORM_IOS;
138       break;
139     case LC_VERSION_MIN_TVOS:
140       info.target.Platform = PLATFORM_TVOS;
141       break;
142     case LC_VERSION_MIN_WATCHOS:
143       info.target.Platform = PLATFORM_WATCHOS;
144       break;
145     }
146     info.minimum = decodeVersion(cmd->version);
147     platformInfos.emplace_back(std::move(info));
148   }
149 
150   return platformInfos;
151 }
152 
153 static bool checkCompatibility(const InputFile *input) {
154   std::vector<PlatformInfo> platformInfos = getPlatformInfos(input);
155   if (platformInfos.empty())
156     return true;
157 
158   auto it = find_if(platformInfos, [&](const PlatformInfo &info) {
159     return removeSimulator(info.target.Platform) ==
160            removeSimulator(config->platform());
161   });
162   if (it == platformInfos.end()) {
163     std::string platformNames;
164     raw_string_ostream os(platformNames);
165     interleave(
166         platformInfos, os,
167         [&](const PlatformInfo &info) {
168           os << getPlatformName(info.target.Platform);
169         },
170         "/");
171     error(toString(input) + " has platform " + platformNames +
172           Twine(", which is different from target platform ") +
173           getPlatformName(config->platform()));
174     return false;
175   }
176 
177   if (it->minimum > config->platformInfo.minimum)
178     warn(toString(input) + " has version " + it->minimum.getAsString() +
179          ", which is newer than target minimum of " +
180          config->platformInfo.minimum.getAsString());
181 
182   return true;
183 }
184 
185 // This cache mostly exists to store system libraries (and .tbds) as they're
186 // loaded, rather than the input archives, which are already cached at a higher
187 // level, and other files like the filelist that are only read once.
188 // Theoretically this caching could be more efficient by hoisting it, but that
189 // would require altering many callers to track the state.
190 DenseMap<CachedHashStringRef, MemoryBufferRef> macho::cachedReads;
191 // Open a given file path and return it as a memory-mapped file.
192 Optional<MemoryBufferRef> macho::readFile(StringRef path) {
193   CachedHashStringRef key(path);
194   auto entry = cachedReads.find(key);
195   if (entry != cachedReads.end())
196     return entry->second;
197 
198   ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr = MemoryBuffer::getFile(path);
199   if (std::error_code ec = mbOrErr.getError()) {
200     error("cannot open " + path + ": " + ec.message());
201     return None;
202   }
203 
204   std::unique_ptr<MemoryBuffer> &mb = *mbOrErr;
205   MemoryBufferRef mbref = mb->getMemBufferRef();
206   make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take mb ownership
207 
208   // If this is a regular non-fat file, return it.
209   const char *buf = mbref.getBufferStart();
210   const auto *hdr = reinterpret_cast<const fat_header *>(buf);
211   if (mbref.getBufferSize() < sizeof(uint32_t) ||
212       read32be(&hdr->magic) != FAT_MAGIC) {
213     if (tar)
214       tar->append(relativeToRoot(path), mbref.getBuffer());
215     return cachedReads[key] = mbref;
216   }
217 
218   llvm::BumpPtrAllocator &bAlloc = lld::bAlloc();
219 
220   // Object files and archive files may be fat files, which contain multiple
221   // real files for different CPU ISAs. Here, we search for a file that matches
222   // with the current link target and returns it as a MemoryBufferRef.
223   const auto *arch = reinterpret_cast<const fat_arch *>(buf + sizeof(*hdr));
224 
225   for (uint32_t i = 0, n = read32be(&hdr->nfat_arch); i < n; ++i) {
226     if (reinterpret_cast<const char *>(arch + i + 1) >
227         buf + mbref.getBufferSize()) {
228       error(path + ": fat_arch struct extends beyond end of file");
229       return None;
230     }
231 
232     if (read32be(&arch[i].cputype) != static_cast<uint32_t>(target->cpuType) ||
233         read32be(&arch[i].cpusubtype) != target->cpuSubtype)
234       continue;
235 
236     uint32_t offset = read32be(&arch[i].offset);
237     uint32_t size = read32be(&arch[i].size);
238     if (offset + size > mbref.getBufferSize())
239       error(path + ": slice extends beyond end of file");
240     if (tar)
241       tar->append(relativeToRoot(path), mbref.getBuffer());
242     return cachedReads[key] = MemoryBufferRef(StringRef(buf + offset, size),
243                                               path.copy(bAlloc));
244   }
245 
246   error("unable to find matching architecture in " + path);
247   return None;
248 }
249 
250 InputFile::InputFile(Kind kind, const InterfaceFile &interface)
251     : id(idCount++), fileKind(kind), name(saver().save(interface.getPath())) {}
252 
253 // Some sections comprise of fixed-size records, so instead of splitting them at
254 // symbol boundaries, we split them based on size. Records are distinct from
255 // literals in that they may contain references to other sections, instead of
256 // being leaf nodes in the InputSection graph.
257 //
258 // Note that "record" is a term I came up with. In contrast, "literal" is a term
259 // used by the Mach-O format.
260 static Optional<size_t> getRecordSize(StringRef segname, StringRef name) {
261   if (name == section_names::compactUnwind) {
262     if (segname == segment_names::ld)
263       return target->wordSize == 8 ? 32 : 20;
264   }
265   if (config->icfLevel == ICFLevel::none)
266     return {};
267 
268   if (name == section_names::cfString && segname == segment_names::data)
269     return target->wordSize == 8 ? 32 : 16;
270   if (name == section_names::objcClassRefs && segname == segment_names::data)
271     return target->wordSize;
272   return {};
273 }
274 
275 static Error parseCallGraph(ArrayRef<uint8_t> data,
276                             std::vector<CallGraphEntry> &callGraph) {
277   TimeTraceScope timeScope("Parsing call graph section");
278   BinaryStreamReader reader(data, support::little);
279   while (!reader.empty()) {
280     uint32_t fromIndex, toIndex;
281     uint64_t count;
282     if (Error err = reader.readInteger(fromIndex))
283       return err;
284     if (Error err = reader.readInteger(toIndex))
285       return err;
286     if (Error err = reader.readInteger(count))
287       return err;
288     callGraph.emplace_back(fromIndex, toIndex, count);
289   }
290   return Error::success();
291 }
292 
293 // Parse the sequence of sections within a single LC_SEGMENT(_64).
294 // Split each section into subsections.
295 template <class SectionHeader>
296 void ObjFile::parseSections(ArrayRef<SectionHeader> sectionHeaders) {
297   sections.reserve(sectionHeaders.size());
298   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
299 
300   for (const SectionHeader &sec : sectionHeaders) {
301     StringRef name =
302         StringRef(sec.sectname, strnlen(sec.sectname, sizeof(sec.sectname)));
303     StringRef segname =
304         StringRef(sec.segname, strnlen(sec.segname, sizeof(sec.segname)));
305     sections.push_back(make<Section>(this, segname, name, sec.flags, sec.addr));
306     if (sec.align >= 32) {
307       error("alignment " + std::to_string(sec.align) + " of section " + name +
308             " is too large");
309       continue;
310     }
311     Section &section = *sections.back();
312     uint32_t align = 1 << sec.align;
313     ArrayRef<uint8_t> data = {isZeroFill(sec.flags) ? nullptr
314                                                     : buf + sec.offset,
315                               static_cast<size_t>(sec.size)};
316 
317     auto splitRecords = [&](int recordSize) -> void {
318       if (data.empty())
319         return;
320       Subsections &subsections = section.subsections;
321       subsections.reserve(data.size() / recordSize);
322       for (uint64_t off = 0; off < data.size(); off += recordSize) {
323         auto *isec = make<ConcatInputSection>(
324             section, data.slice(off, recordSize), align);
325         subsections.push_back({off, isec});
326       }
327       section.doneSplitting = true;
328     };
329 
330     if (sectionType(sec.flags) == S_CSTRING_LITERALS ||
331         (config->dedupLiterals && isWordLiteralSection(sec.flags))) {
332       if (sec.nreloc && config->dedupLiterals)
333         fatal(toString(this) + " contains relocations in " + sec.segname + "," +
334               sec.sectname +
335               ", so LLD cannot deduplicate literals. Try re-running without "
336               "--deduplicate-literals.");
337 
338       InputSection *isec;
339       if (sectionType(sec.flags) == S_CSTRING_LITERALS) {
340         isec = make<CStringInputSection>(section, data, align);
341         // FIXME: parallelize this?
342         cast<CStringInputSection>(isec)->splitIntoPieces();
343       } else {
344         isec = make<WordLiteralInputSection>(section, data, align);
345       }
346       section.subsections.push_back({0, isec});
347     } else if (auto recordSize = getRecordSize(segname, name)) {
348       splitRecords(*recordSize);
349     } else if (config->parseEhFrames && name == section_names::ehFrame &&
350                segname == segment_names::text) {
351       splitEhFrames(data, *sections.back());
352     } else if (segname == segment_names::llvm) {
353       if (config->callGraphProfileSort && name == section_names::cgProfile)
354         checkError(parseCallGraph(data, callGraph));
355       // ld64 does not appear to emit contents from sections within the __LLVM
356       // segment. Symbols within those sections point to bitcode metadata
357       // instead of actual symbols. Global symbols within those sections could
358       // have the same name without causing duplicate symbol errors. To avoid
359       // spurious duplicate symbol errors, we do not parse these sections.
360       // TODO: Evaluate whether the bitcode metadata is needed.
361     } else {
362       if (name == section_names::addrSig)
363         addrSigSection = sections.back();
364 
365       auto *isec = make<ConcatInputSection>(section, data, align);
366       if (isDebugSection(isec->getFlags()) &&
367           isec->getSegName() == segment_names::dwarf) {
368         // Instead of emitting DWARF sections, we emit STABS symbols to the
369         // object files that contain them. We filter them out early to avoid
370         // parsing their relocations unnecessarily.
371         debugSections.push_back(isec);
372       } else {
373         section.subsections.push_back({0, isec});
374       }
375     }
376   }
377 }
378 
379 void ObjFile::splitEhFrames(ArrayRef<uint8_t> data, Section &ehFrameSection) {
380   EhReader reader(this, data, /*dataOff=*/0, target->wordSize);
381   size_t off = 0;
382   while (off < reader.size()) {
383     uint64_t frameOff = off;
384     uint64_t length = reader.readLength(&off);
385     if (length == 0)
386       break;
387     uint64_t fullLength = length + (off - frameOff);
388     off += length;
389     // We hard-code an alignment of 1 here because we don't actually want our
390     // EH frames to be aligned to the section alignment. EH frame decoders don't
391     // expect this alignment. Moreover, each EH frame must start where the
392     // previous one ends, and where it ends is indicated by the length field.
393     // Unless we update the length field (troublesome), we should keep the
394     // alignment to 1.
395     // Note that we still want to preserve the alignment of the overall section,
396     // just not of the individual EH frames.
397     ehFrameSection.subsections.push_back(
398         {frameOff, make<ConcatInputSection>(ehFrameSection,
399                                             data.slice(frameOff, fullLength),
400                                             /*align=*/1)});
401   }
402   ehFrameSection.doneSplitting = true;
403 }
404 
405 template <class T>
406 static Section *findContainingSection(const std::vector<Section *> &sections,
407                                       T *offset) {
408   static_assert(std::is_same<uint64_t, T>::value ||
409                     std::is_same<uint32_t, T>::value,
410                 "unexpected type for offset");
411   auto it = std::prev(llvm::upper_bound(
412       sections, *offset,
413       [](uint64_t value, const Section *sec) { return value < sec->addr; }));
414   *offset -= (*it)->addr;
415   return *it;
416 }
417 
418 // Find the subsection corresponding to the greatest section offset that is <=
419 // that of the given offset.
420 //
421 // offset: an offset relative to the start of the original InputSection (before
422 // any subsection splitting has occurred). It will be updated to represent the
423 // same location as an offset relative to the start of the containing
424 // subsection.
425 template <class T>
426 static InputSection *findContainingSubsection(const Section &section,
427                                               T *offset) {
428   static_assert(std::is_same<uint64_t, T>::value ||
429                     std::is_same<uint32_t, T>::value,
430                 "unexpected type for offset");
431   auto it = std::prev(llvm::upper_bound(
432       section.subsections, *offset,
433       [](uint64_t value, Subsection subsec) { return value < subsec.offset; }));
434   *offset -= it->offset;
435   return it->isec;
436 }
437 
438 // Find a symbol at offset `off` within `isec`.
439 static Defined *findSymbolAtOffset(const ConcatInputSection *isec,
440                                    uint64_t off) {
441   auto it = llvm::lower_bound(isec->symbols, off, [](Defined *d, uint64_t off) {
442     return d->value < off;
443   });
444   // The offset should point at the exact address of a symbol (with no addend.)
445   if (it == isec->symbols.end() || (*it)->value != off) {
446     assert(isec->wasCoalesced);
447     return nullptr;
448   }
449   return *it;
450 }
451 
452 template <class SectionHeader>
453 static bool validateRelocationInfo(InputFile *file, const SectionHeader &sec,
454                                    relocation_info rel) {
455   const RelocAttrs &relocAttrs = target->getRelocAttrs(rel.r_type);
456   bool valid = true;
457   auto message = [relocAttrs, file, sec, rel, &valid](const Twine &diagnostic) {
458     valid = false;
459     return (relocAttrs.name + " relocation " + diagnostic + " at offset " +
460             std::to_string(rel.r_address) + " of " + sec.segname + "," +
461             sec.sectname + " in " + toString(file))
462         .str();
463   };
464 
465   if (!relocAttrs.hasAttr(RelocAttrBits::LOCAL) && !rel.r_extern)
466     error(message("must be extern"));
467   if (relocAttrs.hasAttr(RelocAttrBits::PCREL) != rel.r_pcrel)
468     error(message(Twine("must ") + (rel.r_pcrel ? "not " : "") +
469                   "be PC-relative"));
470   if (isThreadLocalVariables(sec.flags) &&
471       !relocAttrs.hasAttr(RelocAttrBits::UNSIGNED))
472     error(message("not allowed in thread-local section, must be UNSIGNED"));
473   if (rel.r_length < 2 || rel.r_length > 3 ||
474       !relocAttrs.hasAttr(static_cast<RelocAttrBits>(1 << rel.r_length))) {
475     static SmallVector<StringRef, 4> widths{"0", "4", "8", "4 or 8"};
476     error(message("has width " + std::to_string(1 << rel.r_length) +
477                   " bytes, but must be " +
478                   widths[(static_cast<int>(relocAttrs.bits) >> 2) & 3] +
479                   " bytes"));
480   }
481   return valid;
482 }
483 
484 template <class SectionHeader>
485 void ObjFile::parseRelocations(ArrayRef<SectionHeader> sectionHeaders,
486                                const SectionHeader &sec, Section &section) {
487   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
488   ArrayRef<relocation_info> relInfos(
489       reinterpret_cast<const relocation_info *>(buf + sec.reloff), sec.nreloc);
490 
491   Subsections &subsections = section.subsections;
492   auto subsecIt = subsections.rbegin();
493   for (size_t i = 0; i < relInfos.size(); i++) {
494     // Paired relocations serve as Mach-O's method for attaching a
495     // supplemental datum to a primary relocation record. ELF does not
496     // need them because the *_RELOC_RELA records contain the extra
497     // addend field, vs. *_RELOC_REL which omit the addend.
498     //
499     // The {X86_64,ARM64}_RELOC_SUBTRACTOR record holds the subtrahend,
500     // and the paired *_RELOC_UNSIGNED record holds the minuend. The
501     // datum for each is a symbolic address. The result is the offset
502     // between two addresses.
503     //
504     // The ARM64_RELOC_ADDEND record holds the addend, and the paired
505     // ARM64_RELOC_BRANCH26 or ARM64_RELOC_PAGE21/PAGEOFF12 holds the
506     // base symbolic address.
507     //
508     // Note: X86 does not use *_RELOC_ADDEND because it can embed an
509     // addend into the instruction stream. On X86, a relocatable address
510     // field always occupies an entire contiguous sequence of byte(s),
511     // so there is no need to merge opcode bits with address
512     // bits. Therefore, it's easy and convenient to store addends in the
513     // instruction-stream bytes that would otherwise contain zeroes. By
514     // contrast, RISC ISAs such as ARM64 mix opcode bits with with
515     // address bits so that bitwise arithmetic is necessary to extract
516     // and insert them. Storing addends in the instruction stream is
517     // possible, but inconvenient and more costly at link time.
518 
519     relocation_info relInfo = relInfos[i];
520     bool isSubtrahend =
521         target->hasAttr(relInfo.r_type, RelocAttrBits::SUBTRAHEND);
522     int64_t pairedAddend = 0;
523     if (target->hasAttr(relInfo.r_type, RelocAttrBits::ADDEND)) {
524       pairedAddend = SignExtend64<24>(relInfo.r_symbolnum);
525       relInfo = relInfos[++i];
526     }
527     assert(i < relInfos.size());
528     if (!validateRelocationInfo(this, sec, relInfo))
529       continue;
530     if (relInfo.r_address & R_SCATTERED)
531       fatal("TODO: Scattered relocations not supported");
532 
533     int64_t embeddedAddend = target->getEmbeddedAddend(mb, sec.offset, relInfo);
534     assert(!(embeddedAddend && pairedAddend));
535     int64_t totalAddend = pairedAddend + embeddedAddend;
536     Reloc r;
537     r.type = relInfo.r_type;
538     r.pcrel = relInfo.r_pcrel;
539     r.length = relInfo.r_length;
540     r.offset = relInfo.r_address;
541     if (relInfo.r_extern) {
542       r.referent = symbols[relInfo.r_symbolnum];
543       r.addend = isSubtrahend ? 0 : totalAddend;
544     } else {
545       assert(!isSubtrahend);
546       const SectionHeader &referentSecHead =
547           sectionHeaders[relInfo.r_symbolnum - 1];
548       uint64_t referentOffset;
549       if (relInfo.r_pcrel) {
550         // The implicit addend for pcrel section relocations is the pcrel offset
551         // in terms of the addresses in the input file. Here we adjust it so
552         // that it describes the offset from the start of the referent section.
553         // FIXME This logic was written around x86_64 behavior -- ARM64 doesn't
554         // have pcrel section relocations. We may want to factor this out into
555         // the arch-specific .cpp file.
556         assert(target->hasAttr(r.type, RelocAttrBits::BYTE4));
557         referentOffset = sec.addr + relInfo.r_address + 4 + totalAddend -
558                          referentSecHead.addr;
559       } else {
560         // The addend for a non-pcrel relocation is its absolute address.
561         referentOffset = totalAddend - referentSecHead.addr;
562       }
563       r.referent = findContainingSubsection(*sections[relInfo.r_symbolnum - 1],
564                                             &referentOffset);
565       r.addend = referentOffset;
566     }
567 
568     // Find the subsection that this relocation belongs to.
569     // Though not required by the Mach-O format, clang and gcc seem to emit
570     // relocations in order, so let's take advantage of it. However, ld64 emits
571     // unsorted relocations (in `-r` mode), so we have a fallback for that
572     // uncommon case.
573     InputSection *subsec;
574     while (subsecIt != subsections.rend() && subsecIt->offset > r.offset)
575       ++subsecIt;
576     if (subsecIt == subsections.rend() ||
577         subsecIt->offset + subsecIt->isec->getSize() <= r.offset) {
578       subsec = findContainingSubsection(section, &r.offset);
579       // Now that we know the relocs are unsorted, avoid trying the 'fast path'
580       // for the other relocations.
581       subsecIt = subsections.rend();
582     } else {
583       subsec = subsecIt->isec;
584       r.offset -= subsecIt->offset;
585     }
586     subsec->relocs.push_back(r);
587 
588     if (isSubtrahend) {
589       relocation_info minuendInfo = relInfos[++i];
590       // SUBTRACTOR relocations should always be followed by an UNSIGNED one
591       // attached to the same address.
592       assert(target->hasAttr(minuendInfo.r_type, RelocAttrBits::UNSIGNED) &&
593              relInfo.r_address == minuendInfo.r_address);
594       Reloc p;
595       p.type = minuendInfo.r_type;
596       if (minuendInfo.r_extern) {
597         p.referent = symbols[minuendInfo.r_symbolnum];
598         p.addend = totalAddend;
599       } else {
600         uint64_t referentOffset =
601             totalAddend - sectionHeaders[minuendInfo.r_symbolnum - 1].addr;
602         p.referent = findContainingSubsection(
603             *sections[minuendInfo.r_symbolnum - 1], &referentOffset);
604         p.addend = referentOffset;
605       }
606       subsec->relocs.push_back(p);
607     }
608   }
609 }
610 
611 template <class NList>
612 static macho::Symbol *createDefined(const NList &sym, StringRef name,
613                                     InputSection *isec, uint64_t value,
614                                     uint64_t size) {
615   // Symbol scope is determined by sym.n_type & (N_EXT | N_PEXT):
616   // N_EXT: Global symbols. These go in the symbol table during the link,
617   //        and also in the export table of the output so that the dynamic
618   //        linker sees them.
619   // N_EXT | N_PEXT: Linkage unit (think: dylib) scoped. These go in the
620   //                 symbol table during the link so that duplicates are
621   //                 either reported (for non-weak symbols) or merged
622   //                 (for weak symbols), but they do not go in the export
623   //                 table of the output.
624   // N_PEXT: llvm-mc does not emit these, but `ld -r` (wherein ld64 emits
625   //         object files) may produce them. LLD does not yet support -r.
626   //         These are translation-unit scoped, identical to the `0` case.
627   // 0: Translation-unit scoped. These are not in the symbol table during
628   //    link, and not in the export table of the output either.
629   bool isWeakDefCanBeHidden =
630       (sym.n_desc & (N_WEAK_DEF | N_WEAK_REF)) == (N_WEAK_DEF | N_WEAK_REF);
631 
632   if (sym.n_type & N_EXT) {
633     bool isPrivateExtern = sym.n_type & N_PEXT;
634     // lld's behavior for merging symbols is slightly different from ld64:
635     // ld64 picks the winning symbol based on several criteria (see
636     // pickBetweenRegularAtoms() in ld64's SymbolTable.cpp), while lld
637     // just merges metadata and keeps the contents of the first symbol
638     // with that name (see SymbolTable::addDefined). For:
639     // * inline function F in a TU built with -fvisibility-inlines-hidden
640     // * and inline function F in another TU built without that flag
641     // ld64 will pick the one from the file built without
642     // -fvisibility-inlines-hidden.
643     // lld will instead pick the one listed first on the link command line and
644     // give it visibility as if the function was built without
645     // -fvisibility-inlines-hidden.
646     // If both functions have the same contents, this will have the same
647     // behavior. If not, it won't, but the input had an ODR violation in
648     // that case.
649     //
650     // Similarly, merging a symbol
651     // that's isPrivateExtern and not isWeakDefCanBeHidden with one
652     // that's not isPrivateExtern but isWeakDefCanBeHidden technically
653     // should produce one
654     // that's not isPrivateExtern but isWeakDefCanBeHidden. That matters
655     // with ld64's semantics, because it means the non-private-extern
656     // definition will continue to take priority if more private extern
657     // definitions are encountered. With lld's semantics there's no observable
658     // difference between a symbol that's isWeakDefCanBeHidden(autohide) or one
659     // that's privateExtern -- neither makes it into the dynamic symbol table,
660     // unless the autohide symbol is explicitly exported.
661     // But if a symbol is both privateExtern and autohide then it can't
662     // be exported.
663     // So we nullify the autohide flag when privateExtern is present
664     // and promote the symbol to privateExtern when it is not already.
665     if (isWeakDefCanBeHidden && isPrivateExtern)
666       isWeakDefCanBeHidden = false;
667     else if (isWeakDefCanBeHidden)
668       isPrivateExtern = true;
669     return symtab->addDefined(
670         name, isec->getFile(), isec, value, size, sym.n_desc & N_WEAK_DEF,
671         isPrivateExtern, sym.n_desc & N_ARM_THUMB_DEF,
672         sym.n_desc & REFERENCED_DYNAMICALLY, sym.n_desc & N_NO_DEAD_STRIP,
673         isWeakDefCanBeHidden);
674   }
675   assert(!isWeakDefCanBeHidden &&
676          "weak_def_can_be_hidden on already-hidden symbol?");
677   bool includeInSymtab =
678       !name.startswith("l") && !name.startswith("L") && !isEhFrameSection(isec);
679   return make<Defined>(
680       name, isec->getFile(), isec, value, size, sym.n_desc & N_WEAK_DEF,
681       /*isExternal=*/false, /*isPrivateExtern=*/false, includeInSymtab,
682       sym.n_desc & N_ARM_THUMB_DEF, sym.n_desc & REFERENCED_DYNAMICALLY,
683       sym.n_desc & N_NO_DEAD_STRIP);
684 }
685 
686 // Absolute symbols are defined symbols that do not have an associated
687 // InputSection. They cannot be weak.
688 template <class NList>
689 static macho::Symbol *createAbsolute(const NList &sym, InputFile *file,
690                                      StringRef name) {
691   if (sym.n_type & N_EXT) {
692     return symtab->addDefined(
693         name, file, nullptr, sym.n_value, /*size=*/0,
694         /*isWeakDef=*/false, sym.n_type & N_PEXT, sym.n_desc & N_ARM_THUMB_DEF,
695         /*isReferencedDynamically=*/false, sym.n_desc & N_NO_DEAD_STRIP,
696         /*isWeakDefCanBeHidden=*/false);
697   }
698   return make<Defined>(name, file, nullptr, sym.n_value, /*size=*/0,
699                        /*isWeakDef=*/false,
700                        /*isExternal=*/false, /*isPrivateExtern=*/false,
701                        /*includeInSymtab=*/true, sym.n_desc & N_ARM_THUMB_DEF,
702                        /*isReferencedDynamically=*/false,
703                        sym.n_desc & N_NO_DEAD_STRIP);
704 }
705 
706 template <class NList>
707 macho::Symbol *ObjFile::parseNonSectionSymbol(const NList &sym,
708                                               StringRef name) {
709   uint8_t type = sym.n_type & N_TYPE;
710   switch (type) {
711   case N_UNDF:
712     return sym.n_value == 0
713                ? symtab->addUndefined(name, this, sym.n_desc & N_WEAK_REF)
714                : symtab->addCommon(name, this, sym.n_value,
715                                    1 << GET_COMM_ALIGN(sym.n_desc),
716                                    sym.n_type & N_PEXT);
717   case N_ABS:
718     return createAbsolute(sym, this, name);
719   case N_PBUD:
720   case N_INDR:
721     error("TODO: support symbols of type " + std::to_string(type));
722     return nullptr;
723   case N_SECT:
724     llvm_unreachable(
725         "N_SECT symbols should not be passed to parseNonSectionSymbol");
726   default:
727     llvm_unreachable("invalid symbol type");
728   }
729 }
730 
731 template <class NList> static bool isUndef(const NList &sym) {
732   return (sym.n_type & N_TYPE) == N_UNDF && sym.n_value == 0;
733 }
734 
735 template <class LP>
736 void ObjFile::parseSymbols(ArrayRef<typename LP::section> sectionHeaders,
737                            ArrayRef<typename LP::nlist> nList,
738                            const char *strtab, bool subsectionsViaSymbols) {
739   using NList = typename LP::nlist;
740 
741   // Groups indices of the symbols by the sections that contain them.
742   std::vector<std::vector<uint32_t>> symbolsBySection(sections.size());
743   symbols.resize(nList.size());
744   SmallVector<unsigned, 32> undefineds;
745   for (uint32_t i = 0; i < nList.size(); ++i) {
746     const NList &sym = nList[i];
747 
748     // Ignore debug symbols for now.
749     // FIXME: may need special handling.
750     if (sym.n_type & N_STAB)
751       continue;
752 
753     StringRef name = strtab + sym.n_strx;
754     if ((sym.n_type & N_TYPE) == N_SECT) {
755       Subsections &subsections = sections[sym.n_sect - 1]->subsections;
756       // parseSections() may have chosen not to parse this section.
757       if (subsections.empty())
758         continue;
759       symbolsBySection[sym.n_sect - 1].push_back(i);
760     } else if (isUndef(sym)) {
761       undefineds.push_back(i);
762     } else {
763       symbols[i] = parseNonSectionSymbol(sym, name);
764     }
765   }
766 
767   for (size_t i = 0; i < sections.size(); ++i) {
768     Subsections &subsections = sections[i]->subsections;
769     if (subsections.empty())
770       continue;
771     std::vector<uint32_t> &symbolIndices = symbolsBySection[i];
772     uint64_t sectionAddr = sectionHeaders[i].addr;
773     uint32_t sectionAlign = 1u << sectionHeaders[i].align;
774 
775     // Some sections have already been split into subsections during
776     // parseSections(), so we simply need to match Symbols to the corresponding
777     // subsection here.
778     if (sections[i]->doneSplitting) {
779       for (size_t j = 0; j < symbolIndices.size(); ++j) {
780         uint32_t symIndex = symbolIndices[j];
781         const NList &sym = nList[symIndex];
782         StringRef name = strtab + sym.n_strx;
783         uint64_t symbolOffset = sym.n_value - sectionAddr;
784         InputSection *isec =
785             findContainingSubsection(*sections[i], &symbolOffset);
786         if (symbolOffset != 0) {
787           error(toString(*sections[i]) + ":  symbol " + name +
788                 " at misaligned offset");
789           continue;
790         }
791         symbols[symIndex] = createDefined(sym, name, isec, 0, isec->getSize());
792       }
793       continue;
794     }
795     sections[i]->doneSplitting = true;
796 
797     // Calculate symbol sizes and create subsections by splitting the sections
798     // along symbol boundaries.
799     // We populate subsections by repeatedly splitting the last (highest
800     // address) subsection.
801     llvm::stable_sort(symbolIndices, [&](uint32_t lhs, uint32_t rhs) {
802       return nList[lhs].n_value < nList[rhs].n_value;
803     });
804     for (size_t j = 0; j < symbolIndices.size(); ++j) {
805       uint32_t symIndex = symbolIndices[j];
806       const NList &sym = nList[symIndex];
807       StringRef name = strtab + sym.n_strx;
808       Subsection &subsec = subsections.back();
809       InputSection *isec = subsec.isec;
810 
811       uint64_t subsecAddr = sectionAddr + subsec.offset;
812       size_t symbolOffset = sym.n_value - subsecAddr;
813       uint64_t symbolSize =
814           j + 1 < symbolIndices.size()
815               ? nList[symbolIndices[j + 1]].n_value - sym.n_value
816               : isec->data.size() - symbolOffset;
817       // There are 4 cases where we do not need to create a new subsection:
818       //   1. If the input file does not use subsections-via-symbols.
819       //   2. Multiple symbols at the same address only induce one subsection.
820       //      (The symbolOffset == 0 check covers both this case as well as
821       //      the first loop iteration.)
822       //   3. Alternative entry points do not induce new subsections.
823       //   4. If we have a literal section (e.g. __cstring and __literal4).
824       if (!subsectionsViaSymbols || symbolOffset == 0 ||
825           sym.n_desc & N_ALT_ENTRY || !isa<ConcatInputSection>(isec)) {
826         symbols[symIndex] =
827             createDefined(sym, name, isec, symbolOffset, symbolSize);
828         continue;
829       }
830       auto *concatIsec = cast<ConcatInputSection>(isec);
831 
832       auto *nextIsec = make<ConcatInputSection>(*concatIsec);
833       nextIsec->wasCoalesced = false;
834       if (isZeroFill(isec->getFlags())) {
835         // Zero-fill sections have NULL data.data() non-zero data.size()
836         nextIsec->data = {nullptr, isec->data.size() - symbolOffset};
837         isec->data = {nullptr, symbolOffset};
838       } else {
839         nextIsec->data = isec->data.slice(symbolOffset);
840         isec->data = isec->data.slice(0, symbolOffset);
841       }
842 
843       // By construction, the symbol will be at offset zero in the new
844       // subsection.
845       symbols[symIndex] =
846           createDefined(sym, name, nextIsec, /*value=*/0, symbolSize);
847       // TODO: ld64 appears to preserve the original alignment as well as each
848       // subsection's offset from the last aligned address. We should consider
849       // emulating that behavior.
850       nextIsec->align = MinAlign(sectionAlign, sym.n_value);
851       subsections.push_back({sym.n_value - sectionAddr, nextIsec});
852     }
853   }
854 
855   // Undefined symbols can trigger recursive fetch from Archives due to
856   // LazySymbols. Process defined symbols first so that the relative order
857   // between a defined symbol and an undefined symbol does not change the
858   // symbol resolution behavior. In addition, a set of interconnected symbols
859   // will all be resolved to the same file, instead of being resolved to
860   // different files.
861   for (unsigned i : undefineds) {
862     const NList &sym = nList[i];
863     StringRef name = strtab + sym.n_strx;
864     symbols[i] = parseNonSectionSymbol(sym, name);
865   }
866 }
867 
868 OpaqueFile::OpaqueFile(MemoryBufferRef mb, StringRef segName,
869                        StringRef sectName)
870     : InputFile(OpaqueKind, mb) {
871   const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
872   ArrayRef<uint8_t> data = {buf, mb.getBufferSize()};
873   sections.push_back(make<Section>(/*file=*/this, segName.take_front(16),
874                                    sectName.take_front(16),
875                                    /*flags=*/0, /*addr=*/0));
876   Section &section = *sections.back();
877   ConcatInputSection *isec = make<ConcatInputSection>(section, data);
878   isec->live = true;
879   section.subsections.push_back({0, isec});
880 }
881 
882 ObjFile::ObjFile(MemoryBufferRef mb, uint32_t modTime, StringRef archiveName,
883                  bool lazy)
884     : InputFile(ObjKind, mb, lazy), modTime(modTime) {
885   this->archiveName = std::string(archiveName);
886   if (lazy) {
887     if (target->wordSize == 8)
888       parseLazy<LP64>();
889     else
890       parseLazy<ILP32>();
891   } else {
892     if (target->wordSize == 8)
893       parse<LP64>();
894     else
895       parse<ILP32>();
896   }
897 }
898 
899 template <class LP> void ObjFile::parse() {
900   using Header = typename LP::mach_header;
901   using SegmentCommand = typename LP::segment_command;
902   using SectionHeader = typename LP::section;
903   using NList = typename LP::nlist;
904 
905   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
906   auto *hdr = reinterpret_cast<const Header *>(mb.getBufferStart());
907 
908   Architecture arch = getArchitectureFromCpuType(hdr->cputype, hdr->cpusubtype);
909   if (arch != config->arch()) {
910     auto msg = config->errorForArchMismatch
911                    ? static_cast<void (*)(const Twine &)>(error)
912                    : warn;
913     msg(toString(this) + " has architecture " + getArchitectureName(arch) +
914         " which is incompatible with target architecture " +
915         getArchitectureName(config->arch()));
916     return;
917   }
918 
919   if (!checkCompatibility(this))
920     return;
921 
922   for (auto *cmd : findCommands<linker_option_command>(hdr, LC_LINKER_OPTION)) {
923     StringRef data{reinterpret_cast<const char *>(cmd + 1),
924                    cmd->cmdsize - sizeof(linker_option_command)};
925     parseLCLinkerOption(this, cmd->count, data);
926   }
927 
928   ArrayRef<SectionHeader> sectionHeaders;
929   if (const load_command *cmd = findCommand(hdr, LP::segmentLCType)) {
930     auto *c = reinterpret_cast<const SegmentCommand *>(cmd);
931     sectionHeaders = ArrayRef<SectionHeader>{
932         reinterpret_cast<const SectionHeader *>(c + 1), c->nsects};
933     parseSections(sectionHeaders);
934   }
935 
936   // TODO: Error on missing LC_SYMTAB?
937   if (const load_command *cmd = findCommand(hdr, LC_SYMTAB)) {
938     auto *c = reinterpret_cast<const symtab_command *>(cmd);
939     ArrayRef<NList> nList(reinterpret_cast<const NList *>(buf + c->symoff),
940                           c->nsyms);
941     const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff;
942     bool subsectionsViaSymbols = hdr->flags & MH_SUBSECTIONS_VIA_SYMBOLS;
943     parseSymbols<LP>(sectionHeaders, nList, strtab, subsectionsViaSymbols);
944   }
945 
946   // The relocations may refer to the symbols, so we parse them after we have
947   // parsed all the symbols.
948   for (size_t i = 0, n = sections.size(); i < n; ++i)
949     if (!sections[i]->subsections.empty())
950       parseRelocations(sectionHeaders, sectionHeaders[i], *sections[i]);
951 
952   parseDebugInfo();
953 
954   Section *ehFrameSection = nullptr;
955   Section *compactUnwindSection = nullptr;
956   for (Section *sec : sections) {
957     Section **s = StringSwitch<Section **>(sec->name)
958                       .Case(section_names::compactUnwind, &compactUnwindSection)
959                       .Case(section_names::ehFrame, &ehFrameSection)
960                       .Default(nullptr);
961     if (s)
962       *s = sec;
963   }
964   if (compactUnwindSection)
965     registerCompactUnwind(*compactUnwindSection);
966   if (config->parseEhFrames && ehFrameSection)
967     registerEhFrames(*ehFrameSection);
968 }
969 
970 template <class LP> void ObjFile::parseLazy() {
971   using Header = typename LP::mach_header;
972   using NList = typename LP::nlist;
973 
974   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
975   auto *hdr = reinterpret_cast<const Header *>(mb.getBufferStart());
976   const load_command *cmd = findCommand(hdr, LC_SYMTAB);
977   if (!cmd)
978     return;
979   auto *c = reinterpret_cast<const symtab_command *>(cmd);
980   ArrayRef<NList> nList(reinterpret_cast<const NList *>(buf + c->symoff),
981                         c->nsyms);
982   const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff;
983   symbols.resize(nList.size());
984   for (auto it : llvm::enumerate(nList)) {
985     const NList &sym = it.value();
986     if ((sym.n_type & N_EXT) && !isUndef(sym)) {
987       // TODO: Bound checking
988       StringRef name = strtab + sym.n_strx;
989       symbols[it.index()] = symtab->addLazyObject(name, *this);
990       if (!lazy)
991         break;
992     }
993   }
994 }
995 
996 void ObjFile::parseDebugInfo() {
997   std::unique_ptr<DwarfObject> dObj = DwarfObject::create(this);
998   if (!dObj)
999     return;
1000 
1001   // We do not re-use the context from getDwarf() here as that function
1002   // constructs an expensive DWARFCache object.
1003   auto *ctx = make<DWARFContext>(
1004       std::move(dObj), "",
1005       [&](Error err) {
1006         warn(toString(this) + ": " + toString(std::move(err)));
1007       },
1008       [&](Error warning) {
1009         warn(toString(this) + ": " + toString(std::move(warning)));
1010       });
1011 
1012   // TODO: Since object files can contain a lot of DWARF info, we should verify
1013   // that we are parsing just the info we need
1014   const DWARFContext::compile_unit_range &units = ctx->compile_units();
1015   // FIXME: There can be more than one compile unit per object file. See
1016   // PR48637.
1017   auto it = units.begin();
1018   compileUnit = it != units.end() ? it->get() : nullptr;
1019 }
1020 
1021 ArrayRef<data_in_code_entry> ObjFile::getDataInCode() const {
1022   const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
1023   const load_command *cmd = findCommand(buf, LC_DATA_IN_CODE);
1024   if (!cmd)
1025     return {};
1026   const auto *c = reinterpret_cast<const linkedit_data_command *>(cmd);
1027   return {reinterpret_cast<const data_in_code_entry *>(buf + c->dataoff),
1028           c->datasize / sizeof(data_in_code_entry)};
1029 }
1030 
1031 // Create pointers from symbols to their associated compact unwind entries.
1032 void ObjFile::registerCompactUnwind(Section &compactUnwindSection) {
1033   for (const Subsection &subsection : compactUnwindSection.subsections) {
1034     ConcatInputSection *isec = cast<ConcatInputSection>(subsection.isec);
1035     // Hack!! Since each CUE contains a different function address, if ICF
1036     // operated naively and compared the entire contents of each CUE, entries
1037     // with identical unwind info but belonging to different functions would
1038     // never be considered equivalent. To work around this problem, we slice
1039     // away the function address here. (Note that we do not adjust the offsets
1040     // of the corresponding relocations.) We rely on `relocateCompactUnwind()`
1041     // to correctly handle these truncated input sections.
1042     isec->data = isec->data.slice(target->wordSize);
1043     uint32_t encoding = read32le(isec->data.data() + sizeof(uint32_t));
1044     // llvm-mc omits CU entries for functions that need DWARF encoding, but
1045     // `ld -r` doesn't. We can ignore them because we will re-synthesize these
1046     // CU entries from the DWARF info during the output phase.
1047     if ((encoding & target->modeDwarfEncoding) == target->modeDwarfEncoding)
1048       continue;
1049 
1050     ConcatInputSection *referentIsec;
1051     for (auto it = isec->relocs.begin(); it != isec->relocs.end();) {
1052       Reloc &r = *it;
1053       // CUE::functionAddress is at offset 0. Skip personality & LSDA relocs.
1054       if (r.offset != 0) {
1055         ++it;
1056         continue;
1057       }
1058       uint64_t add = r.addend;
1059       if (auto *sym = cast_or_null<Defined>(r.referent.dyn_cast<Symbol *>())) {
1060         // Check whether the symbol defined in this file is the prevailing one.
1061         // Skip if it is e.g. a weak def that didn't prevail.
1062         if (sym->getFile() != this) {
1063           ++it;
1064           continue;
1065         }
1066         add += sym->value;
1067         referentIsec = cast<ConcatInputSection>(sym->isec);
1068       } else {
1069         referentIsec =
1070             cast<ConcatInputSection>(r.referent.dyn_cast<InputSection *>());
1071       }
1072       // Unwind info lives in __DATA, and finalization of __TEXT will occur
1073       // before finalization of __DATA. Moreover, the finalization of unwind
1074       // info depends on the exact addresses that it references. So it is safe
1075       // for compact unwind to reference addresses in __TEXT, but not addresses
1076       // in any other segment.
1077       if (referentIsec->getSegName() != segment_names::text)
1078         error(isec->getLocation(r.offset) + " references section " +
1079               referentIsec->getName() + " which is not in segment __TEXT");
1080       // The functionAddress relocations are typically section relocations.
1081       // However, unwind info operates on a per-symbol basis, so we search for
1082       // the function symbol here.
1083       Defined *d = findSymbolAtOffset(referentIsec, add);
1084       if (!d) {
1085         ++it;
1086         continue;
1087       }
1088       d->unwindEntry = isec;
1089       // Since we've sliced away the functionAddress, we should remove the
1090       // corresponding relocation too. Given that clang emits relocations in
1091       // reverse order of address, this relocation should be at the end of the
1092       // vector for most of our input object files, so this is typically an O(1)
1093       // operation.
1094       it = isec->relocs.erase(it);
1095     }
1096   }
1097 }
1098 
1099 struct CIE {
1100   macho::Symbol *personalitySymbol = nullptr;
1101   bool fdesHaveLsda = false;
1102   bool fdesHaveAug = false;
1103 };
1104 
1105 static CIE parseCIE(const InputSection *isec, const EhReader &reader,
1106                     size_t off) {
1107   // Handling the full generality of possible DWARF encodings would be a major
1108   // pain. We instead take advantage of our knowledge of how llvm-mc encodes
1109   // DWARF and handle just that.
1110   constexpr uint8_t expectedPersonalityEnc =
1111       dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_sdata4;
1112   constexpr uint8_t expectedPointerEnc =
1113       dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_absptr;
1114 
1115   CIE cie;
1116   uint8_t version = reader.readByte(&off);
1117   if (version != 1 && version != 3)
1118     fatal("Expected CIE version of 1 or 3, got " + Twine(version));
1119   StringRef aug = reader.readString(&off);
1120   reader.skipLeb128(&off); // skip code alignment
1121   reader.skipLeb128(&off); // skip data alignment
1122   reader.skipLeb128(&off); // skip return address register
1123   reader.skipLeb128(&off); // skip aug data length
1124   uint64_t personalityAddrOff = 0;
1125   for (char c : aug) {
1126     switch (c) {
1127     case 'z':
1128       cie.fdesHaveAug = true;
1129       break;
1130     case 'P': {
1131       uint8_t personalityEnc = reader.readByte(&off);
1132       if (personalityEnc != expectedPersonalityEnc)
1133         reader.failOn(off, "unexpected personality encoding 0x" +
1134                                Twine::utohexstr(personalityEnc));
1135       personalityAddrOff = off;
1136       off += 4;
1137       break;
1138     }
1139     case 'L': {
1140       cie.fdesHaveLsda = true;
1141       uint8_t lsdaEnc = reader.readByte(&off);
1142       if (lsdaEnc != expectedPointerEnc)
1143         reader.failOn(off, "unexpected LSDA encoding 0x" +
1144                                Twine::utohexstr(lsdaEnc));
1145       break;
1146     }
1147     case 'R': {
1148       uint8_t pointerEnc = reader.readByte(&off);
1149       if (pointerEnc != expectedPointerEnc)
1150         reader.failOn(off, "unexpected pointer encoding 0x" +
1151                                Twine::utohexstr(pointerEnc));
1152       break;
1153     }
1154     default:
1155       break;
1156     }
1157   }
1158   if (personalityAddrOff != 0) {
1159     auto personalityRelocIt =
1160         llvm::find_if(isec->relocs, [=](const macho::Reloc &r) {
1161           return r.offset == personalityAddrOff;
1162         });
1163     if (personalityRelocIt == isec->relocs.end())
1164       reader.failOn(off, "Failed to locate relocation for personality symbol");
1165     cie.personalitySymbol = personalityRelocIt->referent.get<macho::Symbol *>();
1166   }
1167   return cie;
1168 }
1169 
1170 // EH frame target addresses may be encoded as pcrel offsets. However, instead
1171 // of using an actual pcrel reloc, ld64 emits subtractor relocations instead.
1172 // This function recovers the target address from the subtractors, essentially
1173 // performing the inverse operation of EhRelocator.
1174 //
1175 // Concretely, we expect our relocations to write the value of `PC -
1176 // target_addr` to `PC`. `PC` itself is denoted by a minuend relocation that
1177 // points to a symbol plus an addend.
1178 //
1179 // It is important that the minuend relocation point to a symbol within the
1180 // same section as the fixup value, since sections may get moved around.
1181 //
1182 // For example, for arm64, llvm-mc emits relocations for the target function
1183 // address like so:
1184 //
1185 //   ltmp:
1186 //     <CIE start>
1187 //     ...
1188 //     <CIE end>
1189 //     ... multiple FDEs ...
1190 //     <FDE start>
1191 //     <target function address - (ltmp + pcrel offset)>
1192 //     ...
1193 //
1194 // If any of the FDEs in `multiple FDEs` get dead-stripped, then `FDE start`
1195 // will move to an earlier address, and `ltmp + pcrel offset` will no longer
1196 // reflect an accurate pcrel value. To avoid this problem, we "canonicalize"
1197 // our relocation by adding an `EH_Frame` symbol at `FDE start`, and updating
1198 // the reloc to be `target function address - (EH_Frame + new pcrel offset)`.
1199 //
1200 // If `Invert` is set, then we instead expect `target_addr - PC` to be written
1201 // to `PC`.
1202 template <bool Invert = false>
1203 Defined *
1204 targetSymFromCanonicalSubtractor(const InputSection *isec,
1205                                  std::vector<macho::Reloc>::iterator relocIt) {
1206   macho::Reloc &subtrahend = *relocIt;
1207   macho::Reloc &minuend = *std::next(relocIt);
1208   assert(target->hasAttr(subtrahend.type, RelocAttrBits::SUBTRAHEND));
1209   assert(target->hasAttr(minuend.type, RelocAttrBits::UNSIGNED));
1210   // Note: pcSym may *not* be exactly at the PC; there's usually a non-zero
1211   // addend.
1212   auto *pcSym = cast<Defined>(subtrahend.referent.get<macho::Symbol *>());
1213   Defined *target =
1214       cast_or_null<Defined>(minuend.referent.dyn_cast<macho::Symbol *>());
1215   if (!pcSym) {
1216     auto *targetIsec =
1217         cast<ConcatInputSection>(minuend.referent.get<InputSection *>());
1218     target = findSymbolAtOffset(targetIsec, minuend.addend);
1219   }
1220   if (Invert)
1221     std::swap(pcSym, target);
1222   if (pcSym->isec == isec) {
1223     if (pcSym->value - (Invert ? -1 : 1) * minuend.addend != subtrahend.offset)
1224       fatal("invalid FDE relocation in __eh_frame");
1225   } else {
1226     // Ensure the pcReloc points to a symbol within the current EH frame.
1227     // HACK: we should really verify that the original relocation's semantics
1228     // are preserved. In particular, we should have
1229     // `oldSym->value + oldOffset == newSym + newOffset`. However, we don't
1230     // have an easy way to access the offsets from this point in the code; some
1231     // refactoring is needed for that.
1232     macho::Reloc &pcReloc = Invert ? minuend : subtrahend;
1233     pcReloc.referent = isec->symbols[0];
1234     assert(isec->symbols[0]->value == 0);
1235     minuend.addend = pcReloc.offset * (Invert ? 1LL : -1LL);
1236   }
1237   return target;
1238 }
1239 
1240 Defined *findSymbolAtAddress(const std::vector<Section *> &sections,
1241                              uint64_t addr) {
1242   Section *sec = findContainingSection(sections, &addr);
1243   auto *isec = cast<ConcatInputSection>(findContainingSubsection(*sec, &addr));
1244   return findSymbolAtOffset(isec, addr);
1245 }
1246 
1247 // For symbols that don't have compact unwind info, associate them with the more
1248 // general-purpose (and verbose) DWARF unwind info found in __eh_frame.
1249 //
1250 // This requires us to parse the contents of __eh_frame. See EhFrame.h for a
1251 // description of its format.
1252 //
1253 // While parsing, we also look for what MC calls "abs-ified" relocations -- they
1254 // are relocations which are implicitly encoded as offsets in the section data.
1255 // We convert them into explicit Reloc structs so that the EH frames can be
1256 // handled just like a regular ConcatInputSection later in our output phase.
1257 //
1258 // We also need to handle the case where our input object file has explicit
1259 // relocations. This is the case when e.g. it's the output of `ld -r`. We only
1260 // look for the "abs-ified" relocation if an explicit relocation is absent.
1261 void ObjFile::registerEhFrames(Section &ehFrameSection) {
1262   DenseMap<const InputSection *, CIE> cieMap;
1263   for (const Subsection &subsec : ehFrameSection.subsections) {
1264     auto *isec = cast<ConcatInputSection>(subsec.isec);
1265     uint64_t isecOff = subsec.offset;
1266 
1267     // Subtractor relocs require the subtrahend to be a symbol reloc. Ensure
1268     // that all EH frames have an associated symbol so that we can generate
1269     // subtractor relocs that reference them.
1270     if (isec->symbols.size() == 0)
1271       isec->symbols.push_back(make<Defined>(
1272           "EH_Frame", isec->getFile(), isec, /*value=*/0, /*size=*/0,
1273           /*isWeakDef=*/false, /*isExternal=*/false, /*isPrivateExtern=*/false,
1274           /*includeInSymtab=*/false, /*isThumb=*/false,
1275           /*isReferencedDynamically=*/false, /*noDeadStrip=*/false));
1276     else if (isec->symbols[0]->value != 0)
1277       fatal("found symbol at unexpected offset in __eh_frame");
1278 
1279     EhReader reader(this, isec->data, subsec.offset, target->wordSize);
1280     size_t dataOff = 0; // Offset from the start of the EH frame.
1281     reader.skipValidLength(&dataOff); // readLength() already validated this.
1282     // cieOffOff is the offset from the start of the EH frame to the cieOff
1283     // value, which is itself an offset from the current PC to a CIE.
1284     const size_t cieOffOff = dataOff;
1285 
1286     EhRelocator ehRelocator(isec);
1287     auto cieOffRelocIt = llvm::find_if(
1288         isec->relocs, [=](const Reloc &r) { return r.offset == cieOffOff; });
1289     InputSection *cieIsec = nullptr;
1290     if (cieOffRelocIt != isec->relocs.end()) {
1291       // We already have an explicit relocation for the CIE offset.
1292       cieIsec =
1293           targetSymFromCanonicalSubtractor</*Invert=*/true>(isec, cieOffRelocIt)
1294               ->isec;
1295       dataOff += sizeof(uint32_t);
1296     } else {
1297       // If we haven't found a relocation, then the CIE offset is most likely
1298       // embedded in the section data (AKA an "abs-ified" reloc.). Parse that
1299       // and generate a Reloc struct.
1300       uint32_t cieMinuend = reader.readU32(&dataOff);
1301       if (cieMinuend == 0)
1302         cieIsec = isec;
1303       else {
1304         uint32_t cieOff = isecOff + dataOff - cieMinuend;
1305         cieIsec = findContainingSubsection(ehFrameSection, &cieOff);
1306         if (cieIsec == nullptr)
1307           fatal("failed to find CIE");
1308       }
1309       if (cieIsec != isec)
1310         ehRelocator.makeNegativePcRel(cieOffOff, cieIsec->symbols[0],
1311                                       /*length=*/2);
1312     }
1313     if (cieIsec == isec) {
1314       cieMap[cieIsec] = parseCIE(isec, reader, dataOff);
1315       continue;
1316     }
1317 
1318     // Offset of the function address within the EH frame.
1319     const size_t funcAddrOff = dataOff;
1320     uint64_t funcAddr = reader.readPointer(&dataOff) + ehFrameSection.addr +
1321                         isecOff + funcAddrOff;
1322     uint32_t funcLength = reader.readPointer(&dataOff);
1323     size_t lsdaAddrOff = 0; // Offset of the LSDA address within the EH frame.
1324     assert(cieMap.count(cieIsec));
1325     const CIE &cie = cieMap[cieIsec];
1326     Optional<uint64_t> lsdaAddrOpt;
1327     if (cie.fdesHaveAug) {
1328       reader.skipLeb128(&dataOff);
1329       lsdaAddrOff = dataOff;
1330       if (cie.fdesHaveLsda) {
1331         uint64_t lsdaOff = reader.readPointer(&dataOff);
1332         if (lsdaOff != 0) // FIXME possible to test this?
1333           lsdaAddrOpt = ehFrameSection.addr + isecOff + lsdaAddrOff + lsdaOff;
1334       }
1335     }
1336 
1337     auto funcAddrRelocIt = isec->relocs.end();
1338     auto lsdaAddrRelocIt = isec->relocs.end();
1339     for (auto it = isec->relocs.begin(); it != isec->relocs.end(); ++it) {
1340       if (it->offset == funcAddrOff)
1341         funcAddrRelocIt = it++; // Found subtrahend; skip over minuend reloc
1342       else if (lsdaAddrOpt && it->offset == lsdaAddrOff)
1343         lsdaAddrRelocIt = it++; // Found subtrahend; skip over minuend reloc
1344     }
1345 
1346     Defined *funcSym;
1347     if (funcAddrRelocIt != isec->relocs.end()) {
1348       funcSym = targetSymFromCanonicalSubtractor(isec, funcAddrRelocIt);
1349     } else {
1350       funcSym = findSymbolAtAddress(sections, funcAddr);
1351       ehRelocator.makePcRel(funcAddrOff, funcSym, target->p2WordSize);
1352     }
1353     // The symbol has been coalesced, or already has a compact unwind entry.
1354     if (!funcSym || funcSym->getFile() != this || funcSym->unwindEntry) {
1355       // We must prune unused FDEs for correctness, so we cannot rely on
1356       // -dead_strip being enabled.
1357       isec->live = false;
1358       continue;
1359     }
1360 
1361     InputSection *lsdaIsec = nullptr;
1362     if (lsdaAddrRelocIt != isec->relocs.end()) {
1363       lsdaIsec = targetSymFromCanonicalSubtractor(isec, lsdaAddrRelocIt)->isec;
1364     } else if (lsdaAddrOpt) {
1365       uint64_t lsdaAddr = *lsdaAddrOpt;
1366       Section *sec = findContainingSection(sections, &lsdaAddr);
1367       lsdaIsec =
1368           cast<ConcatInputSection>(findContainingSubsection(*sec, &lsdaAddr));
1369       ehRelocator.makePcRel(lsdaAddrOff, lsdaIsec, target->p2WordSize);
1370     }
1371 
1372     fdes[isec] = {funcLength, cie.personalitySymbol, lsdaIsec};
1373     funcSym->unwindEntry = isec;
1374     ehRelocator.commit();
1375   }
1376 }
1377 
1378 std::string ObjFile::sourceFile() const {
1379   SmallString<261> dir(compileUnit->getCompilationDir());
1380   StringRef sep = sys::path::get_separator();
1381   // We don't use `path::append` here because we want an empty `dir` to result
1382   // in an absolute path. `append` would give us a relative path for that case.
1383   if (!dir.endswith(sep))
1384     dir += sep;
1385   return (dir + compileUnit->getUnitDIE().getShortName()).str();
1386 }
1387 
1388 lld::DWARFCache *ObjFile::getDwarf() {
1389   llvm::call_once(initDwarf, [this]() {
1390     auto dwObj = DwarfObject::create(this);
1391     if (!dwObj)
1392       return;
1393     dwarfCache = std::make_unique<DWARFCache>(std::make_unique<DWARFContext>(
1394         std::move(dwObj), "",
1395         [&](Error err) { warn(getName() + ": " + toString(std::move(err))); },
1396         [&](Error warning) {
1397           warn(getName() + ": " + toString(std::move(warning)));
1398         }));
1399   });
1400 
1401   return dwarfCache.get();
1402 }
1403 // The path can point to either a dylib or a .tbd file.
1404 static DylibFile *loadDylib(StringRef path, DylibFile *umbrella) {
1405   Optional<MemoryBufferRef> mbref = readFile(path);
1406   if (!mbref) {
1407     error("could not read dylib file at " + path);
1408     return nullptr;
1409   }
1410   return loadDylib(*mbref, umbrella);
1411 }
1412 
1413 // TBD files are parsed into a series of TAPI documents (InterfaceFiles), with
1414 // the first document storing child pointers to the rest of them. When we are
1415 // processing a given TBD file, we store that top-level document in
1416 // currentTopLevelTapi. When processing re-exports, we search its children for
1417 // potentially matching documents in the same TBD file. Note that the children
1418 // themselves don't point to further documents, i.e. this is a two-level tree.
1419 //
1420 // Re-exports can either refer to on-disk files, or to documents within .tbd
1421 // files.
1422 static DylibFile *findDylib(StringRef path, DylibFile *umbrella,
1423                             const InterfaceFile *currentTopLevelTapi) {
1424   // Search order:
1425   // 1. Install name basename in -F / -L directories.
1426   {
1427     StringRef stem = path::stem(path);
1428     SmallString<128> frameworkName;
1429     path::append(frameworkName, path::Style::posix, stem + ".framework", stem);
1430     bool isFramework = path.endswith(frameworkName);
1431     if (isFramework) {
1432       for (StringRef dir : config->frameworkSearchPaths) {
1433         SmallString<128> candidate = dir;
1434         path::append(candidate, frameworkName);
1435         if (Optional<StringRef> dylibPath = resolveDylibPath(candidate.str()))
1436           return loadDylib(*dylibPath, umbrella);
1437       }
1438     } else if (Optional<StringRef> dylibPath = findPathCombination(
1439                    stem, config->librarySearchPaths, {".tbd", ".dylib"}))
1440       return loadDylib(*dylibPath, umbrella);
1441   }
1442 
1443   // 2. As absolute path.
1444   if (path::is_absolute(path, path::Style::posix))
1445     for (StringRef root : config->systemLibraryRoots)
1446       if (Optional<StringRef> dylibPath = resolveDylibPath((root + path).str()))
1447         return loadDylib(*dylibPath, umbrella);
1448 
1449   // 3. As relative path.
1450 
1451   // TODO: Handle -dylib_file
1452 
1453   // Replace @executable_path, @loader_path, @rpath prefixes in install name.
1454   SmallString<128> newPath;
1455   if (config->outputType == MH_EXECUTE &&
1456       path.consume_front("@executable_path/")) {
1457     // ld64 allows overriding this with the undocumented flag -executable_path.
1458     // lld doesn't currently implement that flag.
1459     // FIXME: Consider using finalOutput instead of outputFile.
1460     path::append(newPath, path::parent_path(config->outputFile), path);
1461     path = newPath;
1462   } else if (path.consume_front("@loader_path/")) {
1463     fs::real_path(umbrella->getName(), newPath);
1464     path::remove_filename(newPath);
1465     path::append(newPath, path);
1466     path = newPath;
1467   } else if (path.startswith("@rpath/")) {
1468     for (StringRef rpath : umbrella->rpaths) {
1469       newPath.clear();
1470       if (rpath.consume_front("@loader_path/")) {
1471         fs::real_path(umbrella->getName(), newPath);
1472         path::remove_filename(newPath);
1473       }
1474       path::append(newPath, rpath, path.drop_front(strlen("@rpath/")));
1475       if (Optional<StringRef> dylibPath = resolveDylibPath(newPath.str()))
1476         return loadDylib(*dylibPath, umbrella);
1477     }
1478   }
1479 
1480   // FIXME: Should this be further up?
1481   if (currentTopLevelTapi) {
1482     for (InterfaceFile &child :
1483          make_pointee_range(currentTopLevelTapi->documents())) {
1484       assert(child.documents().empty());
1485       if (path == child.getInstallName()) {
1486         auto file = make<DylibFile>(child, umbrella, /*isBundleLoader=*/false,
1487                                     /*explicitlyLinked=*/false);
1488         file->parseReexports(child);
1489         return file;
1490       }
1491     }
1492   }
1493 
1494   if (Optional<StringRef> dylibPath = resolveDylibPath(path))
1495     return loadDylib(*dylibPath, umbrella);
1496 
1497   return nullptr;
1498 }
1499 
1500 // If a re-exported dylib is public (lives in /usr/lib or
1501 // /System/Library/Frameworks), then it is considered implicitly linked: we
1502 // should bind to its symbols directly instead of via the re-exporting umbrella
1503 // library.
1504 static bool isImplicitlyLinked(StringRef path) {
1505   if (!config->implicitDylibs)
1506     return false;
1507 
1508   if (path::parent_path(path) == "/usr/lib")
1509     return true;
1510 
1511   // Match /System/Library/Frameworks/$FOO.framework/**/$FOO
1512   if (path.consume_front("/System/Library/Frameworks/")) {
1513     StringRef frameworkName = path.take_until([](char c) { return c == '.'; });
1514     return path::filename(path) == frameworkName;
1515   }
1516 
1517   return false;
1518 }
1519 
1520 static void loadReexport(StringRef path, DylibFile *umbrella,
1521                          const InterfaceFile *currentTopLevelTapi) {
1522   DylibFile *reexport = findDylib(path, umbrella, currentTopLevelTapi);
1523   if (!reexport)
1524     error("unable to locate re-export with install name " + path);
1525 }
1526 
1527 DylibFile::DylibFile(MemoryBufferRef mb, DylibFile *umbrella,
1528                      bool isBundleLoader, bool explicitlyLinked)
1529     : InputFile(DylibKind, mb), refState(RefState::Unreferenced),
1530       explicitlyLinked(explicitlyLinked), isBundleLoader(isBundleLoader) {
1531   assert(!isBundleLoader || !umbrella);
1532   if (umbrella == nullptr)
1533     umbrella = this;
1534   this->umbrella = umbrella;
1535 
1536   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
1537   auto *hdr = reinterpret_cast<const mach_header *>(mb.getBufferStart());
1538 
1539   // Initialize installName.
1540   if (const load_command *cmd = findCommand(hdr, LC_ID_DYLIB)) {
1541     auto *c = reinterpret_cast<const dylib_command *>(cmd);
1542     currentVersion = read32le(&c->dylib.current_version);
1543     compatibilityVersion = read32le(&c->dylib.compatibility_version);
1544     installName =
1545         reinterpret_cast<const char *>(cmd) + read32le(&c->dylib.name);
1546   } else if (!isBundleLoader) {
1547     // macho_executable and macho_bundle don't have LC_ID_DYLIB,
1548     // so it's OK.
1549     error("dylib " + toString(this) + " missing LC_ID_DYLIB load command");
1550     return;
1551   }
1552 
1553   if (config->printEachFile)
1554     message(toString(this));
1555   inputFiles.insert(this);
1556 
1557   deadStrippable = hdr->flags & MH_DEAD_STRIPPABLE_DYLIB;
1558 
1559   if (!checkCompatibility(this))
1560     return;
1561 
1562   checkAppExtensionSafety(hdr->flags & MH_APP_EXTENSION_SAFE);
1563 
1564   for (auto *cmd : findCommands<rpath_command>(hdr, LC_RPATH)) {
1565     StringRef rpath{reinterpret_cast<const char *>(cmd) + cmd->path};
1566     rpaths.push_back(rpath);
1567   }
1568 
1569   // Initialize symbols.
1570   exportingFile = isImplicitlyLinked(installName) ? this : this->umbrella;
1571   if (const load_command *cmd = findCommand(hdr, LC_DYLD_INFO_ONLY)) {
1572     auto *c = reinterpret_cast<const dyld_info_command *>(cmd);
1573     struct TrieEntry {
1574       StringRef name;
1575       uint64_t flags;
1576     };
1577 
1578     std::vector<TrieEntry> entries;
1579     // Find all the $ld$* symbols to process first.
1580     parseTrie(buf + c->export_off, c->export_size,
1581               [&](const Twine &name, uint64_t flags) {
1582                 StringRef savedName = saver().save(name);
1583                 if (handleLDSymbol(savedName))
1584                   return;
1585                 entries.push_back({savedName, flags});
1586               });
1587 
1588     // Process the "normal" symbols.
1589     for (TrieEntry &entry : entries) {
1590       if (exportingFile->hiddenSymbols.contains(
1591               CachedHashStringRef(entry.name)))
1592         continue;
1593 
1594       bool isWeakDef = entry.flags & EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION;
1595       bool isTlv = entry.flags & EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL;
1596 
1597       symbols.push_back(
1598           symtab->addDylib(entry.name, exportingFile, isWeakDef, isTlv));
1599     }
1600 
1601   } else {
1602     error("LC_DYLD_INFO_ONLY not found in " + toString(this));
1603     return;
1604   }
1605 }
1606 
1607 void DylibFile::parseLoadCommands(MemoryBufferRef mb) {
1608   auto *hdr = reinterpret_cast<const mach_header *>(mb.getBufferStart());
1609   const uint8_t *p = reinterpret_cast<const uint8_t *>(mb.getBufferStart()) +
1610                      target->headerSize;
1611   for (uint32_t i = 0, n = hdr->ncmds; i < n; ++i) {
1612     auto *cmd = reinterpret_cast<const load_command *>(p);
1613     p += cmd->cmdsize;
1614 
1615     if (!(hdr->flags & MH_NO_REEXPORTED_DYLIBS) &&
1616         cmd->cmd == LC_REEXPORT_DYLIB) {
1617       const auto *c = reinterpret_cast<const dylib_command *>(cmd);
1618       StringRef reexportPath =
1619           reinterpret_cast<const char *>(c) + read32le(&c->dylib.name);
1620       loadReexport(reexportPath, exportingFile, nullptr);
1621     }
1622 
1623     // FIXME: What about LC_LOAD_UPWARD_DYLIB, LC_LAZY_LOAD_DYLIB,
1624     // LC_LOAD_WEAK_DYLIB, LC_REEXPORT_DYLIB (..are reexports from dylibs with
1625     // MH_NO_REEXPORTED_DYLIBS loaded for -flat_namespace)?
1626     if (config->namespaceKind == NamespaceKind::flat &&
1627         cmd->cmd == LC_LOAD_DYLIB) {
1628       const auto *c = reinterpret_cast<const dylib_command *>(cmd);
1629       StringRef dylibPath =
1630           reinterpret_cast<const char *>(c) + read32le(&c->dylib.name);
1631       DylibFile *dylib = findDylib(dylibPath, umbrella, nullptr);
1632       if (!dylib)
1633         error(Twine("unable to locate library '") + dylibPath +
1634               "' loaded from '" + toString(this) + "' for -flat_namespace");
1635     }
1636   }
1637 }
1638 
1639 // Some versions of Xcode ship with .tbd files that don't have the right
1640 // platform settings.
1641 constexpr std::array<StringRef, 3> skipPlatformChecks{
1642     "/usr/lib/system/libsystem_kernel.dylib",
1643     "/usr/lib/system/libsystem_platform.dylib",
1644     "/usr/lib/system/libsystem_pthread.dylib"};
1645 
1646 static bool skipPlatformCheckForCatalyst(const InterfaceFile &interface,
1647                                          bool explicitlyLinked) {
1648   // Catalyst outputs can link against implicitly linked macOS-only libraries.
1649   if (config->platform() != PLATFORM_MACCATALYST || explicitlyLinked)
1650     return false;
1651   return is_contained(interface.targets(),
1652                       MachO::Target(config->arch(), PLATFORM_MACOS));
1653 }
1654 
1655 DylibFile::DylibFile(const InterfaceFile &interface, DylibFile *umbrella,
1656                      bool isBundleLoader, bool explicitlyLinked)
1657     : InputFile(DylibKind, interface), refState(RefState::Unreferenced),
1658       explicitlyLinked(explicitlyLinked), isBundleLoader(isBundleLoader) {
1659   // FIXME: Add test for the missing TBD code path.
1660 
1661   if (umbrella == nullptr)
1662     umbrella = this;
1663   this->umbrella = umbrella;
1664 
1665   installName = saver().save(interface.getInstallName());
1666   compatibilityVersion = interface.getCompatibilityVersion().rawValue();
1667   currentVersion = interface.getCurrentVersion().rawValue();
1668 
1669   if (config->printEachFile)
1670     message(toString(this));
1671   inputFiles.insert(this);
1672 
1673   if (!is_contained(skipPlatformChecks, installName) &&
1674       !is_contained(interface.targets(), config->platformInfo.target) &&
1675       !skipPlatformCheckForCatalyst(interface, explicitlyLinked)) {
1676     error(toString(this) + " is incompatible with " +
1677           std::string(config->platformInfo.target));
1678     return;
1679   }
1680 
1681   checkAppExtensionSafety(interface.isApplicationExtensionSafe());
1682 
1683   exportingFile = isImplicitlyLinked(installName) ? this : umbrella;
1684   auto addSymbol = [&](const Twine &name) -> void {
1685     StringRef savedName = saver().save(name);
1686     if (exportingFile->hiddenSymbols.contains(CachedHashStringRef(savedName)))
1687       return;
1688 
1689     symbols.push_back(symtab->addDylib(savedName, exportingFile,
1690                                        /*isWeakDef=*/false,
1691                                        /*isTlv=*/false));
1692   };
1693 
1694   std::vector<const llvm::MachO::Symbol *> normalSymbols;
1695   normalSymbols.reserve(interface.symbolsCount());
1696   for (const auto *symbol : interface.symbols()) {
1697     if (!symbol->getArchitectures().has(config->arch()))
1698       continue;
1699     if (handleLDSymbol(symbol->getName()))
1700       continue;
1701 
1702     switch (symbol->getKind()) {
1703     case SymbolKind::GlobalSymbol:               // Fallthrough
1704     case SymbolKind::ObjectiveCClass:            // Fallthrough
1705     case SymbolKind::ObjectiveCClassEHType:      // Fallthrough
1706     case SymbolKind::ObjectiveCInstanceVariable: // Fallthrough
1707       normalSymbols.push_back(symbol);
1708     }
1709   }
1710 
1711   // TODO(compnerd) filter out symbols based on the target platform
1712   // TODO: handle weak defs, thread locals
1713   for (const auto *symbol : normalSymbols) {
1714     switch (symbol->getKind()) {
1715     case SymbolKind::GlobalSymbol:
1716       addSymbol(symbol->getName());
1717       break;
1718     case SymbolKind::ObjectiveCClass:
1719       // XXX ld64 only creates these symbols when -ObjC is passed in. We may
1720       // want to emulate that.
1721       addSymbol(objc::klass + symbol->getName());
1722       addSymbol(objc::metaclass + symbol->getName());
1723       break;
1724     case SymbolKind::ObjectiveCClassEHType:
1725       addSymbol(objc::ehtype + symbol->getName());
1726       break;
1727     case SymbolKind::ObjectiveCInstanceVariable:
1728       addSymbol(objc::ivar + symbol->getName());
1729       break;
1730     }
1731   }
1732 }
1733 
1734 void DylibFile::parseReexports(const InterfaceFile &interface) {
1735   const InterfaceFile *topLevel =
1736       interface.getParent() == nullptr ? &interface : interface.getParent();
1737   for (const InterfaceFileRef &intfRef : interface.reexportedLibraries()) {
1738     InterfaceFile::const_target_range targets = intfRef.targets();
1739     if (is_contained(skipPlatformChecks, intfRef.getInstallName()) ||
1740         is_contained(targets, config->platformInfo.target))
1741       loadReexport(intfRef.getInstallName(), exportingFile, topLevel);
1742   }
1743 }
1744 
1745 // $ld$ symbols modify the properties/behavior of the library (e.g. its install
1746 // name, compatibility version or hide/add symbols) for specific target
1747 // versions.
1748 bool DylibFile::handleLDSymbol(StringRef originalName) {
1749   if (!originalName.startswith("$ld$"))
1750     return false;
1751 
1752   StringRef action;
1753   StringRef name;
1754   std::tie(action, name) = originalName.drop_front(strlen("$ld$")).split('$');
1755   if (action == "previous")
1756     handleLDPreviousSymbol(name, originalName);
1757   else if (action == "install_name")
1758     handleLDInstallNameSymbol(name, originalName);
1759   else if (action == "hide")
1760     handleLDHideSymbol(name, originalName);
1761   return true;
1762 }
1763 
1764 void DylibFile::handleLDPreviousSymbol(StringRef name, StringRef originalName) {
1765   // originalName: $ld$ previous $ <installname> $ <compatversion> $
1766   // <platformstr> $ <startversion> $ <endversion> $ <symbol-name> $
1767   StringRef installName;
1768   StringRef compatVersion;
1769   StringRef platformStr;
1770   StringRef startVersion;
1771   StringRef endVersion;
1772   StringRef symbolName;
1773   StringRef rest;
1774 
1775   std::tie(installName, name) = name.split('$');
1776   std::tie(compatVersion, name) = name.split('$');
1777   std::tie(platformStr, name) = name.split('$');
1778   std::tie(startVersion, name) = name.split('$');
1779   std::tie(endVersion, name) = name.split('$');
1780   std::tie(symbolName, rest) = name.split('$');
1781   // TODO: ld64 contains some logic for non-empty symbolName as well.
1782   if (!symbolName.empty())
1783     return;
1784   unsigned platform;
1785   if (platformStr.getAsInteger(10, platform) ||
1786       platform != static_cast<unsigned>(config->platform()))
1787     return;
1788 
1789   VersionTuple start;
1790   if (start.tryParse(startVersion)) {
1791     warn("failed to parse start version, symbol '" + originalName +
1792          "' ignored");
1793     return;
1794   }
1795   VersionTuple end;
1796   if (end.tryParse(endVersion)) {
1797     warn("failed to parse end version, symbol '" + originalName + "' ignored");
1798     return;
1799   }
1800   if (config->platformInfo.minimum < start ||
1801       config->platformInfo.minimum >= end)
1802     return;
1803 
1804   this->installName = saver().save(installName);
1805 
1806   if (!compatVersion.empty()) {
1807     VersionTuple cVersion;
1808     if (cVersion.tryParse(compatVersion)) {
1809       warn("failed to parse compatibility version, symbol '" + originalName +
1810            "' ignored");
1811       return;
1812     }
1813     compatibilityVersion = encodeVersion(cVersion);
1814   }
1815 }
1816 
1817 void DylibFile::handleLDInstallNameSymbol(StringRef name,
1818                                           StringRef originalName) {
1819   // originalName: $ld$ install_name $ os<version> $ install_name
1820   StringRef condition, installName;
1821   std::tie(condition, installName) = name.split('$');
1822   VersionTuple version;
1823   if (!condition.consume_front("os") || version.tryParse(condition))
1824     warn("failed to parse os version, symbol '" + originalName + "' ignored");
1825   else if (version == config->platformInfo.minimum)
1826     this->installName = saver().save(installName);
1827 }
1828 
1829 void DylibFile::handleLDHideSymbol(StringRef name, StringRef originalName) {
1830   StringRef symbolName;
1831   bool shouldHide = true;
1832   if (name.startswith("os")) {
1833     // If it's hidden based on versions.
1834     name = name.drop_front(2);
1835     StringRef minVersion;
1836     std::tie(minVersion, symbolName) = name.split('$');
1837     VersionTuple versionTup;
1838     if (versionTup.tryParse(minVersion)) {
1839       warn("Failed to parse hidden version, symbol `" + originalName +
1840            "` ignored.");
1841       return;
1842     }
1843     shouldHide = versionTup == config->platformInfo.minimum;
1844   } else {
1845     symbolName = name;
1846   }
1847 
1848   if (shouldHide)
1849     exportingFile->hiddenSymbols.insert(CachedHashStringRef(symbolName));
1850 }
1851 
1852 void DylibFile::checkAppExtensionSafety(bool dylibIsAppExtensionSafe) const {
1853   if (config->applicationExtension && !dylibIsAppExtensionSafe)
1854     warn("using '-application_extension' with unsafe dylib: " + toString(this));
1855 }
1856 
1857 ArchiveFile::ArchiveFile(std::unique_ptr<object::Archive> &&f)
1858     : InputFile(ArchiveKind, f->getMemoryBufferRef()), file(std::move(f)) {}
1859 
1860 void ArchiveFile::addLazySymbols() {
1861   for (const object::Archive::Symbol &sym : file->symbols())
1862     symtab->addLazyArchive(sym.getName(), this, sym);
1863 }
1864 
1865 static Expected<InputFile *> loadArchiveMember(MemoryBufferRef mb,
1866                                                uint32_t modTime,
1867                                                StringRef archiveName,
1868                                                uint64_t offsetInArchive) {
1869   if (config->zeroModTime)
1870     modTime = 0;
1871 
1872   switch (identify_magic(mb.getBuffer())) {
1873   case file_magic::macho_object:
1874     return make<ObjFile>(mb, modTime, archiveName);
1875   case file_magic::bitcode:
1876     return make<BitcodeFile>(mb, archiveName, offsetInArchive);
1877   default:
1878     return createStringError(inconvertibleErrorCode(),
1879                              mb.getBufferIdentifier() +
1880                                  " has unhandled file type");
1881   }
1882 }
1883 
1884 Error ArchiveFile::fetch(const object::Archive::Child &c, StringRef reason) {
1885   if (!seen.insert(c.getChildOffset()).second)
1886     return Error::success();
1887 
1888   Expected<MemoryBufferRef> mb = c.getMemoryBufferRef();
1889   if (!mb)
1890     return mb.takeError();
1891 
1892   // Thin archives refer to .o files, so --reproduce needs the .o files too.
1893   if (tar && c.getParent()->isThin())
1894     tar->append(relativeToRoot(CHECK(c.getFullName(), this)), mb->getBuffer());
1895 
1896   Expected<TimePoint<std::chrono::seconds>> modTime = c.getLastModified();
1897   if (!modTime)
1898     return modTime.takeError();
1899 
1900   Expected<InputFile *> file =
1901       loadArchiveMember(*mb, toTimeT(*modTime), getName(), c.getChildOffset());
1902 
1903   if (!file)
1904     return file.takeError();
1905 
1906   inputFiles.insert(*file);
1907   printArchiveMemberLoad(reason, *file);
1908   return Error::success();
1909 }
1910 
1911 void ArchiveFile::fetch(const object::Archive::Symbol &sym) {
1912   object::Archive::Child c =
1913       CHECK(sym.getMember(), toString(this) +
1914                                  ": could not get the member defining symbol " +
1915                                  toMachOString(sym));
1916 
1917   // `sym` is owned by a LazySym, which will be replace<>()d by make<ObjFile>
1918   // and become invalid after that call. Copy it to the stack so we can refer
1919   // to it later.
1920   const object::Archive::Symbol symCopy = sym;
1921 
1922   // ld64 doesn't demangle sym here even with -demangle.
1923   // Match that: intentionally don't call toMachOString().
1924   if (Error e = fetch(c, symCopy.getName()))
1925     error(toString(this) + ": could not get the member defining symbol " +
1926           toMachOString(symCopy) + ": " + toString(std::move(e)));
1927 }
1928 
1929 static macho::Symbol *createBitcodeSymbol(const lto::InputFile::Symbol &objSym,
1930                                           BitcodeFile &file) {
1931   StringRef name = saver().save(objSym.getName());
1932 
1933   if (objSym.isUndefined())
1934     return symtab->addUndefined(name, &file, /*isWeakRef=*/objSym.isWeak());
1935 
1936   // TODO: Write a test demonstrating why computing isPrivateExtern before
1937   // LTO compilation is important.
1938   bool isPrivateExtern = false;
1939   switch (objSym.getVisibility()) {
1940   case GlobalValue::HiddenVisibility:
1941     isPrivateExtern = true;
1942     break;
1943   case GlobalValue::ProtectedVisibility:
1944     error(name + " has protected visibility, which is not supported by Mach-O");
1945     break;
1946   case GlobalValue::DefaultVisibility:
1947     break;
1948   }
1949   isPrivateExtern = isPrivateExtern || objSym.canBeOmittedFromSymbolTable();
1950 
1951   if (objSym.isCommon())
1952     return symtab->addCommon(name, &file, objSym.getCommonSize(),
1953                              objSym.getCommonAlignment(), isPrivateExtern);
1954 
1955   return symtab->addDefined(name, &file, /*isec=*/nullptr, /*value=*/0,
1956                             /*size=*/0, objSym.isWeak(), isPrivateExtern,
1957                             /*isThumb=*/false,
1958                             /*isReferencedDynamically=*/false,
1959                             /*noDeadStrip=*/false,
1960                             /*isWeakDefCanBeHidden=*/false);
1961 }
1962 
1963 BitcodeFile::BitcodeFile(MemoryBufferRef mb, StringRef archiveName,
1964                          uint64_t offsetInArchive, bool lazy)
1965     : InputFile(BitcodeKind, mb, lazy) {
1966   this->archiveName = std::string(archiveName);
1967   std::string path = mb.getBufferIdentifier().str();
1968   // ThinLTO assumes that all MemoryBufferRefs given to it have a unique
1969   // name. If two members with the same name are provided, this causes a
1970   // collision and ThinLTO can't proceed.
1971   // So, we append the archive name to disambiguate two members with the same
1972   // name from multiple different archives, and offset within the archive to
1973   // disambiguate two members of the same name from a single archive.
1974   MemoryBufferRef mbref(mb.getBuffer(),
1975                         saver().save(archiveName.empty()
1976                                          ? path
1977                                          : archiveName +
1978                                                sys::path::filename(path) +
1979                                                utostr(offsetInArchive)));
1980 
1981   obj = check(lto::InputFile::create(mbref));
1982   if (lazy)
1983     parseLazy();
1984   else
1985     parse();
1986 }
1987 
1988 void BitcodeFile::parse() {
1989   // Convert LTO Symbols to LLD Symbols in order to perform resolution. The
1990   // "winning" symbol will then be marked as Prevailing at LTO compilation
1991   // time.
1992   symbols.clear();
1993   for (const lto::InputFile::Symbol &objSym : obj->symbols())
1994     symbols.push_back(createBitcodeSymbol(objSym, *this));
1995 }
1996 
1997 void BitcodeFile::parseLazy() {
1998   symbols.resize(obj->symbols().size());
1999   for (auto it : llvm::enumerate(obj->symbols())) {
2000     const lto::InputFile::Symbol &objSym = it.value();
2001     if (!objSym.isUndefined()) {
2002       symbols[it.index()] =
2003           symtab->addLazyObject(saver().save(objSym.getName()), *this);
2004       if (!lazy)
2005         break;
2006     }
2007   }
2008 }
2009 
2010 void macho::extract(InputFile &file, StringRef reason) {
2011   assert(file.lazy);
2012   file.lazy = false;
2013   printArchiveMemberLoad(reason, &file);
2014   if (auto *bitcode = dyn_cast<BitcodeFile>(&file)) {
2015     bitcode->parse();
2016   } else {
2017     auto &f = cast<ObjFile>(file);
2018     if (target->wordSize == 8)
2019       f.parse<LP64>();
2020     else
2021       f.parse<ILP32>();
2022   }
2023 }
2024 
2025 template void ObjFile::parse<LP64>();
2026