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