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