Path: blob/main/contrib/llvm-project/lld/MachO/InputFiles.cpp
34878 views
//===- InputFiles.cpp -----------------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file contains functions to parse Mach-O object files. In this comment,9// we describe the Mach-O file structure and how we parse it.10//11// Mach-O is not very different from ELF or COFF. The notion of symbols,12// sections and relocations exists in Mach-O as it does in ELF and COFF.13//14// Perhaps the notion that is new to those who know ELF/COFF is "subsections".15// In ELF/COFF, sections are an atomic unit of data copied from input files to16// output files. When we merge or garbage-collect sections, we treat each17// section as an atomic unit. In Mach-O, that's not the case. Sections can18// consist of multiple subsections, and subsections are a unit of merging and19// garbage-collecting. Therefore, Mach-O's subsections are more similar to20// ELF/COFF's sections than Mach-O's sections are.21//22// A section can have multiple symbols. A symbol that does not have the23// N_ALT_ENTRY attribute indicates a beginning of a subsection. Therefore, by24// definition, a symbol is always present at the beginning of each subsection. A25// symbol with N_ALT_ENTRY attribute does not start a new subsection and can26// point to a middle of a subsection.27//28// The notion of subsections also affects how relocations are represented in29// Mach-O. All references within a section need to be explicitly represented as30// relocations if they refer to different subsections, because we obviously need31// to fix up addresses if subsections are laid out in an output file differently32// than they were in object files. To represent that, Mach-O relocations can33// refer to an unnamed location via its address. Scattered relocations (those34// with the R_SCATTERED bit set) always refer to unnamed locations.35// Non-scattered relocations refer to an unnamed location if r_extern is not set36// and r_symbolnum is zero.37//38// Without the above differences, I think you can use your knowledge about ELF39// and COFF for Mach-O.40//41//===----------------------------------------------------------------------===//4243#include "InputFiles.h"44#include "Config.h"45#include "Driver.h"46#include "Dwarf.h"47#include "EhFrame.h"48#include "ExportTrie.h"49#include "InputSection.h"50#include "MachOStructs.h"51#include "ObjC.h"52#include "OutputSection.h"53#include "OutputSegment.h"54#include "SymbolTable.h"55#include "Symbols.h"56#include "SyntheticSections.h"57#include "Target.h"5859#include "lld/Common/CommonLinkerContext.h"60#include "lld/Common/DWARF.h"61#include "lld/Common/Reproduce.h"62#include "llvm/ADT/iterator.h"63#include "llvm/BinaryFormat/MachO.h"64#include "llvm/LTO/LTO.h"65#include "llvm/Support/BinaryStreamReader.h"66#include "llvm/Support/Endian.h"67#include "llvm/Support/LEB128.h"68#include "llvm/Support/MemoryBuffer.h"69#include "llvm/Support/Path.h"70#include "llvm/Support/TarWriter.h"71#include "llvm/Support/TimeProfiler.h"72#include "llvm/TextAPI/Architecture.h"73#include "llvm/TextAPI/InterfaceFile.h"7475#include <optional>76#include <type_traits>7778using namespace llvm;79using namespace llvm::MachO;80using namespace llvm::support::endian;81using namespace llvm::sys;82using namespace lld;83using namespace lld::macho;8485// Returns "<internal>", "foo.a(bar.o)", or "baz.o".86std::string lld::toString(const InputFile *f) {87if (!f)88return "<internal>";8990// Multiple dylibs can be defined in one .tbd file.91if (const auto *dylibFile = dyn_cast<DylibFile>(f))92if (f->getName().ends_with(".tbd"))93return (f->getName() + "(" + dylibFile->installName + ")").str();9495if (f->archiveName.empty())96return std::string(f->getName());97return (f->archiveName + "(" + path::filename(f->getName()) + ")").str();98}99100std::string lld::toString(const Section &sec) {101return (toString(sec.file) + ":(" + sec.name + ")").str();102}103104SetVector<InputFile *> macho::inputFiles;105std::unique_ptr<TarWriter> macho::tar;106int InputFile::idCount = 0;107108static VersionTuple decodeVersion(uint32_t version) {109unsigned major = version >> 16;110unsigned minor = (version >> 8) & 0xffu;111unsigned subMinor = version & 0xffu;112return VersionTuple(major, minor, subMinor);113}114115static std::vector<PlatformInfo> getPlatformInfos(const InputFile *input) {116if (!isa<ObjFile>(input) && !isa<DylibFile>(input))117return {};118119const char *hdr = input->mb.getBufferStart();120121// "Zippered" object files can have multiple LC_BUILD_VERSION load commands.122std::vector<PlatformInfo> platformInfos;123for (auto *cmd : findCommands<build_version_command>(hdr, LC_BUILD_VERSION)) {124PlatformInfo info;125info.target.Platform = static_cast<PlatformType>(cmd->platform);126info.target.MinDeployment = decodeVersion(cmd->minos);127platformInfos.emplace_back(std::move(info));128}129for (auto *cmd : findCommands<version_min_command>(130hdr, LC_VERSION_MIN_MACOSX, LC_VERSION_MIN_IPHONEOS,131LC_VERSION_MIN_TVOS, LC_VERSION_MIN_WATCHOS)) {132PlatformInfo info;133switch (cmd->cmd) {134case LC_VERSION_MIN_MACOSX:135info.target.Platform = PLATFORM_MACOS;136break;137case LC_VERSION_MIN_IPHONEOS:138info.target.Platform = PLATFORM_IOS;139break;140case LC_VERSION_MIN_TVOS:141info.target.Platform = PLATFORM_TVOS;142break;143case LC_VERSION_MIN_WATCHOS:144info.target.Platform = PLATFORM_WATCHOS;145break;146}147info.target.MinDeployment = decodeVersion(cmd->version);148platformInfos.emplace_back(std::move(info));149}150151return platformInfos;152}153154static bool checkCompatibility(const InputFile *input) {155std::vector<PlatformInfo> platformInfos = getPlatformInfos(input);156if (platformInfos.empty())157return true;158159auto it = find_if(platformInfos, [&](const PlatformInfo &info) {160return removeSimulator(info.target.Platform) ==161removeSimulator(config->platform());162});163if (it == platformInfos.end()) {164std::string platformNames;165raw_string_ostream os(platformNames);166interleave(167platformInfos, os,168[&](const PlatformInfo &info) {169os << getPlatformName(info.target.Platform);170},171"/");172error(toString(input) + " has platform " + platformNames +173Twine(", which is different from target platform ") +174getPlatformName(config->platform()));175return false;176}177178if (it->target.MinDeployment > config->platformInfo.target.MinDeployment)179warn(toString(input) + " has version " +180it->target.MinDeployment.getAsString() +181", which is newer than target minimum of " +182config->platformInfo.target.MinDeployment.getAsString());183184return true;185}186187template <class Header>188static bool compatWithTargetArch(const InputFile *file, const Header *hdr) {189uint32_t cpuType;190std::tie(cpuType, std::ignore) = getCPUTypeFromArchitecture(config->arch());191192if (hdr->cputype != cpuType) {193Architecture arch =194getArchitectureFromCpuType(hdr->cputype, hdr->cpusubtype);195auto msg = config->errorForArchMismatch196? static_cast<void (*)(const Twine &)>(error)197: warn;198199msg(toString(file) + " has architecture " + getArchitectureName(arch) +200" which is incompatible with target architecture " +201getArchitectureName(config->arch()));202return false;203}204205return checkCompatibility(file);206}207208// This cache mostly exists to store system libraries (and .tbds) as they're209// loaded, rather than the input archives, which are already cached at a higher210// level, and other files like the filelist that are only read once.211// Theoretically this caching could be more efficient by hoisting it, but that212// would require altering many callers to track the state.213DenseMap<CachedHashStringRef, MemoryBufferRef> macho::cachedReads;214// Open a given file path and return it as a memory-mapped file.215std::optional<MemoryBufferRef> macho::readFile(StringRef path) {216CachedHashStringRef key(path);217auto entry = cachedReads.find(key);218if (entry != cachedReads.end())219return entry->second;220221ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr = MemoryBuffer::getFile(path);222if (std::error_code ec = mbOrErr.getError()) {223error("cannot open " + path + ": " + ec.message());224return std::nullopt;225}226227std::unique_ptr<MemoryBuffer> &mb = *mbOrErr;228MemoryBufferRef mbref = mb->getMemBufferRef();229make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take mb ownership230231// If this is a regular non-fat file, return it.232const char *buf = mbref.getBufferStart();233const auto *hdr = reinterpret_cast<const fat_header *>(buf);234if (mbref.getBufferSize() < sizeof(uint32_t) ||235read32be(&hdr->magic) != FAT_MAGIC) {236if (tar)237tar->append(relativeToRoot(path), mbref.getBuffer());238return cachedReads[key] = mbref;239}240241llvm::BumpPtrAllocator &bAlloc = lld::bAlloc();242243// Object files and archive files may be fat files, which contain multiple244// real files for different CPU ISAs. Here, we search for a file that matches245// with the current link target and returns it as a MemoryBufferRef.246const auto *arch = reinterpret_cast<const fat_arch *>(buf + sizeof(*hdr));247auto getArchName = [](uint32_t cpuType, uint32_t cpuSubtype) {248return getArchitectureName(getArchitectureFromCpuType(cpuType, cpuSubtype));249};250251std::vector<StringRef> archs;252for (uint32_t i = 0, n = read32be(&hdr->nfat_arch); i < n; ++i) {253if (reinterpret_cast<const char *>(arch + i + 1) >254buf + mbref.getBufferSize()) {255error(path + ": fat_arch struct extends beyond end of file");256return std::nullopt;257}258259uint32_t cpuType = read32be(&arch[i].cputype);260uint32_t cpuSubtype =261read32be(&arch[i].cpusubtype) & ~MachO::CPU_SUBTYPE_MASK;262263// FIXME: LD64 has a more complex fallback logic here.264// Consider implementing that as well?265if (cpuType != static_cast<uint32_t>(target->cpuType) ||266cpuSubtype != target->cpuSubtype) {267archs.emplace_back(getArchName(cpuType, cpuSubtype));268continue;269}270271uint32_t offset = read32be(&arch[i].offset);272uint32_t size = read32be(&arch[i].size);273if (offset + size > mbref.getBufferSize())274error(path + ": slice extends beyond end of file");275if (tar)276tar->append(relativeToRoot(path), mbref.getBuffer());277return cachedReads[key] = MemoryBufferRef(StringRef(buf + offset, size),278path.copy(bAlloc));279}280281auto targetArchName = getArchName(target->cpuType, target->cpuSubtype);282warn(path + ": ignoring file because it is universal (" + join(archs, ",") +283") but does not contain the " + targetArchName + " architecture");284return std::nullopt;285}286287InputFile::InputFile(Kind kind, const InterfaceFile &interface)288: id(idCount++), fileKind(kind), name(saver().save(interface.getPath())) {}289290// Some sections comprise of fixed-size records, so instead of splitting them at291// symbol boundaries, we split them based on size. Records are distinct from292// literals in that they may contain references to other sections, instead of293// being leaf nodes in the InputSection graph.294//295// Note that "record" is a term I came up with. In contrast, "literal" is a term296// used by the Mach-O format.297static std::optional<size_t> getRecordSize(StringRef segname, StringRef name) {298if (name == section_names::compactUnwind) {299if (segname == segment_names::ld)300return target->wordSize == 8 ? 32 : 20;301}302if (!config->dedupStrings)303return {};304305if (name == section_names::cfString && segname == segment_names::data)306return target->wordSize == 8 ? 32 : 16;307308if (config->icfLevel == ICFLevel::none)309return {};310311if (name == section_names::objcClassRefs && segname == segment_names::data)312return target->wordSize;313314if (name == section_names::objcSelrefs && segname == segment_names::data)315return target->wordSize;316return {};317}318319static Error parseCallGraph(ArrayRef<uint8_t> data,320std::vector<CallGraphEntry> &callGraph) {321TimeTraceScope timeScope("Parsing call graph section");322BinaryStreamReader reader(data, llvm::endianness::little);323while (!reader.empty()) {324uint32_t fromIndex, toIndex;325uint64_t count;326if (Error err = reader.readInteger(fromIndex))327return err;328if (Error err = reader.readInteger(toIndex))329return err;330if (Error err = reader.readInteger(count))331return err;332callGraph.emplace_back(fromIndex, toIndex, count);333}334return Error::success();335}336337// Parse the sequence of sections within a single LC_SEGMENT(_64).338// Split each section into subsections.339template <class SectionHeader>340void ObjFile::parseSections(ArrayRef<SectionHeader> sectionHeaders) {341sections.reserve(sectionHeaders.size());342auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());343344for (const SectionHeader &sec : sectionHeaders) {345StringRef name =346StringRef(sec.sectname, strnlen(sec.sectname, sizeof(sec.sectname)));347StringRef segname =348StringRef(sec.segname, strnlen(sec.segname, sizeof(sec.segname)));349sections.push_back(make<Section>(this, segname, name, sec.flags, sec.addr));350if (sec.align >= 32) {351error("alignment " + std::to_string(sec.align) + " of section " + name +352" is too large");353continue;354}355Section §ion = *sections.back();356uint32_t align = 1 << sec.align;357ArrayRef<uint8_t> data = {isZeroFill(sec.flags) ? nullptr358: buf + sec.offset,359static_cast<size_t>(sec.size)};360361auto splitRecords = [&](size_t recordSize) -> void {362if (data.empty())363return;364Subsections &subsections = section.subsections;365subsections.reserve(data.size() / recordSize);366for (uint64_t off = 0; off < data.size(); off += recordSize) {367auto *isec = make<ConcatInputSection>(368section, data.slice(off, std::min(data.size(), recordSize)), align);369subsections.push_back({off, isec});370}371section.doneSplitting = true;372};373374if (sectionType(sec.flags) == S_CSTRING_LITERALS) {375if (sec.nreloc)376fatal(toString(this) + ": " + sec.segname + "," + sec.sectname +377" contains relocations, which is unsupported");378bool dedupLiterals =379name == section_names::objcMethname || config->dedupStrings;380InputSection *isec =381make<CStringInputSection>(section, data, align, dedupLiterals);382// FIXME: parallelize this?383cast<CStringInputSection>(isec)->splitIntoPieces();384section.subsections.push_back({0, isec});385} else if (isWordLiteralSection(sec.flags)) {386if (sec.nreloc)387fatal(toString(this) + ": " + sec.segname + "," + sec.sectname +388" contains relocations, which is unsupported");389InputSection *isec = make<WordLiteralInputSection>(section, data, align);390section.subsections.push_back({0, isec});391} else if (auto recordSize = getRecordSize(segname, name)) {392splitRecords(*recordSize);393} else if (name == section_names::ehFrame &&394segname == segment_names::text) {395splitEhFrames(data, *sections.back());396} else if (segname == segment_names::llvm) {397if (config->callGraphProfileSort && name == section_names::cgProfile)398checkError(parseCallGraph(data, callGraph));399// ld64 does not appear to emit contents from sections within the __LLVM400// segment. Symbols within those sections point to bitcode metadata401// instead of actual symbols. Global symbols within those sections could402// have the same name without causing duplicate symbol errors. To avoid403// spurious duplicate symbol errors, we do not parse these sections.404// TODO: Evaluate whether the bitcode metadata is needed.405} else if (name == section_names::objCImageInfo &&406segname == segment_names::data) {407objCImageInfo = data;408} else {409if (name == section_names::addrSig)410addrSigSection = sections.back();411412auto *isec = make<ConcatInputSection>(section, data, align);413if (isDebugSection(isec->getFlags()) &&414isec->getSegName() == segment_names::dwarf) {415// Instead of emitting DWARF sections, we emit STABS symbols to the416// object files that contain them. We filter them out early to avoid417// parsing their relocations unnecessarily.418debugSections.push_back(isec);419} else {420section.subsections.push_back({0, isec});421}422}423}424}425426void ObjFile::splitEhFrames(ArrayRef<uint8_t> data, Section &ehFrameSection) {427EhReader reader(this, data, /*dataOff=*/0);428size_t off = 0;429while (off < reader.size()) {430uint64_t frameOff = off;431uint64_t length = reader.readLength(&off);432if (length == 0)433break;434uint64_t fullLength = length + (off - frameOff);435off += length;436// We hard-code an alignment of 1 here because we don't actually want our437// EH frames to be aligned to the section alignment. EH frame decoders don't438// expect this alignment. Moreover, each EH frame must start where the439// previous one ends, and where it ends is indicated by the length field.440// Unless we update the length field (troublesome), we should keep the441// alignment to 1.442// Note that we still want to preserve the alignment of the overall section,443// just not of the individual EH frames.444ehFrameSection.subsections.push_back(445{frameOff, make<ConcatInputSection>(ehFrameSection,446data.slice(frameOff, fullLength),447/*align=*/1)});448}449ehFrameSection.doneSplitting = true;450}451452template <class T>453static Section *findContainingSection(const std::vector<Section *> §ions,454T *offset) {455static_assert(std::is_same<uint64_t, T>::value ||456std::is_same<uint32_t, T>::value,457"unexpected type for offset");458auto it = std::prev(llvm::upper_bound(459sections, *offset,460[](uint64_t value, const Section *sec) { return value < sec->addr; }));461*offset -= (*it)->addr;462return *it;463}464465// Find the subsection corresponding to the greatest section offset that is <=466// that of the given offset.467//468// offset: an offset relative to the start of the original InputSection (before469// any subsection splitting has occurred). It will be updated to represent the470// same location as an offset relative to the start of the containing471// subsection.472template <class T>473static InputSection *findContainingSubsection(const Section §ion,474T *offset) {475static_assert(std::is_same<uint64_t, T>::value ||476std::is_same<uint32_t, T>::value,477"unexpected type for offset");478auto it = std::prev(llvm::upper_bound(479section.subsections, *offset,480[](uint64_t value, Subsection subsec) { return value < subsec.offset; }));481*offset -= it->offset;482return it->isec;483}484485// Find a symbol at offset `off` within `isec`.486static Defined *findSymbolAtOffset(const ConcatInputSection *isec,487uint64_t off) {488auto it = llvm::lower_bound(isec->symbols, off, [](Defined *d, uint64_t off) {489return d->value < off;490});491// The offset should point at the exact address of a symbol (with no addend.)492if (it == isec->symbols.end() || (*it)->value != off) {493assert(isec->wasCoalesced);494return nullptr;495}496return *it;497}498499template <class SectionHeader>500static bool validateRelocationInfo(InputFile *file, const SectionHeader &sec,501relocation_info rel) {502const RelocAttrs &relocAttrs = target->getRelocAttrs(rel.r_type);503bool valid = true;504auto message = [relocAttrs, file, sec, rel, &valid](const Twine &diagnostic) {505valid = false;506return (relocAttrs.name + " relocation " + diagnostic + " at offset " +507std::to_string(rel.r_address) + " of " + sec.segname + "," +508sec.sectname + " in " + toString(file))509.str();510};511512if (!relocAttrs.hasAttr(RelocAttrBits::LOCAL) && !rel.r_extern)513error(message("must be extern"));514if (relocAttrs.hasAttr(RelocAttrBits::PCREL) != rel.r_pcrel)515error(message(Twine("must ") + (rel.r_pcrel ? "not " : "") +516"be PC-relative"));517if (isThreadLocalVariables(sec.flags) &&518!relocAttrs.hasAttr(RelocAttrBits::UNSIGNED))519error(message("not allowed in thread-local section, must be UNSIGNED"));520if (rel.r_length < 2 || rel.r_length > 3 ||521!relocAttrs.hasAttr(static_cast<RelocAttrBits>(1 << rel.r_length))) {522static SmallVector<StringRef, 4> widths{"0", "4", "8", "4 or 8"};523error(message("has width " + std::to_string(1 << rel.r_length) +524" bytes, but must be " +525widths[(static_cast<int>(relocAttrs.bits) >> 2) & 3] +526" bytes"));527}528return valid;529}530531template <class SectionHeader>532void ObjFile::parseRelocations(ArrayRef<SectionHeader> sectionHeaders,533const SectionHeader &sec, Section §ion) {534auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());535ArrayRef<relocation_info> relInfos(536reinterpret_cast<const relocation_info *>(buf + sec.reloff), sec.nreloc);537538Subsections &subsections = section.subsections;539auto subsecIt = subsections.rbegin();540for (size_t i = 0; i < relInfos.size(); i++) {541// Paired relocations serve as Mach-O's method for attaching a542// supplemental datum to a primary relocation record. ELF does not543// need them because the *_RELOC_RELA records contain the extra544// addend field, vs. *_RELOC_REL which omit the addend.545//546// The {X86_64,ARM64}_RELOC_SUBTRACTOR record holds the subtrahend,547// and the paired *_RELOC_UNSIGNED record holds the minuend. The548// datum for each is a symbolic address. The result is the offset549// between two addresses.550//551// The ARM64_RELOC_ADDEND record holds the addend, and the paired552// ARM64_RELOC_BRANCH26 or ARM64_RELOC_PAGE21/PAGEOFF12 holds the553// base symbolic address.554//555// Note: X86 does not use *_RELOC_ADDEND because it can embed an addend into556// the instruction stream. On X86, a relocatable address field always557// occupies an entire contiguous sequence of byte(s), so there is no need to558// merge opcode bits with address bits. Therefore, it's easy and convenient559// to store addends in the instruction-stream bytes that would otherwise560// contain zeroes. By contrast, RISC ISAs such as ARM64 mix opcode bits with561// address bits so that bitwise arithmetic is necessary to extract and562// insert them. Storing addends in the instruction stream is possible, but563// inconvenient and more costly at link time.564565relocation_info relInfo = relInfos[i];566bool isSubtrahend =567target->hasAttr(relInfo.r_type, RelocAttrBits::SUBTRAHEND);568int64_t pairedAddend = 0;569if (target->hasAttr(relInfo.r_type, RelocAttrBits::ADDEND)) {570pairedAddend = SignExtend64<24>(relInfo.r_symbolnum);571relInfo = relInfos[++i];572}573assert(i < relInfos.size());574if (!validateRelocationInfo(this, sec, relInfo))575continue;576if (relInfo.r_address & R_SCATTERED)577fatal("TODO: Scattered relocations not supported");578579int64_t embeddedAddend = target->getEmbeddedAddend(mb, sec.offset, relInfo);580assert(!(embeddedAddend && pairedAddend));581int64_t totalAddend = pairedAddend + embeddedAddend;582Reloc r;583r.type = relInfo.r_type;584r.pcrel = relInfo.r_pcrel;585r.length = relInfo.r_length;586r.offset = relInfo.r_address;587if (relInfo.r_extern) {588r.referent = symbols[relInfo.r_symbolnum];589r.addend = isSubtrahend ? 0 : totalAddend;590} else {591assert(!isSubtrahend);592const SectionHeader &referentSecHead =593sectionHeaders[relInfo.r_symbolnum - 1];594uint64_t referentOffset;595if (relInfo.r_pcrel) {596// The implicit addend for pcrel section relocations is the pcrel offset597// in terms of the addresses in the input file. Here we adjust it so598// that it describes the offset from the start of the referent section.599// FIXME This logic was written around x86_64 behavior -- ARM64 doesn't600// have pcrel section relocations. We may want to factor this out into601// the arch-specific .cpp file.602assert(target->hasAttr(r.type, RelocAttrBits::BYTE4));603referentOffset = sec.addr + relInfo.r_address + 4 + totalAddend -604referentSecHead.addr;605} else {606// The addend for a non-pcrel relocation is its absolute address.607referentOffset = totalAddend - referentSecHead.addr;608}609r.referent = findContainingSubsection(*sections[relInfo.r_symbolnum - 1],610&referentOffset);611r.addend = referentOffset;612}613614// Find the subsection that this relocation belongs to.615// Though not required by the Mach-O format, clang and gcc seem to emit616// relocations in order, so let's take advantage of it. However, ld64 emits617// unsorted relocations (in `-r` mode), so we have a fallback for that618// uncommon case.619InputSection *subsec;620while (subsecIt != subsections.rend() && subsecIt->offset > r.offset)621++subsecIt;622if (subsecIt == subsections.rend() ||623subsecIt->offset + subsecIt->isec->getSize() <= r.offset) {624subsec = findContainingSubsection(section, &r.offset);625// Now that we know the relocs are unsorted, avoid trying the 'fast path'626// for the other relocations.627subsecIt = subsections.rend();628} else {629subsec = subsecIt->isec;630r.offset -= subsecIt->offset;631}632subsec->relocs.push_back(r);633634if (isSubtrahend) {635relocation_info minuendInfo = relInfos[++i];636// SUBTRACTOR relocations should always be followed by an UNSIGNED one637// attached to the same address.638assert(target->hasAttr(minuendInfo.r_type, RelocAttrBits::UNSIGNED) &&639relInfo.r_address == minuendInfo.r_address);640Reloc p;641p.type = minuendInfo.r_type;642if (minuendInfo.r_extern) {643p.referent = symbols[minuendInfo.r_symbolnum];644p.addend = totalAddend;645} else {646uint64_t referentOffset =647totalAddend - sectionHeaders[minuendInfo.r_symbolnum - 1].addr;648p.referent = findContainingSubsection(649*sections[minuendInfo.r_symbolnum - 1], &referentOffset);650p.addend = referentOffset;651}652subsec->relocs.push_back(p);653}654}655}656657template <class NList>658static macho::Symbol *createDefined(const NList &sym, StringRef name,659InputSection *isec, uint64_t value,660uint64_t size, bool forceHidden) {661// Symbol scope is determined by sym.n_type & (N_EXT | N_PEXT):662// N_EXT: Global symbols. These go in the symbol table during the link,663// and also in the export table of the output so that the dynamic664// linker sees them.665// N_EXT | N_PEXT: Linkage unit (think: dylib) scoped. These go in the666// symbol table during the link so that duplicates are667// either reported (for non-weak symbols) or merged668// (for weak symbols), but they do not go in the export669// table of the output.670// N_PEXT: llvm-mc does not emit these, but `ld -r` (wherein ld64 emits671// object files) may produce them. LLD does not yet support -r.672// These are translation-unit scoped, identical to the `0` case.673// 0: Translation-unit scoped. These are not in the symbol table during674// link, and not in the export table of the output either.675bool isWeakDefCanBeHidden =676(sym.n_desc & (N_WEAK_DEF | N_WEAK_REF)) == (N_WEAK_DEF | N_WEAK_REF);677678assert(!(sym.n_desc & N_ARM_THUMB_DEF) && "ARM32 arch is not supported");679680if (sym.n_type & N_EXT) {681// -load_hidden makes us treat global symbols as linkage unit scoped.682// Duplicates are reported but the symbol does not go in the export trie.683bool isPrivateExtern = sym.n_type & N_PEXT || forceHidden;684685// lld's behavior for merging symbols is slightly different from ld64:686// ld64 picks the winning symbol based on several criteria (see687// pickBetweenRegularAtoms() in ld64's SymbolTable.cpp), while lld688// just merges metadata and keeps the contents of the first symbol689// with that name (see SymbolTable::addDefined). For:690// * inline function F in a TU built with -fvisibility-inlines-hidden691// * and inline function F in another TU built without that flag692// ld64 will pick the one from the file built without693// -fvisibility-inlines-hidden.694// lld will instead pick the one listed first on the link command line and695// give it visibility as if the function was built without696// -fvisibility-inlines-hidden.697// If both functions have the same contents, this will have the same698// behavior. If not, it won't, but the input had an ODR violation in699// that case.700//701// Similarly, merging a symbol702// that's isPrivateExtern and not isWeakDefCanBeHidden with one703// that's not isPrivateExtern but isWeakDefCanBeHidden technically704// should produce one705// that's not isPrivateExtern but isWeakDefCanBeHidden. That matters706// with ld64's semantics, because it means the non-private-extern707// definition will continue to take priority if more private extern708// definitions are encountered. With lld's semantics there's no observable709// difference between a symbol that's isWeakDefCanBeHidden(autohide) or one710// that's privateExtern -- neither makes it into the dynamic symbol table,711// unless the autohide symbol is explicitly exported.712// But if a symbol is both privateExtern and autohide then it can't713// be exported.714// So we nullify the autohide flag when privateExtern is present715// and promote the symbol to privateExtern when it is not already.716if (isWeakDefCanBeHidden && isPrivateExtern)717isWeakDefCanBeHidden = false;718else if (isWeakDefCanBeHidden)719isPrivateExtern = true;720return symtab->addDefined(721name, isec->getFile(), isec, value, size, sym.n_desc & N_WEAK_DEF,722isPrivateExtern, sym.n_desc & REFERENCED_DYNAMICALLY,723sym.n_desc & N_NO_DEAD_STRIP, isWeakDefCanBeHidden);724}725bool includeInSymtab = !isPrivateLabel(name) && !isEhFrameSection(isec);726return make<Defined>(727name, isec->getFile(), isec, value, size, sym.n_desc & N_WEAK_DEF,728/*isExternal=*/false, /*isPrivateExtern=*/false, includeInSymtab,729sym.n_desc & REFERENCED_DYNAMICALLY, sym.n_desc & N_NO_DEAD_STRIP);730}731732// Absolute symbols are defined symbols that do not have an associated733// InputSection. They cannot be weak.734template <class NList>735static macho::Symbol *createAbsolute(const NList &sym, InputFile *file,736StringRef name, bool forceHidden) {737assert(!(sym.n_desc & N_ARM_THUMB_DEF) && "ARM32 arch is not supported");738739if (sym.n_type & N_EXT) {740bool isPrivateExtern = sym.n_type & N_PEXT || forceHidden;741return symtab->addDefined(name, file, nullptr, sym.n_value, /*size=*/0,742/*isWeakDef=*/false, isPrivateExtern,743/*isReferencedDynamically=*/false,744sym.n_desc & N_NO_DEAD_STRIP,745/*isWeakDefCanBeHidden=*/false);746}747return make<Defined>(name, file, nullptr, sym.n_value, /*size=*/0,748/*isWeakDef=*/false,749/*isExternal=*/false, /*isPrivateExtern=*/false,750/*includeInSymtab=*/true,751/*isReferencedDynamically=*/false,752sym.n_desc & N_NO_DEAD_STRIP);753}754755template <class NList>756macho::Symbol *ObjFile::parseNonSectionSymbol(const NList &sym,757const char *strtab) {758StringRef name = StringRef(strtab + sym.n_strx);759uint8_t type = sym.n_type & N_TYPE;760bool isPrivateExtern = sym.n_type & N_PEXT || forceHidden;761switch (type) {762case N_UNDF:763return sym.n_value == 0764? symtab->addUndefined(name, this, sym.n_desc & N_WEAK_REF)765: symtab->addCommon(name, this, sym.n_value,7661 << GET_COMM_ALIGN(sym.n_desc),767isPrivateExtern);768case N_ABS:769return createAbsolute(sym, this, name, forceHidden);770case N_INDR: {771// Not much point in making local aliases -- relocs in the current file can772// just refer to the actual symbol itself. ld64 ignores these symbols too.773if (!(sym.n_type & N_EXT))774return nullptr;775StringRef aliasedName = StringRef(strtab + sym.n_value);776// isPrivateExtern is the only symbol flag that has an impact on the final777// aliased symbol.778auto *alias = make<AliasSymbol>(this, name, aliasedName, isPrivateExtern);779aliases.push_back(alias);780return alias;781}782case N_PBUD:783error("TODO: support symbols of type N_PBUD");784return nullptr;785case N_SECT:786llvm_unreachable(787"N_SECT symbols should not be passed to parseNonSectionSymbol");788default:789llvm_unreachable("invalid symbol type");790}791}792793template <class NList> static bool isUndef(const NList &sym) {794return (sym.n_type & N_TYPE) == N_UNDF && sym.n_value == 0;795}796797template <class LP>798void ObjFile::parseSymbols(ArrayRef<typename LP::section> sectionHeaders,799ArrayRef<typename LP::nlist> nList,800const char *strtab, bool subsectionsViaSymbols) {801using NList = typename LP::nlist;802803// Groups indices of the symbols by the sections that contain them.804std::vector<std::vector<uint32_t>> symbolsBySection(sections.size());805symbols.resize(nList.size());806SmallVector<unsigned, 32> undefineds;807for (uint32_t i = 0; i < nList.size(); ++i) {808const NList &sym = nList[i];809810// Ignore debug symbols for now.811// FIXME: may need special handling.812if (sym.n_type & N_STAB)813continue;814815if ((sym.n_type & N_TYPE) == N_SECT) {816Subsections &subsections = sections[sym.n_sect - 1]->subsections;817// parseSections() may have chosen not to parse this section.818if (subsections.empty())819continue;820symbolsBySection[sym.n_sect - 1].push_back(i);821} else if (isUndef(sym)) {822undefineds.push_back(i);823} else {824symbols[i] = parseNonSectionSymbol(sym, strtab);825}826}827828for (size_t i = 0; i < sections.size(); ++i) {829Subsections &subsections = sections[i]->subsections;830if (subsections.empty())831continue;832std::vector<uint32_t> &symbolIndices = symbolsBySection[i];833uint64_t sectionAddr = sectionHeaders[i].addr;834uint32_t sectionAlign = 1u << sectionHeaders[i].align;835836// Some sections have already been split into subsections during837// parseSections(), so we simply need to match Symbols to the corresponding838// subsection here.839if (sections[i]->doneSplitting) {840for (size_t j = 0; j < symbolIndices.size(); ++j) {841const uint32_t symIndex = symbolIndices[j];842const NList &sym = nList[symIndex];843StringRef name = strtab + sym.n_strx;844uint64_t symbolOffset = sym.n_value - sectionAddr;845InputSection *isec =846findContainingSubsection(*sections[i], &symbolOffset);847if (symbolOffset != 0) {848error(toString(*sections[i]) + ": symbol " + name +849" at misaligned offset");850continue;851}852symbols[symIndex] =853createDefined(sym, name, isec, 0, isec->getSize(), forceHidden);854}855continue;856}857sections[i]->doneSplitting = true;858859auto getSymName = [strtab](const NList& sym) -> StringRef {860return StringRef(strtab + sym.n_strx);861};862863// Calculate symbol sizes and create subsections by splitting the sections864// along symbol boundaries.865// We populate subsections by repeatedly splitting the last (highest866// address) subsection.867llvm::stable_sort(symbolIndices, [&](uint32_t lhs, uint32_t rhs) {868// Put extern weak symbols after other symbols at the same address so869// that weak symbol coalescing works correctly. See870// SymbolTable::addDefined() for details.871if (nList[lhs].n_value == nList[rhs].n_value &&872nList[lhs].n_type & N_EXT && nList[rhs].n_type & N_EXT)873return !(nList[lhs].n_desc & N_WEAK_DEF) && (nList[rhs].n_desc & N_WEAK_DEF);874return nList[lhs].n_value < nList[rhs].n_value;875});876for (size_t j = 0; j < symbolIndices.size(); ++j) {877const uint32_t symIndex = symbolIndices[j];878const NList &sym = nList[symIndex];879StringRef name = getSymName(sym);880Subsection &subsec = subsections.back();881InputSection *isec = subsec.isec;882883uint64_t subsecAddr = sectionAddr + subsec.offset;884size_t symbolOffset = sym.n_value - subsecAddr;885uint64_t symbolSize =886j + 1 < symbolIndices.size()887? nList[symbolIndices[j + 1]].n_value - sym.n_value888: isec->data.size() - symbolOffset;889// There are 4 cases where we do not need to create a new subsection:890// 1. If the input file does not use subsections-via-symbols.891// 2. Multiple symbols at the same address only induce one subsection.892// (The symbolOffset == 0 check covers both this case as well as893// the first loop iteration.)894// 3. Alternative entry points do not induce new subsections.895// 4. If we have a literal section (e.g. __cstring and __literal4).896if (!subsectionsViaSymbols || symbolOffset == 0 ||897sym.n_desc & N_ALT_ENTRY || !isa<ConcatInputSection>(isec)) {898isec->hasAltEntry = symbolOffset != 0;899symbols[symIndex] = createDefined(sym, name, isec, symbolOffset,900symbolSize, forceHidden);901continue;902}903auto *concatIsec = cast<ConcatInputSection>(isec);904905auto *nextIsec = make<ConcatInputSection>(*concatIsec);906nextIsec->wasCoalesced = false;907if (isZeroFill(isec->getFlags())) {908// Zero-fill sections have NULL data.data() non-zero data.size()909nextIsec->data = {nullptr, isec->data.size() - symbolOffset};910isec->data = {nullptr, symbolOffset};911} else {912nextIsec->data = isec->data.slice(symbolOffset);913isec->data = isec->data.slice(0, symbolOffset);914}915916// By construction, the symbol will be at offset zero in the new917// subsection.918symbols[symIndex] = createDefined(sym, name, nextIsec, /*value=*/0,919symbolSize, forceHidden);920// TODO: ld64 appears to preserve the original alignment as well as each921// subsection's offset from the last aligned address. We should consider922// emulating that behavior.923nextIsec->align = MinAlign(sectionAlign, sym.n_value);924subsections.push_back({sym.n_value - sectionAddr, nextIsec});925}926}927928// Undefined symbols can trigger recursive fetch from Archives due to929// LazySymbols. Process defined symbols first so that the relative order930// between a defined symbol and an undefined symbol does not change the931// symbol resolution behavior. In addition, a set of interconnected symbols932// will all be resolved to the same file, instead of being resolved to933// different files.934for (unsigned i : undefineds)935symbols[i] = parseNonSectionSymbol(nList[i], strtab);936}937938OpaqueFile::OpaqueFile(MemoryBufferRef mb, StringRef segName,939StringRef sectName)940: InputFile(OpaqueKind, mb) {941const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());942ArrayRef<uint8_t> data = {buf, mb.getBufferSize()};943sections.push_back(make<Section>(/*file=*/this, segName.take_front(16),944sectName.take_front(16),945/*flags=*/0, /*addr=*/0));946Section §ion = *sections.back();947ConcatInputSection *isec = make<ConcatInputSection>(section, data);948isec->live = true;949section.subsections.push_back({0, isec});950}951952template <class LP>953void ObjFile::parseLinkerOptions(SmallVectorImpl<StringRef> &LCLinkerOptions) {954using Header = typename LP::mach_header;955auto *hdr = reinterpret_cast<const Header *>(mb.getBufferStart());956957for (auto *cmd : findCommands<linker_option_command>(hdr, LC_LINKER_OPTION)) {958StringRef data{reinterpret_cast<const char *>(cmd + 1),959cmd->cmdsize - sizeof(linker_option_command)};960parseLCLinkerOption(LCLinkerOptions, this, cmd->count, data);961}962}963964SmallVector<StringRef> macho::unprocessedLCLinkerOptions;965ObjFile::ObjFile(MemoryBufferRef mb, uint32_t modTime, StringRef archiveName,966bool lazy, bool forceHidden, bool compatArch,967bool builtFromBitcode)968: InputFile(ObjKind, mb, lazy), modTime(modTime), forceHidden(forceHidden),969builtFromBitcode(builtFromBitcode) {970this->archiveName = std::string(archiveName);971this->compatArch = compatArch;972if (lazy) {973if (target->wordSize == 8)974parseLazy<LP64>();975else976parseLazy<ILP32>();977} else {978if (target->wordSize == 8)979parse<LP64>();980else981parse<ILP32>();982}983}984985template <class LP> void ObjFile::parse() {986using Header = typename LP::mach_header;987using SegmentCommand = typename LP::segment_command;988using SectionHeader = typename LP::section;989using NList = typename LP::nlist;990991auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());992auto *hdr = reinterpret_cast<const Header *>(mb.getBufferStart());993994// If we've already checked the arch, then don't need to check again.995if (!compatArch)996return;997if (!(compatArch = compatWithTargetArch(this, hdr)))998return;9991000// We will resolve LC linker options once all native objects are loaded after1001// LTO is finished.1002SmallVector<StringRef, 4> LCLinkerOptions;1003parseLinkerOptions<LP>(LCLinkerOptions);1004unprocessedLCLinkerOptions.append(LCLinkerOptions);10051006ArrayRef<SectionHeader> sectionHeaders;1007if (const load_command *cmd = findCommand(hdr, LP::segmentLCType)) {1008auto *c = reinterpret_cast<const SegmentCommand *>(cmd);1009sectionHeaders = ArrayRef<SectionHeader>{1010reinterpret_cast<const SectionHeader *>(c + 1), c->nsects};1011parseSections(sectionHeaders);1012}10131014// TODO: Error on missing LC_SYMTAB?1015if (const load_command *cmd = findCommand(hdr, LC_SYMTAB)) {1016auto *c = reinterpret_cast<const symtab_command *>(cmd);1017ArrayRef<NList> nList(reinterpret_cast<const NList *>(buf + c->symoff),1018c->nsyms);1019const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff;1020bool subsectionsViaSymbols = hdr->flags & MH_SUBSECTIONS_VIA_SYMBOLS;1021parseSymbols<LP>(sectionHeaders, nList, strtab, subsectionsViaSymbols);1022}10231024// The relocations may refer to the symbols, so we parse them after we have1025// parsed all the symbols.1026for (size_t i = 0, n = sections.size(); i < n; ++i)1027if (!sections[i]->subsections.empty())1028parseRelocations(sectionHeaders, sectionHeaders[i], *sections[i]);10291030parseDebugInfo();10311032Section *ehFrameSection = nullptr;1033Section *compactUnwindSection = nullptr;1034for (Section *sec : sections) {1035Section **s = StringSwitch<Section **>(sec->name)1036.Case(section_names::compactUnwind, &compactUnwindSection)1037.Case(section_names::ehFrame, &ehFrameSection)1038.Default(nullptr);1039if (s)1040*s = sec;1041}1042if (compactUnwindSection)1043registerCompactUnwind(*compactUnwindSection);1044if (ehFrameSection)1045registerEhFrames(*ehFrameSection);1046}10471048template <class LP> void ObjFile::parseLazy() {1049using Header = typename LP::mach_header;1050using NList = typename LP::nlist;10511052auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());1053auto *hdr = reinterpret_cast<const Header *>(mb.getBufferStart());10541055if (!compatArch)1056return;1057if (!(compatArch = compatWithTargetArch(this, hdr)))1058return;10591060const load_command *cmd = findCommand(hdr, LC_SYMTAB);1061if (!cmd)1062return;1063auto *c = reinterpret_cast<const symtab_command *>(cmd);1064ArrayRef<NList> nList(reinterpret_cast<const NList *>(buf + c->symoff),1065c->nsyms);1066const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff;1067symbols.resize(nList.size());1068for (const auto &[i, sym] : llvm::enumerate(nList)) {1069if ((sym.n_type & N_EXT) && !isUndef(sym)) {1070// TODO: Bound checking1071StringRef name = strtab + sym.n_strx;1072symbols[i] = symtab->addLazyObject(name, *this);1073if (!lazy)1074break;1075}1076}1077}10781079void ObjFile::parseDebugInfo() {1080std::unique_ptr<DwarfObject> dObj = DwarfObject::create(this);1081if (!dObj)1082return;10831084// We do not re-use the context from getDwarf() here as that function1085// constructs an expensive DWARFCache object.1086auto *ctx = make<DWARFContext>(1087std::move(dObj), "",1088[&](Error err) {1089warn(toString(this) + ": " + toString(std::move(err)));1090},1091[&](Error warning) {1092warn(toString(this) + ": " + toString(std::move(warning)));1093});10941095// TODO: Since object files can contain a lot of DWARF info, we should verify1096// that we are parsing just the info we need1097const DWARFContext::compile_unit_range &units = ctx->compile_units();1098// FIXME: There can be more than one compile unit per object file. See1099// PR48637.1100auto it = units.begin();1101compileUnit = it != units.end() ? it->get() : nullptr;1102}11031104ArrayRef<data_in_code_entry> ObjFile::getDataInCode() const {1105const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());1106const load_command *cmd = findCommand(buf, LC_DATA_IN_CODE);1107if (!cmd)1108return {};1109const auto *c = reinterpret_cast<const linkedit_data_command *>(cmd);1110return {reinterpret_cast<const data_in_code_entry *>(buf + c->dataoff),1111c->datasize / sizeof(data_in_code_entry)};1112}11131114ArrayRef<uint8_t> ObjFile::getOptimizationHints() const {1115const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());1116if (auto *cmd =1117findCommand<linkedit_data_command>(buf, LC_LINKER_OPTIMIZATION_HINT))1118return {buf + cmd->dataoff, cmd->datasize};1119return {};1120}11211122// Create pointers from symbols to their associated compact unwind entries.1123void ObjFile::registerCompactUnwind(Section &compactUnwindSection) {1124for (const Subsection &subsection : compactUnwindSection.subsections) {1125ConcatInputSection *isec = cast<ConcatInputSection>(subsection.isec);1126// Hack!! Each compact unwind entry (CUE) has its UNSIGNED relocations embed1127// their addends in its data. Thus if ICF operated naively and compared the1128// entire contents of each CUE, entries with identical unwind info but e.g.1129// belonging to different functions would never be considered equivalent. To1130// work around this problem, we remove some parts of the data containing the1131// embedded addends. In particular, we remove the function address and LSDA1132// pointers. Since these locations are at the start and end of the entry,1133// we can do this using a simple, efficient slice rather than performing a1134// copy. We are not losing any information here because the embedded1135// addends have already been parsed in the corresponding Reloc structs.1136//1137// Removing these pointers would not be safe if they were pointers to1138// absolute symbols. In that case, there would be no corresponding1139// relocation. However, (AFAIK) MC cannot emit references to absolute1140// symbols for either the function address or the LSDA. However, it *can* do1141// so for the personality pointer, so we are not slicing that field away.1142//1143// Note that we do not adjust the offsets of the corresponding relocations;1144// instead, we rely on `relocateCompactUnwind()` to correctly handle these1145// truncated input sections.1146isec->data = isec->data.slice(target->wordSize, 8 + target->wordSize);1147uint32_t encoding = read32le(isec->data.data() + sizeof(uint32_t));1148// llvm-mc omits CU entries for functions that need DWARF encoding, but1149// `ld -r` doesn't. We can ignore them because we will re-synthesize these1150// CU entries from the DWARF info during the output phase.1151if ((encoding & static_cast<uint32_t>(UNWIND_MODE_MASK)) ==1152target->modeDwarfEncoding)1153continue;11541155ConcatInputSection *referentIsec;1156for (auto it = isec->relocs.begin(); it != isec->relocs.end();) {1157Reloc &r = *it;1158// CUE::functionAddress is at offset 0. Skip personality & LSDA relocs.1159if (r.offset != 0) {1160++it;1161continue;1162}1163uint64_t add = r.addend;1164if (auto *sym = cast_or_null<Defined>(r.referent.dyn_cast<Symbol *>())) {1165// Check whether the symbol defined in this file is the prevailing one.1166// Skip if it is e.g. a weak def that didn't prevail.1167if (sym->getFile() != this) {1168++it;1169continue;1170}1171add += sym->value;1172referentIsec = cast<ConcatInputSection>(sym->isec());1173} else {1174referentIsec =1175cast<ConcatInputSection>(r.referent.dyn_cast<InputSection *>());1176}1177// Unwind info lives in __DATA, and finalization of __TEXT will occur1178// before finalization of __DATA. Moreover, the finalization of unwind1179// info depends on the exact addresses that it references. So it is safe1180// for compact unwind to reference addresses in __TEXT, but not addresses1181// in any other segment.1182if (referentIsec->getSegName() != segment_names::text)1183error(isec->getLocation(r.offset) + " references section " +1184referentIsec->getName() + " which is not in segment __TEXT");1185// The functionAddress relocations are typically section relocations.1186// However, unwind info operates on a per-symbol basis, so we search for1187// the function symbol here.1188Defined *d = findSymbolAtOffset(referentIsec, add);1189if (!d) {1190++it;1191continue;1192}1193d->originalUnwindEntry = isec;1194// Now that the symbol points to the unwind entry, we can remove the reloc1195// that points from the unwind entry back to the symbol.1196//1197// First, the symbol keeps the unwind entry alive (and not vice versa), so1198// this keeps dead-stripping simple.1199//1200// Moreover, it reduces the work that ICF needs to do to figure out if1201// functions with unwind info are foldable.1202//1203// However, this does make it possible for ICF to fold CUEs that point to1204// distinct functions (if the CUEs are otherwise identical).1205// UnwindInfoSection takes care of this by re-duplicating the CUEs so that1206// each one can hold a distinct functionAddress value.1207//1208// Given that clang emits relocations in reverse order of address, this1209// relocation should be at the end of the vector for most of our input1210// object files, so this erase() is typically an O(1) operation.1211it = isec->relocs.erase(it);1212}1213}1214}12151216struct CIE {1217macho::Symbol *personalitySymbol = nullptr;1218bool fdesHaveAug = false;1219uint8_t lsdaPtrSize = 0; // 0 => no LSDA1220uint8_t funcPtrSize = 0;1221};12221223static uint8_t pointerEncodingToSize(uint8_t enc) {1224switch (enc & 0xf) {1225case dwarf::DW_EH_PE_absptr:1226return target->wordSize;1227case dwarf::DW_EH_PE_sdata4:1228return 4;1229case dwarf::DW_EH_PE_sdata8:1230// ld64 doesn't actually support sdata8, but this seems simple enough...1231return 8;1232default:1233return 0;1234};1235}12361237static CIE parseCIE(const InputSection *isec, const EhReader &reader,1238size_t off) {1239// Handling the full generality of possible DWARF encodings would be a major1240// pain. We instead take advantage of our knowledge of how llvm-mc encodes1241// DWARF and handle just that.1242constexpr uint8_t expectedPersonalityEnc =1243dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_sdata4;12441245CIE cie;1246uint8_t version = reader.readByte(&off);1247if (version != 1 && version != 3)1248fatal("Expected CIE version of 1 or 3, got " + Twine(version));1249StringRef aug = reader.readString(&off);1250reader.skipLeb128(&off); // skip code alignment1251reader.skipLeb128(&off); // skip data alignment1252reader.skipLeb128(&off); // skip return address register1253reader.skipLeb128(&off); // skip aug data length1254uint64_t personalityAddrOff = 0;1255for (char c : aug) {1256switch (c) {1257case 'z':1258cie.fdesHaveAug = true;1259break;1260case 'P': {1261uint8_t personalityEnc = reader.readByte(&off);1262if (personalityEnc != expectedPersonalityEnc)1263reader.failOn(off, "unexpected personality encoding 0x" +1264Twine::utohexstr(personalityEnc));1265personalityAddrOff = off;1266off += 4;1267break;1268}1269case 'L': {1270uint8_t lsdaEnc = reader.readByte(&off);1271cie.lsdaPtrSize = pointerEncodingToSize(lsdaEnc);1272if (cie.lsdaPtrSize == 0)1273reader.failOn(off, "unexpected LSDA encoding 0x" +1274Twine::utohexstr(lsdaEnc));1275break;1276}1277case 'R': {1278uint8_t pointerEnc = reader.readByte(&off);1279cie.funcPtrSize = pointerEncodingToSize(pointerEnc);1280if (cie.funcPtrSize == 0 || !(pointerEnc & dwarf::DW_EH_PE_pcrel))1281reader.failOn(off, "unexpected pointer encoding 0x" +1282Twine::utohexstr(pointerEnc));1283break;1284}1285default:1286break;1287}1288}1289if (personalityAddrOff != 0) {1290const auto *personalityReloc = isec->getRelocAt(personalityAddrOff);1291if (!personalityReloc)1292reader.failOn(off, "Failed to locate relocation for personality symbol");1293cie.personalitySymbol = personalityReloc->referent.get<macho::Symbol *>();1294}1295return cie;1296}12971298// EH frame target addresses may be encoded as pcrel offsets. However, instead1299// of using an actual pcrel reloc, ld64 emits subtractor relocations instead.1300// This function recovers the target address from the subtractors, essentially1301// performing the inverse operation of EhRelocator.1302//1303// Concretely, we expect our relocations to write the value of `PC -1304// target_addr` to `PC`. `PC` itself is denoted by a minuend relocation that1305// points to a symbol plus an addend.1306//1307// It is important that the minuend relocation point to a symbol within the1308// same section as the fixup value, since sections may get moved around.1309//1310// For example, for arm64, llvm-mc emits relocations for the target function1311// address like so:1312//1313// ltmp:1314// <CIE start>1315// ...1316// <CIE end>1317// ... multiple FDEs ...1318// <FDE start>1319// <target function address - (ltmp + pcrel offset)>1320// ...1321//1322// If any of the FDEs in `multiple FDEs` get dead-stripped, then `FDE start`1323// will move to an earlier address, and `ltmp + pcrel offset` will no longer1324// reflect an accurate pcrel value. To avoid this problem, we "canonicalize"1325// our relocation by adding an `EH_Frame` symbol at `FDE start`, and updating1326// the reloc to be `target function address - (EH_Frame + new pcrel offset)`.1327//1328// If `Invert` is set, then we instead expect `target_addr - PC` to be written1329// to `PC`.1330template <bool Invert = false>1331Defined *1332targetSymFromCanonicalSubtractor(const InputSection *isec,1333std::vector<macho::Reloc>::iterator relocIt) {1334macho::Reloc &subtrahend = *relocIt;1335macho::Reloc &minuend = *std::next(relocIt);1336assert(target->hasAttr(subtrahend.type, RelocAttrBits::SUBTRAHEND));1337assert(target->hasAttr(minuend.type, RelocAttrBits::UNSIGNED));1338// Note: pcSym may *not* be exactly at the PC; there's usually a non-zero1339// addend.1340auto *pcSym = cast<Defined>(subtrahend.referent.get<macho::Symbol *>());1341Defined *target =1342cast_or_null<Defined>(minuend.referent.dyn_cast<macho::Symbol *>());1343if (!pcSym) {1344auto *targetIsec =1345cast<ConcatInputSection>(minuend.referent.get<InputSection *>());1346target = findSymbolAtOffset(targetIsec, minuend.addend);1347}1348if (Invert)1349std::swap(pcSym, target);1350if (pcSym->isec() == isec) {1351if (pcSym->value - (Invert ? -1 : 1) * minuend.addend != subtrahend.offset)1352fatal("invalid FDE relocation in __eh_frame");1353} else {1354// Ensure the pcReloc points to a symbol within the current EH frame.1355// HACK: we should really verify that the original relocation's semantics1356// are preserved. In particular, we should have1357// `oldSym->value + oldOffset == newSym + newOffset`. However, we don't1358// have an easy way to access the offsets from this point in the code; some1359// refactoring is needed for that.1360macho::Reloc &pcReloc = Invert ? minuend : subtrahend;1361pcReloc.referent = isec->symbols[0];1362assert(isec->symbols[0]->value == 0);1363minuend.addend = pcReloc.offset * (Invert ? 1LL : -1LL);1364}1365return target;1366}13671368Defined *findSymbolAtAddress(const std::vector<Section *> §ions,1369uint64_t addr) {1370Section *sec = findContainingSection(sections, &addr);1371auto *isec = cast<ConcatInputSection>(findContainingSubsection(*sec, &addr));1372return findSymbolAtOffset(isec, addr);1373}13741375// For symbols that don't have compact unwind info, associate them with the more1376// general-purpose (and verbose) DWARF unwind info found in __eh_frame.1377//1378// This requires us to parse the contents of __eh_frame. See EhFrame.h for a1379// description of its format.1380//1381// While parsing, we also look for what MC calls "abs-ified" relocations -- they1382// are relocations which are implicitly encoded as offsets in the section data.1383// We convert them into explicit Reloc structs so that the EH frames can be1384// handled just like a regular ConcatInputSection later in our output phase.1385//1386// We also need to handle the case where our input object file has explicit1387// relocations. This is the case when e.g. it's the output of `ld -r`. We only1388// look for the "abs-ified" relocation if an explicit relocation is absent.1389void ObjFile::registerEhFrames(Section &ehFrameSection) {1390DenseMap<const InputSection *, CIE> cieMap;1391for (const Subsection &subsec : ehFrameSection.subsections) {1392auto *isec = cast<ConcatInputSection>(subsec.isec);1393uint64_t isecOff = subsec.offset;13941395// Subtractor relocs require the subtrahend to be a symbol reloc. Ensure1396// that all EH frames have an associated symbol so that we can generate1397// subtractor relocs that reference them.1398if (isec->symbols.size() == 0)1399make<Defined>("EH_Frame", isec->getFile(), isec, /*value=*/0,1400isec->getSize(), /*isWeakDef=*/false, /*isExternal=*/false,1401/*isPrivateExtern=*/false, /*includeInSymtab=*/false,1402/*isReferencedDynamically=*/false,1403/*noDeadStrip=*/false);1404else if (isec->symbols[0]->value != 0)1405fatal("found symbol at unexpected offset in __eh_frame");14061407EhReader reader(this, isec->data, subsec.offset);1408size_t dataOff = 0; // Offset from the start of the EH frame.1409reader.skipValidLength(&dataOff); // readLength() already validated this.1410// cieOffOff is the offset from the start of the EH frame to the cieOff1411// value, which is itself an offset from the current PC to a CIE.1412const size_t cieOffOff = dataOff;14131414EhRelocator ehRelocator(isec);1415auto cieOffRelocIt = llvm::find_if(1416isec->relocs, [=](const Reloc &r) { return r.offset == cieOffOff; });1417InputSection *cieIsec = nullptr;1418if (cieOffRelocIt != isec->relocs.end()) {1419// We already have an explicit relocation for the CIE offset.1420cieIsec =1421targetSymFromCanonicalSubtractor</*Invert=*/true>(isec, cieOffRelocIt)1422->isec();1423dataOff += sizeof(uint32_t);1424} else {1425// If we haven't found a relocation, then the CIE offset is most likely1426// embedded in the section data (AKA an "abs-ified" reloc.). Parse that1427// and generate a Reloc struct.1428uint32_t cieMinuend = reader.readU32(&dataOff);1429if (cieMinuend == 0) {1430cieIsec = isec;1431} else {1432uint32_t cieOff = isecOff + dataOff - cieMinuend;1433cieIsec = findContainingSubsection(ehFrameSection, &cieOff);1434if (cieIsec == nullptr)1435fatal("failed to find CIE");1436}1437if (cieIsec != isec)1438ehRelocator.makeNegativePcRel(cieOffOff, cieIsec->symbols[0],1439/*length=*/2);1440}1441if (cieIsec == isec) {1442cieMap[cieIsec] = parseCIE(isec, reader, dataOff);1443continue;1444}14451446assert(cieMap.count(cieIsec));1447const CIE &cie = cieMap[cieIsec];1448// Offset of the function address within the EH frame.1449const size_t funcAddrOff = dataOff;1450uint64_t funcAddr = reader.readPointer(&dataOff, cie.funcPtrSize) +1451ehFrameSection.addr + isecOff + funcAddrOff;1452uint32_t funcLength = reader.readPointer(&dataOff, cie.funcPtrSize);1453size_t lsdaAddrOff = 0; // Offset of the LSDA address within the EH frame.1454std::optional<uint64_t> lsdaAddrOpt;1455if (cie.fdesHaveAug) {1456reader.skipLeb128(&dataOff);1457lsdaAddrOff = dataOff;1458if (cie.lsdaPtrSize != 0) {1459uint64_t lsdaOff = reader.readPointer(&dataOff, cie.lsdaPtrSize);1460if (lsdaOff != 0) // FIXME possible to test this?1461lsdaAddrOpt = ehFrameSection.addr + isecOff + lsdaAddrOff + lsdaOff;1462}1463}14641465auto funcAddrRelocIt = isec->relocs.end();1466auto lsdaAddrRelocIt = isec->relocs.end();1467for (auto it = isec->relocs.begin(); it != isec->relocs.end(); ++it) {1468if (it->offset == funcAddrOff)1469funcAddrRelocIt = it++; // Found subtrahend; skip over minuend reloc1470else if (lsdaAddrOpt && it->offset == lsdaAddrOff)1471lsdaAddrRelocIt = it++; // Found subtrahend; skip over minuend reloc1472}14731474Defined *funcSym;1475if (funcAddrRelocIt != isec->relocs.end()) {1476funcSym = targetSymFromCanonicalSubtractor(isec, funcAddrRelocIt);1477// Canonicalize the symbol. If there are multiple symbols at the same1478// address, we want both `registerEhFrame` and `registerCompactUnwind`1479// to register the unwind entry under same symbol.1480// This is not particularly efficient, but we should run into this case1481// infrequently (only when handling the output of `ld -r`).1482if (funcSym->isec())1483funcSym = findSymbolAtOffset(cast<ConcatInputSection>(funcSym->isec()),1484funcSym->value);1485} else {1486funcSym = findSymbolAtAddress(sections, funcAddr);1487ehRelocator.makePcRel(funcAddrOff, funcSym, target->p2WordSize);1488}1489// The symbol has been coalesced, or already has a compact unwind entry.1490if (!funcSym || funcSym->getFile() != this || funcSym->unwindEntry()) {1491// We must prune unused FDEs for correctness, so we cannot rely on1492// -dead_strip being enabled.1493isec->live = false;1494continue;1495}14961497InputSection *lsdaIsec = nullptr;1498if (lsdaAddrRelocIt != isec->relocs.end()) {1499lsdaIsec =1500targetSymFromCanonicalSubtractor(isec, lsdaAddrRelocIt)->isec();1501} else if (lsdaAddrOpt) {1502uint64_t lsdaAddr = *lsdaAddrOpt;1503Section *sec = findContainingSection(sections, &lsdaAddr);1504lsdaIsec =1505cast<ConcatInputSection>(findContainingSubsection(*sec, &lsdaAddr));1506ehRelocator.makePcRel(lsdaAddrOff, lsdaIsec, target->p2WordSize);1507}15081509fdes[isec] = {funcLength, cie.personalitySymbol, lsdaIsec};1510funcSym->originalUnwindEntry = isec;1511ehRelocator.commit();1512}15131514// __eh_frame is marked as S_ATTR_LIVE_SUPPORT in input files, because FDEs1515// 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, so1517// dead-stripping will just work as usual, and S_ATTR_LIVE_SUPPORT will only1518// serve to incorrectly prevent us from dead-stripping duplicate FDEs for a1519// live symbol (e.g. if there were multiple weak copies). Remove this flag to1520// let dead-stripping proceed correctly.1521ehFrameSection.flags &= ~S_ATTR_LIVE_SUPPORT;1522}15231524std::string ObjFile::sourceFile() const {1525const char *unitName = compileUnit->getUnitDIE().getShortName();1526// DWARF allows DW_AT_name to be absolute, in which case nothing should be1527// prepended. As for the styles, debug info can contain paths from any OS, not1528// necessarily an OS we're currently running on. Moreover different1529// compilation units can be compiled on different operating systems and linked1530// together later.1531if (sys::path::is_absolute(unitName, llvm::sys::path::Style::posix) ||1532sys::path::is_absolute(unitName, llvm::sys::path::Style::windows))1533return unitName;1534SmallString<261> dir(compileUnit->getCompilationDir());1535StringRef sep = sys::path::get_separator();1536// We don't use `path::append` here because we want an empty `dir` to result1537// in an absolute path. `append` would give us a relative path for that case.1538if (!dir.ends_with(sep))1539dir += sep;1540return (dir + unitName).str();1541}15421543lld::DWARFCache *ObjFile::getDwarf() {1544llvm::call_once(initDwarf, [this]() {1545auto dwObj = DwarfObject::create(this);1546if (!dwObj)1547return;1548dwarfCache = std::make_unique<DWARFCache>(std::make_unique<DWARFContext>(1549std::move(dwObj), "",1550[&](Error err) { warn(getName() + ": " + toString(std::move(err))); },1551[&](Error warning) {1552warn(getName() + ": " + toString(std::move(warning)));1553}));1554});15551556return dwarfCache.get();1557}1558// The path can point to either a dylib or a .tbd file.1559static DylibFile *loadDylib(StringRef path, DylibFile *umbrella) {1560std::optional<MemoryBufferRef> mbref = readFile(path);1561if (!mbref) {1562error("could not read dylib file at " + path);1563return nullptr;1564}1565return loadDylib(*mbref, umbrella);1566}15671568// TBD files are parsed into a series of TAPI documents (InterfaceFiles), with1569// the first document storing child pointers to the rest of them. When we are1570// processing a given TBD file, we store that top-level document in1571// currentTopLevelTapi. When processing re-exports, we search its children for1572// potentially matching documents in the same TBD file. Note that the children1573// 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 .tbd1576// files.1577static DylibFile *findDylib(StringRef path, DylibFile *umbrella,1578const InterfaceFile *currentTopLevelTapi) {1579// Search order:1580// 1. Install name basename in -F / -L directories.1581{1582StringRef stem = path::stem(path);1583SmallString<128> frameworkName;1584path::append(frameworkName, path::Style::posix, stem + ".framework", stem);1585bool isFramework = path.ends_with(frameworkName);1586if (isFramework) {1587for (StringRef dir : config->frameworkSearchPaths) {1588SmallString<128> candidate = dir;1589path::append(candidate, frameworkName);1590if (std::optional<StringRef> dylibPath =1591resolveDylibPath(candidate.str()))1592return loadDylib(*dylibPath, umbrella);1593}1594} else if (std::optional<StringRef> dylibPath = findPathCombination(1595stem, config->librarySearchPaths, {".tbd", ".dylib", ".so"}))1596return loadDylib(*dylibPath, umbrella);1597}15981599// 2. As absolute path.1600if (path::is_absolute(path, path::Style::posix))1601for (StringRef root : config->systemLibraryRoots)1602if (std::optional<StringRef> dylibPath =1603resolveDylibPath((root + path).str()))1604return loadDylib(*dylibPath, umbrella);16051606// 3. As relative path.16071608// TODO: Handle -dylib_file16091610// Replace @executable_path, @loader_path, @rpath prefixes in install name.1611SmallString<128> newPath;1612if (config->outputType == MH_EXECUTE &&1613path.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.1617path::append(newPath, path::parent_path(config->outputFile), path);1618path = newPath;1619} else if (path.consume_front("@loader_path/")) {1620fs::real_path(umbrella->getName(), newPath);1621path::remove_filename(newPath);1622path::append(newPath, path);1623path = newPath;1624} else if (path.starts_with("@rpath/")) {1625for (StringRef rpath : umbrella->rpaths) {1626newPath.clear();1627if (rpath.consume_front("@loader_path/")) {1628fs::real_path(umbrella->getName(), newPath);1629path::remove_filename(newPath);1630}1631path::append(newPath, rpath, path.drop_front(strlen("@rpath/")));1632if (std::optional<StringRef> dylibPath = resolveDylibPath(newPath.str()))1633return loadDylib(*dylibPath, umbrella);1634}1635}16361637// FIXME: Should this be further up?1638if (currentTopLevelTapi) {1639for (InterfaceFile &child :1640make_pointee_range(currentTopLevelTapi->documents())) {1641assert(child.documents().empty());1642if (path == child.getInstallName()) {1643auto *file = make<DylibFile>(child, umbrella, /*isBundleLoader=*/false,1644/*explicitlyLinked=*/false);1645file->parseReexports(child);1646return file;1647}1648}1649}16501651if (std::optional<StringRef> dylibPath = resolveDylibPath(path))1652return loadDylib(*dylibPath, umbrella);16531654return nullptr;1655}16561657// If a re-exported dylib is public (lives in /usr/lib or1658// /System/Library/Frameworks), then it is considered implicitly linked: we1659// should bind to its symbols directly instead of via the re-exporting umbrella1660// library.1661static bool isImplicitlyLinked(StringRef path) {1662if (!config->implicitDylibs)1663return false;16641665if (path::parent_path(path) == "/usr/lib")1666return true;16671668// Match /System/Library/Frameworks/$FOO.framework/**/$FOO1669if (path.consume_front("/System/Library/Frameworks/")) {1670StringRef frameworkName = path.take_until([](char c) { return c == '.'; });1671return path::filename(path) == frameworkName;1672}16731674return false;1675}16761677void DylibFile::loadReexport(StringRef path, DylibFile *umbrella,1678const InterfaceFile *currentTopLevelTapi) {1679DylibFile *reexport = findDylib(path, umbrella, currentTopLevelTapi);1680if (!reexport)1681error(toString(this) + ": unable to locate re-export with install name " +1682path);1683}16841685DylibFile::DylibFile(MemoryBufferRef mb, DylibFile *umbrella,1686bool isBundleLoader, bool explicitlyLinked)1687: InputFile(DylibKind, mb), refState(RefState::Unreferenced),1688explicitlyLinked(explicitlyLinked), isBundleLoader(isBundleLoader) {1689assert(!isBundleLoader || !umbrella);1690if (umbrella == nullptr)1691umbrella = this;1692this->umbrella = umbrella;16931694auto *hdr = reinterpret_cast<const mach_header *>(mb.getBufferStart());16951696// Initialize installName.1697if (const load_command *cmd = findCommand(hdr, LC_ID_DYLIB)) {1698auto *c = reinterpret_cast<const dylib_command *>(cmd);1699currentVersion = read32le(&c->dylib.current_version);1700compatibilityVersion = read32le(&c->dylib.compatibility_version);1701installName =1702reinterpret_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.1706error(toString(this) + ": dylib missing LC_ID_DYLIB load command");1707return;1708}17091710if (config->printEachFile)1711message(toString(this));1712inputFiles.insert(this);17131714deadStrippable = hdr->flags & MH_DEAD_STRIPPABLE_DYLIB;17151716if (!checkCompatibility(this))1717return;17181719checkAppExtensionSafety(hdr->flags & MH_APP_EXTENSION_SAFE);17201721for (auto *cmd : findCommands<rpath_command>(hdr, LC_RPATH)) {1722StringRef rpath{reinterpret_cast<const char *>(cmd) + cmd->path};1723rpaths.push_back(rpath);1724}17251726// Initialize symbols.1727bool canBeImplicitlyLinked = findCommand(hdr, LC_SUB_CLIENT) == nullptr;1728exportingFile = (canBeImplicitlyLinked && isImplicitlyLinked(installName))1729? this1730: this->umbrella;17311732const auto *dyldInfo = findCommand<dyld_info_command>(hdr, LC_DYLD_INFO_ONLY);1733const auto *exportsTrie =1734findCommand<linkedit_data_command>(hdr, LC_DYLD_EXPORTS_TRIE);1735if (dyldInfo && exportsTrie) {1736// It's unclear what should happen in this case. Maybe we should only error1737// out if the two load commands refer to different data?1738error(toString(this) +1739": dylib has both LC_DYLD_INFO_ONLY and LC_DYLD_EXPORTS_TRIE");1740return;1741}17421743if (dyldInfo) {1744parseExportedSymbols(dyldInfo->export_off, dyldInfo->export_size);1745} else if (exportsTrie) {1746parseExportedSymbols(exportsTrie->dataoff, exportsTrie->datasize);1747} else {1748error("No LC_DYLD_INFO_ONLY or LC_DYLD_EXPORTS_TRIE found in " +1749toString(this));1750}1751}17521753void DylibFile::parseExportedSymbols(uint32_t offset, uint32_t size) {1754struct TrieEntry {1755StringRef name;1756uint64_t flags;1757};17581759auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart());1760std::vector<TrieEntry> entries;1761// Find all the $ld$* symbols to process first.1762parseTrie(buf + offset, size, [&](const Twine &name, uint64_t flags) {1763StringRef savedName = saver().save(name);1764if (handleLDSymbol(savedName))1765return;1766entries.push_back({savedName, flags});1767});17681769// Process the "normal" symbols.1770for (TrieEntry &entry : entries) {1771if (exportingFile->hiddenSymbols.contains(CachedHashStringRef(entry.name)))1772continue;17731774bool isWeakDef = entry.flags & EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION;1775bool isTlv = entry.flags & EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL;17761777symbols.push_back(1778symtab->addDylib(entry.name, exportingFile, isWeakDef, isTlv));1779}1780}17811782void DylibFile::parseLoadCommands(MemoryBufferRef mb) {1783auto *hdr = reinterpret_cast<const mach_header *>(mb.getBufferStart());1784const uint8_t *p = reinterpret_cast<const uint8_t *>(mb.getBufferStart()) +1785target->headerSize;1786for (uint32_t i = 0, n = hdr->ncmds; i < n; ++i) {1787auto *cmd = reinterpret_cast<const load_command *>(p);1788p += cmd->cmdsize;17891790if (!(hdr->flags & MH_NO_REEXPORTED_DYLIBS) &&1791cmd->cmd == LC_REEXPORT_DYLIB) {1792const auto *c = reinterpret_cast<const dylib_command *>(cmd);1793StringRef reexportPath =1794reinterpret_cast<const char *>(c) + read32le(&c->dylib.name);1795loadReexport(reexportPath, exportingFile, nullptr);1796}17971798// FIXME: What about LC_LOAD_UPWARD_DYLIB, LC_LAZY_LOAD_DYLIB,1799// LC_LOAD_WEAK_DYLIB, LC_REEXPORT_DYLIB (..are reexports from dylibs with1800// MH_NO_REEXPORTED_DYLIBS loaded for -flat_namespace)?1801if (config->namespaceKind == NamespaceKind::flat &&1802cmd->cmd == LC_LOAD_DYLIB) {1803const auto *c = reinterpret_cast<const dylib_command *>(cmd);1804StringRef dylibPath =1805reinterpret_cast<const char *>(c) + read32le(&c->dylib.name);1806DylibFile *dylib = findDylib(dylibPath, umbrella, nullptr);1807if (!dylib)1808error(Twine("unable to locate library '") + dylibPath +1809"' loaded from '" + toString(this) + "' for -flat_namespace");1810}1811}1812}18131814// Some versions of Xcode ship with .tbd files that don't have the right1815// platform settings.1816constexpr std::array<StringRef, 3> skipPlatformChecks{1817"/usr/lib/system/libsystem_kernel.dylib",1818"/usr/lib/system/libsystem_platform.dylib",1819"/usr/lib/system/libsystem_pthread.dylib"};18201821static bool skipPlatformCheckForCatalyst(const InterfaceFile &interface,1822bool explicitlyLinked) {1823// Catalyst outputs can link against implicitly linked macOS-only libraries.1824if (config->platform() != PLATFORM_MACCATALYST || explicitlyLinked)1825return false;1826return is_contained(interface.targets(),1827MachO::Target(config->arch(), PLATFORM_MACOS));1828}18291830static bool isArchABICompatible(ArchitectureSet archSet,1831Architecture targetArch) {1832uint32_t cpuType;1833uint32_t targetCpuType;1834std::tie(targetCpuType, std::ignore) = getCPUTypeFromArchitecture(targetArch);18351836return llvm::any_of(archSet, [&](const auto &p) {1837std::tie(cpuType, std::ignore) = getCPUTypeFromArchitecture(p);1838return cpuType == targetCpuType;1839});1840}18411842static bool isTargetPlatformArchCompatible(1843InterfaceFile::const_target_range interfaceTargets, Target target) {1844if (is_contained(interfaceTargets, target))1845return true;18461847if (config->forceExactCpuSubtypeMatch)1848return false;18491850ArchitectureSet archSet;1851for (const auto &p : interfaceTargets)1852if (p.Platform == target.Platform)1853archSet.set(p.Arch);1854if (archSet.empty())1855return false;18561857return isArchABICompatible(archSet, target.Arch);1858}18591860DylibFile::DylibFile(const InterfaceFile &interface, DylibFile *umbrella,1861bool isBundleLoader, bool explicitlyLinked)1862: InputFile(DylibKind, interface), refState(RefState::Unreferenced),1863explicitlyLinked(explicitlyLinked), isBundleLoader(isBundleLoader) {1864// FIXME: Add test for the missing TBD code path.18651866if (umbrella == nullptr)1867umbrella = this;1868this->umbrella = umbrella;18691870installName = saver().save(interface.getInstallName());1871compatibilityVersion = interface.getCompatibilityVersion().rawValue();1872currentVersion = interface.getCurrentVersion().rawValue();18731874if (config->printEachFile)1875message(toString(this));1876inputFiles.insert(this);18771878if (!is_contained(skipPlatformChecks, installName) &&1879!isTargetPlatformArchCompatible(interface.targets(),1880config->platformInfo.target) &&1881!skipPlatformCheckForCatalyst(interface, explicitlyLinked)) {1882error(toString(this) + " is incompatible with " +1883std::string(config->platformInfo.target));1884return;1885}18861887checkAppExtensionSafety(interface.isApplicationExtensionSafe());18881889bool canBeImplicitlyLinked = interface.allowableClients().size() == 0;1890exportingFile = (canBeImplicitlyLinked && isImplicitlyLinked(installName))1891? this1892: umbrella;1893auto addSymbol = [&](const llvm::MachO::Symbol &symbol,1894const Twine &name) -> void {1895StringRef savedName = saver().save(name);1896if (exportingFile->hiddenSymbols.contains(CachedHashStringRef(savedName)))1897return;18981899symbols.push_back(symtab->addDylib(savedName, exportingFile,1900symbol.isWeakDefined(),1901symbol.isThreadLocalValue()));1902};19031904std::vector<const llvm::MachO::Symbol *> normalSymbols;1905normalSymbols.reserve(interface.symbolsCount());1906for (const auto *symbol : interface.symbols()) {1907if (!isArchABICompatible(symbol->getArchitectures(), config->arch()))1908continue;1909if (handleLDSymbol(symbol->getName()))1910continue;19111912switch (symbol->getKind()) {1913case EncodeKind::GlobalSymbol:1914case EncodeKind::ObjectiveCClass:1915case EncodeKind::ObjectiveCClassEHType:1916case EncodeKind::ObjectiveCInstanceVariable:1917normalSymbols.push_back(symbol);1918}1919}1920// interface.symbols() order is non-deterministic.1921llvm::sort(normalSymbols,1922[](auto *l, auto *r) { return l->getName() < r->getName(); });19231924// TODO(compnerd) filter out symbols based on the target platform1925for (const auto *symbol : normalSymbols) {1926switch (symbol->getKind()) {1927case EncodeKind::GlobalSymbol:1928addSymbol(*symbol, symbol->getName());1929break;1930case EncodeKind::ObjectiveCClass:1931// XXX ld64 only creates these symbols when -ObjC is passed in. We may1932// want to emulate that.1933addSymbol(*symbol, objc::symbol_names::klass + symbol->getName());1934addSymbol(*symbol, objc::symbol_names::metaclass + symbol->getName());1935break;1936case EncodeKind::ObjectiveCClassEHType:1937addSymbol(*symbol, objc::symbol_names::ehtype + symbol->getName());1938break;1939case EncodeKind::ObjectiveCInstanceVariable:1940addSymbol(*symbol, objc::symbol_names::ivar + symbol->getName());1941break;1942}1943}1944}19451946DylibFile::DylibFile(DylibFile *umbrella)1947: InputFile(DylibKind, MemoryBufferRef{}), refState(RefState::Unreferenced),1948explicitlyLinked(false), isBundleLoader(false) {1949if (umbrella == nullptr)1950umbrella = this;1951this->umbrella = umbrella;1952}19531954void DylibFile::parseReexports(const InterfaceFile &interface) {1955const InterfaceFile *topLevel =1956interface.getParent() == nullptr ? &interface : interface.getParent();1957for (const InterfaceFileRef &intfRef : interface.reexportedLibraries()) {1958InterfaceFile::const_target_range targets = intfRef.targets();1959if (is_contained(skipPlatformChecks, intfRef.getInstallName()) ||1960isTargetPlatformArchCompatible(targets, config->platformInfo.target))1961loadReexport(intfRef.getInstallName(), exportingFile, topLevel);1962}1963}19641965bool DylibFile::isExplicitlyLinked() const {1966if (!explicitlyLinked)1967return false;19681969// If this dylib was explicitly linked, but at least one of the symbols1970// of the synthetic dylibs it created via $ld$previous symbols is1971// referenced, then that synthetic dylib fulfils the explicit linkedness1972// and we can deadstrip this dylib if it's unreferenced.1973for (const auto *dylib : extraDylibs)1974if (dylib->isReferenced())1975return false;19761977return true;1978}19791980DylibFile *DylibFile::getSyntheticDylib(StringRef installName,1981uint32_t currentVersion,1982uint32_t compatVersion) {1983for (DylibFile *dylib : extraDylibs)1984if (dylib->installName == installName) {1985// FIXME: Check what to do if different $ld$previous symbols1986// request the same dylib, but with different versions.1987return dylib;1988}19891990auto *dylib = make<DylibFile>(umbrella == this ? nullptr : umbrella);1991dylib->installName = saver().save(installName);1992dylib->currentVersion = currentVersion;1993dylib->compatibilityVersion = compatVersion;1994extraDylibs.push_back(dylib);1995return dylib;1996}19971998// $ld$ symbols modify the properties/behavior of the library (e.g. its install1999// name, compatibility version or hide/add symbols) for specific target2000// versions.2001bool DylibFile::handleLDSymbol(StringRef originalName) {2002if (!originalName.starts_with("$ld$"))2003return false;20042005StringRef action;2006StringRef name;2007std::tie(action, name) = originalName.drop_front(strlen("$ld$")).split('$');2008if (action == "previous")2009handleLDPreviousSymbol(name, originalName);2010else if (action == "install_name")2011handleLDInstallNameSymbol(name, originalName);2012else if (action == "hide")2013handleLDHideSymbol(name, originalName);2014return true;2015}20162017void DylibFile::handleLDPreviousSymbol(StringRef name, StringRef originalName) {2018// originalName: $ld$ previous $ <installname> $ <compatversion> $2019// <platformstr> $ <startversion> $ <endversion> $ <symbol-name> $2020StringRef installName;2021StringRef compatVersion;2022StringRef platformStr;2023StringRef startVersion;2024StringRef endVersion;2025StringRef symbolName;2026StringRef rest;20272028std::tie(installName, name) = name.split('$');2029std::tie(compatVersion, name) = name.split('$');2030std::tie(platformStr, name) = name.split('$');2031std::tie(startVersion, name) = name.split('$');2032std::tie(endVersion, name) = name.split('$');2033std::tie(symbolName, rest) = name.rsplit('$');20342035// FIXME: Does this do the right thing for zippered files?2036unsigned platform;2037if (platformStr.getAsInteger(10, platform) ||2038platform != static_cast<unsigned>(config->platform()))2039return;20402041VersionTuple start;2042if (start.tryParse(startVersion)) {2043warn(toString(this) + ": failed to parse start version, symbol '" +2044originalName + "' ignored");2045return;2046}2047VersionTuple end;2048if (end.tryParse(endVersion)) {2049warn(toString(this) + ": failed to parse end version, symbol '" +2050originalName + "' ignored");2051return;2052}2053if (config->platformInfo.target.MinDeployment < start ||2054config->platformInfo.target.MinDeployment >= end)2055return;20562057// Initialized to compatibilityVersion for the symbolName branch below.2058uint32_t newCompatibilityVersion = compatibilityVersion;2059uint32_t newCurrentVersionForSymbol = currentVersion;2060if (!compatVersion.empty()) {2061VersionTuple cVersion;2062if (cVersion.tryParse(compatVersion)) {2063warn(toString(this) +2064": failed to parse compatibility version, symbol '" + originalName +2065"' ignored");2066return;2067}2068newCompatibilityVersion = encodeVersion(cVersion);2069newCurrentVersionForSymbol = newCompatibilityVersion;2070}20712072if (!symbolName.empty()) {2073// A $ld$previous$ symbol with symbol name adds a symbol with that name to2074// a dylib with given name and version.2075auto *dylib = getSyntheticDylib(installName, newCurrentVersionForSymbol,2076newCompatibilityVersion);20772078// The tbd file usually contains the $ld$previous symbol for an old version,2079// and then the symbol itself later, for newer deployment targets, like so:2080// symbols: [2081// '$ld$previous$/Another$$1$3.0$14.0$_zzz$',2082// _zzz,2083// ]2084// Since the symbols are sorted, adding them to the symtab in the given2085// order means the $ld$previous version of _zzz will prevail, as desired.2086dylib->symbols.push_back(symtab->addDylib(2087saver().save(symbolName), dylib, /*isWeakDef=*/false, /*isTlv=*/false));2088return;2089}20902091// A $ld$previous$ symbol without symbol name modifies the dylib it's in.2092this->installName = saver().save(installName);2093this->compatibilityVersion = newCompatibilityVersion;2094}20952096void DylibFile::handleLDInstallNameSymbol(StringRef name,2097StringRef originalName) {2098// originalName: $ld$ install_name $ os<version> $ install_name2099StringRef condition, installName;2100std::tie(condition, installName) = name.split('$');2101VersionTuple version;2102if (!condition.consume_front("os") || version.tryParse(condition))2103warn(toString(this) + ": failed to parse os version, symbol '" +2104originalName + "' ignored");2105else if (version == config->platformInfo.target.MinDeployment)2106this->installName = saver().save(installName);2107}21082109void DylibFile::handleLDHideSymbol(StringRef name, StringRef originalName) {2110StringRef symbolName;2111bool shouldHide = true;2112if (name.starts_with("os")) {2113// If it's hidden based on versions.2114name = name.drop_front(2);2115StringRef minVersion;2116std::tie(minVersion, symbolName) = name.split('$');2117VersionTuple versionTup;2118if (versionTup.tryParse(minVersion)) {2119warn(toString(this) + ": failed to parse hidden version, symbol `" + originalName +2120"` ignored.");2121return;2122}2123shouldHide = versionTup == config->platformInfo.target.MinDeployment;2124} else {2125symbolName = name;2126}21272128if (shouldHide)2129exportingFile->hiddenSymbols.insert(CachedHashStringRef(symbolName));2130}21312132void DylibFile::checkAppExtensionSafety(bool dylibIsAppExtensionSafe) const {2133if (config->applicationExtension && !dylibIsAppExtensionSafe)2134warn("using '-application_extension' with unsafe dylib: " + toString(this));2135}21362137ArchiveFile::ArchiveFile(std::unique_ptr<object::Archive> &&f, bool forceHidden)2138: InputFile(ArchiveKind, f->getMemoryBufferRef()), file(std::move(f)),2139forceHidden(forceHidden) {}21402141void ArchiveFile::addLazySymbols() {2142// Avoid calling getMemoryBufferRef() on zero-symbol archive2143// since that crashes.2144if (file->isEmpty() || file->getNumberOfSymbols() == 0)2145return;21462147Error err = Error::success();2148auto child = file->child_begin(err);2149// Ignore the I/O error here - will be reported later.2150if (!err) {2151Expected<MemoryBufferRef> mbOrErr = child->getMemoryBufferRef();2152if (!mbOrErr) {2153llvm::consumeError(mbOrErr.takeError());2154} else {2155if (identify_magic(mbOrErr->getBuffer()) == file_magic::macho_object) {2156if (target->wordSize == 8)2157compatArch = compatWithTargetArch(2158this, reinterpret_cast<const LP64::mach_header *>(2159mbOrErr->getBufferStart()));2160else2161compatArch = compatWithTargetArch(2162this, reinterpret_cast<const ILP32::mach_header *>(2163mbOrErr->getBufferStart()));2164if (!compatArch)2165return;2166}2167}2168}21692170for (const object::Archive::Symbol &sym : file->symbols())2171symtab->addLazyArchive(sym.getName(), this, sym);2172}21732174static Expected<InputFile *>2175loadArchiveMember(MemoryBufferRef mb, uint32_t modTime, StringRef archiveName,2176uint64_t offsetInArchive, bool forceHidden, bool compatArch) {2177if (config->zeroModTime)2178modTime = 0;21792180switch (identify_magic(mb.getBuffer())) {2181case file_magic::macho_object:2182return make<ObjFile>(mb, modTime, archiveName, /*lazy=*/false, forceHidden,2183compatArch);2184case file_magic::bitcode:2185return make<BitcodeFile>(mb, archiveName, offsetInArchive, /*lazy=*/false,2186forceHidden, compatArch);2187default:2188return createStringError(inconvertibleErrorCode(),2189mb.getBufferIdentifier() +2190" has unhandled file type");2191}2192}21932194Error ArchiveFile::fetch(const object::Archive::Child &c, StringRef reason) {2195if (!seen.insert(c.getChildOffset()).second)2196return Error::success();21972198Expected<MemoryBufferRef> mb = c.getMemoryBufferRef();2199if (!mb)2200return mb.takeError();22012202Expected<TimePoint<std::chrono::seconds>> modTime = c.getLastModified();2203if (!modTime)2204return modTime.takeError();22052206Expected<InputFile *> file =2207loadArchiveMember(*mb, toTimeT(*modTime), getName(), c.getChildOffset(),2208forceHidden, compatArch);22092210if (!file)2211return file.takeError();22122213inputFiles.insert(*file);2214printArchiveMemberLoad(reason, *file);2215return Error::success();2216}22172218void ArchiveFile::fetch(const object::Archive::Symbol &sym) {2219object::Archive::Child c =2220CHECK(sym.getMember(), toString(this) +2221": could not get the member defining symbol " +2222toMachOString(sym));22232224// `sym` is owned by a LazySym, which will be replace<>()d by make<ObjFile>2225// and become invalid after that call. Copy it to the stack so we can refer2226// to it later.2227const object::Archive::Symbol symCopy = sym;22282229// ld64 doesn't demangle sym here even with -demangle.2230// Match that: intentionally don't call toMachOString().2231if (Error e = fetch(c, symCopy.getName()))2232error(toString(this) + ": could not get the member defining symbol " +2233toMachOString(symCopy) + ": " + toString(std::move(e)));2234}22352236static macho::Symbol *createBitcodeSymbol(const lto::InputFile::Symbol &objSym,2237BitcodeFile &file) {2238StringRef name = saver().save(objSym.getName());22392240if (objSym.isUndefined())2241return symtab->addUndefined(name, &file, /*isWeakRef=*/objSym.isWeak());22422243// TODO: Write a test demonstrating why computing isPrivateExtern before2244// LTO compilation is important.2245bool isPrivateExtern = false;2246switch (objSym.getVisibility()) {2247case GlobalValue::HiddenVisibility:2248isPrivateExtern = true;2249break;2250case GlobalValue::ProtectedVisibility:2251error(name + " has protected visibility, which is not supported by Mach-O");2252break;2253case GlobalValue::DefaultVisibility:2254break;2255}2256isPrivateExtern = isPrivateExtern || objSym.canBeOmittedFromSymbolTable() ||2257file.forceHidden;22582259if (objSym.isCommon())2260return symtab->addCommon(name, &file, objSym.getCommonSize(),2261objSym.getCommonAlignment(), isPrivateExtern);22622263return symtab->addDefined(name, &file, /*isec=*/nullptr, /*value=*/0,2264/*size=*/0, objSym.isWeak(), isPrivateExtern,2265/*isReferencedDynamically=*/false,2266/*noDeadStrip=*/false,2267/*isWeakDefCanBeHidden=*/false);2268}22692270BitcodeFile::BitcodeFile(MemoryBufferRef mb, StringRef archiveName,2271uint64_t offsetInArchive, bool lazy, bool forceHidden,2272bool compatArch)2273: InputFile(BitcodeKind, mb, lazy), forceHidden(forceHidden) {2274this->archiveName = std::string(archiveName);2275this->compatArch = compatArch;2276std::string path = mb.getBufferIdentifier().str();2277if (config->thinLTOIndexOnly)2278path = replaceThinLTOSuffix(mb.getBufferIdentifier());22792280// If the parent archive already determines that the arch is not compat with2281// target, then just return.2282if (!compatArch)2283return;22842285// ThinLTO assumes that all MemoryBufferRefs given to it have a unique2286// name. If two members with the same name are provided, this causes a2287// collision and ThinLTO can't proceed.2288// So, we append the archive name to disambiguate two members with the same2289// name from multiple different archives, and offset within the archive to2290// disambiguate two members of the same name from a single archive.2291MemoryBufferRef mbref(mb.getBuffer(),2292saver().save(archiveName.empty()2293? path2294: archiveName + "(" +2295sys::path::filename(path) + ")" +2296utostr(offsetInArchive)));2297obj = check(lto::InputFile::create(mbref));2298if (lazy)2299parseLazy();2300else2301parse();2302}23032304void BitcodeFile::parse() {2305// Convert LTO Symbols to LLD Symbols in order to perform resolution. The2306// "winning" symbol will then be marked as Prevailing at LTO compilation2307// time.2308symbols.resize(obj->symbols().size());23092310// Process defined symbols first. See the comment at the end of2311// ObjFile<>::parseSymbols.2312for (auto it : llvm::enumerate(obj->symbols()))2313if (!it.value().isUndefined())2314symbols[it.index()] = createBitcodeSymbol(it.value(), *this);2315for (auto it : llvm::enumerate(obj->symbols()))2316if (it.value().isUndefined())2317symbols[it.index()] = createBitcodeSymbol(it.value(), *this);2318}23192320void BitcodeFile::parseLazy() {2321symbols.resize(obj->symbols().size());2322for (const auto &[i, objSym] : llvm::enumerate(obj->symbols())) {2323if (!objSym.isUndefined()) {2324symbols[i] = symtab->addLazyObject(saver().save(objSym.getName()), *this);2325if (!lazy)2326break;2327}2328}2329}23302331std::string macho::replaceThinLTOSuffix(StringRef path) {2332auto [suffix, repl] = config->thinLTOObjectSuffixReplace;2333if (path.consume_back(suffix))2334return (path + repl).str();2335return std::string(path);2336}23372338void macho::extract(InputFile &file, StringRef reason) {2339if (!file.lazy)2340return;2341file.lazy = false;23422343printArchiveMemberLoad(reason, &file);2344if (auto *bitcode = dyn_cast<BitcodeFile>(&file)) {2345bitcode->parse();2346} else {2347auto &f = cast<ObjFile>(file);2348if (target->wordSize == 8)2349f.parse<LP64>();2350else2351f.parse<ILP32>();2352}2353}23542355template void ObjFile::parse<LP64>();235623572358