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 // (The symbolOffset == 0 check covers both this case as well as 603 // the first loop iteration.) 604 // 3. Alternative entry points do not induce new subsections. 605 if (!subsectionsViaSymbols || symbolOffset == 0 || 606 sym.n_desc & N_ALT_ENTRY) { 607 symbols[symIndex] = 608 createDefined(sym, name, isec, symbolOffset, symbolSize); 609 continue; 610 } 611 612 auto *nextIsec = make<InputSection>(*isec); 613 nextIsec->data = isec->data.slice(symbolOffset); 614 nextIsec->numRefs = 0; 615 nextIsec->canOmitFromOutput = false; 616 isec->data = isec->data.slice(0, symbolOffset); 617 618 // By construction, the symbol will be at offset zero in the new 619 // subsection. 620 symbols[symIndex] = 621 createDefined(sym, name, nextIsec, /*value=*/0, symbolSize); 622 // TODO: ld64 appears to preserve the original alignment as well as each 623 // subsection's offset from the last aligned address. We should consider 624 // emulating that behavior. 625 nextIsec->align = MinAlign(isec->align, sym.n_value); 626 subsecMap.push_back({sym.n_value - sectionAddr, nextIsec}); 627 subsecEntry = subsecMap.back(); 628 } 629 } 630 } 631 632 OpaqueFile::OpaqueFile(MemoryBufferRef mb, StringRef segName, 633 StringRef sectName) 634 : InputFile(OpaqueKind, mb) { 635 InputSection *isec = make<InputSection>(); 636 isec->file = this; 637 isec->name = sectName.take_front(16); 638 isec->segname = segName.take_front(16); 639 const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 640 isec->data = {buf, mb.getBufferSize()}; 641 subsections.push_back({{0, isec}}); 642 } 643 644 ObjFile::ObjFile(MemoryBufferRef mb, uint32_t modTime, StringRef archiveName) 645 : InputFile(ObjKind, mb), modTime(modTime) { 646 this->archiveName = std::string(archiveName); 647 if (target->wordSize == 8) 648 parse<LP64>(); 649 else 650 parse<ILP32>(); 651 } 652 653 template <class LP> void ObjFile::parse() { 654 using Header = typename LP::mach_header; 655 using SegmentCommand = typename LP::segment_command; 656 using Section = typename LP::section; 657 using NList = typename LP::nlist; 658 659 auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 660 auto *hdr = reinterpret_cast<const Header *>(mb.getBufferStart()); 661 662 Architecture arch = getArchitectureFromCpuType(hdr->cputype, hdr->cpusubtype); 663 if (arch != config->arch()) { 664 error(toString(this) + " has architecture " + getArchitectureName(arch) + 665 " which is incompatible with target architecture " + 666 getArchitectureName(config->arch())); 667 return; 668 } 669 670 if (!checkCompatibility(this)) 671 return; 672 673 if (const load_command *cmd = findCommand(hdr, LC_LINKER_OPTION)) { 674 auto *c = reinterpret_cast<const linker_option_command *>(cmd); 675 StringRef data{reinterpret_cast<const char *>(c + 1), 676 c->cmdsize - sizeof(linker_option_command)}; 677 parseLCLinkerOption(this, c->count, data); 678 } 679 680 ArrayRef<Section> sectionHeaders; 681 if (const load_command *cmd = findCommand(hdr, LP::segmentLCType)) { 682 auto *c = reinterpret_cast<const SegmentCommand *>(cmd); 683 sectionHeaders = 684 ArrayRef<Section>{reinterpret_cast<const Section *>(c + 1), c->nsects}; 685 parseSections(sectionHeaders); 686 } 687 688 // TODO: Error on missing LC_SYMTAB? 689 if (const load_command *cmd = findCommand(hdr, LC_SYMTAB)) { 690 auto *c = reinterpret_cast<const symtab_command *>(cmd); 691 ArrayRef<NList> nList(reinterpret_cast<const NList *>(buf + c->symoff), 692 c->nsyms); 693 const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff; 694 bool subsectionsViaSymbols = hdr->flags & MH_SUBSECTIONS_VIA_SYMBOLS; 695 parseSymbols<LP>(sectionHeaders, nList, strtab, subsectionsViaSymbols); 696 } 697 698 // The relocations may refer to the symbols, so we parse them after we have 699 // parsed all the symbols. 700 for (size_t i = 0, n = subsections.size(); i < n; ++i) 701 if (!subsections[i].empty()) 702 parseRelocations(sectionHeaders, sectionHeaders[i], subsections[i]); 703 704 parseDebugInfo(); 705 } 706 707 void ObjFile::parseDebugInfo() { 708 std::unique_ptr<DwarfObject> dObj = DwarfObject::create(this); 709 if (!dObj) 710 return; 711 712 auto *ctx = make<DWARFContext>( 713 std::move(dObj), "", 714 [&](Error err) { 715 warn(toString(this) + ": " + toString(std::move(err))); 716 }, 717 [&](Error warning) { 718 warn(toString(this) + ": " + toString(std::move(warning))); 719 }); 720 721 // TODO: Since object files can contain a lot of DWARF info, we should verify 722 // that we are parsing just the info we need 723 const DWARFContext::compile_unit_range &units = ctx->compile_units(); 724 // FIXME: There can be more than one compile unit per object file. See 725 // PR48637. 726 auto it = units.begin(); 727 compileUnit = it->get(); 728 } 729 730 // The path can point to either a dylib or a .tbd file. 731 static Optional<DylibFile *> loadDylib(StringRef path, DylibFile *umbrella) { 732 Optional<MemoryBufferRef> mbref = readFile(path); 733 if (!mbref) { 734 error("could not read dylib file at " + path); 735 return {}; 736 } 737 return loadDylib(*mbref, umbrella); 738 } 739 740 // TBD files are parsed into a series of TAPI documents (InterfaceFiles), with 741 // the first document storing child pointers to the rest of them. When we are 742 // processing a given TBD file, we store that top-level document in 743 // currentTopLevelTapi. When processing re-exports, we search its children for 744 // potentially matching documents in the same TBD file. Note that the children 745 // themselves don't point to further documents, i.e. this is a two-level tree. 746 // 747 // Re-exports can either refer to on-disk files, or to documents within .tbd 748 // files. 749 static Optional<DylibFile *> 750 findDylib(StringRef path, DylibFile *umbrella, 751 const InterfaceFile *currentTopLevelTapi) { 752 if (path::is_absolute(path, path::Style::posix)) 753 for (StringRef root : config->systemLibraryRoots) 754 if (Optional<std::string> dylibPath = 755 resolveDylibPath((root + path).str())) 756 return loadDylib(*dylibPath, umbrella); 757 758 // TODO: Expand @loader_path, @executable_path, @rpath etc, handle -dylib_path 759 760 if (currentTopLevelTapi) { 761 for (InterfaceFile &child : 762 make_pointee_range(currentTopLevelTapi->documents())) { 763 assert(child.documents().empty()); 764 if (path == child.getInstallName()) 765 return make<DylibFile>(child, umbrella); 766 } 767 } 768 769 if (Optional<std::string> dylibPath = resolveDylibPath(path)) 770 return loadDylib(*dylibPath, umbrella); 771 772 return {}; 773 } 774 775 // If a re-exported dylib is public (lives in /usr/lib or 776 // /System/Library/Frameworks), then it is considered implicitly linked: we 777 // should bind to its symbols directly instead of via the re-exporting umbrella 778 // library. 779 static bool isImplicitlyLinked(StringRef path) { 780 if (!config->implicitDylibs) 781 return false; 782 783 if (path::parent_path(path) == "/usr/lib") 784 return true; 785 786 // Match /System/Library/Frameworks/$FOO.framework/**/$FOO 787 if (path.consume_front("/System/Library/Frameworks/")) { 788 StringRef frameworkName = path.take_until([](char c) { return c == '.'; }); 789 return path::filename(path) == frameworkName; 790 } 791 792 return false; 793 } 794 795 void loadReexport(StringRef path, DylibFile *umbrella, 796 const InterfaceFile *currentTopLevelTapi) { 797 Optional<DylibFile *> reexport = 798 findDylib(path, umbrella, currentTopLevelTapi); 799 if (!reexport) 800 error("unable to locate re-export with install name " + path); 801 else if (isImplicitlyLinked(path)) 802 inputFiles.insert(*reexport); 803 } 804 805 DylibFile::DylibFile(MemoryBufferRef mb, DylibFile *umbrella, 806 bool isBundleLoader) 807 : InputFile(DylibKind, mb), refState(RefState::Unreferenced), 808 isBundleLoader(isBundleLoader) { 809 assert(!isBundleLoader || !umbrella); 810 if (umbrella == nullptr) 811 umbrella = this; 812 813 auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 814 auto *hdr = reinterpret_cast<const mach_header *>(mb.getBufferStart()); 815 816 // Initialize dylibName. 817 if (const load_command *cmd = findCommand(hdr, LC_ID_DYLIB)) { 818 auto *c = reinterpret_cast<const dylib_command *>(cmd); 819 currentVersion = read32le(&c->dylib.current_version); 820 compatibilityVersion = read32le(&c->dylib.compatibility_version); 821 dylibName = reinterpret_cast<const char *>(cmd) + read32le(&c->dylib.name); 822 } else if (!isBundleLoader) { 823 // macho_executable and macho_bundle don't have LC_ID_DYLIB, 824 // so it's OK. 825 error("dylib " + toString(this) + " missing LC_ID_DYLIB load command"); 826 return; 827 } 828 829 if (!checkCompatibility(this)) 830 return; 831 832 // Initialize symbols. 833 DylibFile *exportingFile = isImplicitlyLinked(dylibName) ? this : umbrella; 834 if (const load_command *cmd = findCommand(hdr, LC_DYLD_INFO_ONLY)) { 835 auto *c = reinterpret_cast<const dyld_info_command *>(cmd); 836 parseTrie(buf + c->export_off, c->export_size, 837 [&](const Twine &name, uint64_t flags) { 838 bool isWeakDef = flags & EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION; 839 bool isTlv = flags & EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL; 840 symbols.push_back(symtab->addDylib( 841 saver.save(name), exportingFile, isWeakDef, isTlv)); 842 }); 843 } else { 844 error("LC_DYLD_INFO_ONLY not found in " + toString(this)); 845 return; 846 } 847 848 const uint8_t *p = 849 reinterpret_cast<const uint8_t *>(hdr) + target->headerSize; 850 for (uint32_t i = 0, n = hdr->ncmds; i < n; ++i) { 851 auto *cmd = reinterpret_cast<const load_command *>(p); 852 p += cmd->cmdsize; 853 854 if (!(hdr->flags & MH_NO_REEXPORTED_DYLIBS) && 855 cmd->cmd == LC_REEXPORT_DYLIB) { 856 const auto *c = reinterpret_cast<const dylib_command *>(cmd); 857 StringRef reexportPath = 858 reinterpret_cast<const char *>(c) + read32le(&c->dylib.name); 859 loadReexport(reexportPath, exportingFile, nullptr); 860 } 861 862 // FIXME: What about LC_LOAD_UPWARD_DYLIB, LC_LAZY_LOAD_DYLIB, 863 // LC_LOAD_WEAK_DYLIB, LC_REEXPORT_DYLIB (..are reexports from dylibs with 864 // MH_NO_REEXPORTED_DYLIBS loaded for -flat_namespace)? 865 if (config->namespaceKind == NamespaceKind::flat && 866 cmd->cmd == LC_LOAD_DYLIB) { 867 const auto *c = reinterpret_cast<const dylib_command *>(cmd); 868 StringRef dylibPath = 869 reinterpret_cast<const char *>(c) + read32le(&c->dylib.name); 870 Optional<DylibFile *> dylib = findDylib(dylibPath, umbrella, nullptr); 871 if (!dylib) 872 error(Twine("unable to locate library '") + dylibPath + 873 "' loaded from '" + toString(this) + "' for -flat_namespace"); 874 } 875 } 876 } 877 878 DylibFile::DylibFile(const InterfaceFile &interface, DylibFile *umbrella, 879 bool isBundleLoader) 880 : InputFile(DylibKind, interface), refState(RefState::Unreferenced), 881 isBundleLoader(isBundleLoader) { 882 // FIXME: Add test for the missing TBD code path. 883 884 if (umbrella == nullptr) 885 umbrella = this; 886 887 dylibName = saver.save(interface.getInstallName()); 888 compatibilityVersion = interface.getCompatibilityVersion().rawValue(); 889 currentVersion = interface.getCurrentVersion().rawValue(); 890 891 // Some versions of XCode ship with .tbd files that don't have the right 892 // platform settings. 893 static constexpr std::array<StringRef, 3> skipPlatformChecks{ 894 "/usr/lib/system/libsystem_kernel.dylib", 895 "/usr/lib/system/libsystem_platform.dylib", 896 "/usr/lib/system/libsystem_pthread.dylib"}; 897 898 if (!is_contained(skipPlatformChecks, dylibName) && 899 !is_contained(interface.targets(), config->platformInfo.target)) { 900 error(toString(this) + " is incompatible with " + 901 std::string(config->platformInfo.target)); 902 return; 903 } 904 905 DylibFile *exportingFile = isImplicitlyLinked(dylibName) ? this : umbrella; 906 auto addSymbol = [&](const Twine &name) -> void { 907 symbols.push_back(symtab->addDylib(saver.save(name), exportingFile, 908 /*isWeakDef=*/false, 909 /*isTlv=*/false)); 910 }; 911 // TODO(compnerd) filter out symbols based on the target platform 912 // TODO: handle weak defs, thread locals 913 for (const auto *symbol : interface.symbols()) { 914 if (!symbol->getArchitectures().has(config->arch())) 915 continue; 916 917 switch (symbol->getKind()) { 918 case SymbolKind::GlobalSymbol: 919 addSymbol(symbol->getName()); 920 break; 921 case SymbolKind::ObjectiveCClass: 922 // XXX ld64 only creates these symbols when -ObjC is passed in. We may 923 // want to emulate that. 924 addSymbol(objc::klass + symbol->getName()); 925 addSymbol(objc::metaclass + symbol->getName()); 926 break; 927 case SymbolKind::ObjectiveCClassEHType: 928 addSymbol(objc::ehtype + symbol->getName()); 929 break; 930 case SymbolKind::ObjectiveCInstanceVariable: 931 addSymbol(objc::ivar + symbol->getName()); 932 break; 933 } 934 } 935 936 const InterfaceFile *topLevel = 937 interface.getParent() == nullptr ? &interface : interface.getParent(); 938 939 for (InterfaceFileRef intfRef : interface.reexportedLibraries()) { 940 InterfaceFile::const_target_range targets = intfRef.targets(); 941 if (is_contained(skipPlatformChecks, intfRef.getInstallName()) || 942 is_contained(targets, config->platformInfo.target)) 943 loadReexport(intfRef.getInstallName(), exportingFile, topLevel); 944 } 945 } 946 947 ArchiveFile::ArchiveFile(std::unique_ptr<object::Archive> &&f) 948 : InputFile(ArchiveKind, f->getMemoryBufferRef()), file(std::move(f)) { 949 for (const object::Archive::Symbol &sym : file->symbols()) 950 symtab->addLazy(sym.getName(), this, sym); 951 } 952 953 void ArchiveFile::fetch(const object::Archive::Symbol &sym) { 954 object::Archive::Child c = 955 CHECK(sym.getMember(), toString(this) + 956 ": could not get the member for symbol " + 957 toMachOString(sym)); 958 959 if (!seen.insert(c.getChildOffset()).second) 960 return; 961 962 MemoryBufferRef mb = 963 CHECK(c.getMemoryBufferRef(), 964 toString(this) + 965 ": could not get the buffer for the member defining symbol " + 966 toMachOString(sym)); 967 968 if (tar && c.getParent()->isThin()) 969 tar->append(relativeToRoot(CHECK(c.getFullName(), this)), mb.getBuffer()); 970 971 uint32_t modTime = toTimeT( 972 CHECK(c.getLastModified(), toString(this) + 973 ": could not get the modification time " 974 "for the member defining symbol " + 975 toMachOString(sym))); 976 977 // `sym` is owned by a LazySym, which will be replace<>()d by make<ObjFile> 978 // and become invalid after that call. Copy it to the stack so we can refer 979 // to it later. 980 const object::Archive::Symbol symCopy = sym; 981 982 if (Optional<InputFile *> file = 983 loadArchiveMember(mb, modTime, getName(), /*objCOnly=*/false)) { 984 inputFiles.insert(*file); 985 // ld64 doesn't demangle sym here even with -demangle. 986 // Match that: intentionally don't call toMachOString(). 987 printArchiveMemberLoad(symCopy.getName(), *file); 988 } 989 } 990 991 static macho::Symbol *createBitcodeSymbol(const lto::InputFile::Symbol &objSym, 992 BitcodeFile &file) { 993 StringRef name = saver.save(objSym.getName()); 994 995 // TODO: support weak references 996 if (objSym.isUndefined()) 997 return symtab->addUndefined(name, &file, /*isWeakRef=*/false); 998 999 assert(!objSym.isCommon() && "TODO: support common symbols in LTO"); 1000 1001 // TODO: Write a test demonstrating why computing isPrivateExtern before 1002 // LTO compilation is important. 1003 bool isPrivateExtern = false; 1004 switch (objSym.getVisibility()) { 1005 case GlobalValue::HiddenVisibility: 1006 isPrivateExtern = true; 1007 break; 1008 case GlobalValue::ProtectedVisibility: 1009 error(name + " has protected visibility, which is not supported by Mach-O"); 1010 break; 1011 case GlobalValue::DefaultVisibility: 1012 break; 1013 } 1014 1015 return symtab->addDefined(name, &file, /*isec=*/nullptr, /*value=*/0, 1016 /*size=*/0, objSym.isWeak(), isPrivateExtern, 1017 /*isThumb=*/false); 1018 } 1019 1020 BitcodeFile::BitcodeFile(MemoryBufferRef mbref) 1021 : InputFile(BitcodeKind, mbref) { 1022 obj = check(lto::InputFile::create(mbref)); 1023 1024 // Convert LTO Symbols to LLD Symbols in order to perform resolution. The 1025 // "winning" symbol will then be marked as Prevailing at LTO compilation 1026 // time. 1027 for (const lto::InputFile::Symbol &objSym : obj->symbols()) 1028 symbols.push_back(createBitcodeSymbol(objSym, *this)); 1029 } 1030 1031 template void ObjFile::parse<LP64>(); 1032