1 //===- InputFiles.cpp -----------------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file contains functions to parse Mach-O object files. In this comment, 10 // we describe the Mach-O file structure and how we parse it. 11 // 12 // Mach-O is not very different from ELF or COFF. The notion of symbols, 13 // sections and relocations exists in Mach-O as it does in ELF and COFF. 14 // 15 // Perhaps the notion that is new to those who know ELF/COFF is "subsections". 16 // In ELF/COFF, sections are an atomic unit of data copied from input files to 17 // output files. When we merge or garbage-collect sections, we treat each 18 // section as an atomic unit. In Mach-O, that's not the case. Sections can 19 // consist of multiple subsections, and subsections are a unit of merging and 20 // garbage-collecting. Therefore, Mach-O's subsections are more similar to 21 // ELF/COFF's sections than Mach-O's sections are. 22 // 23 // A section can have multiple symbols. A symbol that does not have the 24 // N_ALT_ENTRY attribute indicates a beginning of a subsection. Therefore, by 25 // definition, a symbol is always present at the beginning of each subsection. A 26 // symbol with N_ALT_ENTRY attribute does not start a new subsection and can 27 // point to a middle of a subsection. 28 // 29 // The notion of subsections also affects how relocations are represented in 30 // Mach-O. All references within a section need to be explicitly represented as 31 // relocations if they refer to different subsections, because we obviously need 32 // to fix up addresses if subsections are laid out in an output file differently 33 // than they were in object files. To represent that, Mach-O relocations can 34 // refer to an unnamed location via its address. Scattered relocations (those 35 // with the R_SCATTERED bit set) always refer to unnamed locations. 36 // Non-scattered relocations refer to an unnamed location if r_extern is not set 37 // and r_symbolnum is zero. 38 // 39 // Without the above differences, I think you can use your knowledge about ELF 40 // and COFF for Mach-O. 41 // 42 //===----------------------------------------------------------------------===// 43 44 #include "InputFiles.h" 45 #include "Config.h" 46 #include "Driver.h" 47 #include "Dwarf.h" 48 #include "ExportTrie.h" 49 #include "InputSection.h" 50 #include "MachOStructs.h" 51 #include "ObjC.h" 52 #include "OutputSection.h" 53 #include "OutputSegment.h" 54 #include "SymbolTable.h" 55 #include "Symbols.h" 56 #include "SyntheticSections.h" 57 #include "Target.h" 58 59 #include "lld/Common/CommonLinkerContext.h" 60 #include "lld/Common/DWARF.h" 61 #include "lld/Common/Reproduce.h" 62 #include "llvm/ADT/iterator.h" 63 #include "llvm/BinaryFormat/MachO.h" 64 #include "llvm/LTO/LTO.h" 65 #include "llvm/Support/BinaryStreamReader.h" 66 #include "llvm/Support/Endian.h" 67 #include "llvm/Support/MemoryBuffer.h" 68 #include "llvm/Support/Path.h" 69 #include "llvm/Support/TarWriter.h" 70 #include "llvm/Support/TimeProfiler.h" 71 #include "llvm/TextAPI/Architecture.h" 72 #include "llvm/TextAPI/InterfaceFile.h" 73 74 #include <type_traits> 75 76 using namespace llvm; 77 using namespace llvm::MachO; 78 using namespace llvm::support::endian; 79 using namespace llvm::sys; 80 using namespace lld; 81 using namespace lld::macho; 82 83 // Returns "<internal>", "foo.a(bar.o)", or "baz.o". 84 std::string lld::toString(const InputFile *f) { 85 if (!f) 86 return "<internal>"; 87 88 // Multiple dylibs can be defined in one .tbd file. 89 if (auto dylibFile = dyn_cast<DylibFile>(f)) 90 if (f->getName().endswith(".tbd")) 91 return (f->getName() + "(" + dylibFile->installName + ")").str(); 92 93 if (f->archiveName.empty()) 94 return std::string(f->getName()); 95 return (f->archiveName + "(" + path::filename(f->getName()) + ")").str(); 96 } 97 98 std::string lld::toString(const Section &sec) { 99 return (toString(sec.file) + ":(" + sec.name + ")").str(); 100 } 101 102 SetVector<InputFile *> macho::inputFiles; 103 std::unique_ptr<TarWriter> macho::tar; 104 int InputFile::idCount = 0; 105 106 static VersionTuple decodeVersion(uint32_t version) { 107 unsigned major = version >> 16; 108 unsigned minor = (version >> 8) & 0xffu; 109 unsigned subMinor = version & 0xffu; 110 return VersionTuple(major, minor, subMinor); 111 } 112 113 static std::vector<PlatformInfo> getPlatformInfos(const InputFile *input) { 114 if (!isa<ObjFile>(input) && !isa<DylibFile>(input)) 115 return {}; 116 117 const char *hdr = input->mb.getBufferStart(); 118 119 // "Zippered" object files can have multiple LC_BUILD_VERSION load commands. 120 std::vector<PlatformInfo> platformInfos; 121 for (auto *cmd : findCommands<build_version_command>(hdr, LC_BUILD_VERSION)) { 122 PlatformInfo info; 123 info.target.Platform = static_cast<PlatformType>(cmd->platform); 124 info.minimum = decodeVersion(cmd->minos); 125 platformInfos.emplace_back(std::move(info)); 126 } 127 for (auto *cmd : findCommands<version_min_command>( 128 hdr, LC_VERSION_MIN_MACOSX, LC_VERSION_MIN_IPHONEOS, 129 LC_VERSION_MIN_TVOS, LC_VERSION_MIN_WATCHOS)) { 130 PlatformInfo info; 131 switch (cmd->cmd) { 132 case LC_VERSION_MIN_MACOSX: 133 info.target.Platform = PLATFORM_MACOS; 134 break; 135 case LC_VERSION_MIN_IPHONEOS: 136 info.target.Platform = PLATFORM_IOS; 137 break; 138 case LC_VERSION_MIN_TVOS: 139 info.target.Platform = PLATFORM_TVOS; 140 break; 141 case LC_VERSION_MIN_WATCHOS: 142 info.target.Platform = PLATFORM_WATCHOS; 143 break; 144 } 145 info.minimum = decodeVersion(cmd->version); 146 platformInfos.emplace_back(std::move(info)); 147 } 148 149 return platformInfos; 150 } 151 152 static bool checkCompatibility(const InputFile *input) { 153 std::vector<PlatformInfo> platformInfos = getPlatformInfos(input); 154 if (platformInfos.empty()) 155 return true; 156 157 auto it = find_if(platformInfos, [&](const PlatformInfo &info) { 158 return removeSimulator(info.target.Platform) == 159 removeSimulator(config->platform()); 160 }); 161 if (it == platformInfos.end()) { 162 std::string platformNames; 163 raw_string_ostream os(platformNames); 164 interleave( 165 platformInfos, os, 166 [&](const PlatformInfo &info) { 167 os << getPlatformName(info.target.Platform); 168 }, 169 "/"); 170 error(toString(input) + " has platform " + platformNames + 171 Twine(", which is different from target platform ") + 172 getPlatformName(config->platform())); 173 return false; 174 } 175 176 if (it->minimum > config->platformInfo.minimum) 177 warn(toString(input) + " has version " + it->minimum.getAsString() + 178 ", which is newer than target minimum of " + 179 config->platformInfo.minimum.getAsString()); 180 181 return true; 182 } 183 184 // This cache mostly exists to store system libraries (and .tbds) as they're 185 // loaded, rather than the input archives, which are already cached at a higher 186 // level, and other files like the filelist that are only read once. 187 // Theoretically this caching could be more efficient by hoisting it, but that 188 // would require altering many callers to track the state. 189 DenseMap<CachedHashStringRef, MemoryBufferRef> macho::cachedReads; 190 // Open a given file path and return it as a memory-mapped file. 191 Optional<MemoryBufferRef> macho::readFile(StringRef path) { 192 CachedHashStringRef key(path); 193 auto entry = cachedReads.find(key); 194 if (entry != cachedReads.end()) 195 return entry->second; 196 197 ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr = MemoryBuffer::getFile(path); 198 if (std::error_code ec = mbOrErr.getError()) { 199 error("cannot open " + path + ": " + ec.message()); 200 return None; 201 } 202 203 std::unique_ptr<MemoryBuffer> &mb = *mbOrErr; 204 MemoryBufferRef mbref = mb->getMemBufferRef(); 205 make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take mb ownership 206 207 // If this is a regular non-fat file, return it. 208 const char *buf = mbref.getBufferStart(); 209 const auto *hdr = reinterpret_cast<const fat_header *>(buf); 210 if (mbref.getBufferSize() < sizeof(uint32_t) || 211 read32be(&hdr->magic) != FAT_MAGIC) { 212 if (tar) 213 tar->append(relativeToRoot(path), mbref.getBuffer()); 214 return cachedReads[key] = mbref; 215 } 216 217 llvm::BumpPtrAllocator &bAlloc = lld::bAlloc(); 218 219 // Object files and archive files may be fat files, which contain multiple 220 // real files for different CPU ISAs. Here, we search for a file that matches 221 // with the current link target and returns it as a MemoryBufferRef. 222 const auto *arch = reinterpret_cast<const fat_arch *>(buf + sizeof(*hdr)); 223 224 for (uint32_t i = 0, n = read32be(&hdr->nfat_arch); i < n; ++i) { 225 if (reinterpret_cast<const char *>(arch + i + 1) > 226 buf + mbref.getBufferSize()) { 227 error(path + ": fat_arch struct extends beyond end of file"); 228 return None; 229 } 230 231 if (read32be(&arch[i].cputype) != static_cast<uint32_t>(target->cpuType) || 232 read32be(&arch[i].cpusubtype) != target->cpuSubtype) 233 continue; 234 235 uint32_t offset = read32be(&arch[i].offset); 236 uint32_t size = read32be(&arch[i].size); 237 if (offset + size > mbref.getBufferSize()) 238 error(path + ": slice extends beyond end of file"); 239 if (tar) 240 tar->append(relativeToRoot(path), mbref.getBuffer()); 241 return cachedReads[key] = MemoryBufferRef(StringRef(buf + offset, size), 242 path.copy(bAlloc)); 243 } 244 245 error("unable to find matching architecture in " + path); 246 return None; 247 } 248 249 InputFile::InputFile(Kind kind, const InterfaceFile &interface) 250 : id(idCount++), fileKind(kind), name(saver().save(interface.getPath())) {} 251 252 // Some sections comprise of fixed-size records, so instead of splitting them at 253 // symbol boundaries, we split them based on size. Records are distinct from 254 // literals in that they may contain references to other sections, instead of 255 // being leaf nodes in the InputSection graph. 256 // 257 // Note that "record" is a term I came up with. In contrast, "literal" is a term 258 // used by the Mach-O format. 259 static Optional<size_t> getRecordSize(StringRef segname, StringRef name) { 260 if (name == section_names::compactUnwind) { 261 if (segname == segment_names::ld) 262 return target->wordSize == 8 ? 32 : 20; 263 } 264 if (config->icfLevel == ICFLevel::none) 265 return {}; 266 267 if (name == section_names::cfString && segname == segment_names::data) 268 return target->wordSize == 8 ? 32 : 16; 269 if (name == section_names::objcClassRefs && segname == segment_names::data) 270 return target->wordSize; 271 return {}; 272 } 273 274 static Error parseCallGraph(ArrayRef<uint8_t> data, 275 std::vector<CallGraphEntry> &callGraph) { 276 TimeTraceScope timeScope("Parsing call graph section"); 277 BinaryStreamReader reader(data, support::little); 278 while (!reader.empty()) { 279 uint32_t fromIndex, toIndex; 280 uint64_t count; 281 if (Error err = reader.readInteger(fromIndex)) 282 return err; 283 if (Error err = reader.readInteger(toIndex)) 284 return err; 285 if (Error err = reader.readInteger(count)) 286 return err; 287 callGraph.emplace_back(fromIndex, toIndex, count); 288 } 289 return Error::success(); 290 } 291 292 // Parse the sequence of sections within a single LC_SEGMENT(_64). 293 // Split each section into subsections. 294 template <class SectionHeader> 295 void ObjFile::parseSections(ArrayRef<SectionHeader> sectionHeaders) { 296 sections.reserve(sectionHeaders.size()); 297 auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 298 299 for (const SectionHeader &sec : sectionHeaders) { 300 StringRef name = 301 StringRef(sec.sectname, strnlen(sec.sectname, sizeof(sec.sectname))); 302 StringRef segname = 303 StringRef(sec.segname, strnlen(sec.segname, sizeof(sec.segname))); 304 sections.push_back(make<Section>(this, segname, name, sec.flags, sec.addr)); 305 if (sec.align >= 32) { 306 error("alignment " + std::to_string(sec.align) + " of section " + name + 307 " is too large"); 308 continue; 309 } 310 Section §ion = *sections.back(); 311 uint32_t align = 1 << sec.align; 312 ArrayRef<uint8_t> data = {isZeroFill(sec.flags) ? nullptr 313 : buf + sec.offset, 314 static_cast<size_t>(sec.size)}; 315 316 auto splitRecords = [&](int recordSize) -> void { 317 if (data.empty()) 318 return; 319 Subsections &subsections = section.subsections; 320 subsections.reserve(data.size() / recordSize); 321 for (uint64_t off = 0; off < data.size(); off += recordSize) { 322 auto *isec = make<ConcatInputSection>( 323 section, data.slice(off, recordSize), align); 324 subsections.push_back({off, isec}); 325 } 326 }; 327 328 if (sectionType(sec.flags) == S_CSTRING_LITERALS || 329 (config->dedupLiterals && isWordLiteralSection(sec.flags))) { 330 if (sec.nreloc && config->dedupLiterals) 331 fatal(toString(this) + " contains relocations in " + sec.segname + "," + 332 sec.sectname + 333 ", so LLD cannot deduplicate literals. Try re-running without " 334 "--deduplicate-literals."); 335 336 InputSection *isec; 337 if (sectionType(sec.flags) == S_CSTRING_LITERALS) { 338 isec = make<CStringInputSection>(section, data, align); 339 // FIXME: parallelize this? 340 cast<CStringInputSection>(isec)->splitIntoPieces(); 341 } else { 342 isec = make<WordLiteralInputSection>(section, data, align); 343 } 344 section.subsections.push_back({0, isec}); 345 } else if (auto recordSize = getRecordSize(segname, name)) { 346 splitRecords(*recordSize); 347 } else if (segname == segment_names::llvm) { 348 if (config->callGraphProfileSort && name == section_names::cgProfile) 349 checkError(parseCallGraph(data, callGraph)); 350 // ld64 does not appear to emit contents from sections within the __LLVM 351 // segment. Symbols within those sections point to bitcode metadata 352 // instead of actual symbols. Global symbols within those sections could 353 // have the same name without causing duplicate symbol errors. To avoid 354 // spurious duplicate symbol errors, we do not parse these sections. 355 // TODO: Evaluate whether the bitcode metadata is needed. 356 } else { 357 auto *isec = make<ConcatInputSection>(section, data, align); 358 if (isDebugSection(isec->getFlags()) && 359 isec->getSegName() == segment_names::dwarf) { 360 // Instead of emitting DWARF sections, we emit STABS symbols to the 361 // object files that contain them. We filter them out early to avoid 362 // parsing their relocations unnecessarily. 363 debugSections.push_back(isec); 364 } else { 365 section.subsections.push_back({0, isec}); 366 } 367 } 368 } 369 } 370 371 // Find the subsection corresponding to the greatest section offset that is <= 372 // that of the given offset. 373 // 374 // offset: an offset relative to the start of the original InputSection (before 375 // any subsection splitting has occurred). It will be updated to represent the 376 // same location as an offset relative to the start of the containing 377 // subsection. 378 template <class T> 379 static InputSection *findContainingSubsection(const Section §ion, 380 T *offset) { 381 static_assert(std::is_same<uint64_t, T>::value || 382 std::is_same<uint32_t, T>::value, 383 "unexpected type for offset"); 384 auto it = std::prev(llvm::upper_bound( 385 section.subsections, *offset, 386 [](uint64_t value, Subsection subsec) { return value < subsec.offset; })); 387 *offset -= it->offset; 388 return it->isec; 389 } 390 391 // Find a symbol at offset `off` within `isec`. 392 static Defined *findSymbolAtOffset(const ConcatInputSection *isec, 393 uint64_t off) { 394 auto it = llvm::lower_bound(isec->symbols, off, [](Defined *d, uint64_t off) { 395 return d->value < off; 396 }); 397 // The offset should point at the exact address of a symbol (with no addend.) 398 if (it == isec->symbols.end() || (*it)->value != off) { 399 assert(isec->wasCoalesced); 400 return nullptr; 401 } 402 return *it; 403 } 404 405 template <class SectionHeader> 406 static bool validateRelocationInfo(InputFile *file, const SectionHeader &sec, 407 relocation_info rel) { 408 const RelocAttrs &relocAttrs = target->getRelocAttrs(rel.r_type); 409 bool valid = true; 410 auto message = [relocAttrs, file, sec, rel, &valid](const Twine &diagnostic) { 411 valid = false; 412 return (relocAttrs.name + " relocation " + diagnostic + " at offset " + 413 std::to_string(rel.r_address) + " of " + sec.segname + "," + 414 sec.sectname + " in " + toString(file)) 415 .str(); 416 }; 417 418 if (!relocAttrs.hasAttr(RelocAttrBits::LOCAL) && !rel.r_extern) 419 error(message("must be extern")); 420 if (relocAttrs.hasAttr(RelocAttrBits::PCREL) != rel.r_pcrel) 421 error(message(Twine("must ") + (rel.r_pcrel ? "not " : "") + 422 "be PC-relative")); 423 if (isThreadLocalVariables(sec.flags) && 424 !relocAttrs.hasAttr(RelocAttrBits::UNSIGNED)) 425 error(message("not allowed in thread-local section, must be UNSIGNED")); 426 if (rel.r_length < 2 || rel.r_length > 3 || 427 !relocAttrs.hasAttr(static_cast<RelocAttrBits>(1 << rel.r_length))) { 428 static SmallVector<StringRef, 4> widths{"0", "4", "8", "4 or 8"}; 429 error(message("has width " + std::to_string(1 << rel.r_length) + 430 " bytes, but must be " + 431 widths[(static_cast<int>(relocAttrs.bits) >> 2) & 3] + 432 " bytes")); 433 } 434 return valid; 435 } 436 437 template <class SectionHeader> 438 void ObjFile::parseRelocations(ArrayRef<SectionHeader> sectionHeaders, 439 const SectionHeader &sec, 440 Section §ion) { 441 auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 442 ArrayRef<relocation_info> relInfos( 443 reinterpret_cast<const relocation_info *>(buf + sec.reloff), sec.nreloc); 444 445 Subsections &subsections = section.subsections; 446 auto subsecIt = subsections.rbegin(); 447 for (size_t i = 0; i < relInfos.size(); i++) { 448 // Paired relocations serve as Mach-O's method for attaching a 449 // supplemental datum to a primary relocation record. ELF does not 450 // need them because the *_RELOC_RELA records contain the extra 451 // addend field, vs. *_RELOC_REL which omit the addend. 452 // 453 // The {X86_64,ARM64}_RELOC_SUBTRACTOR record holds the subtrahend, 454 // and the paired *_RELOC_UNSIGNED record holds the minuend. The 455 // datum for each is a symbolic address. The result is the offset 456 // between two addresses. 457 // 458 // The ARM64_RELOC_ADDEND record holds the addend, and the paired 459 // ARM64_RELOC_BRANCH26 or ARM64_RELOC_PAGE21/PAGEOFF12 holds the 460 // base symbolic address. 461 // 462 // Note: X86 does not use *_RELOC_ADDEND because it can embed an 463 // addend into the instruction stream. On X86, a relocatable address 464 // field always occupies an entire contiguous sequence of byte(s), 465 // so there is no need to merge opcode bits with address 466 // bits. Therefore, it's easy and convenient to store addends in the 467 // instruction-stream bytes that would otherwise contain zeroes. By 468 // contrast, RISC ISAs such as ARM64 mix opcode bits with with 469 // address bits so that bitwise arithmetic is necessary to extract 470 // and insert them. Storing addends in the instruction stream is 471 // possible, but inconvenient and more costly at link time. 472 473 relocation_info relInfo = relInfos[i]; 474 bool isSubtrahend = 475 target->hasAttr(relInfo.r_type, RelocAttrBits::SUBTRAHEND); 476 if (isSubtrahend && StringRef(sec.sectname) == section_names::ehFrame) { 477 // __TEXT,__eh_frame only has symbols and SUBTRACTOR relocs when ld64 -r 478 // adds local "EH_Frame1" and "func.eh". Ignore them because they have 479 // gone unused by Mac OS since Snow Leopard (10.6), vintage 2009. 480 ++i; 481 continue; 482 } 483 int64_t pairedAddend = 0; 484 if (target->hasAttr(relInfo.r_type, RelocAttrBits::ADDEND)) { 485 pairedAddend = SignExtend64<24>(relInfo.r_symbolnum); 486 relInfo = relInfos[++i]; 487 } 488 assert(i < relInfos.size()); 489 if (!validateRelocationInfo(this, sec, relInfo)) 490 continue; 491 if (relInfo.r_address & R_SCATTERED) 492 fatal("TODO: Scattered relocations not supported"); 493 494 int64_t embeddedAddend = target->getEmbeddedAddend(mb, sec.offset, relInfo); 495 assert(!(embeddedAddend && pairedAddend)); 496 int64_t totalAddend = pairedAddend + embeddedAddend; 497 Reloc r; 498 r.type = relInfo.r_type; 499 r.pcrel = relInfo.r_pcrel; 500 r.length = relInfo.r_length; 501 r.offset = relInfo.r_address; 502 if (relInfo.r_extern) { 503 r.referent = symbols[relInfo.r_symbolnum]; 504 r.addend = isSubtrahend ? 0 : totalAddend; 505 } else { 506 assert(!isSubtrahend); 507 const SectionHeader &referentSecHead = 508 sectionHeaders[relInfo.r_symbolnum - 1]; 509 uint64_t referentOffset; 510 if (relInfo.r_pcrel) { 511 // The implicit addend for pcrel section relocations is the pcrel offset 512 // in terms of the addresses in the input file. Here we adjust it so 513 // that it describes the offset from the start of the referent section. 514 // FIXME This logic was written around x86_64 behavior -- ARM64 doesn't 515 // have pcrel section relocations. We may want to factor this out into 516 // the arch-specific .cpp file. 517 assert(target->hasAttr(r.type, RelocAttrBits::BYTE4)); 518 referentOffset = sec.addr + relInfo.r_address + 4 + totalAddend - 519 referentSecHead.addr; 520 } else { 521 // The addend for a non-pcrel relocation is its absolute address. 522 referentOffset = totalAddend - referentSecHead.addr; 523 } 524 r.referent = findContainingSubsection(*sections[relInfo.r_symbolnum - 1], 525 &referentOffset); 526 r.addend = referentOffset; 527 } 528 529 // Find the subsection that this relocation belongs to. 530 // Though not required by the Mach-O format, clang and gcc seem to emit 531 // relocations in order, so let's take advantage of it. However, ld64 emits 532 // unsorted relocations (in `-r` mode), so we have a fallback for that 533 // uncommon case. 534 InputSection *subsec; 535 while (subsecIt != subsections.rend() && subsecIt->offset > r.offset) 536 ++subsecIt; 537 if (subsecIt == subsections.rend() || 538 subsecIt->offset + subsecIt->isec->getSize() <= r.offset) { 539 subsec = findContainingSubsection(section, &r.offset); 540 // Now that we know the relocs are unsorted, avoid trying the 'fast path' 541 // for the other relocations. 542 subsecIt = subsections.rend(); 543 } else { 544 subsec = subsecIt->isec; 545 r.offset -= subsecIt->offset; 546 } 547 subsec->relocs.push_back(r); 548 549 if (isSubtrahend) { 550 relocation_info minuendInfo = relInfos[++i]; 551 // SUBTRACTOR relocations should always be followed by an UNSIGNED one 552 // attached to the same address. 553 assert(target->hasAttr(minuendInfo.r_type, RelocAttrBits::UNSIGNED) && 554 relInfo.r_address == minuendInfo.r_address); 555 Reloc p; 556 p.type = minuendInfo.r_type; 557 if (minuendInfo.r_extern) { 558 p.referent = symbols[minuendInfo.r_symbolnum]; 559 p.addend = totalAddend; 560 } else { 561 uint64_t referentOffset = 562 totalAddend - sectionHeaders[minuendInfo.r_symbolnum - 1].addr; 563 p.referent = findContainingSubsection( 564 *sections[minuendInfo.r_symbolnum - 1], &referentOffset); 565 p.addend = referentOffset; 566 } 567 subsec->relocs.push_back(p); 568 } 569 } 570 } 571 572 template <class NList> 573 static macho::Symbol *createDefined(const NList &sym, StringRef name, 574 InputSection *isec, uint64_t value, 575 uint64_t size) { 576 // Symbol scope is determined by sym.n_type & (N_EXT | N_PEXT): 577 // N_EXT: Global symbols. These go in the symbol table during the link, 578 // and also in the export table of the output so that the dynamic 579 // linker sees them. 580 // N_EXT | N_PEXT: Linkage unit (think: dylib) scoped. These go in the 581 // symbol table during the link so that duplicates are 582 // either reported (for non-weak symbols) or merged 583 // (for weak symbols), but they do not go in the export 584 // table of the output. 585 // N_PEXT: llvm-mc does not emit these, but `ld -r` (wherein ld64 emits 586 // object files) may produce them. LLD does not yet support -r. 587 // These are translation-unit scoped, identical to the `0` case. 588 // 0: Translation-unit scoped. These are not in the symbol table during 589 // link, and not in the export table of the output either. 590 bool isWeakDefCanBeHidden = 591 (sym.n_desc & (N_WEAK_DEF | N_WEAK_REF)) == (N_WEAK_DEF | N_WEAK_REF); 592 593 if (sym.n_type & N_EXT) { 594 bool isPrivateExtern = sym.n_type & N_PEXT; 595 // lld's behavior for merging symbols is slightly different from ld64: 596 // ld64 picks the winning symbol based on several criteria (see 597 // pickBetweenRegularAtoms() in ld64's SymbolTable.cpp), while lld 598 // just merges metadata and keeps the contents of the first symbol 599 // with that name (see SymbolTable::addDefined). For: 600 // * inline function F in a TU built with -fvisibility-inlines-hidden 601 // * and inline function F in another TU built without that flag 602 // ld64 will pick the one from the file built without 603 // -fvisibility-inlines-hidden. 604 // lld will instead pick the one listed first on the link command line and 605 // give it visibility as if the function was built without 606 // -fvisibility-inlines-hidden. 607 // If both functions have the same contents, this will have the same 608 // behavior. If not, it won't, but the input had an ODR violation in 609 // that case. 610 // 611 // Similarly, merging a symbol 612 // that's isPrivateExtern and not isWeakDefCanBeHidden with one 613 // that's not isPrivateExtern but isWeakDefCanBeHidden technically 614 // should produce one 615 // that's not isPrivateExtern but isWeakDefCanBeHidden. That matters 616 // with ld64's semantics, because it means the non-private-extern 617 // definition will continue to take priority if more private extern 618 // definitions are encountered. With lld's semantics there's no observable 619 // difference between a symbol that's isWeakDefCanBeHidden(autohide) or one 620 // that's privateExtern -- neither makes it into the dynamic symbol table, 621 // unless the autohide symbol is explicitly exported. 622 // But if a symbol is both privateExtern and autohide then it can't 623 // be exported. 624 // So we nullify the autohide flag when privateExtern is present 625 // and promote the symbol to privateExtern when it is not already. 626 if (isWeakDefCanBeHidden && isPrivateExtern) 627 isWeakDefCanBeHidden = false; 628 else if (isWeakDefCanBeHidden) 629 isPrivateExtern = true; 630 return symtab->addDefined( 631 name, isec->getFile(), isec, value, size, sym.n_desc & N_WEAK_DEF, 632 isPrivateExtern, sym.n_desc & N_ARM_THUMB_DEF, 633 sym.n_desc & REFERENCED_DYNAMICALLY, sym.n_desc & N_NO_DEAD_STRIP, 634 isWeakDefCanBeHidden); 635 } 636 assert(!isWeakDefCanBeHidden && 637 "weak_def_can_be_hidden on already-hidden symbol?"); 638 bool includeInSymtab = !name.startswith("l") && !name.startswith("L"); 639 return make<Defined>( 640 name, isec->getFile(), isec, value, size, sym.n_desc & N_WEAK_DEF, 641 /*isExternal=*/false, /*isPrivateExtern=*/false, includeInSymtab, 642 sym.n_desc & N_ARM_THUMB_DEF, sym.n_desc & REFERENCED_DYNAMICALLY, 643 sym.n_desc & N_NO_DEAD_STRIP); 644 } 645 646 // Absolute symbols are defined symbols that do not have an associated 647 // InputSection. They cannot be weak. 648 template <class NList> 649 static macho::Symbol *createAbsolute(const NList &sym, InputFile *file, 650 StringRef name) { 651 if (sym.n_type & N_EXT) { 652 return symtab->addDefined( 653 name, file, nullptr, sym.n_value, /*size=*/0, 654 /*isWeakDef=*/false, sym.n_type & N_PEXT, sym.n_desc & N_ARM_THUMB_DEF, 655 /*isReferencedDynamically=*/false, sym.n_desc & N_NO_DEAD_STRIP, 656 /*isWeakDefCanBeHidden=*/false); 657 } 658 return make<Defined>(name, file, nullptr, sym.n_value, /*size=*/0, 659 /*isWeakDef=*/false, 660 /*isExternal=*/false, /*isPrivateExtern=*/false, 661 /*includeInSymtab=*/true, sym.n_desc & N_ARM_THUMB_DEF, 662 /*isReferencedDynamically=*/false, 663 sym.n_desc & N_NO_DEAD_STRIP); 664 } 665 666 template <class NList> 667 macho::Symbol *ObjFile::parseNonSectionSymbol(const NList &sym, 668 StringRef name) { 669 uint8_t type = sym.n_type & N_TYPE; 670 switch (type) { 671 case N_UNDF: 672 return sym.n_value == 0 673 ? symtab->addUndefined(name, this, sym.n_desc & N_WEAK_REF) 674 : symtab->addCommon(name, this, sym.n_value, 675 1 << GET_COMM_ALIGN(sym.n_desc), 676 sym.n_type & N_PEXT); 677 case N_ABS: 678 return createAbsolute(sym, this, name); 679 case N_PBUD: 680 case N_INDR: 681 error("TODO: support symbols of type " + std::to_string(type)); 682 return nullptr; 683 case N_SECT: 684 llvm_unreachable( 685 "N_SECT symbols should not be passed to parseNonSectionSymbol"); 686 default: 687 llvm_unreachable("invalid symbol type"); 688 } 689 } 690 691 template <class NList> static bool isUndef(const NList &sym) { 692 return (sym.n_type & N_TYPE) == N_UNDF && sym.n_value == 0; 693 } 694 695 template <class LP> 696 void ObjFile::parseSymbols(ArrayRef<typename LP::section> sectionHeaders, 697 ArrayRef<typename LP::nlist> nList, 698 const char *strtab, bool subsectionsViaSymbols) { 699 using NList = typename LP::nlist; 700 701 // Groups indices of the symbols by the sections that contain them. 702 std::vector<std::vector<uint32_t>> symbolsBySection(sections.size()); 703 symbols.resize(nList.size()); 704 SmallVector<unsigned, 32> undefineds; 705 for (uint32_t i = 0; i < nList.size(); ++i) { 706 const NList &sym = nList[i]; 707 708 // Ignore debug symbols for now. 709 // FIXME: may need special handling. 710 if (sym.n_type & N_STAB) 711 continue; 712 713 StringRef name = strtab + sym.n_strx; 714 if ((sym.n_type & N_TYPE) == N_SECT) { 715 Subsections &subsections = sections[sym.n_sect - 1]->subsections; 716 // parseSections() may have chosen not to parse this section. 717 if (subsections.empty()) 718 continue; 719 symbolsBySection[sym.n_sect - 1].push_back(i); 720 } else if (isUndef(sym)) { 721 undefineds.push_back(i); 722 } else { 723 symbols[i] = parseNonSectionSymbol(sym, name); 724 } 725 } 726 727 for (size_t i = 0; i < sections.size(); ++i) { 728 Subsections &subsections = sections[i]->subsections; 729 if (subsections.empty()) 730 continue; 731 if (sections[i]->name == section_names::ehFrame) { 732 // __TEXT,__eh_frame only has symbols and SUBTRACTOR relocs when ld64 -r 733 // adds local "EH_Frame1" and "func.eh". Ignore them because they have 734 // gone unused by Mac OS since Snow Leopard (10.6), vintage 2009. 735 continue; 736 } 737 std::vector<uint32_t> &symbolIndices = symbolsBySection[i]; 738 uint64_t sectionAddr = sectionHeaders[i].addr; 739 uint32_t sectionAlign = 1u << sectionHeaders[i].align; 740 741 // Record-based sections have already been split into subsections during 742 // parseSections(), so we simply need to match Symbols to the corresponding 743 // subsection here. 744 if (getRecordSize(sections[i]->segname, sections[i]->name)) { 745 for (size_t j = 0; j < symbolIndices.size(); ++j) { 746 uint32_t symIndex = symbolIndices[j]; 747 const NList &sym = nList[symIndex]; 748 StringRef name = strtab + sym.n_strx; 749 uint64_t symbolOffset = sym.n_value - sectionAddr; 750 InputSection *isec = 751 findContainingSubsection(*sections[i], &symbolOffset); 752 if (symbolOffset != 0) { 753 error(toString(*sections[i]) + ": symbol " + name + 754 " at misaligned offset"); 755 continue; 756 } 757 symbols[symIndex] = createDefined(sym, name, isec, 0, isec->getSize()); 758 } 759 continue; 760 } 761 762 // Calculate symbol sizes and create subsections by splitting the sections 763 // along symbol boundaries. 764 // We populate subsections by repeatedly splitting the last (highest 765 // address) subsection. 766 llvm::stable_sort(symbolIndices, [&](uint32_t lhs, uint32_t rhs) { 767 return nList[lhs].n_value < nList[rhs].n_value; 768 }); 769 for (size_t j = 0; j < symbolIndices.size(); ++j) { 770 uint32_t symIndex = symbolIndices[j]; 771 const NList &sym = nList[symIndex]; 772 StringRef name = strtab + sym.n_strx; 773 Subsection &subsec = subsections.back(); 774 InputSection *isec = subsec.isec; 775 776 uint64_t subsecAddr = sectionAddr + subsec.offset; 777 size_t symbolOffset = sym.n_value - subsecAddr; 778 uint64_t symbolSize = 779 j + 1 < symbolIndices.size() 780 ? nList[symbolIndices[j + 1]].n_value - sym.n_value 781 : isec->data.size() - symbolOffset; 782 // There are 4 cases where we do not need to create a new subsection: 783 // 1. If the input file does not use subsections-via-symbols. 784 // 2. Multiple symbols at the same address only induce one subsection. 785 // (The symbolOffset == 0 check covers both this case as well as 786 // the first loop iteration.) 787 // 3. Alternative entry points do not induce new subsections. 788 // 4. If we have a literal section (e.g. __cstring and __literal4). 789 if (!subsectionsViaSymbols || symbolOffset == 0 || 790 sym.n_desc & N_ALT_ENTRY || !isa<ConcatInputSection>(isec)) { 791 symbols[symIndex] = 792 createDefined(sym, name, isec, symbolOffset, symbolSize); 793 continue; 794 } 795 auto *concatIsec = cast<ConcatInputSection>(isec); 796 797 auto *nextIsec = make<ConcatInputSection>(*concatIsec); 798 nextIsec->wasCoalesced = false; 799 if (isZeroFill(isec->getFlags())) { 800 // Zero-fill sections have NULL data.data() non-zero data.size() 801 nextIsec->data = {nullptr, isec->data.size() - symbolOffset}; 802 isec->data = {nullptr, symbolOffset}; 803 } else { 804 nextIsec->data = isec->data.slice(symbolOffset); 805 isec->data = isec->data.slice(0, symbolOffset); 806 } 807 808 // By construction, the symbol will be at offset zero in the new 809 // subsection. 810 symbols[symIndex] = 811 createDefined(sym, name, nextIsec, /*value=*/0, symbolSize); 812 // TODO: ld64 appears to preserve the original alignment as well as each 813 // subsection's offset from the last aligned address. We should consider 814 // emulating that behavior. 815 nextIsec->align = MinAlign(sectionAlign, sym.n_value); 816 subsections.push_back({sym.n_value - sectionAddr, nextIsec}); 817 } 818 } 819 820 // Undefined symbols can trigger recursive fetch from Archives due to 821 // LazySymbols. Process defined symbols first so that the relative order 822 // between a defined symbol and an undefined symbol does not change the 823 // symbol resolution behavior. In addition, a set of interconnected symbols 824 // will all be resolved to the same file, instead of being resolved to 825 // different files. 826 for (unsigned i : undefineds) { 827 const NList &sym = nList[i]; 828 StringRef name = strtab + sym.n_strx; 829 symbols[i] = parseNonSectionSymbol(sym, name); 830 } 831 } 832 833 OpaqueFile::OpaqueFile(MemoryBufferRef mb, StringRef segName, 834 StringRef sectName) 835 : InputFile(OpaqueKind, mb) { 836 const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 837 ArrayRef<uint8_t> data = {buf, mb.getBufferSize()}; 838 sections.push_back(make<Section>(/*file=*/this, segName.take_front(16), 839 sectName.take_front(16), 840 /*flags=*/0, /*addr=*/0)); 841 Section §ion = *sections.back(); 842 ConcatInputSection *isec = make<ConcatInputSection>(section, data); 843 isec->live = true; 844 section.subsections.push_back({0, isec}); 845 } 846 847 ObjFile::ObjFile(MemoryBufferRef mb, uint32_t modTime, StringRef archiveName, 848 bool lazy) 849 : InputFile(ObjKind, mb, lazy), modTime(modTime) { 850 this->archiveName = std::string(archiveName); 851 if (lazy) { 852 if (target->wordSize == 8) 853 parseLazy<LP64>(); 854 else 855 parseLazy<ILP32>(); 856 } else { 857 if (target->wordSize == 8) 858 parse<LP64>(); 859 else 860 parse<ILP32>(); 861 } 862 } 863 864 template <class LP> void ObjFile::parse() { 865 using Header = typename LP::mach_header; 866 using SegmentCommand = typename LP::segment_command; 867 using SectionHeader = typename LP::section; 868 using NList = typename LP::nlist; 869 870 auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 871 auto *hdr = reinterpret_cast<const Header *>(mb.getBufferStart()); 872 873 Architecture arch = getArchitectureFromCpuType(hdr->cputype, hdr->cpusubtype); 874 if (arch != config->arch()) { 875 auto msg = config->errorForArchMismatch 876 ? static_cast<void (*)(const Twine &)>(error) 877 : warn; 878 msg(toString(this) + " has architecture " + getArchitectureName(arch) + 879 " which is incompatible with target architecture " + 880 getArchitectureName(config->arch())); 881 return; 882 } 883 884 if (!checkCompatibility(this)) 885 return; 886 887 for (auto *cmd : findCommands<linker_option_command>(hdr, LC_LINKER_OPTION)) { 888 StringRef data{reinterpret_cast<const char *>(cmd + 1), 889 cmd->cmdsize - sizeof(linker_option_command)}; 890 parseLCLinkerOption(this, cmd->count, data); 891 } 892 893 ArrayRef<SectionHeader> sectionHeaders; 894 if (const load_command *cmd = findCommand(hdr, LP::segmentLCType)) { 895 auto *c = reinterpret_cast<const SegmentCommand *>(cmd); 896 sectionHeaders = ArrayRef<SectionHeader>{ 897 reinterpret_cast<const SectionHeader *>(c + 1), c->nsects}; 898 parseSections(sectionHeaders); 899 } 900 901 // TODO: Error on missing LC_SYMTAB? 902 if (const load_command *cmd = findCommand(hdr, LC_SYMTAB)) { 903 auto *c = reinterpret_cast<const symtab_command *>(cmd); 904 ArrayRef<NList> nList(reinterpret_cast<const NList *>(buf + c->symoff), 905 c->nsyms); 906 const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff; 907 bool subsectionsViaSymbols = hdr->flags & MH_SUBSECTIONS_VIA_SYMBOLS; 908 parseSymbols<LP>(sectionHeaders, nList, strtab, subsectionsViaSymbols); 909 } 910 911 // The relocations may refer to the symbols, so we parse them after we have 912 // parsed all the symbols. 913 for (size_t i = 0, n = sections.size(); i < n; ++i) 914 if (!sections[i]->subsections.empty()) 915 parseRelocations(sectionHeaders, sectionHeaders[i], *sections[i]); 916 917 parseDebugInfo(); 918 919 Section *ehFrameSection = nullptr; 920 Section *compactUnwindSection = nullptr; 921 for (Section *sec : sections) { 922 Section **s = StringSwitch<Section **>(sec->name) 923 .Case(section_names::compactUnwind, &compactUnwindSection) 924 .Case(section_names::ehFrame, &ehFrameSection) 925 .Default(nullptr); 926 if (s) 927 *s = sec; 928 } 929 if (compactUnwindSection) 930 registerCompactUnwind(*compactUnwindSection); 931 } 932 933 template <class LP> void ObjFile::parseLazy() { 934 using Header = typename LP::mach_header; 935 using NList = typename LP::nlist; 936 937 auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 938 auto *hdr = reinterpret_cast<const Header *>(mb.getBufferStart()); 939 const load_command *cmd = findCommand(hdr, LC_SYMTAB); 940 if (!cmd) 941 return; 942 auto *c = reinterpret_cast<const symtab_command *>(cmd); 943 ArrayRef<NList> nList(reinterpret_cast<const NList *>(buf + c->symoff), 944 c->nsyms); 945 const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff; 946 symbols.resize(nList.size()); 947 for (auto it : llvm::enumerate(nList)) { 948 const NList &sym = it.value(); 949 if ((sym.n_type & N_EXT) && !isUndef(sym)) { 950 // TODO: Bound checking 951 StringRef name = strtab + sym.n_strx; 952 symbols[it.index()] = symtab->addLazyObject(name, *this); 953 if (!lazy) 954 break; 955 } 956 } 957 } 958 959 void ObjFile::parseDebugInfo() { 960 std::unique_ptr<DwarfObject> dObj = DwarfObject::create(this); 961 if (!dObj) 962 return; 963 964 auto *ctx = make<DWARFContext>( 965 std::move(dObj), "", 966 [&](Error err) { 967 warn(toString(this) + ": " + toString(std::move(err))); 968 }, 969 [&](Error warning) { 970 warn(toString(this) + ": " + toString(std::move(warning))); 971 }); 972 973 // TODO: Since object files can contain a lot of DWARF info, we should verify 974 // that we are parsing just the info we need 975 const DWARFContext::compile_unit_range &units = ctx->compile_units(); 976 // FIXME: There can be more than one compile unit per object file. See 977 // PR48637. 978 auto it = units.begin(); 979 compileUnit = it->get(); 980 } 981 982 ArrayRef<data_in_code_entry> ObjFile::getDataInCode() const { 983 const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 984 const load_command *cmd = findCommand(buf, LC_DATA_IN_CODE); 985 if (!cmd) 986 return {}; 987 const auto *c = reinterpret_cast<const linkedit_data_command *>(cmd); 988 return {reinterpret_cast<const data_in_code_entry *>(buf + c->dataoff), 989 c->datasize / sizeof(data_in_code_entry)}; 990 } 991 992 // Create pointers from symbols to their associated compact unwind entries. 993 void ObjFile::registerCompactUnwind(Section &compactUnwindSection) { 994 for (const Subsection &subsection : compactUnwindSection.subsections) { 995 ConcatInputSection *isec = cast<ConcatInputSection>(subsection.isec); 996 // Hack!! Since each CUE contains a different function address, if ICF 997 // operated naively and compared the entire contents of each CUE, entries 998 // with identical unwind info but belonging to different functions would 999 // never be considered equivalent. To work around this problem, we slice 1000 // away the function address here. (Note that we do not adjust the offsets 1001 // of the corresponding relocations.) We rely on `relocateCompactUnwind()` 1002 // to correctly handle these truncated input sections. 1003 isec->data = isec->data.slice(target->wordSize); 1004 1005 ConcatInputSection *referentIsec; 1006 for (auto it = isec->relocs.begin(); it != isec->relocs.end();) { 1007 Reloc &r = *it; 1008 // CUE::functionAddress is at offset 0. Skip personality & LSDA relocs. 1009 if (r.offset != 0) { 1010 ++it; 1011 continue; 1012 } 1013 uint64_t add = r.addend; 1014 if (auto *sym = cast_or_null<Defined>(r.referent.dyn_cast<Symbol *>())) { 1015 // Check whether the symbol defined in this file is the prevailing one. 1016 // Skip if it is e.g. a weak def that didn't prevail. 1017 if (sym->getFile() != this) { 1018 ++it; 1019 continue; 1020 } 1021 add += sym->value; 1022 referentIsec = cast<ConcatInputSection>(sym->isec); 1023 } else { 1024 referentIsec = 1025 cast<ConcatInputSection>(r.referent.dyn_cast<InputSection *>()); 1026 } 1027 // Unwind info lives in __DATA, and finalization of __TEXT will occur 1028 // before finalization of __DATA. Moreover, the finalization of unwind 1029 // info depends on the exact addresses that it references. So it is safe 1030 // for compact unwind to reference addresses in __TEXT, but not addresses 1031 // in any other segment. 1032 if (referentIsec->getSegName() != segment_names::text) 1033 error(isec->getLocation(r.offset) + " references section " + 1034 referentIsec->getName() + " which is not in segment __TEXT"); 1035 // The functionAddress relocations are typically section relocations. 1036 // However, unwind info operates on a per-symbol basis, so we search for 1037 // the function symbol here. 1038 Defined *d = findSymbolAtOffset(referentIsec, add); 1039 if (!d) { 1040 ++it; 1041 continue; 1042 } 1043 d->unwindEntry = isec; 1044 // Since we've sliced away the functionAddress, we should remove the 1045 // corresponding relocation too. Given that clang emits relocations in 1046 // reverse order of address, this relocation should be at the end of the 1047 // vector for most of our input object files, so this is typically an O(1) 1048 // operation. 1049 it = isec->relocs.erase(it); 1050 } 1051 } 1052 } 1053 1054 // The path can point to either a dylib or a .tbd file. 1055 static DylibFile *loadDylib(StringRef path, DylibFile *umbrella) { 1056 Optional<MemoryBufferRef> mbref = readFile(path); 1057 if (!mbref) { 1058 error("could not read dylib file at " + path); 1059 return nullptr; 1060 } 1061 return loadDylib(*mbref, umbrella); 1062 } 1063 1064 // TBD files are parsed into a series of TAPI documents (InterfaceFiles), with 1065 // the first document storing child pointers to the rest of them. When we are 1066 // processing a given TBD file, we store that top-level document in 1067 // currentTopLevelTapi. When processing re-exports, we search its children for 1068 // potentially matching documents in the same TBD file. Note that the children 1069 // themselves don't point to further documents, i.e. this is a two-level tree. 1070 // 1071 // Re-exports can either refer to on-disk files, or to documents within .tbd 1072 // files. 1073 static DylibFile *findDylib(StringRef path, DylibFile *umbrella, 1074 const InterfaceFile *currentTopLevelTapi) { 1075 // Search order: 1076 // 1. Install name basename in -F / -L directories. 1077 { 1078 StringRef stem = path::stem(path); 1079 SmallString<128> frameworkName; 1080 path::append(frameworkName, path::Style::posix, stem + ".framework", stem); 1081 bool isFramework = path.endswith(frameworkName); 1082 if (isFramework) { 1083 for (StringRef dir : config->frameworkSearchPaths) { 1084 SmallString<128> candidate = dir; 1085 path::append(candidate, frameworkName); 1086 if (Optional<StringRef> dylibPath = resolveDylibPath(candidate.str())) 1087 return loadDylib(*dylibPath, umbrella); 1088 } 1089 } else if (Optional<StringRef> dylibPath = findPathCombination( 1090 stem, config->librarySearchPaths, {".tbd", ".dylib"})) 1091 return loadDylib(*dylibPath, umbrella); 1092 } 1093 1094 // 2. As absolute path. 1095 if (path::is_absolute(path, path::Style::posix)) 1096 for (StringRef root : config->systemLibraryRoots) 1097 if (Optional<StringRef> dylibPath = resolveDylibPath((root + path).str())) 1098 return loadDylib(*dylibPath, umbrella); 1099 1100 // 3. As relative path. 1101 1102 // TODO: Handle -dylib_file 1103 1104 // Replace @executable_path, @loader_path, @rpath prefixes in install name. 1105 SmallString<128> newPath; 1106 if (config->outputType == MH_EXECUTE && 1107 path.consume_front("@executable_path/")) { 1108 // ld64 allows overriding this with the undocumented flag -executable_path. 1109 // lld doesn't currently implement that flag. 1110 // FIXME: Consider using finalOutput instead of outputFile. 1111 path::append(newPath, path::parent_path(config->outputFile), path); 1112 path = newPath; 1113 } else if (path.consume_front("@loader_path/")) { 1114 fs::real_path(umbrella->getName(), newPath); 1115 path::remove_filename(newPath); 1116 path::append(newPath, path); 1117 path = newPath; 1118 } else if (path.startswith("@rpath/")) { 1119 for (StringRef rpath : umbrella->rpaths) { 1120 newPath.clear(); 1121 if (rpath.consume_front("@loader_path/")) { 1122 fs::real_path(umbrella->getName(), newPath); 1123 path::remove_filename(newPath); 1124 } 1125 path::append(newPath, rpath, path.drop_front(strlen("@rpath/"))); 1126 if (Optional<StringRef> dylibPath = resolveDylibPath(newPath.str())) 1127 return loadDylib(*dylibPath, umbrella); 1128 } 1129 } 1130 1131 // FIXME: Should this be further up? 1132 if (currentTopLevelTapi) { 1133 for (InterfaceFile &child : 1134 make_pointee_range(currentTopLevelTapi->documents())) { 1135 assert(child.documents().empty()); 1136 if (path == child.getInstallName()) { 1137 auto file = make<DylibFile>(child, umbrella, /*isBundleLoader=*/false, 1138 /*explicitlyLinked=*/false); 1139 file->parseReexports(child); 1140 return file; 1141 } 1142 } 1143 } 1144 1145 if (Optional<StringRef> dylibPath = resolveDylibPath(path)) 1146 return loadDylib(*dylibPath, umbrella); 1147 1148 return nullptr; 1149 } 1150 1151 // If a re-exported dylib is public (lives in /usr/lib or 1152 // /System/Library/Frameworks), then it is considered implicitly linked: we 1153 // should bind to its symbols directly instead of via the re-exporting umbrella 1154 // library. 1155 static bool isImplicitlyLinked(StringRef path) { 1156 if (!config->implicitDylibs) 1157 return false; 1158 1159 if (path::parent_path(path) == "/usr/lib") 1160 return true; 1161 1162 // Match /System/Library/Frameworks/$FOO.framework/**/$FOO 1163 if (path.consume_front("/System/Library/Frameworks/")) { 1164 StringRef frameworkName = path.take_until([](char c) { return c == '.'; }); 1165 return path::filename(path) == frameworkName; 1166 } 1167 1168 return false; 1169 } 1170 1171 static void loadReexport(StringRef path, DylibFile *umbrella, 1172 const InterfaceFile *currentTopLevelTapi) { 1173 DylibFile *reexport = findDylib(path, umbrella, currentTopLevelTapi); 1174 if (!reexport) 1175 error("unable to locate re-export with install name " + path); 1176 } 1177 1178 DylibFile::DylibFile(MemoryBufferRef mb, DylibFile *umbrella, 1179 bool isBundleLoader, bool explicitlyLinked) 1180 : InputFile(DylibKind, mb), refState(RefState::Unreferenced), 1181 explicitlyLinked(explicitlyLinked), isBundleLoader(isBundleLoader) { 1182 assert(!isBundleLoader || !umbrella); 1183 if (umbrella == nullptr) 1184 umbrella = this; 1185 this->umbrella = umbrella; 1186 1187 auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 1188 auto *hdr = reinterpret_cast<const mach_header *>(mb.getBufferStart()); 1189 1190 // Initialize installName. 1191 if (const load_command *cmd = findCommand(hdr, LC_ID_DYLIB)) { 1192 auto *c = reinterpret_cast<const dylib_command *>(cmd); 1193 currentVersion = read32le(&c->dylib.current_version); 1194 compatibilityVersion = read32le(&c->dylib.compatibility_version); 1195 installName = 1196 reinterpret_cast<const char *>(cmd) + read32le(&c->dylib.name); 1197 } else if (!isBundleLoader) { 1198 // macho_executable and macho_bundle don't have LC_ID_DYLIB, 1199 // so it's OK. 1200 error("dylib " + toString(this) + " missing LC_ID_DYLIB load command"); 1201 return; 1202 } 1203 1204 if (config->printEachFile) 1205 message(toString(this)); 1206 inputFiles.insert(this); 1207 1208 deadStrippable = hdr->flags & MH_DEAD_STRIPPABLE_DYLIB; 1209 1210 if (!checkCompatibility(this)) 1211 return; 1212 1213 checkAppExtensionSafety(hdr->flags & MH_APP_EXTENSION_SAFE); 1214 1215 for (auto *cmd : findCommands<rpath_command>(hdr, LC_RPATH)) { 1216 StringRef rpath{reinterpret_cast<const char *>(cmd) + cmd->path}; 1217 rpaths.push_back(rpath); 1218 } 1219 1220 // Initialize symbols. 1221 exportingFile = isImplicitlyLinked(installName) ? this : this->umbrella; 1222 if (const load_command *cmd = findCommand(hdr, LC_DYLD_INFO_ONLY)) { 1223 auto *c = reinterpret_cast<const dyld_info_command *>(cmd); 1224 struct TrieEntry { 1225 StringRef name; 1226 uint64_t flags; 1227 }; 1228 1229 std::vector<TrieEntry> entries; 1230 // Find all the $ld$* symbols to process first. 1231 parseTrie(buf + c->export_off, c->export_size, 1232 [&](const Twine &name, uint64_t flags) { 1233 StringRef savedName = saver().save(name); 1234 if (handleLDSymbol(savedName)) 1235 return; 1236 entries.push_back({savedName, flags}); 1237 }); 1238 1239 // Process the "normal" symbols. 1240 for (TrieEntry &entry : entries) { 1241 if (exportingFile->hiddenSymbols.contains( 1242 CachedHashStringRef(entry.name))) 1243 continue; 1244 1245 bool isWeakDef = entry.flags & EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION; 1246 bool isTlv = entry.flags & EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL; 1247 1248 symbols.push_back( 1249 symtab->addDylib(entry.name, exportingFile, isWeakDef, isTlv)); 1250 } 1251 1252 } else { 1253 error("LC_DYLD_INFO_ONLY not found in " + toString(this)); 1254 return; 1255 } 1256 } 1257 1258 void DylibFile::parseLoadCommands(MemoryBufferRef mb) { 1259 auto *hdr = reinterpret_cast<const mach_header *>(mb.getBufferStart()); 1260 const uint8_t *p = reinterpret_cast<const uint8_t *>(mb.getBufferStart()) + 1261 target->headerSize; 1262 for (uint32_t i = 0, n = hdr->ncmds; i < n; ++i) { 1263 auto *cmd = reinterpret_cast<const load_command *>(p); 1264 p += cmd->cmdsize; 1265 1266 if (!(hdr->flags & MH_NO_REEXPORTED_DYLIBS) && 1267 cmd->cmd == LC_REEXPORT_DYLIB) { 1268 const auto *c = reinterpret_cast<const dylib_command *>(cmd); 1269 StringRef reexportPath = 1270 reinterpret_cast<const char *>(c) + read32le(&c->dylib.name); 1271 loadReexport(reexportPath, exportingFile, nullptr); 1272 } 1273 1274 // FIXME: What about LC_LOAD_UPWARD_DYLIB, LC_LAZY_LOAD_DYLIB, 1275 // LC_LOAD_WEAK_DYLIB, LC_REEXPORT_DYLIB (..are reexports from dylibs with 1276 // MH_NO_REEXPORTED_DYLIBS loaded for -flat_namespace)? 1277 if (config->namespaceKind == NamespaceKind::flat && 1278 cmd->cmd == LC_LOAD_DYLIB) { 1279 const auto *c = reinterpret_cast<const dylib_command *>(cmd); 1280 StringRef dylibPath = 1281 reinterpret_cast<const char *>(c) + read32le(&c->dylib.name); 1282 DylibFile *dylib = findDylib(dylibPath, umbrella, nullptr); 1283 if (!dylib) 1284 error(Twine("unable to locate library '") + dylibPath + 1285 "' loaded from '" + toString(this) + "' for -flat_namespace"); 1286 } 1287 } 1288 } 1289 1290 // Some versions of Xcode ship with .tbd files that don't have the right 1291 // platform settings. 1292 constexpr std::array<StringRef, 3> skipPlatformChecks{ 1293 "/usr/lib/system/libsystem_kernel.dylib", 1294 "/usr/lib/system/libsystem_platform.dylib", 1295 "/usr/lib/system/libsystem_pthread.dylib"}; 1296 1297 static bool skipPlatformCheckForCatalyst(const InterfaceFile &interface, 1298 bool explicitlyLinked) { 1299 // Catalyst outputs can link against implicitly linked macOS-only libraries. 1300 if (config->platform() != PLATFORM_MACCATALYST || explicitlyLinked) 1301 return false; 1302 return is_contained(interface.targets(), 1303 MachO::Target(config->arch(), PLATFORM_MACOS)); 1304 } 1305 1306 DylibFile::DylibFile(const InterfaceFile &interface, DylibFile *umbrella, 1307 bool isBundleLoader, bool explicitlyLinked) 1308 : InputFile(DylibKind, interface), refState(RefState::Unreferenced), 1309 explicitlyLinked(explicitlyLinked), isBundleLoader(isBundleLoader) { 1310 // FIXME: Add test for the missing TBD code path. 1311 1312 if (umbrella == nullptr) 1313 umbrella = this; 1314 this->umbrella = umbrella; 1315 1316 installName = saver().save(interface.getInstallName()); 1317 compatibilityVersion = interface.getCompatibilityVersion().rawValue(); 1318 currentVersion = interface.getCurrentVersion().rawValue(); 1319 1320 if (config->printEachFile) 1321 message(toString(this)); 1322 inputFiles.insert(this); 1323 1324 if (!is_contained(skipPlatformChecks, installName) && 1325 !is_contained(interface.targets(), config->platformInfo.target) && 1326 !skipPlatformCheckForCatalyst(interface, explicitlyLinked)) { 1327 error(toString(this) + " is incompatible with " + 1328 std::string(config->platformInfo.target)); 1329 return; 1330 } 1331 1332 checkAppExtensionSafety(interface.isApplicationExtensionSafe()); 1333 1334 exportingFile = isImplicitlyLinked(installName) ? this : umbrella; 1335 auto addSymbol = [&](const Twine &name) -> void { 1336 StringRef savedName = saver().save(name); 1337 if (exportingFile->hiddenSymbols.contains(CachedHashStringRef(savedName))) 1338 return; 1339 1340 symbols.push_back(symtab->addDylib(savedName, exportingFile, 1341 /*isWeakDef=*/false, 1342 /*isTlv=*/false)); 1343 }; 1344 1345 std::vector<const llvm::MachO::Symbol *> normalSymbols; 1346 normalSymbols.reserve(interface.symbolsCount()); 1347 for (const auto *symbol : interface.symbols()) { 1348 if (!symbol->getArchitectures().has(config->arch())) 1349 continue; 1350 if (handleLDSymbol(symbol->getName())) 1351 continue; 1352 1353 switch (symbol->getKind()) { 1354 case SymbolKind::GlobalSymbol: // Fallthrough 1355 case SymbolKind::ObjectiveCClass: // Fallthrough 1356 case SymbolKind::ObjectiveCClassEHType: // Fallthrough 1357 case SymbolKind::ObjectiveCInstanceVariable: // Fallthrough 1358 normalSymbols.push_back(symbol); 1359 } 1360 } 1361 1362 // TODO(compnerd) filter out symbols based on the target platform 1363 // TODO: handle weak defs, thread locals 1364 for (const auto *symbol : normalSymbols) { 1365 switch (symbol->getKind()) { 1366 case SymbolKind::GlobalSymbol: 1367 addSymbol(symbol->getName()); 1368 break; 1369 case SymbolKind::ObjectiveCClass: 1370 // XXX ld64 only creates these symbols when -ObjC is passed in. We may 1371 // want to emulate that. 1372 addSymbol(objc::klass + symbol->getName()); 1373 addSymbol(objc::metaclass + symbol->getName()); 1374 break; 1375 case SymbolKind::ObjectiveCClassEHType: 1376 addSymbol(objc::ehtype + symbol->getName()); 1377 break; 1378 case SymbolKind::ObjectiveCInstanceVariable: 1379 addSymbol(objc::ivar + symbol->getName()); 1380 break; 1381 } 1382 } 1383 } 1384 1385 void DylibFile::parseReexports(const InterfaceFile &interface) { 1386 const InterfaceFile *topLevel = 1387 interface.getParent() == nullptr ? &interface : interface.getParent(); 1388 for (const InterfaceFileRef &intfRef : interface.reexportedLibraries()) { 1389 InterfaceFile::const_target_range targets = intfRef.targets(); 1390 if (is_contained(skipPlatformChecks, intfRef.getInstallName()) || 1391 is_contained(targets, config->platformInfo.target)) 1392 loadReexport(intfRef.getInstallName(), exportingFile, topLevel); 1393 } 1394 } 1395 1396 // $ld$ symbols modify the properties/behavior of the library (e.g. its install 1397 // name, compatibility version or hide/add symbols) for specific target 1398 // versions. 1399 bool DylibFile::handleLDSymbol(StringRef originalName) { 1400 if (!originalName.startswith("$ld$")) 1401 return false; 1402 1403 StringRef action; 1404 StringRef name; 1405 std::tie(action, name) = originalName.drop_front(strlen("$ld$")).split('$'); 1406 if (action == "previous") 1407 handleLDPreviousSymbol(name, originalName); 1408 else if (action == "install_name") 1409 handleLDInstallNameSymbol(name, originalName); 1410 else if (action == "hide") 1411 handleLDHideSymbol(name, originalName); 1412 return true; 1413 } 1414 1415 void DylibFile::handleLDPreviousSymbol(StringRef name, StringRef originalName) { 1416 // originalName: $ld$ previous $ <installname> $ <compatversion> $ 1417 // <platformstr> $ <startversion> $ <endversion> $ <symbol-name> $ 1418 StringRef installName; 1419 StringRef compatVersion; 1420 StringRef platformStr; 1421 StringRef startVersion; 1422 StringRef endVersion; 1423 StringRef symbolName; 1424 StringRef rest; 1425 1426 std::tie(installName, name) = name.split('$'); 1427 std::tie(compatVersion, name) = name.split('$'); 1428 std::tie(platformStr, name) = name.split('$'); 1429 std::tie(startVersion, name) = name.split('$'); 1430 std::tie(endVersion, name) = name.split('$'); 1431 std::tie(symbolName, rest) = name.split('$'); 1432 // TODO: ld64 contains some logic for non-empty symbolName as well. 1433 if (!symbolName.empty()) 1434 return; 1435 unsigned platform; 1436 if (platformStr.getAsInteger(10, platform) || 1437 platform != static_cast<unsigned>(config->platform())) 1438 return; 1439 1440 VersionTuple start; 1441 if (start.tryParse(startVersion)) { 1442 warn("failed to parse start version, symbol '" + originalName + 1443 "' ignored"); 1444 return; 1445 } 1446 VersionTuple end; 1447 if (end.tryParse(endVersion)) { 1448 warn("failed to parse end version, symbol '" + originalName + "' ignored"); 1449 return; 1450 } 1451 if (config->platformInfo.minimum < start || 1452 config->platformInfo.minimum >= end) 1453 return; 1454 1455 this->installName = saver().save(installName); 1456 1457 if (!compatVersion.empty()) { 1458 VersionTuple cVersion; 1459 if (cVersion.tryParse(compatVersion)) { 1460 warn("failed to parse compatibility version, symbol '" + originalName + 1461 "' ignored"); 1462 return; 1463 } 1464 compatibilityVersion = encodeVersion(cVersion); 1465 } 1466 } 1467 1468 void DylibFile::handleLDInstallNameSymbol(StringRef name, 1469 StringRef originalName) { 1470 // originalName: $ld$ install_name $ os<version> $ install_name 1471 StringRef condition, installName; 1472 std::tie(condition, installName) = name.split('$'); 1473 VersionTuple version; 1474 if (!condition.consume_front("os") || version.tryParse(condition)) 1475 warn("failed to parse os version, symbol '" + originalName + "' ignored"); 1476 else if (version == config->platformInfo.minimum) 1477 this->installName = saver().save(installName); 1478 } 1479 1480 void DylibFile::handleLDHideSymbol(StringRef name, StringRef originalName) { 1481 StringRef symbolName; 1482 bool shouldHide = true; 1483 if (name.startswith("os")) { 1484 // If it's hidden based on versions. 1485 name = name.drop_front(2); 1486 StringRef minVersion; 1487 std::tie(minVersion, symbolName) = name.split('$'); 1488 VersionTuple versionTup; 1489 if (versionTup.tryParse(minVersion)) { 1490 warn("Failed to parse hidden version, symbol `" + originalName + 1491 "` ignored."); 1492 return; 1493 } 1494 shouldHide = versionTup == config->platformInfo.minimum; 1495 } else { 1496 symbolName = name; 1497 } 1498 1499 if (shouldHide) 1500 exportingFile->hiddenSymbols.insert(CachedHashStringRef(symbolName)); 1501 } 1502 1503 void DylibFile::checkAppExtensionSafety(bool dylibIsAppExtensionSafe) const { 1504 if (config->applicationExtension && !dylibIsAppExtensionSafe) 1505 warn("using '-application_extension' with unsafe dylib: " + toString(this)); 1506 } 1507 1508 ArchiveFile::ArchiveFile(std::unique_ptr<object::Archive> &&f) 1509 : InputFile(ArchiveKind, f->getMemoryBufferRef()), file(std::move(f)) {} 1510 1511 void ArchiveFile::addLazySymbols() { 1512 for (const object::Archive::Symbol &sym : file->symbols()) 1513 symtab->addLazyArchive(sym.getName(), this, sym); 1514 } 1515 1516 static Expected<InputFile *> loadArchiveMember(MemoryBufferRef mb, 1517 uint32_t modTime, 1518 StringRef archiveName, 1519 uint64_t offsetInArchive) { 1520 if (config->zeroModTime) 1521 modTime = 0; 1522 1523 switch (identify_magic(mb.getBuffer())) { 1524 case file_magic::macho_object: 1525 return make<ObjFile>(mb, modTime, archiveName); 1526 case file_magic::bitcode: 1527 return make<BitcodeFile>(mb, archiveName, offsetInArchive); 1528 default: 1529 return createStringError(inconvertibleErrorCode(), 1530 mb.getBufferIdentifier() + 1531 " has unhandled file type"); 1532 } 1533 } 1534 1535 Error ArchiveFile::fetch(const object::Archive::Child &c, StringRef reason) { 1536 if (!seen.insert(c.getChildOffset()).second) 1537 return Error::success(); 1538 1539 Expected<MemoryBufferRef> mb = c.getMemoryBufferRef(); 1540 if (!mb) 1541 return mb.takeError(); 1542 1543 // Thin archives refer to .o files, so --reproduce needs the .o files too. 1544 if (tar && c.getParent()->isThin()) 1545 tar->append(relativeToRoot(CHECK(c.getFullName(), this)), mb->getBuffer()); 1546 1547 Expected<TimePoint<std::chrono::seconds>> modTime = c.getLastModified(); 1548 if (!modTime) 1549 return modTime.takeError(); 1550 1551 Expected<InputFile *> file = 1552 loadArchiveMember(*mb, toTimeT(*modTime), getName(), c.getChildOffset()); 1553 1554 if (!file) 1555 return file.takeError(); 1556 1557 inputFiles.insert(*file); 1558 printArchiveMemberLoad(reason, *file); 1559 return Error::success(); 1560 } 1561 1562 void ArchiveFile::fetch(const object::Archive::Symbol &sym) { 1563 object::Archive::Child c = 1564 CHECK(sym.getMember(), toString(this) + 1565 ": could not get the member defining symbol " + 1566 toMachOString(sym)); 1567 1568 // `sym` is owned by a LazySym, which will be replace<>()d by make<ObjFile> 1569 // and become invalid after that call. Copy it to the stack so we can refer 1570 // to it later. 1571 const object::Archive::Symbol symCopy = sym; 1572 1573 // ld64 doesn't demangle sym here even with -demangle. 1574 // Match that: intentionally don't call toMachOString(). 1575 if (Error e = fetch(c, symCopy.getName())) 1576 error(toString(this) + ": could not get the member defining symbol " + 1577 toMachOString(symCopy) + ": " + toString(std::move(e))); 1578 } 1579 1580 static macho::Symbol *createBitcodeSymbol(const lto::InputFile::Symbol &objSym, 1581 BitcodeFile &file) { 1582 StringRef name = saver().save(objSym.getName()); 1583 1584 if (objSym.isUndefined()) 1585 return symtab->addUndefined(name, &file, /*isWeakRef=*/objSym.isWeak()); 1586 1587 // TODO: Write a test demonstrating why computing isPrivateExtern before 1588 // LTO compilation is important. 1589 bool isPrivateExtern = false; 1590 switch (objSym.getVisibility()) { 1591 case GlobalValue::HiddenVisibility: 1592 isPrivateExtern = true; 1593 break; 1594 case GlobalValue::ProtectedVisibility: 1595 error(name + " has protected visibility, which is not supported by Mach-O"); 1596 break; 1597 case GlobalValue::DefaultVisibility: 1598 break; 1599 } 1600 isPrivateExtern = isPrivateExtern || objSym.canBeOmittedFromSymbolTable(); 1601 1602 if (objSym.isCommon()) 1603 return symtab->addCommon(name, &file, objSym.getCommonSize(), 1604 objSym.getCommonAlignment(), isPrivateExtern); 1605 1606 return symtab->addDefined(name, &file, /*isec=*/nullptr, /*value=*/0, 1607 /*size=*/0, objSym.isWeak(), isPrivateExtern, 1608 /*isThumb=*/false, 1609 /*isReferencedDynamically=*/false, 1610 /*noDeadStrip=*/false, 1611 /*isWeakDefCanBeHidden=*/false); 1612 } 1613 1614 BitcodeFile::BitcodeFile(MemoryBufferRef mb, StringRef archiveName, 1615 uint64_t offsetInArchive, bool lazy) 1616 : InputFile(BitcodeKind, mb, lazy) { 1617 this->archiveName = std::string(archiveName); 1618 std::string path = mb.getBufferIdentifier().str(); 1619 // ThinLTO assumes that all MemoryBufferRefs given to it have a unique 1620 // name. If two members with the same name are provided, this causes a 1621 // collision and ThinLTO can't proceed. 1622 // So, we append the archive name to disambiguate two members with the same 1623 // name from multiple different archives, and offset within the archive to 1624 // disambiguate two members of the same name from a single archive. 1625 MemoryBufferRef mbref(mb.getBuffer(), 1626 saver().save(archiveName.empty() 1627 ? path 1628 : archiveName + 1629 sys::path::filename(path) + 1630 utostr(offsetInArchive))); 1631 1632 obj = check(lto::InputFile::create(mbref)); 1633 if (lazy) 1634 parseLazy(); 1635 else 1636 parse(); 1637 } 1638 1639 void BitcodeFile::parse() { 1640 // Convert LTO Symbols to LLD Symbols in order to perform resolution. The 1641 // "winning" symbol will then be marked as Prevailing at LTO compilation 1642 // time. 1643 symbols.clear(); 1644 for (const lto::InputFile::Symbol &objSym : obj->symbols()) 1645 symbols.push_back(createBitcodeSymbol(objSym, *this)); 1646 } 1647 1648 void BitcodeFile::parseLazy() { 1649 symbols.resize(obj->symbols().size()); 1650 for (auto it : llvm::enumerate(obj->symbols())) { 1651 const lto::InputFile::Symbol &objSym = it.value(); 1652 if (!objSym.isUndefined()) { 1653 symbols[it.index()] = 1654 symtab->addLazyObject(saver().save(objSym.getName()), *this); 1655 if (!lazy) 1656 break; 1657 } 1658 } 1659 } 1660 1661 void macho::extract(InputFile &file, StringRef reason) { 1662 assert(file.lazy); 1663 file.lazy = false; 1664 printArchiveMemberLoad(reason, &file); 1665 if (auto *bitcode = dyn_cast<BitcodeFile>(&file)) { 1666 bitcode->parse(); 1667 } else { 1668 auto &f = cast<ObjFile>(file); 1669 if (target->wordSize == 8) 1670 f.parse<LP64>(); 1671 else 1672 f.parse<ILP32>(); 1673 } 1674 } 1675 1676 template void ObjFile::parse<LP64>(); 1677