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" 485ffd83dbSDimitry Andric #include "ExportTrie.h" 495ffd83dbSDimitry Andric #include "InputSection.h" 505ffd83dbSDimitry Andric #include "MachOStructs.h" 51e8d8bef9SDimitry Andric #include "ObjC.h" 525ffd83dbSDimitry Andric #include "OutputSection.h" 53e8d8bef9SDimitry Andric #include "OutputSegment.h" 545ffd83dbSDimitry Andric #include "SymbolTable.h" 555ffd83dbSDimitry Andric #include "Symbols.h" 56fe6060f1SDimitry Andric #include "SyntheticSections.h" 575ffd83dbSDimitry Andric #include "Target.h" 585ffd83dbSDimitry Andric 59*04eeddc0SDimitry Andric #include "lld/Common/CommonLinkerContext.h" 60e8d8bef9SDimitry Andric #include "lld/Common/DWARF.h" 61e8d8bef9SDimitry Andric #include "lld/Common/Reproduce.h" 62e8d8bef9SDimitry Andric #include "llvm/ADT/iterator.h" 635ffd83dbSDimitry Andric #include "llvm/BinaryFormat/MachO.h" 64e8d8bef9SDimitry Andric #include "llvm/LTO/LTO.h" 65*04eeddc0SDimitry Andric #include "llvm/Support/BinaryStreamReader.h" 665ffd83dbSDimitry Andric #include "llvm/Support/Endian.h" 675ffd83dbSDimitry Andric #include "llvm/Support/MemoryBuffer.h" 685ffd83dbSDimitry Andric #include "llvm/Support/Path.h" 69e8d8bef9SDimitry Andric #include "llvm/Support/TarWriter.h" 70*04eeddc0SDimitry Andric #include "llvm/Support/TimeProfiler.h" 71fe6060f1SDimitry Andric #include "llvm/TextAPI/Architecture.h" 72fe6060f1SDimitry Andric #include "llvm/TextAPI/InterfaceFile.h" 735ffd83dbSDimitry Andric 74349cc55cSDimitry Andric #include <type_traits> 75349cc55cSDimitry Andric 765ffd83dbSDimitry Andric using namespace llvm; 775ffd83dbSDimitry Andric using namespace llvm::MachO; 785ffd83dbSDimitry Andric using namespace llvm::support::endian; 795ffd83dbSDimitry Andric using namespace llvm::sys; 805ffd83dbSDimitry Andric using namespace lld; 815ffd83dbSDimitry Andric using namespace lld::macho; 825ffd83dbSDimitry Andric 83e8d8bef9SDimitry Andric // Returns "<internal>", "foo.a(bar.o)", or "baz.o". 84e8d8bef9SDimitry Andric std::string lld::toString(const InputFile *f) { 85e8d8bef9SDimitry Andric if (!f) 86e8d8bef9SDimitry Andric return "<internal>"; 87fe6060f1SDimitry Andric 88fe6060f1SDimitry Andric // Multiple dylibs can be defined in one .tbd file. 89fe6060f1SDimitry Andric if (auto dylibFile = dyn_cast<DylibFile>(f)) 90fe6060f1SDimitry Andric if (f->getName().endswith(".tbd")) 91fe6060f1SDimitry Andric return (f->getName() + "(" + dylibFile->installName + ")").str(); 92fe6060f1SDimitry Andric 93e8d8bef9SDimitry Andric if (f->archiveName.empty()) 94e8d8bef9SDimitry Andric return std::string(f->getName()); 95fe6060f1SDimitry Andric return (f->archiveName + "(" + path::filename(f->getName()) + ")").str(); 96e8d8bef9SDimitry Andric } 97e8d8bef9SDimitry Andric 98e8d8bef9SDimitry Andric SetVector<InputFile *> macho::inputFiles; 99e8d8bef9SDimitry Andric std::unique_ptr<TarWriter> macho::tar; 100e8d8bef9SDimitry Andric int InputFile::idCount = 0; 1015ffd83dbSDimitry Andric 102fe6060f1SDimitry Andric static VersionTuple decodeVersion(uint32_t version) { 103fe6060f1SDimitry Andric unsigned major = version >> 16; 104fe6060f1SDimitry Andric unsigned minor = (version >> 8) & 0xffu; 105fe6060f1SDimitry Andric unsigned subMinor = version & 0xffu; 106fe6060f1SDimitry Andric return VersionTuple(major, minor, subMinor); 107fe6060f1SDimitry Andric } 108fe6060f1SDimitry Andric 109fe6060f1SDimitry Andric static std::vector<PlatformInfo> getPlatformInfos(const InputFile *input) { 110fe6060f1SDimitry Andric if (!isa<ObjFile>(input) && !isa<DylibFile>(input)) 111fe6060f1SDimitry Andric return {}; 112fe6060f1SDimitry Andric 113fe6060f1SDimitry Andric const char *hdr = input->mb.getBufferStart(); 114fe6060f1SDimitry Andric 115fe6060f1SDimitry Andric std::vector<PlatformInfo> platformInfos; 116fe6060f1SDimitry Andric for (auto *cmd : findCommands<build_version_command>(hdr, LC_BUILD_VERSION)) { 117fe6060f1SDimitry Andric PlatformInfo info; 118*04eeddc0SDimitry Andric info.target.Platform = static_cast<PlatformType>(cmd->platform); 119fe6060f1SDimitry Andric info.minimum = decodeVersion(cmd->minos); 120fe6060f1SDimitry Andric platformInfos.emplace_back(std::move(info)); 121fe6060f1SDimitry Andric } 122fe6060f1SDimitry Andric for (auto *cmd : findCommands<version_min_command>( 123fe6060f1SDimitry Andric hdr, LC_VERSION_MIN_MACOSX, LC_VERSION_MIN_IPHONEOS, 124fe6060f1SDimitry Andric LC_VERSION_MIN_TVOS, LC_VERSION_MIN_WATCHOS)) { 125fe6060f1SDimitry Andric PlatformInfo info; 126fe6060f1SDimitry Andric switch (cmd->cmd) { 127fe6060f1SDimitry Andric case LC_VERSION_MIN_MACOSX: 128*04eeddc0SDimitry Andric info.target.Platform = PLATFORM_MACOS; 129fe6060f1SDimitry Andric break; 130fe6060f1SDimitry Andric case LC_VERSION_MIN_IPHONEOS: 131*04eeddc0SDimitry Andric info.target.Platform = PLATFORM_IOS; 132fe6060f1SDimitry Andric break; 133fe6060f1SDimitry Andric case LC_VERSION_MIN_TVOS: 134*04eeddc0SDimitry Andric info.target.Platform = PLATFORM_TVOS; 135fe6060f1SDimitry Andric break; 136fe6060f1SDimitry Andric case LC_VERSION_MIN_WATCHOS: 137*04eeddc0SDimitry Andric info.target.Platform = PLATFORM_WATCHOS; 138fe6060f1SDimitry Andric break; 139fe6060f1SDimitry Andric } 140fe6060f1SDimitry Andric info.minimum = decodeVersion(cmd->version); 141fe6060f1SDimitry Andric platformInfos.emplace_back(std::move(info)); 142fe6060f1SDimitry Andric } 143fe6060f1SDimitry Andric 144fe6060f1SDimitry Andric return platformInfos; 145fe6060f1SDimitry Andric } 146fe6060f1SDimitry Andric 147fe6060f1SDimitry Andric static bool checkCompatibility(const InputFile *input) { 148fe6060f1SDimitry Andric std::vector<PlatformInfo> platformInfos = getPlatformInfos(input); 149fe6060f1SDimitry Andric if (platformInfos.empty()) 150fe6060f1SDimitry Andric return true; 151fe6060f1SDimitry Andric 152fe6060f1SDimitry Andric auto it = find_if(platformInfos, [&](const PlatformInfo &info) { 153fe6060f1SDimitry Andric return removeSimulator(info.target.Platform) == 154fe6060f1SDimitry Andric removeSimulator(config->platform()); 155fe6060f1SDimitry Andric }); 156fe6060f1SDimitry Andric if (it == platformInfos.end()) { 157fe6060f1SDimitry Andric std::string platformNames; 158fe6060f1SDimitry Andric raw_string_ostream os(platformNames); 159fe6060f1SDimitry Andric interleave( 160fe6060f1SDimitry Andric platformInfos, os, 161fe6060f1SDimitry Andric [&](const PlatformInfo &info) { 162fe6060f1SDimitry Andric os << getPlatformName(info.target.Platform); 163fe6060f1SDimitry Andric }, 164fe6060f1SDimitry Andric "/"); 165fe6060f1SDimitry Andric error(toString(input) + " has platform " + platformNames + 166fe6060f1SDimitry Andric Twine(", which is different from target platform ") + 167fe6060f1SDimitry Andric getPlatformName(config->platform())); 168fe6060f1SDimitry Andric return false; 169fe6060f1SDimitry Andric } 170fe6060f1SDimitry Andric 171fe6060f1SDimitry Andric if (it->minimum > config->platformInfo.minimum) 172fe6060f1SDimitry Andric warn(toString(input) + " has version " + it->minimum.getAsString() + 173fe6060f1SDimitry Andric ", which is newer than target minimum of " + 174fe6060f1SDimitry Andric config->platformInfo.minimum.getAsString()); 175fe6060f1SDimitry Andric 176fe6060f1SDimitry Andric return true; 177fe6060f1SDimitry Andric } 178fe6060f1SDimitry Andric 179349cc55cSDimitry Andric // This cache mostly exists to store system libraries (and .tbds) as they're 180349cc55cSDimitry Andric // loaded, rather than the input archives, which are already cached at a higher 181349cc55cSDimitry Andric // level, and other files like the filelist that are only read once. 182349cc55cSDimitry Andric // Theoretically this caching could be more efficient by hoisting it, but that 183349cc55cSDimitry Andric // would require altering many callers to track the state. 184349cc55cSDimitry Andric DenseMap<CachedHashStringRef, MemoryBufferRef> macho::cachedReads; 1855ffd83dbSDimitry Andric // Open a given file path and return it as a memory-mapped file. 1865ffd83dbSDimitry Andric Optional<MemoryBufferRef> macho::readFile(StringRef path) { 187349cc55cSDimitry Andric CachedHashStringRef key(path); 188349cc55cSDimitry Andric auto entry = cachedReads.find(key); 189349cc55cSDimitry Andric if (entry != cachedReads.end()) 190349cc55cSDimitry Andric return entry->second; 191349cc55cSDimitry Andric 192fe6060f1SDimitry Andric ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr = MemoryBuffer::getFile(path); 193fe6060f1SDimitry Andric if (std::error_code ec = mbOrErr.getError()) { 1945ffd83dbSDimitry Andric error("cannot open " + path + ": " + ec.message()); 1955ffd83dbSDimitry Andric return None; 1965ffd83dbSDimitry Andric } 1975ffd83dbSDimitry Andric 1985ffd83dbSDimitry Andric std::unique_ptr<MemoryBuffer> &mb = *mbOrErr; 1995ffd83dbSDimitry Andric MemoryBufferRef mbref = mb->getMemBufferRef(); 2005ffd83dbSDimitry Andric make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take mb ownership 2015ffd83dbSDimitry Andric 2025ffd83dbSDimitry Andric // If this is a regular non-fat file, return it. 2035ffd83dbSDimitry Andric const char *buf = mbref.getBufferStart(); 204fe6060f1SDimitry Andric const auto *hdr = reinterpret_cast<const fat_header *>(buf); 205fe6060f1SDimitry Andric if (mbref.getBufferSize() < sizeof(uint32_t) || 206fe6060f1SDimitry Andric read32be(&hdr->magic) != FAT_MAGIC) { 207e8d8bef9SDimitry Andric if (tar) 208e8d8bef9SDimitry Andric tar->append(relativeToRoot(path), mbref.getBuffer()); 209349cc55cSDimitry Andric return cachedReads[key] = mbref; 210e8d8bef9SDimitry Andric } 2115ffd83dbSDimitry Andric 212*04eeddc0SDimitry Andric llvm::BumpPtrAllocator &bAlloc = lld::bAlloc(); 213*04eeddc0SDimitry Andric 214fe6060f1SDimitry Andric // Object files and archive files may be fat files, which contain multiple 215fe6060f1SDimitry Andric // real files for different CPU ISAs. Here, we search for a file that matches 216fe6060f1SDimitry Andric // with the current link target and returns it as a MemoryBufferRef. 217fe6060f1SDimitry Andric const auto *arch = reinterpret_cast<const fat_arch *>(buf + sizeof(*hdr)); 2185ffd83dbSDimitry Andric 2195ffd83dbSDimitry Andric for (uint32_t i = 0, n = read32be(&hdr->nfat_arch); i < n; ++i) { 2205ffd83dbSDimitry Andric if (reinterpret_cast<const char *>(arch + i + 1) > 2215ffd83dbSDimitry Andric buf + mbref.getBufferSize()) { 2225ffd83dbSDimitry Andric error(path + ": fat_arch struct extends beyond end of file"); 2235ffd83dbSDimitry Andric return None; 2245ffd83dbSDimitry Andric } 2255ffd83dbSDimitry Andric 226fe6060f1SDimitry Andric if (read32be(&arch[i].cputype) != static_cast<uint32_t>(target->cpuType) || 2275ffd83dbSDimitry Andric read32be(&arch[i].cpusubtype) != target->cpuSubtype) 2285ffd83dbSDimitry Andric continue; 2295ffd83dbSDimitry Andric 2305ffd83dbSDimitry Andric uint32_t offset = read32be(&arch[i].offset); 2315ffd83dbSDimitry Andric uint32_t size = read32be(&arch[i].size); 2325ffd83dbSDimitry Andric if (offset + size > mbref.getBufferSize()) 2335ffd83dbSDimitry Andric error(path + ": slice extends beyond end of file"); 234e8d8bef9SDimitry Andric if (tar) 235e8d8bef9SDimitry Andric tar->append(relativeToRoot(path), mbref.getBuffer()); 236349cc55cSDimitry Andric return cachedReads[key] = MemoryBufferRef(StringRef(buf + offset, size), 237349cc55cSDimitry Andric path.copy(bAlloc)); 2385ffd83dbSDimitry Andric } 2395ffd83dbSDimitry Andric 2405ffd83dbSDimitry Andric error("unable to find matching architecture in " + path); 2415ffd83dbSDimitry Andric return None; 2425ffd83dbSDimitry Andric } 2435ffd83dbSDimitry Andric 244fe6060f1SDimitry Andric InputFile::InputFile(Kind kind, const InterfaceFile &interface) 245*04eeddc0SDimitry Andric : id(idCount++), fileKind(kind), name(saver().save(interface.getPath())) {} 2465ffd83dbSDimitry Andric 247349cc55cSDimitry Andric // Some sections comprise of fixed-size records, so instead of splitting them at 248349cc55cSDimitry Andric // symbol boundaries, we split them based on size. Records are distinct from 249349cc55cSDimitry Andric // literals in that they may contain references to other sections, instead of 250349cc55cSDimitry Andric // being leaf nodes in the InputSection graph. 251349cc55cSDimitry Andric // 252349cc55cSDimitry Andric // Note that "record" is a term I came up with. In contrast, "literal" is a term 253349cc55cSDimitry Andric // used by the Mach-O format. 254349cc55cSDimitry Andric static Optional<size_t> getRecordSize(StringRef segname, StringRef name) { 255349cc55cSDimitry Andric if (name == section_names::cfString) { 256349cc55cSDimitry Andric if (config->icfLevel != ICFLevel::none && segname == segment_names::data) 257349cc55cSDimitry Andric return target->wordSize == 8 ? 32 : 16; 258349cc55cSDimitry Andric } else if (name == section_names::compactUnwind) { 259349cc55cSDimitry Andric if (segname == segment_names::ld) 260349cc55cSDimitry Andric return target->wordSize == 8 ? 32 : 20; 261349cc55cSDimitry Andric } 262349cc55cSDimitry Andric return {}; 263349cc55cSDimitry Andric } 264349cc55cSDimitry Andric 265349cc55cSDimitry Andric // Parse the sequence of sections within a single LC_SEGMENT(_64). 266349cc55cSDimitry Andric // Split each section into subsections. 267349cc55cSDimitry Andric template <class SectionHeader> 268349cc55cSDimitry Andric void ObjFile::parseSections(ArrayRef<SectionHeader> sectionHeaders) { 269349cc55cSDimitry Andric sections.reserve(sectionHeaders.size()); 2705ffd83dbSDimitry Andric auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 2715ffd83dbSDimitry Andric 272349cc55cSDimitry Andric for (const SectionHeader &sec : sectionHeaders) { 273fe6060f1SDimitry Andric StringRef name = 274e8d8bef9SDimitry Andric StringRef(sec.sectname, strnlen(sec.sectname, sizeof(sec.sectname))); 275fe6060f1SDimitry Andric StringRef segname = 276e8d8bef9SDimitry Andric StringRef(sec.segname, strnlen(sec.segname, sizeof(sec.segname))); 277fe6060f1SDimitry Andric ArrayRef<uint8_t> data = {isZeroFill(sec.flags) ? nullptr 278fe6060f1SDimitry Andric : buf + sec.offset, 2795ffd83dbSDimitry Andric static_cast<size_t>(sec.size)}; 280fe6060f1SDimitry Andric if (sec.align >= 32) { 281fe6060f1SDimitry Andric error("alignment " + std::to_string(sec.align) + " of section " + name + 282fe6060f1SDimitry Andric " is too large"); 283349cc55cSDimitry Andric sections.push_back(sec.addr); 284fe6060f1SDimitry Andric continue; 285fe6060f1SDimitry Andric } 286fe6060f1SDimitry Andric uint32_t align = 1 << sec.align; 287fe6060f1SDimitry Andric uint32_t flags = sec.flags; 288e8d8bef9SDimitry Andric 289349cc55cSDimitry Andric auto splitRecords = [&](int recordSize) -> void { 290349cc55cSDimitry Andric sections.push_back(sec.addr); 291349cc55cSDimitry Andric if (data.empty()) 292349cc55cSDimitry Andric return; 293349cc55cSDimitry Andric Subsections &subsections = sections.back().subsections; 294349cc55cSDimitry Andric subsections.reserve(data.size() / recordSize); 295349cc55cSDimitry Andric auto *isec = make<ConcatInputSection>( 296349cc55cSDimitry Andric segname, name, this, data.slice(0, recordSize), align, flags); 297349cc55cSDimitry Andric subsections.push_back({0, isec}); 298349cc55cSDimitry Andric for (uint64_t off = recordSize; off < data.size(); off += recordSize) { 299349cc55cSDimitry Andric // Copying requires less memory than constructing a fresh InputSection. 300349cc55cSDimitry Andric auto *copy = make<ConcatInputSection>(*isec); 301349cc55cSDimitry Andric copy->data = data.slice(off, recordSize); 302349cc55cSDimitry Andric subsections.push_back({off, copy}); 303349cc55cSDimitry Andric } 304349cc55cSDimitry Andric }; 305349cc55cSDimitry Andric 306fe6060f1SDimitry Andric if (sectionType(sec.flags) == S_CSTRING_LITERALS || 307fe6060f1SDimitry Andric (config->dedupLiterals && isWordLiteralSection(sec.flags))) { 308fe6060f1SDimitry Andric if (sec.nreloc && config->dedupLiterals) 309fe6060f1SDimitry Andric fatal(toString(this) + " contains relocations in " + sec.segname + "," + 310fe6060f1SDimitry Andric sec.sectname + 311fe6060f1SDimitry Andric ", so LLD cannot deduplicate literals. Try re-running without " 312fe6060f1SDimitry Andric "--deduplicate-literals."); 313fe6060f1SDimitry Andric 314fe6060f1SDimitry Andric InputSection *isec; 315fe6060f1SDimitry Andric if (sectionType(sec.flags) == S_CSTRING_LITERALS) { 316fe6060f1SDimitry Andric isec = 317fe6060f1SDimitry Andric make<CStringInputSection>(segname, name, this, data, align, flags); 318fe6060f1SDimitry Andric // FIXME: parallelize this? 319fe6060f1SDimitry Andric cast<CStringInputSection>(isec)->splitIntoPieces(); 320fe6060f1SDimitry Andric } else { 321fe6060f1SDimitry Andric isec = make<WordLiteralInputSection>(segname, name, this, data, align, 322fe6060f1SDimitry Andric flags); 323fe6060f1SDimitry Andric } 324349cc55cSDimitry Andric sections.push_back(sec.addr); 325349cc55cSDimitry Andric sections.back().subsections.push_back({0, isec}); 326349cc55cSDimitry Andric } else if (auto recordSize = getRecordSize(segname, name)) { 327349cc55cSDimitry Andric splitRecords(*recordSize); 328349cc55cSDimitry Andric if (name == section_names::compactUnwind) 329349cc55cSDimitry Andric compactUnwindSection = §ions.back(); 330349cc55cSDimitry Andric } else if (segname == segment_names::llvm) { 331*04eeddc0SDimitry Andric if (name == "__cg_profile" && config->callGraphProfileSort) { 332*04eeddc0SDimitry Andric TimeTraceScope timeScope("Parsing call graph section"); 333*04eeddc0SDimitry Andric BinaryStreamReader reader(data, support::little); 334*04eeddc0SDimitry Andric while (!reader.empty()) { 335*04eeddc0SDimitry Andric uint32_t fromIndex, toIndex; 336*04eeddc0SDimitry Andric uint64_t count; 337*04eeddc0SDimitry Andric if (Error err = reader.readInteger(fromIndex)) 338*04eeddc0SDimitry Andric fatal(toString(this) + ": Expected 32-bit integer"); 339*04eeddc0SDimitry Andric if (Error err = reader.readInteger(toIndex)) 340*04eeddc0SDimitry Andric fatal(toString(this) + ": Expected 32-bit integer"); 341*04eeddc0SDimitry Andric if (Error err = reader.readInteger(count)) 342*04eeddc0SDimitry Andric fatal(toString(this) + ": Expected 64-bit integer"); 343*04eeddc0SDimitry Andric callGraph.emplace_back(); 344*04eeddc0SDimitry Andric CallGraphEntry &entry = callGraph.back(); 345*04eeddc0SDimitry Andric entry.fromIndex = fromIndex; 346*04eeddc0SDimitry Andric entry.toIndex = toIndex; 347*04eeddc0SDimitry Andric entry.count = count; 348*04eeddc0SDimitry Andric } 349*04eeddc0SDimitry Andric } 350349cc55cSDimitry Andric // ld64 does not appear to emit contents from sections within the __LLVM 351349cc55cSDimitry Andric // segment. Symbols within those sections point to bitcode metadata 352349cc55cSDimitry Andric // instead of actual symbols. Global symbols within those sections could 353349cc55cSDimitry Andric // have the same name without causing duplicate symbol errors. Push an 354349cc55cSDimitry Andric // empty entry to ensure indices line up for the remaining sections. 355349cc55cSDimitry Andric // TODO: Evaluate whether the bitcode metadata is needed. 356349cc55cSDimitry Andric sections.push_back(sec.addr); 357fe6060f1SDimitry Andric } else { 358fe6060f1SDimitry Andric auto *isec = 359fe6060f1SDimitry Andric make<ConcatInputSection>(segname, name, this, data, align, flags); 360349cc55cSDimitry Andric if (isDebugSection(isec->getFlags()) && 361349cc55cSDimitry Andric isec->getSegName() == segment_names::dwarf) { 362e8d8bef9SDimitry Andric // Instead of emitting DWARF sections, we emit STABS symbols to the 363e8d8bef9SDimitry Andric // object files that contain them. We filter them out early to avoid 364e8d8bef9SDimitry Andric // parsing their relocations unnecessarily. But we must still push an 365349cc55cSDimitry Andric // empty entry to ensure the indices line up for the remaining sections. 366349cc55cSDimitry Andric sections.push_back(sec.addr); 367e8d8bef9SDimitry Andric debugSections.push_back(isec); 368349cc55cSDimitry Andric } else { 369349cc55cSDimitry Andric sections.push_back(sec.addr); 370349cc55cSDimitry Andric sections.back().subsections.push_back({0, isec}); 371e8d8bef9SDimitry Andric } 3725ffd83dbSDimitry Andric } 3735ffd83dbSDimitry Andric } 374fe6060f1SDimitry Andric } 3755ffd83dbSDimitry Andric 3765ffd83dbSDimitry Andric // Find the subsection corresponding to the greatest section offset that is <= 3775ffd83dbSDimitry Andric // that of the given offset. 3785ffd83dbSDimitry Andric // 3795ffd83dbSDimitry Andric // offset: an offset relative to the start of the original InputSection (before 3805ffd83dbSDimitry Andric // any subsection splitting has occurred). It will be updated to represent the 3815ffd83dbSDimitry Andric // same location as an offset relative to the start of the containing 3825ffd83dbSDimitry Andric // subsection. 383349cc55cSDimitry Andric template <class T> 384349cc55cSDimitry Andric static InputSection *findContainingSubsection(const Subsections &subsections, 385349cc55cSDimitry Andric T *offset) { 386349cc55cSDimitry Andric static_assert(std::is_same<uint64_t, T>::value || 387349cc55cSDimitry Andric std::is_same<uint32_t, T>::value, 388349cc55cSDimitry Andric "unexpected type for offset"); 389fe6060f1SDimitry Andric auto it = std::prev(llvm::upper_bound( 390349cc55cSDimitry Andric subsections, *offset, 391349cc55cSDimitry Andric [](uint64_t value, Subsection subsec) { return value < subsec.offset; })); 392fe6060f1SDimitry Andric *offset -= it->offset; 393fe6060f1SDimitry Andric return it->isec; 3945ffd83dbSDimitry Andric } 3955ffd83dbSDimitry Andric 396349cc55cSDimitry Andric template <class SectionHeader> 397349cc55cSDimitry Andric static bool validateRelocationInfo(InputFile *file, const SectionHeader &sec, 398fe6060f1SDimitry Andric relocation_info rel) { 399fe6060f1SDimitry Andric const RelocAttrs &relocAttrs = target->getRelocAttrs(rel.r_type); 400fe6060f1SDimitry Andric bool valid = true; 401fe6060f1SDimitry Andric auto message = [relocAttrs, file, sec, rel, &valid](const Twine &diagnostic) { 402fe6060f1SDimitry Andric valid = false; 403fe6060f1SDimitry Andric return (relocAttrs.name + " relocation " + diagnostic + " at offset " + 404fe6060f1SDimitry Andric std::to_string(rel.r_address) + " of " + sec.segname + "," + 405fe6060f1SDimitry Andric sec.sectname + " in " + toString(file)) 406fe6060f1SDimitry Andric .str(); 407fe6060f1SDimitry Andric }; 408fe6060f1SDimitry Andric 409fe6060f1SDimitry Andric if (!relocAttrs.hasAttr(RelocAttrBits::LOCAL) && !rel.r_extern) 410fe6060f1SDimitry Andric error(message("must be extern")); 411fe6060f1SDimitry Andric if (relocAttrs.hasAttr(RelocAttrBits::PCREL) != rel.r_pcrel) 412fe6060f1SDimitry Andric error(message(Twine("must ") + (rel.r_pcrel ? "not " : "") + 413fe6060f1SDimitry Andric "be PC-relative")); 414fe6060f1SDimitry Andric if (isThreadLocalVariables(sec.flags) && 415fe6060f1SDimitry Andric !relocAttrs.hasAttr(RelocAttrBits::UNSIGNED)) 416fe6060f1SDimitry Andric error(message("not allowed in thread-local section, must be UNSIGNED")); 417fe6060f1SDimitry Andric if (rel.r_length < 2 || rel.r_length > 3 || 418fe6060f1SDimitry Andric !relocAttrs.hasAttr(static_cast<RelocAttrBits>(1 << rel.r_length))) { 419fe6060f1SDimitry Andric static SmallVector<StringRef, 4> widths{"0", "4", "8", "4 or 8"}; 420fe6060f1SDimitry Andric error(message("has width " + std::to_string(1 << rel.r_length) + 421fe6060f1SDimitry Andric " bytes, but must be " + 422fe6060f1SDimitry Andric widths[(static_cast<int>(relocAttrs.bits) >> 2) & 3] + 423fe6060f1SDimitry Andric " bytes")); 424fe6060f1SDimitry Andric } 425fe6060f1SDimitry Andric return valid; 426fe6060f1SDimitry Andric } 427fe6060f1SDimitry Andric 428349cc55cSDimitry Andric template <class SectionHeader> 429349cc55cSDimitry Andric void ObjFile::parseRelocations(ArrayRef<SectionHeader> sectionHeaders, 430349cc55cSDimitry Andric const SectionHeader &sec, 431349cc55cSDimitry Andric Subsections &subsections) { 4325ffd83dbSDimitry Andric auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 433e8d8bef9SDimitry Andric ArrayRef<relocation_info> relInfos( 434e8d8bef9SDimitry Andric reinterpret_cast<const relocation_info *>(buf + sec.reloff), sec.nreloc); 4355ffd83dbSDimitry Andric 436349cc55cSDimitry Andric auto subsecIt = subsections.rbegin(); 437e8d8bef9SDimitry Andric for (size_t i = 0; i < relInfos.size(); i++) { 438e8d8bef9SDimitry Andric // Paired relocations serve as Mach-O's method for attaching a 439e8d8bef9SDimitry Andric // supplemental datum to a primary relocation record. ELF does not 440e8d8bef9SDimitry Andric // need them because the *_RELOC_RELA records contain the extra 441e8d8bef9SDimitry Andric // addend field, vs. *_RELOC_REL which omit the addend. 442e8d8bef9SDimitry Andric // 443e8d8bef9SDimitry Andric // The {X86_64,ARM64}_RELOC_SUBTRACTOR record holds the subtrahend, 444e8d8bef9SDimitry Andric // and the paired *_RELOC_UNSIGNED record holds the minuend. The 445fe6060f1SDimitry Andric // datum for each is a symbolic address. The result is the offset 446fe6060f1SDimitry Andric // between two addresses. 447e8d8bef9SDimitry Andric // 448e8d8bef9SDimitry Andric // The ARM64_RELOC_ADDEND record holds the addend, and the paired 449e8d8bef9SDimitry Andric // ARM64_RELOC_BRANCH26 or ARM64_RELOC_PAGE21/PAGEOFF12 holds the 450e8d8bef9SDimitry Andric // base symbolic address. 451e8d8bef9SDimitry Andric // 452e8d8bef9SDimitry Andric // Note: X86 does not use *_RELOC_ADDEND because it can embed an 453e8d8bef9SDimitry Andric // addend into the instruction stream. On X86, a relocatable address 454e8d8bef9SDimitry Andric // field always occupies an entire contiguous sequence of byte(s), 455e8d8bef9SDimitry Andric // so there is no need to merge opcode bits with address 456e8d8bef9SDimitry Andric // bits. Therefore, it's easy and convenient to store addends in the 457e8d8bef9SDimitry Andric // instruction-stream bytes that would otherwise contain zeroes. By 458e8d8bef9SDimitry Andric // contrast, RISC ISAs such as ARM64 mix opcode bits with with 459e8d8bef9SDimitry Andric // address bits so that bitwise arithmetic is necessary to extract 460e8d8bef9SDimitry Andric // and insert them. Storing addends in the instruction stream is 461e8d8bef9SDimitry Andric // possible, but inconvenient and more costly at link time. 462e8d8bef9SDimitry Andric 463fe6060f1SDimitry Andric relocation_info relInfo = relInfos[i]; 464349cc55cSDimitry Andric bool isSubtrahend = 465349cc55cSDimitry Andric target->hasAttr(relInfo.r_type, RelocAttrBits::SUBTRAHEND); 466349cc55cSDimitry Andric if (isSubtrahend && StringRef(sec.sectname) == section_names::ehFrame) { 467349cc55cSDimitry Andric // __TEXT,__eh_frame only has symbols and SUBTRACTOR relocs when ld64 -r 468349cc55cSDimitry Andric // adds local "EH_Frame1" and "func.eh". Ignore them because they have 469349cc55cSDimitry Andric // gone unused by Mac OS since Snow Leopard (10.6), vintage 2009. 470349cc55cSDimitry Andric ++i; 471349cc55cSDimitry Andric continue; 472349cc55cSDimitry Andric } 473349cc55cSDimitry Andric int64_t pairedAddend = 0; 474fe6060f1SDimitry Andric if (target->hasAttr(relInfo.r_type, RelocAttrBits::ADDEND)) { 475fe6060f1SDimitry Andric pairedAddend = SignExtend64<24>(relInfo.r_symbolnum); 476fe6060f1SDimitry Andric relInfo = relInfos[++i]; 477fe6060f1SDimitry Andric } 478e8d8bef9SDimitry Andric assert(i < relInfos.size()); 479fe6060f1SDimitry Andric if (!validateRelocationInfo(this, sec, relInfo)) 480fe6060f1SDimitry Andric continue; 481e8d8bef9SDimitry Andric if (relInfo.r_address & R_SCATTERED) 4825ffd83dbSDimitry Andric fatal("TODO: Scattered relocations not supported"); 4835ffd83dbSDimitry Andric 484fe6060f1SDimitry Andric int64_t embeddedAddend = target->getEmbeddedAddend(mb, sec.offset, relInfo); 485fe6060f1SDimitry Andric assert(!(embeddedAddend && pairedAddend)); 486fe6060f1SDimitry Andric int64_t totalAddend = pairedAddend + embeddedAddend; 4875ffd83dbSDimitry Andric Reloc r; 488e8d8bef9SDimitry Andric r.type = relInfo.r_type; 489e8d8bef9SDimitry Andric r.pcrel = relInfo.r_pcrel; 490e8d8bef9SDimitry Andric r.length = relInfo.r_length; 491e8d8bef9SDimitry Andric r.offset = relInfo.r_address; 492e8d8bef9SDimitry Andric if (relInfo.r_extern) { 493e8d8bef9SDimitry Andric r.referent = symbols[relInfo.r_symbolnum]; 494fe6060f1SDimitry Andric r.addend = isSubtrahend ? 0 : totalAddend; 4955ffd83dbSDimitry Andric } else { 496fe6060f1SDimitry Andric assert(!isSubtrahend); 497349cc55cSDimitry Andric const SectionHeader &referentSecHead = 498349cc55cSDimitry Andric sectionHeaders[relInfo.r_symbolnum - 1]; 499fe6060f1SDimitry Andric uint64_t referentOffset; 500e8d8bef9SDimitry Andric if (relInfo.r_pcrel) { 5015ffd83dbSDimitry Andric // The implicit addend for pcrel section relocations is the pcrel offset 5025ffd83dbSDimitry Andric // in terms of the addresses in the input file. Here we adjust it so 503e8d8bef9SDimitry Andric // that it describes the offset from the start of the referent section. 504fe6060f1SDimitry Andric // FIXME This logic was written around x86_64 behavior -- ARM64 doesn't 505fe6060f1SDimitry Andric // have pcrel section relocations. We may want to factor this out into 506fe6060f1SDimitry Andric // the arch-specific .cpp file. 507fe6060f1SDimitry Andric assert(target->hasAttr(r.type, RelocAttrBits::BYTE4)); 508349cc55cSDimitry Andric referentOffset = sec.addr + relInfo.r_address + 4 + totalAddend - 509349cc55cSDimitry Andric referentSecHead.addr; 5105ffd83dbSDimitry Andric } else { 5115ffd83dbSDimitry Andric // The addend for a non-pcrel relocation is its absolute address. 512349cc55cSDimitry Andric referentOffset = totalAddend - referentSecHead.addr; 5135ffd83dbSDimitry Andric } 514349cc55cSDimitry Andric Subsections &referentSubsections = 515349cc55cSDimitry Andric sections[relInfo.r_symbolnum - 1].subsections; 516349cc55cSDimitry Andric r.referent = 517349cc55cSDimitry Andric findContainingSubsection(referentSubsections, &referentOffset); 518e8d8bef9SDimitry Andric r.addend = referentOffset; 5195ffd83dbSDimitry Andric } 5205ffd83dbSDimitry Andric 521fe6060f1SDimitry Andric // Find the subsection that this relocation belongs to. 522fe6060f1SDimitry Andric // Though not required by the Mach-O format, clang and gcc seem to emit 523fe6060f1SDimitry Andric // relocations in order, so let's take advantage of it. However, ld64 emits 524fe6060f1SDimitry Andric // unsorted relocations (in `-r` mode), so we have a fallback for that 525fe6060f1SDimitry Andric // uncommon case. 526fe6060f1SDimitry Andric InputSection *subsec; 527349cc55cSDimitry Andric while (subsecIt != subsections.rend() && subsecIt->offset > r.offset) 528fe6060f1SDimitry Andric ++subsecIt; 529349cc55cSDimitry Andric if (subsecIt == subsections.rend() || 530fe6060f1SDimitry Andric subsecIt->offset + subsecIt->isec->getSize() <= r.offset) { 531349cc55cSDimitry Andric subsec = findContainingSubsection(subsections, &r.offset); 532fe6060f1SDimitry Andric // Now that we know the relocs are unsorted, avoid trying the 'fast path' 533fe6060f1SDimitry Andric // for the other relocations. 534349cc55cSDimitry Andric subsecIt = subsections.rend(); 535fe6060f1SDimitry Andric } else { 536fe6060f1SDimitry Andric subsec = subsecIt->isec; 537fe6060f1SDimitry Andric r.offset -= subsecIt->offset; 538fe6060f1SDimitry Andric } 5395ffd83dbSDimitry Andric subsec->relocs.push_back(r); 540fe6060f1SDimitry Andric 541fe6060f1SDimitry Andric if (isSubtrahend) { 542fe6060f1SDimitry Andric relocation_info minuendInfo = relInfos[++i]; 543fe6060f1SDimitry Andric // SUBTRACTOR relocations should always be followed by an UNSIGNED one 544fe6060f1SDimitry Andric // attached to the same address. 545fe6060f1SDimitry Andric assert(target->hasAttr(minuendInfo.r_type, RelocAttrBits::UNSIGNED) && 546fe6060f1SDimitry Andric relInfo.r_address == minuendInfo.r_address); 547fe6060f1SDimitry Andric Reloc p; 548fe6060f1SDimitry Andric p.type = minuendInfo.r_type; 549fe6060f1SDimitry Andric if (minuendInfo.r_extern) { 550fe6060f1SDimitry Andric p.referent = symbols[minuendInfo.r_symbolnum]; 551fe6060f1SDimitry Andric p.addend = totalAddend; 552fe6060f1SDimitry Andric } else { 553fe6060f1SDimitry Andric uint64_t referentOffset = 554fe6060f1SDimitry Andric totalAddend - sectionHeaders[minuendInfo.r_symbolnum - 1].addr; 555349cc55cSDimitry Andric Subsections &referentSubsectVec = 556349cc55cSDimitry Andric sections[minuendInfo.r_symbolnum - 1].subsections; 557fe6060f1SDimitry Andric p.referent = 558349cc55cSDimitry Andric findContainingSubsection(referentSubsectVec, &referentOffset); 559fe6060f1SDimitry Andric p.addend = referentOffset; 560fe6060f1SDimitry Andric } 561fe6060f1SDimitry Andric subsec->relocs.push_back(p); 562fe6060f1SDimitry Andric } 5635ffd83dbSDimitry Andric } 5645ffd83dbSDimitry Andric } 5655ffd83dbSDimitry Andric 566fe6060f1SDimitry Andric template <class NList> 567fe6060f1SDimitry Andric static macho::Symbol *createDefined(const NList &sym, StringRef name, 568fe6060f1SDimitry Andric InputSection *isec, uint64_t value, 569fe6060f1SDimitry Andric uint64_t size) { 570e8d8bef9SDimitry Andric // Symbol scope is determined by sym.n_type & (N_EXT | N_PEXT): 571fe6060f1SDimitry Andric // N_EXT: Global symbols. These go in the symbol table during the link, 572fe6060f1SDimitry Andric // and also in the export table of the output so that the dynamic 573fe6060f1SDimitry Andric // linker sees them. 574fe6060f1SDimitry Andric // N_EXT | N_PEXT: Linkage unit (think: dylib) scoped. These go in the 575fe6060f1SDimitry Andric // symbol table during the link so that duplicates are 576fe6060f1SDimitry Andric // either reported (for non-weak symbols) or merged 577fe6060f1SDimitry Andric // (for weak symbols), but they do not go in the export 578fe6060f1SDimitry Andric // table of the output. 579fe6060f1SDimitry Andric // N_PEXT: llvm-mc does not emit these, but `ld -r` (wherein ld64 emits 580fe6060f1SDimitry Andric // object files) may produce them. LLD does not yet support -r. 581fe6060f1SDimitry Andric // These are translation-unit scoped, identical to the `0` case. 582fe6060f1SDimitry Andric // 0: Translation-unit scoped. These are not in the symbol table during 583fe6060f1SDimitry Andric // link, and not in the export table of the output either. 584fe6060f1SDimitry Andric bool isWeakDefCanBeHidden = 585fe6060f1SDimitry Andric (sym.n_desc & (N_WEAK_DEF | N_WEAK_REF)) == (N_WEAK_DEF | N_WEAK_REF); 586e8d8bef9SDimitry Andric 587fe6060f1SDimitry Andric if (sym.n_type & N_EXT) { 588fe6060f1SDimitry Andric bool isPrivateExtern = sym.n_type & N_PEXT; 589fe6060f1SDimitry Andric // lld's behavior for merging symbols is slightly different from ld64: 590fe6060f1SDimitry Andric // ld64 picks the winning symbol based on several criteria (see 591fe6060f1SDimitry Andric // pickBetweenRegularAtoms() in ld64's SymbolTable.cpp), while lld 592fe6060f1SDimitry Andric // just merges metadata and keeps the contents of the first symbol 593fe6060f1SDimitry Andric // with that name (see SymbolTable::addDefined). For: 594fe6060f1SDimitry Andric // * inline function F in a TU built with -fvisibility-inlines-hidden 595fe6060f1SDimitry Andric // * and inline function F in another TU built without that flag 596fe6060f1SDimitry Andric // ld64 will pick the one from the file built without 597fe6060f1SDimitry Andric // -fvisibility-inlines-hidden. 598fe6060f1SDimitry Andric // lld will instead pick the one listed first on the link command line and 599fe6060f1SDimitry Andric // give it visibility as if the function was built without 600fe6060f1SDimitry Andric // -fvisibility-inlines-hidden. 601fe6060f1SDimitry Andric // If both functions have the same contents, this will have the same 602fe6060f1SDimitry Andric // behavior. If not, it won't, but the input had an ODR violation in 603fe6060f1SDimitry Andric // that case. 604fe6060f1SDimitry Andric // 605fe6060f1SDimitry Andric // Similarly, merging a symbol 606fe6060f1SDimitry Andric // that's isPrivateExtern and not isWeakDefCanBeHidden with one 607fe6060f1SDimitry Andric // that's not isPrivateExtern but isWeakDefCanBeHidden technically 608fe6060f1SDimitry Andric // should produce one 609fe6060f1SDimitry Andric // that's not isPrivateExtern but isWeakDefCanBeHidden. That matters 610fe6060f1SDimitry Andric // with ld64's semantics, because it means the non-private-extern 611fe6060f1SDimitry Andric // definition will continue to take priority if more private extern 612fe6060f1SDimitry Andric // definitions are encountered. With lld's semantics there's no observable 613349cc55cSDimitry Andric // difference between a symbol that's isWeakDefCanBeHidden(autohide) or one 614349cc55cSDimitry Andric // that's privateExtern -- neither makes it into the dynamic symbol table, 615349cc55cSDimitry Andric // unless the autohide symbol is explicitly exported. 616349cc55cSDimitry Andric // But if a symbol is both privateExtern and autohide then it can't 617349cc55cSDimitry Andric // be exported. 618349cc55cSDimitry Andric // So we nullify the autohide flag when privateExtern is present 619349cc55cSDimitry Andric // and promote the symbol to privateExtern when it is not already. 620349cc55cSDimitry Andric if (isWeakDefCanBeHidden && isPrivateExtern) 621349cc55cSDimitry Andric isWeakDefCanBeHidden = false; 622349cc55cSDimitry Andric else if (isWeakDefCanBeHidden) 623fe6060f1SDimitry Andric isPrivateExtern = true; 624fe6060f1SDimitry Andric return symtab->addDefined( 625fe6060f1SDimitry Andric name, isec->getFile(), isec, value, size, sym.n_desc & N_WEAK_DEF, 626fe6060f1SDimitry Andric isPrivateExtern, sym.n_desc & N_ARM_THUMB_DEF, 627349cc55cSDimitry Andric sym.n_desc & REFERENCED_DYNAMICALLY, sym.n_desc & N_NO_DEAD_STRIP, 628349cc55cSDimitry Andric isWeakDefCanBeHidden); 629e8d8bef9SDimitry Andric } 630fe6060f1SDimitry Andric assert(!isWeakDefCanBeHidden && 631fe6060f1SDimitry Andric "weak_def_can_be_hidden on already-hidden symbol?"); 632fe6060f1SDimitry Andric return make<Defined>( 633fe6060f1SDimitry Andric name, isec->getFile(), isec, value, size, sym.n_desc & N_WEAK_DEF, 634fe6060f1SDimitry Andric /*isExternal=*/false, /*isPrivateExtern=*/false, 635fe6060f1SDimitry Andric sym.n_desc & N_ARM_THUMB_DEF, sym.n_desc & REFERENCED_DYNAMICALLY, 636fe6060f1SDimitry Andric sym.n_desc & N_NO_DEAD_STRIP); 637e8d8bef9SDimitry Andric } 638e8d8bef9SDimitry Andric 639e8d8bef9SDimitry Andric // Absolute symbols are defined symbols that do not have an associated 640e8d8bef9SDimitry Andric // InputSection. They cannot be weak. 641fe6060f1SDimitry Andric template <class NList> 642fe6060f1SDimitry Andric static macho::Symbol *createAbsolute(const NList &sym, InputFile *file, 643e8d8bef9SDimitry Andric StringRef name) { 644fe6060f1SDimitry Andric if (sym.n_type & N_EXT) { 645fe6060f1SDimitry Andric return symtab->addDefined( 646fe6060f1SDimitry Andric name, file, nullptr, sym.n_value, /*size=*/0, 647fe6060f1SDimitry Andric /*isWeakDef=*/false, sym.n_type & N_PEXT, sym.n_desc & N_ARM_THUMB_DEF, 648349cc55cSDimitry Andric /*isReferencedDynamically=*/false, sym.n_desc & N_NO_DEAD_STRIP, 649349cc55cSDimitry Andric /*isWeakDefCanBeHidden=*/false); 650e8d8bef9SDimitry Andric } 651fe6060f1SDimitry Andric return make<Defined>(name, file, nullptr, sym.n_value, /*size=*/0, 652fe6060f1SDimitry Andric /*isWeakDef=*/false, 653fe6060f1SDimitry Andric /*isExternal=*/false, /*isPrivateExtern=*/false, 654fe6060f1SDimitry Andric sym.n_desc & N_ARM_THUMB_DEF, 655fe6060f1SDimitry Andric /*isReferencedDynamically=*/false, 656fe6060f1SDimitry Andric sym.n_desc & N_NO_DEAD_STRIP); 657e8d8bef9SDimitry Andric } 658e8d8bef9SDimitry Andric 659fe6060f1SDimitry Andric template <class NList> 660fe6060f1SDimitry Andric macho::Symbol *ObjFile::parseNonSectionSymbol(const NList &sym, 661e8d8bef9SDimitry Andric StringRef name) { 662e8d8bef9SDimitry Andric uint8_t type = sym.n_type & N_TYPE; 663e8d8bef9SDimitry Andric switch (type) { 664e8d8bef9SDimitry Andric case N_UNDF: 665e8d8bef9SDimitry Andric return sym.n_value == 0 666fe6060f1SDimitry Andric ? symtab->addUndefined(name, this, sym.n_desc & N_WEAK_REF) 667e8d8bef9SDimitry Andric : symtab->addCommon(name, this, sym.n_value, 668e8d8bef9SDimitry Andric 1 << GET_COMM_ALIGN(sym.n_desc), 669e8d8bef9SDimitry Andric sym.n_type & N_PEXT); 670e8d8bef9SDimitry Andric case N_ABS: 671fe6060f1SDimitry Andric return createAbsolute(sym, this, name); 672e8d8bef9SDimitry Andric case N_PBUD: 673e8d8bef9SDimitry Andric case N_INDR: 674e8d8bef9SDimitry Andric error("TODO: support symbols of type " + std::to_string(type)); 675e8d8bef9SDimitry Andric return nullptr; 676e8d8bef9SDimitry Andric case N_SECT: 677e8d8bef9SDimitry Andric llvm_unreachable( 678e8d8bef9SDimitry Andric "N_SECT symbols should not be passed to parseNonSectionSymbol"); 679e8d8bef9SDimitry Andric default: 680e8d8bef9SDimitry Andric llvm_unreachable("invalid symbol type"); 681e8d8bef9SDimitry Andric } 682e8d8bef9SDimitry Andric } 683e8d8bef9SDimitry Andric 684349cc55cSDimitry Andric template <class NList> static bool isUndef(const NList &sym) { 685fe6060f1SDimitry Andric return (sym.n_type & N_TYPE) == N_UNDF && sym.n_value == 0; 686fe6060f1SDimitry Andric } 687fe6060f1SDimitry Andric 688fe6060f1SDimitry Andric template <class LP> 689fe6060f1SDimitry Andric void ObjFile::parseSymbols(ArrayRef<typename LP::section> sectionHeaders, 690fe6060f1SDimitry Andric ArrayRef<typename LP::nlist> nList, 6915ffd83dbSDimitry Andric const char *strtab, bool subsectionsViaSymbols) { 692fe6060f1SDimitry Andric using NList = typename LP::nlist; 693fe6060f1SDimitry Andric 694fe6060f1SDimitry Andric // Groups indices of the symbols by the sections that contain them. 695349cc55cSDimitry Andric std::vector<std::vector<uint32_t>> symbolsBySection(sections.size()); 6965ffd83dbSDimitry Andric symbols.resize(nList.size()); 697fe6060f1SDimitry Andric SmallVector<unsigned, 32> undefineds; 698fe6060f1SDimitry Andric for (uint32_t i = 0; i < nList.size(); ++i) { 699fe6060f1SDimitry Andric const NList &sym = nList[i]; 7005ffd83dbSDimitry Andric 701fe6060f1SDimitry Andric // Ignore debug symbols for now. 702fe6060f1SDimitry Andric // FIXME: may need special handling. 703fe6060f1SDimitry Andric if (sym.n_type & N_STAB) 704fe6060f1SDimitry Andric continue; 705fe6060f1SDimitry Andric 7065ffd83dbSDimitry Andric StringRef name = strtab + sym.n_strx; 707fe6060f1SDimitry Andric if ((sym.n_type & N_TYPE) == N_SECT) { 708349cc55cSDimitry Andric Subsections &subsections = sections[sym.n_sect - 1].subsections; 709fe6060f1SDimitry Andric // parseSections() may have chosen not to parse this section. 710349cc55cSDimitry Andric if (subsections.empty()) 711fe6060f1SDimitry Andric continue; 712fe6060f1SDimitry Andric symbolsBySection[sym.n_sect - 1].push_back(i); 713fe6060f1SDimitry Andric } else if (isUndef(sym)) { 714fe6060f1SDimitry Andric undefineds.push_back(i); 715fe6060f1SDimitry Andric } else { 716fe6060f1SDimitry Andric symbols[i] = parseNonSectionSymbol(sym, name); 717fe6060f1SDimitry Andric } 718fe6060f1SDimitry Andric } 7195ffd83dbSDimitry Andric 720349cc55cSDimitry Andric for (size_t i = 0; i < sections.size(); ++i) { 721349cc55cSDimitry Andric Subsections &subsections = sections[i].subsections; 722349cc55cSDimitry Andric if (subsections.empty()) 723fe6060f1SDimitry Andric continue; 724349cc55cSDimitry Andric InputSection *lastIsec = subsections.back().isec; 725349cc55cSDimitry Andric if (lastIsec->getName() == section_names::ehFrame) { 726349cc55cSDimitry Andric // __TEXT,__eh_frame only has symbols and SUBTRACTOR relocs when ld64 -r 727349cc55cSDimitry Andric // adds local "EH_Frame1" and "func.eh". Ignore them because they have 728349cc55cSDimitry Andric // gone unused by Mac OS since Snow Leopard (10.6), vintage 2009. 729349cc55cSDimitry Andric continue; 730349cc55cSDimitry Andric } 731fe6060f1SDimitry Andric std::vector<uint32_t> &symbolIndices = symbolsBySection[i]; 732fe6060f1SDimitry Andric uint64_t sectionAddr = sectionHeaders[i].addr; 733fe6060f1SDimitry Andric uint32_t sectionAlign = 1u << sectionHeaders[i].align; 734fe6060f1SDimitry Andric 735349cc55cSDimitry Andric // Record-based sections have already been split into subsections during 736fe6060f1SDimitry Andric // parseSections(), so we simply need to match Symbols to the corresponding 737fe6060f1SDimitry Andric // subsection here. 738349cc55cSDimitry Andric if (getRecordSize(lastIsec->getSegName(), lastIsec->getName())) { 739fe6060f1SDimitry Andric for (size_t j = 0; j < symbolIndices.size(); ++j) { 740fe6060f1SDimitry Andric uint32_t symIndex = symbolIndices[j]; 741fe6060f1SDimitry Andric const NList &sym = nList[symIndex]; 742fe6060f1SDimitry Andric StringRef name = strtab + sym.n_strx; 743fe6060f1SDimitry Andric uint64_t symbolOffset = sym.n_value - sectionAddr; 744349cc55cSDimitry Andric InputSection *isec = 745349cc55cSDimitry Andric findContainingSubsection(subsections, &symbolOffset); 746fe6060f1SDimitry Andric if (symbolOffset != 0) { 747349cc55cSDimitry Andric error(toString(lastIsec) + ": symbol " + name + 748fe6060f1SDimitry Andric " at misaligned offset"); 749fe6060f1SDimitry Andric continue; 750fe6060f1SDimitry Andric } 751fe6060f1SDimitry Andric symbols[symIndex] = createDefined(sym, name, isec, 0, isec->getSize()); 752fe6060f1SDimitry Andric } 7535ffd83dbSDimitry Andric continue; 7545ffd83dbSDimitry Andric } 7555ffd83dbSDimitry Andric 756fe6060f1SDimitry Andric // Calculate symbol sizes and create subsections by splitting the sections 757fe6060f1SDimitry Andric // along symbol boundaries. 758349cc55cSDimitry Andric // We populate subsections by repeatedly splitting the last (highest 759349cc55cSDimitry Andric // address) subsection. 760fe6060f1SDimitry Andric llvm::stable_sort(symbolIndices, [&](uint32_t lhs, uint32_t rhs) { 761fe6060f1SDimitry Andric return nList[lhs].n_value < nList[rhs].n_value; 762fe6060f1SDimitry Andric }); 763fe6060f1SDimitry Andric for (size_t j = 0; j < symbolIndices.size(); ++j) { 764fe6060f1SDimitry Andric uint32_t symIndex = symbolIndices[j]; 765fe6060f1SDimitry Andric const NList &sym = nList[symIndex]; 766fe6060f1SDimitry Andric StringRef name = strtab + sym.n_strx; 767349cc55cSDimitry Andric Subsection &subsec = subsections.back(); 768349cc55cSDimitry Andric InputSection *isec = subsec.isec; 769fe6060f1SDimitry Andric 770349cc55cSDimitry Andric uint64_t subsecAddr = sectionAddr + subsec.offset; 771fe6060f1SDimitry Andric size_t symbolOffset = sym.n_value - subsecAddr; 772fe6060f1SDimitry Andric uint64_t symbolSize = 773fe6060f1SDimitry Andric j + 1 < symbolIndices.size() 774fe6060f1SDimitry Andric ? nList[symbolIndices[j + 1]].n_value - sym.n_value 775fe6060f1SDimitry Andric : isec->data.size() - symbolOffset; 776fe6060f1SDimitry Andric // There are 4 cases where we do not need to create a new subsection: 777fe6060f1SDimitry Andric // 1. If the input file does not use subsections-via-symbols. 778fe6060f1SDimitry Andric // 2. Multiple symbols at the same address only induce one subsection. 779fe6060f1SDimitry Andric // (The symbolOffset == 0 check covers both this case as well as 780fe6060f1SDimitry Andric // the first loop iteration.) 781fe6060f1SDimitry Andric // 3. Alternative entry points do not induce new subsections. 782fe6060f1SDimitry Andric // 4. If we have a literal section (e.g. __cstring and __literal4). 783fe6060f1SDimitry Andric if (!subsectionsViaSymbols || symbolOffset == 0 || 784fe6060f1SDimitry Andric sym.n_desc & N_ALT_ENTRY || !isa<ConcatInputSection>(isec)) { 785fe6060f1SDimitry Andric symbols[symIndex] = 786fe6060f1SDimitry Andric createDefined(sym, name, isec, symbolOffset, symbolSize); 7875ffd83dbSDimitry Andric continue; 7885ffd83dbSDimitry Andric } 789fe6060f1SDimitry Andric auto *concatIsec = cast<ConcatInputSection>(isec); 7905ffd83dbSDimitry Andric 791fe6060f1SDimitry Andric auto *nextIsec = make<ConcatInputSection>(*concatIsec); 792fe6060f1SDimitry Andric nextIsec->wasCoalesced = false; 793fe6060f1SDimitry Andric if (isZeroFill(isec->getFlags())) { 794fe6060f1SDimitry Andric // Zero-fill sections have NULL data.data() non-zero data.size() 795fe6060f1SDimitry Andric nextIsec->data = {nullptr, isec->data.size() - symbolOffset}; 796fe6060f1SDimitry Andric isec->data = {nullptr, symbolOffset}; 797fe6060f1SDimitry Andric } else { 798fe6060f1SDimitry Andric nextIsec->data = isec->data.slice(symbolOffset); 799fe6060f1SDimitry Andric isec->data = isec->data.slice(0, symbolOffset); 8005ffd83dbSDimitry Andric } 8015ffd83dbSDimitry Andric 802fe6060f1SDimitry Andric // By construction, the symbol will be at offset zero in the new 803fe6060f1SDimitry Andric // subsection. 804fe6060f1SDimitry Andric symbols[symIndex] = 805fe6060f1SDimitry Andric createDefined(sym, name, nextIsec, /*value=*/0, symbolSize); 8065ffd83dbSDimitry Andric // TODO: ld64 appears to preserve the original alignment as well as each 8075ffd83dbSDimitry Andric // subsection's offset from the last aligned address. We should consider 8085ffd83dbSDimitry Andric // emulating that behavior. 809fe6060f1SDimitry Andric nextIsec->align = MinAlign(sectionAlign, sym.n_value); 810349cc55cSDimitry Andric subsections.push_back({sym.n_value - sectionAddr, nextIsec}); 811fe6060f1SDimitry Andric } 8125ffd83dbSDimitry Andric } 8135ffd83dbSDimitry Andric 814fe6060f1SDimitry Andric // Undefined symbols can trigger recursive fetch from Archives due to 815fe6060f1SDimitry Andric // LazySymbols. Process defined symbols first so that the relative order 816fe6060f1SDimitry Andric // between a defined symbol and an undefined symbol does not change the 817fe6060f1SDimitry Andric // symbol resolution behavior. In addition, a set of interconnected symbols 818fe6060f1SDimitry Andric // will all be resolved to the same file, instead of being resolved to 819fe6060f1SDimitry Andric // different files. 820fe6060f1SDimitry Andric for (unsigned i : undefineds) { 821fe6060f1SDimitry Andric const NList &sym = nList[i]; 822e8d8bef9SDimitry Andric StringRef name = strtab + sym.n_strx; 823fe6060f1SDimitry Andric symbols[i] = parseNonSectionSymbol(sym, name); 8245ffd83dbSDimitry Andric } 8255ffd83dbSDimitry Andric } 8265ffd83dbSDimitry Andric 827e8d8bef9SDimitry Andric OpaqueFile::OpaqueFile(MemoryBufferRef mb, StringRef segName, 828e8d8bef9SDimitry Andric StringRef sectName) 829e8d8bef9SDimitry Andric : InputFile(OpaqueKind, mb) { 830e8d8bef9SDimitry Andric const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 831fe6060f1SDimitry Andric ArrayRef<uint8_t> data = {buf, mb.getBufferSize()}; 832fe6060f1SDimitry Andric ConcatInputSection *isec = 833fe6060f1SDimitry Andric make<ConcatInputSection>(segName.take_front(16), sectName.take_front(16), 834fe6060f1SDimitry Andric /*file=*/this, data); 835fe6060f1SDimitry Andric isec->live = true; 836349cc55cSDimitry Andric sections.push_back(0); 837349cc55cSDimitry Andric sections.back().subsections.push_back({0, isec}); 838e8d8bef9SDimitry Andric } 839e8d8bef9SDimitry Andric 840*04eeddc0SDimitry Andric ObjFile::ObjFile(MemoryBufferRef mb, uint32_t modTime, StringRef archiveName, 841*04eeddc0SDimitry Andric bool lazy) 842*04eeddc0SDimitry Andric : InputFile(ObjKind, mb, lazy), modTime(modTime) { 843e8d8bef9SDimitry Andric this->archiveName = std::string(archiveName); 844*04eeddc0SDimitry Andric if (lazy) { 845*04eeddc0SDimitry Andric if (target->wordSize == 8) 846*04eeddc0SDimitry Andric parseLazy<LP64>(); 847*04eeddc0SDimitry Andric else 848*04eeddc0SDimitry Andric parseLazy<ILP32>(); 849*04eeddc0SDimitry Andric } else { 850fe6060f1SDimitry Andric if (target->wordSize == 8) 851fe6060f1SDimitry Andric parse<LP64>(); 852fe6060f1SDimitry Andric else 853fe6060f1SDimitry Andric parse<ILP32>(); 854e8d8bef9SDimitry Andric } 855*04eeddc0SDimitry Andric } 856e8d8bef9SDimitry Andric 857fe6060f1SDimitry Andric template <class LP> void ObjFile::parse() { 858fe6060f1SDimitry Andric using Header = typename LP::mach_header; 859fe6060f1SDimitry Andric using SegmentCommand = typename LP::segment_command; 860349cc55cSDimitry Andric using SectionHeader = typename LP::section; 861fe6060f1SDimitry Andric using NList = typename LP::nlist; 862fe6060f1SDimitry Andric 863fe6060f1SDimitry Andric auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 864fe6060f1SDimitry Andric auto *hdr = reinterpret_cast<const Header *>(mb.getBufferStart()); 865fe6060f1SDimitry Andric 866fe6060f1SDimitry Andric Architecture arch = getArchitectureFromCpuType(hdr->cputype, hdr->cpusubtype); 867fe6060f1SDimitry Andric if (arch != config->arch()) { 868349cc55cSDimitry Andric auto msg = config->errorForArchMismatch 869349cc55cSDimitry Andric ? static_cast<void (*)(const Twine &)>(error) 870349cc55cSDimitry Andric : warn; 871349cc55cSDimitry Andric msg(toString(this) + " has architecture " + getArchitectureName(arch) + 872fe6060f1SDimitry Andric " which is incompatible with target architecture " + 873fe6060f1SDimitry Andric getArchitectureName(config->arch())); 874fe6060f1SDimitry Andric return; 875fe6060f1SDimitry Andric } 876fe6060f1SDimitry Andric 877fe6060f1SDimitry Andric if (!checkCompatibility(this)) 878fe6060f1SDimitry Andric return; 879fe6060f1SDimitry Andric 880fe6060f1SDimitry Andric for (auto *cmd : findCommands<linker_option_command>(hdr, LC_LINKER_OPTION)) { 881fe6060f1SDimitry Andric StringRef data{reinterpret_cast<const char *>(cmd + 1), 882fe6060f1SDimitry Andric cmd->cmdsize - sizeof(linker_option_command)}; 883fe6060f1SDimitry Andric parseLCLinkerOption(this, cmd->count, data); 884fe6060f1SDimitry Andric } 885fe6060f1SDimitry Andric 886349cc55cSDimitry Andric ArrayRef<SectionHeader> sectionHeaders; 887fe6060f1SDimitry Andric if (const load_command *cmd = findCommand(hdr, LP::segmentLCType)) { 888fe6060f1SDimitry Andric auto *c = reinterpret_cast<const SegmentCommand *>(cmd); 889349cc55cSDimitry Andric sectionHeaders = ArrayRef<SectionHeader>{ 890349cc55cSDimitry Andric reinterpret_cast<const SectionHeader *>(c + 1), c->nsects}; 8915ffd83dbSDimitry Andric parseSections(sectionHeaders); 8925ffd83dbSDimitry Andric } 8935ffd83dbSDimitry Andric 8945ffd83dbSDimitry Andric // TODO: Error on missing LC_SYMTAB? 8955ffd83dbSDimitry Andric if (const load_command *cmd = findCommand(hdr, LC_SYMTAB)) { 8965ffd83dbSDimitry Andric auto *c = reinterpret_cast<const symtab_command *>(cmd); 897fe6060f1SDimitry Andric ArrayRef<NList> nList(reinterpret_cast<const NList *>(buf + c->symoff), 898fe6060f1SDimitry Andric c->nsyms); 8995ffd83dbSDimitry Andric const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff; 9005ffd83dbSDimitry Andric bool subsectionsViaSymbols = hdr->flags & MH_SUBSECTIONS_VIA_SYMBOLS; 901fe6060f1SDimitry Andric parseSymbols<LP>(sectionHeaders, nList, strtab, subsectionsViaSymbols); 9025ffd83dbSDimitry Andric } 9035ffd83dbSDimitry Andric 9045ffd83dbSDimitry Andric // The relocations may refer to the symbols, so we parse them after we have 9055ffd83dbSDimitry Andric // parsed all the symbols. 906349cc55cSDimitry Andric for (size_t i = 0, n = sections.size(); i < n; ++i) 907349cc55cSDimitry Andric if (!sections[i].subsections.empty()) 908349cc55cSDimitry Andric parseRelocations(sectionHeaders, sectionHeaders[i], 909349cc55cSDimitry Andric sections[i].subsections); 910e8d8bef9SDimitry Andric 911e8d8bef9SDimitry Andric parseDebugInfo(); 912349cc55cSDimitry Andric if (compactUnwindSection) 913349cc55cSDimitry Andric registerCompactUnwind(); 914e8d8bef9SDimitry Andric } 915e8d8bef9SDimitry Andric 916*04eeddc0SDimitry Andric template <class LP> void ObjFile::parseLazy() { 917*04eeddc0SDimitry Andric using Header = typename LP::mach_header; 918*04eeddc0SDimitry Andric using NList = typename LP::nlist; 919*04eeddc0SDimitry Andric 920*04eeddc0SDimitry Andric auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 921*04eeddc0SDimitry Andric auto *hdr = reinterpret_cast<const Header *>(mb.getBufferStart()); 922*04eeddc0SDimitry Andric const load_command *cmd = findCommand(hdr, LC_SYMTAB); 923*04eeddc0SDimitry Andric if (!cmd) 924*04eeddc0SDimitry Andric return; 925*04eeddc0SDimitry Andric auto *c = reinterpret_cast<const symtab_command *>(cmd); 926*04eeddc0SDimitry Andric ArrayRef<NList> nList(reinterpret_cast<const NList *>(buf + c->symoff), 927*04eeddc0SDimitry Andric c->nsyms); 928*04eeddc0SDimitry Andric const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff; 929*04eeddc0SDimitry Andric symbols.resize(nList.size()); 930*04eeddc0SDimitry Andric for (auto it : llvm::enumerate(nList)) { 931*04eeddc0SDimitry Andric const NList &sym = it.value(); 932*04eeddc0SDimitry Andric if ((sym.n_type & N_EXT) && !isUndef(sym)) { 933*04eeddc0SDimitry Andric // TODO: Bound checking 934*04eeddc0SDimitry Andric StringRef name = strtab + sym.n_strx; 935*04eeddc0SDimitry Andric symbols[it.index()] = symtab->addLazyObject(name, *this); 936*04eeddc0SDimitry Andric if (!lazy) 937*04eeddc0SDimitry Andric break; 938*04eeddc0SDimitry Andric } 939*04eeddc0SDimitry Andric } 940*04eeddc0SDimitry Andric } 941*04eeddc0SDimitry Andric 942e8d8bef9SDimitry Andric void ObjFile::parseDebugInfo() { 943e8d8bef9SDimitry Andric std::unique_ptr<DwarfObject> dObj = DwarfObject::create(this); 944e8d8bef9SDimitry Andric if (!dObj) 945e8d8bef9SDimitry Andric return; 946e8d8bef9SDimitry Andric 947e8d8bef9SDimitry Andric auto *ctx = make<DWARFContext>( 948e8d8bef9SDimitry Andric std::move(dObj), "", 949e8d8bef9SDimitry Andric [&](Error err) { 950e8d8bef9SDimitry Andric warn(toString(this) + ": " + toString(std::move(err))); 951e8d8bef9SDimitry Andric }, 952e8d8bef9SDimitry Andric [&](Error warning) { 953e8d8bef9SDimitry Andric warn(toString(this) + ": " + toString(std::move(warning))); 954e8d8bef9SDimitry Andric }); 955e8d8bef9SDimitry Andric 956e8d8bef9SDimitry Andric // TODO: Since object files can contain a lot of DWARF info, we should verify 957e8d8bef9SDimitry Andric // that we are parsing just the info we need 958e8d8bef9SDimitry Andric const DWARFContext::compile_unit_range &units = ctx->compile_units(); 959fe6060f1SDimitry Andric // FIXME: There can be more than one compile unit per object file. See 960fe6060f1SDimitry Andric // PR48637. 961e8d8bef9SDimitry Andric auto it = units.begin(); 962e8d8bef9SDimitry Andric compileUnit = it->get(); 963fe6060f1SDimitry Andric } 964fe6060f1SDimitry Andric 9650eae32dcSDimitry Andric ArrayRef<data_in_code_entry> ObjFile::getDataInCode() const { 966fe6060f1SDimitry Andric const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 967fe6060f1SDimitry Andric const load_command *cmd = findCommand(buf, LC_DATA_IN_CODE); 968fe6060f1SDimitry Andric if (!cmd) 9690eae32dcSDimitry Andric return {}; 970fe6060f1SDimitry Andric const auto *c = reinterpret_cast<const linkedit_data_command *>(cmd); 9710eae32dcSDimitry Andric return {reinterpret_cast<const data_in_code_entry *>(buf + c->dataoff), 972fe6060f1SDimitry Andric c->datasize / sizeof(data_in_code_entry)}; 973e8d8bef9SDimitry Andric } 974e8d8bef9SDimitry Andric 975349cc55cSDimitry Andric // Create pointers from symbols to their associated compact unwind entries. 976349cc55cSDimitry Andric void ObjFile::registerCompactUnwind() { 977349cc55cSDimitry Andric for (const Subsection &subsection : compactUnwindSection->subsections) { 978349cc55cSDimitry Andric ConcatInputSection *isec = cast<ConcatInputSection>(subsection.isec); 979349cc55cSDimitry Andric // Hack!! Since each CUE contains a different function address, if ICF 980349cc55cSDimitry Andric // operated naively and compared the entire contents of each CUE, entries 981349cc55cSDimitry Andric // with identical unwind info but belonging to different functions would 982349cc55cSDimitry Andric // never be considered equivalent. To work around this problem, we slice 983349cc55cSDimitry Andric // away the function address here. (Note that we do not adjust the offsets 984349cc55cSDimitry Andric // of the corresponding relocations.) We rely on `relocateCompactUnwind()` 985349cc55cSDimitry Andric // to correctly handle these truncated input sections. 986349cc55cSDimitry Andric isec->data = isec->data.slice(target->wordSize); 987349cc55cSDimitry Andric 988349cc55cSDimitry Andric ConcatInputSection *referentIsec; 989349cc55cSDimitry Andric for (auto it = isec->relocs.begin(); it != isec->relocs.end();) { 990349cc55cSDimitry Andric Reloc &r = *it; 991349cc55cSDimitry Andric // CUE::functionAddress is at offset 0. Skip personality & LSDA relocs. 992349cc55cSDimitry Andric if (r.offset != 0) { 993349cc55cSDimitry Andric ++it; 994349cc55cSDimitry Andric continue; 995349cc55cSDimitry Andric } 996349cc55cSDimitry Andric uint64_t add = r.addend; 997349cc55cSDimitry Andric if (auto *sym = cast_or_null<Defined>(r.referent.dyn_cast<Symbol *>())) { 998349cc55cSDimitry Andric // Check whether the symbol defined in this file is the prevailing one. 999349cc55cSDimitry Andric // Skip if it is e.g. a weak def that didn't prevail. 1000349cc55cSDimitry Andric if (sym->getFile() != this) { 1001349cc55cSDimitry Andric ++it; 1002349cc55cSDimitry Andric continue; 1003349cc55cSDimitry Andric } 1004349cc55cSDimitry Andric add += sym->value; 1005349cc55cSDimitry Andric referentIsec = cast<ConcatInputSection>(sym->isec); 1006349cc55cSDimitry Andric } else { 1007349cc55cSDimitry Andric referentIsec = 1008349cc55cSDimitry Andric cast<ConcatInputSection>(r.referent.dyn_cast<InputSection *>()); 1009349cc55cSDimitry Andric } 1010349cc55cSDimitry Andric if (referentIsec->getSegName() != segment_names::text) 1011349cc55cSDimitry Andric error("compact unwind references address in " + toString(referentIsec) + 1012349cc55cSDimitry Andric " which is not in segment __TEXT"); 1013349cc55cSDimitry Andric // The functionAddress relocations are typically section relocations. 1014349cc55cSDimitry Andric // However, unwind info operates on a per-symbol basis, so we search for 1015349cc55cSDimitry Andric // the function symbol here. 1016349cc55cSDimitry Andric auto symIt = llvm::lower_bound( 1017349cc55cSDimitry Andric referentIsec->symbols, add, 1018349cc55cSDimitry Andric [](Defined *d, uint64_t add) { return d->value < add; }); 1019349cc55cSDimitry Andric // The relocation should point at the exact address of a symbol (with no 1020349cc55cSDimitry Andric // addend). 1021349cc55cSDimitry Andric if (symIt == referentIsec->symbols.end() || (*symIt)->value != add) { 1022349cc55cSDimitry Andric assert(referentIsec->wasCoalesced); 1023349cc55cSDimitry Andric ++it; 1024349cc55cSDimitry Andric continue; 1025349cc55cSDimitry Andric } 1026349cc55cSDimitry Andric (*symIt)->unwindEntry = isec; 1027349cc55cSDimitry Andric // Since we've sliced away the functionAddress, we should remove the 1028349cc55cSDimitry Andric // corresponding relocation too. Given that clang emits relocations in 1029349cc55cSDimitry Andric // reverse order of address, this relocation should be at the end of the 1030349cc55cSDimitry Andric // vector for most of our input object files, so this is typically an O(1) 1031349cc55cSDimitry Andric // operation. 1032349cc55cSDimitry Andric it = isec->relocs.erase(it); 1033349cc55cSDimitry Andric } 1034349cc55cSDimitry Andric } 1035349cc55cSDimitry Andric } 1036349cc55cSDimitry Andric 1037e8d8bef9SDimitry Andric // The path can point to either a dylib or a .tbd file. 1038fe6060f1SDimitry Andric static DylibFile *loadDylib(StringRef path, DylibFile *umbrella) { 1039e8d8bef9SDimitry Andric Optional<MemoryBufferRef> mbref = readFile(path); 1040e8d8bef9SDimitry Andric if (!mbref) { 1041e8d8bef9SDimitry Andric error("could not read dylib file at " + path); 1042fe6060f1SDimitry Andric return nullptr; 1043e8d8bef9SDimitry Andric } 1044e8d8bef9SDimitry Andric return loadDylib(*mbref, umbrella); 1045e8d8bef9SDimitry Andric } 1046e8d8bef9SDimitry Andric 1047e8d8bef9SDimitry Andric // TBD files are parsed into a series of TAPI documents (InterfaceFiles), with 1048e8d8bef9SDimitry Andric // the first document storing child pointers to the rest of them. When we are 1049fe6060f1SDimitry Andric // processing a given TBD file, we store that top-level document in 1050fe6060f1SDimitry Andric // currentTopLevelTapi. When processing re-exports, we search its children for 1051fe6060f1SDimitry Andric // potentially matching documents in the same TBD file. Note that the children 1052fe6060f1SDimitry Andric // themselves don't point to further documents, i.e. this is a two-level tree. 1053e8d8bef9SDimitry Andric // 1054e8d8bef9SDimitry Andric // Re-exports can either refer to on-disk files, or to documents within .tbd 1055e8d8bef9SDimitry Andric // files. 1056fe6060f1SDimitry Andric static DylibFile *findDylib(StringRef path, DylibFile *umbrella, 1057fe6060f1SDimitry Andric const InterfaceFile *currentTopLevelTapi) { 1058fe6060f1SDimitry Andric // Search order: 1059fe6060f1SDimitry Andric // 1. Install name basename in -F / -L directories. 1060fe6060f1SDimitry Andric { 1061fe6060f1SDimitry Andric StringRef stem = path::stem(path); 1062fe6060f1SDimitry Andric SmallString<128> frameworkName; 1063fe6060f1SDimitry Andric path::append(frameworkName, path::Style::posix, stem + ".framework", stem); 1064fe6060f1SDimitry Andric bool isFramework = path.endswith(frameworkName); 1065fe6060f1SDimitry Andric if (isFramework) { 1066fe6060f1SDimitry Andric for (StringRef dir : config->frameworkSearchPaths) { 1067fe6060f1SDimitry Andric SmallString<128> candidate = dir; 1068fe6060f1SDimitry Andric path::append(candidate, frameworkName); 1069349cc55cSDimitry Andric if (Optional<StringRef> dylibPath = resolveDylibPath(candidate.str())) 1070fe6060f1SDimitry Andric return loadDylib(*dylibPath, umbrella); 1071fe6060f1SDimitry Andric } 1072fe6060f1SDimitry Andric } else if (Optional<StringRef> dylibPath = findPathCombination( 1073fe6060f1SDimitry Andric stem, config->librarySearchPaths, {".tbd", ".dylib"})) 1074fe6060f1SDimitry Andric return loadDylib(*dylibPath, umbrella); 1075fe6060f1SDimitry Andric } 1076fe6060f1SDimitry Andric 1077fe6060f1SDimitry Andric // 2. As absolute path. 1078e8d8bef9SDimitry Andric if (path::is_absolute(path, path::Style::posix)) 1079e8d8bef9SDimitry Andric for (StringRef root : config->systemLibraryRoots) 1080349cc55cSDimitry Andric if (Optional<StringRef> dylibPath = resolveDylibPath((root + path).str())) 1081e8d8bef9SDimitry Andric return loadDylib(*dylibPath, umbrella); 1082e8d8bef9SDimitry Andric 1083fe6060f1SDimitry Andric // 3. As relative path. 1084e8d8bef9SDimitry Andric 1085fe6060f1SDimitry Andric // TODO: Handle -dylib_file 1086fe6060f1SDimitry Andric 1087fe6060f1SDimitry Andric // Replace @executable_path, @loader_path, @rpath prefixes in install name. 1088fe6060f1SDimitry Andric SmallString<128> newPath; 1089fe6060f1SDimitry Andric if (config->outputType == MH_EXECUTE && 1090fe6060f1SDimitry Andric path.consume_front("@executable_path/")) { 1091fe6060f1SDimitry Andric // ld64 allows overriding this with the undocumented flag -executable_path. 1092fe6060f1SDimitry Andric // lld doesn't currently implement that flag. 1093fe6060f1SDimitry Andric // FIXME: Consider using finalOutput instead of outputFile. 1094fe6060f1SDimitry Andric path::append(newPath, path::parent_path(config->outputFile), path); 1095fe6060f1SDimitry Andric path = newPath; 1096fe6060f1SDimitry Andric } else if (path.consume_front("@loader_path/")) { 1097fe6060f1SDimitry Andric fs::real_path(umbrella->getName(), newPath); 1098fe6060f1SDimitry Andric path::remove_filename(newPath); 1099fe6060f1SDimitry Andric path::append(newPath, path); 1100fe6060f1SDimitry Andric path = newPath; 1101fe6060f1SDimitry Andric } else if (path.startswith("@rpath/")) { 1102fe6060f1SDimitry Andric for (StringRef rpath : umbrella->rpaths) { 1103fe6060f1SDimitry Andric newPath.clear(); 1104fe6060f1SDimitry Andric if (rpath.consume_front("@loader_path/")) { 1105fe6060f1SDimitry Andric fs::real_path(umbrella->getName(), newPath); 1106fe6060f1SDimitry Andric path::remove_filename(newPath); 1107fe6060f1SDimitry Andric } 1108fe6060f1SDimitry Andric path::append(newPath, rpath, path.drop_front(strlen("@rpath/"))); 1109349cc55cSDimitry Andric if (Optional<StringRef> dylibPath = resolveDylibPath(newPath.str())) 1110fe6060f1SDimitry Andric return loadDylib(*dylibPath, umbrella); 1111fe6060f1SDimitry Andric } 1112fe6060f1SDimitry Andric } 1113fe6060f1SDimitry Andric 1114fe6060f1SDimitry Andric // FIXME: Should this be further up? 1115e8d8bef9SDimitry Andric if (currentTopLevelTapi) { 1116e8d8bef9SDimitry Andric for (InterfaceFile &child : 1117e8d8bef9SDimitry Andric make_pointee_range(currentTopLevelTapi->documents())) { 1118e8d8bef9SDimitry Andric assert(child.documents().empty()); 1119fe6060f1SDimitry Andric if (path == child.getInstallName()) { 1120fe6060f1SDimitry Andric auto file = make<DylibFile>(child, umbrella); 1121fe6060f1SDimitry Andric file->parseReexports(child); 1122fe6060f1SDimitry Andric return file; 1123fe6060f1SDimitry Andric } 1124e8d8bef9SDimitry Andric } 1125e8d8bef9SDimitry Andric } 1126e8d8bef9SDimitry Andric 1127349cc55cSDimitry Andric if (Optional<StringRef> dylibPath = resolveDylibPath(path)) 1128e8d8bef9SDimitry Andric return loadDylib(*dylibPath, umbrella); 1129e8d8bef9SDimitry Andric 1130fe6060f1SDimitry Andric return nullptr; 1131e8d8bef9SDimitry Andric } 1132e8d8bef9SDimitry Andric 1133e8d8bef9SDimitry Andric // If a re-exported dylib is public (lives in /usr/lib or 1134e8d8bef9SDimitry Andric // /System/Library/Frameworks), then it is considered implicitly linked: we 1135e8d8bef9SDimitry Andric // should bind to its symbols directly instead of via the re-exporting umbrella 1136e8d8bef9SDimitry Andric // library. 1137e8d8bef9SDimitry Andric static bool isImplicitlyLinked(StringRef path) { 1138e8d8bef9SDimitry Andric if (!config->implicitDylibs) 1139e8d8bef9SDimitry Andric return false; 1140e8d8bef9SDimitry Andric 1141e8d8bef9SDimitry Andric if (path::parent_path(path) == "/usr/lib") 1142e8d8bef9SDimitry Andric return true; 1143e8d8bef9SDimitry Andric 1144e8d8bef9SDimitry Andric // Match /System/Library/Frameworks/$FOO.framework/**/$FOO 1145e8d8bef9SDimitry Andric if (path.consume_front("/System/Library/Frameworks/")) { 1146e8d8bef9SDimitry Andric StringRef frameworkName = path.take_until([](char c) { return c == '.'; }); 1147e8d8bef9SDimitry Andric return path::filename(path) == frameworkName; 1148e8d8bef9SDimitry Andric } 1149e8d8bef9SDimitry Andric 1150e8d8bef9SDimitry Andric return false; 1151e8d8bef9SDimitry Andric } 1152e8d8bef9SDimitry Andric 1153fe6060f1SDimitry Andric static void loadReexport(StringRef path, DylibFile *umbrella, 1154fe6060f1SDimitry Andric const InterfaceFile *currentTopLevelTapi) { 1155fe6060f1SDimitry Andric DylibFile *reexport = findDylib(path, umbrella, currentTopLevelTapi); 1156fe6060f1SDimitry Andric if (!reexport) 1157fe6060f1SDimitry Andric error("unable to locate re-export with install name " + path); 11585ffd83dbSDimitry Andric } 11595ffd83dbSDimitry Andric 1160fe6060f1SDimitry Andric DylibFile::DylibFile(MemoryBufferRef mb, DylibFile *umbrella, 1161fe6060f1SDimitry Andric bool isBundleLoader) 1162fe6060f1SDimitry Andric : InputFile(DylibKind, mb), refState(RefState::Unreferenced), 1163fe6060f1SDimitry Andric isBundleLoader(isBundleLoader) { 1164fe6060f1SDimitry Andric assert(!isBundleLoader || !umbrella); 11655ffd83dbSDimitry Andric if (umbrella == nullptr) 11665ffd83dbSDimitry Andric umbrella = this; 1167fe6060f1SDimitry Andric this->umbrella = umbrella; 11685ffd83dbSDimitry Andric 11695ffd83dbSDimitry Andric auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 1170fe6060f1SDimitry Andric auto *hdr = reinterpret_cast<const mach_header *>(mb.getBufferStart()); 11715ffd83dbSDimitry Andric 1172fe6060f1SDimitry Andric // Initialize installName. 11735ffd83dbSDimitry Andric if (const load_command *cmd = findCommand(hdr, LC_ID_DYLIB)) { 11745ffd83dbSDimitry Andric auto *c = reinterpret_cast<const dylib_command *>(cmd); 1175e8d8bef9SDimitry Andric currentVersion = read32le(&c->dylib.current_version); 1176e8d8bef9SDimitry Andric compatibilityVersion = read32le(&c->dylib.compatibility_version); 1177fe6060f1SDimitry Andric installName = 1178fe6060f1SDimitry Andric reinterpret_cast<const char *>(cmd) + read32le(&c->dylib.name); 1179fe6060f1SDimitry Andric } else if (!isBundleLoader) { 1180fe6060f1SDimitry Andric // macho_executable and macho_bundle don't have LC_ID_DYLIB, 1181fe6060f1SDimitry Andric // so it's OK. 1182e8d8bef9SDimitry Andric error("dylib " + toString(this) + " missing LC_ID_DYLIB load command"); 11835ffd83dbSDimitry Andric return; 11845ffd83dbSDimitry Andric } 11855ffd83dbSDimitry Andric 1186fe6060f1SDimitry Andric if (config->printEachFile) 1187fe6060f1SDimitry Andric message(toString(this)); 1188fe6060f1SDimitry Andric inputFiles.insert(this); 1189fe6060f1SDimitry Andric 1190fe6060f1SDimitry Andric deadStrippable = hdr->flags & MH_DEAD_STRIPPABLE_DYLIB; 1191fe6060f1SDimitry Andric 1192fe6060f1SDimitry Andric if (!checkCompatibility(this)) 1193fe6060f1SDimitry Andric return; 1194fe6060f1SDimitry Andric 1195fe6060f1SDimitry Andric checkAppExtensionSafety(hdr->flags & MH_APP_EXTENSION_SAFE); 1196fe6060f1SDimitry Andric 1197fe6060f1SDimitry Andric for (auto *cmd : findCommands<rpath_command>(hdr, LC_RPATH)) { 1198fe6060f1SDimitry Andric StringRef rpath{reinterpret_cast<const char *>(cmd) + cmd->path}; 1199fe6060f1SDimitry Andric rpaths.push_back(rpath); 1200fe6060f1SDimitry Andric } 1201fe6060f1SDimitry Andric 12025ffd83dbSDimitry Andric // Initialize symbols. 1203fe6060f1SDimitry Andric exportingFile = isImplicitlyLinked(installName) ? this : this->umbrella; 12045ffd83dbSDimitry Andric if (const load_command *cmd = findCommand(hdr, LC_DYLD_INFO_ONLY)) { 12055ffd83dbSDimitry Andric auto *c = reinterpret_cast<const dyld_info_command *>(cmd); 12060eae32dcSDimitry Andric struct TrieEntry { 12070eae32dcSDimitry Andric StringRef name; 12080eae32dcSDimitry Andric uint64_t flags; 12090eae32dcSDimitry Andric }; 12100eae32dcSDimitry Andric 12110eae32dcSDimitry Andric std::vector<TrieEntry> entries; 12120eae32dcSDimitry Andric // Find all the $ld$* symbols to process first. 12135ffd83dbSDimitry Andric parseTrie(buf + c->export_off, c->export_size, 12145ffd83dbSDimitry Andric [&](const Twine &name, uint64_t flags) { 1215*04eeddc0SDimitry Andric StringRef savedName = saver().save(name); 1216fe6060f1SDimitry Andric if (handleLDSymbol(savedName)) 1217fe6060f1SDimitry Andric return; 12180eae32dcSDimitry Andric entries.push_back({savedName, flags}); 12195ffd83dbSDimitry Andric }); 12200eae32dcSDimitry Andric 12210eae32dcSDimitry Andric // Process the "normal" symbols. 12220eae32dcSDimitry Andric for (TrieEntry &entry : entries) { 12230eae32dcSDimitry Andric if (exportingFile->hiddenSymbols.contains( 12240eae32dcSDimitry Andric CachedHashStringRef(entry.name))) 12250eae32dcSDimitry Andric continue; 12260eae32dcSDimitry Andric 12270eae32dcSDimitry Andric bool isWeakDef = entry.flags & EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION; 12280eae32dcSDimitry Andric bool isTlv = entry.flags & EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL; 12290eae32dcSDimitry Andric 12300eae32dcSDimitry Andric symbols.push_back( 12310eae32dcSDimitry Andric symtab->addDylib(entry.name, exportingFile, isWeakDef, isTlv)); 12320eae32dcSDimitry Andric } 12330eae32dcSDimitry Andric 12345ffd83dbSDimitry Andric } else { 1235e8d8bef9SDimitry Andric error("LC_DYLD_INFO_ONLY not found in " + toString(this)); 12365ffd83dbSDimitry Andric return; 12375ffd83dbSDimitry Andric } 1238fe6060f1SDimitry Andric } 12395ffd83dbSDimitry Andric 1240fe6060f1SDimitry Andric void DylibFile::parseLoadCommands(MemoryBufferRef mb) { 1241fe6060f1SDimitry Andric auto *hdr = reinterpret_cast<const mach_header *>(mb.getBufferStart()); 1242fe6060f1SDimitry Andric const uint8_t *p = reinterpret_cast<const uint8_t *>(mb.getBufferStart()) + 1243fe6060f1SDimitry Andric target->headerSize; 12445ffd83dbSDimitry Andric for (uint32_t i = 0, n = hdr->ncmds; i < n; ++i) { 12455ffd83dbSDimitry Andric auto *cmd = reinterpret_cast<const load_command *>(p); 12465ffd83dbSDimitry Andric p += cmd->cmdsize; 12475ffd83dbSDimitry Andric 1248fe6060f1SDimitry Andric if (!(hdr->flags & MH_NO_REEXPORTED_DYLIBS) && 1249fe6060f1SDimitry Andric cmd->cmd == LC_REEXPORT_DYLIB) { 1250fe6060f1SDimitry Andric const auto *c = reinterpret_cast<const dylib_command *>(cmd); 12515ffd83dbSDimitry Andric StringRef reexportPath = 12525ffd83dbSDimitry Andric reinterpret_cast<const char *>(c) + read32le(&c->dylib.name); 1253fe6060f1SDimitry Andric loadReexport(reexportPath, exportingFile, nullptr); 1254fe6060f1SDimitry Andric } 1255fe6060f1SDimitry Andric 1256fe6060f1SDimitry Andric // FIXME: What about LC_LOAD_UPWARD_DYLIB, LC_LAZY_LOAD_DYLIB, 1257fe6060f1SDimitry Andric // LC_LOAD_WEAK_DYLIB, LC_REEXPORT_DYLIB (..are reexports from dylibs with 1258fe6060f1SDimitry Andric // MH_NO_REEXPORTED_DYLIBS loaded for -flat_namespace)? 1259fe6060f1SDimitry Andric if (config->namespaceKind == NamespaceKind::flat && 1260fe6060f1SDimitry Andric cmd->cmd == LC_LOAD_DYLIB) { 1261fe6060f1SDimitry Andric const auto *c = reinterpret_cast<const dylib_command *>(cmd); 1262fe6060f1SDimitry Andric StringRef dylibPath = 1263fe6060f1SDimitry Andric reinterpret_cast<const char *>(c) + read32le(&c->dylib.name); 1264fe6060f1SDimitry Andric DylibFile *dylib = findDylib(dylibPath, umbrella, nullptr); 1265fe6060f1SDimitry Andric if (!dylib) 1266fe6060f1SDimitry Andric error(Twine("unable to locate library '") + dylibPath + 1267fe6060f1SDimitry Andric "' loaded from '" + toString(this) + "' for -flat_namespace"); 1268fe6060f1SDimitry Andric } 12695ffd83dbSDimitry Andric } 12705ffd83dbSDimitry Andric } 12715ffd83dbSDimitry Andric 1272fe6060f1SDimitry Andric // Some versions of XCode ship with .tbd files that don't have the right 1273fe6060f1SDimitry Andric // platform settings. 1274fe6060f1SDimitry Andric static constexpr std::array<StringRef, 3> skipPlatformChecks{ 1275fe6060f1SDimitry Andric "/usr/lib/system/libsystem_kernel.dylib", 1276fe6060f1SDimitry Andric "/usr/lib/system/libsystem_platform.dylib", 1277fe6060f1SDimitry Andric "/usr/lib/system/libsystem_pthread.dylib"}; 1278fe6060f1SDimitry Andric 1279fe6060f1SDimitry Andric DylibFile::DylibFile(const InterfaceFile &interface, DylibFile *umbrella, 1280fe6060f1SDimitry Andric bool isBundleLoader) 1281fe6060f1SDimitry Andric : InputFile(DylibKind, interface), refState(RefState::Unreferenced), 1282fe6060f1SDimitry Andric isBundleLoader(isBundleLoader) { 1283fe6060f1SDimitry Andric // FIXME: Add test for the missing TBD code path. 1284fe6060f1SDimitry Andric 12855ffd83dbSDimitry Andric if (umbrella == nullptr) 12865ffd83dbSDimitry Andric umbrella = this; 1287fe6060f1SDimitry Andric this->umbrella = umbrella; 12885ffd83dbSDimitry Andric 1289*04eeddc0SDimitry Andric installName = saver().save(interface.getInstallName()); 1290e8d8bef9SDimitry Andric compatibilityVersion = interface.getCompatibilityVersion().rawValue(); 1291e8d8bef9SDimitry Andric currentVersion = interface.getCurrentVersion().rawValue(); 1292fe6060f1SDimitry Andric 1293fe6060f1SDimitry Andric if (config->printEachFile) 1294fe6060f1SDimitry Andric message(toString(this)); 1295fe6060f1SDimitry Andric inputFiles.insert(this); 1296fe6060f1SDimitry Andric 1297fe6060f1SDimitry Andric if (!is_contained(skipPlatformChecks, installName) && 1298fe6060f1SDimitry Andric !is_contained(interface.targets(), config->platformInfo.target)) { 1299fe6060f1SDimitry Andric error(toString(this) + " is incompatible with " + 1300fe6060f1SDimitry Andric std::string(config->platformInfo.target)); 1301fe6060f1SDimitry Andric return; 1302fe6060f1SDimitry Andric } 1303fe6060f1SDimitry Andric 1304fe6060f1SDimitry Andric checkAppExtensionSafety(interface.isApplicationExtensionSafe()); 1305fe6060f1SDimitry Andric 1306fe6060f1SDimitry Andric exportingFile = isImplicitlyLinked(installName) ? this : umbrella; 1307e8d8bef9SDimitry Andric auto addSymbol = [&](const Twine &name) -> void { 1308*04eeddc0SDimitry Andric StringRef savedName = saver().save(name); 13090eae32dcSDimitry Andric if (exportingFile->hiddenSymbols.contains(CachedHashStringRef(savedName))) 13100eae32dcSDimitry Andric return; 13110eae32dcSDimitry Andric 13120eae32dcSDimitry Andric symbols.push_back(symtab->addDylib(savedName, exportingFile, 1313e8d8bef9SDimitry Andric /*isWeakDef=*/false, 1314e8d8bef9SDimitry Andric /*isTlv=*/false)); 1315e8d8bef9SDimitry Andric }; 13160eae32dcSDimitry Andric 13170eae32dcSDimitry Andric std::vector<const llvm::MachO::Symbol *> normalSymbols; 13180eae32dcSDimitry Andric normalSymbols.reserve(interface.symbolsCount()); 1319fe6060f1SDimitry Andric for (const auto *symbol : interface.symbols()) { 1320fe6060f1SDimitry Andric if (!symbol->getArchitectures().has(config->arch())) 1321fe6060f1SDimitry Andric continue; 1322fe6060f1SDimitry Andric if (handleLDSymbol(symbol->getName())) 1323e8d8bef9SDimitry Andric continue; 1324e8d8bef9SDimitry Andric 1325e8d8bef9SDimitry Andric switch (symbol->getKind()) { 13260eae32dcSDimitry Andric case SymbolKind::GlobalSymbol: // Fallthrough 13270eae32dcSDimitry Andric case SymbolKind::ObjectiveCClass: // Fallthrough 13280eae32dcSDimitry Andric case SymbolKind::ObjectiveCClassEHType: // Fallthrough 13290eae32dcSDimitry Andric case SymbolKind::ObjectiveCInstanceVariable: // Fallthrough 13300eae32dcSDimitry Andric normalSymbols.push_back(symbol); 13310eae32dcSDimitry Andric } 13320eae32dcSDimitry Andric } 13330eae32dcSDimitry Andric 13340eae32dcSDimitry Andric // TODO(compnerd) filter out symbols based on the target platform 13350eae32dcSDimitry Andric // TODO: handle weak defs, thread locals 13360eae32dcSDimitry Andric for (const auto *symbol : normalSymbols) { 13370eae32dcSDimitry Andric switch (symbol->getKind()) { 1338e8d8bef9SDimitry Andric case SymbolKind::GlobalSymbol: 1339e8d8bef9SDimitry Andric addSymbol(symbol->getName()); 1340e8d8bef9SDimitry Andric break; 1341e8d8bef9SDimitry Andric case SymbolKind::ObjectiveCClass: 1342e8d8bef9SDimitry Andric // XXX ld64 only creates these symbols when -ObjC is passed in. We may 1343e8d8bef9SDimitry Andric // want to emulate that. 1344e8d8bef9SDimitry Andric addSymbol(objc::klass + symbol->getName()); 1345e8d8bef9SDimitry Andric addSymbol(objc::metaclass + symbol->getName()); 1346e8d8bef9SDimitry Andric break; 1347e8d8bef9SDimitry Andric case SymbolKind::ObjectiveCClassEHType: 1348e8d8bef9SDimitry Andric addSymbol(objc::ehtype + symbol->getName()); 1349e8d8bef9SDimitry Andric break; 1350e8d8bef9SDimitry Andric case SymbolKind::ObjectiveCInstanceVariable: 1351e8d8bef9SDimitry Andric addSymbol(objc::ivar + symbol->getName()); 1352e8d8bef9SDimitry Andric break; 1353e8d8bef9SDimitry Andric } 13545ffd83dbSDimitry Andric } 1355e8d8bef9SDimitry Andric } 1356e8d8bef9SDimitry Andric 1357fe6060f1SDimitry Andric void DylibFile::parseReexports(const InterfaceFile &interface) { 1358fe6060f1SDimitry Andric const InterfaceFile *topLevel = 1359fe6060f1SDimitry Andric interface.getParent() == nullptr ? &interface : interface.getParent(); 1360349cc55cSDimitry Andric for (const InterfaceFileRef &intfRef : interface.reexportedLibraries()) { 1361fe6060f1SDimitry Andric InterfaceFile::const_target_range targets = intfRef.targets(); 1362fe6060f1SDimitry Andric if (is_contained(skipPlatformChecks, intfRef.getInstallName()) || 1363fe6060f1SDimitry Andric is_contained(targets, config->platformInfo.target)) 1364fe6060f1SDimitry Andric loadReexport(intfRef.getInstallName(), exportingFile, topLevel); 1365fe6060f1SDimitry Andric } 1366fe6060f1SDimitry Andric } 1367e8d8bef9SDimitry Andric 1368fe6060f1SDimitry Andric // $ld$ symbols modify the properties/behavior of the library (e.g. its install 1369fe6060f1SDimitry Andric // name, compatibility version or hide/add symbols) for specific target 1370fe6060f1SDimitry Andric // versions. 1371fe6060f1SDimitry Andric bool DylibFile::handleLDSymbol(StringRef originalName) { 1372fe6060f1SDimitry Andric if (!originalName.startswith("$ld$")) 1373fe6060f1SDimitry Andric return false; 1374fe6060f1SDimitry Andric 1375fe6060f1SDimitry Andric StringRef action; 1376fe6060f1SDimitry Andric StringRef name; 1377fe6060f1SDimitry Andric std::tie(action, name) = originalName.drop_front(strlen("$ld$")).split('$'); 1378fe6060f1SDimitry Andric if (action == "previous") 1379fe6060f1SDimitry Andric handleLDPreviousSymbol(name, originalName); 1380fe6060f1SDimitry Andric else if (action == "install_name") 1381fe6060f1SDimitry Andric handleLDInstallNameSymbol(name, originalName); 13820eae32dcSDimitry Andric else if (action == "hide") 13830eae32dcSDimitry Andric handleLDHideSymbol(name, originalName); 1384fe6060f1SDimitry Andric return true; 1385fe6060f1SDimitry Andric } 1386fe6060f1SDimitry Andric 1387fe6060f1SDimitry Andric void DylibFile::handleLDPreviousSymbol(StringRef name, StringRef originalName) { 1388fe6060f1SDimitry Andric // originalName: $ld$ previous $ <installname> $ <compatversion> $ 1389fe6060f1SDimitry Andric // <platformstr> $ <startversion> $ <endversion> $ <symbol-name> $ 1390fe6060f1SDimitry Andric StringRef installName; 1391fe6060f1SDimitry Andric StringRef compatVersion; 1392fe6060f1SDimitry Andric StringRef platformStr; 1393fe6060f1SDimitry Andric StringRef startVersion; 1394fe6060f1SDimitry Andric StringRef endVersion; 1395fe6060f1SDimitry Andric StringRef symbolName; 1396fe6060f1SDimitry Andric StringRef rest; 1397fe6060f1SDimitry Andric 1398fe6060f1SDimitry Andric std::tie(installName, name) = name.split('$'); 1399fe6060f1SDimitry Andric std::tie(compatVersion, name) = name.split('$'); 1400fe6060f1SDimitry Andric std::tie(platformStr, name) = name.split('$'); 1401fe6060f1SDimitry Andric std::tie(startVersion, name) = name.split('$'); 1402fe6060f1SDimitry Andric std::tie(endVersion, name) = name.split('$'); 1403fe6060f1SDimitry Andric std::tie(symbolName, rest) = name.split('$'); 1404fe6060f1SDimitry Andric // TODO: ld64 contains some logic for non-empty symbolName as well. 1405fe6060f1SDimitry Andric if (!symbolName.empty()) 1406fe6060f1SDimitry Andric return; 1407fe6060f1SDimitry Andric unsigned platform; 1408fe6060f1SDimitry Andric if (platformStr.getAsInteger(10, platform) || 1409fe6060f1SDimitry Andric platform != static_cast<unsigned>(config->platform())) 1410fe6060f1SDimitry Andric return; 1411fe6060f1SDimitry Andric 1412fe6060f1SDimitry Andric VersionTuple start; 1413fe6060f1SDimitry Andric if (start.tryParse(startVersion)) { 1414fe6060f1SDimitry Andric warn("failed to parse start version, symbol '" + originalName + 1415fe6060f1SDimitry Andric "' ignored"); 1416fe6060f1SDimitry Andric return; 1417fe6060f1SDimitry Andric } 1418fe6060f1SDimitry Andric VersionTuple end; 1419fe6060f1SDimitry Andric if (end.tryParse(endVersion)) { 1420fe6060f1SDimitry Andric warn("failed to parse end version, symbol '" + originalName + "' ignored"); 1421fe6060f1SDimitry Andric return; 1422fe6060f1SDimitry Andric } 1423fe6060f1SDimitry Andric if (config->platformInfo.minimum < start || 1424fe6060f1SDimitry Andric config->platformInfo.minimum >= end) 1425fe6060f1SDimitry Andric return; 1426fe6060f1SDimitry Andric 1427*04eeddc0SDimitry Andric this->installName = saver().save(installName); 1428fe6060f1SDimitry Andric 1429fe6060f1SDimitry Andric if (!compatVersion.empty()) { 1430fe6060f1SDimitry Andric VersionTuple cVersion; 1431fe6060f1SDimitry Andric if (cVersion.tryParse(compatVersion)) { 1432fe6060f1SDimitry Andric warn("failed to parse compatibility version, symbol '" + originalName + 1433fe6060f1SDimitry Andric "' ignored"); 1434fe6060f1SDimitry Andric return; 1435fe6060f1SDimitry Andric } 1436fe6060f1SDimitry Andric compatibilityVersion = encodeVersion(cVersion); 1437fe6060f1SDimitry Andric } 1438fe6060f1SDimitry Andric } 1439fe6060f1SDimitry Andric 1440fe6060f1SDimitry Andric void DylibFile::handleLDInstallNameSymbol(StringRef name, 1441fe6060f1SDimitry Andric StringRef originalName) { 1442fe6060f1SDimitry Andric // originalName: $ld$ install_name $ os<version> $ install_name 1443fe6060f1SDimitry Andric StringRef condition, installName; 1444fe6060f1SDimitry Andric std::tie(condition, installName) = name.split('$'); 1445fe6060f1SDimitry Andric VersionTuple version; 1446fe6060f1SDimitry Andric if (!condition.consume_front("os") || version.tryParse(condition)) 1447fe6060f1SDimitry Andric warn("failed to parse os version, symbol '" + originalName + "' ignored"); 1448fe6060f1SDimitry Andric else if (version == config->platformInfo.minimum) 1449*04eeddc0SDimitry Andric this->installName = saver().save(installName); 1450fe6060f1SDimitry Andric } 1451fe6060f1SDimitry Andric 14520eae32dcSDimitry Andric void DylibFile::handleLDHideSymbol(StringRef name, StringRef originalName) { 14530eae32dcSDimitry Andric StringRef symbolName; 14540eae32dcSDimitry Andric bool shouldHide = true; 14550eae32dcSDimitry Andric if (name.startswith("os")) { 14560eae32dcSDimitry Andric // If it's hidden based on versions. 14570eae32dcSDimitry Andric name = name.drop_front(2); 14580eae32dcSDimitry Andric StringRef minVersion; 14590eae32dcSDimitry Andric std::tie(minVersion, symbolName) = name.split('$'); 14600eae32dcSDimitry Andric VersionTuple versionTup; 14610eae32dcSDimitry Andric if (versionTup.tryParse(minVersion)) { 14620eae32dcSDimitry Andric warn("Failed to parse hidden version, symbol `" + originalName + 14630eae32dcSDimitry Andric "` ignored."); 14640eae32dcSDimitry Andric return; 14650eae32dcSDimitry Andric } 14660eae32dcSDimitry Andric shouldHide = versionTup == config->platformInfo.minimum; 14670eae32dcSDimitry Andric } else { 14680eae32dcSDimitry Andric symbolName = name; 14690eae32dcSDimitry Andric } 14700eae32dcSDimitry Andric 14710eae32dcSDimitry Andric if (shouldHide) 14720eae32dcSDimitry Andric exportingFile->hiddenSymbols.insert(CachedHashStringRef(symbolName)); 14730eae32dcSDimitry Andric } 14740eae32dcSDimitry Andric 1475fe6060f1SDimitry Andric void DylibFile::checkAppExtensionSafety(bool dylibIsAppExtensionSafe) const { 1476fe6060f1SDimitry Andric if (config->applicationExtension && !dylibIsAppExtensionSafe) 1477fe6060f1SDimitry Andric warn("using '-application_extension' with unsafe dylib: " + toString(this)); 1478e8d8bef9SDimitry Andric } 1479e8d8bef9SDimitry Andric 1480e8d8bef9SDimitry Andric ArchiveFile::ArchiveFile(std::unique_ptr<object::Archive> &&f) 1481349cc55cSDimitry Andric : InputFile(ArchiveKind, f->getMemoryBufferRef()), file(std::move(f)) {} 1482349cc55cSDimitry Andric 1483349cc55cSDimitry Andric void ArchiveFile::addLazySymbols() { 14845ffd83dbSDimitry Andric for (const object::Archive::Symbol &sym : file->symbols()) 1485*04eeddc0SDimitry Andric symtab->addLazyArchive(sym.getName(), this, sym); 14865ffd83dbSDimitry Andric } 14875ffd83dbSDimitry Andric 1488349cc55cSDimitry Andric static Expected<InputFile *> loadArchiveMember(MemoryBufferRef mb, 1489349cc55cSDimitry Andric uint32_t modTime, 1490349cc55cSDimitry Andric StringRef archiveName, 1491349cc55cSDimitry Andric uint64_t offsetInArchive) { 1492349cc55cSDimitry Andric if (config->zeroModTime) 1493349cc55cSDimitry Andric modTime = 0; 1494349cc55cSDimitry Andric 1495349cc55cSDimitry Andric switch (identify_magic(mb.getBuffer())) { 1496349cc55cSDimitry Andric case file_magic::macho_object: 1497349cc55cSDimitry Andric return make<ObjFile>(mb, modTime, archiveName); 1498349cc55cSDimitry Andric case file_magic::bitcode: 1499349cc55cSDimitry Andric return make<BitcodeFile>(mb, archiveName, offsetInArchive); 1500349cc55cSDimitry Andric default: 1501349cc55cSDimitry Andric return createStringError(inconvertibleErrorCode(), 1502349cc55cSDimitry Andric mb.getBufferIdentifier() + 1503349cc55cSDimitry Andric " has unhandled file type"); 1504349cc55cSDimitry Andric } 1505349cc55cSDimitry Andric } 1506349cc55cSDimitry Andric 1507349cc55cSDimitry Andric Error ArchiveFile::fetch(const object::Archive::Child &c, StringRef reason) { 1508349cc55cSDimitry Andric if (!seen.insert(c.getChildOffset()).second) 1509349cc55cSDimitry Andric return Error::success(); 1510349cc55cSDimitry Andric 1511349cc55cSDimitry Andric Expected<MemoryBufferRef> mb = c.getMemoryBufferRef(); 1512349cc55cSDimitry Andric if (!mb) 1513349cc55cSDimitry Andric return mb.takeError(); 1514349cc55cSDimitry Andric 1515349cc55cSDimitry Andric // Thin archives refer to .o files, so --reproduce needs the .o files too. 1516349cc55cSDimitry Andric if (tar && c.getParent()->isThin()) 1517349cc55cSDimitry Andric tar->append(relativeToRoot(CHECK(c.getFullName(), this)), mb->getBuffer()); 1518349cc55cSDimitry Andric 1519349cc55cSDimitry Andric Expected<TimePoint<std::chrono::seconds>> modTime = c.getLastModified(); 1520349cc55cSDimitry Andric if (!modTime) 1521349cc55cSDimitry Andric return modTime.takeError(); 1522349cc55cSDimitry Andric 1523349cc55cSDimitry Andric Expected<InputFile *> file = 1524349cc55cSDimitry Andric loadArchiveMember(*mb, toTimeT(*modTime), getName(), c.getChildOffset()); 1525349cc55cSDimitry Andric 1526349cc55cSDimitry Andric if (!file) 1527349cc55cSDimitry Andric return file.takeError(); 1528349cc55cSDimitry Andric 1529349cc55cSDimitry Andric inputFiles.insert(*file); 1530349cc55cSDimitry Andric printArchiveMemberLoad(reason, *file); 1531349cc55cSDimitry Andric return Error::success(); 1532349cc55cSDimitry Andric } 1533349cc55cSDimitry Andric 15345ffd83dbSDimitry Andric void ArchiveFile::fetch(const object::Archive::Symbol &sym) { 15355ffd83dbSDimitry Andric object::Archive::Child c = 15365ffd83dbSDimitry Andric CHECK(sym.getMember(), toString(this) + 1537349cc55cSDimitry Andric ": could not get the member defining symbol " + 1538e8d8bef9SDimitry Andric toMachOString(sym)); 15395ffd83dbSDimitry Andric 1540fe6060f1SDimitry Andric // `sym` is owned by a LazySym, which will be replace<>()d by make<ObjFile> 1541e8d8bef9SDimitry Andric // and become invalid after that call. Copy it to the stack so we can refer 1542e8d8bef9SDimitry Andric // to it later. 1543fe6060f1SDimitry Andric const object::Archive::Symbol symCopy = sym; 1544e8d8bef9SDimitry Andric 1545fe6060f1SDimitry Andric // ld64 doesn't demangle sym here even with -demangle. 1546fe6060f1SDimitry Andric // Match that: intentionally don't call toMachOString(). 1547349cc55cSDimitry Andric if (Error e = fetch(c, symCopy.getName())) 1548349cc55cSDimitry Andric error(toString(this) + ": could not get the member defining symbol " + 1549349cc55cSDimitry Andric toMachOString(symCopy) + ": " + toString(std::move(e))); 15505ffd83dbSDimitry Andric } 15515ffd83dbSDimitry Andric 1552fe6060f1SDimitry Andric static macho::Symbol *createBitcodeSymbol(const lto::InputFile::Symbol &objSym, 1553fe6060f1SDimitry Andric BitcodeFile &file) { 1554*04eeddc0SDimitry Andric StringRef name = saver().save(objSym.getName()); 1555fe6060f1SDimitry Andric 1556fe6060f1SDimitry Andric if (objSym.isUndefined()) 15570eae32dcSDimitry Andric return symtab->addUndefined(name, &file, /*isWeakRef=*/objSym.isWeak()); 1558fe6060f1SDimitry Andric 1559fe6060f1SDimitry Andric // TODO: Write a test demonstrating why computing isPrivateExtern before 1560fe6060f1SDimitry Andric // LTO compilation is important. 1561fe6060f1SDimitry Andric bool isPrivateExtern = false; 1562fe6060f1SDimitry Andric switch (objSym.getVisibility()) { 1563fe6060f1SDimitry Andric case GlobalValue::HiddenVisibility: 1564fe6060f1SDimitry Andric isPrivateExtern = true; 1565fe6060f1SDimitry Andric break; 1566fe6060f1SDimitry Andric case GlobalValue::ProtectedVisibility: 1567fe6060f1SDimitry Andric error(name + " has protected visibility, which is not supported by Mach-O"); 1568fe6060f1SDimitry Andric break; 1569fe6060f1SDimitry Andric case GlobalValue::DefaultVisibility: 1570fe6060f1SDimitry Andric break; 1571fe6060f1SDimitry Andric } 1572fe6060f1SDimitry Andric 1573349cc55cSDimitry Andric if (objSym.isCommon()) 1574349cc55cSDimitry Andric return symtab->addCommon(name, &file, objSym.getCommonSize(), 1575349cc55cSDimitry Andric objSym.getCommonAlignment(), isPrivateExtern); 1576349cc55cSDimitry Andric 1577fe6060f1SDimitry Andric return symtab->addDefined(name, &file, /*isec=*/nullptr, /*value=*/0, 1578fe6060f1SDimitry Andric /*size=*/0, objSym.isWeak(), isPrivateExtern, 1579fe6060f1SDimitry Andric /*isThumb=*/false, 1580fe6060f1SDimitry Andric /*isReferencedDynamically=*/false, 1581349cc55cSDimitry Andric /*noDeadStrip=*/false, 1582349cc55cSDimitry Andric /*isWeakDefCanBeHidden=*/false); 1583fe6060f1SDimitry Andric } 1584fe6060f1SDimitry Andric 1585fe6060f1SDimitry Andric BitcodeFile::BitcodeFile(MemoryBufferRef mb, StringRef archiveName, 1586*04eeddc0SDimitry Andric uint64_t offsetInArchive, bool lazy) 1587*04eeddc0SDimitry Andric : InputFile(BitcodeKind, mb, lazy) { 15880eae32dcSDimitry Andric this->archiveName = std::string(archiveName); 1589fe6060f1SDimitry Andric std::string path = mb.getBufferIdentifier().str(); 1590fe6060f1SDimitry Andric // ThinLTO assumes that all MemoryBufferRefs given to it have a unique 1591fe6060f1SDimitry Andric // name. If two members with the same name are provided, this causes a 1592fe6060f1SDimitry Andric // collision and ThinLTO can't proceed. 1593fe6060f1SDimitry Andric // So, we append the archive name to disambiguate two members with the same 1594fe6060f1SDimitry Andric // name from multiple different archives, and offset within the archive to 1595fe6060f1SDimitry Andric // disambiguate two members of the same name from a single archive. 1596*04eeddc0SDimitry Andric MemoryBufferRef mbref(mb.getBuffer(), 1597*04eeddc0SDimitry Andric saver().save(archiveName.empty() 1598*04eeddc0SDimitry Andric ? path 1599*04eeddc0SDimitry Andric : archiveName + 1600*04eeddc0SDimitry Andric sys::path::filename(path) + 1601fe6060f1SDimitry Andric utostr(offsetInArchive))); 1602fe6060f1SDimitry Andric 1603e8d8bef9SDimitry Andric obj = check(lto::InputFile::create(mbref)); 1604*04eeddc0SDimitry Andric if (lazy) 1605*04eeddc0SDimitry Andric parseLazy(); 1606*04eeddc0SDimitry Andric else 1607*04eeddc0SDimitry Andric parse(); 1608*04eeddc0SDimitry Andric } 1609fe6060f1SDimitry Andric 1610*04eeddc0SDimitry Andric void BitcodeFile::parse() { 1611fe6060f1SDimitry Andric // Convert LTO Symbols to LLD Symbols in order to perform resolution. The 1612fe6060f1SDimitry Andric // "winning" symbol will then be marked as Prevailing at LTO compilation 1613fe6060f1SDimitry Andric // time. 1614*04eeddc0SDimitry Andric symbols.clear(); 1615fe6060f1SDimitry Andric for (const lto::InputFile::Symbol &objSym : obj->symbols()) 1616fe6060f1SDimitry Andric symbols.push_back(createBitcodeSymbol(objSym, *this)); 16175ffd83dbSDimitry Andric } 1618fe6060f1SDimitry Andric 1619*04eeddc0SDimitry Andric void BitcodeFile::parseLazy() { 1620*04eeddc0SDimitry Andric symbols.resize(obj->symbols().size()); 1621*04eeddc0SDimitry Andric for (auto it : llvm::enumerate(obj->symbols())) { 1622*04eeddc0SDimitry Andric const lto::InputFile::Symbol &objSym = it.value(); 1623*04eeddc0SDimitry Andric if (!objSym.isUndefined()) { 1624*04eeddc0SDimitry Andric symbols[it.index()] = 1625*04eeddc0SDimitry Andric symtab->addLazyObject(saver().save(objSym.getName()), *this); 1626*04eeddc0SDimitry Andric if (!lazy) 1627*04eeddc0SDimitry Andric break; 1628*04eeddc0SDimitry Andric } 1629*04eeddc0SDimitry Andric } 1630*04eeddc0SDimitry Andric } 1631*04eeddc0SDimitry Andric 1632*04eeddc0SDimitry Andric void macho::extract(InputFile &file, StringRef reason) { 1633*04eeddc0SDimitry Andric assert(file.lazy); 1634*04eeddc0SDimitry Andric file.lazy = false; 1635*04eeddc0SDimitry Andric printArchiveMemberLoad(reason, &file); 1636*04eeddc0SDimitry Andric if (auto *bitcode = dyn_cast<BitcodeFile>(&file)) { 1637*04eeddc0SDimitry Andric bitcode->parse(); 1638*04eeddc0SDimitry Andric } else { 1639*04eeddc0SDimitry Andric auto &f = cast<ObjFile>(file); 1640*04eeddc0SDimitry Andric if (target->wordSize == 8) 1641*04eeddc0SDimitry Andric f.parse<LP64>(); 1642*04eeddc0SDimitry Andric else 1643*04eeddc0SDimitry Andric f.parse<ILP32>(); 1644*04eeddc0SDimitry Andric } 1645*04eeddc0SDimitry Andric } 1646*04eeddc0SDimitry Andric 1647fe6060f1SDimitry Andric template void ObjFile::parse<LP64>(); 1648