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