15ffd83dbSDimitry Andric //===- InputFiles.cpp -----------------------------------------------------===// 25ffd83dbSDimitry Andric // 35ffd83dbSDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 45ffd83dbSDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 55ffd83dbSDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 65ffd83dbSDimitry Andric // 75ffd83dbSDimitry Andric //===----------------------------------------------------------------------===// 85ffd83dbSDimitry Andric // 95ffd83dbSDimitry Andric // This file contains functions to parse Mach-O object files. In this comment, 105ffd83dbSDimitry Andric // we describe the Mach-O file structure and how we parse it. 115ffd83dbSDimitry Andric // 125ffd83dbSDimitry Andric // Mach-O is not very different from ELF or COFF. The notion of symbols, 135ffd83dbSDimitry Andric // sections and relocations exists in Mach-O as it does in ELF and COFF. 145ffd83dbSDimitry Andric // 155ffd83dbSDimitry Andric // Perhaps the notion that is new to those who know ELF/COFF is "subsections". 165ffd83dbSDimitry Andric // In ELF/COFF, sections are an atomic unit of data copied from input files to 175ffd83dbSDimitry Andric // output files. When we merge or garbage-collect sections, we treat each 185ffd83dbSDimitry Andric // section as an atomic unit. In Mach-O, that's not the case. Sections can 195ffd83dbSDimitry Andric // consist of multiple subsections, and subsections are a unit of merging and 205ffd83dbSDimitry Andric // garbage-collecting. Therefore, Mach-O's subsections are more similar to 215ffd83dbSDimitry Andric // ELF/COFF's sections than Mach-O's sections are. 225ffd83dbSDimitry Andric // 235ffd83dbSDimitry Andric // A section can have multiple symbols. A symbol that does not have the 245ffd83dbSDimitry Andric // N_ALT_ENTRY attribute indicates a beginning of a subsection. Therefore, by 255ffd83dbSDimitry Andric // definition, a symbol is always present at the beginning of each subsection. A 265ffd83dbSDimitry Andric // symbol with N_ALT_ENTRY attribute does not start a new subsection and can 275ffd83dbSDimitry Andric // point to a middle of a subsection. 285ffd83dbSDimitry Andric // 295ffd83dbSDimitry Andric // The notion of subsections also affects how relocations are represented in 305ffd83dbSDimitry Andric // Mach-O. All references within a section need to be explicitly represented as 315ffd83dbSDimitry Andric // relocations if they refer to different subsections, because we obviously need 325ffd83dbSDimitry Andric // to fix up addresses if subsections are laid out in an output file differently 335ffd83dbSDimitry Andric // than they were in object files. To represent that, Mach-O relocations can 345ffd83dbSDimitry Andric // refer to an unnamed location via its address. Scattered relocations (those 355ffd83dbSDimitry Andric // with the R_SCATTERED bit set) always refer to unnamed locations. 365ffd83dbSDimitry Andric // Non-scattered relocations refer to an unnamed location if r_extern is not set 375ffd83dbSDimitry Andric // and r_symbolnum is zero. 385ffd83dbSDimitry Andric // 395ffd83dbSDimitry Andric // Without the above differences, I think you can use your knowledge about ELF 405ffd83dbSDimitry Andric // and COFF for Mach-O. 415ffd83dbSDimitry Andric // 425ffd83dbSDimitry Andric //===----------------------------------------------------------------------===// 435ffd83dbSDimitry Andric 445ffd83dbSDimitry Andric #include "InputFiles.h" 455ffd83dbSDimitry Andric #include "Config.h" 46e8d8bef9SDimitry Andric #include "Driver.h" 47e8d8bef9SDimitry Andric #include "Dwarf.h" 4881ad6265SDimitry Andric #include "EhFrame.h" 495ffd83dbSDimitry Andric #include "ExportTrie.h" 505ffd83dbSDimitry Andric #include "InputSection.h" 515ffd83dbSDimitry Andric #include "MachOStructs.h" 52e8d8bef9SDimitry Andric #include "ObjC.h" 535ffd83dbSDimitry Andric #include "OutputSection.h" 54e8d8bef9SDimitry Andric #include "OutputSegment.h" 555ffd83dbSDimitry Andric #include "SymbolTable.h" 565ffd83dbSDimitry Andric #include "Symbols.h" 57fe6060f1SDimitry Andric #include "SyntheticSections.h" 585ffd83dbSDimitry Andric #include "Target.h" 595ffd83dbSDimitry Andric 6004eeddc0SDimitry Andric #include "lld/Common/CommonLinkerContext.h" 61e8d8bef9SDimitry Andric #include "lld/Common/DWARF.h" 62e8d8bef9SDimitry Andric #include "lld/Common/Reproduce.h" 63e8d8bef9SDimitry Andric #include "llvm/ADT/iterator.h" 645ffd83dbSDimitry Andric #include "llvm/BinaryFormat/MachO.h" 65e8d8bef9SDimitry Andric #include "llvm/LTO/LTO.h" 6604eeddc0SDimitry Andric #include "llvm/Support/BinaryStreamReader.h" 675ffd83dbSDimitry Andric #include "llvm/Support/Endian.h" 6881ad6265SDimitry Andric #include "llvm/Support/LEB128.h" 695ffd83dbSDimitry Andric #include "llvm/Support/MemoryBuffer.h" 705ffd83dbSDimitry Andric #include "llvm/Support/Path.h" 71e8d8bef9SDimitry Andric #include "llvm/Support/TarWriter.h" 7204eeddc0SDimitry Andric #include "llvm/Support/TimeProfiler.h" 73fe6060f1SDimitry Andric #include "llvm/TextAPI/Architecture.h" 74fe6060f1SDimitry Andric #include "llvm/TextAPI/InterfaceFile.h" 755ffd83dbSDimitry Andric 76*bdd1243dSDimitry Andric #include <optional> 77349cc55cSDimitry Andric #include <type_traits> 78349cc55cSDimitry Andric 795ffd83dbSDimitry Andric using namespace llvm; 805ffd83dbSDimitry Andric using namespace llvm::MachO; 815ffd83dbSDimitry Andric using namespace llvm::support::endian; 825ffd83dbSDimitry Andric using namespace llvm::sys; 835ffd83dbSDimitry Andric using namespace lld; 845ffd83dbSDimitry Andric using namespace lld::macho; 855ffd83dbSDimitry Andric 86e8d8bef9SDimitry Andric // Returns "<internal>", "foo.a(bar.o)", or "baz.o". 87e8d8bef9SDimitry Andric std::string lld::toString(const InputFile *f) { 88e8d8bef9SDimitry Andric if (!f) 89e8d8bef9SDimitry Andric return "<internal>"; 90fe6060f1SDimitry Andric 91fe6060f1SDimitry Andric // Multiple dylibs can be defined in one .tbd file. 92fe6060f1SDimitry Andric if (auto dylibFile = dyn_cast<DylibFile>(f)) 93fe6060f1SDimitry Andric if (f->getName().endswith(".tbd")) 94fe6060f1SDimitry Andric return (f->getName() + "(" + dylibFile->installName + ")").str(); 95fe6060f1SDimitry Andric 96e8d8bef9SDimitry Andric if (f->archiveName.empty()) 97e8d8bef9SDimitry Andric return std::string(f->getName()); 98fe6060f1SDimitry Andric return (f->archiveName + "(" + path::filename(f->getName()) + ")").str(); 99e8d8bef9SDimitry Andric } 100e8d8bef9SDimitry Andric 10181ad6265SDimitry Andric std::string lld::toString(const Section &sec) { 10281ad6265SDimitry Andric return (toString(sec.file) + ":(" + sec.name + ")").str(); 10381ad6265SDimitry Andric } 10481ad6265SDimitry Andric 105e8d8bef9SDimitry Andric SetVector<InputFile *> macho::inputFiles; 106e8d8bef9SDimitry Andric std::unique_ptr<TarWriter> macho::tar; 107e8d8bef9SDimitry Andric int InputFile::idCount = 0; 1085ffd83dbSDimitry Andric 109fe6060f1SDimitry Andric static VersionTuple decodeVersion(uint32_t version) { 110fe6060f1SDimitry Andric unsigned major = version >> 16; 111fe6060f1SDimitry Andric unsigned minor = (version >> 8) & 0xffu; 112fe6060f1SDimitry Andric unsigned subMinor = version & 0xffu; 113fe6060f1SDimitry Andric return VersionTuple(major, minor, subMinor); 114fe6060f1SDimitry Andric } 115fe6060f1SDimitry Andric 116fe6060f1SDimitry Andric static std::vector<PlatformInfo> getPlatformInfos(const InputFile *input) { 117fe6060f1SDimitry Andric if (!isa<ObjFile>(input) && !isa<DylibFile>(input)) 118fe6060f1SDimitry Andric return {}; 119fe6060f1SDimitry Andric 120fe6060f1SDimitry Andric const char *hdr = input->mb.getBufferStart(); 121fe6060f1SDimitry Andric 12281ad6265SDimitry Andric // "Zippered" object files can have multiple LC_BUILD_VERSION load commands. 123fe6060f1SDimitry Andric std::vector<PlatformInfo> platformInfos; 124fe6060f1SDimitry Andric for (auto *cmd : findCommands<build_version_command>(hdr, LC_BUILD_VERSION)) { 125fe6060f1SDimitry Andric PlatformInfo info; 12604eeddc0SDimitry Andric info.target.Platform = static_cast<PlatformType>(cmd->platform); 127fe6060f1SDimitry Andric info.minimum = decodeVersion(cmd->minos); 128fe6060f1SDimitry Andric platformInfos.emplace_back(std::move(info)); 129fe6060f1SDimitry Andric } 130fe6060f1SDimitry Andric for (auto *cmd : findCommands<version_min_command>( 131fe6060f1SDimitry Andric hdr, LC_VERSION_MIN_MACOSX, LC_VERSION_MIN_IPHONEOS, 132fe6060f1SDimitry Andric LC_VERSION_MIN_TVOS, LC_VERSION_MIN_WATCHOS)) { 133fe6060f1SDimitry Andric PlatformInfo info; 134fe6060f1SDimitry Andric switch (cmd->cmd) { 135fe6060f1SDimitry Andric case LC_VERSION_MIN_MACOSX: 13604eeddc0SDimitry Andric info.target.Platform = PLATFORM_MACOS; 137fe6060f1SDimitry Andric break; 138fe6060f1SDimitry Andric case LC_VERSION_MIN_IPHONEOS: 13904eeddc0SDimitry Andric info.target.Platform = PLATFORM_IOS; 140fe6060f1SDimitry Andric break; 141fe6060f1SDimitry Andric case LC_VERSION_MIN_TVOS: 14204eeddc0SDimitry Andric info.target.Platform = PLATFORM_TVOS; 143fe6060f1SDimitry Andric break; 144fe6060f1SDimitry Andric case LC_VERSION_MIN_WATCHOS: 14504eeddc0SDimitry Andric info.target.Platform = PLATFORM_WATCHOS; 146fe6060f1SDimitry Andric break; 147fe6060f1SDimitry Andric } 148fe6060f1SDimitry Andric info.minimum = decodeVersion(cmd->version); 149fe6060f1SDimitry Andric platformInfos.emplace_back(std::move(info)); 150fe6060f1SDimitry Andric } 151fe6060f1SDimitry Andric 152fe6060f1SDimitry Andric return platformInfos; 153fe6060f1SDimitry Andric } 154fe6060f1SDimitry Andric 155fe6060f1SDimitry Andric static bool checkCompatibility(const InputFile *input) { 156fe6060f1SDimitry Andric std::vector<PlatformInfo> platformInfos = getPlatformInfos(input); 157fe6060f1SDimitry Andric if (platformInfos.empty()) 158fe6060f1SDimitry Andric return true; 159fe6060f1SDimitry Andric 160fe6060f1SDimitry Andric auto it = find_if(platformInfos, [&](const PlatformInfo &info) { 161fe6060f1SDimitry Andric return removeSimulator(info.target.Platform) == 162fe6060f1SDimitry Andric removeSimulator(config->platform()); 163fe6060f1SDimitry Andric }); 164fe6060f1SDimitry Andric if (it == platformInfos.end()) { 165fe6060f1SDimitry Andric std::string platformNames; 166fe6060f1SDimitry Andric raw_string_ostream os(platformNames); 167fe6060f1SDimitry Andric interleave( 168fe6060f1SDimitry Andric platformInfos, os, 169fe6060f1SDimitry Andric [&](const PlatformInfo &info) { 170fe6060f1SDimitry Andric os << getPlatformName(info.target.Platform); 171fe6060f1SDimitry Andric }, 172fe6060f1SDimitry Andric "/"); 173fe6060f1SDimitry Andric error(toString(input) + " has platform " + platformNames + 174fe6060f1SDimitry Andric Twine(", which is different from target platform ") + 175fe6060f1SDimitry Andric getPlatformName(config->platform())); 176fe6060f1SDimitry Andric return false; 177fe6060f1SDimitry Andric } 178fe6060f1SDimitry Andric 179fe6060f1SDimitry Andric if (it->minimum > config->platformInfo.minimum) 180fe6060f1SDimitry Andric warn(toString(input) + " has version " + it->minimum.getAsString() + 181fe6060f1SDimitry Andric ", which is newer than target minimum of " + 182fe6060f1SDimitry Andric config->platformInfo.minimum.getAsString()); 183fe6060f1SDimitry Andric 184fe6060f1SDimitry Andric return true; 185fe6060f1SDimitry Andric } 186fe6060f1SDimitry Andric 187349cc55cSDimitry Andric // This cache mostly exists to store system libraries (and .tbds) as they're 188349cc55cSDimitry Andric // loaded, rather than the input archives, which are already cached at a higher 189349cc55cSDimitry Andric // level, and other files like the filelist that are only read once. 190349cc55cSDimitry Andric // Theoretically this caching could be more efficient by hoisting it, but that 191349cc55cSDimitry Andric // would require altering many callers to track the state. 192349cc55cSDimitry Andric DenseMap<CachedHashStringRef, MemoryBufferRef> macho::cachedReads; 1935ffd83dbSDimitry Andric // Open a given file path and return it as a memory-mapped file. 194*bdd1243dSDimitry Andric std::optional<MemoryBufferRef> macho::readFile(StringRef path) { 195349cc55cSDimitry Andric CachedHashStringRef key(path); 196349cc55cSDimitry Andric auto entry = cachedReads.find(key); 197349cc55cSDimitry Andric if (entry != cachedReads.end()) 198349cc55cSDimitry Andric return entry->second; 199349cc55cSDimitry Andric 200fe6060f1SDimitry Andric ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr = MemoryBuffer::getFile(path); 201fe6060f1SDimitry Andric if (std::error_code ec = mbOrErr.getError()) { 2025ffd83dbSDimitry Andric error("cannot open " + path + ": " + ec.message()); 203*bdd1243dSDimitry Andric return std::nullopt; 2045ffd83dbSDimitry Andric } 2055ffd83dbSDimitry Andric 2065ffd83dbSDimitry Andric std::unique_ptr<MemoryBuffer> &mb = *mbOrErr; 2075ffd83dbSDimitry Andric MemoryBufferRef mbref = mb->getMemBufferRef(); 2085ffd83dbSDimitry Andric make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take mb ownership 2095ffd83dbSDimitry Andric 2105ffd83dbSDimitry Andric // If this is a regular non-fat file, return it. 2115ffd83dbSDimitry Andric const char *buf = mbref.getBufferStart(); 212fe6060f1SDimitry Andric const auto *hdr = reinterpret_cast<const fat_header *>(buf); 213fe6060f1SDimitry Andric if (mbref.getBufferSize() < sizeof(uint32_t) || 214fe6060f1SDimitry Andric read32be(&hdr->magic) != FAT_MAGIC) { 215e8d8bef9SDimitry Andric if (tar) 216e8d8bef9SDimitry Andric tar->append(relativeToRoot(path), mbref.getBuffer()); 217349cc55cSDimitry Andric return cachedReads[key] = mbref; 218e8d8bef9SDimitry Andric } 2195ffd83dbSDimitry Andric 22004eeddc0SDimitry Andric llvm::BumpPtrAllocator &bAlloc = lld::bAlloc(); 22104eeddc0SDimitry Andric 222fe6060f1SDimitry Andric // Object files and archive files may be fat files, which contain multiple 223fe6060f1SDimitry Andric // real files for different CPU ISAs. Here, we search for a file that matches 224fe6060f1SDimitry Andric // with the current link target and returns it as a MemoryBufferRef. 225fe6060f1SDimitry Andric const auto *arch = reinterpret_cast<const fat_arch *>(buf + sizeof(*hdr)); 226*bdd1243dSDimitry Andric auto getArchName = [](uint32_t cpuType, uint32_t cpuSubtype) { 227*bdd1243dSDimitry Andric return getArchitectureName(getArchitectureFromCpuType(cpuType, cpuSubtype)); 228*bdd1243dSDimitry Andric }; 2295ffd83dbSDimitry Andric 230*bdd1243dSDimitry Andric std::vector<StringRef> archs; 2315ffd83dbSDimitry Andric for (uint32_t i = 0, n = read32be(&hdr->nfat_arch); i < n; ++i) { 2325ffd83dbSDimitry Andric if (reinterpret_cast<const char *>(arch + i + 1) > 2335ffd83dbSDimitry Andric buf + mbref.getBufferSize()) { 2345ffd83dbSDimitry Andric error(path + ": fat_arch struct extends beyond end of file"); 235*bdd1243dSDimitry Andric return std::nullopt; 2365ffd83dbSDimitry Andric } 2375ffd83dbSDimitry Andric 238*bdd1243dSDimitry Andric uint32_t cpuType = read32be(&arch[i].cputype); 239*bdd1243dSDimitry Andric uint32_t cpuSubtype = 240*bdd1243dSDimitry Andric read32be(&arch[i].cpusubtype) & ~MachO::CPU_SUBTYPE_MASK; 241*bdd1243dSDimitry Andric 242*bdd1243dSDimitry Andric // FIXME: LD64 has a more complex fallback logic here. 243*bdd1243dSDimitry Andric // Consider implementing that as well? 244*bdd1243dSDimitry Andric if (cpuType != static_cast<uint32_t>(target->cpuType) || 245*bdd1243dSDimitry Andric cpuSubtype != target->cpuSubtype) { 246*bdd1243dSDimitry Andric archs.emplace_back(getArchName(cpuType, cpuSubtype)); 2475ffd83dbSDimitry Andric continue; 248*bdd1243dSDimitry Andric } 2495ffd83dbSDimitry Andric 2505ffd83dbSDimitry Andric uint32_t offset = read32be(&arch[i].offset); 2515ffd83dbSDimitry Andric uint32_t size = read32be(&arch[i].size); 2525ffd83dbSDimitry Andric if (offset + size > mbref.getBufferSize()) 2535ffd83dbSDimitry Andric error(path + ": slice extends beyond end of file"); 254e8d8bef9SDimitry Andric if (tar) 255e8d8bef9SDimitry Andric tar->append(relativeToRoot(path), mbref.getBuffer()); 256349cc55cSDimitry Andric return cachedReads[key] = MemoryBufferRef(StringRef(buf + offset, size), 257349cc55cSDimitry Andric path.copy(bAlloc)); 2585ffd83dbSDimitry Andric } 2595ffd83dbSDimitry Andric 260*bdd1243dSDimitry Andric auto targetArchName = getArchName(target->cpuType, target->cpuSubtype); 261*bdd1243dSDimitry Andric warn(path + ": ignoring file because it is universal (" + join(archs, ",") + 262*bdd1243dSDimitry Andric ") but does not contain the " + targetArchName + " architecture"); 263*bdd1243dSDimitry Andric return std::nullopt; 2645ffd83dbSDimitry Andric } 2655ffd83dbSDimitry Andric 266fe6060f1SDimitry Andric InputFile::InputFile(Kind kind, const InterfaceFile &interface) 26704eeddc0SDimitry Andric : id(idCount++), fileKind(kind), name(saver().save(interface.getPath())) {} 2685ffd83dbSDimitry Andric 269349cc55cSDimitry Andric // Some sections comprise of fixed-size records, so instead of splitting them at 270349cc55cSDimitry Andric // symbol boundaries, we split them based on size. Records are distinct from 271349cc55cSDimitry Andric // literals in that they may contain references to other sections, instead of 272349cc55cSDimitry Andric // being leaf nodes in the InputSection graph. 273349cc55cSDimitry Andric // 274349cc55cSDimitry Andric // Note that "record" is a term I came up with. In contrast, "literal" is a term 275349cc55cSDimitry Andric // used by the Mach-O format. 276*bdd1243dSDimitry Andric static std::optional<size_t> getRecordSize(StringRef segname, StringRef name) { 27781ad6265SDimitry Andric if (name == section_names::compactUnwind) { 278349cc55cSDimitry Andric if (segname == segment_names::ld) 279349cc55cSDimitry Andric return target->wordSize == 8 ? 32 : 20; 280349cc55cSDimitry Andric } 281*bdd1243dSDimitry Andric if (!config->dedupStrings) 282349cc55cSDimitry Andric return {}; 28381ad6265SDimitry Andric 28481ad6265SDimitry Andric if (name == section_names::cfString && segname == segment_names::data) 28581ad6265SDimitry Andric return target->wordSize == 8 ? 32 : 16; 286fcaf7f86SDimitry Andric 287fcaf7f86SDimitry Andric if (config->icfLevel == ICFLevel::none) 288fcaf7f86SDimitry Andric return {}; 289fcaf7f86SDimitry Andric 29081ad6265SDimitry Andric if (name == section_names::objcClassRefs && segname == segment_names::data) 29181ad6265SDimitry Andric return target->wordSize; 292*bdd1243dSDimitry Andric 293*bdd1243dSDimitry Andric if (name == section_names::objcSelrefs && segname == segment_names::data) 294*bdd1243dSDimitry Andric return target->wordSize; 29581ad6265SDimitry Andric return {}; 29681ad6265SDimitry Andric } 29781ad6265SDimitry Andric 29881ad6265SDimitry Andric static Error parseCallGraph(ArrayRef<uint8_t> data, 29981ad6265SDimitry Andric std::vector<CallGraphEntry> &callGraph) { 30081ad6265SDimitry Andric TimeTraceScope timeScope("Parsing call graph section"); 30181ad6265SDimitry Andric BinaryStreamReader reader(data, support::little); 30281ad6265SDimitry Andric while (!reader.empty()) { 30381ad6265SDimitry Andric uint32_t fromIndex, toIndex; 30481ad6265SDimitry Andric uint64_t count; 30581ad6265SDimitry Andric if (Error err = reader.readInteger(fromIndex)) 30681ad6265SDimitry Andric return err; 30781ad6265SDimitry Andric if (Error err = reader.readInteger(toIndex)) 30881ad6265SDimitry Andric return err; 30981ad6265SDimitry Andric if (Error err = reader.readInteger(count)) 31081ad6265SDimitry Andric return err; 31181ad6265SDimitry Andric callGraph.emplace_back(fromIndex, toIndex, count); 31281ad6265SDimitry Andric } 31381ad6265SDimitry Andric return Error::success(); 314349cc55cSDimitry Andric } 315349cc55cSDimitry Andric 316349cc55cSDimitry Andric // Parse the sequence of sections within a single LC_SEGMENT(_64). 317349cc55cSDimitry Andric // Split each section into subsections. 318349cc55cSDimitry Andric template <class SectionHeader> 319349cc55cSDimitry Andric void ObjFile::parseSections(ArrayRef<SectionHeader> sectionHeaders) { 320349cc55cSDimitry Andric sections.reserve(sectionHeaders.size()); 3215ffd83dbSDimitry Andric auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 3225ffd83dbSDimitry Andric 323349cc55cSDimitry Andric for (const SectionHeader &sec : sectionHeaders) { 324fe6060f1SDimitry Andric StringRef name = 325e8d8bef9SDimitry Andric StringRef(sec.sectname, strnlen(sec.sectname, sizeof(sec.sectname))); 326fe6060f1SDimitry Andric StringRef segname = 327e8d8bef9SDimitry Andric StringRef(sec.segname, strnlen(sec.segname, sizeof(sec.segname))); 32881ad6265SDimitry Andric sections.push_back(make<Section>(this, segname, name, sec.flags, sec.addr)); 329fe6060f1SDimitry Andric if (sec.align >= 32) { 330fe6060f1SDimitry Andric error("alignment " + std::to_string(sec.align) + " of section " + name + 331fe6060f1SDimitry Andric " is too large"); 332fe6060f1SDimitry Andric continue; 333fe6060f1SDimitry Andric } 33481ad6265SDimitry Andric Section §ion = *sections.back(); 335fe6060f1SDimitry Andric uint32_t align = 1 << sec.align; 33681ad6265SDimitry Andric ArrayRef<uint8_t> data = {isZeroFill(sec.flags) ? nullptr 33781ad6265SDimitry Andric : buf + sec.offset, 33881ad6265SDimitry Andric static_cast<size_t>(sec.size)}; 339e8d8bef9SDimitry Andric 340*bdd1243dSDimitry Andric auto splitRecords = [&](size_t recordSize) -> void { 341349cc55cSDimitry Andric if (data.empty()) 342349cc55cSDimitry Andric return; 34381ad6265SDimitry Andric Subsections &subsections = section.subsections; 344349cc55cSDimitry Andric subsections.reserve(data.size() / recordSize); 34581ad6265SDimitry Andric for (uint64_t off = 0; off < data.size(); off += recordSize) { 346349cc55cSDimitry Andric auto *isec = make<ConcatInputSection>( 347*bdd1243dSDimitry Andric section, data.slice(off, std::min(data.size(), recordSize)), align); 34881ad6265SDimitry Andric subsections.push_back({off, isec}); 349349cc55cSDimitry Andric } 35081ad6265SDimitry Andric section.doneSplitting = true; 351349cc55cSDimitry Andric }; 352349cc55cSDimitry Andric 353fe6060f1SDimitry Andric if (sectionType(sec.flags) == S_CSTRING_LITERALS) { 354*bdd1243dSDimitry Andric if (sec.nreloc) 355*bdd1243dSDimitry Andric fatal(toString(this) + ": " + sec.segname + "," + sec.sectname + 356*bdd1243dSDimitry Andric " contains relocations, which is unsupported"); 357*bdd1243dSDimitry Andric bool dedupLiterals = 358*bdd1243dSDimitry Andric name == section_names::objcMethname || config->dedupStrings; 359*bdd1243dSDimitry Andric InputSection *isec = 360*bdd1243dSDimitry Andric make<CStringInputSection>(section, data, align, dedupLiterals); 361fe6060f1SDimitry Andric // FIXME: parallelize this? 362fe6060f1SDimitry Andric cast<CStringInputSection>(isec)->splitIntoPieces(); 363*bdd1243dSDimitry Andric section.subsections.push_back({0, isec}); 364*bdd1243dSDimitry Andric } else if (isWordLiteralSection(sec.flags)) { 365*bdd1243dSDimitry Andric if (sec.nreloc) 366*bdd1243dSDimitry Andric fatal(toString(this) + ": " + sec.segname + "," + sec.sectname + 367*bdd1243dSDimitry Andric " contains relocations, which is unsupported"); 368*bdd1243dSDimitry Andric InputSection *isec = make<WordLiteralInputSection>(section, data, align); 36981ad6265SDimitry Andric section.subsections.push_back({0, isec}); 370349cc55cSDimitry Andric } else if (auto recordSize = getRecordSize(segname, name)) { 371349cc55cSDimitry Andric splitRecords(*recordSize); 372753f127fSDimitry Andric } else if (name == section_names::ehFrame && 37381ad6265SDimitry Andric segname == segment_names::text) { 37481ad6265SDimitry Andric splitEhFrames(data, *sections.back()); 375349cc55cSDimitry Andric } else if (segname == segment_names::llvm) { 37681ad6265SDimitry Andric if (config->callGraphProfileSort && name == section_names::cgProfile) 37781ad6265SDimitry Andric checkError(parseCallGraph(data, callGraph)); 378349cc55cSDimitry Andric // ld64 does not appear to emit contents from sections within the __LLVM 379349cc55cSDimitry Andric // segment. Symbols within those sections point to bitcode metadata 380349cc55cSDimitry Andric // instead of actual symbols. Global symbols within those sections could 38181ad6265SDimitry Andric // have the same name without causing duplicate symbol errors. To avoid 38281ad6265SDimitry Andric // spurious duplicate symbol errors, we do not parse these sections. 383349cc55cSDimitry Andric // TODO: Evaluate whether the bitcode metadata is needed. 384fcaf7f86SDimitry Andric } else if (name == section_names::objCImageInfo && 385fcaf7f86SDimitry Andric segname == segment_names::data) { 386fcaf7f86SDimitry Andric objCImageInfo = data; 387fe6060f1SDimitry Andric } else { 38881ad6265SDimitry Andric if (name == section_names::addrSig) 38981ad6265SDimitry Andric addrSigSection = sections.back(); 39081ad6265SDimitry Andric 39181ad6265SDimitry Andric auto *isec = make<ConcatInputSection>(section, data, align); 392349cc55cSDimitry Andric if (isDebugSection(isec->getFlags()) && 393349cc55cSDimitry Andric isec->getSegName() == segment_names::dwarf) { 394e8d8bef9SDimitry Andric // Instead of emitting DWARF sections, we emit STABS symbols to the 395e8d8bef9SDimitry Andric // object files that contain them. We filter them out early to avoid 39681ad6265SDimitry Andric // parsing their relocations unnecessarily. 397e8d8bef9SDimitry Andric debugSections.push_back(isec); 398349cc55cSDimitry Andric } else { 39981ad6265SDimitry Andric section.subsections.push_back({0, isec}); 400e8d8bef9SDimitry Andric } 4015ffd83dbSDimitry Andric } 4025ffd83dbSDimitry Andric } 403fe6060f1SDimitry Andric } 4045ffd83dbSDimitry Andric 40581ad6265SDimitry Andric void ObjFile::splitEhFrames(ArrayRef<uint8_t> data, Section &ehFrameSection) { 40661cfbce3SDimitry Andric EhReader reader(this, data, /*dataOff=*/0); 40781ad6265SDimitry Andric size_t off = 0; 40881ad6265SDimitry Andric while (off < reader.size()) { 40981ad6265SDimitry Andric uint64_t frameOff = off; 41081ad6265SDimitry Andric uint64_t length = reader.readLength(&off); 41181ad6265SDimitry Andric if (length == 0) 41281ad6265SDimitry Andric break; 41381ad6265SDimitry Andric uint64_t fullLength = length + (off - frameOff); 41481ad6265SDimitry Andric off += length; 41581ad6265SDimitry Andric // We hard-code an alignment of 1 here because we don't actually want our 41681ad6265SDimitry Andric // EH frames to be aligned to the section alignment. EH frame decoders don't 41781ad6265SDimitry Andric // expect this alignment. Moreover, each EH frame must start where the 41881ad6265SDimitry Andric // previous one ends, and where it ends is indicated by the length field. 41981ad6265SDimitry Andric // Unless we update the length field (troublesome), we should keep the 42081ad6265SDimitry Andric // alignment to 1. 42181ad6265SDimitry Andric // Note that we still want to preserve the alignment of the overall section, 42281ad6265SDimitry Andric // just not of the individual EH frames. 42381ad6265SDimitry Andric ehFrameSection.subsections.push_back( 42481ad6265SDimitry Andric {frameOff, make<ConcatInputSection>(ehFrameSection, 42581ad6265SDimitry Andric data.slice(frameOff, fullLength), 42681ad6265SDimitry Andric /*align=*/1)}); 42781ad6265SDimitry Andric } 42881ad6265SDimitry Andric ehFrameSection.doneSplitting = true; 42981ad6265SDimitry Andric } 43081ad6265SDimitry Andric 43181ad6265SDimitry Andric template <class T> 43281ad6265SDimitry Andric static Section *findContainingSection(const std::vector<Section *> §ions, 43381ad6265SDimitry Andric T *offset) { 43481ad6265SDimitry Andric static_assert(std::is_same<uint64_t, T>::value || 43581ad6265SDimitry Andric std::is_same<uint32_t, T>::value, 43681ad6265SDimitry Andric "unexpected type for offset"); 43781ad6265SDimitry Andric auto it = std::prev(llvm::upper_bound( 43881ad6265SDimitry Andric sections, *offset, 43981ad6265SDimitry Andric [](uint64_t value, const Section *sec) { return value < sec->addr; })); 44081ad6265SDimitry Andric *offset -= (*it)->addr; 44181ad6265SDimitry Andric return *it; 44281ad6265SDimitry Andric } 44381ad6265SDimitry Andric 4445ffd83dbSDimitry Andric // Find the subsection corresponding to the greatest section offset that is <= 4455ffd83dbSDimitry Andric // that of the given offset. 4465ffd83dbSDimitry Andric // 4475ffd83dbSDimitry Andric // offset: an offset relative to the start of the original InputSection (before 4485ffd83dbSDimitry Andric // any subsection splitting has occurred). It will be updated to represent the 4495ffd83dbSDimitry Andric // same location as an offset relative to the start of the containing 4505ffd83dbSDimitry Andric // subsection. 451349cc55cSDimitry Andric template <class T> 45281ad6265SDimitry Andric static InputSection *findContainingSubsection(const Section §ion, 453349cc55cSDimitry Andric T *offset) { 454349cc55cSDimitry Andric static_assert(std::is_same<uint64_t, T>::value || 455349cc55cSDimitry Andric std::is_same<uint32_t, T>::value, 456349cc55cSDimitry Andric "unexpected type for offset"); 457fe6060f1SDimitry Andric auto it = std::prev(llvm::upper_bound( 45881ad6265SDimitry Andric section.subsections, *offset, 459349cc55cSDimitry Andric [](uint64_t value, Subsection subsec) { return value < subsec.offset; })); 460fe6060f1SDimitry Andric *offset -= it->offset; 461fe6060f1SDimitry Andric return it->isec; 4625ffd83dbSDimitry Andric } 4635ffd83dbSDimitry Andric 46481ad6265SDimitry Andric // Find a symbol at offset `off` within `isec`. 46581ad6265SDimitry Andric static Defined *findSymbolAtOffset(const ConcatInputSection *isec, 46681ad6265SDimitry Andric uint64_t off) { 46781ad6265SDimitry Andric auto it = llvm::lower_bound(isec->symbols, off, [](Defined *d, uint64_t off) { 46881ad6265SDimitry Andric return d->value < off; 46981ad6265SDimitry Andric }); 47081ad6265SDimitry Andric // The offset should point at the exact address of a symbol (with no addend.) 47181ad6265SDimitry Andric if (it == isec->symbols.end() || (*it)->value != off) { 47281ad6265SDimitry Andric assert(isec->wasCoalesced); 47381ad6265SDimitry Andric return nullptr; 47481ad6265SDimitry Andric } 47581ad6265SDimitry Andric return *it; 47681ad6265SDimitry Andric } 47781ad6265SDimitry Andric 478349cc55cSDimitry Andric template <class SectionHeader> 479349cc55cSDimitry Andric static bool validateRelocationInfo(InputFile *file, const SectionHeader &sec, 480fe6060f1SDimitry Andric relocation_info rel) { 481fe6060f1SDimitry Andric const RelocAttrs &relocAttrs = target->getRelocAttrs(rel.r_type); 482fe6060f1SDimitry Andric bool valid = true; 483fe6060f1SDimitry Andric auto message = [relocAttrs, file, sec, rel, &valid](const Twine &diagnostic) { 484fe6060f1SDimitry Andric valid = false; 485fe6060f1SDimitry Andric return (relocAttrs.name + " relocation " + diagnostic + " at offset " + 486fe6060f1SDimitry Andric std::to_string(rel.r_address) + " of " + sec.segname + "," + 487fe6060f1SDimitry Andric sec.sectname + " in " + toString(file)) 488fe6060f1SDimitry Andric .str(); 489fe6060f1SDimitry Andric }; 490fe6060f1SDimitry Andric 491fe6060f1SDimitry Andric if (!relocAttrs.hasAttr(RelocAttrBits::LOCAL) && !rel.r_extern) 492fe6060f1SDimitry Andric error(message("must be extern")); 493fe6060f1SDimitry Andric if (relocAttrs.hasAttr(RelocAttrBits::PCREL) != rel.r_pcrel) 494fe6060f1SDimitry Andric error(message(Twine("must ") + (rel.r_pcrel ? "not " : "") + 495fe6060f1SDimitry Andric "be PC-relative")); 496fe6060f1SDimitry Andric if (isThreadLocalVariables(sec.flags) && 497fe6060f1SDimitry Andric !relocAttrs.hasAttr(RelocAttrBits::UNSIGNED)) 498fe6060f1SDimitry Andric error(message("not allowed in thread-local section, must be UNSIGNED")); 499fe6060f1SDimitry Andric if (rel.r_length < 2 || rel.r_length > 3 || 500fe6060f1SDimitry Andric !relocAttrs.hasAttr(static_cast<RelocAttrBits>(1 << rel.r_length))) { 501fe6060f1SDimitry Andric static SmallVector<StringRef, 4> widths{"0", "4", "8", "4 or 8"}; 502fe6060f1SDimitry Andric error(message("has width " + std::to_string(1 << rel.r_length) + 503fe6060f1SDimitry Andric " bytes, but must be " + 504fe6060f1SDimitry Andric widths[(static_cast<int>(relocAttrs.bits) >> 2) & 3] + 505fe6060f1SDimitry Andric " bytes")); 506fe6060f1SDimitry Andric } 507fe6060f1SDimitry Andric return valid; 508fe6060f1SDimitry Andric } 509fe6060f1SDimitry Andric 510349cc55cSDimitry Andric template <class SectionHeader> 511349cc55cSDimitry Andric void ObjFile::parseRelocations(ArrayRef<SectionHeader> sectionHeaders, 51281ad6265SDimitry Andric const SectionHeader &sec, Section §ion) { 5135ffd83dbSDimitry Andric auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 514e8d8bef9SDimitry Andric ArrayRef<relocation_info> relInfos( 515e8d8bef9SDimitry Andric reinterpret_cast<const relocation_info *>(buf + sec.reloff), sec.nreloc); 5165ffd83dbSDimitry Andric 51781ad6265SDimitry Andric Subsections &subsections = section.subsections; 518349cc55cSDimitry Andric auto subsecIt = subsections.rbegin(); 519e8d8bef9SDimitry Andric for (size_t i = 0; i < relInfos.size(); i++) { 520e8d8bef9SDimitry Andric // Paired relocations serve as Mach-O's method for attaching a 521e8d8bef9SDimitry Andric // supplemental datum to a primary relocation record. ELF does not 522e8d8bef9SDimitry Andric // need them because the *_RELOC_RELA records contain the extra 523e8d8bef9SDimitry Andric // addend field, vs. *_RELOC_REL which omit the addend. 524e8d8bef9SDimitry Andric // 525e8d8bef9SDimitry Andric // The {X86_64,ARM64}_RELOC_SUBTRACTOR record holds the subtrahend, 526e8d8bef9SDimitry Andric // and the paired *_RELOC_UNSIGNED record holds the minuend. The 527fe6060f1SDimitry Andric // datum for each is a symbolic address. The result is the offset 528fe6060f1SDimitry Andric // between two addresses. 529e8d8bef9SDimitry Andric // 530e8d8bef9SDimitry Andric // The ARM64_RELOC_ADDEND record holds the addend, and the paired 531e8d8bef9SDimitry Andric // ARM64_RELOC_BRANCH26 or ARM64_RELOC_PAGE21/PAGEOFF12 holds the 532e8d8bef9SDimitry Andric // base symbolic address. 533e8d8bef9SDimitry Andric // 534*bdd1243dSDimitry Andric // Note: X86 does not use *_RELOC_ADDEND because it can embed an addend into 535*bdd1243dSDimitry Andric // the instruction stream. On X86, a relocatable address field always 536*bdd1243dSDimitry Andric // occupies an entire contiguous sequence of byte(s), so there is no need to 537*bdd1243dSDimitry Andric // merge opcode bits with address bits. Therefore, it's easy and convenient 538*bdd1243dSDimitry Andric // to store addends in the instruction-stream bytes that would otherwise 539*bdd1243dSDimitry Andric // contain zeroes. By contrast, RISC ISAs such as ARM64 mix opcode bits with 540*bdd1243dSDimitry Andric // address bits so that bitwise arithmetic is necessary to extract and 541*bdd1243dSDimitry Andric // insert them. Storing addends in the instruction stream is possible, but 542*bdd1243dSDimitry Andric // inconvenient and more costly at link time. 543e8d8bef9SDimitry Andric 544fe6060f1SDimitry Andric relocation_info relInfo = relInfos[i]; 545349cc55cSDimitry Andric bool isSubtrahend = 546349cc55cSDimitry Andric target->hasAttr(relInfo.r_type, RelocAttrBits::SUBTRAHEND); 547349cc55cSDimitry Andric int64_t pairedAddend = 0; 548fe6060f1SDimitry Andric if (target->hasAttr(relInfo.r_type, RelocAttrBits::ADDEND)) { 549fe6060f1SDimitry Andric pairedAddend = SignExtend64<24>(relInfo.r_symbolnum); 550fe6060f1SDimitry Andric relInfo = relInfos[++i]; 551fe6060f1SDimitry Andric } 552e8d8bef9SDimitry Andric assert(i < relInfos.size()); 553fe6060f1SDimitry Andric if (!validateRelocationInfo(this, sec, relInfo)) 554fe6060f1SDimitry Andric continue; 555e8d8bef9SDimitry Andric if (relInfo.r_address & R_SCATTERED) 5565ffd83dbSDimitry Andric fatal("TODO: Scattered relocations not supported"); 5575ffd83dbSDimitry Andric 558fe6060f1SDimitry Andric int64_t embeddedAddend = target->getEmbeddedAddend(mb, sec.offset, relInfo); 559fe6060f1SDimitry Andric assert(!(embeddedAddend && pairedAddend)); 560fe6060f1SDimitry Andric int64_t totalAddend = pairedAddend + embeddedAddend; 5615ffd83dbSDimitry Andric Reloc r; 562e8d8bef9SDimitry Andric r.type = relInfo.r_type; 563e8d8bef9SDimitry Andric r.pcrel = relInfo.r_pcrel; 564e8d8bef9SDimitry Andric r.length = relInfo.r_length; 565e8d8bef9SDimitry Andric r.offset = relInfo.r_address; 566e8d8bef9SDimitry Andric if (relInfo.r_extern) { 567e8d8bef9SDimitry Andric r.referent = symbols[relInfo.r_symbolnum]; 568fe6060f1SDimitry Andric r.addend = isSubtrahend ? 0 : totalAddend; 5695ffd83dbSDimitry Andric } else { 570fe6060f1SDimitry Andric assert(!isSubtrahend); 571349cc55cSDimitry Andric const SectionHeader &referentSecHead = 572349cc55cSDimitry Andric sectionHeaders[relInfo.r_symbolnum - 1]; 573fe6060f1SDimitry Andric uint64_t referentOffset; 574e8d8bef9SDimitry Andric if (relInfo.r_pcrel) { 5755ffd83dbSDimitry Andric // The implicit addend for pcrel section relocations is the pcrel offset 5765ffd83dbSDimitry Andric // in terms of the addresses in the input file. Here we adjust it so 577e8d8bef9SDimitry Andric // that it describes the offset from the start of the referent section. 578fe6060f1SDimitry Andric // FIXME This logic was written around x86_64 behavior -- ARM64 doesn't 579fe6060f1SDimitry Andric // have pcrel section relocations. We may want to factor this out into 580fe6060f1SDimitry Andric // the arch-specific .cpp file. 581fe6060f1SDimitry Andric assert(target->hasAttr(r.type, RelocAttrBits::BYTE4)); 582349cc55cSDimitry Andric referentOffset = sec.addr + relInfo.r_address + 4 + totalAddend - 583349cc55cSDimitry Andric referentSecHead.addr; 5845ffd83dbSDimitry Andric } else { 5855ffd83dbSDimitry Andric // The addend for a non-pcrel relocation is its absolute address. 586349cc55cSDimitry Andric referentOffset = totalAddend - referentSecHead.addr; 5875ffd83dbSDimitry Andric } 58881ad6265SDimitry Andric r.referent = findContainingSubsection(*sections[relInfo.r_symbolnum - 1], 58981ad6265SDimitry Andric &referentOffset); 590e8d8bef9SDimitry Andric r.addend = referentOffset; 5915ffd83dbSDimitry Andric } 5925ffd83dbSDimitry Andric 593fe6060f1SDimitry Andric // Find the subsection that this relocation belongs to. 594fe6060f1SDimitry Andric // Though not required by the Mach-O format, clang and gcc seem to emit 595fe6060f1SDimitry Andric // relocations in order, so let's take advantage of it. However, ld64 emits 596fe6060f1SDimitry Andric // unsorted relocations (in `-r` mode), so we have a fallback for that 597fe6060f1SDimitry Andric // uncommon case. 598fe6060f1SDimitry Andric InputSection *subsec; 599349cc55cSDimitry Andric while (subsecIt != subsections.rend() && subsecIt->offset > r.offset) 600fe6060f1SDimitry Andric ++subsecIt; 601349cc55cSDimitry Andric if (subsecIt == subsections.rend() || 602fe6060f1SDimitry Andric subsecIt->offset + subsecIt->isec->getSize() <= r.offset) { 60381ad6265SDimitry Andric subsec = findContainingSubsection(section, &r.offset); 604fe6060f1SDimitry Andric // Now that we know the relocs are unsorted, avoid trying the 'fast path' 605fe6060f1SDimitry Andric // for the other relocations. 606349cc55cSDimitry Andric subsecIt = subsections.rend(); 607fe6060f1SDimitry Andric } else { 608fe6060f1SDimitry Andric subsec = subsecIt->isec; 609fe6060f1SDimitry Andric r.offset -= subsecIt->offset; 610fe6060f1SDimitry Andric } 6115ffd83dbSDimitry Andric subsec->relocs.push_back(r); 612fe6060f1SDimitry Andric 613fe6060f1SDimitry Andric if (isSubtrahend) { 614fe6060f1SDimitry Andric relocation_info minuendInfo = relInfos[++i]; 615fe6060f1SDimitry Andric // SUBTRACTOR relocations should always be followed by an UNSIGNED one 616fe6060f1SDimitry Andric // attached to the same address. 617fe6060f1SDimitry Andric assert(target->hasAttr(minuendInfo.r_type, RelocAttrBits::UNSIGNED) && 618fe6060f1SDimitry Andric relInfo.r_address == minuendInfo.r_address); 619fe6060f1SDimitry Andric Reloc p; 620fe6060f1SDimitry Andric p.type = minuendInfo.r_type; 621fe6060f1SDimitry Andric if (minuendInfo.r_extern) { 622fe6060f1SDimitry Andric p.referent = symbols[minuendInfo.r_symbolnum]; 623fe6060f1SDimitry Andric p.addend = totalAddend; 624fe6060f1SDimitry Andric } else { 625fe6060f1SDimitry Andric uint64_t referentOffset = 626fe6060f1SDimitry Andric totalAddend - sectionHeaders[minuendInfo.r_symbolnum - 1].addr; 62781ad6265SDimitry Andric p.referent = findContainingSubsection( 62881ad6265SDimitry Andric *sections[minuendInfo.r_symbolnum - 1], &referentOffset); 629fe6060f1SDimitry Andric p.addend = referentOffset; 630fe6060f1SDimitry Andric } 631fe6060f1SDimitry Andric subsec->relocs.push_back(p); 632fe6060f1SDimitry Andric } 6335ffd83dbSDimitry Andric } 6345ffd83dbSDimitry Andric } 6355ffd83dbSDimitry Andric 636*bdd1243dSDimitry Andric // Symbols with `l` or `L` as a prefix are linker-private and never appear in 637*bdd1243dSDimitry Andric // the output. 638*bdd1243dSDimitry Andric static bool isPrivateLabel(StringRef name) { 639*bdd1243dSDimitry Andric return name.startswith("l") || name.startswith("L"); 640*bdd1243dSDimitry Andric } 641*bdd1243dSDimitry Andric 642fe6060f1SDimitry Andric template <class NList> 643fe6060f1SDimitry Andric static macho::Symbol *createDefined(const NList &sym, StringRef name, 644fe6060f1SDimitry Andric InputSection *isec, uint64_t value, 645972a253aSDimitry Andric uint64_t size, bool forceHidden) { 646e8d8bef9SDimitry Andric // Symbol scope is determined by sym.n_type & (N_EXT | N_PEXT): 647fe6060f1SDimitry Andric // N_EXT: Global symbols. These go in the symbol table during the link, 648fe6060f1SDimitry Andric // and also in the export table of the output so that the dynamic 649fe6060f1SDimitry Andric // linker sees them. 650fe6060f1SDimitry Andric // N_EXT | N_PEXT: Linkage unit (think: dylib) scoped. These go in the 651fe6060f1SDimitry Andric // symbol table during the link so that duplicates are 652fe6060f1SDimitry Andric // either reported (for non-weak symbols) or merged 653fe6060f1SDimitry Andric // (for weak symbols), but they do not go in the export 654fe6060f1SDimitry Andric // table of the output. 655fe6060f1SDimitry Andric // N_PEXT: llvm-mc does not emit these, but `ld -r` (wherein ld64 emits 656fe6060f1SDimitry Andric // object files) may produce them. LLD does not yet support -r. 657fe6060f1SDimitry Andric // These are translation-unit scoped, identical to the `0` case. 658fe6060f1SDimitry Andric // 0: Translation-unit scoped. These are not in the symbol table during 659fe6060f1SDimitry Andric // link, and not in the export table of the output either. 660fe6060f1SDimitry Andric bool isWeakDefCanBeHidden = 661fe6060f1SDimitry Andric (sym.n_desc & (N_WEAK_DEF | N_WEAK_REF)) == (N_WEAK_DEF | N_WEAK_REF); 662e8d8bef9SDimitry Andric 663fe6060f1SDimitry Andric if (sym.n_type & N_EXT) { 664972a253aSDimitry Andric // -load_hidden makes us treat global symbols as linkage unit scoped. 665972a253aSDimitry Andric // Duplicates are reported but the symbol does not go in the export trie. 666972a253aSDimitry Andric bool isPrivateExtern = sym.n_type & N_PEXT || forceHidden; 667972a253aSDimitry Andric 668fe6060f1SDimitry Andric // lld's behavior for merging symbols is slightly different from ld64: 669fe6060f1SDimitry Andric // ld64 picks the winning symbol based on several criteria (see 670fe6060f1SDimitry Andric // pickBetweenRegularAtoms() in ld64's SymbolTable.cpp), while lld 671fe6060f1SDimitry Andric // just merges metadata and keeps the contents of the first symbol 672fe6060f1SDimitry Andric // with that name (see SymbolTable::addDefined). For: 673fe6060f1SDimitry Andric // * inline function F in a TU built with -fvisibility-inlines-hidden 674fe6060f1SDimitry Andric // * and inline function F in another TU built without that flag 675fe6060f1SDimitry Andric // ld64 will pick the one from the file built without 676fe6060f1SDimitry Andric // -fvisibility-inlines-hidden. 677fe6060f1SDimitry Andric // lld will instead pick the one listed first on the link command line and 678fe6060f1SDimitry Andric // give it visibility as if the function was built without 679fe6060f1SDimitry Andric // -fvisibility-inlines-hidden. 680fe6060f1SDimitry Andric // If both functions have the same contents, this will have the same 681fe6060f1SDimitry Andric // behavior. If not, it won't, but the input had an ODR violation in 682fe6060f1SDimitry Andric // that case. 683fe6060f1SDimitry Andric // 684fe6060f1SDimitry Andric // Similarly, merging a symbol 685fe6060f1SDimitry Andric // that's isPrivateExtern and not isWeakDefCanBeHidden with one 686fe6060f1SDimitry Andric // that's not isPrivateExtern but isWeakDefCanBeHidden technically 687fe6060f1SDimitry Andric // should produce one 688fe6060f1SDimitry Andric // that's not isPrivateExtern but isWeakDefCanBeHidden. That matters 689fe6060f1SDimitry Andric // with ld64's semantics, because it means the non-private-extern 690fe6060f1SDimitry Andric // definition will continue to take priority if more private extern 691fe6060f1SDimitry Andric // definitions are encountered. With lld's semantics there's no observable 692349cc55cSDimitry Andric // difference between a symbol that's isWeakDefCanBeHidden(autohide) or one 693349cc55cSDimitry Andric // that's privateExtern -- neither makes it into the dynamic symbol table, 694349cc55cSDimitry Andric // unless the autohide symbol is explicitly exported. 695349cc55cSDimitry Andric // But if a symbol is both privateExtern and autohide then it can't 696349cc55cSDimitry Andric // be exported. 697349cc55cSDimitry Andric // So we nullify the autohide flag when privateExtern is present 698349cc55cSDimitry Andric // and promote the symbol to privateExtern when it is not already. 699349cc55cSDimitry Andric if (isWeakDefCanBeHidden && isPrivateExtern) 700349cc55cSDimitry Andric isWeakDefCanBeHidden = false; 701349cc55cSDimitry Andric else if (isWeakDefCanBeHidden) 702fe6060f1SDimitry Andric isPrivateExtern = true; 703fe6060f1SDimitry Andric return symtab->addDefined( 704fe6060f1SDimitry Andric name, isec->getFile(), isec, value, size, sym.n_desc & N_WEAK_DEF, 705fe6060f1SDimitry Andric isPrivateExtern, sym.n_desc & N_ARM_THUMB_DEF, 706349cc55cSDimitry Andric sym.n_desc & REFERENCED_DYNAMICALLY, sym.n_desc & N_NO_DEAD_STRIP, 707349cc55cSDimitry Andric isWeakDefCanBeHidden); 708e8d8bef9SDimitry Andric } 709*bdd1243dSDimitry Andric bool includeInSymtab = !isPrivateLabel(name) && !isEhFrameSection(isec); 710fe6060f1SDimitry Andric return make<Defined>( 711fe6060f1SDimitry Andric name, isec->getFile(), isec, value, size, sym.n_desc & N_WEAK_DEF, 71281ad6265SDimitry Andric /*isExternal=*/false, /*isPrivateExtern=*/false, includeInSymtab, 713fe6060f1SDimitry Andric sym.n_desc & N_ARM_THUMB_DEF, sym.n_desc & REFERENCED_DYNAMICALLY, 714fe6060f1SDimitry Andric sym.n_desc & N_NO_DEAD_STRIP); 715e8d8bef9SDimitry Andric } 716e8d8bef9SDimitry Andric 717e8d8bef9SDimitry Andric // Absolute symbols are defined symbols that do not have an associated 718e8d8bef9SDimitry Andric // InputSection. They cannot be weak. 719fe6060f1SDimitry Andric template <class NList> 720fe6060f1SDimitry Andric static macho::Symbol *createAbsolute(const NList &sym, InputFile *file, 721972a253aSDimitry Andric StringRef name, bool forceHidden) { 722fe6060f1SDimitry Andric if (sym.n_type & N_EXT) { 723972a253aSDimitry Andric bool isPrivateExtern = sym.n_type & N_PEXT || forceHidden; 724fe6060f1SDimitry Andric return symtab->addDefined( 725fe6060f1SDimitry Andric name, file, nullptr, sym.n_value, /*size=*/0, 726972a253aSDimitry Andric /*isWeakDef=*/false, isPrivateExtern, sym.n_desc & N_ARM_THUMB_DEF, 727349cc55cSDimitry Andric /*isReferencedDynamically=*/false, sym.n_desc & N_NO_DEAD_STRIP, 728349cc55cSDimitry Andric /*isWeakDefCanBeHidden=*/false); 729e8d8bef9SDimitry Andric } 730fe6060f1SDimitry Andric return make<Defined>(name, file, nullptr, sym.n_value, /*size=*/0, 731fe6060f1SDimitry Andric /*isWeakDef=*/false, 732fe6060f1SDimitry Andric /*isExternal=*/false, /*isPrivateExtern=*/false, 73381ad6265SDimitry Andric /*includeInSymtab=*/true, sym.n_desc & N_ARM_THUMB_DEF, 734fe6060f1SDimitry Andric /*isReferencedDynamically=*/false, 735fe6060f1SDimitry Andric sym.n_desc & N_NO_DEAD_STRIP); 736e8d8bef9SDimitry Andric } 737e8d8bef9SDimitry Andric 738fe6060f1SDimitry Andric template <class NList> 739fe6060f1SDimitry Andric macho::Symbol *ObjFile::parseNonSectionSymbol(const NList &sym, 740*bdd1243dSDimitry Andric const char *strtab) { 741*bdd1243dSDimitry Andric StringRef name = StringRef(strtab + sym.n_strx); 742e8d8bef9SDimitry Andric uint8_t type = sym.n_type & N_TYPE; 743972a253aSDimitry Andric bool isPrivateExtern = sym.n_type & N_PEXT || forceHidden; 744e8d8bef9SDimitry Andric switch (type) { 745e8d8bef9SDimitry Andric case N_UNDF: 746e8d8bef9SDimitry Andric return sym.n_value == 0 747fe6060f1SDimitry Andric ? symtab->addUndefined(name, this, sym.n_desc & N_WEAK_REF) 748e8d8bef9SDimitry Andric : symtab->addCommon(name, this, sym.n_value, 749e8d8bef9SDimitry Andric 1 << GET_COMM_ALIGN(sym.n_desc), 750972a253aSDimitry Andric isPrivateExtern); 751e8d8bef9SDimitry Andric case N_ABS: 752972a253aSDimitry Andric return createAbsolute(sym, this, name, forceHidden); 753*bdd1243dSDimitry Andric case N_INDR: { 754*bdd1243dSDimitry Andric // Not much point in making local aliases -- relocs in the current file can 755*bdd1243dSDimitry Andric // just refer to the actual symbol itself. ld64 ignores these symbols too. 756*bdd1243dSDimitry Andric if (!(sym.n_type & N_EXT)) 757*bdd1243dSDimitry Andric return nullptr; 758*bdd1243dSDimitry Andric StringRef aliasedName = StringRef(strtab + sym.n_value); 759*bdd1243dSDimitry Andric // isPrivateExtern is the only symbol flag that has an impact on the final 760*bdd1243dSDimitry Andric // aliased symbol. 761*bdd1243dSDimitry Andric auto alias = make<AliasSymbol>(this, name, aliasedName, isPrivateExtern); 762*bdd1243dSDimitry Andric aliases.push_back(alias); 763*bdd1243dSDimitry Andric return alias; 764*bdd1243dSDimitry Andric } 765e8d8bef9SDimitry Andric case N_PBUD: 766*bdd1243dSDimitry Andric error("TODO: support symbols of type N_PBUD"); 767e8d8bef9SDimitry Andric return nullptr; 768e8d8bef9SDimitry Andric case N_SECT: 769e8d8bef9SDimitry Andric llvm_unreachable( 770e8d8bef9SDimitry Andric "N_SECT symbols should not be passed to parseNonSectionSymbol"); 771e8d8bef9SDimitry Andric default: 772e8d8bef9SDimitry Andric llvm_unreachable("invalid symbol type"); 773e8d8bef9SDimitry Andric } 774e8d8bef9SDimitry Andric } 775e8d8bef9SDimitry Andric 776349cc55cSDimitry Andric template <class NList> static bool isUndef(const NList &sym) { 777fe6060f1SDimitry Andric return (sym.n_type & N_TYPE) == N_UNDF && sym.n_value == 0; 778fe6060f1SDimitry Andric } 779fe6060f1SDimitry Andric 780fe6060f1SDimitry Andric template <class LP> 781fe6060f1SDimitry Andric void ObjFile::parseSymbols(ArrayRef<typename LP::section> sectionHeaders, 782fe6060f1SDimitry Andric ArrayRef<typename LP::nlist> nList, 7835ffd83dbSDimitry Andric const char *strtab, bool subsectionsViaSymbols) { 784fe6060f1SDimitry Andric using NList = typename LP::nlist; 785fe6060f1SDimitry Andric 786fe6060f1SDimitry Andric // Groups indices of the symbols by the sections that contain them. 787349cc55cSDimitry Andric std::vector<std::vector<uint32_t>> symbolsBySection(sections.size()); 7885ffd83dbSDimitry Andric symbols.resize(nList.size()); 789fe6060f1SDimitry Andric SmallVector<unsigned, 32> undefineds; 790fe6060f1SDimitry Andric for (uint32_t i = 0; i < nList.size(); ++i) { 791fe6060f1SDimitry Andric const NList &sym = nList[i]; 7925ffd83dbSDimitry Andric 793fe6060f1SDimitry Andric // Ignore debug symbols for now. 794fe6060f1SDimitry Andric // FIXME: may need special handling. 795fe6060f1SDimitry Andric if (sym.n_type & N_STAB) 796fe6060f1SDimitry Andric continue; 797fe6060f1SDimitry Andric 798fe6060f1SDimitry Andric if ((sym.n_type & N_TYPE) == N_SECT) { 79981ad6265SDimitry Andric Subsections &subsections = sections[sym.n_sect - 1]->subsections; 800fe6060f1SDimitry Andric // parseSections() may have chosen not to parse this section. 801349cc55cSDimitry Andric if (subsections.empty()) 802fe6060f1SDimitry Andric continue; 803fe6060f1SDimitry Andric symbolsBySection[sym.n_sect - 1].push_back(i); 804fe6060f1SDimitry Andric } else if (isUndef(sym)) { 805fe6060f1SDimitry Andric undefineds.push_back(i); 806fe6060f1SDimitry Andric } else { 807*bdd1243dSDimitry Andric symbols[i] = parseNonSectionSymbol(sym, strtab); 808fe6060f1SDimitry Andric } 809fe6060f1SDimitry Andric } 8105ffd83dbSDimitry Andric 811349cc55cSDimitry Andric for (size_t i = 0; i < sections.size(); ++i) { 81281ad6265SDimitry Andric Subsections &subsections = sections[i]->subsections; 813349cc55cSDimitry Andric if (subsections.empty()) 814fe6060f1SDimitry Andric continue; 815fe6060f1SDimitry Andric std::vector<uint32_t> &symbolIndices = symbolsBySection[i]; 816fe6060f1SDimitry Andric uint64_t sectionAddr = sectionHeaders[i].addr; 817fe6060f1SDimitry Andric uint32_t sectionAlign = 1u << sectionHeaders[i].align; 818fe6060f1SDimitry Andric 81981ad6265SDimitry Andric // Some sections have already been split into subsections during 820fe6060f1SDimitry Andric // parseSections(), so we simply need to match Symbols to the corresponding 821fe6060f1SDimitry Andric // subsection here. 82281ad6265SDimitry Andric if (sections[i]->doneSplitting) { 823fe6060f1SDimitry Andric for (size_t j = 0; j < symbolIndices.size(); ++j) { 824*bdd1243dSDimitry Andric const uint32_t symIndex = symbolIndices[j]; 825fe6060f1SDimitry Andric const NList &sym = nList[symIndex]; 826fe6060f1SDimitry Andric StringRef name = strtab + sym.n_strx; 827fe6060f1SDimitry Andric uint64_t symbolOffset = sym.n_value - sectionAddr; 828349cc55cSDimitry Andric InputSection *isec = 82981ad6265SDimitry Andric findContainingSubsection(*sections[i], &symbolOffset); 830fe6060f1SDimitry Andric if (symbolOffset != 0) { 83181ad6265SDimitry Andric error(toString(*sections[i]) + ": symbol " + name + 832fe6060f1SDimitry Andric " at misaligned offset"); 833fe6060f1SDimitry Andric continue; 834fe6060f1SDimitry Andric } 835972a253aSDimitry Andric symbols[symIndex] = 836972a253aSDimitry Andric createDefined(sym, name, isec, 0, isec->getSize(), forceHidden); 837fe6060f1SDimitry Andric } 8385ffd83dbSDimitry Andric continue; 8395ffd83dbSDimitry Andric } 84081ad6265SDimitry Andric sections[i]->doneSplitting = true; 8415ffd83dbSDimitry Andric 842*bdd1243dSDimitry Andric auto getSymName = [strtab](const NList& sym) -> StringRef { 843*bdd1243dSDimitry Andric return StringRef(strtab + sym.n_strx); 844*bdd1243dSDimitry Andric }; 845*bdd1243dSDimitry Andric 846fe6060f1SDimitry Andric // Calculate symbol sizes and create subsections by splitting the sections 847fe6060f1SDimitry Andric // along symbol boundaries. 848349cc55cSDimitry Andric // We populate subsections by repeatedly splitting the last (highest 849349cc55cSDimitry Andric // address) subsection. 850fe6060f1SDimitry Andric llvm::stable_sort(symbolIndices, [&](uint32_t lhs, uint32_t rhs) { 851*bdd1243dSDimitry Andric // Put private-label symbols that have no flags after other symbols at the 852*bdd1243dSDimitry Andric // same address. 853*bdd1243dSDimitry Andric StringRef lhsName = getSymName(nList[lhs]); 854*bdd1243dSDimitry Andric StringRef rhsName = getSymName(nList[rhs]); 855*bdd1243dSDimitry Andric if (nList[lhs].n_value == nList[rhs].n_value) { 856*bdd1243dSDimitry Andric if (isPrivateLabel(lhsName) && isPrivateLabel(rhsName)) 857*bdd1243dSDimitry Andric return nList[lhs].n_desc > nList[rhs].n_desc; 858*bdd1243dSDimitry Andric return !isPrivateLabel(lhsName) && isPrivateLabel(rhsName); 859*bdd1243dSDimitry Andric } 860fe6060f1SDimitry Andric return nList[lhs].n_value < nList[rhs].n_value; 861fe6060f1SDimitry Andric }); 862fe6060f1SDimitry Andric for (size_t j = 0; j < symbolIndices.size(); ++j) { 863*bdd1243dSDimitry Andric const uint32_t symIndex = symbolIndices[j]; 864fe6060f1SDimitry Andric const NList &sym = nList[symIndex]; 865*bdd1243dSDimitry Andric StringRef name = getSymName(sym); 866349cc55cSDimitry Andric Subsection &subsec = subsections.back(); 867349cc55cSDimitry Andric InputSection *isec = subsec.isec; 868fe6060f1SDimitry Andric 869349cc55cSDimitry Andric uint64_t subsecAddr = sectionAddr + subsec.offset; 870fe6060f1SDimitry Andric size_t symbolOffset = sym.n_value - subsecAddr; 871fe6060f1SDimitry Andric uint64_t symbolSize = 872fe6060f1SDimitry Andric j + 1 < symbolIndices.size() 873fe6060f1SDimitry Andric ? nList[symbolIndices[j + 1]].n_value - sym.n_value 874fe6060f1SDimitry Andric : isec->data.size() - symbolOffset; 875fe6060f1SDimitry Andric // There are 4 cases where we do not need to create a new subsection: 876fe6060f1SDimitry Andric // 1. If the input file does not use subsections-via-symbols. 877fe6060f1SDimitry Andric // 2. Multiple symbols at the same address only induce one subsection. 878fe6060f1SDimitry Andric // (The symbolOffset == 0 check covers both this case as well as 879fe6060f1SDimitry Andric // the first loop iteration.) 880fe6060f1SDimitry Andric // 3. Alternative entry points do not induce new subsections. 881fe6060f1SDimitry Andric // 4. If we have a literal section (e.g. __cstring and __literal4). 882fe6060f1SDimitry Andric if (!subsectionsViaSymbols || symbolOffset == 0 || 883fe6060f1SDimitry Andric sym.n_desc & N_ALT_ENTRY || !isa<ConcatInputSection>(isec)) { 884*bdd1243dSDimitry Andric isec->hasAltEntry = symbolOffset != 0; 885*bdd1243dSDimitry Andric // If we have an private-label symbol that's an alias, and that alias 886*bdd1243dSDimitry Andric // doesn't have any flags of its own, then we can just reuse the aliased 887*bdd1243dSDimitry Andric // symbol. Our sorting step above ensures that any such symbols will 888*bdd1243dSDimitry Andric // appear after the non-private-label ones. See weak-def-alias-ignored.s 889*bdd1243dSDimitry Andric // for the motivation behind this. 890*bdd1243dSDimitry Andric if (symbolOffset == 0 && isPrivateLabel(name) && j != 0 && 891*bdd1243dSDimitry Andric sym.n_desc == 0) 892*bdd1243dSDimitry Andric symbols[symIndex] = symbols[symbolIndices[j - 1]]; 893*bdd1243dSDimitry Andric else 894972a253aSDimitry Andric symbols[symIndex] = createDefined(sym, name, isec, symbolOffset, 895972a253aSDimitry Andric symbolSize, forceHidden); 8965ffd83dbSDimitry Andric continue; 8975ffd83dbSDimitry Andric } 898fe6060f1SDimitry Andric auto *concatIsec = cast<ConcatInputSection>(isec); 8995ffd83dbSDimitry Andric 900fe6060f1SDimitry Andric auto *nextIsec = make<ConcatInputSection>(*concatIsec); 901fe6060f1SDimitry Andric nextIsec->wasCoalesced = false; 902fe6060f1SDimitry Andric if (isZeroFill(isec->getFlags())) { 903fe6060f1SDimitry Andric // Zero-fill sections have NULL data.data() non-zero data.size() 904fe6060f1SDimitry Andric nextIsec->data = {nullptr, isec->data.size() - symbolOffset}; 905fe6060f1SDimitry Andric isec->data = {nullptr, symbolOffset}; 906fe6060f1SDimitry Andric } else { 907fe6060f1SDimitry Andric nextIsec->data = isec->data.slice(symbolOffset); 908fe6060f1SDimitry Andric isec->data = isec->data.slice(0, symbolOffset); 9095ffd83dbSDimitry Andric } 9105ffd83dbSDimitry Andric 911fe6060f1SDimitry Andric // By construction, the symbol will be at offset zero in the new 912fe6060f1SDimitry Andric // subsection. 913972a253aSDimitry Andric symbols[symIndex] = createDefined(sym, name, nextIsec, /*value=*/0, 914972a253aSDimitry Andric symbolSize, forceHidden); 9155ffd83dbSDimitry Andric // TODO: ld64 appears to preserve the original alignment as well as each 9165ffd83dbSDimitry Andric // subsection's offset from the last aligned address. We should consider 9175ffd83dbSDimitry Andric // emulating that behavior. 918fe6060f1SDimitry Andric nextIsec->align = MinAlign(sectionAlign, sym.n_value); 919349cc55cSDimitry Andric subsections.push_back({sym.n_value - sectionAddr, nextIsec}); 920fe6060f1SDimitry Andric } 9215ffd83dbSDimitry Andric } 9225ffd83dbSDimitry Andric 923fe6060f1SDimitry Andric // Undefined symbols can trigger recursive fetch from Archives due to 924fe6060f1SDimitry Andric // LazySymbols. Process defined symbols first so that the relative order 925fe6060f1SDimitry Andric // between a defined symbol and an undefined symbol does not change the 926fe6060f1SDimitry Andric // symbol resolution behavior. In addition, a set of interconnected symbols 927fe6060f1SDimitry Andric // will all be resolved to the same file, instead of being resolved to 928fe6060f1SDimitry Andric // different files. 929*bdd1243dSDimitry Andric for (unsigned i : undefineds) 930*bdd1243dSDimitry Andric symbols[i] = parseNonSectionSymbol(nList[i], strtab); 9315ffd83dbSDimitry Andric } 9325ffd83dbSDimitry Andric 933e8d8bef9SDimitry Andric OpaqueFile::OpaqueFile(MemoryBufferRef mb, StringRef segName, 934e8d8bef9SDimitry Andric StringRef sectName) 935e8d8bef9SDimitry Andric : InputFile(OpaqueKind, mb) { 936e8d8bef9SDimitry Andric const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 937fe6060f1SDimitry Andric ArrayRef<uint8_t> data = {buf, mb.getBufferSize()}; 93881ad6265SDimitry Andric sections.push_back(make<Section>(/*file=*/this, segName.take_front(16), 93981ad6265SDimitry Andric sectName.take_front(16), 94081ad6265SDimitry Andric /*flags=*/0, /*addr=*/0)); 94181ad6265SDimitry Andric Section §ion = *sections.back(); 94281ad6265SDimitry Andric ConcatInputSection *isec = make<ConcatInputSection>(section, data); 943fe6060f1SDimitry Andric isec->live = true; 94481ad6265SDimitry Andric section.subsections.push_back({0, isec}); 945e8d8bef9SDimitry Andric } 946e8d8bef9SDimitry Andric 94704eeddc0SDimitry Andric ObjFile::ObjFile(MemoryBufferRef mb, uint32_t modTime, StringRef archiveName, 948972a253aSDimitry Andric bool lazy, bool forceHidden) 949972a253aSDimitry Andric : InputFile(ObjKind, mb, lazy), modTime(modTime), forceHidden(forceHidden) { 950e8d8bef9SDimitry Andric this->archiveName = std::string(archiveName); 95104eeddc0SDimitry Andric if (lazy) { 95204eeddc0SDimitry Andric if (target->wordSize == 8) 95304eeddc0SDimitry Andric parseLazy<LP64>(); 95404eeddc0SDimitry Andric else 95504eeddc0SDimitry Andric parseLazy<ILP32>(); 95604eeddc0SDimitry Andric } else { 957fe6060f1SDimitry Andric if (target->wordSize == 8) 958fe6060f1SDimitry Andric parse<LP64>(); 959fe6060f1SDimitry Andric else 960fe6060f1SDimitry Andric parse<ILP32>(); 961e8d8bef9SDimitry Andric } 96204eeddc0SDimitry Andric } 963e8d8bef9SDimitry Andric 964fe6060f1SDimitry Andric template <class LP> void ObjFile::parse() { 965fe6060f1SDimitry Andric using Header = typename LP::mach_header; 966fe6060f1SDimitry Andric using SegmentCommand = typename LP::segment_command; 967349cc55cSDimitry Andric using SectionHeader = typename LP::section; 968fe6060f1SDimitry Andric using NList = typename LP::nlist; 969fe6060f1SDimitry Andric 970fe6060f1SDimitry Andric auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 971fe6060f1SDimitry Andric auto *hdr = reinterpret_cast<const Header *>(mb.getBufferStart()); 972fe6060f1SDimitry Andric 973*bdd1243dSDimitry Andric uint32_t cpuType; 974*bdd1243dSDimitry Andric std::tie(cpuType, std::ignore) = getCPUTypeFromArchitecture(config->arch()); 975*bdd1243dSDimitry Andric if (hdr->cputype != cpuType) { 976*bdd1243dSDimitry Andric Architecture arch = 977*bdd1243dSDimitry Andric getArchitectureFromCpuType(hdr->cputype, hdr->cpusubtype); 978349cc55cSDimitry Andric auto msg = config->errorForArchMismatch 979349cc55cSDimitry Andric ? static_cast<void (*)(const Twine &)>(error) 980349cc55cSDimitry Andric : warn; 981349cc55cSDimitry Andric msg(toString(this) + " has architecture " + getArchitectureName(arch) + 982fe6060f1SDimitry Andric " which is incompatible with target architecture " + 983fe6060f1SDimitry Andric getArchitectureName(config->arch())); 984fe6060f1SDimitry Andric return; 985fe6060f1SDimitry Andric } 986fe6060f1SDimitry Andric 987fe6060f1SDimitry Andric if (!checkCompatibility(this)) 988fe6060f1SDimitry Andric return; 989fe6060f1SDimitry Andric 990fe6060f1SDimitry Andric for (auto *cmd : findCommands<linker_option_command>(hdr, LC_LINKER_OPTION)) { 991fe6060f1SDimitry Andric StringRef data{reinterpret_cast<const char *>(cmd + 1), 992fe6060f1SDimitry Andric cmd->cmdsize - sizeof(linker_option_command)}; 993fe6060f1SDimitry Andric parseLCLinkerOption(this, cmd->count, data); 994fe6060f1SDimitry Andric } 995fe6060f1SDimitry Andric 996349cc55cSDimitry Andric ArrayRef<SectionHeader> sectionHeaders; 997fe6060f1SDimitry Andric if (const load_command *cmd = findCommand(hdr, LP::segmentLCType)) { 998fe6060f1SDimitry Andric auto *c = reinterpret_cast<const SegmentCommand *>(cmd); 999349cc55cSDimitry Andric sectionHeaders = ArrayRef<SectionHeader>{ 1000349cc55cSDimitry Andric reinterpret_cast<const SectionHeader *>(c + 1), c->nsects}; 10015ffd83dbSDimitry Andric parseSections(sectionHeaders); 10025ffd83dbSDimitry Andric } 10035ffd83dbSDimitry Andric 10045ffd83dbSDimitry Andric // TODO: Error on missing LC_SYMTAB? 10055ffd83dbSDimitry Andric if (const load_command *cmd = findCommand(hdr, LC_SYMTAB)) { 10065ffd83dbSDimitry Andric auto *c = reinterpret_cast<const symtab_command *>(cmd); 1007fe6060f1SDimitry Andric ArrayRef<NList> nList(reinterpret_cast<const NList *>(buf + c->symoff), 1008fe6060f1SDimitry Andric c->nsyms); 10095ffd83dbSDimitry Andric const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff; 10105ffd83dbSDimitry Andric bool subsectionsViaSymbols = hdr->flags & MH_SUBSECTIONS_VIA_SYMBOLS; 1011fe6060f1SDimitry Andric parseSymbols<LP>(sectionHeaders, nList, strtab, subsectionsViaSymbols); 10125ffd83dbSDimitry Andric } 10135ffd83dbSDimitry Andric 10145ffd83dbSDimitry Andric // The relocations may refer to the symbols, so we parse them after we have 10155ffd83dbSDimitry Andric // parsed all the symbols. 1016349cc55cSDimitry Andric for (size_t i = 0, n = sections.size(); i < n; ++i) 101781ad6265SDimitry Andric if (!sections[i]->subsections.empty()) 101881ad6265SDimitry Andric parseRelocations(sectionHeaders, sectionHeaders[i], *sections[i]); 101981ad6265SDimitry Andric 1020e8d8bef9SDimitry Andric parseDebugInfo(); 102181ad6265SDimitry Andric 102281ad6265SDimitry Andric Section *ehFrameSection = nullptr; 102381ad6265SDimitry Andric Section *compactUnwindSection = nullptr; 102481ad6265SDimitry Andric for (Section *sec : sections) { 102581ad6265SDimitry Andric Section **s = StringSwitch<Section **>(sec->name) 102681ad6265SDimitry Andric .Case(section_names::compactUnwind, &compactUnwindSection) 102781ad6265SDimitry Andric .Case(section_names::ehFrame, &ehFrameSection) 102881ad6265SDimitry Andric .Default(nullptr); 102981ad6265SDimitry Andric if (s) 103081ad6265SDimitry Andric *s = sec; 103181ad6265SDimitry Andric } 1032349cc55cSDimitry Andric if (compactUnwindSection) 103381ad6265SDimitry Andric registerCompactUnwind(*compactUnwindSection); 1034753f127fSDimitry Andric if (ehFrameSection) 103581ad6265SDimitry Andric registerEhFrames(*ehFrameSection); 1036e8d8bef9SDimitry Andric } 1037e8d8bef9SDimitry Andric 103804eeddc0SDimitry Andric template <class LP> void ObjFile::parseLazy() { 103904eeddc0SDimitry Andric using Header = typename LP::mach_header; 104004eeddc0SDimitry Andric using NList = typename LP::nlist; 104104eeddc0SDimitry Andric 104204eeddc0SDimitry Andric auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 104304eeddc0SDimitry Andric auto *hdr = reinterpret_cast<const Header *>(mb.getBufferStart()); 104404eeddc0SDimitry Andric const load_command *cmd = findCommand(hdr, LC_SYMTAB); 104504eeddc0SDimitry Andric if (!cmd) 104604eeddc0SDimitry Andric return; 104704eeddc0SDimitry Andric auto *c = reinterpret_cast<const symtab_command *>(cmd); 104804eeddc0SDimitry Andric ArrayRef<NList> nList(reinterpret_cast<const NList *>(buf + c->symoff), 104904eeddc0SDimitry Andric c->nsyms); 105004eeddc0SDimitry Andric const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff; 105104eeddc0SDimitry Andric symbols.resize(nList.size()); 1052*bdd1243dSDimitry Andric for (const auto &[i, sym] : llvm::enumerate(nList)) { 105304eeddc0SDimitry Andric if ((sym.n_type & N_EXT) && !isUndef(sym)) { 105404eeddc0SDimitry Andric // TODO: Bound checking 105504eeddc0SDimitry Andric StringRef name = strtab + sym.n_strx; 1056*bdd1243dSDimitry Andric symbols[i] = symtab->addLazyObject(name, *this); 105704eeddc0SDimitry Andric if (!lazy) 105804eeddc0SDimitry Andric break; 105904eeddc0SDimitry Andric } 106004eeddc0SDimitry Andric } 106104eeddc0SDimitry Andric } 106204eeddc0SDimitry Andric 1063e8d8bef9SDimitry Andric void ObjFile::parseDebugInfo() { 1064e8d8bef9SDimitry Andric std::unique_ptr<DwarfObject> dObj = DwarfObject::create(this); 1065e8d8bef9SDimitry Andric if (!dObj) 1066e8d8bef9SDimitry Andric return; 1067e8d8bef9SDimitry Andric 106881ad6265SDimitry Andric // We do not re-use the context from getDwarf() here as that function 106981ad6265SDimitry Andric // constructs an expensive DWARFCache object. 1070e8d8bef9SDimitry Andric auto *ctx = make<DWARFContext>( 1071e8d8bef9SDimitry Andric std::move(dObj), "", 1072e8d8bef9SDimitry Andric [&](Error err) { 1073e8d8bef9SDimitry Andric warn(toString(this) + ": " + toString(std::move(err))); 1074e8d8bef9SDimitry Andric }, 1075e8d8bef9SDimitry Andric [&](Error warning) { 1076e8d8bef9SDimitry Andric warn(toString(this) + ": " + toString(std::move(warning))); 1077e8d8bef9SDimitry Andric }); 1078e8d8bef9SDimitry Andric 1079e8d8bef9SDimitry Andric // TODO: Since object files can contain a lot of DWARF info, we should verify 1080e8d8bef9SDimitry Andric // that we are parsing just the info we need 1081e8d8bef9SDimitry Andric const DWARFContext::compile_unit_range &units = ctx->compile_units(); 1082fe6060f1SDimitry Andric // FIXME: There can be more than one compile unit per object file. See 1083fe6060f1SDimitry Andric // PR48637. 1084e8d8bef9SDimitry Andric auto it = units.begin(); 108581ad6265SDimitry Andric compileUnit = it != units.end() ? it->get() : nullptr; 1086fe6060f1SDimitry Andric } 1087fe6060f1SDimitry Andric 10880eae32dcSDimitry Andric ArrayRef<data_in_code_entry> ObjFile::getDataInCode() const { 1089fe6060f1SDimitry Andric const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 1090fe6060f1SDimitry Andric const load_command *cmd = findCommand(buf, LC_DATA_IN_CODE); 1091fe6060f1SDimitry Andric if (!cmd) 10920eae32dcSDimitry Andric return {}; 1093fe6060f1SDimitry Andric const auto *c = reinterpret_cast<const linkedit_data_command *>(cmd); 10940eae32dcSDimitry Andric return {reinterpret_cast<const data_in_code_entry *>(buf + c->dataoff), 1095fe6060f1SDimitry Andric c->datasize / sizeof(data_in_code_entry)}; 1096e8d8bef9SDimitry Andric } 1097e8d8bef9SDimitry Andric 1098*bdd1243dSDimitry Andric ArrayRef<uint8_t> ObjFile::getOptimizationHints() const { 1099*bdd1243dSDimitry Andric const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 1100*bdd1243dSDimitry Andric if (auto *cmd = 1101*bdd1243dSDimitry Andric findCommand<linkedit_data_command>(buf, LC_LINKER_OPTIMIZATION_HINT)) 1102*bdd1243dSDimitry Andric return {buf + cmd->dataoff, cmd->datasize}; 1103*bdd1243dSDimitry Andric return {}; 1104*bdd1243dSDimitry Andric } 1105*bdd1243dSDimitry Andric 1106349cc55cSDimitry Andric // Create pointers from symbols to their associated compact unwind entries. 110781ad6265SDimitry Andric void ObjFile::registerCompactUnwind(Section &compactUnwindSection) { 110881ad6265SDimitry Andric for (const Subsection &subsection : compactUnwindSection.subsections) { 1109349cc55cSDimitry Andric ConcatInputSection *isec = cast<ConcatInputSection>(subsection.isec); 1110fcaf7f86SDimitry Andric // Hack!! Each compact unwind entry (CUE) has its UNSIGNED relocations embed 1111fcaf7f86SDimitry Andric // their addends in its data. Thus if ICF operated naively and compared the 1112fcaf7f86SDimitry Andric // entire contents of each CUE, entries with identical unwind info but e.g. 1113fcaf7f86SDimitry Andric // belonging to different functions would never be considered equivalent. To 1114fcaf7f86SDimitry Andric // work around this problem, we remove some parts of the data containing the 1115fcaf7f86SDimitry Andric // embedded addends. In particular, we remove the function address and LSDA 1116fcaf7f86SDimitry Andric // pointers. Since these locations are at the start and end of the entry, 1117fcaf7f86SDimitry Andric // we can do this using a simple, efficient slice rather than performing a 1118fcaf7f86SDimitry Andric // copy. We are not losing any information here because the embedded 1119fcaf7f86SDimitry Andric // addends have already been parsed in the corresponding Reloc structs. 1120fcaf7f86SDimitry Andric // 1121fcaf7f86SDimitry Andric // Removing these pointers would not be safe if they were pointers to 1122fcaf7f86SDimitry Andric // absolute symbols. In that case, there would be no corresponding 1123fcaf7f86SDimitry Andric // relocation. However, (AFAIK) MC cannot emit references to absolute 1124fcaf7f86SDimitry Andric // symbols for either the function address or the LSDA. However, it *can* do 1125fcaf7f86SDimitry Andric // so for the personality pointer, so we are not slicing that field away. 1126fcaf7f86SDimitry Andric // 1127fcaf7f86SDimitry Andric // Note that we do not adjust the offsets of the corresponding relocations; 1128fcaf7f86SDimitry Andric // instead, we rely on `relocateCompactUnwind()` to correctly handle these 1129fcaf7f86SDimitry Andric // truncated input sections. 1130fcaf7f86SDimitry Andric isec->data = isec->data.slice(target->wordSize, 8 + target->wordSize); 113181ad6265SDimitry Andric uint32_t encoding = read32le(isec->data.data() + sizeof(uint32_t)); 113281ad6265SDimitry Andric // llvm-mc omits CU entries for functions that need DWARF encoding, but 113381ad6265SDimitry Andric // `ld -r` doesn't. We can ignore them because we will re-synthesize these 113481ad6265SDimitry Andric // CU entries from the DWARF info during the output phase. 1135*bdd1243dSDimitry Andric if ((encoding & static_cast<uint32_t>(UNWIND_MODE_MASK)) == 1136*bdd1243dSDimitry Andric target->modeDwarfEncoding) 113781ad6265SDimitry Andric continue; 1138349cc55cSDimitry Andric 1139349cc55cSDimitry Andric ConcatInputSection *referentIsec; 1140349cc55cSDimitry Andric for (auto it = isec->relocs.begin(); it != isec->relocs.end();) { 1141349cc55cSDimitry Andric Reloc &r = *it; 1142349cc55cSDimitry Andric // CUE::functionAddress is at offset 0. Skip personality & LSDA relocs. 1143349cc55cSDimitry Andric if (r.offset != 0) { 1144349cc55cSDimitry Andric ++it; 1145349cc55cSDimitry Andric continue; 1146349cc55cSDimitry Andric } 1147349cc55cSDimitry Andric uint64_t add = r.addend; 1148349cc55cSDimitry Andric if (auto *sym = cast_or_null<Defined>(r.referent.dyn_cast<Symbol *>())) { 1149349cc55cSDimitry Andric // Check whether the symbol defined in this file is the prevailing one. 1150349cc55cSDimitry Andric // Skip if it is e.g. a weak def that didn't prevail. 1151349cc55cSDimitry Andric if (sym->getFile() != this) { 1152349cc55cSDimitry Andric ++it; 1153349cc55cSDimitry Andric continue; 1154349cc55cSDimitry Andric } 1155349cc55cSDimitry Andric add += sym->value; 1156349cc55cSDimitry Andric referentIsec = cast<ConcatInputSection>(sym->isec); 1157349cc55cSDimitry Andric } else { 1158349cc55cSDimitry Andric referentIsec = 1159349cc55cSDimitry Andric cast<ConcatInputSection>(r.referent.dyn_cast<InputSection *>()); 1160349cc55cSDimitry Andric } 116181ad6265SDimitry Andric // Unwind info lives in __DATA, and finalization of __TEXT will occur 116281ad6265SDimitry Andric // before finalization of __DATA. Moreover, the finalization of unwind 116381ad6265SDimitry Andric // info depends on the exact addresses that it references. So it is safe 116481ad6265SDimitry Andric // for compact unwind to reference addresses in __TEXT, but not addresses 116581ad6265SDimitry Andric // in any other segment. 1166349cc55cSDimitry Andric if (referentIsec->getSegName() != segment_names::text) 116781ad6265SDimitry Andric error(isec->getLocation(r.offset) + " references section " + 116881ad6265SDimitry Andric referentIsec->getName() + " which is not in segment __TEXT"); 1169349cc55cSDimitry Andric // The functionAddress relocations are typically section relocations. 1170349cc55cSDimitry Andric // However, unwind info operates on a per-symbol basis, so we search for 1171349cc55cSDimitry Andric // the function symbol here. 117281ad6265SDimitry Andric Defined *d = findSymbolAtOffset(referentIsec, add); 117381ad6265SDimitry Andric if (!d) { 1174349cc55cSDimitry Andric ++it; 1175349cc55cSDimitry Andric continue; 1176349cc55cSDimitry Andric } 117781ad6265SDimitry Andric d->unwindEntry = isec; 1178fcaf7f86SDimitry Andric // Now that the symbol points to the unwind entry, we can remove the reloc 1179fcaf7f86SDimitry Andric // that points from the unwind entry back to the symbol. 1180fcaf7f86SDimitry Andric // 1181fcaf7f86SDimitry Andric // First, the symbol keeps the unwind entry alive (and not vice versa), so 1182fcaf7f86SDimitry Andric // this keeps dead-stripping simple. 1183fcaf7f86SDimitry Andric // 1184fcaf7f86SDimitry Andric // Moreover, it reduces the work that ICF needs to do to figure out if 1185fcaf7f86SDimitry Andric // functions with unwind info are foldable. 1186fcaf7f86SDimitry Andric // 1187fcaf7f86SDimitry Andric // However, this does make it possible for ICF to fold CUEs that point to 1188fcaf7f86SDimitry Andric // distinct functions (if the CUEs are otherwise identical). 1189fcaf7f86SDimitry Andric // UnwindInfoSection takes care of this by re-duplicating the CUEs so that 1190fcaf7f86SDimitry Andric // each one can hold a distinct functionAddress value. 1191fcaf7f86SDimitry Andric // 1192fcaf7f86SDimitry Andric // Given that clang emits relocations in reverse order of address, this 1193fcaf7f86SDimitry Andric // relocation should be at the end of the vector for most of our input 1194fcaf7f86SDimitry Andric // object files, so this erase() is typically an O(1) operation. 1195349cc55cSDimitry Andric it = isec->relocs.erase(it); 1196349cc55cSDimitry Andric } 1197349cc55cSDimitry Andric } 1198349cc55cSDimitry Andric } 1199349cc55cSDimitry Andric 120081ad6265SDimitry Andric struct CIE { 120181ad6265SDimitry Andric macho::Symbol *personalitySymbol = nullptr; 120281ad6265SDimitry Andric bool fdesHaveAug = false; 120361cfbce3SDimitry Andric uint8_t lsdaPtrSize = 0; // 0 => no LSDA 120461cfbce3SDimitry Andric uint8_t funcPtrSize = 0; 120581ad6265SDimitry Andric }; 120681ad6265SDimitry Andric 120761cfbce3SDimitry Andric static uint8_t pointerEncodingToSize(uint8_t enc) { 120861cfbce3SDimitry Andric switch (enc & 0xf) { 120961cfbce3SDimitry Andric case dwarf::DW_EH_PE_absptr: 121061cfbce3SDimitry Andric return target->wordSize; 121161cfbce3SDimitry Andric case dwarf::DW_EH_PE_sdata4: 121261cfbce3SDimitry Andric return 4; 121361cfbce3SDimitry Andric case dwarf::DW_EH_PE_sdata8: 121461cfbce3SDimitry Andric // ld64 doesn't actually support sdata8, but this seems simple enough... 121561cfbce3SDimitry Andric return 8; 121661cfbce3SDimitry Andric default: 121761cfbce3SDimitry Andric return 0; 121861cfbce3SDimitry Andric }; 121961cfbce3SDimitry Andric } 122061cfbce3SDimitry Andric 122181ad6265SDimitry Andric static CIE parseCIE(const InputSection *isec, const EhReader &reader, 122281ad6265SDimitry Andric size_t off) { 122381ad6265SDimitry Andric // Handling the full generality of possible DWARF encodings would be a major 122481ad6265SDimitry Andric // pain. We instead take advantage of our knowledge of how llvm-mc encodes 122581ad6265SDimitry Andric // DWARF and handle just that. 122681ad6265SDimitry Andric constexpr uint8_t expectedPersonalityEnc = 122781ad6265SDimitry Andric dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_sdata4; 122881ad6265SDimitry Andric 122981ad6265SDimitry Andric CIE cie; 123081ad6265SDimitry Andric uint8_t version = reader.readByte(&off); 123181ad6265SDimitry Andric if (version != 1 && version != 3) 123281ad6265SDimitry Andric fatal("Expected CIE version of 1 or 3, got " + Twine(version)); 123381ad6265SDimitry Andric StringRef aug = reader.readString(&off); 123481ad6265SDimitry Andric reader.skipLeb128(&off); // skip code alignment 123581ad6265SDimitry Andric reader.skipLeb128(&off); // skip data alignment 123681ad6265SDimitry Andric reader.skipLeb128(&off); // skip return address register 123781ad6265SDimitry Andric reader.skipLeb128(&off); // skip aug data length 123881ad6265SDimitry Andric uint64_t personalityAddrOff = 0; 123981ad6265SDimitry Andric for (char c : aug) { 124081ad6265SDimitry Andric switch (c) { 124181ad6265SDimitry Andric case 'z': 124281ad6265SDimitry Andric cie.fdesHaveAug = true; 124381ad6265SDimitry Andric break; 124481ad6265SDimitry Andric case 'P': { 124581ad6265SDimitry Andric uint8_t personalityEnc = reader.readByte(&off); 124681ad6265SDimitry Andric if (personalityEnc != expectedPersonalityEnc) 124781ad6265SDimitry Andric reader.failOn(off, "unexpected personality encoding 0x" + 124881ad6265SDimitry Andric Twine::utohexstr(personalityEnc)); 124981ad6265SDimitry Andric personalityAddrOff = off; 125081ad6265SDimitry Andric off += 4; 125181ad6265SDimitry Andric break; 125281ad6265SDimitry Andric } 125381ad6265SDimitry Andric case 'L': { 125481ad6265SDimitry Andric uint8_t lsdaEnc = reader.readByte(&off); 125561cfbce3SDimitry Andric cie.lsdaPtrSize = pointerEncodingToSize(lsdaEnc); 125661cfbce3SDimitry Andric if (cie.lsdaPtrSize == 0) 125781ad6265SDimitry Andric reader.failOn(off, "unexpected LSDA encoding 0x" + 125881ad6265SDimitry Andric Twine::utohexstr(lsdaEnc)); 125981ad6265SDimitry Andric break; 126081ad6265SDimitry Andric } 126181ad6265SDimitry Andric case 'R': { 126281ad6265SDimitry Andric uint8_t pointerEnc = reader.readByte(&off); 126361cfbce3SDimitry Andric cie.funcPtrSize = pointerEncodingToSize(pointerEnc); 126461cfbce3SDimitry Andric if (cie.funcPtrSize == 0 || !(pointerEnc & dwarf::DW_EH_PE_pcrel)) 126581ad6265SDimitry Andric reader.failOn(off, "unexpected pointer encoding 0x" + 126681ad6265SDimitry Andric Twine::utohexstr(pointerEnc)); 126781ad6265SDimitry Andric break; 126881ad6265SDimitry Andric } 126981ad6265SDimitry Andric default: 127081ad6265SDimitry Andric break; 127181ad6265SDimitry Andric } 127281ad6265SDimitry Andric } 127381ad6265SDimitry Andric if (personalityAddrOff != 0) { 127481ad6265SDimitry Andric auto personalityRelocIt = 127581ad6265SDimitry Andric llvm::find_if(isec->relocs, [=](const macho::Reloc &r) { 127681ad6265SDimitry Andric return r.offset == personalityAddrOff; 127781ad6265SDimitry Andric }); 127881ad6265SDimitry Andric if (personalityRelocIt == isec->relocs.end()) 127981ad6265SDimitry Andric reader.failOn(off, "Failed to locate relocation for personality symbol"); 128081ad6265SDimitry Andric cie.personalitySymbol = personalityRelocIt->referent.get<macho::Symbol *>(); 128181ad6265SDimitry Andric } 128281ad6265SDimitry Andric return cie; 128381ad6265SDimitry Andric } 128481ad6265SDimitry Andric 128581ad6265SDimitry Andric // EH frame target addresses may be encoded as pcrel offsets. However, instead 128681ad6265SDimitry Andric // of using an actual pcrel reloc, ld64 emits subtractor relocations instead. 128781ad6265SDimitry Andric // This function recovers the target address from the subtractors, essentially 128881ad6265SDimitry Andric // performing the inverse operation of EhRelocator. 128981ad6265SDimitry Andric // 129081ad6265SDimitry Andric // Concretely, we expect our relocations to write the value of `PC - 129181ad6265SDimitry Andric // target_addr` to `PC`. `PC` itself is denoted by a minuend relocation that 129281ad6265SDimitry Andric // points to a symbol plus an addend. 129381ad6265SDimitry Andric // 129481ad6265SDimitry Andric // It is important that the minuend relocation point to a symbol within the 129581ad6265SDimitry Andric // same section as the fixup value, since sections may get moved around. 129681ad6265SDimitry Andric // 129781ad6265SDimitry Andric // For example, for arm64, llvm-mc emits relocations for the target function 129881ad6265SDimitry Andric // address like so: 129981ad6265SDimitry Andric // 130081ad6265SDimitry Andric // ltmp: 130181ad6265SDimitry Andric // <CIE start> 130281ad6265SDimitry Andric // ... 130381ad6265SDimitry Andric // <CIE end> 130481ad6265SDimitry Andric // ... multiple FDEs ... 130581ad6265SDimitry Andric // <FDE start> 130681ad6265SDimitry Andric // <target function address - (ltmp + pcrel offset)> 130781ad6265SDimitry Andric // ... 130881ad6265SDimitry Andric // 130981ad6265SDimitry Andric // If any of the FDEs in `multiple FDEs` get dead-stripped, then `FDE start` 131081ad6265SDimitry Andric // will move to an earlier address, and `ltmp + pcrel offset` will no longer 131181ad6265SDimitry Andric // reflect an accurate pcrel value. To avoid this problem, we "canonicalize" 131281ad6265SDimitry Andric // our relocation by adding an `EH_Frame` symbol at `FDE start`, and updating 131381ad6265SDimitry Andric // the reloc to be `target function address - (EH_Frame + new pcrel offset)`. 131481ad6265SDimitry Andric // 131581ad6265SDimitry Andric // If `Invert` is set, then we instead expect `target_addr - PC` to be written 131681ad6265SDimitry Andric // to `PC`. 131781ad6265SDimitry Andric template <bool Invert = false> 131881ad6265SDimitry Andric Defined * 131981ad6265SDimitry Andric targetSymFromCanonicalSubtractor(const InputSection *isec, 132081ad6265SDimitry Andric std::vector<macho::Reloc>::iterator relocIt) { 132181ad6265SDimitry Andric macho::Reloc &subtrahend = *relocIt; 132281ad6265SDimitry Andric macho::Reloc &minuend = *std::next(relocIt); 132381ad6265SDimitry Andric assert(target->hasAttr(subtrahend.type, RelocAttrBits::SUBTRAHEND)); 132481ad6265SDimitry Andric assert(target->hasAttr(minuend.type, RelocAttrBits::UNSIGNED)); 132581ad6265SDimitry Andric // Note: pcSym may *not* be exactly at the PC; there's usually a non-zero 132681ad6265SDimitry Andric // addend. 132781ad6265SDimitry Andric auto *pcSym = cast<Defined>(subtrahend.referent.get<macho::Symbol *>()); 132881ad6265SDimitry Andric Defined *target = 132981ad6265SDimitry Andric cast_or_null<Defined>(minuend.referent.dyn_cast<macho::Symbol *>()); 133081ad6265SDimitry Andric if (!pcSym) { 133181ad6265SDimitry Andric auto *targetIsec = 133281ad6265SDimitry Andric cast<ConcatInputSection>(minuend.referent.get<InputSection *>()); 133381ad6265SDimitry Andric target = findSymbolAtOffset(targetIsec, minuend.addend); 133481ad6265SDimitry Andric } 133581ad6265SDimitry Andric if (Invert) 133681ad6265SDimitry Andric std::swap(pcSym, target); 133781ad6265SDimitry Andric if (pcSym->isec == isec) { 133881ad6265SDimitry Andric if (pcSym->value - (Invert ? -1 : 1) * minuend.addend != subtrahend.offset) 133981ad6265SDimitry Andric fatal("invalid FDE relocation in __eh_frame"); 134081ad6265SDimitry Andric } else { 134181ad6265SDimitry Andric // Ensure the pcReloc points to a symbol within the current EH frame. 134281ad6265SDimitry Andric // HACK: we should really verify that the original relocation's semantics 134381ad6265SDimitry Andric // are preserved. In particular, we should have 134481ad6265SDimitry Andric // `oldSym->value + oldOffset == newSym + newOffset`. However, we don't 134581ad6265SDimitry Andric // have an easy way to access the offsets from this point in the code; some 134681ad6265SDimitry Andric // refactoring is needed for that. 134781ad6265SDimitry Andric macho::Reloc &pcReloc = Invert ? minuend : subtrahend; 134881ad6265SDimitry Andric pcReloc.referent = isec->symbols[0]; 134981ad6265SDimitry Andric assert(isec->symbols[0]->value == 0); 135081ad6265SDimitry Andric minuend.addend = pcReloc.offset * (Invert ? 1LL : -1LL); 135181ad6265SDimitry Andric } 135281ad6265SDimitry Andric return target; 135381ad6265SDimitry Andric } 135481ad6265SDimitry Andric 135581ad6265SDimitry Andric Defined *findSymbolAtAddress(const std::vector<Section *> §ions, 135681ad6265SDimitry Andric uint64_t addr) { 135781ad6265SDimitry Andric Section *sec = findContainingSection(sections, &addr); 135881ad6265SDimitry Andric auto *isec = cast<ConcatInputSection>(findContainingSubsection(*sec, &addr)); 135981ad6265SDimitry Andric return findSymbolAtOffset(isec, addr); 136081ad6265SDimitry Andric } 136181ad6265SDimitry Andric 136281ad6265SDimitry Andric // For symbols that don't have compact unwind info, associate them with the more 136381ad6265SDimitry Andric // general-purpose (and verbose) DWARF unwind info found in __eh_frame. 136481ad6265SDimitry Andric // 136581ad6265SDimitry Andric // This requires us to parse the contents of __eh_frame. See EhFrame.h for a 136681ad6265SDimitry Andric // description of its format. 136781ad6265SDimitry Andric // 136881ad6265SDimitry Andric // While parsing, we also look for what MC calls "abs-ified" relocations -- they 136981ad6265SDimitry Andric // are relocations which are implicitly encoded as offsets in the section data. 137081ad6265SDimitry Andric // We convert them into explicit Reloc structs so that the EH frames can be 137181ad6265SDimitry Andric // handled just like a regular ConcatInputSection later in our output phase. 137281ad6265SDimitry Andric // 137381ad6265SDimitry Andric // We also need to handle the case where our input object file has explicit 137481ad6265SDimitry Andric // relocations. This is the case when e.g. it's the output of `ld -r`. We only 137581ad6265SDimitry Andric // look for the "abs-ified" relocation if an explicit relocation is absent. 137681ad6265SDimitry Andric void ObjFile::registerEhFrames(Section &ehFrameSection) { 137781ad6265SDimitry Andric DenseMap<const InputSection *, CIE> cieMap; 137881ad6265SDimitry Andric for (const Subsection &subsec : ehFrameSection.subsections) { 137981ad6265SDimitry Andric auto *isec = cast<ConcatInputSection>(subsec.isec); 138081ad6265SDimitry Andric uint64_t isecOff = subsec.offset; 138181ad6265SDimitry Andric 138281ad6265SDimitry Andric // Subtractor relocs require the subtrahend to be a symbol reloc. Ensure 138381ad6265SDimitry Andric // that all EH frames have an associated symbol so that we can generate 138481ad6265SDimitry Andric // subtractor relocs that reference them. 138581ad6265SDimitry Andric if (isec->symbols.size() == 0) 1386*bdd1243dSDimitry Andric make<Defined>("EH_Frame", isec->getFile(), isec, /*value=*/0, 1387*bdd1243dSDimitry Andric isec->getSize(), /*isWeakDef=*/false, /*isExternal=*/false, 1388*bdd1243dSDimitry Andric /*isPrivateExtern=*/false, /*includeInSymtab=*/false, 1389*bdd1243dSDimitry Andric /*isThumb=*/false, /*isReferencedDynamically=*/false, 1390*bdd1243dSDimitry Andric /*noDeadStrip=*/false); 139181ad6265SDimitry Andric else if (isec->symbols[0]->value != 0) 139281ad6265SDimitry Andric fatal("found symbol at unexpected offset in __eh_frame"); 139381ad6265SDimitry Andric 139461cfbce3SDimitry Andric EhReader reader(this, isec->data, subsec.offset); 139581ad6265SDimitry Andric size_t dataOff = 0; // Offset from the start of the EH frame. 139681ad6265SDimitry Andric reader.skipValidLength(&dataOff); // readLength() already validated this. 139781ad6265SDimitry Andric // cieOffOff is the offset from the start of the EH frame to the cieOff 139881ad6265SDimitry Andric // value, which is itself an offset from the current PC to a CIE. 139981ad6265SDimitry Andric const size_t cieOffOff = dataOff; 140081ad6265SDimitry Andric 140181ad6265SDimitry Andric EhRelocator ehRelocator(isec); 140281ad6265SDimitry Andric auto cieOffRelocIt = llvm::find_if( 140381ad6265SDimitry Andric isec->relocs, [=](const Reloc &r) { return r.offset == cieOffOff; }); 140481ad6265SDimitry Andric InputSection *cieIsec = nullptr; 140581ad6265SDimitry Andric if (cieOffRelocIt != isec->relocs.end()) { 140681ad6265SDimitry Andric // We already have an explicit relocation for the CIE offset. 140781ad6265SDimitry Andric cieIsec = 140881ad6265SDimitry Andric targetSymFromCanonicalSubtractor</*Invert=*/true>(isec, cieOffRelocIt) 140981ad6265SDimitry Andric ->isec; 141081ad6265SDimitry Andric dataOff += sizeof(uint32_t); 141181ad6265SDimitry Andric } else { 141281ad6265SDimitry Andric // If we haven't found a relocation, then the CIE offset is most likely 141381ad6265SDimitry Andric // embedded in the section data (AKA an "abs-ified" reloc.). Parse that 141481ad6265SDimitry Andric // and generate a Reloc struct. 141581ad6265SDimitry Andric uint32_t cieMinuend = reader.readU32(&dataOff); 1416*bdd1243dSDimitry Andric if (cieMinuend == 0) { 141781ad6265SDimitry Andric cieIsec = isec; 1418*bdd1243dSDimitry Andric } else { 141981ad6265SDimitry Andric uint32_t cieOff = isecOff + dataOff - cieMinuend; 142081ad6265SDimitry Andric cieIsec = findContainingSubsection(ehFrameSection, &cieOff); 142181ad6265SDimitry Andric if (cieIsec == nullptr) 142281ad6265SDimitry Andric fatal("failed to find CIE"); 142381ad6265SDimitry Andric } 142481ad6265SDimitry Andric if (cieIsec != isec) 142581ad6265SDimitry Andric ehRelocator.makeNegativePcRel(cieOffOff, cieIsec->symbols[0], 142681ad6265SDimitry Andric /*length=*/2); 142781ad6265SDimitry Andric } 142881ad6265SDimitry Andric if (cieIsec == isec) { 142981ad6265SDimitry Andric cieMap[cieIsec] = parseCIE(isec, reader, dataOff); 143081ad6265SDimitry Andric continue; 143181ad6265SDimitry Andric } 143281ad6265SDimitry Andric 143381ad6265SDimitry Andric assert(cieMap.count(cieIsec)); 143481ad6265SDimitry Andric const CIE &cie = cieMap[cieIsec]; 143561cfbce3SDimitry Andric // Offset of the function address within the EH frame. 143661cfbce3SDimitry Andric const size_t funcAddrOff = dataOff; 143761cfbce3SDimitry Andric uint64_t funcAddr = reader.readPointer(&dataOff, cie.funcPtrSize) + 143861cfbce3SDimitry Andric ehFrameSection.addr + isecOff + funcAddrOff; 143961cfbce3SDimitry Andric uint32_t funcLength = reader.readPointer(&dataOff, cie.funcPtrSize); 144061cfbce3SDimitry Andric size_t lsdaAddrOff = 0; // Offset of the LSDA address within the EH frame. 1441*bdd1243dSDimitry Andric std::optional<uint64_t> lsdaAddrOpt; 144281ad6265SDimitry Andric if (cie.fdesHaveAug) { 144381ad6265SDimitry Andric reader.skipLeb128(&dataOff); 144481ad6265SDimitry Andric lsdaAddrOff = dataOff; 144561cfbce3SDimitry Andric if (cie.lsdaPtrSize != 0) { 144661cfbce3SDimitry Andric uint64_t lsdaOff = reader.readPointer(&dataOff, cie.lsdaPtrSize); 144781ad6265SDimitry Andric if (lsdaOff != 0) // FIXME possible to test this? 144881ad6265SDimitry Andric lsdaAddrOpt = ehFrameSection.addr + isecOff + lsdaAddrOff + lsdaOff; 144981ad6265SDimitry Andric } 145081ad6265SDimitry Andric } 145181ad6265SDimitry Andric 145281ad6265SDimitry Andric auto funcAddrRelocIt = isec->relocs.end(); 145381ad6265SDimitry Andric auto lsdaAddrRelocIt = isec->relocs.end(); 145481ad6265SDimitry Andric for (auto it = isec->relocs.begin(); it != isec->relocs.end(); ++it) { 145581ad6265SDimitry Andric if (it->offset == funcAddrOff) 145681ad6265SDimitry Andric funcAddrRelocIt = it++; // Found subtrahend; skip over minuend reloc 145781ad6265SDimitry Andric else if (lsdaAddrOpt && it->offset == lsdaAddrOff) 145881ad6265SDimitry Andric lsdaAddrRelocIt = it++; // Found subtrahend; skip over minuend reloc 145981ad6265SDimitry Andric } 146081ad6265SDimitry Andric 146181ad6265SDimitry Andric Defined *funcSym; 146281ad6265SDimitry Andric if (funcAddrRelocIt != isec->relocs.end()) { 146381ad6265SDimitry Andric funcSym = targetSymFromCanonicalSubtractor(isec, funcAddrRelocIt); 1464fcaf7f86SDimitry Andric // Canonicalize the symbol. If there are multiple symbols at the same 1465fcaf7f86SDimitry Andric // address, we want both `registerEhFrame` and `registerCompactUnwind` 1466fcaf7f86SDimitry Andric // to register the unwind entry under same symbol. 1467fcaf7f86SDimitry Andric // This is not particularly efficient, but we should run into this case 1468fcaf7f86SDimitry Andric // infrequently (only when handling the output of `ld -r`). 1469fcaf7f86SDimitry Andric if (funcSym->isec) 1470fcaf7f86SDimitry Andric funcSym = findSymbolAtOffset(cast<ConcatInputSection>(funcSym->isec), 1471fcaf7f86SDimitry Andric funcSym->value); 147281ad6265SDimitry Andric } else { 147381ad6265SDimitry Andric funcSym = findSymbolAtAddress(sections, funcAddr); 147481ad6265SDimitry Andric ehRelocator.makePcRel(funcAddrOff, funcSym, target->p2WordSize); 147581ad6265SDimitry Andric } 147681ad6265SDimitry Andric // The symbol has been coalesced, or already has a compact unwind entry. 147781ad6265SDimitry Andric if (!funcSym || funcSym->getFile() != this || funcSym->unwindEntry) { 147881ad6265SDimitry Andric // We must prune unused FDEs for correctness, so we cannot rely on 147981ad6265SDimitry Andric // -dead_strip being enabled. 148081ad6265SDimitry Andric isec->live = false; 148181ad6265SDimitry Andric continue; 148281ad6265SDimitry Andric } 148381ad6265SDimitry Andric 148481ad6265SDimitry Andric InputSection *lsdaIsec = nullptr; 148581ad6265SDimitry Andric if (lsdaAddrRelocIt != isec->relocs.end()) { 148681ad6265SDimitry Andric lsdaIsec = targetSymFromCanonicalSubtractor(isec, lsdaAddrRelocIt)->isec; 148781ad6265SDimitry Andric } else if (lsdaAddrOpt) { 148881ad6265SDimitry Andric uint64_t lsdaAddr = *lsdaAddrOpt; 148981ad6265SDimitry Andric Section *sec = findContainingSection(sections, &lsdaAddr); 149081ad6265SDimitry Andric lsdaIsec = 149181ad6265SDimitry Andric cast<ConcatInputSection>(findContainingSubsection(*sec, &lsdaAddr)); 149281ad6265SDimitry Andric ehRelocator.makePcRel(lsdaAddrOff, lsdaIsec, target->p2WordSize); 149381ad6265SDimitry Andric } 149481ad6265SDimitry Andric 149581ad6265SDimitry Andric fdes[isec] = {funcLength, cie.personalitySymbol, lsdaIsec}; 149681ad6265SDimitry Andric funcSym->unwindEntry = isec; 149781ad6265SDimitry Andric ehRelocator.commit(); 149881ad6265SDimitry Andric } 14996246ae0bSDimitry Andric 15006246ae0bSDimitry Andric // __eh_frame is marked as S_ATTR_LIVE_SUPPORT in input files, because FDEs 15016246ae0bSDimitry Andric // are normally required to be kept alive if they reference a live symbol. 15026246ae0bSDimitry Andric // However, we've explicitly created a dependency from a symbol to its FDE, so 15036246ae0bSDimitry Andric // dead-stripping will just work as usual, and S_ATTR_LIVE_SUPPORT will only 15046246ae0bSDimitry Andric // serve to incorrectly prevent us from dead-stripping duplicate FDEs for a 15056246ae0bSDimitry Andric // live symbol (e.g. if there were multiple weak copies). Remove this flag to 15066246ae0bSDimitry Andric // let dead-stripping proceed correctly. 15076246ae0bSDimitry Andric ehFrameSection.flags &= ~S_ATTR_LIVE_SUPPORT; 150881ad6265SDimitry Andric } 150981ad6265SDimitry Andric 151081ad6265SDimitry Andric std::string ObjFile::sourceFile() const { 151181ad6265SDimitry Andric SmallString<261> dir(compileUnit->getCompilationDir()); 151281ad6265SDimitry Andric StringRef sep = sys::path::get_separator(); 151381ad6265SDimitry Andric // We don't use `path::append` here because we want an empty `dir` to result 151481ad6265SDimitry Andric // in an absolute path. `append` would give us a relative path for that case. 151581ad6265SDimitry Andric if (!dir.endswith(sep)) 151681ad6265SDimitry Andric dir += sep; 151781ad6265SDimitry Andric return (dir + compileUnit->getUnitDIE().getShortName()).str(); 151881ad6265SDimitry Andric } 151981ad6265SDimitry Andric 152081ad6265SDimitry Andric lld::DWARFCache *ObjFile::getDwarf() { 152181ad6265SDimitry Andric llvm::call_once(initDwarf, [this]() { 152281ad6265SDimitry Andric auto dwObj = DwarfObject::create(this); 152381ad6265SDimitry Andric if (!dwObj) 152481ad6265SDimitry Andric return; 152581ad6265SDimitry Andric dwarfCache = std::make_unique<DWARFCache>(std::make_unique<DWARFContext>( 152681ad6265SDimitry Andric std::move(dwObj), "", 152781ad6265SDimitry Andric [&](Error err) { warn(getName() + ": " + toString(std::move(err))); }, 152881ad6265SDimitry Andric [&](Error warning) { 152981ad6265SDimitry Andric warn(getName() + ": " + toString(std::move(warning))); 153081ad6265SDimitry Andric })); 153181ad6265SDimitry Andric }); 153281ad6265SDimitry Andric 153381ad6265SDimitry Andric return dwarfCache.get(); 153481ad6265SDimitry Andric } 1535e8d8bef9SDimitry Andric // The path can point to either a dylib or a .tbd file. 1536fe6060f1SDimitry Andric static DylibFile *loadDylib(StringRef path, DylibFile *umbrella) { 1537*bdd1243dSDimitry Andric std::optional<MemoryBufferRef> mbref = readFile(path); 1538e8d8bef9SDimitry Andric if (!mbref) { 1539e8d8bef9SDimitry Andric error("could not read dylib file at " + path); 1540fe6060f1SDimitry Andric return nullptr; 1541e8d8bef9SDimitry Andric } 1542e8d8bef9SDimitry Andric return loadDylib(*mbref, umbrella); 1543e8d8bef9SDimitry Andric } 1544e8d8bef9SDimitry Andric 1545e8d8bef9SDimitry Andric // TBD files are parsed into a series of TAPI documents (InterfaceFiles), with 1546e8d8bef9SDimitry Andric // the first document storing child pointers to the rest of them. When we are 1547fe6060f1SDimitry Andric // processing a given TBD file, we store that top-level document in 1548fe6060f1SDimitry Andric // currentTopLevelTapi. When processing re-exports, we search its children for 1549fe6060f1SDimitry Andric // potentially matching documents in the same TBD file. Note that the children 1550fe6060f1SDimitry Andric // themselves don't point to further documents, i.e. this is a two-level tree. 1551e8d8bef9SDimitry Andric // 1552e8d8bef9SDimitry Andric // Re-exports can either refer to on-disk files, or to documents within .tbd 1553e8d8bef9SDimitry Andric // files. 1554fe6060f1SDimitry Andric static DylibFile *findDylib(StringRef path, DylibFile *umbrella, 1555fe6060f1SDimitry Andric const InterfaceFile *currentTopLevelTapi) { 1556fe6060f1SDimitry Andric // Search order: 1557fe6060f1SDimitry Andric // 1. Install name basename in -F / -L directories. 1558fe6060f1SDimitry Andric { 1559fe6060f1SDimitry Andric StringRef stem = path::stem(path); 1560fe6060f1SDimitry Andric SmallString<128> frameworkName; 1561fe6060f1SDimitry Andric path::append(frameworkName, path::Style::posix, stem + ".framework", stem); 1562fe6060f1SDimitry Andric bool isFramework = path.endswith(frameworkName); 1563fe6060f1SDimitry Andric if (isFramework) { 1564fe6060f1SDimitry Andric for (StringRef dir : config->frameworkSearchPaths) { 1565fe6060f1SDimitry Andric SmallString<128> candidate = dir; 1566fe6060f1SDimitry Andric path::append(candidate, frameworkName); 1567*bdd1243dSDimitry Andric if (std::optional<StringRef> dylibPath = 1568*bdd1243dSDimitry Andric resolveDylibPath(candidate.str())) 1569fe6060f1SDimitry Andric return loadDylib(*dylibPath, umbrella); 1570fe6060f1SDimitry Andric } 1571*bdd1243dSDimitry Andric } else if (std::optional<StringRef> dylibPath = findPathCombination( 1572fe6060f1SDimitry Andric stem, config->librarySearchPaths, {".tbd", ".dylib"})) 1573fe6060f1SDimitry Andric return loadDylib(*dylibPath, umbrella); 1574fe6060f1SDimitry Andric } 1575fe6060f1SDimitry Andric 1576fe6060f1SDimitry Andric // 2. As absolute path. 1577e8d8bef9SDimitry Andric if (path::is_absolute(path, path::Style::posix)) 1578e8d8bef9SDimitry Andric for (StringRef root : config->systemLibraryRoots) 1579*bdd1243dSDimitry Andric if (std::optional<StringRef> dylibPath = 1580*bdd1243dSDimitry Andric resolveDylibPath((root + path).str())) 1581e8d8bef9SDimitry Andric return loadDylib(*dylibPath, umbrella); 1582e8d8bef9SDimitry Andric 1583fe6060f1SDimitry Andric // 3. As relative path. 1584e8d8bef9SDimitry Andric 1585fe6060f1SDimitry Andric // TODO: Handle -dylib_file 1586fe6060f1SDimitry Andric 1587fe6060f1SDimitry Andric // Replace @executable_path, @loader_path, @rpath prefixes in install name. 1588fe6060f1SDimitry Andric SmallString<128> newPath; 1589fe6060f1SDimitry Andric if (config->outputType == MH_EXECUTE && 1590fe6060f1SDimitry Andric path.consume_front("@executable_path/")) { 1591fe6060f1SDimitry Andric // ld64 allows overriding this with the undocumented flag -executable_path. 1592fe6060f1SDimitry Andric // lld doesn't currently implement that flag. 1593fe6060f1SDimitry Andric // FIXME: Consider using finalOutput instead of outputFile. 1594fe6060f1SDimitry Andric path::append(newPath, path::parent_path(config->outputFile), path); 1595fe6060f1SDimitry Andric path = newPath; 1596fe6060f1SDimitry Andric } else if (path.consume_front("@loader_path/")) { 1597fe6060f1SDimitry Andric fs::real_path(umbrella->getName(), newPath); 1598fe6060f1SDimitry Andric path::remove_filename(newPath); 1599fe6060f1SDimitry Andric path::append(newPath, path); 1600fe6060f1SDimitry Andric path = newPath; 1601fe6060f1SDimitry Andric } else if (path.startswith("@rpath/")) { 1602fe6060f1SDimitry Andric for (StringRef rpath : umbrella->rpaths) { 1603fe6060f1SDimitry Andric newPath.clear(); 1604fe6060f1SDimitry Andric if (rpath.consume_front("@loader_path/")) { 1605fe6060f1SDimitry Andric fs::real_path(umbrella->getName(), newPath); 1606fe6060f1SDimitry Andric path::remove_filename(newPath); 1607fe6060f1SDimitry Andric } 1608fe6060f1SDimitry Andric path::append(newPath, rpath, path.drop_front(strlen("@rpath/"))); 1609*bdd1243dSDimitry Andric if (std::optional<StringRef> dylibPath = resolveDylibPath(newPath.str())) 1610fe6060f1SDimitry Andric return loadDylib(*dylibPath, umbrella); 1611fe6060f1SDimitry Andric } 1612fe6060f1SDimitry Andric } 1613fe6060f1SDimitry Andric 1614fe6060f1SDimitry Andric // FIXME: Should this be further up? 1615e8d8bef9SDimitry Andric if (currentTopLevelTapi) { 1616e8d8bef9SDimitry Andric for (InterfaceFile &child : 1617e8d8bef9SDimitry Andric make_pointee_range(currentTopLevelTapi->documents())) { 1618e8d8bef9SDimitry Andric assert(child.documents().empty()); 1619fe6060f1SDimitry Andric if (path == child.getInstallName()) { 162081ad6265SDimitry Andric auto file = make<DylibFile>(child, umbrella, /*isBundleLoader=*/false, 162181ad6265SDimitry Andric /*explicitlyLinked=*/false); 1622fe6060f1SDimitry Andric file->parseReexports(child); 1623fe6060f1SDimitry Andric return file; 1624fe6060f1SDimitry Andric } 1625e8d8bef9SDimitry Andric } 1626e8d8bef9SDimitry Andric } 1627e8d8bef9SDimitry Andric 1628*bdd1243dSDimitry Andric if (std::optional<StringRef> dylibPath = resolveDylibPath(path)) 1629e8d8bef9SDimitry Andric return loadDylib(*dylibPath, umbrella); 1630e8d8bef9SDimitry Andric 1631fe6060f1SDimitry Andric return nullptr; 1632e8d8bef9SDimitry Andric } 1633e8d8bef9SDimitry Andric 1634e8d8bef9SDimitry Andric // If a re-exported dylib is public (lives in /usr/lib or 1635e8d8bef9SDimitry Andric // /System/Library/Frameworks), then it is considered implicitly linked: we 1636e8d8bef9SDimitry Andric // should bind to its symbols directly instead of via the re-exporting umbrella 1637e8d8bef9SDimitry Andric // library. 1638e8d8bef9SDimitry Andric static bool isImplicitlyLinked(StringRef path) { 1639e8d8bef9SDimitry Andric if (!config->implicitDylibs) 1640e8d8bef9SDimitry Andric return false; 1641e8d8bef9SDimitry Andric 1642e8d8bef9SDimitry Andric if (path::parent_path(path) == "/usr/lib") 1643e8d8bef9SDimitry Andric return true; 1644e8d8bef9SDimitry Andric 1645e8d8bef9SDimitry Andric // Match /System/Library/Frameworks/$FOO.framework/**/$FOO 1646e8d8bef9SDimitry Andric if (path.consume_front("/System/Library/Frameworks/")) { 1647e8d8bef9SDimitry Andric StringRef frameworkName = path.take_until([](char c) { return c == '.'; }); 1648e8d8bef9SDimitry Andric return path::filename(path) == frameworkName; 1649e8d8bef9SDimitry Andric } 1650e8d8bef9SDimitry Andric 1651e8d8bef9SDimitry Andric return false; 1652e8d8bef9SDimitry Andric } 1653e8d8bef9SDimitry Andric 1654*bdd1243dSDimitry Andric void DylibFile::loadReexport(StringRef path, DylibFile *umbrella, 1655fe6060f1SDimitry Andric const InterfaceFile *currentTopLevelTapi) { 1656fe6060f1SDimitry Andric DylibFile *reexport = findDylib(path, umbrella, currentTopLevelTapi); 1657fe6060f1SDimitry Andric if (!reexport) 1658*bdd1243dSDimitry Andric error(toString(this) + ": unable to locate re-export with install name " + 1659*bdd1243dSDimitry Andric path); 16605ffd83dbSDimitry Andric } 16615ffd83dbSDimitry Andric 1662fe6060f1SDimitry Andric DylibFile::DylibFile(MemoryBufferRef mb, DylibFile *umbrella, 166381ad6265SDimitry Andric bool isBundleLoader, bool explicitlyLinked) 1664fe6060f1SDimitry Andric : InputFile(DylibKind, mb), refState(RefState::Unreferenced), 166581ad6265SDimitry Andric explicitlyLinked(explicitlyLinked), isBundleLoader(isBundleLoader) { 1666fe6060f1SDimitry Andric assert(!isBundleLoader || !umbrella); 16675ffd83dbSDimitry Andric if (umbrella == nullptr) 16685ffd83dbSDimitry Andric umbrella = this; 1669fe6060f1SDimitry Andric this->umbrella = umbrella; 16705ffd83dbSDimitry Andric 1671fe6060f1SDimitry Andric auto *hdr = reinterpret_cast<const mach_header *>(mb.getBufferStart()); 16725ffd83dbSDimitry Andric 1673fe6060f1SDimitry Andric // Initialize installName. 16745ffd83dbSDimitry Andric if (const load_command *cmd = findCommand(hdr, LC_ID_DYLIB)) { 16755ffd83dbSDimitry Andric auto *c = reinterpret_cast<const dylib_command *>(cmd); 1676e8d8bef9SDimitry Andric currentVersion = read32le(&c->dylib.current_version); 1677e8d8bef9SDimitry Andric compatibilityVersion = read32le(&c->dylib.compatibility_version); 1678fe6060f1SDimitry Andric installName = 1679fe6060f1SDimitry Andric reinterpret_cast<const char *>(cmd) + read32le(&c->dylib.name); 1680fe6060f1SDimitry Andric } else if (!isBundleLoader) { 1681fe6060f1SDimitry Andric // macho_executable and macho_bundle don't have LC_ID_DYLIB, 1682fe6060f1SDimitry Andric // so it's OK. 1683*bdd1243dSDimitry Andric error(toString(this) + ": dylib missing LC_ID_DYLIB load command"); 16845ffd83dbSDimitry Andric return; 16855ffd83dbSDimitry Andric } 16865ffd83dbSDimitry Andric 1687fe6060f1SDimitry Andric if (config->printEachFile) 1688fe6060f1SDimitry Andric message(toString(this)); 1689fe6060f1SDimitry Andric inputFiles.insert(this); 1690fe6060f1SDimitry Andric 1691fe6060f1SDimitry Andric deadStrippable = hdr->flags & MH_DEAD_STRIPPABLE_DYLIB; 1692fe6060f1SDimitry Andric 1693fe6060f1SDimitry Andric if (!checkCompatibility(this)) 1694fe6060f1SDimitry Andric return; 1695fe6060f1SDimitry Andric 1696fe6060f1SDimitry Andric checkAppExtensionSafety(hdr->flags & MH_APP_EXTENSION_SAFE); 1697fe6060f1SDimitry Andric 1698fe6060f1SDimitry Andric for (auto *cmd : findCommands<rpath_command>(hdr, LC_RPATH)) { 1699fe6060f1SDimitry Andric StringRef rpath{reinterpret_cast<const char *>(cmd) + cmd->path}; 1700fe6060f1SDimitry Andric rpaths.push_back(rpath); 1701fe6060f1SDimitry Andric } 1702fe6060f1SDimitry Andric 17035ffd83dbSDimitry Andric // Initialize symbols. 1704fe6060f1SDimitry Andric exportingFile = isImplicitlyLinked(installName) ? this : this->umbrella; 1705753f127fSDimitry Andric 1706753f127fSDimitry Andric const auto *dyldInfo = findCommand<dyld_info_command>(hdr, LC_DYLD_INFO_ONLY); 1707753f127fSDimitry Andric const auto *exportsTrie = 1708753f127fSDimitry Andric findCommand<linkedit_data_command>(hdr, LC_DYLD_EXPORTS_TRIE); 1709753f127fSDimitry Andric if (dyldInfo && exportsTrie) { 1710753f127fSDimitry Andric // It's unclear what should happen in this case. Maybe we should only error 1711753f127fSDimitry Andric // out if the two load commands refer to different data? 1712*bdd1243dSDimitry Andric error(toString(this) + 1713*bdd1243dSDimitry Andric ": dylib has both LC_DYLD_INFO_ONLY and LC_DYLD_EXPORTS_TRIE"); 1714753f127fSDimitry Andric return; 1715753f127fSDimitry Andric } else if (dyldInfo) { 1716753f127fSDimitry Andric parseExportedSymbols(dyldInfo->export_off, dyldInfo->export_size); 1717753f127fSDimitry Andric } else if (exportsTrie) { 1718753f127fSDimitry Andric parseExportedSymbols(exportsTrie->dataoff, exportsTrie->datasize); 1719753f127fSDimitry Andric } else { 1720753f127fSDimitry Andric error("No LC_DYLD_INFO_ONLY or LC_DYLD_EXPORTS_TRIE found in " + 1721753f127fSDimitry Andric toString(this)); 1722753f127fSDimitry Andric return; 1723753f127fSDimitry Andric } 1724753f127fSDimitry Andric } 1725753f127fSDimitry Andric 1726753f127fSDimitry Andric void DylibFile::parseExportedSymbols(uint32_t offset, uint32_t size) { 17270eae32dcSDimitry Andric struct TrieEntry { 17280eae32dcSDimitry Andric StringRef name; 17290eae32dcSDimitry Andric uint64_t flags; 17300eae32dcSDimitry Andric }; 17310eae32dcSDimitry Andric 1732753f127fSDimitry Andric auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 17330eae32dcSDimitry Andric std::vector<TrieEntry> entries; 17340eae32dcSDimitry Andric // Find all the $ld$* symbols to process first. 1735753f127fSDimitry Andric parseTrie(buf + offset, size, [&](const Twine &name, uint64_t flags) { 173604eeddc0SDimitry Andric StringRef savedName = saver().save(name); 1737fe6060f1SDimitry Andric if (handleLDSymbol(savedName)) 1738fe6060f1SDimitry Andric return; 17390eae32dcSDimitry Andric entries.push_back({savedName, flags}); 17405ffd83dbSDimitry Andric }); 17410eae32dcSDimitry Andric 17420eae32dcSDimitry Andric // Process the "normal" symbols. 17430eae32dcSDimitry Andric for (TrieEntry &entry : entries) { 1744753f127fSDimitry Andric if (exportingFile->hiddenSymbols.contains(CachedHashStringRef(entry.name))) 17450eae32dcSDimitry Andric continue; 17460eae32dcSDimitry Andric 17470eae32dcSDimitry Andric bool isWeakDef = entry.flags & EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION; 17480eae32dcSDimitry Andric bool isTlv = entry.flags & EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL; 17490eae32dcSDimitry Andric 17500eae32dcSDimitry Andric symbols.push_back( 17510eae32dcSDimitry Andric symtab->addDylib(entry.name, exportingFile, isWeakDef, isTlv)); 17520eae32dcSDimitry Andric } 1753fe6060f1SDimitry Andric } 17545ffd83dbSDimitry Andric 1755fe6060f1SDimitry Andric void DylibFile::parseLoadCommands(MemoryBufferRef mb) { 1756fe6060f1SDimitry Andric auto *hdr = reinterpret_cast<const mach_header *>(mb.getBufferStart()); 1757fe6060f1SDimitry Andric const uint8_t *p = reinterpret_cast<const uint8_t *>(mb.getBufferStart()) + 1758fe6060f1SDimitry Andric target->headerSize; 17595ffd83dbSDimitry Andric for (uint32_t i = 0, n = hdr->ncmds; i < n; ++i) { 17605ffd83dbSDimitry Andric auto *cmd = reinterpret_cast<const load_command *>(p); 17615ffd83dbSDimitry Andric p += cmd->cmdsize; 17625ffd83dbSDimitry Andric 1763fe6060f1SDimitry Andric if (!(hdr->flags & MH_NO_REEXPORTED_DYLIBS) && 1764fe6060f1SDimitry Andric cmd->cmd == LC_REEXPORT_DYLIB) { 1765fe6060f1SDimitry Andric const auto *c = reinterpret_cast<const dylib_command *>(cmd); 17665ffd83dbSDimitry Andric StringRef reexportPath = 17675ffd83dbSDimitry Andric reinterpret_cast<const char *>(c) + read32le(&c->dylib.name); 1768fe6060f1SDimitry Andric loadReexport(reexportPath, exportingFile, nullptr); 1769fe6060f1SDimitry Andric } 1770fe6060f1SDimitry Andric 1771fe6060f1SDimitry Andric // FIXME: What about LC_LOAD_UPWARD_DYLIB, LC_LAZY_LOAD_DYLIB, 1772fe6060f1SDimitry Andric // LC_LOAD_WEAK_DYLIB, LC_REEXPORT_DYLIB (..are reexports from dylibs with 1773fe6060f1SDimitry Andric // MH_NO_REEXPORTED_DYLIBS loaded for -flat_namespace)? 1774fe6060f1SDimitry Andric if (config->namespaceKind == NamespaceKind::flat && 1775fe6060f1SDimitry Andric cmd->cmd == LC_LOAD_DYLIB) { 1776fe6060f1SDimitry Andric const auto *c = reinterpret_cast<const dylib_command *>(cmd); 1777fe6060f1SDimitry Andric StringRef dylibPath = 1778fe6060f1SDimitry Andric reinterpret_cast<const char *>(c) + read32le(&c->dylib.name); 1779fe6060f1SDimitry Andric DylibFile *dylib = findDylib(dylibPath, umbrella, nullptr); 1780fe6060f1SDimitry Andric if (!dylib) 1781fe6060f1SDimitry Andric error(Twine("unable to locate library '") + dylibPath + 1782fe6060f1SDimitry Andric "' loaded from '" + toString(this) + "' for -flat_namespace"); 1783fe6060f1SDimitry Andric } 17845ffd83dbSDimitry Andric } 17855ffd83dbSDimitry Andric } 17865ffd83dbSDimitry Andric 178781ad6265SDimitry Andric // Some versions of Xcode ship with .tbd files that don't have the right 1788fe6060f1SDimitry Andric // platform settings. 178981ad6265SDimitry Andric constexpr std::array<StringRef, 3> skipPlatformChecks{ 1790fe6060f1SDimitry Andric "/usr/lib/system/libsystem_kernel.dylib", 1791fe6060f1SDimitry Andric "/usr/lib/system/libsystem_platform.dylib", 1792fe6060f1SDimitry Andric "/usr/lib/system/libsystem_pthread.dylib"}; 1793fe6060f1SDimitry Andric 179481ad6265SDimitry Andric static bool skipPlatformCheckForCatalyst(const InterfaceFile &interface, 179581ad6265SDimitry Andric bool explicitlyLinked) { 179681ad6265SDimitry Andric // Catalyst outputs can link against implicitly linked macOS-only libraries. 179781ad6265SDimitry Andric if (config->platform() != PLATFORM_MACCATALYST || explicitlyLinked) 179881ad6265SDimitry Andric return false; 179981ad6265SDimitry Andric return is_contained(interface.targets(), 180081ad6265SDimitry Andric MachO::Target(config->arch(), PLATFORM_MACOS)); 180181ad6265SDimitry Andric } 180281ad6265SDimitry Andric 1803*bdd1243dSDimitry Andric static bool isArchABICompatible(ArchitectureSet archSet, 1804*bdd1243dSDimitry Andric Architecture targetArch) { 1805*bdd1243dSDimitry Andric uint32_t cpuType; 1806*bdd1243dSDimitry Andric uint32_t targetCpuType; 1807*bdd1243dSDimitry Andric std::tie(targetCpuType, std::ignore) = getCPUTypeFromArchitecture(targetArch); 1808*bdd1243dSDimitry Andric 1809*bdd1243dSDimitry Andric return llvm::any_of(archSet, [&](const auto &p) { 1810*bdd1243dSDimitry Andric std::tie(cpuType, std::ignore) = getCPUTypeFromArchitecture(p); 1811*bdd1243dSDimitry Andric return cpuType == targetCpuType; 1812*bdd1243dSDimitry Andric }); 1813*bdd1243dSDimitry Andric } 1814*bdd1243dSDimitry Andric 1815*bdd1243dSDimitry Andric static bool isTargetPlatformArchCompatible( 1816*bdd1243dSDimitry Andric InterfaceFile::const_target_range interfaceTargets, Target target) { 1817*bdd1243dSDimitry Andric if (is_contained(interfaceTargets, target)) 1818*bdd1243dSDimitry Andric return true; 1819*bdd1243dSDimitry Andric 1820*bdd1243dSDimitry Andric if (config->forceExactCpuSubtypeMatch) 1821*bdd1243dSDimitry Andric return false; 1822*bdd1243dSDimitry Andric 1823*bdd1243dSDimitry Andric ArchitectureSet archSet; 1824*bdd1243dSDimitry Andric for (const auto &p : interfaceTargets) 1825*bdd1243dSDimitry Andric if (p.Platform == target.Platform) 1826*bdd1243dSDimitry Andric archSet.set(p.Arch); 1827*bdd1243dSDimitry Andric if (archSet.empty()) 1828*bdd1243dSDimitry Andric return false; 1829*bdd1243dSDimitry Andric 1830*bdd1243dSDimitry Andric return isArchABICompatible(archSet, target.Arch); 1831*bdd1243dSDimitry Andric } 1832*bdd1243dSDimitry Andric 1833fe6060f1SDimitry Andric DylibFile::DylibFile(const InterfaceFile &interface, DylibFile *umbrella, 183481ad6265SDimitry Andric bool isBundleLoader, bool explicitlyLinked) 1835fe6060f1SDimitry Andric : InputFile(DylibKind, interface), refState(RefState::Unreferenced), 183681ad6265SDimitry Andric explicitlyLinked(explicitlyLinked), isBundleLoader(isBundleLoader) { 1837fe6060f1SDimitry Andric // FIXME: Add test for the missing TBD code path. 1838fe6060f1SDimitry Andric 18395ffd83dbSDimitry Andric if (umbrella == nullptr) 18405ffd83dbSDimitry Andric umbrella = this; 1841fe6060f1SDimitry Andric this->umbrella = umbrella; 18425ffd83dbSDimitry Andric 184304eeddc0SDimitry Andric installName = saver().save(interface.getInstallName()); 1844e8d8bef9SDimitry Andric compatibilityVersion = interface.getCompatibilityVersion().rawValue(); 1845e8d8bef9SDimitry Andric currentVersion = interface.getCurrentVersion().rawValue(); 1846fe6060f1SDimitry Andric 1847fe6060f1SDimitry Andric if (config->printEachFile) 1848fe6060f1SDimitry Andric message(toString(this)); 1849fe6060f1SDimitry Andric inputFiles.insert(this); 1850fe6060f1SDimitry Andric 1851fe6060f1SDimitry Andric if (!is_contained(skipPlatformChecks, installName) && 1852*bdd1243dSDimitry Andric !isTargetPlatformArchCompatible(interface.targets(), 1853*bdd1243dSDimitry Andric config->platformInfo.target) && 185481ad6265SDimitry Andric !skipPlatformCheckForCatalyst(interface, explicitlyLinked)) { 1855fe6060f1SDimitry Andric error(toString(this) + " is incompatible with " + 1856fe6060f1SDimitry Andric std::string(config->platformInfo.target)); 1857fe6060f1SDimitry Andric return; 1858fe6060f1SDimitry Andric } 1859fe6060f1SDimitry Andric 1860fe6060f1SDimitry Andric checkAppExtensionSafety(interface.isApplicationExtensionSafe()); 1861fe6060f1SDimitry Andric 1862fe6060f1SDimitry Andric exportingFile = isImplicitlyLinked(installName) ? this : umbrella; 1863*bdd1243dSDimitry Andric auto addSymbol = [&](const llvm::MachO::Symbol &symbol, 1864*bdd1243dSDimitry Andric const Twine &name) -> void { 186504eeddc0SDimitry Andric StringRef savedName = saver().save(name); 18660eae32dcSDimitry Andric if (exportingFile->hiddenSymbols.contains(CachedHashStringRef(savedName))) 18670eae32dcSDimitry Andric return; 18680eae32dcSDimitry Andric 18690eae32dcSDimitry Andric symbols.push_back(symtab->addDylib(savedName, exportingFile, 1870*bdd1243dSDimitry Andric symbol.isWeakDefined(), 1871*bdd1243dSDimitry Andric symbol.isThreadLocalValue())); 1872e8d8bef9SDimitry Andric }; 18730eae32dcSDimitry Andric 18740eae32dcSDimitry Andric std::vector<const llvm::MachO::Symbol *> normalSymbols; 18750eae32dcSDimitry Andric normalSymbols.reserve(interface.symbolsCount()); 1876fe6060f1SDimitry Andric for (const auto *symbol : interface.symbols()) { 1877*bdd1243dSDimitry Andric if (!isArchABICompatible(symbol->getArchitectures(), config->arch())) 1878fe6060f1SDimitry Andric continue; 1879fe6060f1SDimitry Andric if (handleLDSymbol(symbol->getName())) 1880e8d8bef9SDimitry Andric continue; 1881e8d8bef9SDimitry Andric 1882e8d8bef9SDimitry Andric switch (symbol->getKind()) { 1883*bdd1243dSDimitry Andric case SymbolKind::GlobalSymbol: 1884*bdd1243dSDimitry Andric case SymbolKind::ObjectiveCClass: 1885*bdd1243dSDimitry Andric case SymbolKind::ObjectiveCClassEHType: 1886*bdd1243dSDimitry Andric case SymbolKind::ObjectiveCInstanceVariable: 18870eae32dcSDimitry Andric normalSymbols.push_back(symbol); 18880eae32dcSDimitry Andric } 18890eae32dcSDimitry Andric } 18900eae32dcSDimitry Andric 18910eae32dcSDimitry Andric // TODO(compnerd) filter out symbols based on the target platform 18920eae32dcSDimitry Andric for (const auto *symbol : normalSymbols) { 18930eae32dcSDimitry Andric switch (symbol->getKind()) { 1894e8d8bef9SDimitry Andric case SymbolKind::GlobalSymbol: 1895*bdd1243dSDimitry Andric addSymbol(*symbol, symbol->getName()); 1896e8d8bef9SDimitry Andric break; 1897e8d8bef9SDimitry Andric case SymbolKind::ObjectiveCClass: 1898e8d8bef9SDimitry Andric // XXX ld64 only creates these symbols when -ObjC is passed in. We may 1899e8d8bef9SDimitry Andric // want to emulate that. 1900*bdd1243dSDimitry Andric addSymbol(*symbol, objc::klass + symbol->getName()); 1901*bdd1243dSDimitry Andric addSymbol(*symbol, objc::metaclass + symbol->getName()); 1902e8d8bef9SDimitry Andric break; 1903e8d8bef9SDimitry Andric case SymbolKind::ObjectiveCClassEHType: 1904*bdd1243dSDimitry Andric addSymbol(*symbol, objc::ehtype + symbol->getName()); 1905e8d8bef9SDimitry Andric break; 1906e8d8bef9SDimitry Andric case SymbolKind::ObjectiveCInstanceVariable: 1907*bdd1243dSDimitry Andric addSymbol(*symbol, objc::ivar + symbol->getName()); 1908e8d8bef9SDimitry Andric break; 1909e8d8bef9SDimitry Andric } 19105ffd83dbSDimitry Andric } 1911e8d8bef9SDimitry Andric } 1912e8d8bef9SDimitry Andric 191361cfbce3SDimitry Andric DylibFile::DylibFile(DylibFile *umbrella) 191461cfbce3SDimitry Andric : InputFile(DylibKind, MemoryBufferRef{}), refState(RefState::Unreferenced), 191561cfbce3SDimitry Andric explicitlyLinked(false), isBundleLoader(false) { 191661cfbce3SDimitry Andric if (umbrella == nullptr) 191761cfbce3SDimitry Andric umbrella = this; 191861cfbce3SDimitry Andric this->umbrella = umbrella; 191961cfbce3SDimitry Andric } 192061cfbce3SDimitry Andric 1921fe6060f1SDimitry Andric void DylibFile::parseReexports(const InterfaceFile &interface) { 1922fe6060f1SDimitry Andric const InterfaceFile *topLevel = 1923fe6060f1SDimitry Andric interface.getParent() == nullptr ? &interface : interface.getParent(); 1924349cc55cSDimitry Andric for (const InterfaceFileRef &intfRef : interface.reexportedLibraries()) { 1925fe6060f1SDimitry Andric InterfaceFile::const_target_range targets = intfRef.targets(); 1926fe6060f1SDimitry Andric if (is_contained(skipPlatformChecks, intfRef.getInstallName()) || 1927*bdd1243dSDimitry Andric isTargetPlatformArchCompatible(targets, config->platformInfo.target)) 1928fe6060f1SDimitry Andric loadReexport(intfRef.getInstallName(), exportingFile, topLevel); 1929fe6060f1SDimitry Andric } 1930fe6060f1SDimitry Andric } 1931e8d8bef9SDimitry Andric 193261cfbce3SDimitry Andric bool DylibFile::isExplicitlyLinked() const { 193361cfbce3SDimitry Andric if (!explicitlyLinked) 193461cfbce3SDimitry Andric return false; 193561cfbce3SDimitry Andric 193661cfbce3SDimitry Andric // If this dylib was explicitly linked, but at least one of the symbols 193761cfbce3SDimitry Andric // of the synthetic dylibs it created via $ld$previous symbols is 193861cfbce3SDimitry Andric // referenced, then that synthetic dylib fulfils the explicit linkedness 193961cfbce3SDimitry Andric // and we can deadstrip this dylib if it's unreferenced. 194061cfbce3SDimitry Andric for (const auto *dylib : extraDylibs) 194161cfbce3SDimitry Andric if (dylib->isReferenced()) 194261cfbce3SDimitry Andric return false; 194361cfbce3SDimitry Andric 194461cfbce3SDimitry Andric return true; 194561cfbce3SDimitry Andric } 194661cfbce3SDimitry Andric 194761cfbce3SDimitry Andric DylibFile *DylibFile::getSyntheticDylib(StringRef installName, 194861cfbce3SDimitry Andric uint32_t currentVersion, 194961cfbce3SDimitry Andric uint32_t compatVersion) { 195061cfbce3SDimitry Andric for (DylibFile *dylib : extraDylibs) 195161cfbce3SDimitry Andric if (dylib->installName == installName) { 195261cfbce3SDimitry Andric // FIXME: Check what to do if different $ld$previous symbols 195361cfbce3SDimitry Andric // request the same dylib, but with different versions. 195461cfbce3SDimitry Andric return dylib; 195561cfbce3SDimitry Andric } 195661cfbce3SDimitry Andric 195761cfbce3SDimitry Andric auto *dylib = make<DylibFile>(umbrella == this ? nullptr : umbrella); 195861cfbce3SDimitry Andric dylib->installName = saver().save(installName); 195961cfbce3SDimitry Andric dylib->currentVersion = currentVersion; 196061cfbce3SDimitry Andric dylib->compatibilityVersion = compatVersion; 196161cfbce3SDimitry Andric extraDylibs.push_back(dylib); 196261cfbce3SDimitry Andric return dylib; 196361cfbce3SDimitry Andric } 196461cfbce3SDimitry Andric 1965fe6060f1SDimitry Andric // $ld$ symbols modify the properties/behavior of the library (e.g. its install 1966fe6060f1SDimitry Andric // name, compatibility version or hide/add symbols) for specific target 1967fe6060f1SDimitry Andric // versions. 1968fe6060f1SDimitry Andric bool DylibFile::handleLDSymbol(StringRef originalName) { 1969fe6060f1SDimitry Andric if (!originalName.startswith("$ld$")) 1970fe6060f1SDimitry Andric return false; 1971fe6060f1SDimitry Andric 1972fe6060f1SDimitry Andric StringRef action; 1973fe6060f1SDimitry Andric StringRef name; 1974fe6060f1SDimitry Andric std::tie(action, name) = originalName.drop_front(strlen("$ld$")).split('$'); 1975fe6060f1SDimitry Andric if (action == "previous") 1976fe6060f1SDimitry Andric handleLDPreviousSymbol(name, originalName); 1977fe6060f1SDimitry Andric else if (action == "install_name") 1978fe6060f1SDimitry Andric handleLDInstallNameSymbol(name, originalName); 19790eae32dcSDimitry Andric else if (action == "hide") 19800eae32dcSDimitry Andric handleLDHideSymbol(name, originalName); 1981fe6060f1SDimitry Andric return true; 1982fe6060f1SDimitry Andric } 1983fe6060f1SDimitry Andric 1984fe6060f1SDimitry Andric void DylibFile::handleLDPreviousSymbol(StringRef name, StringRef originalName) { 1985fe6060f1SDimitry Andric // originalName: $ld$ previous $ <installname> $ <compatversion> $ 1986fe6060f1SDimitry Andric // <platformstr> $ <startversion> $ <endversion> $ <symbol-name> $ 1987fe6060f1SDimitry Andric StringRef installName; 1988fe6060f1SDimitry Andric StringRef compatVersion; 1989fe6060f1SDimitry Andric StringRef platformStr; 1990fe6060f1SDimitry Andric StringRef startVersion; 1991fe6060f1SDimitry Andric StringRef endVersion; 1992fe6060f1SDimitry Andric StringRef symbolName; 1993fe6060f1SDimitry Andric StringRef rest; 1994fe6060f1SDimitry Andric 1995fe6060f1SDimitry Andric std::tie(installName, name) = name.split('$'); 1996fe6060f1SDimitry Andric std::tie(compatVersion, name) = name.split('$'); 1997fe6060f1SDimitry Andric std::tie(platformStr, name) = name.split('$'); 1998fe6060f1SDimitry Andric std::tie(startVersion, name) = name.split('$'); 1999fe6060f1SDimitry Andric std::tie(endVersion, name) = name.split('$'); 200061cfbce3SDimitry Andric std::tie(symbolName, rest) = name.rsplit('$'); 200161cfbce3SDimitry Andric 200261cfbce3SDimitry Andric // FIXME: Does this do the right thing for zippered files? 2003fe6060f1SDimitry Andric unsigned platform; 2004fe6060f1SDimitry Andric if (platformStr.getAsInteger(10, platform) || 2005fe6060f1SDimitry Andric platform != static_cast<unsigned>(config->platform())) 2006fe6060f1SDimitry Andric return; 2007fe6060f1SDimitry Andric 2008fe6060f1SDimitry Andric VersionTuple start; 2009fe6060f1SDimitry Andric if (start.tryParse(startVersion)) { 2010*bdd1243dSDimitry Andric warn(toString(this) + ": failed to parse start version, symbol '" + 2011*bdd1243dSDimitry Andric originalName + "' ignored"); 2012fe6060f1SDimitry Andric return; 2013fe6060f1SDimitry Andric } 2014fe6060f1SDimitry Andric VersionTuple end; 2015fe6060f1SDimitry Andric if (end.tryParse(endVersion)) { 2016*bdd1243dSDimitry Andric warn(toString(this) + ": failed to parse end version, symbol '" + 2017*bdd1243dSDimitry Andric originalName + "' ignored"); 2018fe6060f1SDimitry Andric return; 2019fe6060f1SDimitry Andric } 2020fe6060f1SDimitry Andric if (config->platformInfo.minimum < start || 2021fe6060f1SDimitry Andric config->platformInfo.minimum >= end) 2022fe6060f1SDimitry Andric return; 2023fe6060f1SDimitry Andric 202461cfbce3SDimitry Andric // Initialized to compatibilityVersion for the symbolName branch below. 202561cfbce3SDimitry Andric uint32_t newCompatibilityVersion = compatibilityVersion; 202661cfbce3SDimitry Andric uint32_t newCurrentVersionForSymbol = currentVersion; 2027fe6060f1SDimitry Andric if (!compatVersion.empty()) { 2028fe6060f1SDimitry Andric VersionTuple cVersion; 2029fe6060f1SDimitry Andric if (cVersion.tryParse(compatVersion)) { 2030*bdd1243dSDimitry Andric warn(toString(this) + 2031*bdd1243dSDimitry Andric ": failed to parse compatibility version, symbol '" + originalName + 2032fe6060f1SDimitry Andric "' ignored"); 2033fe6060f1SDimitry Andric return; 2034fe6060f1SDimitry Andric } 203561cfbce3SDimitry Andric newCompatibilityVersion = encodeVersion(cVersion); 203661cfbce3SDimitry Andric newCurrentVersionForSymbol = newCompatibilityVersion; 2037fe6060f1SDimitry Andric } 203861cfbce3SDimitry Andric 203961cfbce3SDimitry Andric if (!symbolName.empty()) { 204061cfbce3SDimitry Andric // A $ld$previous$ symbol with symbol name adds a symbol with that name to 204161cfbce3SDimitry Andric // a dylib with given name and version. 204261cfbce3SDimitry Andric auto *dylib = getSyntheticDylib(installName, newCurrentVersionForSymbol, 204361cfbce3SDimitry Andric newCompatibilityVersion); 204461cfbce3SDimitry Andric 2045*bdd1243dSDimitry Andric // The tbd file usually contains the $ld$previous symbol for an old version, 2046*bdd1243dSDimitry Andric // and then the symbol itself later, for newer deployment targets, like so: 2047*bdd1243dSDimitry Andric // symbols: [ 2048*bdd1243dSDimitry Andric // '$ld$previous$/Another$$1$3.0$14.0$_zzz$', 2049*bdd1243dSDimitry Andric // _zzz, 2050*bdd1243dSDimitry Andric // ] 2051*bdd1243dSDimitry Andric // Since the symbols are sorted, adding them to the symtab in the given 2052*bdd1243dSDimitry Andric // order means the $ld$previous version of _zzz will prevail, as desired. 205361cfbce3SDimitry Andric dylib->symbols.push_back(symtab->addDylib( 205461cfbce3SDimitry Andric saver().save(symbolName), dylib, /*isWeakDef=*/false, /*isTlv=*/false)); 205561cfbce3SDimitry Andric return; 205661cfbce3SDimitry Andric } 205761cfbce3SDimitry Andric 205861cfbce3SDimitry Andric // A $ld$previous$ symbol without symbol name modifies the dylib it's in. 205961cfbce3SDimitry Andric this->installName = saver().save(installName); 206061cfbce3SDimitry Andric this->compatibilityVersion = newCompatibilityVersion; 2061fe6060f1SDimitry Andric } 2062fe6060f1SDimitry Andric 2063fe6060f1SDimitry Andric void DylibFile::handleLDInstallNameSymbol(StringRef name, 2064fe6060f1SDimitry Andric StringRef originalName) { 2065fe6060f1SDimitry Andric // originalName: $ld$ install_name $ os<version> $ install_name 2066fe6060f1SDimitry Andric StringRef condition, installName; 2067fe6060f1SDimitry Andric std::tie(condition, installName) = name.split('$'); 2068fe6060f1SDimitry Andric VersionTuple version; 2069fe6060f1SDimitry Andric if (!condition.consume_front("os") || version.tryParse(condition)) 2070*bdd1243dSDimitry Andric warn(toString(this) + ": failed to parse os version, symbol '" + 2071*bdd1243dSDimitry Andric originalName + "' ignored"); 2072fe6060f1SDimitry Andric else if (version == config->platformInfo.minimum) 207304eeddc0SDimitry Andric this->installName = saver().save(installName); 2074fe6060f1SDimitry Andric } 2075fe6060f1SDimitry Andric 20760eae32dcSDimitry Andric void DylibFile::handleLDHideSymbol(StringRef name, StringRef originalName) { 20770eae32dcSDimitry Andric StringRef symbolName; 20780eae32dcSDimitry Andric bool shouldHide = true; 20790eae32dcSDimitry Andric if (name.startswith("os")) { 20800eae32dcSDimitry Andric // If it's hidden based on versions. 20810eae32dcSDimitry Andric name = name.drop_front(2); 20820eae32dcSDimitry Andric StringRef minVersion; 20830eae32dcSDimitry Andric std::tie(minVersion, symbolName) = name.split('$'); 20840eae32dcSDimitry Andric VersionTuple versionTup; 20850eae32dcSDimitry Andric if (versionTup.tryParse(minVersion)) { 2086*bdd1243dSDimitry Andric warn(toString(this) + ": failed to parse hidden version, symbol `" + originalName + 20870eae32dcSDimitry Andric "` ignored."); 20880eae32dcSDimitry Andric return; 20890eae32dcSDimitry Andric } 20900eae32dcSDimitry Andric shouldHide = versionTup == config->platformInfo.minimum; 20910eae32dcSDimitry Andric } else { 20920eae32dcSDimitry Andric symbolName = name; 20930eae32dcSDimitry Andric } 20940eae32dcSDimitry Andric 20950eae32dcSDimitry Andric if (shouldHide) 20960eae32dcSDimitry Andric exportingFile->hiddenSymbols.insert(CachedHashStringRef(symbolName)); 20970eae32dcSDimitry Andric } 20980eae32dcSDimitry Andric 2099fe6060f1SDimitry Andric void DylibFile::checkAppExtensionSafety(bool dylibIsAppExtensionSafe) const { 2100fe6060f1SDimitry Andric if (config->applicationExtension && !dylibIsAppExtensionSafe) 2101fe6060f1SDimitry Andric warn("using '-application_extension' with unsafe dylib: " + toString(this)); 2102e8d8bef9SDimitry Andric } 2103e8d8bef9SDimitry Andric 2104972a253aSDimitry Andric ArchiveFile::ArchiveFile(std::unique_ptr<object::Archive> &&f, bool forceHidden) 2105972a253aSDimitry Andric : InputFile(ArchiveKind, f->getMemoryBufferRef()), file(std::move(f)), 2106972a253aSDimitry Andric forceHidden(forceHidden) {} 2107349cc55cSDimitry Andric 2108349cc55cSDimitry Andric void ArchiveFile::addLazySymbols() { 21095ffd83dbSDimitry Andric for (const object::Archive::Symbol &sym : file->symbols()) 211004eeddc0SDimitry Andric symtab->addLazyArchive(sym.getName(), this, sym); 21115ffd83dbSDimitry Andric } 21125ffd83dbSDimitry Andric 2113972a253aSDimitry Andric static Expected<InputFile *> 2114972a253aSDimitry Andric loadArchiveMember(MemoryBufferRef mb, uint32_t modTime, StringRef archiveName, 2115972a253aSDimitry Andric uint64_t offsetInArchive, bool forceHidden) { 2116349cc55cSDimitry Andric if (config->zeroModTime) 2117349cc55cSDimitry Andric modTime = 0; 2118349cc55cSDimitry Andric 2119349cc55cSDimitry Andric switch (identify_magic(mb.getBuffer())) { 2120349cc55cSDimitry Andric case file_magic::macho_object: 2121972a253aSDimitry Andric return make<ObjFile>(mb, modTime, archiveName, /*lazy=*/false, forceHidden); 2122349cc55cSDimitry Andric case file_magic::bitcode: 2123972a253aSDimitry Andric return make<BitcodeFile>(mb, archiveName, offsetInArchive, /*lazy=*/false, 2124972a253aSDimitry Andric forceHidden); 2125349cc55cSDimitry Andric default: 2126349cc55cSDimitry Andric return createStringError(inconvertibleErrorCode(), 2127349cc55cSDimitry Andric mb.getBufferIdentifier() + 2128349cc55cSDimitry Andric " has unhandled file type"); 2129349cc55cSDimitry Andric } 2130349cc55cSDimitry Andric } 2131349cc55cSDimitry Andric 2132349cc55cSDimitry Andric Error ArchiveFile::fetch(const object::Archive::Child &c, StringRef reason) { 2133349cc55cSDimitry Andric if (!seen.insert(c.getChildOffset()).second) 2134349cc55cSDimitry Andric return Error::success(); 2135349cc55cSDimitry Andric 2136349cc55cSDimitry Andric Expected<MemoryBufferRef> mb = c.getMemoryBufferRef(); 2137349cc55cSDimitry Andric if (!mb) 2138349cc55cSDimitry Andric return mb.takeError(); 2139349cc55cSDimitry Andric 2140349cc55cSDimitry Andric // Thin archives refer to .o files, so --reproduce needs the .o files too. 2141349cc55cSDimitry Andric if (tar && c.getParent()->isThin()) 2142349cc55cSDimitry Andric tar->append(relativeToRoot(CHECK(c.getFullName(), this)), mb->getBuffer()); 2143349cc55cSDimitry Andric 2144349cc55cSDimitry Andric Expected<TimePoint<std::chrono::seconds>> modTime = c.getLastModified(); 2145349cc55cSDimitry Andric if (!modTime) 2146349cc55cSDimitry Andric return modTime.takeError(); 2147349cc55cSDimitry Andric 2148972a253aSDimitry Andric Expected<InputFile *> file = loadArchiveMember( 2149972a253aSDimitry Andric *mb, toTimeT(*modTime), getName(), c.getChildOffset(), forceHidden); 2150349cc55cSDimitry Andric 2151349cc55cSDimitry Andric if (!file) 2152349cc55cSDimitry Andric return file.takeError(); 2153349cc55cSDimitry Andric 2154349cc55cSDimitry Andric inputFiles.insert(*file); 2155349cc55cSDimitry Andric printArchiveMemberLoad(reason, *file); 2156349cc55cSDimitry Andric return Error::success(); 2157349cc55cSDimitry Andric } 2158349cc55cSDimitry Andric 21595ffd83dbSDimitry Andric void ArchiveFile::fetch(const object::Archive::Symbol &sym) { 21605ffd83dbSDimitry Andric object::Archive::Child c = 21615ffd83dbSDimitry Andric CHECK(sym.getMember(), toString(this) + 2162349cc55cSDimitry Andric ": could not get the member defining symbol " + 2163e8d8bef9SDimitry Andric toMachOString(sym)); 21645ffd83dbSDimitry Andric 2165fe6060f1SDimitry Andric // `sym` is owned by a LazySym, which will be replace<>()d by make<ObjFile> 2166e8d8bef9SDimitry Andric // and become invalid after that call. Copy it to the stack so we can refer 2167e8d8bef9SDimitry Andric // to it later. 2168fe6060f1SDimitry Andric const object::Archive::Symbol symCopy = sym; 2169e8d8bef9SDimitry Andric 2170fe6060f1SDimitry Andric // ld64 doesn't demangle sym here even with -demangle. 2171fe6060f1SDimitry Andric // Match that: intentionally don't call toMachOString(). 2172349cc55cSDimitry Andric if (Error e = fetch(c, symCopy.getName())) 2173349cc55cSDimitry Andric error(toString(this) + ": could not get the member defining symbol " + 2174349cc55cSDimitry Andric toMachOString(symCopy) + ": " + toString(std::move(e))); 21755ffd83dbSDimitry Andric } 21765ffd83dbSDimitry Andric 2177fe6060f1SDimitry Andric static macho::Symbol *createBitcodeSymbol(const lto::InputFile::Symbol &objSym, 2178fe6060f1SDimitry Andric BitcodeFile &file) { 217904eeddc0SDimitry Andric StringRef name = saver().save(objSym.getName()); 2180fe6060f1SDimitry Andric 2181fe6060f1SDimitry Andric if (objSym.isUndefined()) 21820eae32dcSDimitry Andric return symtab->addUndefined(name, &file, /*isWeakRef=*/objSym.isWeak()); 2183fe6060f1SDimitry Andric 2184fe6060f1SDimitry Andric // TODO: Write a test demonstrating why computing isPrivateExtern before 2185fe6060f1SDimitry Andric // LTO compilation is important. 2186fe6060f1SDimitry Andric bool isPrivateExtern = false; 2187fe6060f1SDimitry Andric switch (objSym.getVisibility()) { 2188fe6060f1SDimitry Andric case GlobalValue::HiddenVisibility: 2189fe6060f1SDimitry Andric isPrivateExtern = true; 2190fe6060f1SDimitry Andric break; 2191fe6060f1SDimitry Andric case GlobalValue::ProtectedVisibility: 2192fe6060f1SDimitry Andric error(name + " has protected visibility, which is not supported by Mach-O"); 2193fe6060f1SDimitry Andric break; 2194fe6060f1SDimitry Andric case GlobalValue::DefaultVisibility: 2195fe6060f1SDimitry Andric break; 2196fe6060f1SDimitry Andric } 2197972a253aSDimitry Andric isPrivateExtern = isPrivateExtern || objSym.canBeOmittedFromSymbolTable() || 2198972a253aSDimitry Andric file.forceHidden; 2199fe6060f1SDimitry Andric 2200349cc55cSDimitry Andric if (objSym.isCommon()) 2201349cc55cSDimitry Andric return symtab->addCommon(name, &file, objSym.getCommonSize(), 2202349cc55cSDimitry Andric objSym.getCommonAlignment(), isPrivateExtern); 2203349cc55cSDimitry Andric 2204fe6060f1SDimitry Andric return symtab->addDefined(name, &file, /*isec=*/nullptr, /*value=*/0, 2205fe6060f1SDimitry Andric /*size=*/0, objSym.isWeak(), isPrivateExtern, 2206fe6060f1SDimitry Andric /*isThumb=*/false, 2207fe6060f1SDimitry Andric /*isReferencedDynamically=*/false, 2208349cc55cSDimitry Andric /*noDeadStrip=*/false, 2209349cc55cSDimitry Andric /*isWeakDefCanBeHidden=*/false); 2210fe6060f1SDimitry Andric } 2211fe6060f1SDimitry Andric 2212fe6060f1SDimitry Andric BitcodeFile::BitcodeFile(MemoryBufferRef mb, StringRef archiveName, 2213972a253aSDimitry Andric uint64_t offsetInArchive, bool lazy, bool forceHidden) 2214972a253aSDimitry Andric : InputFile(BitcodeKind, mb, lazy), forceHidden(forceHidden) { 22150eae32dcSDimitry Andric this->archiveName = std::string(archiveName); 2216fe6060f1SDimitry Andric std::string path = mb.getBufferIdentifier().str(); 2217*bdd1243dSDimitry Andric if (config->thinLTOIndexOnly) 2218*bdd1243dSDimitry Andric path = replaceThinLTOSuffix(mb.getBufferIdentifier()); 2219*bdd1243dSDimitry Andric 2220fe6060f1SDimitry Andric // ThinLTO assumes that all MemoryBufferRefs given to it have a unique 2221fe6060f1SDimitry Andric // name. If two members with the same name are provided, this causes a 2222fe6060f1SDimitry Andric // collision and ThinLTO can't proceed. 2223fe6060f1SDimitry Andric // So, we append the archive name to disambiguate two members with the same 2224fe6060f1SDimitry Andric // name from multiple different archives, and offset within the archive to 2225fe6060f1SDimitry Andric // disambiguate two members of the same name from a single archive. 222604eeddc0SDimitry Andric MemoryBufferRef mbref(mb.getBuffer(), 222704eeddc0SDimitry Andric saver().save(archiveName.empty() 222804eeddc0SDimitry Andric ? path 222904eeddc0SDimitry Andric : archiveName + 223004eeddc0SDimitry Andric sys::path::filename(path) + 2231fe6060f1SDimitry Andric utostr(offsetInArchive))); 2232fe6060f1SDimitry Andric 2233e8d8bef9SDimitry Andric obj = check(lto::InputFile::create(mbref)); 223404eeddc0SDimitry Andric if (lazy) 223504eeddc0SDimitry Andric parseLazy(); 223604eeddc0SDimitry Andric else 223704eeddc0SDimitry Andric parse(); 223804eeddc0SDimitry Andric } 2239fe6060f1SDimitry Andric 224004eeddc0SDimitry Andric void BitcodeFile::parse() { 2241fe6060f1SDimitry Andric // Convert LTO Symbols to LLD Symbols in order to perform resolution. The 2242fe6060f1SDimitry Andric // "winning" symbol will then be marked as Prevailing at LTO compilation 2243fe6060f1SDimitry Andric // time. 224404eeddc0SDimitry Andric symbols.clear(); 2245fe6060f1SDimitry Andric for (const lto::InputFile::Symbol &objSym : obj->symbols()) 2246fe6060f1SDimitry Andric symbols.push_back(createBitcodeSymbol(objSym, *this)); 22475ffd83dbSDimitry Andric } 2248fe6060f1SDimitry Andric 224904eeddc0SDimitry Andric void BitcodeFile::parseLazy() { 225004eeddc0SDimitry Andric symbols.resize(obj->symbols().size()); 2251*bdd1243dSDimitry Andric for (const auto &[i, objSym] : llvm::enumerate(obj->symbols())) { 225204eeddc0SDimitry Andric if (!objSym.isUndefined()) { 2253*bdd1243dSDimitry Andric symbols[i] = symtab->addLazyObject(saver().save(objSym.getName()), *this); 225404eeddc0SDimitry Andric if (!lazy) 225504eeddc0SDimitry Andric break; 225604eeddc0SDimitry Andric } 225704eeddc0SDimitry Andric } 225804eeddc0SDimitry Andric } 225904eeddc0SDimitry Andric 2260*bdd1243dSDimitry Andric std::string macho::replaceThinLTOSuffix(StringRef path) { 2261*bdd1243dSDimitry Andric auto [suffix, repl] = config->thinLTOObjectSuffixReplace; 2262*bdd1243dSDimitry Andric if (path.consume_back(suffix)) 2263*bdd1243dSDimitry Andric return (path + repl).str(); 2264*bdd1243dSDimitry Andric return std::string(path); 2265*bdd1243dSDimitry Andric } 2266*bdd1243dSDimitry Andric 226704eeddc0SDimitry Andric void macho::extract(InputFile &file, StringRef reason) { 2268*bdd1243dSDimitry Andric if (!file.lazy) 2269*bdd1243dSDimitry Andric return; 227004eeddc0SDimitry Andric file.lazy = false; 2271*bdd1243dSDimitry Andric 227204eeddc0SDimitry Andric printArchiveMemberLoad(reason, &file); 227304eeddc0SDimitry Andric if (auto *bitcode = dyn_cast<BitcodeFile>(&file)) { 227404eeddc0SDimitry Andric bitcode->parse(); 227504eeddc0SDimitry Andric } else { 227604eeddc0SDimitry Andric auto &f = cast<ObjFile>(file); 227704eeddc0SDimitry Andric if (target->wordSize == 8) 227804eeddc0SDimitry Andric f.parse<LP64>(); 227904eeddc0SDimitry Andric else 228004eeddc0SDimitry Andric f.parse<ILP32>(); 228104eeddc0SDimitry Andric } 228204eeddc0SDimitry Andric } 228304eeddc0SDimitry Andric 2284fe6060f1SDimitry Andric template void ObjFile::parse<LP64>(); 2285