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" 56*fe6060f1SDimitry Andric #include "SyntheticSections.h" 575ffd83dbSDimitry Andric #include "Target.h" 585ffd83dbSDimitry Andric 59e8d8bef9SDimitry Andric #include "lld/Common/DWARF.h" 605ffd83dbSDimitry Andric #include "lld/Common/ErrorHandler.h" 615ffd83dbSDimitry Andric #include "lld/Common/Memory.h" 62e8d8bef9SDimitry Andric #include "lld/Common/Reproduce.h" 63e8d8bef9SDimitry Andric #include "llvm/ADT/iterator.h" 645ffd83dbSDimitry Andric #include "llvm/BinaryFormat/MachO.h" 65e8d8bef9SDimitry Andric #include "llvm/LTO/LTO.h" 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*fe6060f1SDimitry Andric #include "llvm/TextAPI/Architecture.h" 71*fe6060f1SDimitry Andric #include "llvm/TextAPI/InterfaceFile.h" 725ffd83dbSDimitry Andric 735ffd83dbSDimitry Andric using namespace llvm; 745ffd83dbSDimitry Andric using namespace llvm::MachO; 755ffd83dbSDimitry Andric using namespace llvm::support::endian; 765ffd83dbSDimitry Andric using namespace llvm::sys; 775ffd83dbSDimitry Andric using namespace lld; 785ffd83dbSDimitry Andric using namespace lld::macho; 795ffd83dbSDimitry Andric 80e8d8bef9SDimitry Andric // Returns "<internal>", "foo.a(bar.o)", or "baz.o". 81e8d8bef9SDimitry Andric std::string lld::toString(const InputFile *f) { 82e8d8bef9SDimitry Andric if (!f) 83e8d8bef9SDimitry Andric return "<internal>"; 84*fe6060f1SDimitry Andric 85*fe6060f1SDimitry Andric // Multiple dylibs can be defined in one .tbd file. 86*fe6060f1SDimitry Andric if (auto dylibFile = dyn_cast<DylibFile>(f)) 87*fe6060f1SDimitry Andric if (f->getName().endswith(".tbd")) 88*fe6060f1SDimitry Andric return (f->getName() + "(" + dylibFile->installName + ")").str(); 89*fe6060f1SDimitry Andric 90e8d8bef9SDimitry Andric if (f->archiveName.empty()) 91e8d8bef9SDimitry Andric return std::string(f->getName()); 92*fe6060f1SDimitry Andric return (f->archiveName + "(" + path::filename(f->getName()) + ")").str(); 93e8d8bef9SDimitry Andric } 94e8d8bef9SDimitry Andric 95e8d8bef9SDimitry Andric SetVector<InputFile *> macho::inputFiles; 96e8d8bef9SDimitry Andric std::unique_ptr<TarWriter> macho::tar; 97e8d8bef9SDimitry Andric int InputFile::idCount = 0; 985ffd83dbSDimitry Andric 99*fe6060f1SDimitry Andric static VersionTuple decodeVersion(uint32_t version) { 100*fe6060f1SDimitry Andric unsigned major = version >> 16; 101*fe6060f1SDimitry Andric unsigned minor = (version >> 8) & 0xffu; 102*fe6060f1SDimitry Andric unsigned subMinor = version & 0xffu; 103*fe6060f1SDimitry Andric return VersionTuple(major, minor, subMinor); 104*fe6060f1SDimitry Andric } 105*fe6060f1SDimitry Andric 106*fe6060f1SDimitry Andric static std::vector<PlatformInfo> getPlatformInfos(const InputFile *input) { 107*fe6060f1SDimitry Andric if (!isa<ObjFile>(input) && !isa<DylibFile>(input)) 108*fe6060f1SDimitry Andric return {}; 109*fe6060f1SDimitry Andric 110*fe6060f1SDimitry Andric const char *hdr = input->mb.getBufferStart(); 111*fe6060f1SDimitry Andric 112*fe6060f1SDimitry Andric std::vector<PlatformInfo> platformInfos; 113*fe6060f1SDimitry Andric for (auto *cmd : findCommands<build_version_command>(hdr, LC_BUILD_VERSION)) { 114*fe6060f1SDimitry Andric PlatformInfo info; 115*fe6060f1SDimitry Andric info.target.Platform = static_cast<PlatformKind>(cmd->platform); 116*fe6060f1SDimitry Andric info.minimum = decodeVersion(cmd->minos); 117*fe6060f1SDimitry Andric platformInfos.emplace_back(std::move(info)); 118*fe6060f1SDimitry Andric } 119*fe6060f1SDimitry Andric for (auto *cmd : findCommands<version_min_command>( 120*fe6060f1SDimitry Andric hdr, LC_VERSION_MIN_MACOSX, LC_VERSION_MIN_IPHONEOS, 121*fe6060f1SDimitry Andric LC_VERSION_MIN_TVOS, LC_VERSION_MIN_WATCHOS)) { 122*fe6060f1SDimitry Andric PlatformInfo info; 123*fe6060f1SDimitry Andric switch (cmd->cmd) { 124*fe6060f1SDimitry Andric case LC_VERSION_MIN_MACOSX: 125*fe6060f1SDimitry Andric info.target.Platform = PlatformKind::macOS; 126*fe6060f1SDimitry Andric break; 127*fe6060f1SDimitry Andric case LC_VERSION_MIN_IPHONEOS: 128*fe6060f1SDimitry Andric info.target.Platform = PlatformKind::iOS; 129*fe6060f1SDimitry Andric break; 130*fe6060f1SDimitry Andric case LC_VERSION_MIN_TVOS: 131*fe6060f1SDimitry Andric info.target.Platform = PlatformKind::tvOS; 132*fe6060f1SDimitry Andric break; 133*fe6060f1SDimitry Andric case LC_VERSION_MIN_WATCHOS: 134*fe6060f1SDimitry Andric info.target.Platform = PlatformKind::watchOS; 135*fe6060f1SDimitry Andric break; 136*fe6060f1SDimitry Andric } 137*fe6060f1SDimitry Andric info.minimum = decodeVersion(cmd->version); 138*fe6060f1SDimitry Andric platformInfos.emplace_back(std::move(info)); 139*fe6060f1SDimitry Andric } 140*fe6060f1SDimitry Andric 141*fe6060f1SDimitry Andric return platformInfos; 142*fe6060f1SDimitry Andric } 143*fe6060f1SDimitry Andric 144*fe6060f1SDimitry Andric static bool checkCompatibility(const InputFile *input) { 145*fe6060f1SDimitry Andric std::vector<PlatformInfo> platformInfos = getPlatformInfos(input); 146*fe6060f1SDimitry Andric if (platformInfos.empty()) 147*fe6060f1SDimitry Andric return true; 148*fe6060f1SDimitry Andric 149*fe6060f1SDimitry Andric auto it = find_if(platformInfos, [&](const PlatformInfo &info) { 150*fe6060f1SDimitry Andric return removeSimulator(info.target.Platform) == 151*fe6060f1SDimitry Andric removeSimulator(config->platform()); 152*fe6060f1SDimitry Andric }); 153*fe6060f1SDimitry Andric if (it == platformInfos.end()) { 154*fe6060f1SDimitry Andric std::string platformNames; 155*fe6060f1SDimitry Andric raw_string_ostream os(platformNames); 156*fe6060f1SDimitry Andric interleave( 157*fe6060f1SDimitry Andric platformInfos, os, 158*fe6060f1SDimitry Andric [&](const PlatformInfo &info) { 159*fe6060f1SDimitry Andric os << getPlatformName(info.target.Platform); 160*fe6060f1SDimitry Andric }, 161*fe6060f1SDimitry Andric "/"); 162*fe6060f1SDimitry Andric error(toString(input) + " has platform " + platformNames + 163*fe6060f1SDimitry Andric Twine(", which is different from target platform ") + 164*fe6060f1SDimitry Andric getPlatformName(config->platform())); 165*fe6060f1SDimitry Andric return false; 166*fe6060f1SDimitry Andric } 167*fe6060f1SDimitry Andric 168*fe6060f1SDimitry Andric if (it->minimum > config->platformInfo.minimum) 169*fe6060f1SDimitry Andric warn(toString(input) + " has version " + it->minimum.getAsString() + 170*fe6060f1SDimitry Andric ", which is newer than target minimum of " + 171*fe6060f1SDimitry Andric config->platformInfo.minimum.getAsString()); 172*fe6060f1SDimitry Andric 173*fe6060f1SDimitry Andric return true; 174*fe6060f1SDimitry Andric } 175*fe6060f1SDimitry Andric 1765ffd83dbSDimitry Andric // Open a given file path and return it as a memory-mapped file. 1775ffd83dbSDimitry Andric Optional<MemoryBufferRef> macho::readFile(StringRef path) { 178*fe6060f1SDimitry Andric ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr = MemoryBuffer::getFile(path); 179*fe6060f1SDimitry Andric if (std::error_code ec = mbOrErr.getError()) { 1805ffd83dbSDimitry Andric error("cannot open " + path + ": " + ec.message()); 1815ffd83dbSDimitry Andric return None; 1825ffd83dbSDimitry Andric } 1835ffd83dbSDimitry Andric 1845ffd83dbSDimitry Andric std::unique_ptr<MemoryBuffer> &mb = *mbOrErr; 1855ffd83dbSDimitry Andric MemoryBufferRef mbref = mb->getMemBufferRef(); 1865ffd83dbSDimitry Andric make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take mb ownership 1875ffd83dbSDimitry Andric 1885ffd83dbSDimitry Andric // If this is a regular non-fat file, return it. 1895ffd83dbSDimitry Andric const char *buf = mbref.getBufferStart(); 190*fe6060f1SDimitry Andric const auto *hdr = reinterpret_cast<const fat_header *>(buf); 191*fe6060f1SDimitry Andric if (mbref.getBufferSize() < sizeof(uint32_t) || 192*fe6060f1SDimitry Andric read32be(&hdr->magic) != FAT_MAGIC) { 193e8d8bef9SDimitry Andric if (tar) 194e8d8bef9SDimitry Andric tar->append(relativeToRoot(path), mbref.getBuffer()); 1955ffd83dbSDimitry Andric return mbref; 196e8d8bef9SDimitry Andric } 1975ffd83dbSDimitry Andric 198*fe6060f1SDimitry Andric // Object files and archive files may be fat files, which contain multiple 199*fe6060f1SDimitry Andric // real files for different CPU ISAs. Here, we search for a file that matches 200*fe6060f1SDimitry Andric // with the current link target and returns it as a MemoryBufferRef. 201*fe6060f1SDimitry Andric const auto *arch = reinterpret_cast<const fat_arch *>(buf + sizeof(*hdr)); 2025ffd83dbSDimitry Andric 2035ffd83dbSDimitry Andric for (uint32_t i = 0, n = read32be(&hdr->nfat_arch); i < n; ++i) { 2045ffd83dbSDimitry Andric if (reinterpret_cast<const char *>(arch + i + 1) > 2055ffd83dbSDimitry Andric buf + mbref.getBufferSize()) { 2065ffd83dbSDimitry Andric error(path + ": fat_arch struct extends beyond end of file"); 2075ffd83dbSDimitry Andric return None; 2085ffd83dbSDimitry Andric } 2095ffd83dbSDimitry Andric 210*fe6060f1SDimitry Andric if (read32be(&arch[i].cputype) != static_cast<uint32_t>(target->cpuType) || 2115ffd83dbSDimitry Andric read32be(&arch[i].cpusubtype) != target->cpuSubtype) 2125ffd83dbSDimitry Andric continue; 2135ffd83dbSDimitry Andric 2145ffd83dbSDimitry Andric uint32_t offset = read32be(&arch[i].offset); 2155ffd83dbSDimitry Andric uint32_t size = read32be(&arch[i].size); 2165ffd83dbSDimitry Andric if (offset + size > mbref.getBufferSize()) 2175ffd83dbSDimitry Andric error(path + ": slice extends beyond end of file"); 218e8d8bef9SDimitry Andric if (tar) 219e8d8bef9SDimitry Andric tar->append(relativeToRoot(path), mbref.getBuffer()); 2205ffd83dbSDimitry Andric return MemoryBufferRef(StringRef(buf + offset, size), path.copy(bAlloc)); 2215ffd83dbSDimitry Andric } 2225ffd83dbSDimitry Andric 2235ffd83dbSDimitry Andric error("unable to find matching architecture in " + path); 2245ffd83dbSDimitry Andric return None; 2255ffd83dbSDimitry Andric } 2265ffd83dbSDimitry Andric 227*fe6060f1SDimitry Andric InputFile::InputFile(Kind kind, const InterfaceFile &interface) 228*fe6060f1SDimitry Andric : id(idCount++), fileKind(kind), name(saver.save(interface.getPath())) {} 2295ffd83dbSDimitry Andric 230*fe6060f1SDimitry Andric template <class Section> 231*fe6060f1SDimitry Andric void ObjFile::parseSections(ArrayRef<Section> sections) { 2325ffd83dbSDimitry Andric subsections.reserve(sections.size()); 2335ffd83dbSDimitry Andric auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 2345ffd83dbSDimitry Andric 235*fe6060f1SDimitry Andric for (const Section &sec : sections) { 236*fe6060f1SDimitry Andric StringRef name = 237e8d8bef9SDimitry Andric StringRef(sec.sectname, strnlen(sec.sectname, sizeof(sec.sectname))); 238*fe6060f1SDimitry Andric StringRef segname = 239e8d8bef9SDimitry Andric StringRef(sec.segname, strnlen(sec.segname, sizeof(sec.segname))); 240*fe6060f1SDimitry Andric ArrayRef<uint8_t> data = {isZeroFill(sec.flags) ? nullptr 241*fe6060f1SDimitry Andric : buf + sec.offset, 2425ffd83dbSDimitry Andric static_cast<size_t>(sec.size)}; 243*fe6060f1SDimitry Andric if (sec.align >= 32) { 244*fe6060f1SDimitry Andric error("alignment " + std::to_string(sec.align) + " of section " + name + 245*fe6060f1SDimitry Andric " is too large"); 246*fe6060f1SDimitry Andric subsections.push_back({}); 247*fe6060f1SDimitry Andric continue; 248*fe6060f1SDimitry Andric } 249*fe6060f1SDimitry Andric uint32_t align = 1 << sec.align; 250*fe6060f1SDimitry Andric uint32_t flags = sec.flags; 251e8d8bef9SDimitry Andric 252*fe6060f1SDimitry Andric if (sectionType(sec.flags) == S_CSTRING_LITERALS || 253*fe6060f1SDimitry Andric (config->dedupLiterals && isWordLiteralSection(sec.flags))) { 254*fe6060f1SDimitry Andric if (sec.nreloc && config->dedupLiterals) 255*fe6060f1SDimitry Andric fatal(toString(this) + " contains relocations in " + sec.segname + "," + 256*fe6060f1SDimitry Andric sec.sectname + 257*fe6060f1SDimitry Andric ", so LLD cannot deduplicate literals. Try re-running without " 258*fe6060f1SDimitry Andric "--deduplicate-literals."); 259*fe6060f1SDimitry Andric 260*fe6060f1SDimitry Andric InputSection *isec; 261*fe6060f1SDimitry Andric if (sectionType(sec.flags) == S_CSTRING_LITERALS) { 262*fe6060f1SDimitry Andric isec = 263*fe6060f1SDimitry Andric make<CStringInputSection>(segname, name, this, data, align, flags); 264*fe6060f1SDimitry Andric // FIXME: parallelize this? 265*fe6060f1SDimitry Andric cast<CStringInputSection>(isec)->splitIntoPieces(); 266*fe6060f1SDimitry Andric } else { 267*fe6060f1SDimitry Andric isec = make<WordLiteralInputSection>(segname, name, this, data, align, 268*fe6060f1SDimitry Andric flags); 269*fe6060f1SDimitry Andric } 270*fe6060f1SDimitry Andric subsections.push_back({{0, isec}}); 271*fe6060f1SDimitry Andric } else if (config->icfLevel != ICFLevel::none && 272*fe6060f1SDimitry Andric (name == section_names::cfString && 273*fe6060f1SDimitry Andric segname == segment_names::data)) { 274*fe6060f1SDimitry Andric uint64_t literalSize = target->wordSize == 8 ? 32 : 16; 275*fe6060f1SDimitry Andric subsections.push_back({}); 276*fe6060f1SDimitry Andric SubsectionMap &subsecMap = subsections.back(); 277*fe6060f1SDimitry Andric for (uint64_t off = 0; off < data.size(); off += literalSize) 278*fe6060f1SDimitry Andric subsecMap.push_back( 279*fe6060f1SDimitry Andric {off, make<ConcatInputSection>(segname, name, this, 280*fe6060f1SDimitry Andric data.slice(off, literalSize), align, 281*fe6060f1SDimitry Andric flags)}); 282*fe6060f1SDimitry Andric } else { 283*fe6060f1SDimitry Andric auto *isec = 284*fe6060f1SDimitry Andric make<ConcatInputSection>(segname, name, this, data, align, flags); 285*fe6060f1SDimitry Andric if (!(isDebugSection(isec->getFlags()) && 286*fe6060f1SDimitry Andric isec->getSegName() == segment_names::dwarf)) { 2875ffd83dbSDimitry Andric subsections.push_back({{0, isec}}); 288e8d8bef9SDimitry Andric } else { 289e8d8bef9SDimitry Andric // Instead of emitting DWARF sections, we emit STABS symbols to the 290e8d8bef9SDimitry Andric // object files that contain them. We filter them out early to avoid 291e8d8bef9SDimitry Andric // parsing their relocations unnecessarily. But we must still push an 292e8d8bef9SDimitry Andric // empty map to ensure the indices line up for the remaining sections. 293e8d8bef9SDimitry Andric subsections.push_back({}); 294e8d8bef9SDimitry Andric debugSections.push_back(isec); 295e8d8bef9SDimitry Andric } 2965ffd83dbSDimitry Andric } 2975ffd83dbSDimitry Andric } 298*fe6060f1SDimitry Andric } 2995ffd83dbSDimitry Andric 3005ffd83dbSDimitry Andric // Find the subsection corresponding to the greatest section offset that is <= 3015ffd83dbSDimitry Andric // that of the given offset. 3025ffd83dbSDimitry Andric // 3035ffd83dbSDimitry Andric // offset: an offset relative to the start of the original InputSection (before 3045ffd83dbSDimitry Andric // any subsection splitting has occurred). It will be updated to represent the 3055ffd83dbSDimitry Andric // same location as an offset relative to the start of the containing 3065ffd83dbSDimitry Andric // subsection. 3075ffd83dbSDimitry Andric static InputSection *findContainingSubsection(SubsectionMap &map, 308*fe6060f1SDimitry Andric uint64_t *offset) { 309*fe6060f1SDimitry Andric auto it = std::prev(llvm::upper_bound( 310*fe6060f1SDimitry Andric map, *offset, [](uint64_t value, SubsectionEntry subsecEntry) { 311*fe6060f1SDimitry Andric return value < subsecEntry.offset; 312*fe6060f1SDimitry Andric })); 313*fe6060f1SDimitry Andric *offset -= it->offset; 314*fe6060f1SDimitry Andric return it->isec; 3155ffd83dbSDimitry Andric } 3165ffd83dbSDimitry Andric 317*fe6060f1SDimitry Andric template <class Section> 318*fe6060f1SDimitry Andric static bool validateRelocationInfo(InputFile *file, const Section &sec, 319*fe6060f1SDimitry Andric relocation_info rel) { 320*fe6060f1SDimitry Andric const RelocAttrs &relocAttrs = target->getRelocAttrs(rel.r_type); 321*fe6060f1SDimitry Andric bool valid = true; 322*fe6060f1SDimitry Andric auto message = [relocAttrs, file, sec, rel, &valid](const Twine &diagnostic) { 323*fe6060f1SDimitry Andric valid = false; 324*fe6060f1SDimitry Andric return (relocAttrs.name + " relocation " + diagnostic + " at offset " + 325*fe6060f1SDimitry Andric std::to_string(rel.r_address) + " of " + sec.segname + "," + 326*fe6060f1SDimitry Andric sec.sectname + " in " + toString(file)) 327*fe6060f1SDimitry Andric .str(); 328*fe6060f1SDimitry Andric }; 329*fe6060f1SDimitry Andric 330*fe6060f1SDimitry Andric if (!relocAttrs.hasAttr(RelocAttrBits::LOCAL) && !rel.r_extern) 331*fe6060f1SDimitry Andric error(message("must be extern")); 332*fe6060f1SDimitry Andric if (relocAttrs.hasAttr(RelocAttrBits::PCREL) != rel.r_pcrel) 333*fe6060f1SDimitry Andric error(message(Twine("must ") + (rel.r_pcrel ? "not " : "") + 334*fe6060f1SDimitry Andric "be PC-relative")); 335*fe6060f1SDimitry Andric if (isThreadLocalVariables(sec.flags) && 336*fe6060f1SDimitry Andric !relocAttrs.hasAttr(RelocAttrBits::UNSIGNED)) 337*fe6060f1SDimitry Andric error(message("not allowed in thread-local section, must be UNSIGNED")); 338*fe6060f1SDimitry Andric if (rel.r_length < 2 || rel.r_length > 3 || 339*fe6060f1SDimitry Andric !relocAttrs.hasAttr(static_cast<RelocAttrBits>(1 << rel.r_length))) { 340*fe6060f1SDimitry Andric static SmallVector<StringRef, 4> widths{"0", "4", "8", "4 or 8"}; 341*fe6060f1SDimitry Andric error(message("has width " + std::to_string(1 << rel.r_length) + 342*fe6060f1SDimitry Andric " bytes, but must be " + 343*fe6060f1SDimitry Andric widths[(static_cast<int>(relocAttrs.bits) >> 2) & 3] + 344*fe6060f1SDimitry Andric " bytes")); 345*fe6060f1SDimitry Andric } 346*fe6060f1SDimitry Andric return valid; 347*fe6060f1SDimitry Andric } 348*fe6060f1SDimitry Andric 349*fe6060f1SDimitry Andric template <class Section> 350*fe6060f1SDimitry Andric void ObjFile::parseRelocations(ArrayRef<Section> sectionHeaders, 351*fe6060f1SDimitry Andric const Section &sec, SubsectionMap &subsecMap) { 3525ffd83dbSDimitry Andric auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 353e8d8bef9SDimitry Andric ArrayRef<relocation_info> relInfos( 354e8d8bef9SDimitry Andric reinterpret_cast<const relocation_info *>(buf + sec.reloff), sec.nreloc); 3555ffd83dbSDimitry Andric 356*fe6060f1SDimitry Andric auto subsecIt = subsecMap.rbegin(); 357e8d8bef9SDimitry Andric for (size_t i = 0; i < relInfos.size(); i++) { 358e8d8bef9SDimitry Andric // Paired relocations serve as Mach-O's method for attaching a 359e8d8bef9SDimitry Andric // supplemental datum to a primary relocation record. ELF does not 360e8d8bef9SDimitry Andric // need them because the *_RELOC_RELA records contain the extra 361e8d8bef9SDimitry Andric // addend field, vs. *_RELOC_REL which omit the addend. 362e8d8bef9SDimitry Andric // 363e8d8bef9SDimitry Andric // The {X86_64,ARM64}_RELOC_SUBTRACTOR record holds the subtrahend, 364e8d8bef9SDimitry Andric // and the paired *_RELOC_UNSIGNED record holds the minuend. The 365*fe6060f1SDimitry Andric // datum for each is a symbolic address. The result is the offset 366*fe6060f1SDimitry Andric // between two addresses. 367e8d8bef9SDimitry Andric // 368e8d8bef9SDimitry Andric // The ARM64_RELOC_ADDEND record holds the addend, and the paired 369e8d8bef9SDimitry Andric // ARM64_RELOC_BRANCH26 or ARM64_RELOC_PAGE21/PAGEOFF12 holds the 370e8d8bef9SDimitry Andric // base symbolic address. 371e8d8bef9SDimitry Andric // 372e8d8bef9SDimitry Andric // Note: X86 does not use *_RELOC_ADDEND because it can embed an 373e8d8bef9SDimitry Andric // addend into the instruction stream. On X86, a relocatable address 374e8d8bef9SDimitry Andric // field always occupies an entire contiguous sequence of byte(s), 375e8d8bef9SDimitry Andric // so there is no need to merge opcode bits with address 376e8d8bef9SDimitry Andric // bits. Therefore, it's easy and convenient to store addends in the 377e8d8bef9SDimitry Andric // instruction-stream bytes that would otherwise contain zeroes. By 378e8d8bef9SDimitry Andric // contrast, RISC ISAs such as ARM64 mix opcode bits with with 379e8d8bef9SDimitry Andric // address bits so that bitwise arithmetic is necessary to extract 380e8d8bef9SDimitry Andric // and insert them. Storing addends in the instruction stream is 381e8d8bef9SDimitry Andric // possible, but inconvenient and more costly at link time. 382e8d8bef9SDimitry Andric 383*fe6060f1SDimitry Andric int64_t pairedAddend = 0; 384*fe6060f1SDimitry Andric relocation_info relInfo = relInfos[i]; 385*fe6060f1SDimitry Andric if (target->hasAttr(relInfo.r_type, RelocAttrBits::ADDEND)) { 386*fe6060f1SDimitry Andric pairedAddend = SignExtend64<24>(relInfo.r_symbolnum); 387*fe6060f1SDimitry Andric relInfo = relInfos[++i]; 388*fe6060f1SDimitry Andric } 389e8d8bef9SDimitry Andric assert(i < relInfos.size()); 390*fe6060f1SDimitry Andric if (!validateRelocationInfo(this, sec, relInfo)) 391*fe6060f1SDimitry Andric continue; 392e8d8bef9SDimitry Andric if (relInfo.r_address & R_SCATTERED) 3935ffd83dbSDimitry Andric fatal("TODO: Scattered relocations not supported"); 3945ffd83dbSDimitry Andric 395*fe6060f1SDimitry Andric bool isSubtrahend = 396*fe6060f1SDimitry Andric target->hasAttr(relInfo.r_type, RelocAttrBits::SUBTRAHEND); 397*fe6060f1SDimitry Andric int64_t embeddedAddend = target->getEmbeddedAddend(mb, sec.offset, relInfo); 398*fe6060f1SDimitry Andric assert(!(embeddedAddend && pairedAddend)); 399*fe6060f1SDimitry Andric int64_t totalAddend = pairedAddend + embeddedAddend; 4005ffd83dbSDimitry Andric Reloc r; 401e8d8bef9SDimitry Andric r.type = relInfo.r_type; 402e8d8bef9SDimitry Andric r.pcrel = relInfo.r_pcrel; 403e8d8bef9SDimitry Andric r.length = relInfo.r_length; 404e8d8bef9SDimitry Andric r.offset = relInfo.r_address; 405e8d8bef9SDimitry Andric if (relInfo.r_extern) { 406e8d8bef9SDimitry Andric r.referent = symbols[relInfo.r_symbolnum]; 407*fe6060f1SDimitry Andric r.addend = isSubtrahend ? 0 : totalAddend; 4085ffd83dbSDimitry Andric } else { 409*fe6060f1SDimitry Andric assert(!isSubtrahend); 410*fe6060f1SDimitry Andric const Section &referentSec = sectionHeaders[relInfo.r_symbolnum - 1]; 411*fe6060f1SDimitry Andric uint64_t referentOffset; 412e8d8bef9SDimitry Andric if (relInfo.r_pcrel) { 4135ffd83dbSDimitry Andric // The implicit addend for pcrel section relocations is the pcrel offset 4145ffd83dbSDimitry Andric // in terms of the addresses in the input file. Here we adjust it so 415e8d8bef9SDimitry Andric // that it describes the offset from the start of the referent section. 416*fe6060f1SDimitry Andric // FIXME This logic was written around x86_64 behavior -- ARM64 doesn't 417*fe6060f1SDimitry Andric // have pcrel section relocations. We may want to factor this out into 418*fe6060f1SDimitry Andric // the arch-specific .cpp file. 419*fe6060f1SDimitry Andric assert(target->hasAttr(r.type, RelocAttrBits::BYTE4)); 420e8d8bef9SDimitry Andric referentOffset = 421*fe6060f1SDimitry Andric sec.addr + relInfo.r_address + 4 + totalAddend - referentSec.addr; 4225ffd83dbSDimitry Andric } else { 4235ffd83dbSDimitry Andric // The addend for a non-pcrel relocation is its absolute address. 424*fe6060f1SDimitry Andric referentOffset = totalAddend - referentSec.addr; 4255ffd83dbSDimitry Andric } 426*fe6060f1SDimitry Andric SubsectionMap &referentSubsecMap = subsections[relInfo.r_symbolnum - 1]; 427e8d8bef9SDimitry Andric r.referent = findContainingSubsection(referentSubsecMap, &referentOffset); 428e8d8bef9SDimitry Andric r.addend = referentOffset; 4295ffd83dbSDimitry Andric } 4305ffd83dbSDimitry Andric 431*fe6060f1SDimitry Andric // Find the subsection that this relocation belongs to. 432*fe6060f1SDimitry Andric // Though not required by the Mach-O format, clang and gcc seem to emit 433*fe6060f1SDimitry Andric // relocations in order, so let's take advantage of it. However, ld64 emits 434*fe6060f1SDimitry Andric // unsorted relocations (in `-r` mode), so we have a fallback for that 435*fe6060f1SDimitry Andric // uncommon case. 436*fe6060f1SDimitry Andric InputSection *subsec; 437*fe6060f1SDimitry Andric while (subsecIt != subsecMap.rend() && subsecIt->offset > r.offset) 438*fe6060f1SDimitry Andric ++subsecIt; 439*fe6060f1SDimitry Andric if (subsecIt == subsecMap.rend() || 440*fe6060f1SDimitry Andric subsecIt->offset + subsecIt->isec->getSize() <= r.offset) { 441*fe6060f1SDimitry Andric subsec = findContainingSubsection(subsecMap, &r.offset); 442*fe6060f1SDimitry Andric // Now that we know the relocs are unsorted, avoid trying the 'fast path' 443*fe6060f1SDimitry Andric // for the other relocations. 444*fe6060f1SDimitry Andric subsecIt = subsecMap.rend(); 445*fe6060f1SDimitry Andric } else { 446*fe6060f1SDimitry Andric subsec = subsecIt->isec; 447*fe6060f1SDimitry Andric r.offset -= subsecIt->offset; 448*fe6060f1SDimitry Andric } 4495ffd83dbSDimitry Andric subsec->relocs.push_back(r); 450*fe6060f1SDimitry Andric 451*fe6060f1SDimitry Andric if (isSubtrahend) { 452*fe6060f1SDimitry Andric relocation_info minuendInfo = relInfos[++i]; 453*fe6060f1SDimitry Andric // SUBTRACTOR relocations should always be followed by an UNSIGNED one 454*fe6060f1SDimitry Andric // attached to the same address. 455*fe6060f1SDimitry Andric assert(target->hasAttr(minuendInfo.r_type, RelocAttrBits::UNSIGNED) && 456*fe6060f1SDimitry Andric relInfo.r_address == minuendInfo.r_address); 457*fe6060f1SDimitry Andric Reloc p; 458*fe6060f1SDimitry Andric p.type = minuendInfo.r_type; 459*fe6060f1SDimitry Andric if (minuendInfo.r_extern) { 460*fe6060f1SDimitry Andric p.referent = symbols[minuendInfo.r_symbolnum]; 461*fe6060f1SDimitry Andric p.addend = totalAddend; 462*fe6060f1SDimitry Andric } else { 463*fe6060f1SDimitry Andric uint64_t referentOffset = 464*fe6060f1SDimitry Andric totalAddend - sectionHeaders[minuendInfo.r_symbolnum - 1].addr; 465*fe6060f1SDimitry Andric SubsectionMap &referentSubsecMap = 466*fe6060f1SDimitry Andric subsections[minuendInfo.r_symbolnum - 1]; 467*fe6060f1SDimitry Andric p.referent = 468*fe6060f1SDimitry Andric findContainingSubsection(referentSubsecMap, &referentOffset); 469*fe6060f1SDimitry Andric p.addend = referentOffset; 470*fe6060f1SDimitry Andric } 471*fe6060f1SDimitry Andric subsec->relocs.push_back(p); 472*fe6060f1SDimitry Andric } 4735ffd83dbSDimitry Andric } 4745ffd83dbSDimitry Andric } 4755ffd83dbSDimitry Andric 476*fe6060f1SDimitry Andric template <class NList> 477*fe6060f1SDimitry Andric static macho::Symbol *createDefined(const NList &sym, StringRef name, 478*fe6060f1SDimitry Andric InputSection *isec, uint64_t value, 479*fe6060f1SDimitry Andric uint64_t size) { 480e8d8bef9SDimitry Andric // Symbol scope is determined by sym.n_type & (N_EXT | N_PEXT): 481*fe6060f1SDimitry Andric // N_EXT: Global symbols. These go in the symbol table during the link, 482*fe6060f1SDimitry Andric // and also in the export table of the output so that the dynamic 483*fe6060f1SDimitry Andric // linker sees them. 484*fe6060f1SDimitry Andric // N_EXT | N_PEXT: Linkage unit (think: dylib) scoped. These go in the 485*fe6060f1SDimitry Andric // symbol table during the link so that duplicates are 486*fe6060f1SDimitry Andric // either reported (for non-weak symbols) or merged 487*fe6060f1SDimitry Andric // (for weak symbols), but they do not go in the export 488*fe6060f1SDimitry Andric // table of the output. 489*fe6060f1SDimitry Andric // N_PEXT: llvm-mc does not emit these, but `ld -r` (wherein ld64 emits 490*fe6060f1SDimitry Andric // object files) may produce them. LLD does not yet support -r. 491*fe6060f1SDimitry Andric // These are translation-unit scoped, identical to the `0` case. 492*fe6060f1SDimitry Andric // 0: Translation-unit scoped. These are not in the symbol table during 493*fe6060f1SDimitry Andric // link, and not in the export table of the output either. 494*fe6060f1SDimitry Andric bool isWeakDefCanBeHidden = 495*fe6060f1SDimitry Andric (sym.n_desc & (N_WEAK_DEF | N_WEAK_REF)) == (N_WEAK_DEF | N_WEAK_REF); 496e8d8bef9SDimitry Andric 497*fe6060f1SDimitry Andric if (sym.n_type & N_EXT) { 498*fe6060f1SDimitry Andric bool isPrivateExtern = sym.n_type & N_PEXT; 499*fe6060f1SDimitry Andric // lld's behavior for merging symbols is slightly different from ld64: 500*fe6060f1SDimitry Andric // ld64 picks the winning symbol based on several criteria (see 501*fe6060f1SDimitry Andric // pickBetweenRegularAtoms() in ld64's SymbolTable.cpp), while lld 502*fe6060f1SDimitry Andric // just merges metadata and keeps the contents of the first symbol 503*fe6060f1SDimitry Andric // with that name (see SymbolTable::addDefined). For: 504*fe6060f1SDimitry Andric // * inline function F in a TU built with -fvisibility-inlines-hidden 505*fe6060f1SDimitry Andric // * and inline function F in another TU built without that flag 506*fe6060f1SDimitry Andric // ld64 will pick the one from the file built without 507*fe6060f1SDimitry Andric // -fvisibility-inlines-hidden. 508*fe6060f1SDimitry Andric // lld will instead pick the one listed first on the link command line and 509*fe6060f1SDimitry Andric // give it visibility as if the function was built without 510*fe6060f1SDimitry Andric // -fvisibility-inlines-hidden. 511*fe6060f1SDimitry Andric // If both functions have the same contents, this will have the same 512*fe6060f1SDimitry Andric // behavior. If not, it won't, but the input had an ODR violation in 513*fe6060f1SDimitry Andric // that case. 514*fe6060f1SDimitry Andric // 515*fe6060f1SDimitry Andric // Similarly, merging a symbol 516*fe6060f1SDimitry Andric // that's isPrivateExtern and not isWeakDefCanBeHidden with one 517*fe6060f1SDimitry Andric // that's not isPrivateExtern but isWeakDefCanBeHidden technically 518*fe6060f1SDimitry Andric // should produce one 519*fe6060f1SDimitry Andric // that's not isPrivateExtern but isWeakDefCanBeHidden. That matters 520*fe6060f1SDimitry Andric // with ld64's semantics, because it means the non-private-extern 521*fe6060f1SDimitry Andric // definition will continue to take priority if more private extern 522*fe6060f1SDimitry Andric // definitions are encountered. With lld's semantics there's no observable 523*fe6060f1SDimitry Andric // difference between a symbol that's isWeakDefCanBeHidden or one that's 524*fe6060f1SDimitry Andric // privateExtern -- neither makes it into the dynamic symbol table. So just 525*fe6060f1SDimitry Andric // promote isWeakDefCanBeHidden to isPrivateExtern here. 526*fe6060f1SDimitry Andric if (isWeakDefCanBeHidden) 527*fe6060f1SDimitry Andric isPrivateExtern = true; 528*fe6060f1SDimitry Andric 529*fe6060f1SDimitry Andric return symtab->addDefined( 530*fe6060f1SDimitry Andric name, isec->getFile(), isec, value, size, sym.n_desc & N_WEAK_DEF, 531*fe6060f1SDimitry Andric isPrivateExtern, sym.n_desc & N_ARM_THUMB_DEF, 532*fe6060f1SDimitry Andric sym.n_desc & REFERENCED_DYNAMICALLY, sym.n_desc & N_NO_DEAD_STRIP); 533e8d8bef9SDimitry Andric } 534*fe6060f1SDimitry Andric 535*fe6060f1SDimitry Andric assert(!isWeakDefCanBeHidden && 536*fe6060f1SDimitry Andric "weak_def_can_be_hidden on already-hidden symbol?"); 537*fe6060f1SDimitry Andric return make<Defined>( 538*fe6060f1SDimitry Andric name, isec->getFile(), isec, value, size, sym.n_desc & N_WEAK_DEF, 539*fe6060f1SDimitry Andric /*isExternal=*/false, /*isPrivateExtern=*/false, 540*fe6060f1SDimitry Andric sym.n_desc & N_ARM_THUMB_DEF, sym.n_desc & REFERENCED_DYNAMICALLY, 541*fe6060f1SDimitry Andric sym.n_desc & N_NO_DEAD_STRIP); 542e8d8bef9SDimitry Andric } 543e8d8bef9SDimitry Andric 544e8d8bef9SDimitry Andric // Absolute symbols are defined symbols that do not have an associated 545e8d8bef9SDimitry Andric // InputSection. They cannot be weak. 546*fe6060f1SDimitry Andric template <class NList> 547*fe6060f1SDimitry Andric static macho::Symbol *createAbsolute(const NList &sym, InputFile *file, 548e8d8bef9SDimitry Andric StringRef name) { 549*fe6060f1SDimitry Andric if (sym.n_type & N_EXT) { 550*fe6060f1SDimitry Andric return symtab->addDefined( 551*fe6060f1SDimitry Andric name, file, nullptr, sym.n_value, /*size=*/0, 552*fe6060f1SDimitry Andric /*isWeakDef=*/false, sym.n_type & N_PEXT, sym.n_desc & N_ARM_THUMB_DEF, 553*fe6060f1SDimitry Andric /*isReferencedDynamically=*/false, sym.n_desc & N_NO_DEAD_STRIP); 554e8d8bef9SDimitry Andric } 555*fe6060f1SDimitry Andric return make<Defined>(name, file, nullptr, sym.n_value, /*size=*/0, 556*fe6060f1SDimitry Andric /*isWeakDef=*/false, 557*fe6060f1SDimitry Andric /*isExternal=*/false, /*isPrivateExtern=*/false, 558*fe6060f1SDimitry Andric sym.n_desc & N_ARM_THUMB_DEF, 559*fe6060f1SDimitry Andric /*isReferencedDynamically=*/false, 560*fe6060f1SDimitry Andric sym.n_desc & N_NO_DEAD_STRIP); 561e8d8bef9SDimitry Andric } 562e8d8bef9SDimitry Andric 563*fe6060f1SDimitry Andric template <class NList> 564*fe6060f1SDimitry Andric macho::Symbol *ObjFile::parseNonSectionSymbol(const NList &sym, 565e8d8bef9SDimitry Andric StringRef name) { 566e8d8bef9SDimitry Andric uint8_t type = sym.n_type & N_TYPE; 567e8d8bef9SDimitry Andric switch (type) { 568e8d8bef9SDimitry Andric case N_UNDF: 569e8d8bef9SDimitry Andric return sym.n_value == 0 570*fe6060f1SDimitry Andric ? symtab->addUndefined(name, this, sym.n_desc & N_WEAK_REF) 571e8d8bef9SDimitry Andric : symtab->addCommon(name, this, sym.n_value, 572e8d8bef9SDimitry Andric 1 << GET_COMM_ALIGN(sym.n_desc), 573e8d8bef9SDimitry Andric sym.n_type & N_PEXT); 574e8d8bef9SDimitry Andric case N_ABS: 575*fe6060f1SDimitry Andric return createAbsolute(sym, this, name); 576e8d8bef9SDimitry Andric case N_PBUD: 577e8d8bef9SDimitry Andric case N_INDR: 578e8d8bef9SDimitry Andric error("TODO: support symbols of type " + std::to_string(type)); 579e8d8bef9SDimitry Andric return nullptr; 580e8d8bef9SDimitry Andric case N_SECT: 581e8d8bef9SDimitry Andric llvm_unreachable( 582e8d8bef9SDimitry Andric "N_SECT symbols should not be passed to parseNonSectionSymbol"); 583e8d8bef9SDimitry Andric default: 584e8d8bef9SDimitry Andric llvm_unreachable("invalid symbol type"); 585e8d8bef9SDimitry Andric } 586e8d8bef9SDimitry Andric } 587e8d8bef9SDimitry Andric 588*fe6060f1SDimitry Andric template <class NList> 589*fe6060f1SDimitry Andric static bool isUndef(const NList &sym) { 590*fe6060f1SDimitry Andric return (sym.n_type & N_TYPE) == N_UNDF && sym.n_value == 0; 591*fe6060f1SDimitry Andric } 592*fe6060f1SDimitry Andric 593*fe6060f1SDimitry Andric template <class LP> 594*fe6060f1SDimitry Andric void ObjFile::parseSymbols(ArrayRef<typename LP::section> sectionHeaders, 595*fe6060f1SDimitry Andric ArrayRef<typename LP::nlist> nList, 5965ffd83dbSDimitry Andric const char *strtab, bool subsectionsViaSymbols) { 597*fe6060f1SDimitry Andric using NList = typename LP::nlist; 598*fe6060f1SDimitry Andric 599*fe6060f1SDimitry Andric // Groups indices of the symbols by the sections that contain them. 600*fe6060f1SDimitry Andric std::vector<std::vector<uint32_t>> symbolsBySection(subsections.size()); 6015ffd83dbSDimitry Andric symbols.resize(nList.size()); 602*fe6060f1SDimitry Andric SmallVector<unsigned, 32> undefineds; 603*fe6060f1SDimitry Andric for (uint32_t i = 0; i < nList.size(); ++i) { 604*fe6060f1SDimitry Andric const NList &sym = nList[i]; 6055ffd83dbSDimitry Andric 606*fe6060f1SDimitry Andric // Ignore debug symbols for now. 607*fe6060f1SDimitry Andric // FIXME: may need special handling. 608*fe6060f1SDimitry Andric if (sym.n_type & N_STAB) 609*fe6060f1SDimitry Andric continue; 610*fe6060f1SDimitry Andric 6115ffd83dbSDimitry Andric StringRef name = strtab + sym.n_strx; 612*fe6060f1SDimitry Andric if ((sym.n_type & N_TYPE) == N_SECT) { 6135ffd83dbSDimitry Andric SubsectionMap &subsecMap = subsections[sym.n_sect - 1]; 614*fe6060f1SDimitry Andric // parseSections() may have chosen not to parse this section. 615*fe6060f1SDimitry Andric if (subsecMap.empty()) 616*fe6060f1SDimitry Andric continue; 617*fe6060f1SDimitry Andric symbolsBySection[sym.n_sect - 1].push_back(i); 618*fe6060f1SDimitry Andric } else if (isUndef(sym)) { 619*fe6060f1SDimitry Andric undefineds.push_back(i); 620*fe6060f1SDimitry Andric } else { 621*fe6060f1SDimitry Andric symbols[i] = parseNonSectionSymbol(sym, name); 622*fe6060f1SDimitry Andric } 623*fe6060f1SDimitry Andric } 6245ffd83dbSDimitry Andric 625*fe6060f1SDimitry Andric for (size_t i = 0; i < subsections.size(); ++i) { 626*fe6060f1SDimitry Andric SubsectionMap &subsecMap = subsections[i]; 627*fe6060f1SDimitry Andric if (subsecMap.empty()) 628*fe6060f1SDimitry Andric continue; 629*fe6060f1SDimitry Andric 630*fe6060f1SDimitry Andric std::vector<uint32_t> &symbolIndices = symbolsBySection[i]; 631*fe6060f1SDimitry Andric uint64_t sectionAddr = sectionHeaders[i].addr; 632*fe6060f1SDimitry Andric uint32_t sectionAlign = 1u << sectionHeaders[i].align; 633*fe6060f1SDimitry Andric 634*fe6060f1SDimitry Andric InputSection *isec = subsecMap.back().isec; 635*fe6060f1SDimitry Andric // __cfstring has already been split into subsections during 636*fe6060f1SDimitry Andric // parseSections(), so we simply need to match Symbols to the corresponding 637*fe6060f1SDimitry Andric // subsection here. 638*fe6060f1SDimitry Andric if (config->icfLevel != ICFLevel::none && isCfStringSection(isec)) { 639*fe6060f1SDimitry Andric for (size_t j = 0; j < symbolIndices.size(); ++j) { 640*fe6060f1SDimitry Andric uint32_t symIndex = symbolIndices[j]; 641*fe6060f1SDimitry Andric const NList &sym = nList[symIndex]; 642*fe6060f1SDimitry Andric StringRef name = strtab + sym.n_strx; 643*fe6060f1SDimitry Andric uint64_t symbolOffset = sym.n_value - sectionAddr; 644*fe6060f1SDimitry Andric InputSection *isec = findContainingSubsection(subsecMap, &symbolOffset); 645*fe6060f1SDimitry Andric if (symbolOffset != 0) { 646*fe6060f1SDimitry Andric error(toString(this) + ": __cfstring contains symbol " + name + 647*fe6060f1SDimitry Andric " at misaligned offset"); 648*fe6060f1SDimitry Andric continue; 649*fe6060f1SDimitry Andric } 650*fe6060f1SDimitry Andric symbols[symIndex] = createDefined(sym, name, isec, 0, isec->getSize()); 651*fe6060f1SDimitry Andric } 6525ffd83dbSDimitry Andric continue; 6535ffd83dbSDimitry Andric } 6545ffd83dbSDimitry Andric 655*fe6060f1SDimitry Andric // Calculate symbol sizes and create subsections by splitting the sections 656*fe6060f1SDimitry Andric // along symbol boundaries. 657*fe6060f1SDimitry Andric // We populate subsecMap by repeatedly splitting the last (highest address) 658*fe6060f1SDimitry Andric // subsection. 659*fe6060f1SDimitry Andric llvm::stable_sort(symbolIndices, [&](uint32_t lhs, uint32_t rhs) { 660*fe6060f1SDimitry Andric return nList[lhs].n_value < nList[rhs].n_value; 661*fe6060f1SDimitry Andric }); 662*fe6060f1SDimitry Andric SubsectionEntry subsecEntry = subsecMap.back(); 663*fe6060f1SDimitry Andric for (size_t j = 0; j < symbolIndices.size(); ++j) { 664*fe6060f1SDimitry Andric uint32_t symIndex = symbolIndices[j]; 665*fe6060f1SDimitry Andric const NList &sym = nList[symIndex]; 666*fe6060f1SDimitry Andric StringRef name = strtab + sym.n_strx; 667*fe6060f1SDimitry Andric InputSection *isec = subsecEntry.isec; 668*fe6060f1SDimitry Andric 669*fe6060f1SDimitry Andric uint64_t subsecAddr = sectionAddr + subsecEntry.offset; 670*fe6060f1SDimitry Andric size_t symbolOffset = sym.n_value - subsecAddr; 671*fe6060f1SDimitry Andric uint64_t symbolSize = 672*fe6060f1SDimitry Andric j + 1 < symbolIndices.size() 673*fe6060f1SDimitry Andric ? nList[symbolIndices[j + 1]].n_value - sym.n_value 674*fe6060f1SDimitry Andric : isec->data.size() - symbolOffset; 675*fe6060f1SDimitry Andric // There are 4 cases where we do not need to create a new subsection: 676*fe6060f1SDimitry Andric // 1. If the input file does not use subsections-via-symbols. 677*fe6060f1SDimitry Andric // 2. Multiple symbols at the same address only induce one subsection. 678*fe6060f1SDimitry Andric // (The symbolOffset == 0 check covers both this case as well as 679*fe6060f1SDimitry Andric // the first loop iteration.) 680*fe6060f1SDimitry Andric // 3. Alternative entry points do not induce new subsections. 681*fe6060f1SDimitry Andric // 4. If we have a literal section (e.g. __cstring and __literal4). 682*fe6060f1SDimitry Andric if (!subsectionsViaSymbols || symbolOffset == 0 || 683*fe6060f1SDimitry Andric sym.n_desc & N_ALT_ENTRY || !isa<ConcatInputSection>(isec)) { 684*fe6060f1SDimitry Andric symbols[symIndex] = 685*fe6060f1SDimitry Andric createDefined(sym, name, isec, symbolOffset, symbolSize); 6865ffd83dbSDimitry Andric continue; 6875ffd83dbSDimitry Andric } 688*fe6060f1SDimitry Andric auto *concatIsec = cast<ConcatInputSection>(isec); 6895ffd83dbSDimitry Andric 690*fe6060f1SDimitry Andric auto *nextIsec = make<ConcatInputSection>(*concatIsec); 691*fe6060f1SDimitry Andric nextIsec->numRefs = 0; 692*fe6060f1SDimitry Andric nextIsec->wasCoalesced = false; 693*fe6060f1SDimitry Andric if (isZeroFill(isec->getFlags())) { 694*fe6060f1SDimitry Andric // Zero-fill sections have NULL data.data() non-zero data.size() 695*fe6060f1SDimitry Andric nextIsec->data = {nullptr, isec->data.size() - symbolOffset}; 696*fe6060f1SDimitry Andric isec->data = {nullptr, symbolOffset}; 697*fe6060f1SDimitry Andric } else { 698*fe6060f1SDimitry Andric nextIsec->data = isec->data.slice(symbolOffset); 699*fe6060f1SDimitry Andric isec->data = isec->data.slice(0, symbolOffset); 7005ffd83dbSDimitry Andric } 7015ffd83dbSDimitry Andric 702*fe6060f1SDimitry Andric // By construction, the symbol will be at offset zero in the new 703*fe6060f1SDimitry Andric // subsection. 704*fe6060f1SDimitry Andric symbols[symIndex] = 705*fe6060f1SDimitry Andric createDefined(sym, name, nextIsec, /*value=*/0, symbolSize); 7065ffd83dbSDimitry Andric // TODO: ld64 appears to preserve the original alignment as well as each 7075ffd83dbSDimitry Andric // subsection's offset from the last aligned address. We should consider 7085ffd83dbSDimitry Andric // emulating that behavior. 709*fe6060f1SDimitry Andric nextIsec->align = MinAlign(sectionAlign, sym.n_value); 710*fe6060f1SDimitry Andric subsecMap.push_back({sym.n_value - sectionAddr, nextIsec}); 711*fe6060f1SDimitry Andric subsecEntry = subsecMap.back(); 712*fe6060f1SDimitry Andric } 7135ffd83dbSDimitry Andric } 7145ffd83dbSDimitry Andric 715*fe6060f1SDimitry Andric // Undefined symbols can trigger recursive fetch from Archives due to 716*fe6060f1SDimitry Andric // LazySymbols. Process defined symbols first so that the relative order 717*fe6060f1SDimitry Andric // between a defined symbol and an undefined symbol does not change the 718*fe6060f1SDimitry Andric // symbol resolution behavior. In addition, a set of interconnected symbols 719*fe6060f1SDimitry Andric // will all be resolved to the same file, instead of being resolved to 720*fe6060f1SDimitry Andric // different files. 721*fe6060f1SDimitry Andric for (unsigned i : undefineds) { 722*fe6060f1SDimitry Andric const NList &sym = nList[i]; 723e8d8bef9SDimitry Andric StringRef name = strtab + sym.n_strx; 724*fe6060f1SDimitry Andric symbols[i] = parseNonSectionSymbol(sym, name); 7255ffd83dbSDimitry Andric } 7265ffd83dbSDimitry Andric } 7275ffd83dbSDimitry Andric 728e8d8bef9SDimitry Andric OpaqueFile::OpaqueFile(MemoryBufferRef mb, StringRef segName, 729e8d8bef9SDimitry Andric StringRef sectName) 730e8d8bef9SDimitry Andric : InputFile(OpaqueKind, mb) { 731e8d8bef9SDimitry Andric const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 732*fe6060f1SDimitry Andric ArrayRef<uint8_t> data = {buf, mb.getBufferSize()}; 733*fe6060f1SDimitry Andric ConcatInputSection *isec = 734*fe6060f1SDimitry Andric make<ConcatInputSection>(segName.take_front(16), sectName.take_front(16), 735*fe6060f1SDimitry Andric /*file=*/this, data); 736*fe6060f1SDimitry Andric isec->live = true; 737e8d8bef9SDimitry Andric subsections.push_back({{0, isec}}); 738e8d8bef9SDimitry Andric } 739e8d8bef9SDimitry Andric 740e8d8bef9SDimitry Andric ObjFile::ObjFile(MemoryBufferRef mb, uint32_t modTime, StringRef archiveName) 741e8d8bef9SDimitry Andric : InputFile(ObjKind, mb), modTime(modTime) { 742e8d8bef9SDimitry Andric this->archiveName = std::string(archiveName); 743*fe6060f1SDimitry Andric if (target->wordSize == 8) 744*fe6060f1SDimitry Andric parse<LP64>(); 745*fe6060f1SDimitry Andric else 746*fe6060f1SDimitry Andric parse<ILP32>(); 747e8d8bef9SDimitry Andric } 748e8d8bef9SDimitry Andric 749*fe6060f1SDimitry Andric template <class LP> void ObjFile::parse() { 750*fe6060f1SDimitry Andric using Header = typename LP::mach_header; 751*fe6060f1SDimitry Andric using SegmentCommand = typename LP::segment_command; 752*fe6060f1SDimitry Andric using Section = typename LP::section; 753*fe6060f1SDimitry Andric using NList = typename LP::nlist; 754*fe6060f1SDimitry Andric 755*fe6060f1SDimitry Andric auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 756*fe6060f1SDimitry Andric auto *hdr = reinterpret_cast<const Header *>(mb.getBufferStart()); 757*fe6060f1SDimitry Andric 758*fe6060f1SDimitry Andric Architecture arch = getArchitectureFromCpuType(hdr->cputype, hdr->cpusubtype); 759*fe6060f1SDimitry Andric if (arch != config->arch()) { 760*fe6060f1SDimitry Andric error(toString(this) + " has architecture " + getArchitectureName(arch) + 761*fe6060f1SDimitry Andric " which is incompatible with target architecture " + 762*fe6060f1SDimitry Andric getArchitectureName(config->arch())); 763*fe6060f1SDimitry Andric return; 764*fe6060f1SDimitry Andric } 765*fe6060f1SDimitry Andric 766*fe6060f1SDimitry Andric if (!checkCompatibility(this)) 767*fe6060f1SDimitry Andric return; 768*fe6060f1SDimitry Andric 769*fe6060f1SDimitry Andric for (auto *cmd : findCommands<linker_option_command>(hdr, LC_LINKER_OPTION)) { 770*fe6060f1SDimitry Andric StringRef data{reinterpret_cast<const char *>(cmd + 1), 771*fe6060f1SDimitry Andric cmd->cmdsize - sizeof(linker_option_command)}; 772*fe6060f1SDimitry Andric parseLCLinkerOption(this, cmd->count, data); 773*fe6060f1SDimitry Andric } 774*fe6060f1SDimitry Andric 775*fe6060f1SDimitry Andric ArrayRef<Section> sectionHeaders; 776*fe6060f1SDimitry Andric if (const load_command *cmd = findCommand(hdr, LP::segmentLCType)) { 777*fe6060f1SDimitry Andric auto *c = reinterpret_cast<const SegmentCommand *>(cmd); 778*fe6060f1SDimitry Andric sectionHeaders = 779*fe6060f1SDimitry Andric ArrayRef<Section>{reinterpret_cast<const Section *>(c + 1), c->nsects}; 7805ffd83dbSDimitry Andric parseSections(sectionHeaders); 7815ffd83dbSDimitry Andric } 7825ffd83dbSDimitry Andric 7835ffd83dbSDimitry Andric // TODO: Error on missing LC_SYMTAB? 7845ffd83dbSDimitry Andric if (const load_command *cmd = findCommand(hdr, LC_SYMTAB)) { 7855ffd83dbSDimitry Andric auto *c = reinterpret_cast<const symtab_command *>(cmd); 786*fe6060f1SDimitry Andric ArrayRef<NList> nList(reinterpret_cast<const NList *>(buf + c->symoff), 787*fe6060f1SDimitry Andric c->nsyms); 7885ffd83dbSDimitry Andric const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff; 7895ffd83dbSDimitry Andric bool subsectionsViaSymbols = hdr->flags & MH_SUBSECTIONS_VIA_SYMBOLS; 790*fe6060f1SDimitry Andric parseSymbols<LP>(sectionHeaders, nList, strtab, subsectionsViaSymbols); 7915ffd83dbSDimitry Andric } 7925ffd83dbSDimitry Andric 7935ffd83dbSDimitry Andric // The relocations may refer to the symbols, so we parse them after we have 7945ffd83dbSDimitry Andric // parsed all the symbols. 7955ffd83dbSDimitry Andric for (size_t i = 0, n = subsections.size(); i < n; ++i) 796e8d8bef9SDimitry Andric if (!subsections[i].empty()) 797*fe6060f1SDimitry Andric parseRelocations(sectionHeaders, sectionHeaders[i], subsections[i]); 798e8d8bef9SDimitry Andric 799e8d8bef9SDimitry Andric parseDebugInfo(); 800*fe6060f1SDimitry Andric if (config->emitDataInCodeInfo) 801*fe6060f1SDimitry Andric parseDataInCode(); 802e8d8bef9SDimitry Andric } 803e8d8bef9SDimitry Andric 804e8d8bef9SDimitry Andric void ObjFile::parseDebugInfo() { 805e8d8bef9SDimitry Andric std::unique_ptr<DwarfObject> dObj = DwarfObject::create(this); 806e8d8bef9SDimitry Andric if (!dObj) 807e8d8bef9SDimitry Andric return; 808e8d8bef9SDimitry Andric 809e8d8bef9SDimitry Andric auto *ctx = make<DWARFContext>( 810e8d8bef9SDimitry Andric std::move(dObj), "", 811e8d8bef9SDimitry Andric [&](Error err) { 812e8d8bef9SDimitry Andric warn(toString(this) + ": " + toString(std::move(err))); 813e8d8bef9SDimitry Andric }, 814e8d8bef9SDimitry Andric [&](Error warning) { 815e8d8bef9SDimitry Andric warn(toString(this) + ": " + toString(std::move(warning))); 816e8d8bef9SDimitry Andric }); 817e8d8bef9SDimitry Andric 818e8d8bef9SDimitry Andric // TODO: Since object files can contain a lot of DWARF info, we should verify 819e8d8bef9SDimitry Andric // that we are parsing just the info we need 820e8d8bef9SDimitry Andric const DWARFContext::compile_unit_range &units = ctx->compile_units(); 821*fe6060f1SDimitry Andric // FIXME: There can be more than one compile unit per object file. See 822*fe6060f1SDimitry Andric // PR48637. 823e8d8bef9SDimitry Andric auto it = units.begin(); 824e8d8bef9SDimitry Andric compileUnit = it->get(); 825*fe6060f1SDimitry Andric } 826*fe6060f1SDimitry Andric 827*fe6060f1SDimitry Andric void ObjFile::parseDataInCode() { 828*fe6060f1SDimitry Andric const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 829*fe6060f1SDimitry Andric const load_command *cmd = findCommand(buf, LC_DATA_IN_CODE); 830*fe6060f1SDimitry Andric if (!cmd) 831*fe6060f1SDimitry Andric return; 832*fe6060f1SDimitry Andric const auto *c = reinterpret_cast<const linkedit_data_command *>(cmd); 833*fe6060f1SDimitry Andric dataInCodeEntries = { 834*fe6060f1SDimitry Andric reinterpret_cast<const data_in_code_entry *>(buf + c->dataoff), 835*fe6060f1SDimitry Andric c->datasize / sizeof(data_in_code_entry)}; 836*fe6060f1SDimitry Andric assert(is_sorted(dataInCodeEntries, [](const data_in_code_entry &lhs, 837*fe6060f1SDimitry Andric const data_in_code_entry &rhs) { 838*fe6060f1SDimitry Andric return lhs.offset < rhs.offset; 839*fe6060f1SDimitry Andric })); 840e8d8bef9SDimitry Andric } 841e8d8bef9SDimitry Andric 842e8d8bef9SDimitry Andric // The path can point to either a dylib or a .tbd file. 843*fe6060f1SDimitry Andric static DylibFile *loadDylib(StringRef path, DylibFile *umbrella) { 844e8d8bef9SDimitry Andric Optional<MemoryBufferRef> mbref = readFile(path); 845e8d8bef9SDimitry Andric if (!mbref) { 846e8d8bef9SDimitry Andric error("could not read dylib file at " + path); 847*fe6060f1SDimitry Andric return nullptr; 848e8d8bef9SDimitry Andric } 849e8d8bef9SDimitry Andric return loadDylib(*mbref, umbrella); 850e8d8bef9SDimitry Andric } 851e8d8bef9SDimitry Andric 852e8d8bef9SDimitry Andric // TBD files are parsed into a series of TAPI documents (InterfaceFiles), with 853e8d8bef9SDimitry Andric // the first document storing child pointers to the rest of them. When we are 854*fe6060f1SDimitry Andric // processing a given TBD file, we store that top-level document in 855*fe6060f1SDimitry Andric // currentTopLevelTapi. When processing re-exports, we search its children for 856*fe6060f1SDimitry Andric // potentially matching documents in the same TBD file. Note that the children 857*fe6060f1SDimitry Andric // themselves don't point to further documents, i.e. this is a two-level tree. 858e8d8bef9SDimitry Andric // 859e8d8bef9SDimitry Andric // Re-exports can either refer to on-disk files, or to documents within .tbd 860e8d8bef9SDimitry Andric // files. 861*fe6060f1SDimitry Andric static DylibFile *findDylib(StringRef path, DylibFile *umbrella, 862*fe6060f1SDimitry Andric const InterfaceFile *currentTopLevelTapi) { 863*fe6060f1SDimitry Andric // Search order: 864*fe6060f1SDimitry Andric // 1. Install name basename in -F / -L directories. 865*fe6060f1SDimitry Andric { 866*fe6060f1SDimitry Andric StringRef stem = path::stem(path); 867*fe6060f1SDimitry Andric SmallString<128> frameworkName; 868*fe6060f1SDimitry Andric path::append(frameworkName, path::Style::posix, stem + ".framework", stem); 869*fe6060f1SDimitry Andric bool isFramework = path.endswith(frameworkName); 870*fe6060f1SDimitry Andric if (isFramework) { 871*fe6060f1SDimitry Andric for (StringRef dir : config->frameworkSearchPaths) { 872*fe6060f1SDimitry Andric SmallString<128> candidate = dir; 873*fe6060f1SDimitry Andric path::append(candidate, frameworkName); 874*fe6060f1SDimitry Andric if (Optional<std::string> dylibPath = resolveDylibPath(candidate)) 875*fe6060f1SDimitry Andric return loadDylib(*dylibPath, umbrella); 876*fe6060f1SDimitry Andric } 877*fe6060f1SDimitry Andric } else if (Optional<StringRef> dylibPath = findPathCombination( 878*fe6060f1SDimitry Andric stem, config->librarySearchPaths, {".tbd", ".dylib"})) 879*fe6060f1SDimitry Andric return loadDylib(*dylibPath, umbrella); 880*fe6060f1SDimitry Andric } 881*fe6060f1SDimitry Andric 882*fe6060f1SDimitry Andric // 2. As absolute path. 883e8d8bef9SDimitry Andric if (path::is_absolute(path, path::Style::posix)) 884e8d8bef9SDimitry Andric for (StringRef root : config->systemLibraryRoots) 885e8d8bef9SDimitry Andric if (Optional<std::string> dylibPath = 886e8d8bef9SDimitry Andric resolveDylibPath((root + path).str())) 887e8d8bef9SDimitry Andric return loadDylib(*dylibPath, umbrella); 888e8d8bef9SDimitry Andric 889*fe6060f1SDimitry Andric // 3. As relative path. 890e8d8bef9SDimitry Andric 891*fe6060f1SDimitry Andric // TODO: Handle -dylib_file 892*fe6060f1SDimitry Andric 893*fe6060f1SDimitry Andric // Replace @executable_path, @loader_path, @rpath prefixes in install name. 894*fe6060f1SDimitry Andric SmallString<128> newPath; 895*fe6060f1SDimitry Andric if (config->outputType == MH_EXECUTE && 896*fe6060f1SDimitry Andric path.consume_front("@executable_path/")) { 897*fe6060f1SDimitry Andric // ld64 allows overriding this with the undocumented flag -executable_path. 898*fe6060f1SDimitry Andric // lld doesn't currently implement that flag. 899*fe6060f1SDimitry Andric // FIXME: Consider using finalOutput instead of outputFile. 900*fe6060f1SDimitry Andric path::append(newPath, path::parent_path(config->outputFile), path); 901*fe6060f1SDimitry Andric path = newPath; 902*fe6060f1SDimitry Andric } else if (path.consume_front("@loader_path/")) { 903*fe6060f1SDimitry Andric fs::real_path(umbrella->getName(), newPath); 904*fe6060f1SDimitry Andric path::remove_filename(newPath); 905*fe6060f1SDimitry Andric path::append(newPath, path); 906*fe6060f1SDimitry Andric path = newPath; 907*fe6060f1SDimitry Andric } else if (path.startswith("@rpath/")) { 908*fe6060f1SDimitry Andric for (StringRef rpath : umbrella->rpaths) { 909*fe6060f1SDimitry Andric newPath.clear(); 910*fe6060f1SDimitry Andric if (rpath.consume_front("@loader_path/")) { 911*fe6060f1SDimitry Andric fs::real_path(umbrella->getName(), newPath); 912*fe6060f1SDimitry Andric path::remove_filename(newPath); 913*fe6060f1SDimitry Andric } 914*fe6060f1SDimitry Andric path::append(newPath, rpath, path.drop_front(strlen("@rpath/"))); 915*fe6060f1SDimitry Andric if (Optional<std::string> dylibPath = resolveDylibPath(newPath)) 916*fe6060f1SDimitry Andric return loadDylib(*dylibPath, umbrella); 917*fe6060f1SDimitry Andric } 918*fe6060f1SDimitry Andric } 919*fe6060f1SDimitry Andric 920*fe6060f1SDimitry Andric // FIXME: Should this be further up? 921e8d8bef9SDimitry Andric if (currentTopLevelTapi) { 922e8d8bef9SDimitry Andric for (InterfaceFile &child : 923e8d8bef9SDimitry Andric make_pointee_range(currentTopLevelTapi->documents())) { 924e8d8bef9SDimitry Andric assert(child.documents().empty()); 925*fe6060f1SDimitry Andric if (path == child.getInstallName()) { 926*fe6060f1SDimitry Andric auto file = make<DylibFile>(child, umbrella); 927*fe6060f1SDimitry Andric file->parseReexports(child); 928*fe6060f1SDimitry Andric return file; 929*fe6060f1SDimitry Andric } 930e8d8bef9SDimitry Andric } 931e8d8bef9SDimitry Andric } 932e8d8bef9SDimitry Andric 933e8d8bef9SDimitry Andric if (Optional<std::string> dylibPath = resolveDylibPath(path)) 934e8d8bef9SDimitry Andric return loadDylib(*dylibPath, umbrella); 935e8d8bef9SDimitry Andric 936*fe6060f1SDimitry Andric return nullptr; 937e8d8bef9SDimitry Andric } 938e8d8bef9SDimitry Andric 939e8d8bef9SDimitry Andric // If a re-exported dylib is public (lives in /usr/lib or 940e8d8bef9SDimitry Andric // /System/Library/Frameworks), then it is considered implicitly linked: we 941e8d8bef9SDimitry Andric // should bind to its symbols directly instead of via the re-exporting umbrella 942e8d8bef9SDimitry Andric // library. 943e8d8bef9SDimitry Andric static bool isImplicitlyLinked(StringRef path) { 944e8d8bef9SDimitry Andric if (!config->implicitDylibs) 945e8d8bef9SDimitry Andric return false; 946e8d8bef9SDimitry Andric 947e8d8bef9SDimitry Andric if (path::parent_path(path) == "/usr/lib") 948e8d8bef9SDimitry Andric return true; 949e8d8bef9SDimitry Andric 950e8d8bef9SDimitry Andric // Match /System/Library/Frameworks/$FOO.framework/**/$FOO 951e8d8bef9SDimitry Andric if (path.consume_front("/System/Library/Frameworks/")) { 952e8d8bef9SDimitry Andric StringRef frameworkName = path.take_until([](char c) { return c == '.'; }); 953e8d8bef9SDimitry Andric return path::filename(path) == frameworkName; 954e8d8bef9SDimitry Andric } 955e8d8bef9SDimitry Andric 956e8d8bef9SDimitry Andric return false; 957e8d8bef9SDimitry Andric } 958e8d8bef9SDimitry Andric 959*fe6060f1SDimitry Andric static void loadReexport(StringRef path, DylibFile *umbrella, 960*fe6060f1SDimitry Andric const InterfaceFile *currentTopLevelTapi) { 961*fe6060f1SDimitry Andric DylibFile *reexport = findDylib(path, umbrella, currentTopLevelTapi); 962*fe6060f1SDimitry Andric if (!reexport) 963*fe6060f1SDimitry Andric error("unable to locate re-export with install name " + path); 9645ffd83dbSDimitry Andric } 9655ffd83dbSDimitry Andric 966*fe6060f1SDimitry Andric DylibFile::DylibFile(MemoryBufferRef mb, DylibFile *umbrella, 967*fe6060f1SDimitry Andric bool isBundleLoader) 968*fe6060f1SDimitry Andric : InputFile(DylibKind, mb), refState(RefState::Unreferenced), 969*fe6060f1SDimitry Andric isBundleLoader(isBundleLoader) { 970*fe6060f1SDimitry Andric assert(!isBundleLoader || !umbrella); 9715ffd83dbSDimitry Andric if (umbrella == nullptr) 9725ffd83dbSDimitry Andric umbrella = this; 973*fe6060f1SDimitry Andric this->umbrella = umbrella; 9745ffd83dbSDimitry Andric 9755ffd83dbSDimitry Andric auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 976*fe6060f1SDimitry Andric auto *hdr = reinterpret_cast<const mach_header *>(mb.getBufferStart()); 9775ffd83dbSDimitry Andric 978*fe6060f1SDimitry Andric // Initialize installName. 9795ffd83dbSDimitry Andric if (const load_command *cmd = findCommand(hdr, LC_ID_DYLIB)) { 9805ffd83dbSDimitry Andric auto *c = reinterpret_cast<const dylib_command *>(cmd); 981e8d8bef9SDimitry Andric currentVersion = read32le(&c->dylib.current_version); 982e8d8bef9SDimitry Andric compatibilityVersion = read32le(&c->dylib.compatibility_version); 983*fe6060f1SDimitry Andric installName = 984*fe6060f1SDimitry Andric reinterpret_cast<const char *>(cmd) + read32le(&c->dylib.name); 985*fe6060f1SDimitry Andric } else if (!isBundleLoader) { 986*fe6060f1SDimitry Andric // macho_executable and macho_bundle don't have LC_ID_DYLIB, 987*fe6060f1SDimitry Andric // so it's OK. 988e8d8bef9SDimitry Andric error("dylib " + toString(this) + " missing LC_ID_DYLIB load command"); 9895ffd83dbSDimitry Andric return; 9905ffd83dbSDimitry Andric } 9915ffd83dbSDimitry Andric 992*fe6060f1SDimitry Andric if (config->printEachFile) 993*fe6060f1SDimitry Andric message(toString(this)); 994*fe6060f1SDimitry Andric inputFiles.insert(this); 995*fe6060f1SDimitry Andric 996*fe6060f1SDimitry Andric deadStrippable = hdr->flags & MH_DEAD_STRIPPABLE_DYLIB; 997*fe6060f1SDimitry Andric 998*fe6060f1SDimitry Andric if (!checkCompatibility(this)) 999*fe6060f1SDimitry Andric return; 1000*fe6060f1SDimitry Andric 1001*fe6060f1SDimitry Andric checkAppExtensionSafety(hdr->flags & MH_APP_EXTENSION_SAFE); 1002*fe6060f1SDimitry Andric 1003*fe6060f1SDimitry Andric for (auto *cmd : findCommands<rpath_command>(hdr, LC_RPATH)) { 1004*fe6060f1SDimitry Andric StringRef rpath{reinterpret_cast<const char *>(cmd) + cmd->path}; 1005*fe6060f1SDimitry Andric rpaths.push_back(rpath); 1006*fe6060f1SDimitry Andric } 1007*fe6060f1SDimitry Andric 10085ffd83dbSDimitry Andric // Initialize symbols. 1009*fe6060f1SDimitry Andric exportingFile = isImplicitlyLinked(installName) ? this : this->umbrella; 10105ffd83dbSDimitry Andric if (const load_command *cmd = findCommand(hdr, LC_DYLD_INFO_ONLY)) { 10115ffd83dbSDimitry Andric auto *c = reinterpret_cast<const dyld_info_command *>(cmd); 10125ffd83dbSDimitry Andric parseTrie(buf + c->export_off, c->export_size, 10135ffd83dbSDimitry Andric [&](const Twine &name, uint64_t flags) { 1014*fe6060f1SDimitry Andric StringRef savedName = saver.save(name); 1015*fe6060f1SDimitry Andric if (handleLDSymbol(savedName)) 1016*fe6060f1SDimitry Andric return; 1017e8d8bef9SDimitry Andric bool isWeakDef = flags & EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION; 1018e8d8bef9SDimitry Andric bool isTlv = flags & EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL; 1019*fe6060f1SDimitry Andric symbols.push_back(symtab->addDylib(savedName, exportingFile, 1020*fe6060f1SDimitry Andric isWeakDef, isTlv)); 10215ffd83dbSDimitry Andric }); 10225ffd83dbSDimitry Andric } else { 1023e8d8bef9SDimitry Andric error("LC_DYLD_INFO_ONLY not found in " + toString(this)); 10245ffd83dbSDimitry Andric return; 10255ffd83dbSDimitry Andric } 1026*fe6060f1SDimitry Andric } 10275ffd83dbSDimitry Andric 1028*fe6060f1SDimitry Andric void DylibFile::parseLoadCommands(MemoryBufferRef mb) { 1029*fe6060f1SDimitry Andric auto *hdr = reinterpret_cast<const mach_header *>(mb.getBufferStart()); 1030*fe6060f1SDimitry Andric const uint8_t *p = reinterpret_cast<const uint8_t *>(mb.getBufferStart()) + 1031*fe6060f1SDimitry Andric target->headerSize; 10325ffd83dbSDimitry Andric for (uint32_t i = 0, n = hdr->ncmds; i < n; ++i) { 10335ffd83dbSDimitry Andric auto *cmd = reinterpret_cast<const load_command *>(p); 10345ffd83dbSDimitry Andric p += cmd->cmdsize; 10355ffd83dbSDimitry Andric 1036*fe6060f1SDimitry Andric if (!(hdr->flags & MH_NO_REEXPORTED_DYLIBS) && 1037*fe6060f1SDimitry Andric cmd->cmd == LC_REEXPORT_DYLIB) { 1038*fe6060f1SDimitry Andric const auto *c = reinterpret_cast<const dylib_command *>(cmd); 10395ffd83dbSDimitry Andric StringRef reexportPath = 10405ffd83dbSDimitry Andric reinterpret_cast<const char *>(c) + read32le(&c->dylib.name); 1041*fe6060f1SDimitry Andric loadReexport(reexportPath, exportingFile, nullptr); 1042*fe6060f1SDimitry Andric } 1043*fe6060f1SDimitry Andric 1044*fe6060f1SDimitry Andric // FIXME: What about LC_LOAD_UPWARD_DYLIB, LC_LAZY_LOAD_DYLIB, 1045*fe6060f1SDimitry Andric // LC_LOAD_WEAK_DYLIB, LC_REEXPORT_DYLIB (..are reexports from dylibs with 1046*fe6060f1SDimitry Andric // MH_NO_REEXPORTED_DYLIBS loaded for -flat_namespace)? 1047*fe6060f1SDimitry Andric if (config->namespaceKind == NamespaceKind::flat && 1048*fe6060f1SDimitry Andric cmd->cmd == LC_LOAD_DYLIB) { 1049*fe6060f1SDimitry Andric const auto *c = reinterpret_cast<const dylib_command *>(cmd); 1050*fe6060f1SDimitry Andric StringRef dylibPath = 1051*fe6060f1SDimitry Andric reinterpret_cast<const char *>(c) + read32le(&c->dylib.name); 1052*fe6060f1SDimitry Andric DylibFile *dylib = findDylib(dylibPath, umbrella, nullptr); 1053*fe6060f1SDimitry Andric if (!dylib) 1054*fe6060f1SDimitry Andric error(Twine("unable to locate library '") + dylibPath + 1055*fe6060f1SDimitry Andric "' loaded from '" + toString(this) + "' for -flat_namespace"); 1056*fe6060f1SDimitry Andric } 10575ffd83dbSDimitry Andric } 10585ffd83dbSDimitry Andric } 10595ffd83dbSDimitry Andric 1060*fe6060f1SDimitry Andric // Some versions of XCode ship with .tbd files that don't have the right 1061*fe6060f1SDimitry Andric // platform settings. 1062*fe6060f1SDimitry Andric static constexpr std::array<StringRef, 3> skipPlatformChecks{ 1063*fe6060f1SDimitry Andric "/usr/lib/system/libsystem_kernel.dylib", 1064*fe6060f1SDimitry Andric "/usr/lib/system/libsystem_platform.dylib", 1065*fe6060f1SDimitry Andric "/usr/lib/system/libsystem_pthread.dylib"}; 1066*fe6060f1SDimitry Andric 1067*fe6060f1SDimitry Andric DylibFile::DylibFile(const InterfaceFile &interface, DylibFile *umbrella, 1068*fe6060f1SDimitry Andric bool isBundleLoader) 1069*fe6060f1SDimitry Andric : InputFile(DylibKind, interface), refState(RefState::Unreferenced), 1070*fe6060f1SDimitry Andric isBundleLoader(isBundleLoader) { 1071*fe6060f1SDimitry Andric // FIXME: Add test for the missing TBD code path. 1072*fe6060f1SDimitry Andric 10735ffd83dbSDimitry Andric if (umbrella == nullptr) 10745ffd83dbSDimitry Andric umbrella = this; 1075*fe6060f1SDimitry Andric this->umbrella = umbrella; 10765ffd83dbSDimitry Andric 1077*fe6060f1SDimitry Andric installName = saver.save(interface.getInstallName()); 1078e8d8bef9SDimitry Andric compatibilityVersion = interface.getCompatibilityVersion().rawValue(); 1079e8d8bef9SDimitry Andric currentVersion = interface.getCurrentVersion().rawValue(); 1080*fe6060f1SDimitry Andric 1081*fe6060f1SDimitry Andric if (config->printEachFile) 1082*fe6060f1SDimitry Andric message(toString(this)); 1083*fe6060f1SDimitry Andric inputFiles.insert(this); 1084*fe6060f1SDimitry Andric 1085*fe6060f1SDimitry Andric if (!is_contained(skipPlatformChecks, installName) && 1086*fe6060f1SDimitry Andric !is_contained(interface.targets(), config->platformInfo.target)) { 1087*fe6060f1SDimitry Andric error(toString(this) + " is incompatible with " + 1088*fe6060f1SDimitry Andric std::string(config->platformInfo.target)); 1089*fe6060f1SDimitry Andric return; 1090*fe6060f1SDimitry Andric } 1091*fe6060f1SDimitry Andric 1092*fe6060f1SDimitry Andric checkAppExtensionSafety(interface.isApplicationExtensionSafe()); 1093*fe6060f1SDimitry Andric 1094*fe6060f1SDimitry Andric exportingFile = isImplicitlyLinked(installName) ? this : umbrella; 1095e8d8bef9SDimitry Andric auto addSymbol = [&](const Twine &name) -> void { 1096e8d8bef9SDimitry Andric symbols.push_back(symtab->addDylib(saver.save(name), exportingFile, 1097e8d8bef9SDimitry Andric /*isWeakDef=*/false, 1098e8d8bef9SDimitry Andric /*isTlv=*/false)); 1099e8d8bef9SDimitry Andric }; 11005ffd83dbSDimitry Andric // TODO(compnerd) filter out symbols based on the target platform 1101e8d8bef9SDimitry Andric // TODO: handle weak defs, thread locals 1102*fe6060f1SDimitry Andric for (const auto *symbol : interface.symbols()) { 1103*fe6060f1SDimitry Andric if (!symbol->getArchitectures().has(config->arch())) 1104*fe6060f1SDimitry Andric continue; 1105*fe6060f1SDimitry Andric 1106*fe6060f1SDimitry Andric if (handleLDSymbol(symbol->getName())) 1107e8d8bef9SDimitry Andric continue; 1108e8d8bef9SDimitry Andric 1109e8d8bef9SDimitry Andric switch (symbol->getKind()) { 1110e8d8bef9SDimitry Andric case SymbolKind::GlobalSymbol: 1111e8d8bef9SDimitry Andric addSymbol(symbol->getName()); 1112e8d8bef9SDimitry Andric break; 1113e8d8bef9SDimitry Andric case SymbolKind::ObjectiveCClass: 1114e8d8bef9SDimitry Andric // XXX ld64 only creates these symbols when -ObjC is passed in. We may 1115e8d8bef9SDimitry Andric // want to emulate that. 1116e8d8bef9SDimitry Andric addSymbol(objc::klass + symbol->getName()); 1117e8d8bef9SDimitry Andric addSymbol(objc::metaclass + symbol->getName()); 1118e8d8bef9SDimitry Andric break; 1119e8d8bef9SDimitry Andric case SymbolKind::ObjectiveCClassEHType: 1120e8d8bef9SDimitry Andric addSymbol(objc::ehtype + symbol->getName()); 1121e8d8bef9SDimitry Andric break; 1122e8d8bef9SDimitry Andric case SymbolKind::ObjectiveCInstanceVariable: 1123e8d8bef9SDimitry Andric addSymbol(objc::ivar + symbol->getName()); 1124e8d8bef9SDimitry Andric break; 1125e8d8bef9SDimitry Andric } 11265ffd83dbSDimitry Andric } 1127e8d8bef9SDimitry Andric } 1128e8d8bef9SDimitry Andric 1129*fe6060f1SDimitry Andric void DylibFile::parseReexports(const InterfaceFile &interface) { 1130*fe6060f1SDimitry Andric const InterfaceFile *topLevel = 1131*fe6060f1SDimitry Andric interface.getParent() == nullptr ? &interface : interface.getParent(); 1132*fe6060f1SDimitry Andric for (InterfaceFileRef intfRef : interface.reexportedLibraries()) { 1133*fe6060f1SDimitry Andric InterfaceFile::const_target_range targets = intfRef.targets(); 1134*fe6060f1SDimitry Andric if (is_contained(skipPlatformChecks, intfRef.getInstallName()) || 1135*fe6060f1SDimitry Andric is_contained(targets, config->platformInfo.target)) 1136*fe6060f1SDimitry Andric loadReexport(intfRef.getInstallName(), exportingFile, topLevel); 1137*fe6060f1SDimitry Andric } 1138*fe6060f1SDimitry Andric } 1139e8d8bef9SDimitry Andric 1140*fe6060f1SDimitry Andric // $ld$ symbols modify the properties/behavior of the library (e.g. its install 1141*fe6060f1SDimitry Andric // name, compatibility version or hide/add symbols) for specific target 1142*fe6060f1SDimitry Andric // versions. 1143*fe6060f1SDimitry Andric bool DylibFile::handleLDSymbol(StringRef originalName) { 1144*fe6060f1SDimitry Andric if (!originalName.startswith("$ld$")) 1145*fe6060f1SDimitry Andric return false; 1146*fe6060f1SDimitry Andric 1147*fe6060f1SDimitry Andric StringRef action; 1148*fe6060f1SDimitry Andric StringRef name; 1149*fe6060f1SDimitry Andric std::tie(action, name) = originalName.drop_front(strlen("$ld$")).split('$'); 1150*fe6060f1SDimitry Andric if (action == "previous") 1151*fe6060f1SDimitry Andric handleLDPreviousSymbol(name, originalName); 1152*fe6060f1SDimitry Andric else if (action == "install_name") 1153*fe6060f1SDimitry Andric handleLDInstallNameSymbol(name, originalName); 1154*fe6060f1SDimitry Andric return true; 1155*fe6060f1SDimitry Andric } 1156*fe6060f1SDimitry Andric 1157*fe6060f1SDimitry Andric void DylibFile::handleLDPreviousSymbol(StringRef name, StringRef originalName) { 1158*fe6060f1SDimitry Andric // originalName: $ld$ previous $ <installname> $ <compatversion> $ 1159*fe6060f1SDimitry Andric // <platformstr> $ <startversion> $ <endversion> $ <symbol-name> $ 1160*fe6060f1SDimitry Andric StringRef installName; 1161*fe6060f1SDimitry Andric StringRef compatVersion; 1162*fe6060f1SDimitry Andric StringRef platformStr; 1163*fe6060f1SDimitry Andric StringRef startVersion; 1164*fe6060f1SDimitry Andric StringRef endVersion; 1165*fe6060f1SDimitry Andric StringRef symbolName; 1166*fe6060f1SDimitry Andric StringRef rest; 1167*fe6060f1SDimitry Andric 1168*fe6060f1SDimitry Andric std::tie(installName, name) = name.split('$'); 1169*fe6060f1SDimitry Andric std::tie(compatVersion, name) = name.split('$'); 1170*fe6060f1SDimitry Andric std::tie(platformStr, name) = name.split('$'); 1171*fe6060f1SDimitry Andric std::tie(startVersion, name) = name.split('$'); 1172*fe6060f1SDimitry Andric std::tie(endVersion, name) = name.split('$'); 1173*fe6060f1SDimitry Andric std::tie(symbolName, rest) = name.split('$'); 1174*fe6060f1SDimitry Andric // TODO: ld64 contains some logic for non-empty symbolName as well. 1175*fe6060f1SDimitry Andric if (!symbolName.empty()) 1176*fe6060f1SDimitry Andric return; 1177*fe6060f1SDimitry Andric unsigned platform; 1178*fe6060f1SDimitry Andric if (platformStr.getAsInteger(10, platform) || 1179*fe6060f1SDimitry Andric platform != static_cast<unsigned>(config->platform())) 1180*fe6060f1SDimitry Andric return; 1181*fe6060f1SDimitry Andric 1182*fe6060f1SDimitry Andric VersionTuple start; 1183*fe6060f1SDimitry Andric if (start.tryParse(startVersion)) { 1184*fe6060f1SDimitry Andric warn("failed to parse start version, symbol '" + originalName + 1185*fe6060f1SDimitry Andric "' ignored"); 1186*fe6060f1SDimitry Andric return; 1187*fe6060f1SDimitry Andric } 1188*fe6060f1SDimitry Andric VersionTuple end; 1189*fe6060f1SDimitry Andric if (end.tryParse(endVersion)) { 1190*fe6060f1SDimitry Andric warn("failed to parse end version, symbol '" + originalName + "' ignored"); 1191*fe6060f1SDimitry Andric return; 1192*fe6060f1SDimitry Andric } 1193*fe6060f1SDimitry Andric if (config->platformInfo.minimum < start || 1194*fe6060f1SDimitry Andric config->platformInfo.minimum >= end) 1195*fe6060f1SDimitry Andric return; 1196*fe6060f1SDimitry Andric 1197*fe6060f1SDimitry Andric this->installName = saver.save(installName); 1198*fe6060f1SDimitry Andric 1199*fe6060f1SDimitry Andric if (!compatVersion.empty()) { 1200*fe6060f1SDimitry Andric VersionTuple cVersion; 1201*fe6060f1SDimitry Andric if (cVersion.tryParse(compatVersion)) { 1202*fe6060f1SDimitry Andric warn("failed to parse compatibility version, symbol '" + originalName + 1203*fe6060f1SDimitry Andric "' ignored"); 1204*fe6060f1SDimitry Andric return; 1205*fe6060f1SDimitry Andric } 1206*fe6060f1SDimitry Andric compatibilityVersion = encodeVersion(cVersion); 1207*fe6060f1SDimitry Andric } 1208*fe6060f1SDimitry Andric } 1209*fe6060f1SDimitry Andric 1210*fe6060f1SDimitry Andric void DylibFile::handleLDInstallNameSymbol(StringRef name, 1211*fe6060f1SDimitry Andric StringRef originalName) { 1212*fe6060f1SDimitry Andric // originalName: $ld$ install_name $ os<version> $ install_name 1213*fe6060f1SDimitry Andric StringRef condition, installName; 1214*fe6060f1SDimitry Andric std::tie(condition, installName) = name.split('$'); 1215*fe6060f1SDimitry Andric VersionTuple version; 1216*fe6060f1SDimitry Andric if (!condition.consume_front("os") || version.tryParse(condition)) 1217*fe6060f1SDimitry Andric warn("failed to parse os version, symbol '" + originalName + "' ignored"); 1218*fe6060f1SDimitry Andric else if (version == config->platformInfo.minimum) 1219*fe6060f1SDimitry Andric this->installName = saver.save(installName); 1220*fe6060f1SDimitry Andric } 1221*fe6060f1SDimitry Andric 1222*fe6060f1SDimitry Andric void DylibFile::checkAppExtensionSafety(bool dylibIsAppExtensionSafe) const { 1223*fe6060f1SDimitry Andric if (config->applicationExtension && !dylibIsAppExtensionSafe) 1224*fe6060f1SDimitry Andric warn("using '-application_extension' with unsafe dylib: " + toString(this)); 1225e8d8bef9SDimitry Andric } 1226e8d8bef9SDimitry Andric 1227e8d8bef9SDimitry Andric ArchiveFile::ArchiveFile(std::unique_ptr<object::Archive> &&f) 12285ffd83dbSDimitry Andric : InputFile(ArchiveKind, f->getMemoryBufferRef()), file(std::move(f)) { 12295ffd83dbSDimitry Andric for (const object::Archive::Symbol &sym : file->symbols()) 12305ffd83dbSDimitry Andric symtab->addLazy(sym.getName(), this, sym); 12315ffd83dbSDimitry Andric } 12325ffd83dbSDimitry Andric 12335ffd83dbSDimitry Andric void ArchiveFile::fetch(const object::Archive::Symbol &sym) { 12345ffd83dbSDimitry Andric object::Archive::Child c = 12355ffd83dbSDimitry Andric CHECK(sym.getMember(), toString(this) + 12365ffd83dbSDimitry Andric ": could not get the member for symbol " + 1237e8d8bef9SDimitry Andric toMachOString(sym)); 12385ffd83dbSDimitry Andric 12395ffd83dbSDimitry Andric if (!seen.insert(c.getChildOffset()).second) 12405ffd83dbSDimitry Andric return; 12415ffd83dbSDimitry Andric 12425ffd83dbSDimitry Andric MemoryBufferRef mb = 12435ffd83dbSDimitry Andric CHECK(c.getMemoryBufferRef(), 12445ffd83dbSDimitry Andric toString(this) + 12455ffd83dbSDimitry Andric ": could not get the buffer for the member defining symbol " + 1246e8d8bef9SDimitry Andric toMachOString(sym)); 1247e8d8bef9SDimitry Andric 1248e8d8bef9SDimitry Andric if (tar && c.getParent()->isThin()) 1249e8d8bef9SDimitry Andric tar->append(relativeToRoot(CHECK(c.getFullName(), this)), mb.getBuffer()); 1250e8d8bef9SDimitry Andric 1251e8d8bef9SDimitry Andric uint32_t modTime = toTimeT( 1252e8d8bef9SDimitry Andric CHECK(c.getLastModified(), toString(this) + 1253e8d8bef9SDimitry Andric ": could not get the modification time " 1254e8d8bef9SDimitry Andric "for the member defining symbol " + 1255e8d8bef9SDimitry Andric toMachOString(sym))); 1256e8d8bef9SDimitry Andric 1257*fe6060f1SDimitry Andric // `sym` is owned by a LazySym, which will be replace<>()d by make<ObjFile> 1258e8d8bef9SDimitry Andric // and become invalid after that call. Copy it to the stack so we can refer 1259e8d8bef9SDimitry Andric // to it later. 1260*fe6060f1SDimitry Andric const object::Archive::Symbol symCopy = sym; 1261e8d8bef9SDimitry Andric 1262*fe6060f1SDimitry Andric if (Optional<InputFile *> file = loadArchiveMember( 1263*fe6060f1SDimitry Andric mb, modTime, getName(), /*objCOnly=*/false, c.getChildOffset())) { 1264*fe6060f1SDimitry Andric inputFiles.insert(*file); 1265*fe6060f1SDimitry Andric // ld64 doesn't demangle sym here even with -demangle. 1266*fe6060f1SDimitry Andric // Match that: intentionally don't call toMachOString(). 1267*fe6060f1SDimitry Andric printArchiveMemberLoad(symCopy.getName(), *file); 1268e8d8bef9SDimitry Andric } 12695ffd83dbSDimitry Andric } 12705ffd83dbSDimitry Andric 1271*fe6060f1SDimitry Andric static macho::Symbol *createBitcodeSymbol(const lto::InputFile::Symbol &objSym, 1272*fe6060f1SDimitry Andric BitcodeFile &file) { 1273*fe6060f1SDimitry Andric StringRef name = saver.save(objSym.getName()); 1274*fe6060f1SDimitry Andric 1275*fe6060f1SDimitry Andric // TODO: support weak references 1276*fe6060f1SDimitry Andric if (objSym.isUndefined()) 1277*fe6060f1SDimitry Andric return symtab->addUndefined(name, &file, /*isWeakRef=*/false); 1278*fe6060f1SDimitry Andric 1279*fe6060f1SDimitry Andric assert(!objSym.isCommon() && "TODO: support common symbols in LTO"); 1280*fe6060f1SDimitry Andric 1281*fe6060f1SDimitry Andric // TODO: Write a test demonstrating why computing isPrivateExtern before 1282*fe6060f1SDimitry Andric // LTO compilation is important. 1283*fe6060f1SDimitry Andric bool isPrivateExtern = false; 1284*fe6060f1SDimitry Andric switch (objSym.getVisibility()) { 1285*fe6060f1SDimitry Andric case GlobalValue::HiddenVisibility: 1286*fe6060f1SDimitry Andric isPrivateExtern = true; 1287*fe6060f1SDimitry Andric break; 1288*fe6060f1SDimitry Andric case GlobalValue::ProtectedVisibility: 1289*fe6060f1SDimitry Andric error(name + " has protected visibility, which is not supported by Mach-O"); 1290*fe6060f1SDimitry Andric break; 1291*fe6060f1SDimitry Andric case GlobalValue::DefaultVisibility: 1292*fe6060f1SDimitry Andric break; 1293*fe6060f1SDimitry Andric } 1294*fe6060f1SDimitry Andric 1295*fe6060f1SDimitry Andric return symtab->addDefined(name, &file, /*isec=*/nullptr, /*value=*/0, 1296*fe6060f1SDimitry Andric /*size=*/0, objSym.isWeak(), isPrivateExtern, 1297*fe6060f1SDimitry Andric /*isThumb=*/false, 1298*fe6060f1SDimitry Andric /*isReferencedDynamically=*/false, 1299*fe6060f1SDimitry Andric /*noDeadStrip=*/false); 1300*fe6060f1SDimitry Andric } 1301*fe6060f1SDimitry Andric 1302*fe6060f1SDimitry Andric BitcodeFile::BitcodeFile(MemoryBufferRef mb, StringRef archiveName, 1303*fe6060f1SDimitry Andric uint64_t offsetInArchive) 1304*fe6060f1SDimitry Andric : InputFile(BitcodeKind, mb) { 1305*fe6060f1SDimitry Andric std::string path = mb.getBufferIdentifier().str(); 1306*fe6060f1SDimitry Andric // ThinLTO assumes that all MemoryBufferRefs given to it have a unique 1307*fe6060f1SDimitry Andric // name. If two members with the same name are provided, this causes a 1308*fe6060f1SDimitry Andric // collision and ThinLTO can't proceed. 1309*fe6060f1SDimitry Andric // So, we append the archive name to disambiguate two members with the same 1310*fe6060f1SDimitry Andric // name from multiple different archives, and offset within the archive to 1311*fe6060f1SDimitry Andric // disambiguate two members of the same name from a single archive. 1312*fe6060f1SDimitry Andric MemoryBufferRef mbref( 1313*fe6060f1SDimitry Andric mb.getBuffer(), 1314*fe6060f1SDimitry Andric saver.save(archiveName.empty() ? path 1315*fe6060f1SDimitry Andric : archiveName + sys::path::filename(path) + 1316*fe6060f1SDimitry Andric utostr(offsetInArchive))); 1317*fe6060f1SDimitry Andric 1318e8d8bef9SDimitry Andric obj = check(lto::InputFile::create(mbref)); 1319*fe6060f1SDimitry Andric 1320*fe6060f1SDimitry Andric // Convert LTO Symbols to LLD Symbols in order to perform resolution. The 1321*fe6060f1SDimitry Andric // "winning" symbol will then be marked as Prevailing at LTO compilation 1322*fe6060f1SDimitry Andric // time. 1323*fe6060f1SDimitry Andric for (const lto::InputFile::Symbol &objSym : obj->symbols()) 1324*fe6060f1SDimitry Andric symbols.push_back(createBitcodeSymbol(objSym, *this)); 13255ffd83dbSDimitry Andric } 1326*fe6060f1SDimitry Andric 1327*fe6060f1SDimitry Andric template void ObjFile::parse<LP64>(); 1328