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