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