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 using namespace llvm; 74 using namespace llvm::MachO; 75 using namespace llvm::support::endian; 76 using namespace llvm::sys; 77 using namespace lld; 78 using namespace lld::macho; 79 80 // Returns "<internal>", "foo.a(bar.o)", or "baz.o". 81 std::string lld::toString(const InputFile *f) { 82 if (!f) 83 return "<internal>"; 84 85 // Multiple dylibs can be defined in one .tbd file. 86 if (auto dylibFile = dyn_cast<DylibFile>(f)) 87 if (f->getName().endswith(".tbd")) 88 return (f->getName() + "(" + dylibFile->installName + ")").str(); 89 90 if (f->archiveName.empty()) 91 return std::string(f->getName()); 92 return (f->archiveName + "(" + path::filename(f->getName()) + ")").str(); 93 } 94 95 SetVector<InputFile *> macho::inputFiles; 96 std::unique_ptr<TarWriter> macho::tar; 97 int InputFile::idCount = 0; 98 99 static VersionTuple decodeVersion(uint32_t version) { 100 unsigned major = version >> 16; 101 unsigned minor = (version >> 8) & 0xffu; 102 unsigned subMinor = version & 0xffu; 103 return VersionTuple(major, minor, subMinor); 104 } 105 106 static std::vector<PlatformInfo> getPlatformInfos(const InputFile *input) { 107 if (!isa<ObjFile>(input) && !isa<DylibFile>(input)) 108 return {}; 109 110 const char *hdr = input->mb.getBufferStart(); 111 112 std::vector<PlatformInfo> platformInfos; 113 for (auto *cmd : findCommands<build_version_command>(hdr, LC_BUILD_VERSION)) { 114 PlatformInfo info; 115 info.target.Platform = static_cast<PlatformKind>(cmd->platform); 116 info.minimum = decodeVersion(cmd->minos); 117 platformInfos.emplace_back(std::move(info)); 118 } 119 for (auto *cmd : findCommands<version_min_command>( 120 hdr, LC_VERSION_MIN_MACOSX, LC_VERSION_MIN_IPHONEOS, 121 LC_VERSION_MIN_TVOS, LC_VERSION_MIN_WATCHOS)) { 122 PlatformInfo info; 123 switch (cmd->cmd) { 124 case LC_VERSION_MIN_MACOSX: 125 info.target.Platform = PlatformKind::macOS; 126 break; 127 case LC_VERSION_MIN_IPHONEOS: 128 info.target.Platform = PlatformKind::iOS; 129 break; 130 case LC_VERSION_MIN_TVOS: 131 info.target.Platform = PlatformKind::tvOS; 132 break; 133 case LC_VERSION_MIN_WATCHOS: 134 info.target.Platform = PlatformKind::watchOS; 135 break; 136 } 137 info.minimum = decodeVersion(cmd->version); 138 platformInfos.emplace_back(std::move(info)); 139 } 140 141 return platformInfos; 142 } 143 144 static PlatformKind removeSimulator(PlatformKind platform) { 145 // Mapping of platform to simulator and vice-versa. 146 static const std::map<PlatformKind, PlatformKind> platformMap = { 147 {PlatformKind::iOSSimulator, PlatformKind::iOS}, 148 {PlatformKind::tvOSSimulator, PlatformKind::tvOS}, 149 {PlatformKind::watchOSSimulator, PlatformKind::watchOS}}; 150 151 auto iter = platformMap.find(platform); 152 if (iter == platformMap.end()) 153 return platform; 154 return iter->second; 155 } 156 157 static bool checkCompatibility(const InputFile *input) { 158 std::vector<PlatformInfo> platformInfos = getPlatformInfos(input); 159 if (platformInfos.empty()) 160 return true; 161 162 auto it = find_if(platformInfos, [&](const PlatformInfo &info) { 163 return removeSimulator(info.target.Platform) == 164 removeSimulator(config->platform()); 165 }); 166 if (it == platformInfos.end()) { 167 std::string platformNames; 168 raw_string_ostream os(platformNames); 169 interleave( 170 platformInfos, os, 171 [&](const PlatformInfo &info) { 172 os << getPlatformName(info.target.Platform); 173 }, 174 "/"); 175 error(toString(input) + " has platform " + platformNames + 176 Twine(", which is different from target platform ") + 177 getPlatformName(config->platform())); 178 return false; 179 } 180 181 if (it->minimum > config->platformInfo.minimum) 182 warn(toString(input) + " has version " + it->minimum.getAsString() + 183 ", which is newer than target minimum of " + 184 config->platformInfo.minimum.getAsString()); 185 186 return true; 187 } 188 189 // Open a given file path and return it as a memory-mapped file. 190 Optional<MemoryBufferRef> macho::readFile(StringRef path) { 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 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 MemoryBufferRef(StringRef(buf + offset, size), path.copy(bAlloc)); 234 } 235 236 error("unable to find matching architecture in " + path); 237 return None; 238 } 239 240 InputFile::InputFile(Kind kind, const InterfaceFile &interface) 241 : id(idCount++), fileKind(kind), name(saver.save(interface.getPath())) {} 242 243 template <class Section> 244 void ObjFile::parseSections(ArrayRef<Section> sections) { 245 subsections.reserve(sections.size()); 246 auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 247 248 for (const Section &sec : sections) { 249 StringRef name = 250 StringRef(sec.sectname, strnlen(sec.sectname, sizeof(sec.sectname))); 251 StringRef segname = 252 StringRef(sec.segname, strnlen(sec.segname, sizeof(sec.segname))); 253 ArrayRef<uint8_t> data = {isZeroFill(sec.flags) ? nullptr 254 : buf + sec.offset, 255 static_cast<size_t>(sec.size)}; 256 if (sec.align >= 32) { 257 error("alignment " + std::to_string(sec.align) + " of section " + name + 258 " is too large"); 259 subsections.push_back({}); 260 continue; 261 } 262 uint32_t align = 1 << sec.align; 263 uint32_t flags = sec.flags; 264 265 if (config->dedupLiterals && 266 (sectionType(sec.flags) == S_CSTRING_LITERALS || 267 isWordLiteralSection(sec.flags))) { 268 if (sec.nreloc) 269 fatal(toString(this) + " contains relocations in " + sec.segname + "," + 270 sec.sectname + 271 ", so LLD cannot deduplicate literals. Try re-running without " 272 "--deduplicate-literals."); 273 274 InputSection *isec; 275 if (sectionType(sec.flags) == S_CSTRING_LITERALS) { 276 isec = 277 make<CStringInputSection>(segname, name, this, data, align, flags); 278 // FIXME: parallelize this? 279 cast<CStringInputSection>(isec)->splitIntoPieces(); 280 } else { 281 isec = make<WordLiteralInputSection>(segname, name, this, data, align, 282 flags); 283 } 284 subsections.push_back({{0, isec}}); 285 } else { 286 auto *isec = 287 make<ConcatInputSection>(segname, name, this, data, align, flags); 288 if (!(isDebugSection(isec->flags) && 289 isec->segname == segment_names::dwarf)) { 290 subsections.push_back({{0, isec}}); 291 } else { 292 // Instead of emitting DWARF sections, we emit STABS symbols to the 293 // object files that contain them. We filter them out early to avoid 294 // parsing their relocations unnecessarily. But we must still push an 295 // empty map to ensure the indices line up for the remaining sections. 296 subsections.push_back({}); 297 debugSections.push_back(isec); 298 } 299 } 300 } 301 } 302 303 // Find the subsection corresponding to the greatest section offset that is <= 304 // that of the given offset. 305 // 306 // offset: an offset relative to the start of the original InputSection (before 307 // any subsection splitting has occurred). It will be updated to represent the 308 // same location as an offset relative to the start of the containing 309 // subsection. 310 static InputSection *findContainingSubsection(SubsectionMap &map, 311 uint64_t *offset) { 312 auto it = std::prev(llvm::upper_bound( 313 map, *offset, [](uint64_t value, SubsectionEntry subsecEntry) { 314 return value < subsecEntry.offset; 315 })); 316 *offset -= it->offset; 317 return it->isec; 318 } 319 320 template <class Section> 321 static bool validateRelocationInfo(InputFile *file, const Section &sec, 322 relocation_info rel) { 323 const RelocAttrs &relocAttrs = target->getRelocAttrs(rel.r_type); 324 bool valid = true; 325 auto message = [relocAttrs, file, sec, rel, &valid](const Twine &diagnostic) { 326 valid = false; 327 return (relocAttrs.name + " relocation " + diagnostic + " at offset " + 328 std::to_string(rel.r_address) + " of " + sec.segname + "," + 329 sec.sectname + " in " + toString(file)) 330 .str(); 331 }; 332 333 if (!relocAttrs.hasAttr(RelocAttrBits::LOCAL) && !rel.r_extern) 334 error(message("must be extern")); 335 if (relocAttrs.hasAttr(RelocAttrBits::PCREL) != rel.r_pcrel) 336 error(message(Twine("must ") + (rel.r_pcrel ? "not " : "") + 337 "be PC-relative")); 338 if (isThreadLocalVariables(sec.flags) && 339 !relocAttrs.hasAttr(RelocAttrBits::UNSIGNED)) 340 error(message("not allowed in thread-local section, must be UNSIGNED")); 341 if (rel.r_length < 2 || rel.r_length > 3 || 342 !relocAttrs.hasAttr(static_cast<RelocAttrBits>(1 << rel.r_length))) { 343 static SmallVector<StringRef, 4> widths{"0", "4", "8", "4 or 8"}; 344 error(message("has width " + std::to_string(1 << rel.r_length) + 345 " bytes, but must be " + 346 widths[(static_cast<int>(relocAttrs.bits) >> 2) & 3] + 347 " bytes")); 348 } 349 return valid; 350 } 351 352 template <class Section> 353 void ObjFile::parseRelocations(ArrayRef<Section> sectionHeaders, 354 const Section &sec, SubsectionMap &subsecMap) { 355 auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 356 ArrayRef<relocation_info> relInfos( 357 reinterpret_cast<const relocation_info *>(buf + sec.reloff), sec.nreloc); 358 359 for (size_t i = 0; i < relInfos.size(); i++) { 360 // Paired relocations serve as Mach-O's method for attaching a 361 // supplemental datum to a primary relocation record. ELF does not 362 // need them because the *_RELOC_RELA records contain the extra 363 // addend field, vs. *_RELOC_REL which omit the addend. 364 // 365 // The {X86_64,ARM64}_RELOC_SUBTRACTOR record holds the subtrahend, 366 // and the paired *_RELOC_UNSIGNED record holds the minuend. The 367 // datum for each is a symbolic address. The result is the offset 368 // between two addresses. 369 // 370 // The ARM64_RELOC_ADDEND record holds the addend, and the paired 371 // ARM64_RELOC_BRANCH26 or ARM64_RELOC_PAGE21/PAGEOFF12 holds the 372 // base symbolic address. 373 // 374 // Note: X86 does not use *_RELOC_ADDEND because it can embed an 375 // addend into the instruction stream. On X86, a relocatable address 376 // field always occupies an entire contiguous sequence of byte(s), 377 // so there is no need to merge opcode bits with address 378 // bits. Therefore, it's easy and convenient to store addends in the 379 // instruction-stream bytes that would otherwise contain zeroes. By 380 // contrast, RISC ISAs such as ARM64 mix opcode bits with with 381 // address bits so that bitwise arithmetic is necessary to extract 382 // and insert them. Storing addends in the instruction stream is 383 // possible, but inconvenient and more costly at link time. 384 385 int64_t pairedAddend = 0; 386 relocation_info relInfo = relInfos[i]; 387 if (target->hasAttr(relInfo.r_type, RelocAttrBits::ADDEND)) { 388 pairedAddend = SignExtend64<24>(relInfo.r_symbolnum); 389 relInfo = relInfos[++i]; 390 } 391 assert(i < relInfos.size()); 392 if (!validateRelocationInfo(this, sec, relInfo)) 393 continue; 394 if (relInfo.r_address & R_SCATTERED) 395 fatal("TODO: Scattered relocations not supported"); 396 397 bool isSubtrahend = 398 target->hasAttr(relInfo.r_type, RelocAttrBits::SUBTRAHEND); 399 int64_t embeddedAddend = target->getEmbeddedAddend(mb, sec.offset, relInfo); 400 assert(!(embeddedAddend && pairedAddend)); 401 int64_t totalAddend = pairedAddend + embeddedAddend; 402 Reloc r; 403 r.type = relInfo.r_type; 404 r.pcrel = relInfo.r_pcrel; 405 r.length = relInfo.r_length; 406 r.offset = relInfo.r_address; 407 if (relInfo.r_extern) { 408 r.referent = symbols[relInfo.r_symbolnum]; 409 r.addend = isSubtrahend ? 0 : totalAddend; 410 } else { 411 assert(!isSubtrahend); 412 const Section &referentSec = sectionHeaders[relInfo.r_symbolnum - 1]; 413 uint64_t referentOffset; 414 if (relInfo.r_pcrel) { 415 // The implicit addend for pcrel section relocations is the pcrel offset 416 // in terms of the addresses in the input file. Here we adjust it so 417 // that it describes the offset from the start of the referent section. 418 // FIXME This logic was written around x86_64 behavior -- ARM64 doesn't 419 // have pcrel section relocations. We may want to factor this out into 420 // the arch-specific .cpp file. 421 assert(target->hasAttr(r.type, RelocAttrBits::BYTE4)); 422 referentOffset = 423 sec.addr + relInfo.r_address + 4 + totalAddend - referentSec.addr; 424 } else { 425 // The addend for a non-pcrel relocation is its absolute address. 426 referentOffset = totalAddend - referentSec.addr; 427 } 428 SubsectionMap &referentSubsecMap = subsections[relInfo.r_symbolnum - 1]; 429 r.referent = findContainingSubsection(referentSubsecMap, &referentOffset); 430 r.addend = referentOffset; 431 } 432 433 InputSection *subsec = findContainingSubsection(subsecMap, &r.offset); 434 subsec->relocs.push_back(r); 435 436 if (isSubtrahend) { 437 relocation_info minuendInfo = relInfos[++i]; 438 // SUBTRACTOR relocations should always be followed by an UNSIGNED one 439 // attached to the same address. 440 assert(target->hasAttr(minuendInfo.r_type, RelocAttrBits::UNSIGNED) && 441 relInfo.r_address == minuendInfo.r_address); 442 Reloc p; 443 p.type = minuendInfo.r_type; 444 if (minuendInfo.r_extern) { 445 p.referent = symbols[minuendInfo.r_symbolnum]; 446 p.addend = totalAddend; 447 } else { 448 uint64_t referentOffset = 449 totalAddend - sectionHeaders[minuendInfo.r_symbolnum - 1].addr; 450 SubsectionMap &referentSubsecMap = 451 subsections[minuendInfo.r_symbolnum - 1]; 452 p.referent = 453 findContainingSubsection(referentSubsecMap, &referentOffset); 454 p.addend = referentOffset; 455 } 456 subsec->relocs.push_back(p); 457 } 458 } 459 } 460 461 template <class NList> 462 static macho::Symbol *createDefined(const NList &sym, StringRef name, 463 InputSection *isec, uint64_t value, 464 uint64_t size) { 465 // Symbol scope is determined by sym.n_type & (N_EXT | N_PEXT): 466 // N_EXT: Global symbols. These go in the symbol table during the link, 467 // and also in the export table of the output so that the dynamic 468 // linker sees them. 469 // N_EXT | N_PEXT: Linkage unit (think: dylib) scoped. These go in the 470 // symbol table during the link so that duplicates are 471 // either reported (for non-weak symbols) or merged 472 // (for weak symbols), but they do not go in the export 473 // table of the output. 474 // N_PEXT: Does not occur in input files in practice, 475 // a private extern must be external. 476 // 0: Translation-unit scoped. These are not in the symbol table during 477 // link, and not in the export table of the output either. 478 479 bool isWeakDefCanBeHidden = 480 (sym.n_desc & (N_WEAK_DEF | N_WEAK_REF)) == (N_WEAK_DEF | N_WEAK_REF); 481 482 if (sym.n_type & (N_EXT | N_PEXT)) { 483 assert((sym.n_type & N_EXT) && "invalid input"); 484 bool isPrivateExtern = sym.n_type & N_PEXT; 485 486 // lld's behavior for merging symbols is slightly different from ld64: 487 // ld64 picks the winning symbol based on several criteria (see 488 // pickBetweenRegularAtoms() in ld64's SymbolTable.cpp), while lld 489 // just merges metadata and keeps the contents of the first symbol 490 // with that name (see SymbolTable::addDefined). For: 491 // * inline function F in a TU built with -fvisibility-inlines-hidden 492 // * and inline function F in another TU built without that flag 493 // ld64 will pick the one from the file built without 494 // -fvisibility-inlines-hidden. 495 // lld will instead pick the one listed first on the link command line and 496 // give it visibility as if the function was built without 497 // -fvisibility-inlines-hidden. 498 // If both functions have the same contents, this will have the same 499 // behavior. If not, it won't, but the input had an ODR violation in 500 // that case. 501 // 502 // Similarly, merging a symbol 503 // that's isPrivateExtern and not isWeakDefCanBeHidden with one 504 // that's not isPrivateExtern but isWeakDefCanBeHidden technically 505 // should produce one 506 // that's not isPrivateExtern but isWeakDefCanBeHidden. That matters 507 // with ld64's semantics, because it means the non-private-extern 508 // definition will continue to take priority if more private extern 509 // definitions are encountered. With lld's semantics there's no observable 510 // difference between a symbol that's isWeakDefCanBeHidden or one that's 511 // privateExtern -- neither makes it into the dynamic symbol table. So just 512 // promote isWeakDefCanBeHidden to isPrivateExtern here. 513 if (isWeakDefCanBeHidden) 514 isPrivateExtern = true; 515 516 return symtab->addDefined( 517 name, isec->file, isec, value, size, sym.n_desc & N_WEAK_DEF, 518 isPrivateExtern, sym.n_desc & N_ARM_THUMB_DEF, 519 sym.n_desc & REFERENCED_DYNAMICALLY, sym.n_desc & N_NO_DEAD_STRIP); 520 } 521 522 assert(!isWeakDefCanBeHidden && 523 "weak_def_can_be_hidden on already-hidden symbol?"); 524 return make<Defined>( 525 name, isec->file, isec, value, size, sym.n_desc & N_WEAK_DEF, 526 /*isExternal=*/false, /*isPrivateExtern=*/false, 527 sym.n_desc & N_ARM_THUMB_DEF, sym.n_desc & REFERENCED_DYNAMICALLY, 528 sym.n_desc & N_NO_DEAD_STRIP); 529 } 530 531 // Absolute symbols are defined symbols that do not have an associated 532 // InputSection. They cannot be weak. 533 template <class NList> 534 static macho::Symbol *createAbsolute(const NList &sym, InputFile *file, 535 StringRef name) { 536 if (sym.n_type & (N_EXT | N_PEXT)) { 537 assert((sym.n_type & N_EXT) && "invalid input"); 538 return symtab->addDefined(name, file, nullptr, sym.n_value, /*size=*/0, 539 /*isWeakDef=*/false, sym.n_type & N_PEXT, 540 sym.n_desc & N_ARM_THUMB_DEF, 541 /*isReferencedDynamically=*/false, 542 sym.n_desc & N_NO_DEAD_STRIP); 543 } 544 return make<Defined>(name, file, nullptr, sym.n_value, /*size=*/0, 545 /*isWeakDef=*/false, 546 /*isExternal=*/false, /*isPrivateExtern=*/false, 547 sym.n_desc & N_ARM_THUMB_DEF, 548 /*isReferencedDynamically=*/false, 549 sym.n_desc & N_NO_DEAD_STRIP); 550 } 551 552 template <class NList> 553 macho::Symbol *ObjFile::parseNonSectionSymbol(const NList &sym, 554 StringRef name) { 555 uint8_t type = sym.n_type & N_TYPE; 556 switch (type) { 557 case N_UNDF: 558 return sym.n_value == 0 559 ? symtab->addUndefined(name, this, sym.n_desc & N_WEAK_REF) 560 : symtab->addCommon(name, this, sym.n_value, 561 1 << GET_COMM_ALIGN(sym.n_desc), 562 sym.n_type & N_PEXT); 563 case N_ABS: 564 return createAbsolute(sym, this, name); 565 case N_PBUD: 566 case N_INDR: 567 error("TODO: support symbols of type " + std::to_string(type)); 568 return nullptr; 569 case N_SECT: 570 llvm_unreachable( 571 "N_SECT symbols should not be passed to parseNonSectionSymbol"); 572 default: 573 llvm_unreachable("invalid symbol type"); 574 } 575 } 576 577 template <class LP> 578 void ObjFile::parseSymbols(ArrayRef<typename LP::section> sectionHeaders, 579 ArrayRef<typename LP::nlist> nList, 580 const char *strtab, bool subsectionsViaSymbols) { 581 using NList = typename LP::nlist; 582 583 // Groups indices of the symbols by the sections that contain them. 584 std::vector<std::vector<uint32_t>> symbolsBySection(subsections.size()); 585 symbols.resize(nList.size()); 586 for (uint32_t i = 0; i < nList.size(); ++i) { 587 const NList &sym = nList[i]; 588 StringRef name = strtab + sym.n_strx; 589 if ((sym.n_type & N_TYPE) == N_SECT) { 590 SubsectionMap &subsecMap = subsections[sym.n_sect - 1]; 591 // parseSections() may have chosen not to parse this section. 592 if (subsecMap.empty()) 593 continue; 594 symbolsBySection[sym.n_sect - 1].push_back(i); 595 } else { 596 symbols[i] = parseNonSectionSymbol(sym, name); 597 } 598 } 599 600 // Calculate symbol sizes and create subsections by splitting the sections 601 // along symbol boundaries. 602 for (size_t i = 0; i < subsections.size(); ++i) { 603 SubsectionMap &subsecMap = subsections[i]; 604 if (subsecMap.empty()) 605 continue; 606 607 std::vector<uint32_t> &symbolIndices = symbolsBySection[i]; 608 llvm::sort(symbolIndices, [&](uint32_t lhs, uint32_t rhs) { 609 return nList[lhs].n_value < nList[rhs].n_value; 610 }); 611 uint64_t sectionAddr = sectionHeaders[i].addr; 612 uint32_t sectionAlign = 1u << sectionHeaders[i].align; 613 614 // We populate subsecMap by repeatedly splitting the last (highest address) 615 // subsection. 616 SubsectionEntry subsecEntry = subsecMap.back(); 617 for (size_t j = 0; j < symbolIndices.size(); ++j) { 618 uint32_t symIndex = symbolIndices[j]; 619 const NList &sym = nList[symIndex]; 620 StringRef name = strtab + sym.n_strx; 621 InputSection *isec = subsecEntry.isec; 622 623 uint64_t subsecAddr = sectionAddr + subsecEntry.offset; 624 uint64_t symbolOffset = sym.n_value - subsecAddr; 625 uint64_t symbolSize = 626 j + 1 < symbolIndices.size() 627 ? nList[symbolIndices[j + 1]].n_value - sym.n_value 628 : isec->data.size() - symbolOffset; 629 // There are 4 cases where we do not need to create a new subsection: 630 // 1. If the input file does not use subsections-via-symbols. 631 // 2. Multiple symbols at the same address only induce one subsection. 632 // (The symbolOffset == 0 check covers both this case as well as 633 // the first loop iteration.) 634 // 3. Alternative entry points do not induce new subsections. 635 // 4. If we have a literal section (e.g. __cstring and __literal4). 636 if (!subsectionsViaSymbols || symbolOffset == 0 || 637 sym.n_desc & N_ALT_ENTRY || !isa<ConcatInputSection>(isec)) { 638 symbols[symIndex] = 639 createDefined(sym, name, isec, symbolOffset, symbolSize); 640 continue; 641 } 642 auto *concatIsec = cast<ConcatInputSection>(isec); 643 644 auto *nextIsec = make<ConcatInputSection>(*concatIsec); 645 nextIsec->data = isec->data.slice(symbolOffset); 646 nextIsec->numRefs = 0; 647 nextIsec->wasCoalesced = false; 648 isec->data = isec->data.slice(0, symbolOffset); 649 650 // By construction, the symbol will be at offset zero in the new 651 // subsection. 652 symbols[symIndex] = 653 createDefined(sym, name, nextIsec, /*value=*/0, symbolSize); 654 // TODO: ld64 appears to preserve the original alignment as well as each 655 // subsection's offset from the last aligned address. We should consider 656 // emulating that behavior. 657 nextIsec->align = MinAlign(sectionAlign, sym.n_value); 658 subsecMap.push_back({sym.n_value - sectionAddr, nextIsec}); 659 subsecEntry = subsecMap.back(); 660 } 661 } 662 } 663 664 OpaqueFile::OpaqueFile(MemoryBufferRef mb, StringRef segName, 665 StringRef sectName) 666 : InputFile(OpaqueKind, mb) { 667 ConcatInputSection *isec = 668 make<ConcatInputSection>(segName.take_front(16), sectName.take_front(16)); 669 isec->file = this; 670 const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 671 isec->data = {buf, mb.getBufferSize()}; 672 isec->live = true; 673 subsections.push_back({{0, isec}}); 674 } 675 676 ObjFile::ObjFile(MemoryBufferRef mb, uint32_t modTime, StringRef archiveName) 677 : InputFile(ObjKind, mb), modTime(modTime) { 678 this->archiveName = std::string(archiveName); 679 if (target->wordSize == 8) 680 parse<LP64>(); 681 else 682 parse<ILP32>(); 683 } 684 685 template <class LP> void ObjFile::parse() { 686 using Header = typename LP::mach_header; 687 using SegmentCommand = typename LP::segment_command; 688 using Section = typename LP::section; 689 using NList = typename LP::nlist; 690 691 auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 692 auto *hdr = reinterpret_cast<const Header *>(mb.getBufferStart()); 693 694 Architecture arch = getArchitectureFromCpuType(hdr->cputype, hdr->cpusubtype); 695 if (arch != config->arch()) { 696 error(toString(this) + " has architecture " + getArchitectureName(arch) + 697 " which is incompatible with target architecture " + 698 getArchitectureName(config->arch())); 699 return; 700 } 701 702 if (!checkCompatibility(this)) 703 return; 704 705 for (auto *cmd : findCommands<linker_option_command>(hdr, LC_LINKER_OPTION)) { 706 StringRef data{reinterpret_cast<const char *>(cmd + 1), 707 cmd->cmdsize - sizeof(linker_option_command)}; 708 parseLCLinkerOption(this, cmd->count, data); 709 } 710 711 ArrayRef<Section> sectionHeaders; 712 if (const load_command *cmd = findCommand(hdr, LP::segmentLCType)) { 713 auto *c = reinterpret_cast<const SegmentCommand *>(cmd); 714 sectionHeaders = 715 ArrayRef<Section>{reinterpret_cast<const Section *>(c + 1), c->nsects}; 716 parseSections(sectionHeaders); 717 } 718 719 // TODO: Error on missing LC_SYMTAB? 720 if (const load_command *cmd = findCommand(hdr, LC_SYMTAB)) { 721 auto *c = reinterpret_cast<const symtab_command *>(cmd); 722 ArrayRef<NList> nList(reinterpret_cast<const NList *>(buf + c->symoff), 723 c->nsyms); 724 const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff; 725 bool subsectionsViaSymbols = hdr->flags & MH_SUBSECTIONS_VIA_SYMBOLS; 726 parseSymbols<LP>(sectionHeaders, nList, strtab, subsectionsViaSymbols); 727 } 728 729 // The relocations may refer to the symbols, so we parse them after we have 730 // parsed all the symbols. 731 for (size_t i = 0, n = subsections.size(); i < n; ++i) 732 if (!subsections[i].empty()) 733 parseRelocations(sectionHeaders, sectionHeaders[i], subsections[i]); 734 735 parseDebugInfo(); 736 if (config->emitDataInCodeInfo) 737 parseDataInCode(); 738 } 739 740 void ObjFile::parseDebugInfo() { 741 std::unique_ptr<DwarfObject> dObj = DwarfObject::create(this); 742 if (!dObj) 743 return; 744 745 auto *ctx = make<DWARFContext>( 746 std::move(dObj), "", 747 [&](Error err) { 748 warn(toString(this) + ": " + toString(std::move(err))); 749 }, 750 [&](Error warning) { 751 warn(toString(this) + ": " + toString(std::move(warning))); 752 }); 753 754 // TODO: Since object files can contain a lot of DWARF info, we should verify 755 // that we are parsing just the info we need 756 const DWARFContext::compile_unit_range &units = ctx->compile_units(); 757 // FIXME: There can be more than one compile unit per object file. See 758 // PR48637. 759 auto it = units.begin(); 760 compileUnit = it->get(); 761 } 762 763 void ObjFile::parseDataInCode() { 764 const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 765 const load_command *cmd = findCommand(buf, LC_DATA_IN_CODE); 766 if (!cmd) 767 return; 768 const auto *c = reinterpret_cast<const linkedit_data_command *>(cmd); 769 dataInCodeEntries = { 770 reinterpret_cast<const data_in_code_entry *>(buf + c->dataoff), 771 c->datasize / sizeof(data_in_code_entry)}; 772 assert(is_sorted(dataInCodeEntries, [](const data_in_code_entry &lhs, 773 const data_in_code_entry &rhs) { 774 return lhs.offset < rhs.offset; 775 })); 776 } 777 778 // The path can point to either a dylib or a .tbd file. 779 static DylibFile *loadDylib(StringRef path, DylibFile *umbrella) { 780 Optional<MemoryBufferRef> mbref = readFile(path); 781 if (!mbref) { 782 error("could not read dylib file at " + path); 783 return nullptr; 784 } 785 return loadDylib(*mbref, umbrella); 786 } 787 788 // TBD files are parsed into a series of TAPI documents (InterfaceFiles), with 789 // the first document storing child pointers to the rest of them. When we are 790 // processing a given TBD file, we store that top-level document in 791 // currentTopLevelTapi. When processing re-exports, we search its children for 792 // potentially matching documents in the same TBD file. Note that the children 793 // themselves don't point to further documents, i.e. this is a two-level tree. 794 // 795 // Re-exports can either refer to on-disk files, or to documents within .tbd 796 // files. 797 static DylibFile *findDylib(StringRef path, DylibFile *umbrella, 798 const InterfaceFile *currentTopLevelTapi) { 799 if (path::is_absolute(path, path::Style::posix)) 800 for (StringRef root : config->systemLibraryRoots) 801 if (Optional<std::string> dylibPath = 802 resolveDylibPath((root + path).str())) 803 return loadDylib(*dylibPath, umbrella); 804 805 // TODO: Handle -dylib_file 806 807 SmallString<128> newPath; 808 if (config->outputType == MH_EXECUTE && 809 path.consume_front("@executable_path/")) { 810 // ld64 allows overriding this with the undocumented flag -executable_path. 811 // lld doesn't currently implement that flag. 812 path::append(newPath, path::parent_path(config->outputFile), path); 813 path = newPath; 814 } else if (path.consume_front("@loader_path/")) { 815 fs::real_path(umbrella->getName(), newPath); 816 path::remove_filename(newPath); 817 path::append(newPath, path); 818 path = newPath; 819 } else if (path.startswith("@rpath/")) { 820 for (StringRef rpath : umbrella->rpaths) { 821 newPath.clear(); 822 if (rpath.consume_front("@loader_path/")) { 823 fs::real_path(umbrella->getName(), newPath); 824 path::remove_filename(newPath); 825 } 826 path::append(newPath, rpath, path.drop_front(strlen("@rpath/"))); 827 if (Optional<std::string> dylibPath = resolveDylibPath(newPath)) 828 return loadDylib(*dylibPath, umbrella); 829 } 830 } 831 832 if (currentTopLevelTapi) { 833 for (InterfaceFile &child : 834 make_pointee_range(currentTopLevelTapi->documents())) { 835 assert(child.documents().empty()); 836 if (path == child.getInstallName()) { 837 auto file = make<DylibFile>(child, umbrella); 838 file->parseReexports(child); 839 return file; 840 } 841 } 842 } 843 844 if (Optional<std::string> dylibPath = resolveDylibPath(path)) 845 return loadDylib(*dylibPath, umbrella); 846 847 return nullptr; 848 } 849 850 // If a re-exported dylib is public (lives in /usr/lib or 851 // /System/Library/Frameworks), then it is considered implicitly linked: we 852 // should bind to its symbols directly instead of via the re-exporting umbrella 853 // library. 854 static bool isImplicitlyLinked(StringRef path) { 855 if (!config->implicitDylibs) 856 return false; 857 858 if (path::parent_path(path) == "/usr/lib") 859 return true; 860 861 // Match /System/Library/Frameworks/$FOO.framework/**/$FOO 862 if (path.consume_front("/System/Library/Frameworks/")) { 863 StringRef frameworkName = path.take_until([](char c) { return c == '.'; }); 864 return path::filename(path) == frameworkName; 865 } 866 867 return false; 868 } 869 870 static void loadReexport(StringRef path, DylibFile *umbrella, 871 const InterfaceFile *currentTopLevelTapi) { 872 DylibFile *reexport = findDylib(path, umbrella, currentTopLevelTapi); 873 if (!reexport) 874 error("unable to locate re-export with install name " + path); 875 } 876 877 DylibFile::DylibFile(MemoryBufferRef mb, DylibFile *umbrella, 878 bool isBundleLoader) 879 : InputFile(DylibKind, mb), refState(RefState::Unreferenced), 880 isBundleLoader(isBundleLoader) { 881 assert(!isBundleLoader || !umbrella); 882 if (umbrella == nullptr) 883 umbrella = this; 884 this->umbrella = umbrella; 885 886 auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 887 auto *hdr = reinterpret_cast<const mach_header *>(mb.getBufferStart()); 888 889 // Initialize installName. 890 if (const load_command *cmd = findCommand(hdr, LC_ID_DYLIB)) { 891 auto *c = reinterpret_cast<const dylib_command *>(cmd); 892 currentVersion = read32le(&c->dylib.current_version); 893 compatibilityVersion = read32le(&c->dylib.compatibility_version); 894 installName = 895 reinterpret_cast<const char *>(cmd) + read32le(&c->dylib.name); 896 } else if (!isBundleLoader) { 897 // macho_executable and macho_bundle don't have LC_ID_DYLIB, 898 // so it's OK. 899 error("dylib " + toString(this) + " missing LC_ID_DYLIB load command"); 900 return; 901 } 902 903 if (config->printEachFile) 904 message(toString(this)); 905 inputFiles.insert(this); 906 907 deadStrippable = hdr->flags & MH_DEAD_STRIPPABLE_DYLIB; 908 909 if (!checkCompatibility(this)) 910 return; 911 912 for (auto *cmd : findCommands<rpath_command>(hdr, LC_RPATH)) { 913 StringRef rpath{reinterpret_cast<const char *>(cmd) + cmd->path}; 914 rpaths.push_back(rpath); 915 } 916 917 // Initialize symbols. 918 exportingFile = isImplicitlyLinked(installName) ? this : this->umbrella; 919 if (const load_command *cmd = findCommand(hdr, LC_DYLD_INFO_ONLY)) { 920 auto *c = reinterpret_cast<const dyld_info_command *>(cmd); 921 parseTrie(buf + c->export_off, c->export_size, 922 [&](const Twine &name, uint64_t flags) { 923 StringRef savedName = saver.save(name); 924 if (handleLDSymbol(savedName)) 925 return; 926 bool isWeakDef = flags & EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION; 927 bool isTlv = flags & EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL; 928 symbols.push_back(symtab->addDylib(savedName, exportingFile, 929 isWeakDef, isTlv)); 930 }); 931 } else { 932 error("LC_DYLD_INFO_ONLY not found in " + toString(this)); 933 return; 934 } 935 } 936 937 void DylibFile::parseLoadCommands(MemoryBufferRef mb) { 938 auto *hdr = reinterpret_cast<const mach_header *>(mb.getBufferStart()); 939 const uint8_t *p = reinterpret_cast<const uint8_t *>(mb.getBufferStart()) + 940 target->headerSize; 941 for (uint32_t i = 0, n = hdr->ncmds; i < n; ++i) { 942 auto *cmd = reinterpret_cast<const load_command *>(p); 943 p += cmd->cmdsize; 944 945 if (!(hdr->flags & MH_NO_REEXPORTED_DYLIBS) && 946 cmd->cmd == LC_REEXPORT_DYLIB) { 947 const auto *c = reinterpret_cast<const dylib_command *>(cmd); 948 StringRef reexportPath = 949 reinterpret_cast<const char *>(c) + read32le(&c->dylib.name); 950 loadReexport(reexportPath, exportingFile, nullptr); 951 } 952 953 // FIXME: What about LC_LOAD_UPWARD_DYLIB, LC_LAZY_LOAD_DYLIB, 954 // LC_LOAD_WEAK_DYLIB, LC_REEXPORT_DYLIB (..are reexports from dylibs with 955 // MH_NO_REEXPORTED_DYLIBS loaded for -flat_namespace)? 956 if (config->namespaceKind == NamespaceKind::flat && 957 cmd->cmd == LC_LOAD_DYLIB) { 958 const auto *c = reinterpret_cast<const dylib_command *>(cmd); 959 StringRef dylibPath = 960 reinterpret_cast<const char *>(c) + read32le(&c->dylib.name); 961 DylibFile *dylib = findDylib(dylibPath, umbrella, nullptr); 962 if (!dylib) 963 error(Twine("unable to locate library '") + dylibPath + 964 "' loaded from '" + toString(this) + "' for -flat_namespace"); 965 } 966 } 967 } 968 969 // Some versions of XCode ship with .tbd files that don't have the right 970 // platform settings. 971 static constexpr std::array<StringRef, 3> skipPlatformChecks{ 972 "/usr/lib/system/libsystem_kernel.dylib", 973 "/usr/lib/system/libsystem_platform.dylib", 974 "/usr/lib/system/libsystem_pthread.dylib"}; 975 976 DylibFile::DylibFile(const InterfaceFile &interface, DylibFile *umbrella, 977 bool isBundleLoader) 978 : InputFile(DylibKind, interface), refState(RefState::Unreferenced), 979 isBundleLoader(isBundleLoader) { 980 // FIXME: Add test for the missing TBD code path. 981 982 if (umbrella == nullptr) 983 umbrella = this; 984 this->umbrella = umbrella; 985 986 installName = saver.save(interface.getInstallName()); 987 compatibilityVersion = interface.getCompatibilityVersion().rawValue(); 988 currentVersion = interface.getCurrentVersion().rawValue(); 989 990 if (config->printEachFile) 991 message(toString(this)); 992 inputFiles.insert(this); 993 994 if (!is_contained(skipPlatformChecks, installName) && 995 !is_contained(interface.targets(), config->platformInfo.target)) { 996 error(toString(this) + " is incompatible with " + 997 std::string(config->platformInfo.target)); 998 return; 999 } 1000 1001 exportingFile = isImplicitlyLinked(installName) ? this : umbrella; 1002 auto addSymbol = [&](const Twine &name) -> void { 1003 symbols.push_back(symtab->addDylib(saver.save(name), exportingFile, 1004 /*isWeakDef=*/false, 1005 /*isTlv=*/false)); 1006 }; 1007 // TODO(compnerd) filter out symbols based on the target platform 1008 // TODO: handle weak defs, thread locals 1009 for (const auto *symbol : interface.symbols()) { 1010 if (!symbol->getArchitectures().has(config->arch())) 1011 continue; 1012 1013 if (handleLDSymbol(symbol->getName())) 1014 continue; 1015 1016 switch (symbol->getKind()) { 1017 case SymbolKind::GlobalSymbol: 1018 addSymbol(symbol->getName()); 1019 break; 1020 case SymbolKind::ObjectiveCClass: 1021 // XXX ld64 only creates these symbols when -ObjC is passed in. We may 1022 // want to emulate that. 1023 addSymbol(objc::klass + symbol->getName()); 1024 addSymbol(objc::metaclass + symbol->getName()); 1025 break; 1026 case SymbolKind::ObjectiveCClassEHType: 1027 addSymbol(objc::ehtype + symbol->getName()); 1028 break; 1029 case SymbolKind::ObjectiveCInstanceVariable: 1030 addSymbol(objc::ivar + symbol->getName()); 1031 break; 1032 } 1033 } 1034 } 1035 1036 void DylibFile::parseReexports(const InterfaceFile &interface) { 1037 const InterfaceFile *topLevel = 1038 interface.getParent() == nullptr ? &interface : interface.getParent(); 1039 for (InterfaceFileRef intfRef : interface.reexportedLibraries()) { 1040 InterfaceFile::const_target_range targets = intfRef.targets(); 1041 if (is_contained(skipPlatformChecks, intfRef.getInstallName()) || 1042 is_contained(targets, config->platformInfo.target)) 1043 loadReexport(intfRef.getInstallName(), exportingFile, topLevel); 1044 } 1045 } 1046 1047 // $ld$ symbols modify the properties/behavior of the library (e.g. its install 1048 // name, compatibility version or hide/add symbols) for specific target 1049 // versions. 1050 bool DylibFile::handleLDSymbol(StringRef originalName) { 1051 if (!originalName.startswith("$ld$")) 1052 return false; 1053 1054 StringRef action; 1055 StringRef name; 1056 std::tie(action, name) = originalName.drop_front(strlen("$ld$")).split('$'); 1057 if (action == "previous") 1058 handleLDPreviousSymbol(name, originalName); 1059 else if (action == "install_name") 1060 handleLDInstallNameSymbol(name, originalName); 1061 return true; 1062 } 1063 1064 void DylibFile::handleLDPreviousSymbol(StringRef name, StringRef originalName) { 1065 // originalName: $ld$ previous $ <installname> $ <compatversion> $ 1066 // <platformstr> $ <startversion> $ <endversion> $ <symbol-name> $ 1067 StringRef installName; 1068 StringRef compatVersion; 1069 StringRef platformStr; 1070 StringRef startVersion; 1071 StringRef endVersion; 1072 StringRef symbolName; 1073 StringRef rest; 1074 1075 std::tie(installName, name) = name.split('$'); 1076 std::tie(compatVersion, name) = name.split('$'); 1077 std::tie(platformStr, name) = name.split('$'); 1078 std::tie(startVersion, name) = name.split('$'); 1079 std::tie(endVersion, name) = name.split('$'); 1080 std::tie(symbolName, rest) = name.split('$'); 1081 // TODO: ld64 contains some logic for non-empty symbolName as well. 1082 if (!symbolName.empty()) 1083 return; 1084 unsigned platform; 1085 if (platformStr.getAsInteger(10, platform) || 1086 platform != static_cast<unsigned>(config->platform())) 1087 return; 1088 1089 VersionTuple start; 1090 if (start.tryParse(startVersion)) { 1091 warn("failed to parse start version, symbol '" + originalName + 1092 "' ignored"); 1093 return; 1094 } 1095 VersionTuple end; 1096 if (end.tryParse(endVersion)) { 1097 warn("failed to parse end version, symbol '" + originalName + "' ignored"); 1098 return; 1099 } 1100 if (config->platformInfo.minimum < start || 1101 config->platformInfo.minimum >= end) 1102 return; 1103 1104 this->installName = saver.save(installName); 1105 1106 if (!compatVersion.empty()) { 1107 VersionTuple cVersion; 1108 if (cVersion.tryParse(compatVersion)) { 1109 warn("failed to parse compatibility version, symbol '" + originalName + 1110 "' ignored"); 1111 return; 1112 } 1113 compatibilityVersion = encodeVersion(cVersion); 1114 } 1115 } 1116 1117 void DylibFile::handleLDInstallNameSymbol(StringRef name, 1118 StringRef originalName) { 1119 // originalName: $ld$ install_name $ os<version> $ install_name 1120 StringRef condition, installName; 1121 std::tie(condition, installName) = name.split('$'); 1122 VersionTuple version; 1123 if (!condition.consume_front("os") || version.tryParse(condition)) 1124 warn("failed to parse os version, symbol '" + originalName + "' ignored"); 1125 else if (version == config->platformInfo.minimum) 1126 this->installName = saver.save(installName); 1127 } 1128 1129 ArchiveFile::ArchiveFile(std::unique_ptr<object::Archive> &&f) 1130 : InputFile(ArchiveKind, f->getMemoryBufferRef()), file(std::move(f)) { 1131 for (const object::Archive::Symbol &sym : file->symbols()) 1132 symtab->addLazy(sym.getName(), this, sym); 1133 } 1134 1135 void ArchiveFile::fetch(const object::Archive::Symbol &sym) { 1136 object::Archive::Child c = 1137 CHECK(sym.getMember(), toString(this) + 1138 ": could not get the member for symbol " + 1139 toMachOString(sym)); 1140 1141 if (!seen.insert(c.getChildOffset()).second) 1142 return; 1143 1144 MemoryBufferRef mb = 1145 CHECK(c.getMemoryBufferRef(), 1146 toString(this) + 1147 ": could not get the buffer for the member defining symbol " + 1148 toMachOString(sym)); 1149 1150 if (tar && c.getParent()->isThin()) 1151 tar->append(relativeToRoot(CHECK(c.getFullName(), this)), mb.getBuffer()); 1152 1153 uint32_t modTime = toTimeT( 1154 CHECK(c.getLastModified(), toString(this) + 1155 ": could not get the modification time " 1156 "for the member defining symbol " + 1157 toMachOString(sym))); 1158 1159 // `sym` is owned by a LazySym, which will be replace<>()d by make<ObjFile> 1160 // and become invalid after that call. Copy it to the stack so we can refer 1161 // to it later. 1162 const object::Archive::Symbol symCopy = sym; 1163 1164 if (Optional<InputFile *> file = 1165 loadArchiveMember(mb, modTime, getName(), /*objCOnly=*/false)) { 1166 inputFiles.insert(*file); 1167 // ld64 doesn't demangle sym here even with -demangle. 1168 // Match that: intentionally don't call toMachOString(). 1169 printArchiveMemberLoad(symCopy.getName(), *file); 1170 } 1171 } 1172 1173 static macho::Symbol *createBitcodeSymbol(const lto::InputFile::Symbol &objSym, 1174 BitcodeFile &file) { 1175 StringRef name = saver.save(objSym.getName()); 1176 1177 // TODO: support weak references 1178 if (objSym.isUndefined()) 1179 return symtab->addUndefined(name, &file, /*isWeakRef=*/false); 1180 1181 assert(!objSym.isCommon() && "TODO: support common symbols in LTO"); 1182 1183 // TODO: Write a test demonstrating why computing isPrivateExtern before 1184 // LTO compilation is important. 1185 bool isPrivateExtern = false; 1186 switch (objSym.getVisibility()) { 1187 case GlobalValue::HiddenVisibility: 1188 isPrivateExtern = true; 1189 break; 1190 case GlobalValue::ProtectedVisibility: 1191 error(name + " has protected visibility, which is not supported by Mach-O"); 1192 break; 1193 case GlobalValue::DefaultVisibility: 1194 break; 1195 } 1196 1197 return symtab->addDefined(name, &file, /*isec=*/nullptr, /*value=*/0, 1198 /*size=*/0, objSym.isWeak(), isPrivateExtern, 1199 /*isThumb=*/false, 1200 /*isReferencedDynamically=*/false, 1201 /*noDeadStrip=*/false); 1202 } 1203 1204 BitcodeFile::BitcodeFile(MemoryBufferRef mbref) 1205 : InputFile(BitcodeKind, mbref) { 1206 obj = check(lto::InputFile::create(mbref)); 1207 1208 // Convert LTO Symbols to LLD Symbols in order to perform resolution. The 1209 // "winning" symbol will then be marked as Prevailing at LTO compilation 1210 // time. 1211 for (const lto::InputFile::Symbol &objSym : obj->symbols()) 1212 symbols.push_back(createBitcodeSymbol(objSym, *this)); 1213 } 1214 1215 template void ObjFile::parse<LP64>(); 1216