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 "EhFrame.h" 49 #include "ExportTrie.h" 50 #include "InputSection.h" 51 #include "MachOStructs.h" 52 #include "ObjC.h" 53 #include "OutputSection.h" 54 #include "OutputSegment.h" 55 #include "SymbolTable.h" 56 #include "Symbols.h" 57 #include "SyntheticSections.h" 58 #include "Target.h" 59 60 #include "lld/Common/CommonLinkerContext.h" 61 #include "lld/Common/DWARF.h" 62 #include "lld/Common/Reproduce.h" 63 #include "llvm/ADT/iterator.h" 64 #include "llvm/BinaryFormat/MachO.h" 65 #include "llvm/LTO/LTO.h" 66 #include "llvm/Support/BinaryStreamReader.h" 67 #include "llvm/Support/Endian.h" 68 #include "llvm/Support/LEB128.h" 69 #include "llvm/Support/MemoryBuffer.h" 70 #include "llvm/Support/Path.h" 71 #include "llvm/Support/TarWriter.h" 72 #include "llvm/Support/TimeProfiler.h" 73 #include "llvm/TextAPI/Architecture.h" 74 #include "llvm/TextAPI/InterfaceFile.h" 75 76 #include <type_traits> 77 78 using namespace llvm; 79 using namespace llvm::MachO; 80 using namespace llvm::support::endian; 81 using namespace llvm::sys; 82 using namespace lld; 83 using namespace lld::macho; 84 85 // Returns "<internal>", "foo.a(bar.o)", or "baz.o". 86 std::string lld::toString(const InputFile *f) { 87 if (!f) 88 return "<internal>"; 89 90 // Multiple dylibs can be defined in one .tbd file. 91 if (auto dylibFile = dyn_cast<DylibFile>(f)) 92 if (f->getName().endswith(".tbd")) 93 return (f->getName() + "(" + dylibFile->installName + ")").str(); 94 95 if (f->archiveName.empty()) 96 return std::string(f->getName()); 97 return (f->archiveName + "(" + path::filename(f->getName()) + ")").str(); 98 } 99 100 std::string lld::toString(const Section &sec) { 101 return (toString(sec.file) + ":(" + sec.name + ")").str(); 102 } 103 104 SetVector<InputFile *> macho::inputFiles; 105 std::unique_ptr<TarWriter> macho::tar; 106 int InputFile::idCount = 0; 107 108 static VersionTuple decodeVersion(uint32_t version) { 109 unsigned major = version >> 16; 110 unsigned minor = (version >> 8) & 0xffu; 111 unsigned subMinor = version & 0xffu; 112 return VersionTuple(major, minor, subMinor); 113 } 114 115 static std::vector<PlatformInfo> getPlatformInfos(const InputFile *input) { 116 if (!isa<ObjFile>(input) && !isa<DylibFile>(input)) 117 return {}; 118 119 const char *hdr = input->mb.getBufferStart(); 120 121 // "Zippered" object files can have multiple LC_BUILD_VERSION load commands. 122 std::vector<PlatformInfo> platformInfos; 123 for (auto *cmd : findCommands<build_version_command>(hdr, LC_BUILD_VERSION)) { 124 PlatformInfo info; 125 info.target.Platform = static_cast<PlatformType>(cmd->platform); 126 info.minimum = decodeVersion(cmd->minos); 127 platformInfos.emplace_back(std::move(info)); 128 } 129 for (auto *cmd : findCommands<version_min_command>( 130 hdr, LC_VERSION_MIN_MACOSX, LC_VERSION_MIN_IPHONEOS, 131 LC_VERSION_MIN_TVOS, LC_VERSION_MIN_WATCHOS)) { 132 PlatformInfo info; 133 switch (cmd->cmd) { 134 case LC_VERSION_MIN_MACOSX: 135 info.target.Platform = PLATFORM_MACOS; 136 break; 137 case LC_VERSION_MIN_IPHONEOS: 138 info.target.Platform = PLATFORM_IOS; 139 break; 140 case LC_VERSION_MIN_TVOS: 141 info.target.Platform = PLATFORM_TVOS; 142 break; 143 case LC_VERSION_MIN_WATCHOS: 144 info.target.Platform = PLATFORM_WATCHOS; 145 break; 146 } 147 info.minimum = decodeVersion(cmd->version); 148 platformInfos.emplace_back(std::move(info)); 149 } 150 151 return platformInfos; 152 } 153 154 static bool checkCompatibility(const InputFile *input) { 155 std::vector<PlatformInfo> platformInfos = getPlatformInfos(input); 156 if (platformInfos.empty()) 157 return true; 158 159 auto it = find_if(platformInfos, [&](const PlatformInfo &info) { 160 return removeSimulator(info.target.Platform) == 161 removeSimulator(config->platform()); 162 }); 163 if (it == platformInfos.end()) { 164 std::string platformNames; 165 raw_string_ostream os(platformNames); 166 interleave( 167 platformInfos, os, 168 [&](const PlatformInfo &info) { 169 os << getPlatformName(info.target.Platform); 170 }, 171 "/"); 172 error(toString(input) + " has platform " + platformNames + 173 Twine(", which is different from target platform ") + 174 getPlatformName(config->platform())); 175 return false; 176 } 177 178 if (it->minimum > config->platformInfo.minimum) 179 warn(toString(input) + " has version " + it->minimum.getAsString() + 180 ", which is newer than target minimum of " + 181 config->platformInfo.minimum.getAsString()); 182 183 return true; 184 } 185 186 // This cache mostly exists to store system libraries (and .tbds) as they're 187 // loaded, rather than the input archives, which are already cached at a higher 188 // level, and other files like the filelist that are only read once. 189 // Theoretically this caching could be more efficient by hoisting it, but that 190 // would require altering many callers to track the state. 191 DenseMap<CachedHashStringRef, MemoryBufferRef> macho::cachedReads; 192 // Open a given file path and return it as a memory-mapped file. 193 Optional<MemoryBufferRef> macho::readFile(StringRef path) { 194 CachedHashStringRef key(path); 195 auto entry = cachedReads.find(key); 196 if (entry != cachedReads.end()) 197 return entry->second; 198 199 ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr = MemoryBuffer::getFile(path); 200 if (std::error_code ec = mbOrErr.getError()) { 201 error("cannot open " + path + ": " + ec.message()); 202 return None; 203 } 204 205 std::unique_ptr<MemoryBuffer> &mb = *mbOrErr; 206 MemoryBufferRef mbref = mb->getMemBufferRef(); 207 make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take mb ownership 208 209 // If this is a regular non-fat file, return it. 210 const char *buf = mbref.getBufferStart(); 211 const auto *hdr = reinterpret_cast<const fat_header *>(buf); 212 if (mbref.getBufferSize() < sizeof(uint32_t) || 213 read32be(&hdr->magic) != FAT_MAGIC) { 214 if (tar) 215 tar->append(relativeToRoot(path), mbref.getBuffer()); 216 return cachedReads[key] = mbref; 217 } 218 219 llvm::BumpPtrAllocator &bAlloc = lld::bAlloc(); 220 221 // Object files and archive files may be fat files, which contain multiple 222 // real files for different CPU ISAs. Here, we search for a file that matches 223 // with the current link target and returns it as a MemoryBufferRef. 224 const auto *arch = reinterpret_cast<const fat_arch *>(buf + sizeof(*hdr)); 225 226 for (uint32_t i = 0, n = read32be(&hdr->nfat_arch); i < n; ++i) { 227 if (reinterpret_cast<const char *>(arch + i + 1) > 228 buf + mbref.getBufferSize()) { 229 error(path + ": fat_arch struct extends beyond end of file"); 230 return None; 231 } 232 233 if (read32be(&arch[i].cputype) != static_cast<uint32_t>(target->cpuType) || 234 read32be(&arch[i].cpusubtype) != target->cpuSubtype) 235 continue; 236 237 uint32_t offset = read32be(&arch[i].offset); 238 uint32_t size = read32be(&arch[i].size); 239 if (offset + size > mbref.getBufferSize()) 240 error(path + ": slice extends beyond end of file"); 241 if (tar) 242 tar->append(relativeToRoot(path), mbref.getBuffer()); 243 return cachedReads[key] = MemoryBufferRef(StringRef(buf + offset, size), 244 path.copy(bAlloc)); 245 } 246 247 error("unable to find matching architecture in " + path); 248 return None; 249 } 250 251 InputFile::InputFile(Kind kind, const InterfaceFile &interface) 252 : id(idCount++), fileKind(kind), name(saver().save(interface.getPath())) {} 253 254 // Some sections comprise of fixed-size records, so instead of splitting them at 255 // symbol boundaries, we split them based on size. Records are distinct from 256 // literals in that they may contain references to other sections, instead of 257 // being leaf nodes in the InputSection graph. 258 // 259 // Note that "record" is a term I came up with. In contrast, "literal" is a term 260 // used by the Mach-O format. 261 static Optional<size_t> getRecordSize(StringRef segname, StringRef name) { 262 if (name == section_names::compactUnwind) { 263 if (segname == segment_names::ld) 264 return target->wordSize == 8 ? 32 : 20; 265 } 266 if (config->icfLevel == ICFLevel::none) 267 return {}; 268 269 if (name == section_names::cfString && segname == segment_names::data) 270 return target->wordSize == 8 ? 32 : 16; 271 if (name == section_names::objcClassRefs && segname == segment_names::data) 272 return target->wordSize; 273 return {}; 274 } 275 276 static Error parseCallGraph(ArrayRef<uint8_t> data, 277 std::vector<CallGraphEntry> &callGraph) { 278 TimeTraceScope timeScope("Parsing call graph section"); 279 BinaryStreamReader reader(data, support::little); 280 while (!reader.empty()) { 281 uint32_t fromIndex, toIndex; 282 uint64_t count; 283 if (Error err = reader.readInteger(fromIndex)) 284 return err; 285 if (Error err = reader.readInteger(toIndex)) 286 return err; 287 if (Error err = reader.readInteger(count)) 288 return err; 289 callGraph.emplace_back(fromIndex, toIndex, count); 290 } 291 return Error::success(); 292 } 293 294 // Parse the sequence of sections within a single LC_SEGMENT(_64). 295 // Split each section into subsections. 296 template <class SectionHeader> 297 void ObjFile::parseSections(ArrayRef<SectionHeader> sectionHeaders) { 298 sections.reserve(sectionHeaders.size()); 299 auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 300 301 for (const SectionHeader &sec : sectionHeaders) { 302 StringRef name = 303 StringRef(sec.sectname, strnlen(sec.sectname, sizeof(sec.sectname))); 304 StringRef segname = 305 StringRef(sec.segname, strnlen(sec.segname, sizeof(sec.segname))); 306 sections.push_back(make<Section>(this, segname, name, sec.flags, sec.addr)); 307 if (sec.align >= 32) { 308 error("alignment " + std::to_string(sec.align) + " of section " + name + 309 " is too large"); 310 continue; 311 } 312 Section §ion = *sections.back(); 313 uint32_t align = 1 << sec.align; 314 ArrayRef<uint8_t> data = {isZeroFill(sec.flags) ? nullptr 315 : buf + sec.offset, 316 static_cast<size_t>(sec.size)}; 317 318 auto splitRecords = [&](int recordSize) -> void { 319 if (data.empty()) 320 return; 321 Subsections &subsections = section.subsections; 322 subsections.reserve(data.size() / recordSize); 323 for (uint64_t off = 0; off < data.size(); off += recordSize) { 324 auto *isec = make<ConcatInputSection>( 325 section, data.slice(off, recordSize), align); 326 subsections.push_back({off, isec}); 327 } 328 section.doneSplitting = true; 329 }; 330 331 if (sectionType(sec.flags) == S_CSTRING_LITERALS || 332 (config->dedupLiterals && isWordLiteralSection(sec.flags))) { 333 if (sec.nreloc && config->dedupLiterals) 334 fatal(toString(this) + " contains relocations in " + sec.segname + "," + 335 sec.sectname + 336 ", so LLD cannot deduplicate literals. Try re-running without " 337 "--deduplicate-literals."); 338 339 InputSection *isec; 340 if (sectionType(sec.flags) == S_CSTRING_LITERALS) { 341 isec = make<CStringInputSection>(section, data, align); 342 // FIXME: parallelize this? 343 cast<CStringInputSection>(isec)->splitIntoPieces(); 344 } else { 345 isec = make<WordLiteralInputSection>(section, data, align); 346 } 347 section.subsections.push_back({0, isec}); 348 } else if (auto recordSize = getRecordSize(segname, name)) { 349 splitRecords(*recordSize); 350 } else if (name == section_names::ehFrame && 351 segname == segment_names::text) { 352 splitEhFrames(data, *sections.back()); 353 } else if (segname == segment_names::llvm) { 354 if (config->callGraphProfileSort && name == section_names::cgProfile) 355 checkError(parseCallGraph(data, callGraph)); 356 // ld64 does not appear to emit contents from sections within the __LLVM 357 // segment. Symbols within those sections point to bitcode metadata 358 // instead of actual symbols. Global symbols within those sections could 359 // have the same name without causing duplicate symbol errors. To avoid 360 // spurious duplicate symbol errors, we do not parse these sections. 361 // TODO: Evaluate whether the bitcode metadata is needed. 362 } else { 363 if (name == section_names::addrSig) 364 addrSigSection = sections.back(); 365 366 auto *isec = make<ConcatInputSection>(section, data, align); 367 if (isDebugSection(isec->getFlags()) && 368 isec->getSegName() == segment_names::dwarf) { 369 // Instead of emitting DWARF sections, we emit STABS symbols to the 370 // object files that contain them. We filter them out early to avoid 371 // parsing their relocations unnecessarily. 372 debugSections.push_back(isec); 373 } else { 374 section.subsections.push_back({0, isec}); 375 } 376 } 377 } 378 } 379 380 void ObjFile::splitEhFrames(ArrayRef<uint8_t> data, Section &ehFrameSection) { 381 EhReader reader(this, data, /*dataOff=*/0, target->wordSize); 382 size_t off = 0; 383 while (off < reader.size()) { 384 uint64_t frameOff = off; 385 uint64_t length = reader.readLength(&off); 386 if (length == 0) 387 break; 388 uint64_t fullLength = length + (off - frameOff); 389 off += length; 390 // We hard-code an alignment of 1 here because we don't actually want our 391 // EH frames to be aligned to the section alignment. EH frame decoders don't 392 // expect this alignment. Moreover, each EH frame must start where the 393 // previous one ends, and where it ends is indicated by the length field. 394 // Unless we update the length field (troublesome), we should keep the 395 // alignment to 1. 396 // Note that we still want to preserve the alignment of the overall section, 397 // just not of the individual EH frames. 398 ehFrameSection.subsections.push_back( 399 {frameOff, make<ConcatInputSection>(ehFrameSection, 400 data.slice(frameOff, fullLength), 401 /*align=*/1)}); 402 } 403 ehFrameSection.doneSplitting = true; 404 } 405 406 template <class T> 407 static Section *findContainingSection(const std::vector<Section *> §ions, 408 T *offset) { 409 static_assert(std::is_same<uint64_t, T>::value || 410 std::is_same<uint32_t, T>::value, 411 "unexpected type for offset"); 412 auto it = std::prev(llvm::upper_bound( 413 sections, *offset, 414 [](uint64_t value, const Section *sec) { return value < sec->addr; })); 415 *offset -= (*it)->addr; 416 return *it; 417 } 418 419 // Find the subsection corresponding to the greatest section offset that is <= 420 // that of the given offset. 421 // 422 // offset: an offset relative to the start of the original InputSection (before 423 // any subsection splitting has occurred). It will be updated to represent the 424 // same location as an offset relative to the start of the containing 425 // subsection. 426 template <class T> 427 static InputSection *findContainingSubsection(const Section §ion, 428 T *offset) { 429 static_assert(std::is_same<uint64_t, T>::value || 430 std::is_same<uint32_t, T>::value, 431 "unexpected type for offset"); 432 auto it = std::prev(llvm::upper_bound( 433 section.subsections, *offset, 434 [](uint64_t value, Subsection subsec) { return value < subsec.offset; })); 435 *offset -= it->offset; 436 return it->isec; 437 } 438 439 // Find a symbol at offset `off` within `isec`. 440 static Defined *findSymbolAtOffset(const ConcatInputSection *isec, 441 uint64_t off) { 442 auto it = llvm::lower_bound(isec->symbols, off, [](Defined *d, uint64_t off) { 443 return d->value < off; 444 }); 445 // The offset should point at the exact address of a symbol (with no addend.) 446 if (it == isec->symbols.end() || (*it)->value != off) { 447 assert(isec->wasCoalesced); 448 return nullptr; 449 } 450 return *it; 451 } 452 453 // Linker optimization hints mark a sequence of instructions used for 454 // synthesizing an address which that be transformed into a faster sequence. The 455 // transformations depend on conditions that are determined at link time, like 456 // the distance to the referenced symbol or its alignment. 457 // 458 // Each hint has a type and refers to 2 or 3 instructions. Each of those 459 // instructions must have a corresponding relocation. After addresses have been 460 // finalized and relocations have been performed, we check if the requirements 461 // hold, and perform the optimizations if they do. 462 // 463 // Similar linker relaxations exist for ELF as well, with the difference being 464 // that the explicit marking allows for the relaxation of non-consecutive 465 // relocations too. 466 // 467 // The specific types of hints are documented in Arch/ARM64.cpp 468 void ObjFile::parseOptimizationHints(ArrayRef<uint8_t> data) { 469 auto expectedArgCount = [](uint8_t type) { 470 switch (type) { 471 case LOH_ARM64_ADRP_ADRP: 472 case LOH_ARM64_ADRP_LDR: 473 case LOH_ARM64_ADRP_ADD: 474 case LOH_ARM64_ADRP_LDR_GOT: 475 return 2; 476 case LOH_ARM64_ADRP_ADD_LDR: 477 case LOH_ARM64_ADRP_ADD_STR: 478 case LOH_ARM64_ADRP_LDR_GOT_LDR: 479 case LOH_ARM64_ADRP_LDR_GOT_STR: 480 return 3; 481 } 482 return -1; 483 }; 484 485 // Each hint contains at least 4 ULEB128-encoded fields, so in the worst case, 486 // there are data.size() / 4 LOHs. It's a huge overestimation though, as 487 // offsets are unlikely to fall in the 0-127 byte range, so we pre-allocate 488 // half as much. 489 optimizationHints.reserve(data.size() / 8); 490 491 for (const uint8_t *p = data.begin(); p < data.end();) { 492 const ptrdiff_t inputOffset = p - data.begin(); 493 unsigned int n = 0; 494 uint8_t type = decodeULEB128(p, &n, data.end()); 495 p += n; 496 497 // An entry of type 0 terminates the list. 498 if (type == 0) 499 break; 500 501 int expectedCount = expectedArgCount(type); 502 if (LLVM_UNLIKELY(expectedCount == -1)) { 503 error("Linker optimization hint at offset " + Twine(inputOffset) + 504 " has unknown type " + Twine(type)); 505 return; 506 } 507 508 uint8_t argCount = decodeULEB128(p, &n, data.end()); 509 p += n; 510 511 if (LLVM_UNLIKELY(argCount != expectedCount)) { 512 error("Linker optimization hint at offset " + Twine(inputOffset) + 513 " has " + Twine(argCount) + " arguments instead of the expected " + 514 Twine(expectedCount)); 515 return; 516 } 517 518 uint64_t offset0 = decodeULEB128(p, &n, data.end()); 519 p += n; 520 521 int16_t delta[2]; 522 for (int i = 0; i < argCount - 1; ++i) { 523 uint64_t address = decodeULEB128(p, &n, data.end()); 524 p += n; 525 int64_t d = address - offset0; 526 if (LLVM_UNLIKELY(d > std::numeric_limits<int16_t>::max() || 527 d < std::numeric_limits<int16_t>::min())) { 528 error("Linker optimization hint at offset " + Twine(inputOffset) + 529 " has addresses too far apart"); 530 return; 531 } 532 delta[i] = d; 533 } 534 535 optimizationHints.push_back({offset0, {delta[0], delta[1]}, type}); 536 } 537 538 // We sort the per-object vector of optimization hints so each section only 539 // needs to hold an ArrayRef to a contiguous range of hints. 540 llvm::sort(optimizationHints, 541 [](const OptimizationHint &a, const OptimizationHint &b) { 542 return a.offset0 < b.offset0; 543 }); 544 545 auto section = sections.begin(); 546 auto subsection = (*section)->subsections.begin(); 547 uint64_t subsectionBase = 0; 548 uint64_t subsectionEnd = 0; 549 550 auto updateAddr = [&]() { 551 subsectionBase = (*section)->addr + subsection->offset; 552 subsectionEnd = subsectionBase + subsection->isec->getSize(); 553 }; 554 555 auto advanceSubsection = [&]() { 556 if (section == sections.end()) 557 return; 558 ++subsection; 559 if (subsection == (*section)->subsections.end()) { 560 ++section; 561 if (section == sections.end()) 562 return; 563 subsection = (*section)->subsections.begin(); 564 } 565 }; 566 567 updateAddr(); 568 auto hintStart = optimizationHints.begin(); 569 for (auto hintEnd = hintStart, end = optimizationHints.end(); hintEnd != end; 570 ++hintEnd) { 571 if (hintEnd->offset0 >= subsectionEnd) { 572 subsection->isec->optimizationHints = 573 ArrayRef<OptimizationHint>(&*hintStart, hintEnd - hintStart); 574 575 hintStart = hintEnd; 576 while (hintStart->offset0 >= subsectionEnd) { 577 advanceSubsection(); 578 if (section == sections.end()) 579 break; 580 updateAddr(); 581 } 582 } 583 584 hintEnd->offset0 -= subsectionBase; 585 for (int i = 0, count = expectedArgCount(hintEnd->type); i < count - 1; 586 ++i) { 587 if (LLVM_UNLIKELY( 588 hintEnd->delta[i] < -static_cast<int64_t>(hintEnd->offset0) || 589 hintEnd->delta[i] >= 590 static_cast<int64_t>(subsectionEnd - hintEnd->offset0))) { 591 error("Linker optimization hint spans multiple sections"); 592 return; 593 } 594 } 595 } 596 if (section != sections.end()) 597 subsection->isec->optimizationHints = ArrayRef<OptimizationHint>( 598 &*hintStart, optimizationHints.end() - hintStart); 599 } 600 601 template <class SectionHeader> 602 static bool validateRelocationInfo(InputFile *file, const SectionHeader &sec, 603 relocation_info rel) { 604 const RelocAttrs &relocAttrs = target->getRelocAttrs(rel.r_type); 605 bool valid = true; 606 auto message = [relocAttrs, file, sec, rel, &valid](const Twine &diagnostic) { 607 valid = false; 608 return (relocAttrs.name + " relocation " + diagnostic + " at offset " + 609 std::to_string(rel.r_address) + " of " + sec.segname + "," + 610 sec.sectname + " in " + toString(file)) 611 .str(); 612 }; 613 614 if (!relocAttrs.hasAttr(RelocAttrBits::LOCAL) && !rel.r_extern) 615 error(message("must be extern")); 616 if (relocAttrs.hasAttr(RelocAttrBits::PCREL) != rel.r_pcrel) 617 error(message(Twine("must ") + (rel.r_pcrel ? "not " : "") + 618 "be PC-relative")); 619 if (isThreadLocalVariables(sec.flags) && 620 !relocAttrs.hasAttr(RelocAttrBits::UNSIGNED)) 621 error(message("not allowed in thread-local section, must be UNSIGNED")); 622 if (rel.r_length < 2 || rel.r_length > 3 || 623 !relocAttrs.hasAttr(static_cast<RelocAttrBits>(1 << rel.r_length))) { 624 static SmallVector<StringRef, 4> widths{"0", "4", "8", "4 or 8"}; 625 error(message("has width " + std::to_string(1 << rel.r_length) + 626 " bytes, but must be " + 627 widths[(static_cast<int>(relocAttrs.bits) >> 2) & 3] + 628 " bytes")); 629 } 630 return valid; 631 } 632 633 template <class SectionHeader> 634 void ObjFile::parseRelocations(ArrayRef<SectionHeader> sectionHeaders, 635 const SectionHeader &sec, Section §ion) { 636 auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 637 ArrayRef<relocation_info> relInfos( 638 reinterpret_cast<const relocation_info *>(buf + sec.reloff), sec.nreloc); 639 640 Subsections &subsections = section.subsections; 641 auto subsecIt = subsections.rbegin(); 642 for (size_t i = 0; i < relInfos.size(); i++) { 643 // Paired relocations serve as Mach-O's method for attaching a 644 // supplemental datum to a primary relocation record. ELF does not 645 // need them because the *_RELOC_RELA records contain the extra 646 // addend field, vs. *_RELOC_REL which omit the addend. 647 // 648 // The {X86_64,ARM64}_RELOC_SUBTRACTOR record holds the subtrahend, 649 // and the paired *_RELOC_UNSIGNED record holds the minuend. The 650 // datum for each is a symbolic address. The result is the offset 651 // between two addresses. 652 // 653 // The ARM64_RELOC_ADDEND record holds the addend, and the paired 654 // ARM64_RELOC_BRANCH26 or ARM64_RELOC_PAGE21/PAGEOFF12 holds the 655 // base symbolic address. 656 // 657 // Note: X86 does not use *_RELOC_ADDEND because it can embed an 658 // addend into the instruction stream. On X86, a relocatable address 659 // field always occupies an entire contiguous sequence of byte(s), 660 // so there is no need to merge opcode bits with address 661 // bits. Therefore, it's easy and convenient to store addends in the 662 // instruction-stream bytes that would otherwise contain zeroes. By 663 // contrast, RISC ISAs such as ARM64 mix opcode bits with with 664 // address bits so that bitwise arithmetic is necessary to extract 665 // and insert them. Storing addends in the instruction stream is 666 // possible, but inconvenient and more costly at link time. 667 668 relocation_info relInfo = relInfos[i]; 669 bool isSubtrahend = 670 target->hasAttr(relInfo.r_type, RelocAttrBits::SUBTRAHEND); 671 int64_t pairedAddend = 0; 672 if (target->hasAttr(relInfo.r_type, RelocAttrBits::ADDEND)) { 673 pairedAddend = SignExtend64<24>(relInfo.r_symbolnum); 674 relInfo = relInfos[++i]; 675 } 676 assert(i < relInfos.size()); 677 if (!validateRelocationInfo(this, sec, relInfo)) 678 continue; 679 if (relInfo.r_address & R_SCATTERED) 680 fatal("TODO: Scattered relocations not supported"); 681 682 int64_t embeddedAddend = target->getEmbeddedAddend(mb, sec.offset, relInfo); 683 assert(!(embeddedAddend && pairedAddend)); 684 int64_t totalAddend = pairedAddend + embeddedAddend; 685 Reloc r; 686 r.type = relInfo.r_type; 687 r.pcrel = relInfo.r_pcrel; 688 r.length = relInfo.r_length; 689 r.offset = relInfo.r_address; 690 if (relInfo.r_extern) { 691 r.referent = symbols[relInfo.r_symbolnum]; 692 r.addend = isSubtrahend ? 0 : totalAddend; 693 } else { 694 assert(!isSubtrahend); 695 const SectionHeader &referentSecHead = 696 sectionHeaders[relInfo.r_symbolnum - 1]; 697 uint64_t referentOffset; 698 if (relInfo.r_pcrel) { 699 // The implicit addend for pcrel section relocations is the pcrel offset 700 // in terms of the addresses in the input file. Here we adjust it so 701 // that it describes the offset from the start of the referent section. 702 // FIXME This logic was written around x86_64 behavior -- ARM64 doesn't 703 // have pcrel section relocations. We may want to factor this out into 704 // the arch-specific .cpp file. 705 assert(target->hasAttr(r.type, RelocAttrBits::BYTE4)); 706 referentOffset = sec.addr + relInfo.r_address + 4 + totalAddend - 707 referentSecHead.addr; 708 } else { 709 // The addend for a non-pcrel relocation is its absolute address. 710 referentOffset = totalAddend - referentSecHead.addr; 711 } 712 r.referent = findContainingSubsection(*sections[relInfo.r_symbolnum - 1], 713 &referentOffset); 714 r.addend = referentOffset; 715 } 716 717 // Find the subsection that this relocation belongs to. 718 // Though not required by the Mach-O format, clang and gcc seem to emit 719 // relocations in order, so let's take advantage of it. However, ld64 emits 720 // unsorted relocations (in `-r` mode), so we have a fallback for that 721 // uncommon case. 722 InputSection *subsec; 723 while (subsecIt != subsections.rend() && subsecIt->offset > r.offset) 724 ++subsecIt; 725 if (subsecIt == subsections.rend() || 726 subsecIt->offset + subsecIt->isec->getSize() <= r.offset) { 727 subsec = findContainingSubsection(section, &r.offset); 728 // Now that we know the relocs are unsorted, avoid trying the 'fast path' 729 // for the other relocations. 730 subsecIt = subsections.rend(); 731 } else { 732 subsec = subsecIt->isec; 733 r.offset -= subsecIt->offset; 734 } 735 subsec->relocs.push_back(r); 736 737 if (isSubtrahend) { 738 relocation_info minuendInfo = relInfos[++i]; 739 // SUBTRACTOR relocations should always be followed by an UNSIGNED one 740 // attached to the same address. 741 assert(target->hasAttr(minuendInfo.r_type, RelocAttrBits::UNSIGNED) && 742 relInfo.r_address == minuendInfo.r_address); 743 Reloc p; 744 p.type = minuendInfo.r_type; 745 if (minuendInfo.r_extern) { 746 p.referent = symbols[minuendInfo.r_symbolnum]; 747 p.addend = totalAddend; 748 } else { 749 uint64_t referentOffset = 750 totalAddend - sectionHeaders[minuendInfo.r_symbolnum - 1].addr; 751 p.referent = findContainingSubsection( 752 *sections[minuendInfo.r_symbolnum - 1], &referentOffset); 753 p.addend = referentOffset; 754 } 755 subsec->relocs.push_back(p); 756 } 757 } 758 } 759 760 template <class NList> 761 static macho::Symbol *createDefined(const NList &sym, StringRef name, 762 InputSection *isec, uint64_t value, 763 uint64_t size) { 764 // Symbol scope is determined by sym.n_type & (N_EXT | N_PEXT): 765 // N_EXT: Global symbols. These go in the symbol table during the link, 766 // and also in the export table of the output so that the dynamic 767 // linker sees them. 768 // N_EXT | N_PEXT: Linkage unit (think: dylib) scoped. These go in the 769 // symbol table during the link so that duplicates are 770 // either reported (for non-weak symbols) or merged 771 // (for weak symbols), but they do not go in the export 772 // table of the output. 773 // N_PEXT: llvm-mc does not emit these, but `ld -r` (wherein ld64 emits 774 // object files) may produce them. LLD does not yet support -r. 775 // These are translation-unit scoped, identical to the `0` case. 776 // 0: Translation-unit scoped. These are not in the symbol table during 777 // link, and not in the export table of the output either. 778 bool isWeakDefCanBeHidden = 779 (sym.n_desc & (N_WEAK_DEF | N_WEAK_REF)) == (N_WEAK_DEF | N_WEAK_REF); 780 781 if (sym.n_type & N_EXT) { 782 bool isPrivateExtern = sym.n_type & N_PEXT; 783 // lld's behavior for merging symbols is slightly different from ld64: 784 // ld64 picks the winning symbol based on several criteria (see 785 // pickBetweenRegularAtoms() in ld64's SymbolTable.cpp), while lld 786 // just merges metadata and keeps the contents of the first symbol 787 // with that name (see SymbolTable::addDefined). For: 788 // * inline function F in a TU built with -fvisibility-inlines-hidden 789 // * and inline function F in another TU built without that flag 790 // ld64 will pick the one from the file built without 791 // -fvisibility-inlines-hidden. 792 // lld will instead pick the one listed first on the link command line and 793 // give it visibility as if the function was built without 794 // -fvisibility-inlines-hidden. 795 // If both functions have the same contents, this will have the same 796 // behavior. If not, it won't, but the input had an ODR violation in 797 // that case. 798 // 799 // Similarly, merging a symbol 800 // that's isPrivateExtern and not isWeakDefCanBeHidden with one 801 // that's not isPrivateExtern but isWeakDefCanBeHidden technically 802 // should produce one 803 // that's not isPrivateExtern but isWeakDefCanBeHidden. That matters 804 // with ld64's semantics, because it means the non-private-extern 805 // definition will continue to take priority if more private extern 806 // definitions are encountered. With lld's semantics there's no observable 807 // difference between a symbol that's isWeakDefCanBeHidden(autohide) or one 808 // that's privateExtern -- neither makes it into the dynamic symbol table, 809 // unless the autohide symbol is explicitly exported. 810 // But if a symbol is both privateExtern and autohide then it can't 811 // be exported. 812 // So we nullify the autohide flag when privateExtern is present 813 // and promote the symbol to privateExtern when it is not already. 814 if (isWeakDefCanBeHidden && isPrivateExtern) 815 isWeakDefCanBeHidden = false; 816 else if (isWeakDefCanBeHidden) 817 isPrivateExtern = true; 818 return symtab->addDefined( 819 name, isec->getFile(), isec, value, size, sym.n_desc & N_WEAK_DEF, 820 isPrivateExtern, sym.n_desc & N_ARM_THUMB_DEF, 821 sym.n_desc & REFERENCED_DYNAMICALLY, sym.n_desc & N_NO_DEAD_STRIP, 822 isWeakDefCanBeHidden); 823 } 824 assert(!isWeakDefCanBeHidden && 825 "weak_def_can_be_hidden on already-hidden symbol?"); 826 bool includeInSymtab = 827 !name.startswith("l") && !name.startswith("L") && !isEhFrameSection(isec); 828 return make<Defined>( 829 name, isec->getFile(), isec, value, size, sym.n_desc & N_WEAK_DEF, 830 /*isExternal=*/false, /*isPrivateExtern=*/false, includeInSymtab, 831 sym.n_desc & N_ARM_THUMB_DEF, sym.n_desc & REFERENCED_DYNAMICALLY, 832 sym.n_desc & N_NO_DEAD_STRIP); 833 } 834 835 // Absolute symbols are defined symbols that do not have an associated 836 // InputSection. They cannot be weak. 837 template <class NList> 838 static macho::Symbol *createAbsolute(const NList &sym, InputFile *file, 839 StringRef name) { 840 if (sym.n_type & N_EXT) { 841 return symtab->addDefined( 842 name, file, nullptr, sym.n_value, /*size=*/0, 843 /*isWeakDef=*/false, sym.n_type & N_PEXT, sym.n_desc & N_ARM_THUMB_DEF, 844 /*isReferencedDynamically=*/false, sym.n_desc & N_NO_DEAD_STRIP, 845 /*isWeakDefCanBeHidden=*/false); 846 } 847 return make<Defined>(name, file, nullptr, sym.n_value, /*size=*/0, 848 /*isWeakDef=*/false, 849 /*isExternal=*/false, /*isPrivateExtern=*/false, 850 /*includeInSymtab=*/true, sym.n_desc & N_ARM_THUMB_DEF, 851 /*isReferencedDynamically=*/false, 852 sym.n_desc & N_NO_DEAD_STRIP); 853 } 854 855 template <class NList> 856 macho::Symbol *ObjFile::parseNonSectionSymbol(const NList &sym, 857 StringRef name) { 858 uint8_t type = sym.n_type & N_TYPE; 859 switch (type) { 860 case N_UNDF: 861 return sym.n_value == 0 862 ? symtab->addUndefined(name, this, sym.n_desc & N_WEAK_REF) 863 : symtab->addCommon(name, this, sym.n_value, 864 1 << GET_COMM_ALIGN(sym.n_desc), 865 sym.n_type & N_PEXT); 866 case N_ABS: 867 return createAbsolute(sym, this, name); 868 case N_PBUD: 869 case N_INDR: 870 error("TODO: support symbols of type " + std::to_string(type)); 871 return nullptr; 872 case N_SECT: 873 llvm_unreachable( 874 "N_SECT symbols should not be passed to parseNonSectionSymbol"); 875 default: 876 llvm_unreachable("invalid symbol type"); 877 } 878 } 879 880 template <class NList> static bool isUndef(const NList &sym) { 881 return (sym.n_type & N_TYPE) == N_UNDF && sym.n_value == 0; 882 } 883 884 template <class LP> 885 void ObjFile::parseSymbols(ArrayRef<typename LP::section> sectionHeaders, 886 ArrayRef<typename LP::nlist> nList, 887 const char *strtab, bool subsectionsViaSymbols) { 888 using NList = typename LP::nlist; 889 890 // Groups indices of the symbols by the sections that contain them. 891 std::vector<std::vector<uint32_t>> symbolsBySection(sections.size()); 892 symbols.resize(nList.size()); 893 SmallVector<unsigned, 32> undefineds; 894 for (uint32_t i = 0; i < nList.size(); ++i) { 895 const NList &sym = nList[i]; 896 897 // Ignore debug symbols for now. 898 // FIXME: may need special handling. 899 if (sym.n_type & N_STAB) 900 continue; 901 902 StringRef name = strtab + sym.n_strx; 903 if ((sym.n_type & N_TYPE) == N_SECT) { 904 Subsections &subsections = sections[sym.n_sect - 1]->subsections; 905 // parseSections() may have chosen not to parse this section. 906 if (subsections.empty()) 907 continue; 908 symbolsBySection[sym.n_sect - 1].push_back(i); 909 } else if (isUndef(sym)) { 910 undefineds.push_back(i); 911 } else { 912 symbols[i] = parseNonSectionSymbol(sym, name); 913 } 914 } 915 916 for (size_t i = 0; i < sections.size(); ++i) { 917 Subsections &subsections = sections[i]->subsections; 918 if (subsections.empty()) 919 continue; 920 std::vector<uint32_t> &symbolIndices = symbolsBySection[i]; 921 uint64_t sectionAddr = sectionHeaders[i].addr; 922 uint32_t sectionAlign = 1u << sectionHeaders[i].align; 923 924 // Some sections have already been split into subsections during 925 // parseSections(), so we simply need to match Symbols to the corresponding 926 // subsection here. 927 if (sections[i]->doneSplitting) { 928 for (size_t j = 0; j < symbolIndices.size(); ++j) { 929 uint32_t symIndex = symbolIndices[j]; 930 const NList &sym = nList[symIndex]; 931 StringRef name = strtab + sym.n_strx; 932 uint64_t symbolOffset = sym.n_value - sectionAddr; 933 InputSection *isec = 934 findContainingSubsection(*sections[i], &symbolOffset); 935 if (symbolOffset != 0) { 936 error(toString(*sections[i]) + ": symbol " + name + 937 " at misaligned offset"); 938 continue; 939 } 940 symbols[symIndex] = createDefined(sym, name, isec, 0, isec->getSize()); 941 } 942 continue; 943 } 944 sections[i]->doneSplitting = true; 945 946 // Calculate symbol sizes and create subsections by splitting the sections 947 // along symbol boundaries. 948 // We populate subsections by repeatedly splitting the last (highest 949 // address) subsection. 950 llvm::stable_sort(symbolIndices, [&](uint32_t lhs, uint32_t rhs) { 951 return nList[lhs].n_value < nList[rhs].n_value; 952 }); 953 for (size_t j = 0; j < symbolIndices.size(); ++j) { 954 uint32_t symIndex = symbolIndices[j]; 955 const NList &sym = nList[symIndex]; 956 StringRef name = strtab + sym.n_strx; 957 Subsection &subsec = subsections.back(); 958 InputSection *isec = subsec.isec; 959 960 uint64_t subsecAddr = sectionAddr + subsec.offset; 961 size_t symbolOffset = sym.n_value - subsecAddr; 962 uint64_t symbolSize = 963 j + 1 < symbolIndices.size() 964 ? nList[symbolIndices[j + 1]].n_value - sym.n_value 965 : isec->data.size() - symbolOffset; 966 // There are 4 cases where we do not need to create a new subsection: 967 // 1. If the input file does not use subsections-via-symbols. 968 // 2. Multiple symbols at the same address only induce one subsection. 969 // (The symbolOffset == 0 check covers both this case as well as 970 // the first loop iteration.) 971 // 3. Alternative entry points do not induce new subsections. 972 // 4. If we have a literal section (e.g. __cstring and __literal4). 973 if (!subsectionsViaSymbols || symbolOffset == 0 || 974 sym.n_desc & N_ALT_ENTRY || !isa<ConcatInputSection>(isec)) { 975 symbols[symIndex] = 976 createDefined(sym, name, isec, symbolOffset, symbolSize); 977 continue; 978 } 979 auto *concatIsec = cast<ConcatInputSection>(isec); 980 981 auto *nextIsec = make<ConcatInputSection>(*concatIsec); 982 nextIsec->wasCoalesced = false; 983 if (isZeroFill(isec->getFlags())) { 984 // Zero-fill sections have NULL data.data() non-zero data.size() 985 nextIsec->data = {nullptr, isec->data.size() - symbolOffset}; 986 isec->data = {nullptr, symbolOffset}; 987 } else { 988 nextIsec->data = isec->data.slice(symbolOffset); 989 isec->data = isec->data.slice(0, symbolOffset); 990 } 991 992 // By construction, the symbol will be at offset zero in the new 993 // subsection. 994 symbols[symIndex] = 995 createDefined(sym, name, nextIsec, /*value=*/0, symbolSize); 996 // TODO: ld64 appears to preserve the original alignment as well as each 997 // subsection's offset from the last aligned address. We should consider 998 // emulating that behavior. 999 nextIsec->align = MinAlign(sectionAlign, sym.n_value); 1000 subsections.push_back({sym.n_value - sectionAddr, nextIsec}); 1001 } 1002 } 1003 1004 // Undefined symbols can trigger recursive fetch from Archives due to 1005 // LazySymbols. Process defined symbols first so that the relative order 1006 // between a defined symbol and an undefined symbol does not change the 1007 // symbol resolution behavior. In addition, a set of interconnected symbols 1008 // will all be resolved to the same file, instead of being resolved to 1009 // different files. 1010 for (unsigned i : undefineds) { 1011 const NList &sym = nList[i]; 1012 StringRef name = strtab + sym.n_strx; 1013 symbols[i] = parseNonSectionSymbol(sym, name); 1014 } 1015 } 1016 1017 OpaqueFile::OpaqueFile(MemoryBufferRef mb, StringRef segName, 1018 StringRef sectName) 1019 : InputFile(OpaqueKind, mb) { 1020 const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 1021 ArrayRef<uint8_t> data = {buf, mb.getBufferSize()}; 1022 sections.push_back(make<Section>(/*file=*/this, segName.take_front(16), 1023 sectName.take_front(16), 1024 /*flags=*/0, /*addr=*/0)); 1025 Section §ion = *sections.back(); 1026 ConcatInputSection *isec = make<ConcatInputSection>(section, data); 1027 isec->live = true; 1028 section.subsections.push_back({0, isec}); 1029 } 1030 1031 ObjFile::ObjFile(MemoryBufferRef mb, uint32_t modTime, StringRef archiveName, 1032 bool lazy) 1033 : InputFile(ObjKind, mb, lazy), modTime(modTime) { 1034 this->archiveName = std::string(archiveName); 1035 if (lazy) { 1036 if (target->wordSize == 8) 1037 parseLazy<LP64>(); 1038 else 1039 parseLazy<ILP32>(); 1040 } else { 1041 if (target->wordSize == 8) 1042 parse<LP64>(); 1043 else 1044 parse<ILP32>(); 1045 } 1046 } 1047 1048 template <class LP> void ObjFile::parse() { 1049 using Header = typename LP::mach_header; 1050 using SegmentCommand = typename LP::segment_command; 1051 using SectionHeader = typename LP::section; 1052 using NList = typename LP::nlist; 1053 1054 auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 1055 auto *hdr = reinterpret_cast<const Header *>(mb.getBufferStart()); 1056 1057 Architecture arch = getArchitectureFromCpuType(hdr->cputype, hdr->cpusubtype); 1058 if (arch != config->arch()) { 1059 auto msg = config->errorForArchMismatch 1060 ? static_cast<void (*)(const Twine &)>(error) 1061 : warn; 1062 msg(toString(this) + " has architecture " + getArchitectureName(arch) + 1063 " which is incompatible with target architecture " + 1064 getArchitectureName(config->arch())); 1065 return; 1066 } 1067 1068 if (!checkCompatibility(this)) 1069 return; 1070 1071 for (auto *cmd : findCommands<linker_option_command>(hdr, LC_LINKER_OPTION)) { 1072 StringRef data{reinterpret_cast<const char *>(cmd + 1), 1073 cmd->cmdsize - sizeof(linker_option_command)}; 1074 parseLCLinkerOption(this, cmd->count, data); 1075 } 1076 1077 ArrayRef<SectionHeader> sectionHeaders; 1078 if (const load_command *cmd = findCommand(hdr, LP::segmentLCType)) { 1079 auto *c = reinterpret_cast<const SegmentCommand *>(cmd); 1080 sectionHeaders = ArrayRef<SectionHeader>{ 1081 reinterpret_cast<const SectionHeader *>(c + 1), c->nsects}; 1082 parseSections(sectionHeaders); 1083 } 1084 1085 // TODO: Error on missing LC_SYMTAB? 1086 if (const load_command *cmd = findCommand(hdr, LC_SYMTAB)) { 1087 auto *c = reinterpret_cast<const symtab_command *>(cmd); 1088 ArrayRef<NList> nList(reinterpret_cast<const NList *>(buf + c->symoff), 1089 c->nsyms); 1090 const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff; 1091 bool subsectionsViaSymbols = hdr->flags & MH_SUBSECTIONS_VIA_SYMBOLS; 1092 parseSymbols<LP>(sectionHeaders, nList, strtab, subsectionsViaSymbols); 1093 } 1094 1095 // The relocations may refer to the symbols, so we parse them after we have 1096 // parsed all the symbols. 1097 for (size_t i = 0, n = sections.size(); i < n; ++i) 1098 if (!sections[i]->subsections.empty()) 1099 parseRelocations(sectionHeaders, sectionHeaders[i], *sections[i]); 1100 1101 if (!config->ignoreOptimizationHints) 1102 if (auto *cmd = findCommand<linkedit_data_command>( 1103 hdr, LC_LINKER_OPTIMIZATION_HINT)) 1104 parseOptimizationHints({buf + cmd->dataoff, cmd->datasize}); 1105 1106 parseDebugInfo(); 1107 1108 Section *ehFrameSection = nullptr; 1109 Section *compactUnwindSection = nullptr; 1110 for (Section *sec : sections) { 1111 Section **s = StringSwitch<Section **>(sec->name) 1112 .Case(section_names::compactUnwind, &compactUnwindSection) 1113 .Case(section_names::ehFrame, &ehFrameSection) 1114 .Default(nullptr); 1115 if (s) 1116 *s = sec; 1117 } 1118 if (compactUnwindSection) 1119 registerCompactUnwind(*compactUnwindSection); 1120 if (ehFrameSection) 1121 registerEhFrames(*ehFrameSection); 1122 } 1123 1124 template <class LP> void ObjFile::parseLazy() { 1125 using Header = typename LP::mach_header; 1126 using NList = typename LP::nlist; 1127 1128 auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 1129 auto *hdr = reinterpret_cast<const Header *>(mb.getBufferStart()); 1130 const load_command *cmd = findCommand(hdr, LC_SYMTAB); 1131 if (!cmd) 1132 return; 1133 auto *c = reinterpret_cast<const symtab_command *>(cmd); 1134 ArrayRef<NList> nList(reinterpret_cast<const NList *>(buf + c->symoff), 1135 c->nsyms); 1136 const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff; 1137 symbols.resize(nList.size()); 1138 for (auto it : llvm::enumerate(nList)) { 1139 const NList &sym = it.value(); 1140 if ((sym.n_type & N_EXT) && !isUndef(sym)) { 1141 // TODO: Bound checking 1142 StringRef name = strtab + sym.n_strx; 1143 symbols[it.index()] = symtab->addLazyObject(name, *this); 1144 if (!lazy) 1145 break; 1146 } 1147 } 1148 } 1149 1150 void ObjFile::parseDebugInfo() { 1151 std::unique_ptr<DwarfObject> dObj = DwarfObject::create(this); 1152 if (!dObj) 1153 return; 1154 1155 // We do not re-use the context from getDwarf() here as that function 1156 // constructs an expensive DWARFCache object. 1157 auto *ctx = make<DWARFContext>( 1158 std::move(dObj), "", 1159 [&](Error err) { 1160 warn(toString(this) + ": " + toString(std::move(err))); 1161 }, 1162 [&](Error warning) { 1163 warn(toString(this) + ": " + toString(std::move(warning))); 1164 }); 1165 1166 // TODO: Since object files can contain a lot of DWARF info, we should verify 1167 // that we are parsing just the info we need 1168 const DWARFContext::compile_unit_range &units = ctx->compile_units(); 1169 // FIXME: There can be more than one compile unit per object file. See 1170 // PR48637. 1171 auto it = units.begin(); 1172 compileUnit = it != units.end() ? it->get() : nullptr; 1173 } 1174 1175 ArrayRef<data_in_code_entry> ObjFile::getDataInCode() const { 1176 const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 1177 const load_command *cmd = findCommand(buf, LC_DATA_IN_CODE); 1178 if (!cmd) 1179 return {}; 1180 const auto *c = reinterpret_cast<const linkedit_data_command *>(cmd); 1181 return {reinterpret_cast<const data_in_code_entry *>(buf + c->dataoff), 1182 c->datasize / sizeof(data_in_code_entry)}; 1183 } 1184 1185 // Create pointers from symbols to their associated compact unwind entries. 1186 void ObjFile::registerCompactUnwind(Section &compactUnwindSection) { 1187 for (const Subsection &subsection : compactUnwindSection.subsections) { 1188 ConcatInputSection *isec = cast<ConcatInputSection>(subsection.isec); 1189 // Hack!! Each compact unwind entry (CUE) has its UNSIGNED relocations embed 1190 // their addends in its data. Thus if ICF operated naively and compared the 1191 // entire contents of each CUE, entries with identical unwind info but e.g. 1192 // belonging to different functions would never be considered equivalent. To 1193 // work around this problem, we remove some parts of the data containing the 1194 // embedded addends. In particular, we remove the function address and LSDA 1195 // pointers. Since these locations are at the start and end of the entry, 1196 // we can do this using a simple, efficient slice rather than performing a 1197 // copy. We are not losing any information here because the embedded 1198 // addends have already been parsed in the corresponding Reloc structs. 1199 // 1200 // Removing these pointers would not be safe if they were pointers to 1201 // absolute symbols. In that case, there would be no corresponding 1202 // relocation. However, (AFAIK) MC cannot emit references to absolute 1203 // symbols for either the function address or the LSDA. However, it *can* do 1204 // so for the personality pointer, so we are not slicing that field away. 1205 // 1206 // Note that we do not adjust the offsets of the corresponding relocations; 1207 // instead, we rely on `relocateCompactUnwind()` to correctly handle these 1208 // truncated input sections. 1209 isec->data = isec->data.slice(target->wordSize, 8 + target->wordSize); 1210 uint32_t encoding = read32le(isec->data.data() + sizeof(uint32_t)); 1211 // llvm-mc omits CU entries for functions that need DWARF encoding, but 1212 // `ld -r` doesn't. We can ignore them because we will re-synthesize these 1213 // CU entries from the DWARF info during the output phase. 1214 if ((encoding & target->modeDwarfEncoding) == target->modeDwarfEncoding) 1215 continue; 1216 1217 ConcatInputSection *referentIsec; 1218 for (auto it = isec->relocs.begin(); it != isec->relocs.end();) { 1219 Reloc &r = *it; 1220 // CUE::functionAddress is at offset 0. Skip personality & LSDA relocs. 1221 if (r.offset != 0) { 1222 ++it; 1223 continue; 1224 } 1225 uint64_t add = r.addend; 1226 if (auto *sym = cast_or_null<Defined>(r.referent.dyn_cast<Symbol *>())) { 1227 // Check whether the symbol defined in this file is the prevailing one. 1228 // Skip if it is e.g. a weak def that didn't prevail. 1229 if (sym->getFile() != this) { 1230 ++it; 1231 continue; 1232 } 1233 add += sym->value; 1234 referentIsec = cast<ConcatInputSection>(sym->isec); 1235 } else { 1236 referentIsec = 1237 cast<ConcatInputSection>(r.referent.dyn_cast<InputSection *>()); 1238 } 1239 // Unwind info lives in __DATA, and finalization of __TEXT will occur 1240 // before finalization of __DATA. Moreover, the finalization of unwind 1241 // info depends on the exact addresses that it references. So it is safe 1242 // for compact unwind to reference addresses in __TEXT, but not addresses 1243 // in any other segment. 1244 if (referentIsec->getSegName() != segment_names::text) 1245 error(isec->getLocation(r.offset) + " references section " + 1246 referentIsec->getName() + " which is not in segment __TEXT"); 1247 // The functionAddress relocations are typically section relocations. 1248 // However, unwind info operates on a per-symbol basis, so we search for 1249 // the function symbol here. 1250 Defined *d = findSymbolAtOffset(referentIsec, add); 1251 if (!d) { 1252 ++it; 1253 continue; 1254 } 1255 d->unwindEntry = isec; 1256 // Now that the symbol points to the unwind entry, we can remove the reloc 1257 // that points from the unwind entry back to the symbol. 1258 // 1259 // First, the symbol keeps the unwind entry alive (and not vice versa), so 1260 // this keeps dead-stripping simple. 1261 // 1262 // Moreover, it reduces the work that ICF needs to do to figure out if 1263 // functions with unwind info are foldable. 1264 // 1265 // However, this does make it possible for ICF to fold CUEs that point to 1266 // distinct functions (if the CUEs are otherwise identical). 1267 // UnwindInfoSection takes care of this by re-duplicating the CUEs so that 1268 // each one can hold a distinct functionAddress value. 1269 // 1270 // Given that clang emits relocations in reverse order of address, this 1271 // relocation should be at the end of the vector for most of our input 1272 // object files, so this erase() is typically an O(1) operation. 1273 it = isec->relocs.erase(it); 1274 } 1275 } 1276 } 1277 1278 struct CIE { 1279 macho::Symbol *personalitySymbol = nullptr; 1280 bool fdesHaveLsda = false; 1281 bool fdesHaveAug = false; 1282 }; 1283 1284 static CIE parseCIE(const InputSection *isec, const EhReader &reader, 1285 size_t off) { 1286 // Handling the full generality of possible DWARF encodings would be a major 1287 // pain. We instead take advantage of our knowledge of how llvm-mc encodes 1288 // DWARF and handle just that. 1289 constexpr uint8_t expectedPersonalityEnc = 1290 dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_sdata4; 1291 constexpr uint8_t expectedPointerEnc = 1292 dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_absptr; 1293 1294 CIE cie; 1295 uint8_t version = reader.readByte(&off); 1296 if (version != 1 && version != 3) 1297 fatal("Expected CIE version of 1 or 3, got " + Twine(version)); 1298 StringRef aug = reader.readString(&off); 1299 reader.skipLeb128(&off); // skip code alignment 1300 reader.skipLeb128(&off); // skip data alignment 1301 reader.skipLeb128(&off); // skip return address register 1302 reader.skipLeb128(&off); // skip aug data length 1303 uint64_t personalityAddrOff = 0; 1304 for (char c : aug) { 1305 switch (c) { 1306 case 'z': 1307 cie.fdesHaveAug = true; 1308 break; 1309 case 'P': { 1310 uint8_t personalityEnc = reader.readByte(&off); 1311 if (personalityEnc != expectedPersonalityEnc) 1312 reader.failOn(off, "unexpected personality encoding 0x" + 1313 Twine::utohexstr(personalityEnc)); 1314 personalityAddrOff = off; 1315 off += 4; 1316 break; 1317 } 1318 case 'L': { 1319 cie.fdesHaveLsda = true; 1320 uint8_t lsdaEnc = reader.readByte(&off); 1321 if (lsdaEnc != expectedPointerEnc) 1322 reader.failOn(off, "unexpected LSDA encoding 0x" + 1323 Twine::utohexstr(lsdaEnc)); 1324 break; 1325 } 1326 case 'R': { 1327 uint8_t pointerEnc = reader.readByte(&off); 1328 if (pointerEnc != expectedPointerEnc) 1329 reader.failOn(off, "unexpected pointer encoding 0x" + 1330 Twine::utohexstr(pointerEnc)); 1331 break; 1332 } 1333 default: 1334 break; 1335 } 1336 } 1337 if (personalityAddrOff != 0) { 1338 auto personalityRelocIt = 1339 llvm::find_if(isec->relocs, [=](const macho::Reloc &r) { 1340 return r.offset == personalityAddrOff; 1341 }); 1342 if (personalityRelocIt == isec->relocs.end()) 1343 reader.failOn(off, "Failed to locate relocation for personality symbol"); 1344 cie.personalitySymbol = personalityRelocIt->referent.get<macho::Symbol *>(); 1345 } 1346 return cie; 1347 } 1348 1349 // EH frame target addresses may be encoded as pcrel offsets. However, instead 1350 // of using an actual pcrel reloc, ld64 emits subtractor relocations instead. 1351 // This function recovers the target address from the subtractors, essentially 1352 // performing the inverse operation of EhRelocator. 1353 // 1354 // Concretely, we expect our relocations to write the value of `PC - 1355 // target_addr` to `PC`. `PC` itself is denoted by a minuend relocation that 1356 // points to a symbol plus an addend. 1357 // 1358 // It is important that the minuend relocation point to a symbol within the 1359 // same section as the fixup value, since sections may get moved around. 1360 // 1361 // For example, for arm64, llvm-mc emits relocations for the target function 1362 // address like so: 1363 // 1364 // ltmp: 1365 // <CIE start> 1366 // ... 1367 // <CIE end> 1368 // ... multiple FDEs ... 1369 // <FDE start> 1370 // <target function address - (ltmp + pcrel offset)> 1371 // ... 1372 // 1373 // If any of the FDEs in `multiple FDEs` get dead-stripped, then `FDE start` 1374 // will move to an earlier address, and `ltmp + pcrel offset` will no longer 1375 // reflect an accurate pcrel value. To avoid this problem, we "canonicalize" 1376 // our relocation by adding an `EH_Frame` symbol at `FDE start`, and updating 1377 // the reloc to be `target function address - (EH_Frame + new pcrel offset)`. 1378 // 1379 // If `Invert` is set, then we instead expect `target_addr - PC` to be written 1380 // to `PC`. 1381 template <bool Invert = false> 1382 Defined * 1383 targetSymFromCanonicalSubtractor(const InputSection *isec, 1384 std::vector<macho::Reloc>::iterator relocIt) { 1385 macho::Reloc &subtrahend = *relocIt; 1386 macho::Reloc &minuend = *std::next(relocIt); 1387 assert(target->hasAttr(subtrahend.type, RelocAttrBits::SUBTRAHEND)); 1388 assert(target->hasAttr(minuend.type, RelocAttrBits::UNSIGNED)); 1389 // Note: pcSym may *not* be exactly at the PC; there's usually a non-zero 1390 // addend. 1391 auto *pcSym = cast<Defined>(subtrahend.referent.get<macho::Symbol *>()); 1392 Defined *target = 1393 cast_or_null<Defined>(minuend.referent.dyn_cast<macho::Symbol *>()); 1394 if (!pcSym) { 1395 auto *targetIsec = 1396 cast<ConcatInputSection>(minuend.referent.get<InputSection *>()); 1397 target = findSymbolAtOffset(targetIsec, minuend.addend); 1398 } 1399 if (Invert) 1400 std::swap(pcSym, target); 1401 if (pcSym->isec == isec) { 1402 if (pcSym->value - (Invert ? -1 : 1) * minuend.addend != subtrahend.offset) 1403 fatal("invalid FDE relocation in __eh_frame"); 1404 } else { 1405 // Ensure the pcReloc points to a symbol within the current EH frame. 1406 // HACK: we should really verify that the original relocation's semantics 1407 // are preserved. In particular, we should have 1408 // `oldSym->value + oldOffset == newSym + newOffset`. However, we don't 1409 // have an easy way to access the offsets from this point in the code; some 1410 // refactoring is needed for that. 1411 macho::Reloc &pcReloc = Invert ? minuend : subtrahend; 1412 pcReloc.referent = isec->symbols[0]; 1413 assert(isec->symbols[0]->value == 0); 1414 minuend.addend = pcReloc.offset * (Invert ? 1LL : -1LL); 1415 } 1416 return target; 1417 } 1418 1419 Defined *findSymbolAtAddress(const std::vector<Section *> §ions, 1420 uint64_t addr) { 1421 Section *sec = findContainingSection(sections, &addr); 1422 auto *isec = cast<ConcatInputSection>(findContainingSubsection(*sec, &addr)); 1423 return findSymbolAtOffset(isec, addr); 1424 } 1425 1426 // For symbols that don't have compact unwind info, associate them with the more 1427 // general-purpose (and verbose) DWARF unwind info found in __eh_frame. 1428 // 1429 // This requires us to parse the contents of __eh_frame. See EhFrame.h for a 1430 // description of its format. 1431 // 1432 // While parsing, we also look for what MC calls "abs-ified" relocations -- they 1433 // are relocations which are implicitly encoded as offsets in the section data. 1434 // We convert them into explicit Reloc structs so that the EH frames can be 1435 // handled just like a regular ConcatInputSection later in our output phase. 1436 // 1437 // We also need to handle the case where our input object file has explicit 1438 // relocations. This is the case when e.g. it's the output of `ld -r`. We only 1439 // look for the "abs-ified" relocation if an explicit relocation is absent. 1440 void ObjFile::registerEhFrames(Section &ehFrameSection) { 1441 DenseMap<const InputSection *, CIE> cieMap; 1442 for (const Subsection &subsec : ehFrameSection.subsections) { 1443 auto *isec = cast<ConcatInputSection>(subsec.isec); 1444 uint64_t isecOff = subsec.offset; 1445 1446 // Subtractor relocs require the subtrahend to be a symbol reloc. Ensure 1447 // that all EH frames have an associated symbol so that we can generate 1448 // subtractor relocs that reference them. 1449 if (isec->symbols.size() == 0) 1450 isec->symbols.push_back(make<Defined>( 1451 "EH_Frame", isec->getFile(), isec, /*value=*/0, /*size=*/0, 1452 /*isWeakDef=*/false, /*isExternal=*/false, /*isPrivateExtern=*/false, 1453 /*includeInSymtab=*/false, /*isThumb=*/false, 1454 /*isReferencedDynamically=*/false, /*noDeadStrip=*/false)); 1455 else if (isec->symbols[0]->value != 0) 1456 fatal("found symbol at unexpected offset in __eh_frame"); 1457 1458 EhReader reader(this, isec->data, subsec.offset, target->wordSize); 1459 size_t dataOff = 0; // Offset from the start of the EH frame. 1460 reader.skipValidLength(&dataOff); // readLength() already validated this. 1461 // cieOffOff is the offset from the start of the EH frame to the cieOff 1462 // value, which is itself an offset from the current PC to a CIE. 1463 const size_t cieOffOff = dataOff; 1464 1465 EhRelocator ehRelocator(isec); 1466 auto cieOffRelocIt = llvm::find_if( 1467 isec->relocs, [=](const Reloc &r) { return r.offset == cieOffOff; }); 1468 InputSection *cieIsec = nullptr; 1469 if (cieOffRelocIt != isec->relocs.end()) { 1470 // We already have an explicit relocation for the CIE offset. 1471 cieIsec = 1472 targetSymFromCanonicalSubtractor</*Invert=*/true>(isec, cieOffRelocIt) 1473 ->isec; 1474 dataOff += sizeof(uint32_t); 1475 } else { 1476 // If we haven't found a relocation, then the CIE offset is most likely 1477 // embedded in the section data (AKA an "abs-ified" reloc.). Parse that 1478 // and generate a Reloc struct. 1479 uint32_t cieMinuend = reader.readU32(&dataOff); 1480 if (cieMinuend == 0) 1481 cieIsec = isec; 1482 else { 1483 uint32_t cieOff = isecOff + dataOff - cieMinuend; 1484 cieIsec = findContainingSubsection(ehFrameSection, &cieOff); 1485 if (cieIsec == nullptr) 1486 fatal("failed to find CIE"); 1487 } 1488 if (cieIsec != isec) 1489 ehRelocator.makeNegativePcRel(cieOffOff, cieIsec->symbols[0], 1490 /*length=*/2); 1491 } 1492 if (cieIsec == isec) { 1493 cieMap[cieIsec] = parseCIE(isec, reader, dataOff); 1494 continue; 1495 } 1496 1497 // Offset of the function address within the EH frame. 1498 const size_t funcAddrOff = dataOff; 1499 uint64_t funcAddr = reader.readPointer(&dataOff) + ehFrameSection.addr + 1500 isecOff + funcAddrOff; 1501 uint32_t funcLength = reader.readPointer(&dataOff); 1502 size_t lsdaAddrOff = 0; // Offset of the LSDA address within the EH frame. 1503 assert(cieMap.count(cieIsec)); 1504 const CIE &cie = cieMap[cieIsec]; 1505 Optional<uint64_t> lsdaAddrOpt; 1506 if (cie.fdesHaveAug) { 1507 reader.skipLeb128(&dataOff); 1508 lsdaAddrOff = dataOff; 1509 if (cie.fdesHaveLsda) { 1510 uint64_t lsdaOff = reader.readPointer(&dataOff); 1511 if (lsdaOff != 0) // FIXME possible to test this? 1512 lsdaAddrOpt = ehFrameSection.addr + isecOff + lsdaAddrOff + lsdaOff; 1513 } 1514 } 1515 1516 auto funcAddrRelocIt = isec->relocs.end(); 1517 auto lsdaAddrRelocIt = isec->relocs.end(); 1518 for (auto it = isec->relocs.begin(); it != isec->relocs.end(); ++it) { 1519 if (it->offset == funcAddrOff) 1520 funcAddrRelocIt = it++; // Found subtrahend; skip over minuend reloc 1521 else if (lsdaAddrOpt && it->offset == lsdaAddrOff) 1522 lsdaAddrRelocIt = it++; // Found subtrahend; skip over minuend reloc 1523 } 1524 1525 Defined *funcSym; 1526 if (funcAddrRelocIt != isec->relocs.end()) { 1527 funcSym = targetSymFromCanonicalSubtractor(isec, funcAddrRelocIt); 1528 } else { 1529 funcSym = findSymbolAtAddress(sections, funcAddr); 1530 ehRelocator.makePcRel(funcAddrOff, funcSym, target->p2WordSize); 1531 } 1532 // The symbol has been coalesced, or already has a compact unwind entry. 1533 if (!funcSym || funcSym->getFile() != this || funcSym->unwindEntry) { 1534 // We must prune unused FDEs for correctness, so we cannot rely on 1535 // -dead_strip being enabled. 1536 isec->live = false; 1537 continue; 1538 } 1539 1540 InputSection *lsdaIsec = nullptr; 1541 if (lsdaAddrRelocIt != isec->relocs.end()) { 1542 lsdaIsec = targetSymFromCanonicalSubtractor(isec, lsdaAddrRelocIt)->isec; 1543 } else if (lsdaAddrOpt) { 1544 uint64_t lsdaAddr = *lsdaAddrOpt; 1545 Section *sec = findContainingSection(sections, &lsdaAddr); 1546 lsdaIsec = 1547 cast<ConcatInputSection>(findContainingSubsection(*sec, &lsdaAddr)); 1548 ehRelocator.makePcRel(lsdaAddrOff, lsdaIsec, target->p2WordSize); 1549 } 1550 1551 fdes[isec] = {funcLength, cie.personalitySymbol, lsdaIsec}; 1552 funcSym->unwindEntry = isec; 1553 ehRelocator.commit(); 1554 } 1555 } 1556 1557 std::string ObjFile::sourceFile() const { 1558 SmallString<261> dir(compileUnit->getCompilationDir()); 1559 StringRef sep = sys::path::get_separator(); 1560 // We don't use `path::append` here because we want an empty `dir` to result 1561 // in an absolute path. `append` would give us a relative path for that case. 1562 if (!dir.endswith(sep)) 1563 dir += sep; 1564 return (dir + compileUnit->getUnitDIE().getShortName()).str(); 1565 } 1566 1567 lld::DWARFCache *ObjFile::getDwarf() { 1568 llvm::call_once(initDwarf, [this]() { 1569 auto dwObj = DwarfObject::create(this); 1570 if (!dwObj) 1571 return; 1572 dwarfCache = std::make_unique<DWARFCache>(std::make_unique<DWARFContext>( 1573 std::move(dwObj), "", 1574 [&](Error err) { warn(getName() + ": " + toString(std::move(err))); }, 1575 [&](Error warning) { 1576 warn(getName() + ": " + toString(std::move(warning))); 1577 })); 1578 }); 1579 1580 return dwarfCache.get(); 1581 } 1582 // The path can point to either a dylib or a .tbd file. 1583 static DylibFile *loadDylib(StringRef path, DylibFile *umbrella) { 1584 Optional<MemoryBufferRef> mbref = readFile(path); 1585 if (!mbref) { 1586 error("could not read dylib file at " + path); 1587 return nullptr; 1588 } 1589 return loadDylib(*mbref, umbrella); 1590 } 1591 1592 // TBD files are parsed into a series of TAPI documents (InterfaceFiles), with 1593 // the first document storing child pointers to the rest of them. When we are 1594 // processing a given TBD file, we store that top-level document in 1595 // currentTopLevelTapi. When processing re-exports, we search its children for 1596 // potentially matching documents in the same TBD file. Note that the children 1597 // themselves don't point to further documents, i.e. this is a two-level tree. 1598 // 1599 // Re-exports can either refer to on-disk files, or to documents within .tbd 1600 // files. 1601 static DylibFile *findDylib(StringRef path, DylibFile *umbrella, 1602 const InterfaceFile *currentTopLevelTapi) { 1603 // Search order: 1604 // 1. Install name basename in -F / -L directories. 1605 { 1606 StringRef stem = path::stem(path); 1607 SmallString<128> frameworkName; 1608 path::append(frameworkName, path::Style::posix, stem + ".framework", stem); 1609 bool isFramework = path.endswith(frameworkName); 1610 if (isFramework) { 1611 for (StringRef dir : config->frameworkSearchPaths) { 1612 SmallString<128> candidate = dir; 1613 path::append(candidate, frameworkName); 1614 if (Optional<StringRef> dylibPath = resolveDylibPath(candidate.str())) 1615 return loadDylib(*dylibPath, umbrella); 1616 } 1617 } else if (Optional<StringRef> dylibPath = findPathCombination( 1618 stem, config->librarySearchPaths, {".tbd", ".dylib"})) 1619 return loadDylib(*dylibPath, umbrella); 1620 } 1621 1622 // 2. As absolute path. 1623 if (path::is_absolute(path, path::Style::posix)) 1624 for (StringRef root : config->systemLibraryRoots) 1625 if (Optional<StringRef> dylibPath = resolveDylibPath((root + path).str())) 1626 return loadDylib(*dylibPath, umbrella); 1627 1628 // 3. As relative path. 1629 1630 // TODO: Handle -dylib_file 1631 1632 // Replace @executable_path, @loader_path, @rpath prefixes in install name. 1633 SmallString<128> newPath; 1634 if (config->outputType == MH_EXECUTE && 1635 path.consume_front("@executable_path/")) { 1636 // ld64 allows overriding this with the undocumented flag -executable_path. 1637 // lld doesn't currently implement that flag. 1638 // FIXME: Consider using finalOutput instead of outputFile. 1639 path::append(newPath, path::parent_path(config->outputFile), path); 1640 path = newPath; 1641 } else if (path.consume_front("@loader_path/")) { 1642 fs::real_path(umbrella->getName(), newPath); 1643 path::remove_filename(newPath); 1644 path::append(newPath, path); 1645 path = newPath; 1646 } else if (path.startswith("@rpath/")) { 1647 for (StringRef rpath : umbrella->rpaths) { 1648 newPath.clear(); 1649 if (rpath.consume_front("@loader_path/")) { 1650 fs::real_path(umbrella->getName(), newPath); 1651 path::remove_filename(newPath); 1652 } 1653 path::append(newPath, rpath, path.drop_front(strlen("@rpath/"))); 1654 if (Optional<StringRef> dylibPath = resolveDylibPath(newPath.str())) 1655 return loadDylib(*dylibPath, umbrella); 1656 } 1657 } 1658 1659 // FIXME: Should this be further up? 1660 if (currentTopLevelTapi) { 1661 for (InterfaceFile &child : 1662 make_pointee_range(currentTopLevelTapi->documents())) { 1663 assert(child.documents().empty()); 1664 if (path == child.getInstallName()) { 1665 auto file = make<DylibFile>(child, umbrella, /*isBundleLoader=*/false, 1666 /*explicitlyLinked=*/false); 1667 file->parseReexports(child); 1668 return file; 1669 } 1670 } 1671 } 1672 1673 if (Optional<StringRef> dylibPath = resolveDylibPath(path)) 1674 return loadDylib(*dylibPath, umbrella); 1675 1676 return nullptr; 1677 } 1678 1679 // If a re-exported dylib is public (lives in /usr/lib or 1680 // /System/Library/Frameworks), then it is considered implicitly linked: we 1681 // should bind to its symbols directly instead of via the re-exporting umbrella 1682 // library. 1683 static bool isImplicitlyLinked(StringRef path) { 1684 if (!config->implicitDylibs) 1685 return false; 1686 1687 if (path::parent_path(path) == "/usr/lib") 1688 return true; 1689 1690 // Match /System/Library/Frameworks/$FOO.framework/**/$FOO 1691 if (path.consume_front("/System/Library/Frameworks/")) { 1692 StringRef frameworkName = path.take_until([](char c) { return c == '.'; }); 1693 return path::filename(path) == frameworkName; 1694 } 1695 1696 return false; 1697 } 1698 1699 static void loadReexport(StringRef path, DylibFile *umbrella, 1700 const InterfaceFile *currentTopLevelTapi) { 1701 DylibFile *reexport = findDylib(path, umbrella, currentTopLevelTapi); 1702 if (!reexport) 1703 error("unable to locate re-export with install name " + path); 1704 } 1705 1706 DylibFile::DylibFile(MemoryBufferRef mb, DylibFile *umbrella, 1707 bool isBundleLoader, bool explicitlyLinked) 1708 : InputFile(DylibKind, mb), refState(RefState::Unreferenced), 1709 explicitlyLinked(explicitlyLinked), isBundleLoader(isBundleLoader) { 1710 assert(!isBundleLoader || !umbrella); 1711 if (umbrella == nullptr) 1712 umbrella = this; 1713 this->umbrella = umbrella; 1714 1715 auto *hdr = reinterpret_cast<const mach_header *>(mb.getBufferStart()); 1716 1717 // Initialize installName. 1718 if (const load_command *cmd = findCommand(hdr, LC_ID_DYLIB)) { 1719 auto *c = reinterpret_cast<const dylib_command *>(cmd); 1720 currentVersion = read32le(&c->dylib.current_version); 1721 compatibilityVersion = read32le(&c->dylib.compatibility_version); 1722 installName = 1723 reinterpret_cast<const char *>(cmd) + read32le(&c->dylib.name); 1724 } else if (!isBundleLoader) { 1725 // macho_executable and macho_bundle don't have LC_ID_DYLIB, 1726 // so it's OK. 1727 error("dylib " + toString(this) + " missing LC_ID_DYLIB load command"); 1728 return; 1729 } 1730 1731 if (config->printEachFile) 1732 message(toString(this)); 1733 inputFiles.insert(this); 1734 1735 deadStrippable = hdr->flags & MH_DEAD_STRIPPABLE_DYLIB; 1736 1737 if (!checkCompatibility(this)) 1738 return; 1739 1740 checkAppExtensionSafety(hdr->flags & MH_APP_EXTENSION_SAFE); 1741 1742 for (auto *cmd : findCommands<rpath_command>(hdr, LC_RPATH)) { 1743 StringRef rpath{reinterpret_cast<const char *>(cmd) + cmd->path}; 1744 rpaths.push_back(rpath); 1745 } 1746 1747 // Initialize symbols. 1748 exportingFile = isImplicitlyLinked(installName) ? this : this->umbrella; 1749 1750 const auto *dyldInfo = findCommand<dyld_info_command>(hdr, LC_DYLD_INFO_ONLY); 1751 const auto *exportsTrie = 1752 findCommand<linkedit_data_command>(hdr, LC_DYLD_EXPORTS_TRIE); 1753 if (dyldInfo && exportsTrie) { 1754 // It's unclear what should happen in this case. Maybe we should only error 1755 // out if the two load commands refer to different data? 1756 error("dylib " + toString(this) + 1757 " has both LC_DYLD_INFO_ONLY and LC_DYLD_EXPORTS_TRIE"); 1758 return; 1759 } else if (dyldInfo) { 1760 parseExportedSymbols(dyldInfo->export_off, dyldInfo->export_size); 1761 } else if (exportsTrie) { 1762 parseExportedSymbols(exportsTrie->dataoff, exportsTrie->datasize); 1763 } else { 1764 error("No LC_DYLD_INFO_ONLY or LC_DYLD_EXPORTS_TRIE found in " + 1765 toString(this)); 1766 return; 1767 } 1768 } 1769 1770 void DylibFile::parseExportedSymbols(uint32_t offset, uint32_t size) { 1771 struct TrieEntry { 1772 StringRef name; 1773 uint64_t flags; 1774 }; 1775 1776 auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 1777 std::vector<TrieEntry> entries; 1778 // Find all the $ld$* symbols to process first. 1779 parseTrie(buf + offset, size, [&](const Twine &name, uint64_t flags) { 1780 StringRef savedName = saver().save(name); 1781 if (handleLDSymbol(savedName)) 1782 return; 1783 entries.push_back({savedName, flags}); 1784 }); 1785 1786 // Process the "normal" symbols. 1787 for (TrieEntry &entry : entries) { 1788 if (exportingFile->hiddenSymbols.contains(CachedHashStringRef(entry.name))) 1789 continue; 1790 1791 bool isWeakDef = entry.flags & EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION; 1792 bool isTlv = entry.flags & EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL; 1793 1794 symbols.push_back( 1795 symtab->addDylib(entry.name, exportingFile, isWeakDef, isTlv)); 1796 } 1797 } 1798 1799 void DylibFile::parseLoadCommands(MemoryBufferRef mb) { 1800 auto *hdr = reinterpret_cast<const mach_header *>(mb.getBufferStart()); 1801 const uint8_t *p = reinterpret_cast<const uint8_t *>(mb.getBufferStart()) + 1802 target->headerSize; 1803 for (uint32_t i = 0, n = hdr->ncmds; i < n; ++i) { 1804 auto *cmd = reinterpret_cast<const load_command *>(p); 1805 p += cmd->cmdsize; 1806 1807 if (!(hdr->flags & MH_NO_REEXPORTED_DYLIBS) && 1808 cmd->cmd == LC_REEXPORT_DYLIB) { 1809 const auto *c = reinterpret_cast<const dylib_command *>(cmd); 1810 StringRef reexportPath = 1811 reinterpret_cast<const char *>(c) + read32le(&c->dylib.name); 1812 loadReexport(reexportPath, exportingFile, nullptr); 1813 } 1814 1815 // FIXME: What about LC_LOAD_UPWARD_DYLIB, LC_LAZY_LOAD_DYLIB, 1816 // LC_LOAD_WEAK_DYLIB, LC_REEXPORT_DYLIB (..are reexports from dylibs with 1817 // MH_NO_REEXPORTED_DYLIBS loaded for -flat_namespace)? 1818 if (config->namespaceKind == NamespaceKind::flat && 1819 cmd->cmd == LC_LOAD_DYLIB) { 1820 const auto *c = reinterpret_cast<const dylib_command *>(cmd); 1821 StringRef dylibPath = 1822 reinterpret_cast<const char *>(c) + read32le(&c->dylib.name); 1823 DylibFile *dylib = findDylib(dylibPath, umbrella, nullptr); 1824 if (!dylib) 1825 error(Twine("unable to locate library '") + dylibPath + 1826 "' loaded from '" + toString(this) + "' for -flat_namespace"); 1827 } 1828 } 1829 } 1830 1831 // Some versions of Xcode ship with .tbd files that don't have the right 1832 // platform settings. 1833 constexpr std::array<StringRef, 3> skipPlatformChecks{ 1834 "/usr/lib/system/libsystem_kernel.dylib", 1835 "/usr/lib/system/libsystem_platform.dylib", 1836 "/usr/lib/system/libsystem_pthread.dylib"}; 1837 1838 static bool skipPlatformCheckForCatalyst(const InterfaceFile &interface, 1839 bool explicitlyLinked) { 1840 // Catalyst outputs can link against implicitly linked macOS-only libraries. 1841 if (config->platform() != PLATFORM_MACCATALYST || explicitlyLinked) 1842 return false; 1843 return is_contained(interface.targets(), 1844 MachO::Target(config->arch(), PLATFORM_MACOS)); 1845 } 1846 1847 DylibFile::DylibFile(const InterfaceFile &interface, DylibFile *umbrella, 1848 bool isBundleLoader, bool explicitlyLinked) 1849 : InputFile(DylibKind, interface), refState(RefState::Unreferenced), 1850 explicitlyLinked(explicitlyLinked), isBundleLoader(isBundleLoader) { 1851 // FIXME: Add test for the missing TBD code path. 1852 1853 if (umbrella == nullptr) 1854 umbrella = this; 1855 this->umbrella = umbrella; 1856 1857 installName = saver().save(interface.getInstallName()); 1858 compatibilityVersion = interface.getCompatibilityVersion().rawValue(); 1859 currentVersion = interface.getCurrentVersion().rawValue(); 1860 1861 if (config->printEachFile) 1862 message(toString(this)); 1863 inputFiles.insert(this); 1864 1865 if (!is_contained(skipPlatformChecks, installName) && 1866 !is_contained(interface.targets(), config->platformInfo.target) && 1867 !skipPlatformCheckForCatalyst(interface, explicitlyLinked)) { 1868 error(toString(this) + " is incompatible with " + 1869 std::string(config->platformInfo.target)); 1870 return; 1871 } 1872 1873 checkAppExtensionSafety(interface.isApplicationExtensionSafe()); 1874 1875 exportingFile = isImplicitlyLinked(installName) ? this : umbrella; 1876 auto addSymbol = [&](const Twine &name) -> void { 1877 StringRef savedName = saver().save(name); 1878 if (exportingFile->hiddenSymbols.contains(CachedHashStringRef(savedName))) 1879 return; 1880 1881 symbols.push_back(symtab->addDylib(savedName, exportingFile, 1882 /*isWeakDef=*/false, 1883 /*isTlv=*/false)); 1884 }; 1885 1886 std::vector<const llvm::MachO::Symbol *> normalSymbols; 1887 normalSymbols.reserve(interface.symbolsCount()); 1888 for (const auto *symbol : interface.symbols()) { 1889 if (!symbol->getArchitectures().has(config->arch())) 1890 continue; 1891 if (handleLDSymbol(symbol->getName())) 1892 continue; 1893 1894 switch (symbol->getKind()) { 1895 case SymbolKind::GlobalSymbol: // Fallthrough 1896 case SymbolKind::ObjectiveCClass: // Fallthrough 1897 case SymbolKind::ObjectiveCClassEHType: // Fallthrough 1898 case SymbolKind::ObjectiveCInstanceVariable: // Fallthrough 1899 normalSymbols.push_back(symbol); 1900 } 1901 } 1902 1903 // TODO(compnerd) filter out symbols based on the target platform 1904 // TODO: handle weak defs, thread locals 1905 for (const auto *symbol : normalSymbols) { 1906 switch (symbol->getKind()) { 1907 case SymbolKind::GlobalSymbol: 1908 addSymbol(symbol->getName()); 1909 break; 1910 case SymbolKind::ObjectiveCClass: 1911 // XXX ld64 only creates these symbols when -ObjC is passed in. We may 1912 // want to emulate that. 1913 addSymbol(objc::klass + symbol->getName()); 1914 addSymbol(objc::metaclass + symbol->getName()); 1915 break; 1916 case SymbolKind::ObjectiveCClassEHType: 1917 addSymbol(objc::ehtype + symbol->getName()); 1918 break; 1919 case SymbolKind::ObjectiveCInstanceVariable: 1920 addSymbol(objc::ivar + symbol->getName()); 1921 break; 1922 } 1923 } 1924 } 1925 1926 void DylibFile::parseReexports(const InterfaceFile &interface) { 1927 const InterfaceFile *topLevel = 1928 interface.getParent() == nullptr ? &interface : interface.getParent(); 1929 for (const InterfaceFileRef &intfRef : interface.reexportedLibraries()) { 1930 InterfaceFile::const_target_range targets = intfRef.targets(); 1931 if (is_contained(skipPlatformChecks, intfRef.getInstallName()) || 1932 is_contained(targets, config->platformInfo.target)) 1933 loadReexport(intfRef.getInstallName(), exportingFile, topLevel); 1934 } 1935 } 1936 1937 // $ld$ symbols modify the properties/behavior of the library (e.g. its install 1938 // name, compatibility version or hide/add symbols) for specific target 1939 // versions. 1940 bool DylibFile::handleLDSymbol(StringRef originalName) { 1941 if (!originalName.startswith("$ld$")) 1942 return false; 1943 1944 StringRef action; 1945 StringRef name; 1946 std::tie(action, name) = originalName.drop_front(strlen("$ld$")).split('$'); 1947 if (action == "previous") 1948 handleLDPreviousSymbol(name, originalName); 1949 else if (action == "install_name") 1950 handleLDInstallNameSymbol(name, originalName); 1951 else if (action == "hide") 1952 handleLDHideSymbol(name, originalName); 1953 return true; 1954 } 1955 1956 void DylibFile::handleLDPreviousSymbol(StringRef name, StringRef originalName) { 1957 // originalName: $ld$ previous $ <installname> $ <compatversion> $ 1958 // <platformstr> $ <startversion> $ <endversion> $ <symbol-name> $ 1959 StringRef installName; 1960 StringRef compatVersion; 1961 StringRef platformStr; 1962 StringRef startVersion; 1963 StringRef endVersion; 1964 StringRef symbolName; 1965 StringRef rest; 1966 1967 std::tie(installName, name) = name.split('$'); 1968 std::tie(compatVersion, name) = name.split('$'); 1969 std::tie(platformStr, name) = name.split('$'); 1970 std::tie(startVersion, name) = name.split('$'); 1971 std::tie(endVersion, name) = name.split('$'); 1972 std::tie(symbolName, rest) = name.split('$'); 1973 // TODO: ld64 contains some logic for non-empty symbolName as well. 1974 if (!symbolName.empty()) 1975 return; 1976 unsigned platform; 1977 if (platformStr.getAsInteger(10, platform) || 1978 platform != static_cast<unsigned>(config->platform())) 1979 return; 1980 1981 VersionTuple start; 1982 if (start.tryParse(startVersion)) { 1983 warn("failed to parse start version, symbol '" + originalName + 1984 "' ignored"); 1985 return; 1986 } 1987 VersionTuple end; 1988 if (end.tryParse(endVersion)) { 1989 warn("failed to parse end version, symbol '" + originalName + "' ignored"); 1990 return; 1991 } 1992 if (config->platformInfo.minimum < start || 1993 config->platformInfo.minimum >= end) 1994 return; 1995 1996 this->installName = saver().save(installName); 1997 1998 if (!compatVersion.empty()) { 1999 VersionTuple cVersion; 2000 if (cVersion.tryParse(compatVersion)) { 2001 warn("failed to parse compatibility version, symbol '" + originalName + 2002 "' ignored"); 2003 return; 2004 } 2005 compatibilityVersion = encodeVersion(cVersion); 2006 } 2007 } 2008 2009 void DylibFile::handleLDInstallNameSymbol(StringRef name, 2010 StringRef originalName) { 2011 // originalName: $ld$ install_name $ os<version> $ install_name 2012 StringRef condition, installName; 2013 std::tie(condition, installName) = name.split('$'); 2014 VersionTuple version; 2015 if (!condition.consume_front("os") || version.tryParse(condition)) 2016 warn("failed to parse os version, symbol '" + originalName + "' ignored"); 2017 else if (version == config->platformInfo.minimum) 2018 this->installName = saver().save(installName); 2019 } 2020 2021 void DylibFile::handleLDHideSymbol(StringRef name, StringRef originalName) { 2022 StringRef symbolName; 2023 bool shouldHide = true; 2024 if (name.startswith("os")) { 2025 // If it's hidden based on versions. 2026 name = name.drop_front(2); 2027 StringRef minVersion; 2028 std::tie(minVersion, symbolName) = name.split('$'); 2029 VersionTuple versionTup; 2030 if (versionTup.tryParse(minVersion)) { 2031 warn("Failed to parse hidden version, symbol `" + originalName + 2032 "` ignored."); 2033 return; 2034 } 2035 shouldHide = versionTup == config->platformInfo.minimum; 2036 } else { 2037 symbolName = name; 2038 } 2039 2040 if (shouldHide) 2041 exportingFile->hiddenSymbols.insert(CachedHashStringRef(symbolName)); 2042 } 2043 2044 void DylibFile::checkAppExtensionSafety(bool dylibIsAppExtensionSafe) const { 2045 if (config->applicationExtension && !dylibIsAppExtensionSafe) 2046 warn("using '-application_extension' with unsafe dylib: " + toString(this)); 2047 } 2048 2049 ArchiveFile::ArchiveFile(std::unique_ptr<object::Archive> &&f) 2050 : InputFile(ArchiveKind, f->getMemoryBufferRef()), file(std::move(f)) {} 2051 2052 void ArchiveFile::addLazySymbols() { 2053 for (const object::Archive::Symbol &sym : file->symbols()) 2054 symtab->addLazyArchive(sym.getName(), this, sym); 2055 } 2056 2057 static Expected<InputFile *> loadArchiveMember(MemoryBufferRef mb, 2058 uint32_t modTime, 2059 StringRef archiveName, 2060 uint64_t offsetInArchive) { 2061 if (config->zeroModTime) 2062 modTime = 0; 2063 2064 switch (identify_magic(mb.getBuffer())) { 2065 case file_magic::macho_object: 2066 return make<ObjFile>(mb, modTime, archiveName); 2067 case file_magic::bitcode: 2068 return make<BitcodeFile>(mb, archiveName, offsetInArchive); 2069 default: 2070 return createStringError(inconvertibleErrorCode(), 2071 mb.getBufferIdentifier() + 2072 " has unhandled file type"); 2073 } 2074 } 2075 2076 Error ArchiveFile::fetch(const object::Archive::Child &c, StringRef reason) { 2077 if (!seen.insert(c.getChildOffset()).second) 2078 return Error::success(); 2079 2080 Expected<MemoryBufferRef> mb = c.getMemoryBufferRef(); 2081 if (!mb) 2082 return mb.takeError(); 2083 2084 // Thin archives refer to .o files, so --reproduce needs the .o files too. 2085 if (tar && c.getParent()->isThin()) 2086 tar->append(relativeToRoot(CHECK(c.getFullName(), this)), mb->getBuffer()); 2087 2088 Expected<TimePoint<std::chrono::seconds>> modTime = c.getLastModified(); 2089 if (!modTime) 2090 return modTime.takeError(); 2091 2092 Expected<InputFile *> file = 2093 loadArchiveMember(*mb, toTimeT(*modTime), getName(), c.getChildOffset()); 2094 2095 if (!file) 2096 return file.takeError(); 2097 2098 inputFiles.insert(*file); 2099 printArchiveMemberLoad(reason, *file); 2100 return Error::success(); 2101 } 2102 2103 void ArchiveFile::fetch(const object::Archive::Symbol &sym) { 2104 object::Archive::Child c = 2105 CHECK(sym.getMember(), toString(this) + 2106 ": could not get the member defining symbol " + 2107 toMachOString(sym)); 2108 2109 // `sym` is owned by a LazySym, which will be replace<>()d by make<ObjFile> 2110 // and become invalid after that call. Copy it to the stack so we can refer 2111 // to it later. 2112 const object::Archive::Symbol symCopy = sym; 2113 2114 // ld64 doesn't demangle sym here even with -demangle. 2115 // Match that: intentionally don't call toMachOString(). 2116 if (Error e = fetch(c, symCopy.getName())) 2117 error(toString(this) + ": could not get the member defining symbol " + 2118 toMachOString(symCopy) + ": " + toString(std::move(e))); 2119 } 2120 2121 static macho::Symbol *createBitcodeSymbol(const lto::InputFile::Symbol &objSym, 2122 BitcodeFile &file) { 2123 StringRef name = saver().save(objSym.getName()); 2124 2125 if (objSym.isUndefined()) 2126 return symtab->addUndefined(name, &file, /*isWeakRef=*/objSym.isWeak()); 2127 2128 // TODO: Write a test demonstrating why computing isPrivateExtern before 2129 // LTO compilation is important. 2130 bool isPrivateExtern = false; 2131 switch (objSym.getVisibility()) { 2132 case GlobalValue::HiddenVisibility: 2133 isPrivateExtern = true; 2134 break; 2135 case GlobalValue::ProtectedVisibility: 2136 error(name + " has protected visibility, which is not supported by Mach-O"); 2137 break; 2138 case GlobalValue::DefaultVisibility: 2139 break; 2140 } 2141 isPrivateExtern = isPrivateExtern || objSym.canBeOmittedFromSymbolTable(); 2142 2143 if (objSym.isCommon()) 2144 return symtab->addCommon(name, &file, objSym.getCommonSize(), 2145 objSym.getCommonAlignment(), isPrivateExtern); 2146 2147 return symtab->addDefined(name, &file, /*isec=*/nullptr, /*value=*/0, 2148 /*size=*/0, objSym.isWeak(), isPrivateExtern, 2149 /*isThumb=*/false, 2150 /*isReferencedDynamically=*/false, 2151 /*noDeadStrip=*/false, 2152 /*isWeakDefCanBeHidden=*/false); 2153 } 2154 2155 BitcodeFile::BitcodeFile(MemoryBufferRef mb, StringRef archiveName, 2156 uint64_t offsetInArchive, bool lazy) 2157 : InputFile(BitcodeKind, mb, lazy) { 2158 this->archiveName = std::string(archiveName); 2159 std::string path = mb.getBufferIdentifier().str(); 2160 // ThinLTO assumes that all MemoryBufferRefs given to it have a unique 2161 // name. If two members with the same name are provided, this causes a 2162 // collision and ThinLTO can't proceed. 2163 // So, we append the archive name to disambiguate two members with the same 2164 // name from multiple different archives, and offset within the archive to 2165 // disambiguate two members of the same name from a single archive. 2166 MemoryBufferRef mbref(mb.getBuffer(), 2167 saver().save(archiveName.empty() 2168 ? path 2169 : archiveName + 2170 sys::path::filename(path) + 2171 utostr(offsetInArchive))); 2172 2173 obj = check(lto::InputFile::create(mbref)); 2174 if (lazy) 2175 parseLazy(); 2176 else 2177 parse(); 2178 } 2179 2180 void BitcodeFile::parse() { 2181 // Convert LTO Symbols to LLD Symbols in order to perform resolution. The 2182 // "winning" symbol will then be marked as Prevailing at LTO compilation 2183 // time. 2184 symbols.clear(); 2185 for (const lto::InputFile::Symbol &objSym : obj->symbols()) 2186 symbols.push_back(createBitcodeSymbol(objSym, *this)); 2187 } 2188 2189 void BitcodeFile::parseLazy() { 2190 symbols.resize(obj->symbols().size()); 2191 for (auto it : llvm::enumerate(obj->symbols())) { 2192 const lto::InputFile::Symbol &objSym = it.value(); 2193 if (!objSym.isUndefined()) { 2194 symbols[it.index()] = 2195 symtab->addLazyObject(saver().save(objSym.getName()), *this); 2196 if (!lazy) 2197 break; 2198 } 2199 } 2200 } 2201 2202 void macho::extract(InputFile &file, StringRef reason) { 2203 assert(file.lazy); 2204 file.lazy = false; 2205 printArchiveMemberLoad(reason, &file); 2206 if (auto *bitcode = dyn_cast<BitcodeFile>(&file)) { 2207 bitcode->parse(); 2208 } else { 2209 auto &f = cast<ObjFile>(file); 2210 if (target->wordSize == 8) 2211 f.parse<LP64>(); 2212 else 2213 f.parse<ILP32>(); 2214 } 2215 } 2216 2217 template void ObjFile::parse<LP64>(); 2218