16acd3003SFangrui Song //===- InputFiles.cpp -----------------------------------------------------===// 26acd3003SFangrui Song // 36acd3003SFangrui Song // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 46acd3003SFangrui Song // See https://llvm.org/LICENSE.txt for license information. 56acd3003SFangrui Song // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 66acd3003SFangrui Song // 76acd3003SFangrui Song //===----------------------------------------------------------------------===// 86acd3003SFangrui Song // 96acd3003SFangrui Song // This file contains functions to parse Mach-O object files. In this comment, 106acd3003SFangrui Song // we describe the Mach-O file structure and how we parse it. 116acd3003SFangrui Song // 126acd3003SFangrui Song // Mach-O is not very different from ELF or COFF. The notion of symbols, 136acd3003SFangrui Song // sections and relocations exists in Mach-O as it does in ELF and COFF. 146acd3003SFangrui Song // 156acd3003SFangrui Song // Perhaps the notion that is new to those who know ELF/COFF is "subsections". 166acd3003SFangrui Song // In ELF/COFF, sections are an atomic unit of data copied from input files to 176acd3003SFangrui Song // output files. When we merge or garbage-collect sections, we treat each 186acd3003SFangrui Song // section as an atomic unit. In Mach-O, that's not the case. Sections can 196acd3003SFangrui Song // consist of multiple subsections, and subsections are a unit of merging and 206acd3003SFangrui Song // garbage-collecting. Therefore, Mach-O's subsections are more similar to 216acd3003SFangrui Song // ELF/COFF's sections than Mach-O's sections are. 226acd3003SFangrui Song // 236acd3003SFangrui Song // A section can have multiple symbols. A symbol that does not have the 246acd3003SFangrui Song // N_ALT_ENTRY attribute indicates a beginning of a subsection. Therefore, by 256acd3003SFangrui Song // definition, a symbol is always present at the beginning of each subsection. A 266acd3003SFangrui Song // symbol with N_ALT_ENTRY attribute does not start a new subsection and can 276acd3003SFangrui Song // point to a middle of a subsection. 286acd3003SFangrui Song // 296acd3003SFangrui Song // The notion of subsections also affects how relocations are represented in 306acd3003SFangrui Song // Mach-O. All references within a section need to be explicitly represented as 316acd3003SFangrui Song // relocations if they refer to different subsections, because we obviously need 326acd3003SFangrui Song // to fix up addresses if subsections are laid out in an output file differently 336acd3003SFangrui Song // than they were in object files. To represent that, Mach-O relocations can 346acd3003SFangrui Song // refer to an unnamed location via its address. Scattered relocations (those 356acd3003SFangrui Song // with the R_SCATTERED bit set) always refer to unnamed locations. 366acd3003SFangrui Song // Non-scattered relocations refer to an unnamed location if r_extern is not set 376acd3003SFangrui Song // and r_symbolnum is zero. 386acd3003SFangrui Song // 396acd3003SFangrui Song // Without the above differences, I think you can use your knowledge about ELF 406acd3003SFangrui Song // and COFF for Mach-O. 416acd3003SFangrui Song // 426acd3003SFangrui Song //===----------------------------------------------------------------------===// 436acd3003SFangrui Song 446acd3003SFangrui Song #include "InputFiles.h" 4587b6fd3eSJez Ng #include "Config.h" 46c519bc7eSNico Weber #include "Driver.h" 473fcb0eebSJez Ng #include "Dwarf.h" 487bbdbacdSJez Ng #include "ExportTrie.h" 496acd3003SFangrui Song #include "InputSection.h" 501e1a3f67SJez Ng #include "MachOStructs.h" 51cf918c80SJez Ng #include "ObjC.h" 526cb07313SKellie Medlin #include "OutputSection.h" 53cf918c80SJez Ng #include "OutputSegment.h" 546acd3003SFangrui Song #include "SymbolTable.h" 556acd3003SFangrui Song #include "Symbols.h" 566acd3003SFangrui Song #include "Target.h" 576acd3003SFangrui Song 583fcb0eebSJez Ng #include "lld/Common/DWARF.h" 596acd3003SFangrui Song #include "lld/Common/ErrorHandler.h" 606acd3003SFangrui Song #include "lld/Common/Memory.h" 6183e60f5aSNico Weber #include "lld/Common/Reproduce.h" 627394460dSJez Ng #include "llvm/ADT/iterator.h" 636acd3003SFangrui Song #include "llvm/BinaryFormat/MachO.h" 6421f83113SJez Ng #include "llvm/LTO/LTO.h" 656acd3003SFangrui Song #include "llvm/Support/Endian.h" 666acd3003SFangrui Song #include "llvm/Support/MemoryBuffer.h" 6787b6fd3eSJez Ng #include "llvm/Support/Path.h" 6883e60f5aSNico Weber #include "llvm/Support/TarWriter.h" 694752cdc9SJez Ng #include "llvm/TextAPI/MachO/Architecture.h" 706acd3003SFangrui Song 716acd3003SFangrui Song using namespace llvm; 726acd3003SFangrui Song using namespace llvm::MachO; 736acd3003SFangrui Song using namespace llvm::support::endian; 7487b6fd3eSJez Ng using namespace llvm::sys; 756acd3003SFangrui Song using namespace lld; 766acd3003SFangrui Song using namespace lld::macho; 776acd3003SFangrui Song 78b2f00f24SNico Weber // Returns "<internal>", "foo.a(bar.o)", or "baz.o". 79b2f00f24SNico Weber std::string lld::toString(const InputFile *f) { 80b2f00f24SNico Weber if (!f) 81b2f00f24SNico Weber return "<internal>"; 82b2f00f24SNico Weber if (f->archiveName.empty()) 83b2f00f24SNico Weber return std::string(f->getName()); 84b2f00f24SNico Weber return (path::filename(f->archiveName) + "(" + path::filename(f->getName()) + 85b2f00f24SNico Weber ")") 86b2f00f24SNico Weber .str(); 87b2f00f24SNico Weber } 88b2f00f24SNico Weber 89544148aeSJez Ng SetVector<InputFile *> macho::inputFiles; 9083e60f5aSNico Weber std::unique_ptr<TarWriter> macho::tar; 9178f6498cSJez Ng int InputFile::idCount = 0; 926acd3003SFangrui Song 936acd3003SFangrui Song // Open a given file path and return it as a memory-mapped file. 944af1522aSGreg McGary Optional<MemoryBufferRef> macho::readFile(StringRef path) { 956acd3003SFangrui Song // Open a file. 966acd3003SFangrui Song auto mbOrErr = MemoryBuffer::getFile(path); 976acd3003SFangrui Song if (auto ec = mbOrErr.getError()) { 986acd3003SFangrui Song error("cannot open " + path + ": " + ec.message()); 996acd3003SFangrui Song return None; 1006acd3003SFangrui Song } 1016acd3003SFangrui Song 1026acd3003SFangrui Song std::unique_ptr<MemoryBuffer> &mb = *mbOrErr; 1036acd3003SFangrui Song MemoryBufferRef mbref = mb->getMemBufferRef(); 1046acd3003SFangrui Song make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take mb ownership 105060efd24SJez Ng 106060efd24SJez Ng // If this is a regular non-fat file, return it. 107060efd24SJez Ng const char *buf = mbref.getBufferStart(); 108060efd24SJez Ng auto *hdr = reinterpret_cast<const MachO::fat_header *>(buf); 1094af1522aSGreg McGary if (mbref.getBufferSize() < sizeof(uint32_t) || 1104af1522aSGreg McGary read32be(&hdr->magic) != MachO::FAT_MAGIC) { 11183e60f5aSNico Weber if (tar) 11283e60f5aSNico Weber tar->append(relativeToRoot(path), mbref.getBuffer()); 1136acd3003SFangrui Song return mbref; 11483e60f5aSNico Weber } 115060efd24SJez Ng 116918948dbSJez Ng // Object files and archive files may be fat files, which contains 117918948dbSJez Ng // multiple real files for different CPU ISAs. Here, we search for a 118918948dbSJez Ng // file that matches with the current link target and returns it as 119918948dbSJez Ng // a MemoryBufferRef. 120918948dbSJez Ng auto *arch = reinterpret_cast<const MachO::fat_arch *>(buf + sizeof(*hdr)); 121918948dbSJez Ng 122918948dbSJez Ng for (uint32_t i = 0, n = read32be(&hdr->nfat_arch); i < n; ++i) { 123918948dbSJez Ng if (reinterpret_cast<const char *>(arch + i + 1) > 124918948dbSJez Ng buf + mbref.getBufferSize()) { 125918948dbSJez Ng error(path + ": fat_arch struct extends beyond end of file"); 126918948dbSJez Ng return None; 127918948dbSJez Ng } 128918948dbSJez Ng 129918948dbSJez Ng if (read32be(&arch[i].cputype) != target->cpuType || 130918948dbSJez Ng read32be(&arch[i].cpusubtype) != target->cpuSubtype) 131918948dbSJez Ng continue; 132918948dbSJez Ng 133918948dbSJez Ng uint32_t offset = read32be(&arch[i].offset); 134918948dbSJez Ng uint32_t size = read32be(&arch[i].size); 135918948dbSJez Ng if (offset + size > mbref.getBufferSize()) 136918948dbSJez Ng error(path + ": slice extends beyond end of file"); 13783e60f5aSNico Weber if (tar) 13883e60f5aSNico Weber tar->append(relativeToRoot(path), mbref.getBuffer()); 139918948dbSJez Ng return MemoryBufferRef(StringRef(buf + offset, size), path.copy(bAlloc)); 140918948dbSJez Ng } 141918948dbSJez Ng 142918948dbSJez Ng error("unable to find matching architecture in " + path); 143060efd24SJez Ng return None; 1446acd3003SFangrui Song } 1456acd3003SFangrui Song 146cf918c80SJez Ng const load_command *macho::findCommand(const mach_header_64 *hdr, 1476acd3003SFangrui Song uint32_t type) { 1486acd3003SFangrui Song const uint8_t *p = 1496acd3003SFangrui Song reinterpret_cast<const uint8_t *>(hdr) + sizeof(mach_header_64); 1506acd3003SFangrui Song 1516acd3003SFangrui Song for (uint32_t i = 0, n = hdr->ncmds; i < n; ++i) { 1526acd3003SFangrui Song auto *cmd = reinterpret_cast<const load_command *>(p); 1536acd3003SFangrui Song if (cmd->cmd == type) 1546acd3003SFangrui Song return cmd; 1556acd3003SFangrui Song p += cmd->cmdsize; 1566acd3003SFangrui Song } 1576acd3003SFangrui Song return nullptr; 1586acd3003SFangrui Song } 1596acd3003SFangrui Song 1607b007ac0SJez Ng void ObjFile::parseSections(ArrayRef<section_64> sections) { 1614eb6f485SJez Ng subsections.reserve(sections.size()); 1626acd3003SFangrui Song auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 1636acd3003SFangrui Song 1646acd3003SFangrui Song for (const section_64 &sec : sections) { 1656acd3003SFangrui Song InputSection *isec = make<InputSection>(); 1666acd3003SFangrui Song isec->file = this; 167cf918c80SJez Ng isec->name = 168cf918c80SJez Ng StringRef(sec.sectname, strnlen(sec.sectname, sizeof(sec.sectname))); 169cf918c80SJez Ng isec->segname = 170cf918c80SJez Ng StringRef(sec.segname, strnlen(sec.segname, sizeof(sec.segname))); 17174871cdaSJez Ng isec->data = {isZeroFill(sec.flags) ? nullptr : buf + sec.offset, 17274871cdaSJez Ng static_cast<size_t>(sec.size)}; 1736acd3003SFangrui Song if (sec.align >= 32) 1746acd3003SFangrui Song error("alignment " + std::to_string(sec.align) + " of section " + 1756acd3003SFangrui Song isec->name + " is too large"); 1766acd3003SFangrui Song else 1776acd3003SFangrui Song isec->align = 1 << sec.align; 1786acd3003SFangrui Song isec->flags = sec.flags; 179863f7a74SJez Ng 180863f7a74SJez Ng if (!(isDebugSection(isec->flags) && 181863f7a74SJez Ng isec->segname == segment_names::dwarf)) { 1824eb6f485SJez Ng subsections.push_back({{0, isec}}); 183863f7a74SJez Ng } else { 184863f7a74SJez Ng // Instead of emitting DWARF sections, we emit STABS symbols to the 185863f7a74SJez Ng // object files that contain them. We filter them out early to avoid 186863f7a74SJez Ng // parsing their relocations unnecessarily. But we must still push an 187863f7a74SJez Ng // empty map to ensure the indices line up for the remaining sections. 188863f7a74SJez Ng subsections.push_back({}); 189863f7a74SJez Ng debugSections.push_back(isec); 190863f7a74SJez Ng } 1914eb6f485SJez Ng } 1926acd3003SFangrui Song } 1936acd3003SFangrui Song 1944eb6f485SJez Ng // Find the subsection corresponding to the greatest section offset that is <= 1954eb6f485SJez Ng // that of the given offset. 1964eb6f485SJez Ng // 1974eb6f485SJez Ng // offset: an offset relative to the start of the original InputSection (before 1984eb6f485SJez Ng // any subsection splitting has occurred). It will be updated to represent the 1994eb6f485SJez Ng // same location as an offset relative to the start of the containing 2004eb6f485SJez Ng // subsection. 2014eb6f485SJez Ng static InputSection *findContainingSubsection(SubsectionMap &map, 2024eb6f485SJez Ng uint32_t *offset) { 2034eb6f485SJez Ng auto it = std::prev(map.upper_bound(*offset)); 2044eb6f485SJez Ng *offset -= it->first; 2054eb6f485SJez Ng return it->second; 2066acd3003SFangrui Song } 2076acd3003SFangrui Song 208e5d780e0SJez Ng static bool validateRelocationInfo(InputFile *file, const section_64 &sec, 2093a9d2f14SGreg McGary relocation_info rel) { 2103a9d2f14SGreg McGary const TargetInfo::RelocAttrs &relocAttrs = target->getRelocAttrs(rel.r_type); 2113a9d2f14SGreg McGary bool valid = true; 212e5d780e0SJez Ng auto message = [relocAttrs, file, sec, rel, &valid](const Twine &diagnostic) { 2133a9d2f14SGreg McGary valid = false; 2143a9d2f14SGreg McGary return (relocAttrs.name + " relocation " + diagnostic + " at offset " + 2153a9d2f14SGreg McGary std::to_string(rel.r_address) + " of " + sec.segname + "," + 216e5d780e0SJez Ng sec.sectname + " in " + toString(file)) 2173a9d2f14SGreg McGary .str(); 2183a9d2f14SGreg McGary }; 2193a9d2f14SGreg McGary 2203a9d2f14SGreg McGary if (!relocAttrs.hasAttr(RelocAttrBits::LOCAL) && !rel.r_extern) 2213a9d2f14SGreg McGary error(message("must be extern")); 2223a9d2f14SGreg McGary if (relocAttrs.hasAttr(RelocAttrBits::PCREL) != rel.r_pcrel) 2233a9d2f14SGreg McGary error(message(Twine("must ") + (rel.r_pcrel ? "not " : "") + 2243a9d2f14SGreg McGary "be PC-relative")); 2253a9d2f14SGreg McGary if (isThreadLocalVariables(sec.flags) && 2265e851733SJez Ng !relocAttrs.hasAttr(RelocAttrBits::UNSIGNED)) 2273a9d2f14SGreg McGary error(message("not allowed in thread-local section, must be UNSIGNED")); 2283a9d2f14SGreg McGary if (rel.r_length < 2 || rel.r_length > 3 || 2293a9d2f14SGreg McGary !relocAttrs.hasAttr(static_cast<RelocAttrBits>(1 << rel.r_length))) { 23087104faaSGreg McGary static SmallVector<StringRef, 4> widths{"0", "4", "8", "4 or 8"}; 2313a9d2f14SGreg McGary error(message("has width " + std::to_string(1 << rel.r_length) + 2323a9d2f14SGreg McGary " bytes, but must be " + 2333a9d2f14SGreg McGary widths[(static_cast<int>(relocAttrs.bits) >> 2) & 3] + 2343a9d2f14SGreg McGary " bytes")); 2353a9d2f14SGreg McGary } 2363a9d2f14SGreg McGary return valid; 2373a9d2f14SGreg McGary } 2383a9d2f14SGreg McGary 2397b007ac0SJez Ng void ObjFile::parseRelocations(const section_64 &sec, 2404eb6f485SJez Ng SubsectionMap &subsecMap) { 2416acd3003SFangrui Song auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 242d4ec3346SGreg McGary ArrayRef<relocation_info> relInfos( 243d4ec3346SGreg McGary reinterpret_cast<const relocation_info *>(buf + sec.reloff), sec.nreloc); 2446acd3003SFangrui Song 245d4ec3346SGreg McGary for (size_t i = 0; i < relInfos.size(); i++) { 246d4ec3346SGreg McGary // Paired relocations serve as Mach-O's method for attaching a 247d4ec3346SGreg McGary // supplemental datum to a primary relocation record. ELF does not 248d4ec3346SGreg McGary // need them because the *_RELOC_RELA records contain the extra 249d4ec3346SGreg McGary // addend field, vs. *_RELOC_REL which omit the addend. 250d4ec3346SGreg McGary // 251d4ec3346SGreg McGary // The {X86_64,ARM64}_RELOC_SUBTRACTOR record holds the subtrahend, 252d4ec3346SGreg McGary // and the paired *_RELOC_UNSIGNED record holds the minuend. The 2533a9d2f14SGreg McGary // datum for each is a symbolic address. The result is the offset 2543a9d2f14SGreg McGary // between two addresses. 255d4ec3346SGreg McGary // 256d4ec3346SGreg McGary // The ARM64_RELOC_ADDEND record holds the addend, and the paired 257d4ec3346SGreg McGary // ARM64_RELOC_BRANCH26 or ARM64_RELOC_PAGE21/PAGEOFF12 holds the 258d4ec3346SGreg McGary // base symbolic address. 259d4ec3346SGreg McGary // 260d4ec3346SGreg McGary // Note: X86 does not use *_RELOC_ADDEND because it can embed an 261d4ec3346SGreg McGary // addend into the instruction stream. On X86, a relocatable address 262d4ec3346SGreg McGary // field always occupies an entire contiguous sequence of byte(s), 263d4ec3346SGreg McGary // so there is no need to merge opcode bits with address 264d4ec3346SGreg McGary // bits. Therefore, it's easy and convenient to store addends in the 265d4ec3346SGreg McGary // instruction-stream bytes that would otherwise contain zeroes. By 266d4ec3346SGreg McGary // contrast, RISC ISAs such as ARM64 mix opcode bits with with 267d4ec3346SGreg McGary // address bits so that bitwise arithmetic is necessary to extract 268d4ec3346SGreg McGary // and insert them. Storing addends in the instruction stream is 269d4ec3346SGreg McGary // possible, but inconvenient and more costly at link time. 270d4ec3346SGreg McGary 2713a9d2f14SGreg McGary uint64_t pairedAddend = 0; 2723a9d2f14SGreg McGary relocation_info relInfo = relInfos[i]; 2733a9d2f14SGreg McGary if (target->hasAttr(relInfo.r_type, RelocAttrBits::ADDEND)) { 2743a9d2f14SGreg McGary pairedAddend = SignExtend64<24>(relInfo.r_symbolnum); 2753a9d2f14SGreg McGary relInfo = relInfos[++i]; 2763a9d2f14SGreg McGary } 277d4ec3346SGreg McGary assert(i < relInfos.size()); 278e5d780e0SJez Ng if (!validateRelocationInfo(this, sec, relInfo)) 2793a9d2f14SGreg McGary continue; 280d4ec3346SGreg McGary if (relInfo.r_address & R_SCATTERED) 2814eb6f485SJez Ng fatal("TODO: Scattered relocations not supported"); 2824eb6f485SJez Ng 2833a9d2f14SGreg McGary Reloc p; 2843a9d2f14SGreg McGary if (target->hasAttr(relInfo.r_type, RelocAttrBits::SUBTRAHEND)) { 2853a9d2f14SGreg McGary p.type = relInfo.r_type; 2863a9d2f14SGreg McGary p.referent = symbols[relInfo.r_symbolnum]; 2873a9d2f14SGreg McGary relInfo = relInfos[++i]; 28854139013SJez Ng // SUBTRACTOR relocations should always be followed by an UNSIGNED one 28954139013SJez Ng // indicating the minuend symbol. 29054139013SJez Ng assert(target->hasAttr(relInfo.r_type, RelocAttrBits::UNSIGNED) && 29154139013SJez Ng relInfo.r_extern); 2923a9d2f14SGreg McGary } 29382b3da6fSJez Ng uint64_t embeddedAddend = target->getEmbeddedAddend(mb, sec, relInfo); 29482b3da6fSJez Ng assert(!(embeddedAddend && pairedAddend)); 29582b3da6fSJez Ng uint64_t totalAddend = pairedAddend + embeddedAddend; 2964eb6f485SJez Ng Reloc r; 2971a3ef041SGreg McGary r.type = relInfo.r_type; 2981a3ef041SGreg McGary r.pcrel = relInfo.r_pcrel; 2991a3ef041SGreg McGary r.length = relInfo.r_length; 300d4ec3346SGreg McGary r.offset = relInfo.r_address; 3011a3ef041SGreg McGary if (relInfo.r_extern) { 3021a3ef041SGreg McGary r.referent = symbols[relInfo.r_symbolnum]; 3033a9d2f14SGreg McGary r.addend = totalAddend; 304198b0c57SJez Ng } else { 3051a3ef041SGreg McGary SubsectionMap &referentSubsecMap = subsections[relInfo.r_symbolnum - 1]; 3061a3ef041SGreg McGary const section_64 &referentSec = sectionHeaders[relInfo.r_symbolnum - 1]; 3071a3ef041SGreg McGary uint32_t referentOffset; 3081a3ef041SGreg McGary if (relInfo.r_pcrel) { 3094eb6f485SJez Ng // The implicit addend for pcrel section relocations is the pcrel offset 310fcde378dSJez Ng // in terms of the addresses in the input file. Here we adjust it so 3111a3ef041SGreg McGary // that it describes the offset from the start of the referent section. 312f083f652SJez Ng assert(target->hasAttr(r.type, RelocAttrBits::BYTE4)); 3131a3ef041SGreg McGary referentOffset = 3143a9d2f14SGreg McGary sec.addr + relInfo.r_address + 4 + totalAddend - referentSec.addr; 315fcde378dSJez Ng } else { 316fcde378dSJez Ng // The addend for a non-pcrel relocation is its absolute address. 3173a9d2f14SGreg McGary referentOffset = totalAddend - referentSec.addr; 318fcde378dSJez Ng } 3191a3ef041SGreg McGary r.referent = findContainingSubsection(referentSubsecMap, &referentOffset); 3201a3ef041SGreg McGary r.addend = referentOffset; 3214eb6f485SJez Ng } 3224eb6f485SJez Ng 3236f6d9186SJez Ng InputSection *subsec = findContainingSubsection(subsecMap, &r.offset); 32454139013SJez Ng if (p.type != GENERIC_RELOC_INVALID) 3253a9d2f14SGreg McGary subsec->relocs.push_back(p); 3264eb6f485SJez Ng subsec->relocs.push_back(r); 3276acd3003SFangrui Song } 3286acd3003SFangrui Song } 3294eb6f485SJez Ng 33062a3f0c9SJez Ng static macho::Symbol *createDefined(const structs::nlist_64 &sym, 33162a3f0c9SJez Ng StringRef name, InputSection *isec, 33262a3f0c9SJez Ng uint32_t value) { 33313f439a1SNico Weber // Symbol scope is determined by sym.n_type & (N_EXT | N_PEXT): 33413f439a1SNico Weber // N_EXT: Global symbols 33513f439a1SNico Weber // N_EXT | N_PEXT: Linkage unit (think: dylib) scoped 33613f439a1SNico Weber // N_PEXT: Does not occur in input files in practice, 33713f439a1SNico Weber // a private extern must be external. 33813f439a1SNico Weber // 0: Translation-unit scoped. These are not in the symbol table. 33913f439a1SNico Weber 34013f439a1SNico Weber if (sym.n_type & (N_EXT | N_PEXT)) { 34113f439a1SNico Weber assert((sym.n_type & N_EXT) && "invalid input"); 342163dcd85SJez Ng return symtab->addDefined(name, isec->file, isec, value, 343163dcd85SJez Ng sym.n_desc & N_WEAK_DEF, sym.n_type & N_PEXT); 34413f439a1SNico Weber } 345163dcd85SJez Ng return make<Defined>(name, isec->file, isec, value, sym.n_desc & N_WEAK_DEF, 34613f439a1SNico Weber /*isExternal=*/false, /*isPrivateExtern=*/false); 34762a3f0c9SJez Ng } 34862a3f0c9SJez Ng 34962a3f0c9SJez Ng // Absolute symbols are defined symbols that do not have an associated 35062a3f0c9SJez Ng // InputSection. They cannot be weak. 35162a3f0c9SJez Ng static macho::Symbol *createAbsolute(const structs::nlist_64 &sym, 352163dcd85SJez Ng InputFile *file, StringRef name) { 35313f439a1SNico Weber if (sym.n_type & (N_EXT | N_PEXT)) { 35413f439a1SNico Weber assert((sym.n_type & N_EXT) && "invalid input"); 355163dcd85SJez Ng return symtab->addDefined(name, file, nullptr, sym.n_value, 356163dcd85SJez Ng /*isWeakDef=*/false, sym.n_type & N_PEXT); 35713f439a1SNico Weber } 358163dcd85SJez Ng return make<Defined>(name, file, nullptr, sym.n_value, /*isWeakDef=*/false, 35913f439a1SNico Weber /*isExternal=*/false, /*isPrivateExtern=*/false); 36062a3f0c9SJez Ng } 36162a3f0c9SJez Ng 3627b007ac0SJez Ng macho::Symbol *ObjFile::parseNonSectionSymbol(const structs::nlist_64 &sym, 36362a3f0c9SJez Ng StringRef name) { 36462a3f0c9SJez Ng uint8_t type = sym.n_type & N_TYPE; 36562a3f0c9SJez Ng switch (type) { 36662a3f0c9SJez Ng case N_UNDF: 36762a3f0c9SJez Ng return sym.n_value == 0 368163dcd85SJez Ng ? symtab->addUndefined(name, this, sym.n_desc & N_WEAK_REF) 36962a3f0c9SJez Ng : symtab->addCommon(name, this, sym.n_value, 37013f439a1SNico Weber 1 << GET_COMM_ALIGN(sym.n_desc), 37113f439a1SNico Weber sym.n_type & N_PEXT); 37262a3f0c9SJez Ng case N_ABS: 373163dcd85SJez Ng return createAbsolute(sym, this, name); 37462a3f0c9SJez Ng case N_PBUD: 37562a3f0c9SJez Ng case N_INDR: 37662a3f0c9SJez Ng error("TODO: support symbols of type " + std::to_string(type)); 37762a3f0c9SJez Ng return nullptr; 37862a3f0c9SJez Ng case N_SECT: 37962a3f0c9SJez Ng llvm_unreachable( 38062a3f0c9SJez Ng "N_SECT symbols should not be passed to parseNonSectionSymbol"); 38162a3f0c9SJez Ng default: 38262a3f0c9SJez Ng llvm_unreachable("invalid symbol type"); 38362a3f0c9SJez Ng } 38462a3f0c9SJez Ng } 38562a3f0c9SJez Ng 3867b007ac0SJez Ng void ObjFile::parseSymbols(ArrayRef<structs::nlist_64> nList, 3871e1a3f67SJez Ng const char *strtab, bool subsectionsViaSymbols) { 3884eb6f485SJez Ng // resize(), not reserve(), because we are going to create N_ALT_ENTRY symbols 3894eb6f485SJez Ng // out-of-sequence. 3904eb6f485SJez Ng symbols.resize(nList.size()); 3914eb6f485SJez Ng std::vector<size_t> altEntrySymIdxs; 3924eb6f485SJez Ng 3934eb6f485SJez Ng for (size_t i = 0, n = nList.size(); i < n; ++i) { 3941e1a3f67SJez Ng const structs::nlist_64 &sym = nList[i]; 3954eb6f485SJez Ng StringRef name = strtab + sym.n_strx; 39662a3f0c9SJez Ng 39762a3f0c9SJez Ng if ((sym.n_type & N_TYPE) != N_SECT) { 39862a3f0c9SJez Ng symbols[i] = parseNonSectionSymbol(sym, name); 3994eb6f485SJez Ng continue; 4004eb6f485SJez Ng } 4014eb6f485SJez Ng 4024eb6f485SJez Ng const section_64 &sec = sectionHeaders[sym.n_sect - 1]; 4034eb6f485SJez Ng SubsectionMap &subsecMap = subsections[sym.n_sect - 1]; 404863f7a74SJez Ng assert(!subsecMap.empty()); 4054eb6f485SJez Ng uint64_t offset = sym.n_value - sec.addr; 4064eb6f485SJez Ng 4074eb6f485SJez Ng // If the input file does not use subsections-via-symbols, all symbols can 4084eb6f485SJez Ng // use the same subsection. Otherwise, we must split the sections along 4094eb6f485SJez Ng // symbol boundaries. 4104eb6f485SJez Ng if (!subsectionsViaSymbols) { 41162a3f0c9SJez Ng symbols[i] = createDefined(sym, name, subsecMap[0], offset); 4124eb6f485SJez Ng continue; 4134eb6f485SJez Ng } 4144eb6f485SJez Ng 4154eb6f485SJez Ng // nList entries aren't necessarily arranged in address order. Therefore, 4164eb6f485SJez Ng // we can't create alt-entry symbols at this point because a later symbol 4174eb6f485SJez Ng // may split its section, which may affect which subsection the alt-entry 4184eb6f485SJez Ng // symbol is assigned to. So we need to handle them in a second pass below. 4194eb6f485SJez Ng if (sym.n_desc & N_ALT_ENTRY) { 4204eb6f485SJez Ng altEntrySymIdxs.push_back(i); 4214eb6f485SJez Ng continue; 4224eb6f485SJez Ng } 4234eb6f485SJez Ng 4244eb6f485SJez Ng // Find the subsection corresponding to the greatest section offset that is 4254eb6f485SJez Ng // <= that of the current symbol. The subsection that we find either needs 4264eb6f485SJez Ng // to be used directly or split in two. 4274eb6f485SJez Ng uint32_t firstSize = offset; 4284eb6f485SJez Ng InputSection *firstIsec = findContainingSubsection(subsecMap, &firstSize); 4294eb6f485SJez Ng 4304eb6f485SJez Ng if (firstSize == 0) { 4314eb6f485SJez Ng // Alias of an existing symbol, or the first symbol in the section. These 4324eb6f485SJez Ng // are handled by reusing the existing section. 43362a3f0c9SJez Ng symbols[i] = createDefined(sym, name, firstIsec, 0); 4344eb6f485SJez Ng continue; 4354eb6f485SJez Ng } 4364eb6f485SJez Ng 4374eb6f485SJez Ng // We saw a symbol definition at a new offset. Split the section into two 4384eb6f485SJez Ng // subsections. The new symbol uses the second subsection. 4394eb6f485SJez Ng auto *secondIsec = make<InputSection>(*firstIsec); 4404eb6f485SJez Ng secondIsec->data = firstIsec->data.slice(firstSize); 4414eb6f485SJez Ng firstIsec->data = firstIsec->data.slice(0, firstSize); 4424eb6f485SJez Ng // TODO: ld64 appears to preserve the original alignment as well as each 4434eb6f485SJez Ng // subsection's offset from the last aligned address. We should consider 4444eb6f485SJez Ng // emulating that behavior. 4454eb6f485SJez Ng secondIsec->align = MinAlign(firstIsec->align, offset); 4464eb6f485SJez Ng 4474eb6f485SJez Ng subsecMap[offset] = secondIsec; 4484eb6f485SJez Ng // By construction, the symbol will be at offset zero in the new section. 44962a3f0c9SJez Ng symbols[i] = createDefined(sym, name, secondIsec, 0); 4504eb6f485SJez Ng } 4514eb6f485SJez Ng 4524eb6f485SJez Ng for (size_t idx : altEntrySymIdxs) { 4531e1a3f67SJez Ng const structs::nlist_64 &sym = nList[idx]; 45462a3f0c9SJez Ng StringRef name = strtab + sym.n_strx; 4554eb6f485SJez Ng SubsectionMap &subsecMap = subsections[sym.n_sect - 1]; 4564eb6f485SJez Ng uint32_t off = sym.n_value - sectionHeaders[sym.n_sect - 1].addr; 4574eb6f485SJez Ng InputSection *subsec = findContainingSubsection(subsecMap, &off); 45862a3f0c9SJez Ng symbols[idx] = createDefined(sym, name, subsec, off); 4596acd3003SFangrui Song } 4606acd3003SFangrui Song } 4616acd3003SFangrui Song 462a379f2c2SGreg McGary OpaqueFile::OpaqueFile(MemoryBufferRef mb, StringRef segName, 463a379f2c2SGreg McGary StringRef sectName) 464a379f2c2SGreg McGary : InputFile(OpaqueKind, mb) { 465a379f2c2SGreg McGary InputSection *isec = make<InputSection>(); 466a379f2c2SGreg McGary isec->file = this; 467a379f2c2SGreg McGary isec->name = sectName.take_front(16); 468a379f2c2SGreg McGary isec->segname = segName.take_front(16); 469a379f2c2SGreg McGary const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 470a379f2c2SGreg McGary isec->data = {buf, mb.getBufferSize()}; 471a379f2c2SGreg McGary subsections.push_back({{0, isec}}); 472a379f2c2SGreg McGary } 473a379f2c2SGreg McGary 474b2f00f24SNico Weber ObjFile::ObjFile(MemoryBufferRef mb, uint32_t modTime, StringRef archiveName) 475b768d57bSJez Ng : InputFile(ObjKind, mb), modTime(modTime) { 476b2f00f24SNico Weber this->archiveName = std::string(archiveName); 477b2f00f24SNico Weber 4786acd3003SFangrui Song auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 4796acd3003SFangrui Song auto *hdr = reinterpret_cast<const mach_header_64 *>(mb.getBufferStart()); 4806acd3003SFangrui Song 4814752cdc9SJez Ng MachO::Architecture arch = 4824752cdc9SJez Ng MachO::getArchitectureFromCpuType(hdr->cputype, hdr->cpusubtype); 4834752cdc9SJez Ng if (arch != config->arch) { 4844752cdc9SJez Ng error(toString(this) + " has architecture " + getArchitectureName(arch) + 4854752cdc9SJez Ng " which is incompatible with target architecture " + 4864752cdc9SJez Ng getArchitectureName(config->arch)); 4874752cdc9SJez Ng return; 4884752cdc9SJez Ng } 489*b63919e1SJez Ng // TODO: check platform too 4904752cdc9SJez Ng 49116b1f6e3SNico Weber if (const load_command *cmd = findCommand(hdr, LC_LINKER_OPTION)) { 49216b1f6e3SNico Weber auto *c = reinterpret_cast<const linker_option_command *>(cmd); 49316b1f6e3SNico Weber StringRef data{reinterpret_cast<const char *>(c + 1), 49416b1f6e3SNico Weber c->cmdsize - sizeof(linker_option_command)}; 49516b1f6e3SNico Weber parseLCLinkerOption(this, c->count, data); 49616b1f6e3SNico Weber } 49716b1f6e3SNico Weber 4986acd3003SFangrui Song if (const load_command *cmd = findCommand(hdr, LC_SEGMENT_64)) { 4996acd3003SFangrui Song auto *c = reinterpret_cast<const segment_command_64 *>(cmd); 5004eb6f485SJez Ng sectionHeaders = ArrayRef<section_64>{ 5016acd3003SFangrui Song reinterpret_cast<const section_64 *>(c + 1), c->nsects}; 5024eb6f485SJez Ng parseSections(sectionHeaders); 5036acd3003SFangrui Song } 5046acd3003SFangrui Song 505060efd24SJez Ng // TODO: Error on missing LC_SYMTAB? 5066acd3003SFangrui Song if (const load_command *cmd = findCommand(hdr, LC_SYMTAB)) { 5076acd3003SFangrui Song auto *c = reinterpret_cast<const symtab_command *>(cmd); 5081e1a3f67SJez Ng ArrayRef<structs::nlist_64> nList( 5091e1a3f67SJez Ng reinterpret_cast<const structs::nlist_64 *>(buf + c->symoff), c->nsyms); 5104eb6f485SJez Ng const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff; 5114eb6f485SJez Ng bool subsectionsViaSymbols = hdr->flags & MH_SUBSECTIONS_VIA_SYMBOLS; 5124eb6f485SJez Ng parseSymbols(nList, strtab, subsectionsViaSymbols); 5136acd3003SFangrui Song } 5146acd3003SFangrui Song 5156acd3003SFangrui Song // The relocations may refer to the symbols, so we parse them after we have 5164eb6f485SJez Ng // parsed all the symbols. 5174eb6f485SJez Ng for (size_t i = 0, n = subsections.size(); i < n; ++i) 518863f7a74SJez Ng if (!subsections[i].empty()) 5194eb6f485SJez Ng parseRelocations(sectionHeaders[i], subsections[i]); 5203fcb0eebSJez Ng 5213fcb0eebSJez Ng parseDebugInfo(); 5223fcb0eebSJez Ng } 5233fcb0eebSJez Ng 5243fcb0eebSJez Ng void ObjFile::parseDebugInfo() { 5253fcb0eebSJez Ng std::unique_ptr<DwarfObject> dObj = DwarfObject::create(this); 5263fcb0eebSJez Ng if (!dObj) 5273fcb0eebSJez Ng return; 5283fcb0eebSJez Ng 5293fcb0eebSJez Ng auto *ctx = make<DWARFContext>( 5303fcb0eebSJez Ng std::move(dObj), "", 531b2f00f24SNico Weber [&](Error err) { 532b2f00f24SNico Weber warn(toString(this) + ": " + toString(std::move(err))); 533b2f00f24SNico Weber }, 5343fcb0eebSJez Ng [&](Error warning) { 535b2f00f24SNico Weber warn(toString(this) + ": " + toString(std::move(warning))); 5363fcb0eebSJez Ng }); 5373fcb0eebSJez Ng 5383fcb0eebSJez Ng // TODO: Since object files can contain a lot of DWARF info, we should verify 5393fcb0eebSJez Ng // that we are parsing just the info we need 5403fcb0eebSJez Ng const DWARFContext::compile_unit_range &units = ctx->compile_units(); 5413fcb0eebSJez Ng auto it = units.begin(); 5423fcb0eebSJez Ng compileUnit = it->get(); 5433fcb0eebSJez Ng assert(std::next(it) == units.end()); 5446acd3003SFangrui Song } 5456acd3003SFangrui Song 5467394460dSJez Ng // The path can point to either a dylib or a .tbd file. 5477394460dSJez Ng static Optional<DylibFile *> loadDylib(StringRef path, DylibFile *umbrella) { 5484af1522aSGreg McGary Optional<MemoryBufferRef> mbref = readFile(path); 5497394460dSJez Ng if (!mbref) { 5507394460dSJez Ng error("could not read dylib file at " + path); 5517394460dSJez Ng return {}; 5527394460dSJez Ng } 55376c36c11SJez Ng return loadDylib(*mbref, umbrella); 5547394460dSJez Ng } 5557394460dSJez Ng 5567394460dSJez Ng // TBD files are parsed into a series of TAPI documents (InterfaceFiles), with 5577394460dSJez Ng // the first document storing child pointers to the rest of them. When we are 5589a2e2de1SVy Nguyen // processing a given TBD file, we store that top-level document in 5599a2e2de1SVy Nguyen // currentTopLevelTapi. When processing re-exports, we search its children for 5609a2e2de1SVy Nguyen // potentially matching documents in the same TBD file. Note that the children 5619a2e2de1SVy Nguyen // themselves don't point to further documents, i.e. this is a two-level tree. 5627394460dSJez Ng // 5637394460dSJez Ng // Re-exports can either refer to on-disk files, or to documents within .tbd 5647394460dSJez Ng // files. 5659a2e2de1SVy Nguyen static Optional<DylibFile *> 5669a2e2de1SVy Nguyen findDylib(StringRef path, DylibFile *umbrella, 5679a2e2de1SVy Nguyen const InterfaceFile *currentTopLevelTapi) { 5687394460dSJez Ng if (path::is_absolute(path, path::Style::posix)) 5697394460dSJez Ng for (StringRef root : config->systemLibraryRoots) 5707394460dSJez Ng if (Optional<std::string> dylibPath = 5717394460dSJez Ng resolveDylibPath((root + path).str())) 5727394460dSJez Ng return loadDylib(*dylibPath, umbrella); 5737394460dSJez Ng 5748174f33dSNico Weber // TODO: Expand @loader_path, @executable_path, @rpath etc, handle -dylib_path 5757394460dSJez Ng 5769c702814SJez Ng if (currentTopLevelTapi) { 5777394460dSJez Ng for (InterfaceFile &child : 5787394460dSJez Ng make_pointee_range(currentTopLevelTapi->documents())) { 5797394460dSJez Ng if (path == child.getInstallName()) 5807394460dSJez Ng return make<DylibFile>(child, umbrella); 5817394460dSJez Ng assert(child.documents().empty()); 5827394460dSJez Ng } 5837394460dSJez Ng } 5847394460dSJez Ng 5857394460dSJez Ng if (Optional<std::string> dylibPath = resolveDylibPath(path)) 5867394460dSJez Ng return loadDylib(*dylibPath, umbrella); 5877394460dSJez Ng 5887394460dSJez Ng return {}; 5897394460dSJez Ng } 5907394460dSJez Ng 5916a348f61SJez Ng // If a re-exported dylib is public (lives in /usr/lib or 5926a348f61SJez Ng // /System/Library/Frameworks), then it is considered implicitly linked: we 5936a348f61SJez Ng // should bind to its symbols directly instead of via the re-exporting umbrella 5946a348f61SJez Ng // library. 5956a348f61SJez Ng static bool isImplicitlyLinked(StringRef path) { 5966a348f61SJez Ng if (!config->implicitDylibs) 5976a348f61SJez Ng return false; 5986a348f61SJez Ng 5993aa8e071SJez Ng if (path::parent_path(path) == "/usr/lib") 6003aa8e071SJez Ng return true; 6013aa8e071SJez Ng 6023aa8e071SJez Ng // Match /System/Library/Frameworks/$FOO.framework/**/$FOO 6033aa8e071SJez Ng if (path.consume_front("/System/Library/Frameworks/")) { 6043aa8e071SJez Ng StringRef frameworkName = path.take_until([](char c) { return c == '.'; }); 6053aa8e071SJez Ng return path::filename(path) == frameworkName; 6063aa8e071SJez Ng } 6073aa8e071SJez Ng 6083aa8e071SJez Ng return false; 6096a348f61SJez Ng } 6106a348f61SJez Ng 6119a2e2de1SVy Nguyen void loadReexport(StringRef path, DylibFile *umbrella, 6129a2e2de1SVy Nguyen const InterfaceFile *currentTopLevelTapi) { 6139a2e2de1SVy Nguyen Optional<DylibFile *> reexport = 6149a2e2de1SVy Nguyen findDylib(path, umbrella, currentTopLevelTapi); 6158174f33dSNico Weber if (!reexport) 6168174f33dSNico Weber error("unable to locate re-export with install name " + path); 6178174f33dSNico Weber else if (isImplicitlyLinked(path)) 618544148aeSJez Ng inputFiles.insert(*reexport); 6196a348f61SJez Ng } 6206a348f61SJez Ng 6215a856f5bSVy Nguyen DylibFile::DylibFile(MemoryBufferRef mb, DylibFile *umbrella, 6225a856f5bSVy Nguyen bool isBundleLoader) 6235a856f5bSVy Nguyen : InputFile(DylibKind, mb), refState(RefState::Unreferenced), 6245a856f5bSVy Nguyen isBundleLoader(isBundleLoader) { 6255a856f5bSVy Nguyen assert(!isBundleLoader || !umbrella); 62687b6fd3eSJez Ng if (umbrella == nullptr) 62787b6fd3eSJez Ng umbrella = this; 62887b6fd3eSJez Ng 629060efd24SJez Ng auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 630060efd24SJez Ng auto *hdr = reinterpret_cast<const mach_header_64 *>(mb.getBufferStart()); 631060efd24SJez Ng 632060efd24SJez Ng // Initialize dylibName. 633060efd24SJez Ng if (const load_command *cmd = findCommand(hdr, LC_ID_DYLIB)) { 634060efd24SJez Ng auto *c = reinterpret_cast<const dylib_command *>(cmd); 635ec88746aSNico Weber currentVersion = read32le(&c->dylib.current_version); 636ec88746aSNico Weber compatibilityVersion = read32le(&c->dylib.compatibility_version); 637060efd24SJez Ng dylibName = reinterpret_cast<const char *>(cmd) + read32le(&c->dylib.name); 6385a856f5bSVy Nguyen } else if (!isBundleLoader) { 6395a856f5bSVy Nguyen // macho_executable and macho_bundle don't have LC_ID_DYLIB, 6405a856f5bSVy Nguyen // so it's OK. 641b2f00f24SNico Weber error("dylib " + toString(this) + " missing LC_ID_DYLIB load command"); 642060efd24SJez Ng return; 643060efd24SJez Ng } 644060efd24SJez Ng 645060efd24SJez Ng // Initialize symbols. 6466a348f61SJez Ng DylibFile *exportingFile = isImplicitlyLinked(dylibName) ? this : umbrella; 6477bbdbacdSJez Ng if (const load_command *cmd = findCommand(hdr, LC_DYLD_INFO_ONLY)) { 6487bbdbacdSJez Ng auto *c = reinterpret_cast<const dyld_info_command *>(cmd); 6497bbdbacdSJez Ng parseTrie(buf + c->export_off, c->export_size, 6507bbdbacdSJez Ng [&](const Twine &name, uint64_t flags) { 65131d58858SJez Ng bool isWeakDef = flags & EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION; 6523c9100fbSJez Ng bool isTlv = flags & EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL; 6536a348f61SJez Ng symbols.push_back(symtab->addDylib( 6546a348f61SJez Ng saver.save(name), exportingFile, isWeakDef, isTlv)); 6557bbdbacdSJez Ng }); 6567bbdbacdSJez Ng } else { 657b2f00f24SNico Weber error("LC_DYLD_INFO_ONLY not found in " + toString(this)); 65887b6fd3eSJez Ng return; 65987b6fd3eSJez Ng } 66087b6fd3eSJez Ng 66187b6fd3eSJez Ng const uint8_t *p = 66287b6fd3eSJez Ng reinterpret_cast<const uint8_t *>(hdr) + sizeof(mach_header_64); 66387b6fd3eSJez Ng for (uint32_t i = 0, n = hdr->ncmds; i < n; ++i) { 66487b6fd3eSJez Ng auto *cmd = reinterpret_cast<const load_command *>(p); 66587b6fd3eSJez Ng p += cmd->cmdsize; 66687b6fd3eSJez Ng 6678174f33dSNico Weber if (!(hdr->flags & MH_NO_REEXPORTED_DYLIBS) && 6688174f33dSNico Weber cmd->cmd == LC_REEXPORT_DYLIB) { 6698174f33dSNico Weber const auto *c = reinterpret_cast<const dylib_command *>(cmd); 67087b6fd3eSJez Ng StringRef reexportPath = 67187b6fd3eSJez Ng reinterpret_cast<const char *>(c) + read32le(&c->dylib.name); 6729a2e2de1SVy Nguyen loadReexport(reexportPath, umbrella, nullptr); 673060efd24SJez Ng } 6748174f33dSNico Weber 6758174f33dSNico Weber // FIXME: What about LC_LOAD_UPWARD_DYLIB, LC_LAZY_LOAD_DYLIB, 6768174f33dSNico Weber // LC_LOAD_WEAK_DYLIB, LC_REEXPORT_DYLIB (..are reexports from dylibs with 6778174f33dSNico Weber // MH_NO_REEXPORTED_DYLIBS loaded for -flat_namespace)? 6788174f33dSNico Weber if (config->namespaceKind == NamespaceKind::flat && 6798174f33dSNico Weber cmd->cmd == LC_LOAD_DYLIB) { 6808174f33dSNico Weber const auto *c = reinterpret_cast<const dylib_command *>(cmd); 6818174f33dSNico Weber StringRef dylibPath = 6828174f33dSNico Weber reinterpret_cast<const char *>(c) + read32le(&c->dylib.name); 6839a2e2de1SVy Nguyen Optional<DylibFile *> dylib = findDylib(dylibPath, umbrella, nullptr); 6848174f33dSNico Weber if (!dylib) 6858174f33dSNico Weber error(Twine("unable to locate library '") + dylibPath + 6868174f33dSNico Weber "' loaded from '" + toString(this) + "' for -flat_namespace"); 6878174f33dSNico Weber } 6888174f33dSNico Weber } 689060efd24SJez Ng } 690060efd24SJez Ng 6915a856f5bSVy Nguyen DylibFile::DylibFile(const InterfaceFile &interface, DylibFile *umbrella, 6925a856f5bSVy Nguyen bool isBundleLoader) 6935a856f5bSVy Nguyen : InputFile(DylibKind, interface), refState(RefState::Unreferenced), 6945a856f5bSVy Nguyen isBundleLoader(isBundleLoader) { 6955a856f5bSVy Nguyen // FIXME: Add test for the missing TBD code path. 6965a856f5bSVy Nguyen 6976fe27b5fSSaleem Abdulrasool if (umbrella == nullptr) 6986fe27b5fSSaleem Abdulrasool umbrella = this; 6996fe27b5fSSaleem Abdulrasool 7004752cdc9SJez Ng if (!interface.getArchitectures().has(config->arch)) { 7014752cdc9SJez Ng error(toString(this) + " is incompatible with " + 7024752cdc9SJez Ng getArchitectureName(config->arch)); 7034752cdc9SJez Ng return; 7044752cdc9SJez Ng } 7054752cdc9SJez Ng 7067e6d6754SJez Ng dylibName = saver.save(interface.getInstallName()); 707ec88746aSNico Weber compatibilityVersion = interface.getCompatibilityVersion().rawValue(); 708ec88746aSNico Weber currentVersion = interface.getCurrentVersion().rawValue(); 7096a348f61SJez Ng DylibFile *exportingFile = isImplicitlyLinked(dylibName) ? this : umbrella; 710a499898eSJez Ng auto addSymbol = [&](const Twine &name) -> void { 7116a348f61SJez Ng symbols.push_back(symtab->addDylib(saver.save(name), exportingFile, 712a499898eSJez Ng /*isWeakDef=*/false, 713a499898eSJez Ng /*isTlv=*/false)); 714a499898eSJez Ng }; 7156fe27b5fSSaleem Abdulrasool // TODO(compnerd) filter out symbols based on the target platform 7163c9100fbSJez Ng // TODO: handle weak defs, thread locals 7177e6d6754SJez Ng for (const auto symbol : interface.symbols()) { 718a499898eSJez Ng if (!symbol->getArchitectures().has(config->arch)) 719a499898eSJez Ng continue; 720a499898eSJez Ng 721a499898eSJez Ng switch (symbol->getKind()) { 722a499898eSJez Ng case SymbolKind::GlobalSymbol: 723a499898eSJez Ng addSymbol(symbol->getName()); 724a499898eSJez Ng break; 725a499898eSJez Ng case SymbolKind::ObjectiveCClass: 726a499898eSJez Ng // XXX ld64 only creates these symbols when -ObjC is passed in. We may 727a499898eSJez Ng // want to emulate that. 728cf918c80SJez Ng addSymbol(objc::klass + symbol->getName()); 729cf918c80SJez Ng addSymbol(objc::metaclass + symbol->getName()); 730a499898eSJez Ng break; 731a499898eSJez Ng case SymbolKind::ObjectiveCClassEHType: 732cf918c80SJez Ng addSymbol(objc::ehtype + symbol->getName()); 733a499898eSJez Ng break; 734a499898eSJez Ng case SymbolKind::ObjectiveCInstanceVariable: 735cf918c80SJez Ng addSymbol(objc::ivar + symbol->getName()); 736a499898eSJez Ng break; 737a499898eSJez Ng } 738a499898eSJez Ng } 7397394460dSJez Ng 7409a2e2de1SVy Nguyen const InterfaceFile *topLevel = 7419a2e2de1SVy Nguyen interface.getParent() == nullptr ? &interface : interface.getParent(); 7427394460dSJez Ng 7437394460dSJez Ng for (InterfaceFileRef intfRef : interface.reexportedLibraries()) 7449a2e2de1SVy Nguyen loadReexport(intfRef.getInstallName(), umbrella, topLevel); 7456fe27b5fSSaleem Abdulrasool } 7466fe27b5fSSaleem Abdulrasool 747e98b441aSJez Ng ArchiveFile::ArchiveFile(std::unique_ptr<object::Archive> &&f) 7482b920ae7SKellie Medlin : InputFile(ArchiveKind, f->getMemoryBufferRef()), file(std::move(f)) { 7492b920ae7SKellie Medlin for (const object::Archive::Symbol &sym : file->symbols()) 7502b920ae7SKellie Medlin symtab->addLazy(sym.getName(), this, sym); 7512b920ae7SKellie Medlin } 7522b920ae7SKellie Medlin 7532b920ae7SKellie Medlin void ArchiveFile::fetch(const object::Archive::Symbol &sym) { 7542b920ae7SKellie Medlin object::Archive::Child c = 7552b920ae7SKellie Medlin CHECK(sym.getMember(), toString(this) + 7562b920ae7SKellie Medlin ": could not get the member for symbol " + 75707ab597bSNico Weber toMachOString(sym)); 7582b920ae7SKellie Medlin 7592b920ae7SKellie Medlin if (!seen.insert(c.getChildOffset()).second) 7602b920ae7SKellie Medlin return; 7612b920ae7SKellie Medlin 7622b920ae7SKellie Medlin MemoryBufferRef mb = 7632b920ae7SKellie Medlin CHECK(c.getMemoryBufferRef(), 7642b920ae7SKellie Medlin toString(this) + 7652b920ae7SKellie Medlin ": could not get the buffer for the member defining symbol " + 76607ab597bSNico Weber toMachOString(sym)); 767b768d57bSJez Ng 768ca634393SNico Weber if (tar && c.getParent()->isThin()) 769ca634393SNico Weber tar->append(relativeToRoot(CHECK(c.getFullName(), this)), mb.getBuffer()); 770ca634393SNico Weber 771b768d57bSJez Ng uint32_t modTime = toTimeT( 772b768d57bSJez Ng CHECK(c.getLastModified(), toString(this) + 773b768d57bSJez Ng ": could not get the modification time " 774b768d57bSJez Ng "for the member defining symbol " + 77507ab597bSNico Weber toMachOString(sym))); 776b768d57bSJez Ng 7773422f3ccSNico Weber // `sym` is owned by a LazySym, which will be replace<>() by make<ObjFile> 7783422f3ccSNico Weber // and become invalid after that call. Copy it to the stack so we can refer 7793422f3ccSNico Weber // to it later. 7803422f3ccSNico Weber const object::Archive::Symbol sym_copy = sym; 7813422f3ccSNico Weber 782f843bb82SJez Ng if (Optional<InputFile *> file = 783f843bb82SJez Ng loadArchiveMember(mb, modTime, getName(), /*objCOnly=*/false)) { 784f843bb82SJez Ng inputFiles.insert(*file); 7853422f3ccSNico Weber // ld64 doesn't demangle sym here even with -demangle. Match that, so 7863422f3ccSNico Weber // intentionally no call to toMachOString() here. 787f843bb82SJez Ng printArchiveMemberLoad(sym_copy.getName(), *file); 788f843bb82SJez Ng } 7892b920ae7SKellie Medlin } 7902b920ae7SKellie Medlin 79184579fc2SJez Ng static macho::Symbol *createBitcodeSymbol(const lto::InputFile::Symbol &objSym, 79284579fc2SJez Ng BitcodeFile &file) { 79384579fc2SJez Ng StringRef name = saver.save(objSym.getName()); 79484579fc2SJez Ng 79584579fc2SJez Ng // TODO: support weak references 79684579fc2SJez Ng if (objSym.isUndefined()) 79784579fc2SJez Ng return symtab->addUndefined(name, &file, /*isWeakRef=*/false); 79884579fc2SJez Ng 79984579fc2SJez Ng assert(!objSym.isCommon() && "TODO: support common symbols in LTO"); 80084579fc2SJez Ng 80184579fc2SJez Ng // TODO: Write a test demonstrating why computing isPrivateExtern before 80284579fc2SJez Ng // LTO compilation is important. 80384579fc2SJez Ng bool isPrivateExtern = false; 80484579fc2SJez Ng switch (objSym.getVisibility()) { 80584579fc2SJez Ng case GlobalValue::HiddenVisibility: 80684579fc2SJez Ng isPrivateExtern = true; 80784579fc2SJez Ng break; 80884579fc2SJez Ng case GlobalValue::ProtectedVisibility: 80984579fc2SJez Ng error(name + " has protected visibility, which is not supported by Mach-O"); 81084579fc2SJez Ng break; 81184579fc2SJez Ng case GlobalValue::DefaultVisibility: 81284579fc2SJez Ng break; 81384579fc2SJez Ng } 81484579fc2SJez Ng 81584579fc2SJez Ng return symtab->addDefined(name, &file, /*isec=*/nullptr, /*value=*/0, 81684579fc2SJez Ng objSym.isWeak(), isPrivateExtern); 81784579fc2SJez Ng } 81884579fc2SJez Ng 81921f83113SJez Ng BitcodeFile::BitcodeFile(MemoryBufferRef mbref) 82021f83113SJez Ng : InputFile(BitcodeKind, mbref) { 82121f83113SJez Ng obj = check(lto::InputFile::create(mbref)); 82284579fc2SJez Ng 82384579fc2SJez Ng // Convert LTO Symbols to LLD Symbols in order to perform resolution. The 82484579fc2SJez Ng // "winning" symbol will then be marked as Prevailing at LTO compilation 82584579fc2SJez Ng // time. 82684579fc2SJez Ng for (const lto::InputFile::Symbol &objSym : obj->symbols()) 82784579fc2SJez Ng symbols.push_back(createBitcodeSymbol(objSym, *this)); 82821f83113SJez Ng } 829