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   auto *ctx = make<DWARFContext>(
1002       std::move(dObj), "",
1003       [&](Error err) {
1004         warn(toString(this) + ": " + toString(std::move(err)));
1005       },
1006       [&](Error warning) {
1007         warn(toString(this) + ": " + toString(std::move(warning)));
1008       });
1009 
1010   // TODO: Since object files can contain a lot of DWARF info, we should verify
1011   // that we are parsing just the info we need
1012   const DWARFContext::compile_unit_range &units = ctx->compile_units();
1013   // FIXME: There can be more than one compile unit per object file. See
1014   // PR48637.
1015   auto it = units.begin();
1016   compileUnit = it->get();
1017 }
1018 
1019 ArrayRef<data_in_code_entry> ObjFile::getDataInCode() const {
1020   const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
1021   const load_command *cmd = findCommand(buf, LC_DATA_IN_CODE);
1022   if (!cmd)
1023     return {};
1024   const auto *c = reinterpret_cast<const linkedit_data_command *>(cmd);
1025   return {reinterpret_cast<const data_in_code_entry *>(buf + c->dataoff),
1026           c->datasize / sizeof(data_in_code_entry)};
1027 }
1028 
1029 // Create pointers from symbols to their associated compact unwind entries.
1030 void ObjFile::registerCompactUnwind(Section &compactUnwindSection) {
1031   for (const Subsection &subsection : compactUnwindSection.subsections) {
1032     ConcatInputSection *isec = cast<ConcatInputSection>(subsection.isec);
1033     // Hack!! Since each CUE contains a different function address, if ICF
1034     // operated naively and compared the entire contents of each CUE, entries
1035     // with identical unwind info but belonging to different functions would
1036     // never be considered equivalent. To work around this problem, we slice
1037     // away the function address here. (Note that we do not adjust the offsets
1038     // of the corresponding relocations.) We rely on `relocateCompactUnwind()`
1039     // to correctly handle these truncated input sections.
1040     isec->data = isec->data.slice(target->wordSize);
1041     uint32_t encoding = read32le(isec->data.data() + sizeof(uint32_t));
1042     // llvm-mc omits CU entries for functions that need DWARF encoding, but
1043     // `ld -r` doesn't. We can ignore them because we will re-synthesize these
1044     // CU entries from the DWARF info during the output phase.
1045     if ((encoding & target->modeDwarfEncoding) == target->modeDwarfEncoding)
1046       continue;
1047 
1048     ConcatInputSection *referentIsec;
1049     for (auto it = isec->relocs.begin(); it != isec->relocs.end();) {
1050       Reloc &r = *it;
1051       // CUE::functionAddress is at offset 0. Skip personality & LSDA relocs.
1052       if (r.offset != 0) {
1053         ++it;
1054         continue;
1055       }
1056       uint64_t add = r.addend;
1057       if (auto *sym = cast_or_null<Defined>(r.referent.dyn_cast<Symbol *>())) {
1058         // Check whether the symbol defined in this file is the prevailing one.
1059         // Skip if it is e.g. a weak def that didn't prevail.
1060         if (sym->getFile() != this) {
1061           ++it;
1062           continue;
1063         }
1064         add += sym->value;
1065         referentIsec = cast<ConcatInputSection>(sym->isec);
1066       } else {
1067         referentIsec =
1068             cast<ConcatInputSection>(r.referent.dyn_cast<InputSection *>());
1069       }
1070       // Unwind info lives in __DATA, and finalization of __TEXT will occur
1071       // before finalization of __DATA. Moreover, the finalization of unwind
1072       // info depends on the exact addresses that it references. So it is safe
1073       // for compact unwind to reference addresses in __TEXT, but not addresses
1074       // in any other segment.
1075       if (referentIsec->getSegName() != segment_names::text)
1076         error(isec->getLocation(r.offset) + " references section " +
1077               referentIsec->getName() + " which is not in segment __TEXT");
1078       // The functionAddress relocations are typically section relocations.
1079       // However, unwind info operates on a per-symbol basis, so we search for
1080       // the function symbol here.
1081       Defined *d = findSymbolAtOffset(referentIsec, add);
1082       if (!d) {
1083         ++it;
1084         continue;
1085       }
1086       d->unwindEntry = isec;
1087       // Since we've sliced away the functionAddress, we should remove the
1088       // corresponding relocation too. Given that clang emits relocations in
1089       // reverse order of address, this relocation should be at the end of the
1090       // vector for most of our input object files, so this is typically an O(1)
1091       // operation.
1092       it = isec->relocs.erase(it);
1093     }
1094   }
1095 }
1096 
1097 struct CIE {
1098   macho::Symbol *personalitySymbol = nullptr;
1099   bool fdesHaveLsda = false;
1100   bool fdesHaveAug = false;
1101 };
1102 
1103 static CIE parseCIE(const InputSection *isec, const EhReader &reader,
1104                     size_t off) {
1105   // Handling the full generality of possible DWARF encodings would be a major
1106   // pain. We instead take advantage of our knowledge of how llvm-mc encodes
1107   // DWARF and handle just that.
1108   constexpr uint8_t expectedPersonalityEnc =
1109       dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_sdata4;
1110   constexpr uint8_t expectedPointerEnc =
1111       dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_absptr;
1112 
1113   CIE cie;
1114   uint8_t version = reader.readByte(&off);
1115   if (version != 1 && version != 3)
1116     fatal("Expected CIE version of 1 or 3, got " + Twine(version));
1117   StringRef aug = reader.readString(&off);
1118   reader.skipLeb128(&off); // skip code alignment
1119   reader.skipLeb128(&off); // skip data alignment
1120   reader.skipLeb128(&off); // skip return address register
1121   reader.skipLeb128(&off); // skip aug data length
1122   uint64_t personalityAddrOff = 0;
1123   for (char c : aug) {
1124     switch (c) {
1125     case 'z':
1126       cie.fdesHaveAug = true;
1127       break;
1128     case 'P': {
1129       uint8_t personalityEnc = reader.readByte(&off);
1130       if (personalityEnc != expectedPersonalityEnc)
1131         reader.failOn(off, "unexpected personality encoding 0x" +
1132                                Twine::utohexstr(personalityEnc));
1133       personalityAddrOff = off;
1134       off += 4;
1135       break;
1136     }
1137     case 'L': {
1138       cie.fdesHaveLsda = true;
1139       uint8_t lsdaEnc = reader.readByte(&off);
1140       if (lsdaEnc != expectedPointerEnc)
1141         reader.failOn(off, "unexpected LSDA encoding 0x" +
1142                                Twine::utohexstr(lsdaEnc));
1143       break;
1144     }
1145     case 'R': {
1146       uint8_t pointerEnc = reader.readByte(&off);
1147       if (pointerEnc != expectedPointerEnc)
1148         reader.failOn(off, "unexpected pointer encoding 0x" +
1149                                Twine::utohexstr(pointerEnc));
1150       break;
1151     }
1152     default:
1153       break;
1154     }
1155   }
1156   if (personalityAddrOff != 0) {
1157     auto personalityRelocIt =
1158         llvm::find_if(isec->relocs, [=](const macho::Reloc &r) {
1159           return r.offset == personalityAddrOff;
1160         });
1161     if (personalityRelocIt == isec->relocs.end())
1162       reader.failOn(off, "Failed to locate relocation for personality symbol");
1163     cie.personalitySymbol = personalityRelocIt->referent.get<macho::Symbol *>();
1164   }
1165   return cie;
1166 }
1167 
1168 // EH frame target addresses may be encoded as pcrel offsets. However, instead
1169 // of using an actual pcrel reloc, ld64 emits subtractor relocations instead.
1170 // This function recovers the target address from the subtractors, essentially
1171 // performing the inverse operation of EhRelocator.
1172 //
1173 // Concretely, we expect our relocations to write the value of `PC -
1174 // target_addr` to `PC`. `PC` itself is denoted by a minuend relocation that
1175 // points to a symbol plus an addend.
1176 //
1177 // It is important that the minuend relocation point to a symbol within the
1178 // same section as the fixup value, since sections may get moved around.
1179 //
1180 // For example, for arm64, llvm-mc emits relocations for the target function
1181 // address like so:
1182 //
1183 //   ltmp:
1184 //     <CIE start>
1185 //     ...
1186 //     <CIE end>
1187 //     ... multiple FDEs ...
1188 //     <FDE start>
1189 //     <target function address - (ltmp + pcrel offset)>
1190 //     ...
1191 //
1192 // If any of the FDEs in `multiple FDEs` get dead-stripped, then `FDE start`
1193 // will move to an earlier address, and `ltmp + pcrel offset` will no longer
1194 // reflect an accurate pcrel value. To avoid this problem, we "canonicalize"
1195 // our relocation by adding an `EH_Frame` symbol at `FDE start`, and updating
1196 // the reloc to be `target function address - (EH_Frame + new pcrel offset)`.
1197 //
1198 // If `Invert` is set, then we instead expect `target_addr - PC` to be written
1199 // to `PC`.
1200 template <bool Invert = false>
1201 Defined *
1202 targetSymFromCanonicalSubtractor(const InputSection *isec,
1203                                  std::vector<macho::Reloc>::iterator relocIt) {
1204   macho::Reloc &subtrahend = *relocIt;
1205   macho::Reloc &minuend = *std::next(relocIt);
1206   assert(target->hasAttr(subtrahend.type, RelocAttrBits::SUBTRAHEND));
1207   assert(target->hasAttr(minuend.type, RelocAttrBits::UNSIGNED));
1208   // Note: pcSym may *not* be exactly at the PC; there's usually a non-zero
1209   // addend.
1210   auto *pcSym = cast<Defined>(subtrahend.referent.get<macho::Symbol *>());
1211   Defined *target =
1212       cast_or_null<Defined>(minuend.referent.dyn_cast<macho::Symbol *>());
1213   if (!pcSym) {
1214     auto *targetIsec =
1215         cast<ConcatInputSection>(minuend.referent.get<InputSection *>());
1216     target = findSymbolAtOffset(targetIsec, minuend.addend);
1217   }
1218   if (Invert)
1219     std::swap(pcSym, target);
1220   if (pcSym->isec == isec) {
1221     if (pcSym->value - (Invert ? -1 : 1) * minuend.addend != subtrahend.offset)
1222       fatal("invalid FDE relocation in __eh_frame");
1223   } else {
1224     // Ensure the pcReloc points to a symbol within the current EH frame.
1225     // HACK: we should really verify that the original relocation's semantics
1226     // are preserved. In particular, we should have
1227     // `oldSym->value + oldOffset == newSym + newOffset`. However, we don't
1228     // have an easy way to access the offsets from this point in the code; some
1229     // refactoring is needed for that.
1230     macho::Reloc &pcReloc = Invert ? minuend : subtrahend;
1231     pcReloc.referent = isec->symbols[0];
1232     assert(isec->symbols[0]->value == 0);
1233     minuend.addend = pcReloc.offset * (Invert ? 1LL : -1LL);
1234   }
1235   return target;
1236 }
1237 
1238 Defined *findSymbolAtAddress(const std::vector<Section *> &sections,
1239                              uint64_t addr) {
1240   Section *sec = findContainingSection(sections, &addr);
1241   auto *isec = cast<ConcatInputSection>(findContainingSubsection(*sec, &addr));
1242   return findSymbolAtOffset(isec, addr);
1243 }
1244 
1245 // For symbols that don't have compact unwind info, associate them with the more
1246 // general-purpose (and verbose) DWARF unwind info found in __eh_frame.
1247 //
1248 // This requires us to parse the contents of __eh_frame. See EhFrame.h for a
1249 // description of its format.
1250 //
1251 // While parsing, we also look for what MC calls "abs-ified" relocations -- they
1252 // are relocations which are implicitly encoded as offsets in the section data.
1253 // We convert them into explicit Reloc structs so that the EH frames can be
1254 // handled just like a regular ConcatInputSection later in our output phase.
1255 //
1256 // We also need to handle the case where our input object file has explicit
1257 // relocations. This is the case when e.g. it's the output of `ld -r`. We only
1258 // look for the "abs-ified" relocation if an explicit relocation is absent.
1259 void ObjFile::registerEhFrames(Section &ehFrameSection) {
1260   DenseMap<const InputSection *, CIE> cieMap;
1261   for (const Subsection &subsec : ehFrameSection.subsections) {
1262     auto *isec = cast<ConcatInputSection>(subsec.isec);
1263     uint64_t isecOff = subsec.offset;
1264 
1265     // Subtractor relocs require the subtrahend to be a symbol reloc. Ensure
1266     // that all EH frames have an associated symbol so that we can generate
1267     // subtractor relocs that reference them.
1268     if (isec->symbols.size() == 0)
1269       isec->symbols.push_back(make<Defined>(
1270           "EH_Frame", isec->getFile(), isec, /*value=*/0, /*size=*/0,
1271           /*isWeakDef=*/false, /*isExternal=*/false, /*isPrivateExtern=*/false,
1272           /*includeInSymtab=*/false, /*isThumb=*/false,
1273           /*isReferencedDynamically=*/false, /*noDeadStrip=*/false));
1274     else if (isec->symbols[0]->value != 0)
1275       fatal("found symbol at unexpected offset in __eh_frame");
1276 
1277     EhReader reader(this, isec->data, subsec.offset, target->wordSize);
1278     size_t dataOff = 0; // Offset from the start of the EH frame.
1279     reader.skipValidLength(&dataOff); // readLength() already validated this.
1280     // cieOffOff is the offset from the start of the EH frame to the cieOff
1281     // value, which is itself an offset from the current PC to a CIE.
1282     const size_t cieOffOff = dataOff;
1283 
1284     EhRelocator ehRelocator(isec);
1285     auto cieOffRelocIt = llvm::find_if(
1286         isec->relocs, [=](const Reloc &r) { return r.offset == cieOffOff; });
1287     InputSection *cieIsec = nullptr;
1288     if (cieOffRelocIt != isec->relocs.end()) {
1289       // We already have an explicit relocation for the CIE offset.
1290       cieIsec =
1291           targetSymFromCanonicalSubtractor</*Invert=*/true>(isec, cieOffRelocIt)
1292               ->isec;
1293       dataOff += sizeof(uint32_t);
1294     } else {
1295       // If we haven't found a relocation, then the CIE offset is most likely
1296       // embedded in the section data (AKA an "abs-ified" reloc.). Parse that
1297       // and generate a Reloc struct.
1298       uint32_t cieMinuend = reader.readU32(&dataOff);
1299       if (cieMinuend == 0)
1300         cieIsec = isec;
1301       else {
1302         uint32_t cieOff = isecOff + dataOff - cieMinuend;
1303         cieIsec = findContainingSubsection(ehFrameSection, &cieOff);
1304         if (cieIsec == nullptr)
1305           fatal("failed to find CIE");
1306       }
1307       if (cieIsec != isec)
1308         ehRelocator.makeNegativePcRel(cieOffOff, cieIsec->symbols[0],
1309                                       /*length=*/2);
1310     }
1311     if (cieIsec == isec) {
1312       cieMap[cieIsec] = parseCIE(isec, reader, dataOff);
1313       continue;
1314     }
1315 
1316     // Offset of the function address within the EH frame.
1317     const size_t funcAddrOff = dataOff;
1318     uint64_t funcAddr = reader.readPointer(&dataOff) + ehFrameSection.addr +
1319                         isecOff + funcAddrOff;
1320     uint32_t funcLength = reader.readPointer(&dataOff);
1321     size_t lsdaAddrOff = 0; // Offset of the LSDA address within the EH frame.
1322     assert(cieMap.count(cieIsec));
1323     const CIE &cie = cieMap[cieIsec];
1324     Optional<uint64_t> lsdaAddrOpt;
1325     if (cie.fdesHaveAug) {
1326       reader.skipLeb128(&dataOff);
1327       lsdaAddrOff = dataOff;
1328       if (cie.fdesHaveLsda) {
1329         uint64_t lsdaOff = reader.readPointer(&dataOff);
1330         if (lsdaOff != 0) // FIXME possible to test this?
1331           lsdaAddrOpt = ehFrameSection.addr + isecOff + lsdaAddrOff + lsdaOff;
1332       }
1333     }
1334 
1335     auto funcAddrRelocIt = isec->relocs.end();
1336     auto lsdaAddrRelocIt = isec->relocs.end();
1337     for (auto it = isec->relocs.begin(); it != isec->relocs.end(); ++it) {
1338       if (it->offset == funcAddrOff)
1339         funcAddrRelocIt = it++; // Found subtrahend; skip over minuend reloc
1340       else if (lsdaAddrOpt && it->offset == lsdaAddrOff)
1341         lsdaAddrRelocIt = it++; // Found subtrahend; skip over minuend reloc
1342     }
1343 
1344     Defined *funcSym;
1345     if (funcAddrRelocIt != isec->relocs.end()) {
1346       funcSym = targetSymFromCanonicalSubtractor(isec, funcAddrRelocIt);
1347     } else {
1348       funcSym = findSymbolAtAddress(sections, funcAddr);
1349       ehRelocator.makePcRel(funcAddrOff, funcSym, target->p2WordSize);
1350     }
1351     // The symbol has been coalesced, or already has a compact unwind entry.
1352     if (!funcSym || funcSym->getFile() != this || funcSym->unwindEntry) {
1353       // We must prune unused FDEs for correctness, so we cannot rely on
1354       // -dead_strip being enabled.
1355       isec->live = false;
1356       continue;
1357     }
1358 
1359     InputSection *lsdaIsec = nullptr;
1360     if (lsdaAddrRelocIt != isec->relocs.end()) {
1361       lsdaIsec = targetSymFromCanonicalSubtractor(isec, lsdaAddrRelocIt)->isec;
1362     } else if (lsdaAddrOpt) {
1363       uint64_t lsdaAddr = *lsdaAddrOpt;
1364       Section *sec = findContainingSection(sections, &lsdaAddr);
1365       lsdaIsec =
1366           cast<ConcatInputSection>(findContainingSubsection(*sec, &lsdaAddr));
1367       ehRelocator.makePcRel(lsdaAddrOff, lsdaIsec, target->p2WordSize);
1368     }
1369 
1370     fdes[isec] = {funcLength, cie.personalitySymbol, lsdaIsec};
1371     funcSym->unwindEntry = isec;
1372     ehRelocator.commit();
1373   }
1374 }
1375 
1376 // The path can point to either a dylib or a .tbd file.
1377 static DylibFile *loadDylib(StringRef path, DylibFile *umbrella) {
1378   Optional<MemoryBufferRef> mbref = readFile(path);
1379   if (!mbref) {
1380     error("could not read dylib file at " + path);
1381     return nullptr;
1382   }
1383   return loadDylib(*mbref, umbrella);
1384 }
1385 
1386 // TBD files are parsed into a series of TAPI documents (InterfaceFiles), with
1387 // the first document storing child pointers to the rest of them. When we are
1388 // processing a given TBD file, we store that top-level document in
1389 // currentTopLevelTapi. When processing re-exports, we search its children for
1390 // potentially matching documents in the same TBD file. Note that the children
1391 // themselves don't point to further documents, i.e. this is a two-level tree.
1392 //
1393 // Re-exports can either refer to on-disk files, or to documents within .tbd
1394 // files.
1395 static DylibFile *findDylib(StringRef path, DylibFile *umbrella,
1396                             const InterfaceFile *currentTopLevelTapi) {
1397   // Search order:
1398   // 1. Install name basename in -F / -L directories.
1399   {
1400     StringRef stem = path::stem(path);
1401     SmallString<128> frameworkName;
1402     path::append(frameworkName, path::Style::posix, stem + ".framework", stem);
1403     bool isFramework = path.endswith(frameworkName);
1404     if (isFramework) {
1405       for (StringRef dir : config->frameworkSearchPaths) {
1406         SmallString<128> candidate = dir;
1407         path::append(candidate, frameworkName);
1408         if (Optional<StringRef> dylibPath = resolveDylibPath(candidate.str()))
1409           return loadDylib(*dylibPath, umbrella);
1410       }
1411     } else if (Optional<StringRef> dylibPath = findPathCombination(
1412                    stem, config->librarySearchPaths, {".tbd", ".dylib"}))
1413       return loadDylib(*dylibPath, umbrella);
1414   }
1415 
1416   // 2. As absolute path.
1417   if (path::is_absolute(path, path::Style::posix))
1418     for (StringRef root : config->systemLibraryRoots)
1419       if (Optional<StringRef> dylibPath = resolveDylibPath((root + path).str()))
1420         return loadDylib(*dylibPath, umbrella);
1421 
1422   // 3. As relative path.
1423 
1424   // TODO: Handle -dylib_file
1425 
1426   // Replace @executable_path, @loader_path, @rpath prefixes in install name.
1427   SmallString<128> newPath;
1428   if (config->outputType == MH_EXECUTE &&
1429       path.consume_front("@executable_path/")) {
1430     // ld64 allows overriding this with the undocumented flag -executable_path.
1431     // lld doesn't currently implement that flag.
1432     // FIXME: Consider using finalOutput instead of outputFile.
1433     path::append(newPath, path::parent_path(config->outputFile), path);
1434     path = newPath;
1435   } else if (path.consume_front("@loader_path/")) {
1436     fs::real_path(umbrella->getName(), newPath);
1437     path::remove_filename(newPath);
1438     path::append(newPath, path);
1439     path = newPath;
1440   } else if (path.startswith("@rpath/")) {
1441     for (StringRef rpath : umbrella->rpaths) {
1442       newPath.clear();
1443       if (rpath.consume_front("@loader_path/")) {
1444         fs::real_path(umbrella->getName(), newPath);
1445         path::remove_filename(newPath);
1446       }
1447       path::append(newPath, rpath, path.drop_front(strlen("@rpath/")));
1448       if (Optional<StringRef> dylibPath = resolveDylibPath(newPath.str()))
1449         return loadDylib(*dylibPath, umbrella);
1450     }
1451   }
1452 
1453   // FIXME: Should this be further up?
1454   if (currentTopLevelTapi) {
1455     for (InterfaceFile &child :
1456          make_pointee_range(currentTopLevelTapi->documents())) {
1457       assert(child.documents().empty());
1458       if (path == child.getInstallName()) {
1459         auto file = make<DylibFile>(child, umbrella, /*isBundleLoader=*/false,
1460                                     /*explicitlyLinked=*/false);
1461         file->parseReexports(child);
1462         return file;
1463       }
1464     }
1465   }
1466 
1467   if (Optional<StringRef> dylibPath = resolveDylibPath(path))
1468     return loadDylib(*dylibPath, umbrella);
1469 
1470   return nullptr;
1471 }
1472 
1473 // If a re-exported dylib is public (lives in /usr/lib or
1474 // /System/Library/Frameworks), then it is considered implicitly linked: we
1475 // should bind to its symbols directly instead of via the re-exporting umbrella
1476 // library.
1477 static bool isImplicitlyLinked(StringRef path) {
1478   if (!config->implicitDylibs)
1479     return false;
1480 
1481   if (path::parent_path(path) == "/usr/lib")
1482     return true;
1483 
1484   // Match /System/Library/Frameworks/$FOO.framework/**/$FOO
1485   if (path.consume_front("/System/Library/Frameworks/")) {
1486     StringRef frameworkName = path.take_until([](char c) { return c == '.'; });
1487     return path::filename(path) == frameworkName;
1488   }
1489 
1490   return false;
1491 }
1492 
1493 static void loadReexport(StringRef path, DylibFile *umbrella,
1494                          const InterfaceFile *currentTopLevelTapi) {
1495   DylibFile *reexport = findDylib(path, umbrella, currentTopLevelTapi);
1496   if (!reexport)
1497     error("unable to locate re-export with install name " + path);
1498 }
1499 
1500 DylibFile::DylibFile(MemoryBufferRef mb, DylibFile *umbrella,
1501                      bool isBundleLoader, bool explicitlyLinked)
1502     : InputFile(DylibKind, mb), refState(RefState::Unreferenced),
1503       explicitlyLinked(explicitlyLinked), isBundleLoader(isBundleLoader) {
1504   assert(!isBundleLoader || !umbrella);
1505   if (umbrella == nullptr)
1506     umbrella = this;
1507   this->umbrella = umbrella;
1508 
1509   auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());
1510   auto *hdr = reinterpret_cast<const mach_header *>(mb.getBufferStart());
1511 
1512   // Initialize installName.
1513   if (const load_command *cmd = findCommand(hdr, LC_ID_DYLIB)) {
1514     auto *c = reinterpret_cast<const dylib_command *>(cmd);
1515     currentVersion = read32le(&c->dylib.current_version);
1516     compatibilityVersion = read32le(&c->dylib.compatibility_version);
1517     installName =
1518         reinterpret_cast<const char *>(cmd) + read32le(&c->dylib.name);
1519   } else if (!isBundleLoader) {
1520     // macho_executable and macho_bundle don't have LC_ID_DYLIB,
1521     // so it's OK.
1522     error("dylib " + toString(this) + " missing LC_ID_DYLIB load command");
1523     return;
1524   }
1525 
1526   if (config->printEachFile)
1527     message(toString(this));
1528   inputFiles.insert(this);
1529 
1530   deadStrippable = hdr->flags & MH_DEAD_STRIPPABLE_DYLIB;
1531 
1532   if (!checkCompatibility(this))
1533     return;
1534 
1535   checkAppExtensionSafety(hdr->flags & MH_APP_EXTENSION_SAFE);
1536 
1537   for (auto *cmd : findCommands<rpath_command>(hdr, LC_RPATH)) {
1538     StringRef rpath{reinterpret_cast<const char *>(cmd) + cmd->path};
1539     rpaths.push_back(rpath);
1540   }
1541 
1542   // Initialize symbols.
1543   exportingFile = isImplicitlyLinked(installName) ? this : this->umbrella;
1544   if (const load_command *cmd = findCommand(hdr, LC_DYLD_INFO_ONLY)) {
1545     auto *c = reinterpret_cast<const dyld_info_command *>(cmd);
1546     struct TrieEntry {
1547       StringRef name;
1548       uint64_t flags;
1549     };
1550 
1551     std::vector<TrieEntry> entries;
1552     // Find all the $ld$* symbols to process first.
1553     parseTrie(buf + c->export_off, c->export_size,
1554               [&](const Twine &name, uint64_t flags) {
1555                 StringRef savedName = saver().save(name);
1556                 if (handleLDSymbol(savedName))
1557                   return;
1558                 entries.push_back({savedName, flags});
1559               });
1560 
1561     // Process the "normal" symbols.
1562     for (TrieEntry &entry : entries) {
1563       if (exportingFile->hiddenSymbols.contains(
1564               CachedHashStringRef(entry.name)))
1565         continue;
1566 
1567       bool isWeakDef = entry.flags & EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION;
1568       bool isTlv = entry.flags & EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL;
1569 
1570       symbols.push_back(
1571           symtab->addDylib(entry.name, exportingFile, isWeakDef, isTlv));
1572     }
1573 
1574   } else {
1575     error("LC_DYLD_INFO_ONLY not found in " + toString(this));
1576     return;
1577   }
1578 }
1579 
1580 void DylibFile::parseLoadCommands(MemoryBufferRef mb) {
1581   auto *hdr = reinterpret_cast<const mach_header *>(mb.getBufferStart());
1582   const uint8_t *p = reinterpret_cast<const uint8_t *>(mb.getBufferStart()) +
1583                      target->headerSize;
1584   for (uint32_t i = 0, n = hdr->ncmds; i < n; ++i) {
1585     auto *cmd = reinterpret_cast<const load_command *>(p);
1586     p += cmd->cmdsize;
1587 
1588     if (!(hdr->flags & MH_NO_REEXPORTED_DYLIBS) &&
1589         cmd->cmd == LC_REEXPORT_DYLIB) {
1590       const auto *c = reinterpret_cast<const dylib_command *>(cmd);
1591       StringRef reexportPath =
1592           reinterpret_cast<const char *>(c) + read32le(&c->dylib.name);
1593       loadReexport(reexportPath, exportingFile, nullptr);
1594     }
1595 
1596     // FIXME: What about LC_LOAD_UPWARD_DYLIB, LC_LAZY_LOAD_DYLIB,
1597     // LC_LOAD_WEAK_DYLIB, LC_REEXPORT_DYLIB (..are reexports from dylibs with
1598     // MH_NO_REEXPORTED_DYLIBS loaded for -flat_namespace)?
1599     if (config->namespaceKind == NamespaceKind::flat &&
1600         cmd->cmd == LC_LOAD_DYLIB) {
1601       const auto *c = reinterpret_cast<const dylib_command *>(cmd);
1602       StringRef dylibPath =
1603           reinterpret_cast<const char *>(c) + read32le(&c->dylib.name);
1604       DylibFile *dylib = findDylib(dylibPath, umbrella, nullptr);
1605       if (!dylib)
1606         error(Twine("unable to locate library '") + dylibPath +
1607               "' loaded from '" + toString(this) + "' for -flat_namespace");
1608     }
1609   }
1610 }
1611 
1612 // Some versions of Xcode ship with .tbd files that don't have the right
1613 // platform settings.
1614 constexpr std::array<StringRef, 3> skipPlatformChecks{
1615     "/usr/lib/system/libsystem_kernel.dylib",
1616     "/usr/lib/system/libsystem_platform.dylib",
1617     "/usr/lib/system/libsystem_pthread.dylib"};
1618 
1619 static bool skipPlatformCheckForCatalyst(const InterfaceFile &interface,
1620                                          bool explicitlyLinked) {
1621   // Catalyst outputs can link against implicitly linked macOS-only libraries.
1622   if (config->platform() != PLATFORM_MACCATALYST || explicitlyLinked)
1623     return false;
1624   return is_contained(interface.targets(),
1625                       MachO::Target(config->arch(), PLATFORM_MACOS));
1626 }
1627 
1628 DylibFile::DylibFile(const InterfaceFile &interface, DylibFile *umbrella,
1629                      bool isBundleLoader, bool explicitlyLinked)
1630     : InputFile(DylibKind, interface), refState(RefState::Unreferenced),
1631       explicitlyLinked(explicitlyLinked), isBundleLoader(isBundleLoader) {
1632   // FIXME: Add test for the missing TBD code path.
1633 
1634   if (umbrella == nullptr)
1635     umbrella = this;
1636   this->umbrella = umbrella;
1637 
1638   installName = saver().save(interface.getInstallName());
1639   compatibilityVersion = interface.getCompatibilityVersion().rawValue();
1640   currentVersion = interface.getCurrentVersion().rawValue();
1641 
1642   if (config->printEachFile)
1643     message(toString(this));
1644   inputFiles.insert(this);
1645 
1646   if (!is_contained(skipPlatformChecks, installName) &&
1647       !is_contained(interface.targets(), config->platformInfo.target) &&
1648       !skipPlatformCheckForCatalyst(interface, explicitlyLinked)) {
1649     error(toString(this) + " is incompatible with " +
1650           std::string(config->platformInfo.target));
1651     return;
1652   }
1653 
1654   checkAppExtensionSafety(interface.isApplicationExtensionSafe());
1655 
1656   exportingFile = isImplicitlyLinked(installName) ? this : umbrella;
1657   auto addSymbol = [&](const Twine &name) -> void {
1658     StringRef savedName = saver().save(name);
1659     if (exportingFile->hiddenSymbols.contains(CachedHashStringRef(savedName)))
1660       return;
1661 
1662     symbols.push_back(symtab->addDylib(savedName, exportingFile,
1663                                        /*isWeakDef=*/false,
1664                                        /*isTlv=*/false));
1665   };
1666 
1667   std::vector<const llvm::MachO::Symbol *> normalSymbols;
1668   normalSymbols.reserve(interface.symbolsCount());
1669   for (const auto *symbol : interface.symbols()) {
1670     if (!symbol->getArchitectures().has(config->arch()))
1671       continue;
1672     if (handleLDSymbol(symbol->getName()))
1673       continue;
1674 
1675     switch (symbol->getKind()) {
1676     case SymbolKind::GlobalSymbol:               // Fallthrough
1677     case SymbolKind::ObjectiveCClass:            // Fallthrough
1678     case SymbolKind::ObjectiveCClassEHType:      // Fallthrough
1679     case SymbolKind::ObjectiveCInstanceVariable: // Fallthrough
1680       normalSymbols.push_back(symbol);
1681     }
1682   }
1683 
1684   // TODO(compnerd) filter out symbols based on the target platform
1685   // TODO: handle weak defs, thread locals
1686   for (const auto *symbol : normalSymbols) {
1687     switch (symbol->getKind()) {
1688     case SymbolKind::GlobalSymbol:
1689       addSymbol(symbol->getName());
1690       break;
1691     case SymbolKind::ObjectiveCClass:
1692       // XXX ld64 only creates these symbols when -ObjC is passed in. We may
1693       // want to emulate that.
1694       addSymbol(objc::klass + symbol->getName());
1695       addSymbol(objc::metaclass + symbol->getName());
1696       break;
1697     case SymbolKind::ObjectiveCClassEHType:
1698       addSymbol(objc::ehtype + symbol->getName());
1699       break;
1700     case SymbolKind::ObjectiveCInstanceVariable:
1701       addSymbol(objc::ivar + symbol->getName());
1702       break;
1703     }
1704   }
1705 }
1706 
1707 void DylibFile::parseReexports(const InterfaceFile &interface) {
1708   const InterfaceFile *topLevel =
1709       interface.getParent() == nullptr ? &interface : interface.getParent();
1710   for (const InterfaceFileRef &intfRef : interface.reexportedLibraries()) {
1711     InterfaceFile::const_target_range targets = intfRef.targets();
1712     if (is_contained(skipPlatformChecks, intfRef.getInstallName()) ||
1713         is_contained(targets, config->platformInfo.target))
1714       loadReexport(intfRef.getInstallName(), exportingFile, topLevel);
1715   }
1716 }
1717 
1718 // $ld$ symbols modify the properties/behavior of the library (e.g. its install
1719 // name, compatibility version or hide/add symbols) for specific target
1720 // versions.
1721 bool DylibFile::handleLDSymbol(StringRef originalName) {
1722   if (!originalName.startswith("$ld$"))
1723     return false;
1724 
1725   StringRef action;
1726   StringRef name;
1727   std::tie(action, name) = originalName.drop_front(strlen("$ld$")).split('$');
1728   if (action == "previous")
1729     handleLDPreviousSymbol(name, originalName);
1730   else if (action == "install_name")
1731     handleLDInstallNameSymbol(name, originalName);
1732   else if (action == "hide")
1733     handleLDHideSymbol(name, originalName);
1734   return true;
1735 }
1736 
1737 void DylibFile::handleLDPreviousSymbol(StringRef name, StringRef originalName) {
1738   // originalName: $ld$ previous $ <installname> $ <compatversion> $
1739   // <platformstr> $ <startversion> $ <endversion> $ <symbol-name> $
1740   StringRef installName;
1741   StringRef compatVersion;
1742   StringRef platformStr;
1743   StringRef startVersion;
1744   StringRef endVersion;
1745   StringRef symbolName;
1746   StringRef rest;
1747 
1748   std::tie(installName, name) = name.split('$');
1749   std::tie(compatVersion, name) = name.split('$');
1750   std::tie(platformStr, name) = name.split('$');
1751   std::tie(startVersion, name) = name.split('$');
1752   std::tie(endVersion, name) = name.split('$');
1753   std::tie(symbolName, rest) = name.split('$');
1754   // TODO: ld64 contains some logic for non-empty symbolName as well.
1755   if (!symbolName.empty())
1756     return;
1757   unsigned platform;
1758   if (platformStr.getAsInteger(10, platform) ||
1759       platform != static_cast<unsigned>(config->platform()))
1760     return;
1761 
1762   VersionTuple start;
1763   if (start.tryParse(startVersion)) {
1764     warn("failed to parse start version, symbol '" + originalName +
1765          "' ignored");
1766     return;
1767   }
1768   VersionTuple end;
1769   if (end.tryParse(endVersion)) {
1770     warn("failed to parse end version, symbol '" + originalName + "' ignored");
1771     return;
1772   }
1773   if (config->platformInfo.minimum < start ||
1774       config->platformInfo.minimum >= end)
1775     return;
1776 
1777   this->installName = saver().save(installName);
1778 
1779   if (!compatVersion.empty()) {
1780     VersionTuple cVersion;
1781     if (cVersion.tryParse(compatVersion)) {
1782       warn("failed to parse compatibility version, symbol '" + originalName +
1783            "' ignored");
1784       return;
1785     }
1786     compatibilityVersion = encodeVersion(cVersion);
1787   }
1788 }
1789 
1790 void DylibFile::handleLDInstallNameSymbol(StringRef name,
1791                                           StringRef originalName) {
1792   // originalName: $ld$ install_name $ os<version> $ install_name
1793   StringRef condition, installName;
1794   std::tie(condition, installName) = name.split('$');
1795   VersionTuple version;
1796   if (!condition.consume_front("os") || version.tryParse(condition))
1797     warn("failed to parse os version, symbol '" + originalName + "' ignored");
1798   else if (version == config->platformInfo.minimum)
1799     this->installName = saver().save(installName);
1800 }
1801 
1802 void DylibFile::handleLDHideSymbol(StringRef name, StringRef originalName) {
1803   StringRef symbolName;
1804   bool shouldHide = true;
1805   if (name.startswith("os")) {
1806     // If it's hidden based on versions.
1807     name = name.drop_front(2);
1808     StringRef minVersion;
1809     std::tie(minVersion, symbolName) = name.split('$');
1810     VersionTuple versionTup;
1811     if (versionTup.tryParse(minVersion)) {
1812       warn("Failed to parse hidden version, symbol `" + originalName +
1813            "` ignored.");
1814       return;
1815     }
1816     shouldHide = versionTup == config->platformInfo.minimum;
1817   } else {
1818     symbolName = name;
1819   }
1820 
1821   if (shouldHide)
1822     exportingFile->hiddenSymbols.insert(CachedHashStringRef(symbolName));
1823 }
1824 
1825 void DylibFile::checkAppExtensionSafety(bool dylibIsAppExtensionSafe) const {
1826   if (config->applicationExtension && !dylibIsAppExtensionSafe)
1827     warn("using '-application_extension' with unsafe dylib: " + toString(this));
1828 }
1829 
1830 ArchiveFile::ArchiveFile(std::unique_ptr<object::Archive> &&f)
1831     : InputFile(ArchiveKind, f->getMemoryBufferRef()), file(std::move(f)) {}
1832 
1833 void ArchiveFile::addLazySymbols() {
1834   for (const object::Archive::Symbol &sym : file->symbols())
1835     symtab->addLazyArchive(sym.getName(), this, sym);
1836 }
1837 
1838 static Expected<InputFile *> loadArchiveMember(MemoryBufferRef mb,
1839                                                uint32_t modTime,
1840                                                StringRef archiveName,
1841                                                uint64_t offsetInArchive) {
1842   if (config->zeroModTime)
1843     modTime = 0;
1844 
1845   switch (identify_magic(mb.getBuffer())) {
1846   case file_magic::macho_object:
1847     return make<ObjFile>(mb, modTime, archiveName);
1848   case file_magic::bitcode:
1849     return make<BitcodeFile>(mb, archiveName, offsetInArchive);
1850   default:
1851     return createStringError(inconvertibleErrorCode(),
1852                              mb.getBufferIdentifier() +
1853                                  " has unhandled file type");
1854   }
1855 }
1856 
1857 Error ArchiveFile::fetch(const object::Archive::Child &c, StringRef reason) {
1858   if (!seen.insert(c.getChildOffset()).second)
1859     return Error::success();
1860 
1861   Expected<MemoryBufferRef> mb = c.getMemoryBufferRef();
1862   if (!mb)
1863     return mb.takeError();
1864 
1865   // Thin archives refer to .o files, so --reproduce needs the .o files too.
1866   if (tar && c.getParent()->isThin())
1867     tar->append(relativeToRoot(CHECK(c.getFullName(), this)), mb->getBuffer());
1868 
1869   Expected<TimePoint<std::chrono::seconds>> modTime = c.getLastModified();
1870   if (!modTime)
1871     return modTime.takeError();
1872 
1873   Expected<InputFile *> file =
1874       loadArchiveMember(*mb, toTimeT(*modTime), getName(), c.getChildOffset());
1875 
1876   if (!file)
1877     return file.takeError();
1878 
1879   inputFiles.insert(*file);
1880   printArchiveMemberLoad(reason, *file);
1881   return Error::success();
1882 }
1883 
1884 void ArchiveFile::fetch(const object::Archive::Symbol &sym) {
1885   object::Archive::Child c =
1886       CHECK(sym.getMember(), toString(this) +
1887                                  ": could not get the member defining symbol " +
1888                                  toMachOString(sym));
1889 
1890   // `sym` is owned by a LazySym, which will be replace<>()d by make<ObjFile>
1891   // and become invalid after that call. Copy it to the stack so we can refer
1892   // to it later.
1893   const object::Archive::Symbol symCopy = sym;
1894 
1895   // ld64 doesn't demangle sym here even with -demangle.
1896   // Match that: intentionally don't call toMachOString().
1897   if (Error e = fetch(c, symCopy.getName()))
1898     error(toString(this) + ": could not get the member defining symbol " +
1899           toMachOString(symCopy) + ": " + toString(std::move(e)));
1900 }
1901 
1902 static macho::Symbol *createBitcodeSymbol(const lto::InputFile::Symbol &objSym,
1903                                           BitcodeFile &file) {
1904   StringRef name = saver().save(objSym.getName());
1905 
1906   if (objSym.isUndefined())
1907     return symtab->addUndefined(name, &file, /*isWeakRef=*/objSym.isWeak());
1908 
1909   // TODO: Write a test demonstrating why computing isPrivateExtern before
1910   // LTO compilation is important.
1911   bool isPrivateExtern = false;
1912   switch (objSym.getVisibility()) {
1913   case GlobalValue::HiddenVisibility:
1914     isPrivateExtern = true;
1915     break;
1916   case GlobalValue::ProtectedVisibility:
1917     error(name + " has protected visibility, which is not supported by Mach-O");
1918     break;
1919   case GlobalValue::DefaultVisibility:
1920     break;
1921   }
1922   isPrivateExtern = isPrivateExtern || objSym.canBeOmittedFromSymbolTable();
1923 
1924   if (objSym.isCommon())
1925     return symtab->addCommon(name, &file, objSym.getCommonSize(),
1926                              objSym.getCommonAlignment(), isPrivateExtern);
1927 
1928   return symtab->addDefined(name, &file, /*isec=*/nullptr, /*value=*/0,
1929                             /*size=*/0, objSym.isWeak(), isPrivateExtern,
1930                             /*isThumb=*/false,
1931                             /*isReferencedDynamically=*/false,
1932                             /*noDeadStrip=*/false,
1933                             /*isWeakDefCanBeHidden=*/false);
1934 }
1935 
1936 BitcodeFile::BitcodeFile(MemoryBufferRef mb, StringRef archiveName,
1937                          uint64_t offsetInArchive, bool lazy)
1938     : InputFile(BitcodeKind, mb, lazy) {
1939   this->archiveName = std::string(archiveName);
1940   std::string path = mb.getBufferIdentifier().str();
1941   // ThinLTO assumes that all MemoryBufferRefs given to it have a unique
1942   // name. If two members with the same name are provided, this causes a
1943   // collision and ThinLTO can't proceed.
1944   // So, we append the archive name to disambiguate two members with the same
1945   // name from multiple different archives, and offset within the archive to
1946   // disambiguate two members of the same name from a single archive.
1947   MemoryBufferRef mbref(mb.getBuffer(),
1948                         saver().save(archiveName.empty()
1949                                          ? path
1950                                          : archiveName +
1951                                                sys::path::filename(path) +
1952                                                utostr(offsetInArchive)));
1953 
1954   obj = check(lto::InputFile::create(mbref));
1955   if (lazy)
1956     parseLazy();
1957   else
1958     parse();
1959 }
1960 
1961 void BitcodeFile::parse() {
1962   // Convert LTO Symbols to LLD Symbols in order to perform resolution. The
1963   // "winning" symbol will then be marked as Prevailing at LTO compilation
1964   // time.
1965   symbols.clear();
1966   for (const lto::InputFile::Symbol &objSym : obj->symbols())
1967     symbols.push_back(createBitcodeSymbol(objSym, *this));
1968 }
1969 
1970 void BitcodeFile::parseLazy() {
1971   symbols.resize(obj->symbols().size());
1972   for (auto it : llvm::enumerate(obj->symbols())) {
1973     const lto::InputFile::Symbol &objSym = it.value();
1974     if (!objSym.isUndefined()) {
1975       symbols[it.index()] =
1976           symtab->addLazyObject(saver().save(objSym.getName()), *this);
1977       if (!lazy)
1978         break;
1979     }
1980   }
1981 }
1982 
1983 void macho::extract(InputFile &file, StringRef reason) {
1984   assert(file.lazy);
1985   file.lazy = false;
1986   printArchiveMemberLoad(reason, &file);
1987   if (auto *bitcode = dyn_cast<BitcodeFile>(&file)) {
1988     bitcode->parse();
1989   } else {
1990     auto &f = cast<ObjFile>(file);
1991     if (target->wordSize == 8)
1992       f.parse<LP64>();
1993     else
1994       f.parse<ILP32>();
1995   }
1996 }
1997 
1998 template void ObjFile::parse<LP64>();
1999