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 70 using namespace llvm; 71 using namespace llvm::MachO; 72 using namespace llvm::support::endian; 73 using namespace llvm::sys; 74 using namespace lld; 75 using namespace lld::macho; 76 77 // Returns "<internal>", "foo.a(bar.o)", or "baz.o". 78 std::string lld::toString(const InputFile *f) { 79 if (!f) 80 return "<internal>"; 81 if (f->archiveName.empty()) 82 return std::string(f->getName()); 83 return (path::filename(f->archiveName) + "(" + path::filename(f->getName()) + 84 ")") 85 .str(); 86 } 87 88 SetVector<InputFile *> macho::inputFiles; 89 std::unique_ptr<TarWriter> macho::tar; 90 int InputFile::idCount = 0; 91 92 // Open a given file path and return it as a memory-mapped file. 93 Optional<MemoryBufferRef> macho::readFile(StringRef path) { 94 // Open a file. 95 auto mbOrErr = MemoryBuffer::getFile(path); 96 if (auto ec = mbOrErr.getError()) { 97 error("cannot open " + path + ": " + ec.message()); 98 return None; 99 } 100 101 std::unique_ptr<MemoryBuffer> &mb = *mbOrErr; 102 MemoryBufferRef mbref = mb->getMemBufferRef(); 103 make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take mb ownership 104 105 // If this is a regular non-fat file, return it. 106 const char *buf = mbref.getBufferStart(); 107 auto *hdr = reinterpret_cast<const MachO::fat_header *>(buf); 108 if (read32be(&hdr->magic) != MachO::FAT_MAGIC) { 109 if (tar) 110 tar->append(relativeToRoot(path), mbref.getBuffer()); 111 return mbref; 112 } 113 114 // Object files and archive files may be fat files, which contains 115 // multiple real files for different CPU ISAs. Here, we search for a 116 // file that matches with the current link target and returns it as 117 // a MemoryBufferRef. 118 auto *arch = reinterpret_cast<const MachO::fat_arch *>(buf + sizeof(*hdr)); 119 120 for (uint32_t i = 0, n = read32be(&hdr->nfat_arch); i < n; ++i) { 121 if (reinterpret_cast<const char *>(arch + i + 1) > 122 buf + mbref.getBufferSize()) { 123 error(path + ": fat_arch struct extends beyond end of file"); 124 return None; 125 } 126 127 if (read32be(&arch[i].cputype) != target->cpuType || 128 read32be(&arch[i].cpusubtype) != target->cpuSubtype) 129 continue; 130 131 uint32_t offset = read32be(&arch[i].offset); 132 uint32_t size = read32be(&arch[i].size); 133 if (offset + size > mbref.getBufferSize()) 134 error(path + ": slice extends beyond end of file"); 135 if (tar) 136 tar->append(relativeToRoot(path), mbref.getBuffer()); 137 return MemoryBufferRef(StringRef(buf + offset, size), path.copy(bAlloc)); 138 } 139 140 error("unable to find matching architecture in " + path); 141 return None; 142 } 143 144 const load_command *macho::findCommand(const mach_header_64 *hdr, 145 uint32_t type) { 146 const uint8_t *p = 147 reinterpret_cast<const uint8_t *>(hdr) + sizeof(mach_header_64); 148 149 for (uint32_t i = 0, n = hdr->ncmds; i < n; ++i) { 150 auto *cmd = reinterpret_cast<const load_command *>(p); 151 if (cmd->cmd == type) 152 return cmd; 153 p += cmd->cmdsize; 154 } 155 return nullptr; 156 } 157 158 void ObjFile::parseSections(ArrayRef<section_64> sections) { 159 subsections.reserve(sections.size()); 160 auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 161 162 for (const section_64 &sec : sections) { 163 InputSection *isec = make<InputSection>(); 164 isec->file = this; 165 isec->name = 166 StringRef(sec.sectname, strnlen(sec.sectname, sizeof(sec.sectname))); 167 isec->segname = 168 StringRef(sec.segname, strnlen(sec.segname, sizeof(sec.segname))); 169 isec->data = {isZeroFill(sec.flags) ? nullptr : buf + sec.offset, 170 static_cast<size_t>(sec.size)}; 171 if (sec.align >= 32) 172 error("alignment " + std::to_string(sec.align) + " of section " + 173 isec->name + " is too large"); 174 else 175 isec->align = 1 << sec.align; 176 isec->flags = sec.flags; 177 178 if (!(isDebugSection(isec->flags) && 179 isec->segname == segment_names::dwarf)) { 180 subsections.push_back({{0, isec}}); 181 } else { 182 // Instead of emitting DWARF sections, we emit STABS symbols to the 183 // object files that contain them. We filter them out early to avoid 184 // parsing their relocations unnecessarily. But we must still push an 185 // empty map to ensure the indices line up for the remaining sections. 186 subsections.push_back({}); 187 debugSections.push_back(isec); 188 } 189 } 190 } 191 192 // Find the subsection corresponding to the greatest section offset that is <= 193 // that of the given offset. 194 // 195 // offset: an offset relative to the start of the original InputSection (before 196 // any subsection splitting has occurred). It will be updated to represent the 197 // same location as an offset relative to the start of the containing 198 // subsection. 199 static InputSection *findContainingSubsection(SubsectionMap &map, 200 uint32_t *offset) { 201 auto it = std::prev(map.upper_bound(*offset)); 202 *offset -= it->first; 203 return it->second; 204 } 205 206 void ObjFile::parseRelocations(const section_64 &sec, 207 SubsectionMap &subsecMap) { 208 auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 209 ArrayRef<any_relocation_info> anyRelInfos( 210 reinterpret_cast<const any_relocation_info *>(buf + sec.reloff), 211 sec.nreloc); 212 213 for (const any_relocation_info &anyRelInfo : anyRelInfos) { 214 if (anyRelInfo.r_word0 & R_SCATTERED) 215 fatal("TODO: Scattered relocations not supported"); 216 217 auto relInfo = reinterpret_cast<const relocation_info &>(anyRelInfo); 218 219 Reloc r; 220 r.type = relInfo.r_type; 221 r.pcrel = relInfo.r_pcrel; 222 r.length = relInfo.r_length; 223 uint64_t rawAddend = target->getImplicitAddend(mb, sec, relInfo); 224 225 if (relInfo.r_extern) { 226 r.referent = symbols[relInfo.r_symbolnum]; 227 r.addend = rawAddend; 228 } else { 229 if (relInfo.r_symbolnum == 0 || relInfo.r_symbolnum > subsections.size()) 230 fatal("invalid section index in relocation for offset " + 231 std::to_string(r.offset) + " in section " + sec.sectname + 232 " of " + getName()); 233 234 SubsectionMap &referentSubsecMap = subsections[relInfo.r_symbolnum - 1]; 235 const section_64 &referentSec = sectionHeaders[relInfo.r_symbolnum - 1]; 236 uint32_t referentOffset; 237 if (relInfo.r_pcrel) { 238 // The implicit addend for pcrel section relocations is the pcrel offset 239 // in terms of the addresses in the input file. Here we adjust it so 240 // that it describes the offset from the start of the referent section. 241 // TODO: The offset of 4 is probably not right for ARM64, nor for 242 // relocations with r_length != 2. 243 referentOffset = 244 sec.addr + relInfo.r_address + 4 + rawAddend - referentSec.addr; 245 } else { 246 // The addend for a non-pcrel relocation is its absolute address. 247 referentOffset = rawAddend - referentSec.addr; 248 } 249 r.referent = findContainingSubsection(referentSubsecMap, &referentOffset); 250 r.addend = referentOffset; 251 } 252 253 r.offset = relInfo.r_address; 254 InputSection *subsec = findContainingSubsection(subsecMap, &r.offset); 255 subsec->relocs.push_back(r); 256 } 257 } 258 259 static macho::Symbol *createDefined(const structs::nlist_64 &sym, 260 StringRef name, InputSection *isec, 261 uint32_t value) { 262 if (sym.n_type & N_EXT) 263 // Global defined symbol 264 return symtab->addDefined(name, isec, value, sym.n_desc & N_WEAK_DEF); 265 // Local defined symbol 266 return make<Defined>(name, isec, value, sym.n_desc & N_WEAK_DEF, 267 /*isExternal=*/false); 268 } 269 270 // Absolute symbols are defined symbols that do not have an associated 271 // InputSection. They cannot be weak. 272 static macho::Symbol *createAbsolute(const structs::nlist_64 &sym, 273 StringRef name) { 274 if (sym.n_type & N_EXT) 275 return symtab->addDefined(name, nullptr, sym.n_value, /*isWeakDef=*/false); 276 return make<Defined>(name, nullptr, sym.n_value, /*isWeakDef=*/false, 277 /*isExternal=*/false); 278 } 279 280 macho::Symbol *ObjFile::parseNonSectionSymbol(const structs::nlist_64 &sym, 281 StringRef name) { 282 uint8_t type = sym.n_type & N_TYPE; 283 switch (type) { 284 case N_UNDF: 285 return sym.n_value == 0 286 ? symtab->addUndefined(name) 287 : symtab->addCommon(name, this, sym.n_value, 288 1 << GET_COMM_ALIGN(sym.n_desc)); 289 case N_ABS: 290 return createAbsolute(sym, name); 291 case N_PBUD: 292 case N_INDR: 293 error("TODO: support symbols of type " + std::to_string(type)); 294 return nullptr; 295 case N_SECT: 296 llvm_unreachable( 297 "N_SECT symbols should not be passed to parseNonSectionSymbol"); 298 default: 299 llvm_unreachable("invalid symbol type"); 300 } 301 } 302 303 void ObjFile::parseSymbols(ArrayRef<structs::nlist_64> nList, 304 const char *strtab, bool subsectionsViaSymbols) { 305 // resize(), not reserve(), because we are going to create N_ALT_ENTRY symbols 306 // out-of-sequence. 307 symbols.resize(nList.size()); 308 std::vector<size_t> altEntrySymIdxs; 309 310 for (size_t i = 0, n = nList.size(); i < n; ++i) { 311 const structs::nlist_64 &sym = nList[i]; 312 StringRef name = strtab + sym.n_strx; 313 314 if ((sym.n_type & N_TYPE) != N_SECT) { 315 symbols[i] = parseNonSectionSymbol(sym, name); 316 continue; 317 } 318 319 const section_64 &sec = sectionHeaders[sym.n_sect - 1]; 320 SubsectionMap &subsecMap = subsections[sym.n_sect - 1]; 321 assert(!subsecMap.empty()); 322 uint64_t offset = sym.n_value - sec.addr; 323 324 // If the input file does not use subsections-via-symbols, all symbols can 325 // use the same subsection. Otherwise, we must split the sections along 326 // symbol boundaries. 327 if (!subsectionsViaSymbols) { 328 symbols[i] = createDefined(sym, name, subsecMap[0], offset); 329 continue; 330 } 331 332 // nList entries aren't necessarily arranged in address order. Therefore, 333 // we can't create alt-entry symbols at this point because a later symbol 334 // may split its section, which may affect which subsection the alt-entry 335 // symbol is assigned to. So we need to handle them in a second pass below. 336 if (sym.n_desc & N_ALT_ENTRY) { 337 altEntrySymIdxs.push_back(i); 338 continue; 339 } 340 341 // Find the subsection corresponding to the greatest section offset that is 342 // <= that of the current symbol. The subsection that we find either needs 343 // to be used directly or split in two. 344 uint32_t firstSize = offset; 345 InputSection *firstIsec = findContainingSubsection(subsecMap, &firstSize); 346 347 if (firstSize == 0) { 348 // Alias of an existing symbol, or the first symbol in the section. These 349 // are handled by reusing the existing section. 350 symbols[i] = createDefined(sym, name, firstIsec, 0); 351 continue; 352 } 353 354 // We saw a symbol definition at a new offset. Split the section into two 355 // subsections. The new symbol uses the second subsection. 356 auto *secondIsec = make<InputSection>(*firstIsec); 357 secondIsec->data = firstIsec->data.slice(firstSize); 358 firstIsec->data = firstIsec->data.slice(0, firstSize); 359 // TODO: ld64 appears to preserve the original alignment as well as each 360 // subsection's offset from the last aligned address. We should consider 361 // emulating that behavior. 362 secondIsec->align = MinAlign(firstIsec->align, offset); 363 364 subsecMap[offset] = secondIsec; 365 // By construction, the symbol will be at offset zero in the new section. 366 symbols[i] = createDefined(sym, name, secondIsec, 0); 367 } 368 369 for (size_t idx : altEntrySymIdxs) { 370 const structs::nlist_64 &sym = nList[idx]; 371 StringRef name = strtab + sym.n_strx; 372 SubsectionMap &subsecMap = subsections[sym.n_sect - 1]; 373 uint32_t off = sym.n_value - sectionHeaders[sym.n_sect - 1].addr; 374 InputSection *subsec = findContainingSubsection(subsecMap, &off); 375 symbols[idx] = createDefined(sym, name, subsec, off); 376 } 377 } 378 379 OpaqueFile::OpaqueFile(MemoryBufferRef mb, StringRef segName, 380 StringRef sectName) 381 : InputFile(OpaqueKind, mb) { 382 InputSection *isec = make<InputSection>(); 383 isec->file = this; 384 isec->name = sectName.take_front(16); 385 isec->segname = segName.take_front(16); 386 const auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 387 isec->data = {buf, mb.getBufferSize()}; 388 subsections.push_back({{0, isec}}); 389 } 390 391 ObjFile::ObjFile(MemoryBufferRef mb, uint32_t modTime, StringRef archiveName) 392 : InputFile(ObjKind, mb), modTime(modTime) { 393 this->archiveName = std::string(archiveName); 394 395 auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 396 auto *hdr = reinterpret_cast<const mach_header_64 *>(mb.getBufferStart()); 397 398 if (const load_command *cmd = findCommand(hdr, LC_LINKER_OPTION)) { 399 auto *c = reinterpret_cast<const linker_option_command *>(cmd); 400 StringRef data{reinterpret_cast<const char *>(c + 1), 401 c->cmdsize - sizeof(linker_option_command)}; 402 parseLCLinkerOption(this, c->count, data); 403 } 404 405 if (const load_command *cmd = findCommand(hdr, LC_SEGMENT_64)) { 406 auto *c = reinterpret_cast<const segment_command_64 *>(cmd); 407 sectionHeaders = ArrayRef<section_64>{ 408 reinterpret_cast<const section_64 *>(c + 1), c->nsects}; 409 parseSections(sectionHeaders); 410 } 411 412 // TODO: Error on missing LC_SYMTAB? 413 if (const load_command *cmd = findCommand(hdr, LC_SYMTAB)) { 414 auto *c = reinterpret_cast<const symtab_command *>(cmd); 415 ArrayRef<structs::nlist_64> nList( 416 reinterpret_cast<const structs::nlist_64 *>(buf + c->symoff), c->nsyms); 417 const char *strtab = reinterpret_cast<const char *>(buf) + c->stroff; 418 bool subsectionsViaSymbols = hdr->flags & MH_SUBSECTIONS_VIA_SYMBOLS; 419 parseSymbols(nList, strtab, subsectionsViaSymbols); 420 } 421 422 // The relocations may refer to the symbols, so we parse them after we have 423 // parsed all the symbols. 424 for (size_t i = 0, n = subsections.size(); i < n; ++i) 425 if (!subsections[i].empty()) 426 parseRelocations(sectionHeaders[i], subsections[i]); 427 428 parseDebugInfo(); 429 } 430 431 void ObjFile::parseDebugInfo() { 432 std::unique_ptr<DwarfObject> dObj = DwarfObject::create(this); 433 if (!dObj) 434 return; 435 436 auto *ctx = make<DWARFContext>( 437 std::move(dObj), "", 438 [&](Error err) { 439 warn(toString(this) + ": " + toString(std::move(err))); 440 }, 441 [&](Error warning) { 442 warn(toString(this) + ": " + toString(std::move(warning))); 443 }); 444 445 // TODO: Since object files can contain a lot of DWARF info, we should verify 446 // that we are parsing just the info we need 447 const DWARFContext::compile_unit_range &units = ctx->compile_units(); 448 auto it = units.begin(); 449 compileUnit = it->get(); 450 assert(std::next(it) == units.end()); 451 } 452 453 // The path can point to either a dylib or a .tbd file. 454 static Optional<DylibFile *> loadDylib(StringRef path, DylibFile *umbrella) { 455 Optional<MemoryBufferRef> mbref = readFile(path); 456 if (!mbref) { 457 error("could not read dylib file at " + path); 458 return {}; 459 } 460 return loadDylib(*mbref, umbrella); 461 } 462 463 // TBD files are parsed into a series of TAPI documents (InterfaceFiles), with 464 // the first document storing child pointers to the rest of them. When we are 465 // processing a given TBD file, we store that top-level document here. When 466 // processing re-exports, we search its children for potentially matching 467 // documents in the same TBD file. Note that the children themselves don't 468 // point to further documents, i.e. this is a two-level tree. 469 // 470 // ld64 allows a TAPI re-export to reference documents nested within other TBD 471 // files, but that seems like a strange design, so this is an intentional 472 // deviation. 473 const InterfaceFile *currentTopLevelTapi = nullptr; 474 475 // Re-exports can either refer to on-disk files, or to documents within .tbd 476 // files. 477 static Optional<DylibFile *> loadReexportHelper(StringRef path, 478 DylibFile *umbrella) { 479 if (path::is_absolute(path, path::Style::posix)) 480 for (StringRef root : config->systemLibraryRoots) 481 if (Optional<std::string> dylibPath = 482 resolveDylibPath((root + path).str())) 483 return loadDylib(*dylibPath, umbrella); 484 485 // TODO: Expand @loader_path, @executable_path etc 486 487 if (currentTopLevelTapi) { 488 for (InterfaceFile &child : 489 make_pointee_range(currentTopLevelTapi->documents())) { 490 if (path == child.getInstallName()) 491 return make<DylibFile>(child, umbrella); 492 assert(child.documents().empty()); 493 } 494 } 495 496 if (Optional<std::string> dylibPath = resolveDylibPath(path)) 497 return loadDylib(*dylibPath, umbrella); 498 499 error("unable to locate re-export with install name " + path); 500 return {}; 501 } 502 503 // If a re-exported dylib is public (lives in /usr/lib or 504 // /System/Library/Frameworks), then it is considered implicitly linked: we 505 // should bind to its symbols directly instead of via the re-exporting umbrella 506 // library. 507 static bool isImplicitlyLinked(StringRef path) { 508 if (!config->implicitDylibs) 509 return false; 510 511 if (path::parent_path(path) == "/usr/lib") 512 return true; 513 514 // Match /System/Library/Frameworks/$FOO.framework/**/$FOO 515 if (path.consume_front("/System/Library/Frameworks/")) { 516 StringRef frameworkName = path.take_until([](char c) { return c == '.'; }); 517 return path::filename(path) == frameworkName; 518 } 519 520 return false; 521 } 522 523 void loadReexport(StringRef path, DylibFile *umbrella) { 524 Optional<DylibFile *> reexport = loadReexportHelper(path, umbrella); 525 if (reexport && isImplicitlyLinked(path)) 526 inputFiles.insert(*reexport); 527 } 528 529 DylibFile::DylibFile(MemoryBufferRef mb, DylibFile *umbrella) 530 : InputFile(DylibKind, mb) { 531 if (umbrella == nullptr) 532 umbrella = this; 533 534 auto *buf = reinterpret_cast<const uint8_t *>(mb.getBufferStart()); 535 auto *hdr = reinterpret_cast<const mach_header_64 *>(mb.getBufferStart()); 536 537 // Initialize dylibName. 538 if (const load_command *cmd = findCommand(hdr, LC_ID_DYLIB)) { 539 auto *c = reinterpret_cast<const dylib_command *>(cmd); 540 currentVersion = read32le(&c->dylib.current_version); 541 compatibilityVersion = read32le(&c->dylib.compatibility_version); 542 dylibName = reinterpret_cast<const char *>(cmd) + read32le(&c->dylib.name); 543 } else { 544 error("dylib " + toString(this) + " missing LC_ID_DYLIB load command"); 545 return; 546 } 547 548 // Initialize symbols. 549 DylibFile *exportingFile = isImplicitlyLinked(dylibName) ? this : umbrella; 550 if (const load_command *cmd = findCommand(hdr, LC_DYLD_INFO_ONLY)) { 551 auto *c = reinterpret_cast<const dyld_info_command *>(cmd); 552 parseTrie(buf + c->export_off, c->export_size, 553 [&](const Twine &name, uint64_t flags) { 554 bool isWeakDef = flags & EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION; 555 bool isTlv = flags & EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL; 556 symbols.push_back(symtab->addDylib( 557 saver.save(name), exportingFile, isWeakDef, isTlv)); 558 }); 559 } else { 560 error("LC_DYLD_INFO_ONLY not found in " + toString(this)); 561 return; 562 } 563 564 if (hdr->flags & MH_NO_REEXPORTED_DYLIBS) 565 return; 566 567 const uint8_t *p = 568 reinterpret_cast<const uint8_t *>(hdr) + sizeof(mach_header_64); 569 for (uint32_t i = 0, n = hdr->ncmds; i < n; ++i) { 570 auto *cmd = reinterpret_cast<const load_command *>(p); 571 p += cmd->cmdsize; 572 if (cmd->cmd != LC_REEXPORT_DYLIB) 573 continue; 574 575 auto *c = reinterpret_cast<const dylib_command *>(cmd); 576 StringRef reexportPath = 577 reinterpret_cast<const char *>(c) + read32le(&c->dylib.name); 578 loadReexport(reexportPath, umbrella); 579 } 580 } 581 582 DylibFile::DylibFile(const InterfaceFile &interface, DylibFile *umbrella) 583 : InputFile(DylibKind, interface) { 584 if (umbrella == nullptr) 585 umbrella = this; 586 587 dylibName = saver.save(interface.getInstallName()); 588 compatibilityVersion = interface.getCompatibilityVersion().rawValue(); 589 currentVersion = interface.getCurrentVersion().rawValue(); 590 DylibFile *exportingFile = isImplicitlyLinked(dylibName) ? this : umbrella; 591 auto addSymbol = [&](const Twine &name) -> void { 592 symbols.push_back(symtab->addDylib(saver.save(name), exportingFile, 593 /*isWeakDef=*/false, 594 /*isTlv=*/false)); 595 }; 596 // TODO(compnerd) filter out symbols based on the target platform 597 // TODO: handle weak defs, thread locals 598 for (const auto symbol : interface.symbols()) { 599 if (!symbol->getArchitectures().has(config->arch)) 600 continue; 601 602 switch (symbol->getKind()) { 603 case SymbolKind::GlobalSymbol: 604 addSymbol(symbol->getName()); 605 break; 606 case SymbolKind::ObjectiveCClass: 607 // XXX ld64 only creates these symbols when -ObjC is passed in. We may 608 // want to emulate that. 609 addSymbol(objc::klass + symbol->getName()); 610 addSymbol(objc::metaclass + symbol->getName()); 611 break; 612 case SymbolKind::ObjectiveCClassEHType: 613 addSymbol(objc::ehtype + symbol->getName()); 614 break; 615 case SymbolKind::ObjectiveCInstanceVariable: 616 addSymbol(objc::ivar + symbol->getName()); 617 break; 618 } 619 } 620 621 bool isTopLevelTapi = false; 622 if (currentTopLevelTapi == nullptr) { 623 currentTopLevelTapi = &interface; 624 isTopLevelTapi = true; 625 } 626 627 for (InterfaceFileRef intfRef : interface.reexportedLibraries()) 628 loadReexport(intfRef.getInstallName(), umbrella); 629 630 if (isTopLevelTapi) 631 currentTopLevelTapi = nullptr; 632 } 633 634 ArchiveFile::ArchiveFile(std::unique_ptr<llvm::object::Archive> &&f) 635 : InputFile(ArchiveKind, f->getMemoryBufferRef()), file(std::move(f)) { 636 for (const object::Archive::Symbol &sym : file->symbols()) 637 symtab->addLazy(sym.getName(), this, sym); 638 } 639 640 void ArchiveFile::fetch(const object::Archive::Symbol &sym) { 641 object::Archive::Child c = 642 CHECK(sym.getMember(), toString(this) + 643 ": could not get the member for symbol " + 644 toMachOString(sym)); 645 646 if (!seen.insert(c.getChildOffset()).second) 647 return; 648 649 MemoryBufferRef mb = 650 CHECK(c.getMemoryBufferRef(), 651 toString(this) + 652 ": could not get the buffer for the member defining symbol " + 653 toMachOString(sym)); 654 655 if (tar && c.getParent()->isThin()) 656 tar->append(relativeToRoot(CHECK(c.getFullName(), this)), mb.getBuffer()); 657 658 uint32_t modTime = toTimeT( 659 CHECK(c.getLastModified(), toString(this) + 660 ": could not get the modification time " 661 "for the member defining symbol " + 662 toMachOString(sym))); 663 664 // `sym` is owned by a LazySym, which will be replace<>() by make<ObjFile> 665 // and become invalid after that call. Copy it to the stack so we can refer 666 // to it later. 667 const object::Archive::Symbol sym_copy = sym; 668 669 InputFile *file; 670 switch (identify_magic(mb.getBuffer())) { 671 case file_magic::macho_object: 672 file = make<ObjFile>(mb, modTime, getName()); 673 break; 674 case file_magic::bitcode: 675 file = make<BitcodeFile>(mb); 676 break; 677 default: 678 StringRef bufname = 679 CHECK(c.getName(), toString(this) + ": could not get buffer name"); 680 error(toString(this) + ": archive member " + bufname + 681 " has unhandled file type"); 682 return; 683 } 684 inputFiles.insert(file); 685 686 // ld64 doesn't demangle sym here even with -demangle. Match that, so 687 // intentionally no call to toMachOString() here. 688 printArchiveMemberLoad(sym_copy.getName(), file); 689 } 690 691 BitcodeFile::BitcodeFile(MemoryBufferRef mbref) 692 : InputFile(BitcodeKind, mbref) { 693 obj = check(lto::InputFile::create(mbref)); 694 } 695