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