1 //===- SyntheticSections.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 #include "SyntheticSections.h" 10 #include "Config.h" 11 #include "ExportTrie.h" 12 #include "InputFiles.h" 13 #include "MachOStructs.h" 14 #include "MergedOutputSection.h" 15 #include "OutputSegment.h" 16 #include "SymbolTable.h" 17 #include "Symbols.h" 18 #include "Writer.h" 19 20 #include "lld/Common/ErrorHandler.h" 21 #include "lld/Common/Memory.h" 22 #include "llvm/ADT/STLExtras.h" 23 #include "llvm/Support/EndianStream.h" 24 #include "llvm/Support/FileSystem.h" 25 #include "llvm/Support/LEB128.h" 26 #include "llvm/Support/Path.h" 27 28 using namespace llvm; 29 using namespace llvm::support; 30 using namespace llvm::support::endian; 31 using namespace lld; 32 using namespace lld::macho; 33 34 InStruct macho::in; 35 std::vector<SyntheticSection *> macho::syntheticSections; 36 37 SyntheticSection::SyntheticSection(const char *segname, const char *name) 38 : OutputSection(SyntheticKind, name), segname(segname) { 39 syntheticSections.push_back(this); 40 } 41 42 // dyld3's MachOLoaded::getSlide() assumes that the __TEXT segment starts 43 // from the beginning of the file (i.e. the header). 44 MachHeaderSection::MachHeaderSection() 45 : SyntheticSection(segment_names::text, section_names::header) {} 46 47 void MachHeaderSection::addLoadCommand(LoadCommand *lc) { 48 loadCommands.push_back(lc); 49 sizeOfCmds += lc->getSize(); 50 } 51 52 uint64_t MachHeaderSection::getSize() const { 53 return sizeof(MachO::mach_header_64) + sizeOfCmds + config->headerPad; 54 } 55 56 void MachHeaderSection::writeTo(uint8_t *buf) const { 57 auto *hdr = reinterpret_cast<MachO::mach_header_64 *>(buf); 58 hdr->magic = MachO::MH_MAGIC_64; 59 hdr->cputype = target->cpuType; 60 hdr->cpusubtype = target->cpuSubtype | MachO::CPU_SUBTYPE_LIB64; 61 hdr->filetype = config->outputType; 62 hdr->ncmds = loadCommands.size(); 63 hdr->sizeofcmds = sizeOfCmds; 64 hdr->flags = MachO::MH_NOUNDEFS | MachO::MH_DYLDLINK | MachO::MH_TWOLEVEL; 65 66 if (config->outputType == MachO::MH_DYLIB && !config->hasReexports) 67 hdr->flags |= MachO::MH_NO_REEXPORTED_DYLIBS; 68 69 if (config->outputType == MachO::MH_EXECUTE && config->isPic) 70 hdr->flags |= MachO::MH_PIE; 71 72 if (in.exports->hasWeakSymbol || in.weakBinding->hasNonWeakDefinition()) 73 hdr->flags |= MachO::MH_WEAK_DEFINES; 74 75 if (in.exports->hasWeakSymbol || in.weakBinding->hasEntry()) 76 hdr->flags |= MachO::MH_BINDS_TO_WEAK; 77 78 for (OutputSegment *seg : outputSegments) { 79 for (OutputSection *osec : seg->getSections()) { 80 if (isThreadLocalVariables(osec->flags)) { 81 hdr->flags |= MachO::MH_HAS_TLV_DESCRIPTORS; 82 break; 83 } 84 } 85 } 86 87 uint8_t *p = reinterpret_cast<uint8_t *>(hdr + 1); 88 for (LoadCommand *lc : loadCommands) { 89 lc->writeTo(p); 90 p += lc->getSize(); 91 } 92 } 93 94 PageZeroSection::PageZeroSection() 95 : SyntheticSection(segment_names::pageZero, section_names::pageZero) {} 96 97 uint64_t Location::getVA() const { 98 if (const auto *isec = section.dyn_cast<const InputSection *>()) 99 return isec->getVA() + offset; 100 return section.get<const OutputSection *>()->addr + offset; 101 } 102 103 RebaseSection::RebaseSection() 104 : LinkEditSection(segment_names::linkEdit, section_names::rebase) {} 105 106 namespace { 107 struct Rebase { 108 OutputSegment *segment = nullptr; 109 uint64_t offset = 0; 110 uint64_t consecutiveCount = 0; 111 }; 112 } // namespace 113 114 // Rebase opcodes allow us to describe a contiguous sequence of rebase location 115 // using a single DO_REBASE opcode. To take advantage of it, we delay emitting 116 // `DO_REBASE` until we have reached the end of a contiguous sequence. 117 static void encodeDoRebase(Rebase &rebase, raw_svector_ostream &os) { 118 using namespace llvm::MachO; 119 assert(rebase.consecutiveCount != 0); 120 if (rebase.consecutiveCount <= REBASE_IMMEDIATE_MASK) { 121 os << static_cast<uint8_t>(REBASE_OPCODE_DO_REBASE_IMM_TIMES | 122 rebase.consecutiveCount); 123 } else { 124 os << static_cast<uint8_t>(REBASE_OPCODE_DO_REBASE_ULEB_TIMES); 125 encodeULEB128(rebase.consecutiveCount, os); 126 } 127 rebase.consecutiveCount = 0; 128 } 129 130 static void encodeRebase(const OutputSection *osec, uint64_t outSecOff, 131 Rebase &lastRebase, raw_svector_ostream &os) { 132 using namespace llvm::MachO; 133 OutputSegment *seg = osec->parent; 134 uint64_t offset = osec->getSegmentOffset() + outSecOff; 135 if (lastRebase.segment != seg || lastRebase.offset != offset) { 136 if (lastRebase.consecutiveCount != 0) 137 encodeDoRebase(lastRebase, os); 138 139 if (lastRebase.segment != seg) { 140 os << static_cast<uint8_t>(REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB | 141 seg->index); 142 encodeULEB128(offset, os); 143 lastRebase.segment = seg; 144 lastRebase.offset = offset; 145 } else { 146 assert(lastRebase.offset != offset); 147 os << static_cast<uint8_t>(REBASE_OPCODE_ADD_ADDR_ULEB); 148 encodeULEB128(offset - lastRebase.offset, os); 149 lastRebase.offset = offset; 150 } 151 } 152 ++lastRebase.consecutiveCount; 153 // DO_REBASE causes dyld to both perform the binding and increment the offset 154 lastRebase.offset += WordSize; 155 } 156 157 void RebaseSection::finalizeContents() { 158 using namespace llvm::MachO; 159 if (locations.empty()) 160 return; 161 162 raw_svector_ostream os{contents}; 163 Rebase lastRebase; 164 165 os << static_cast<uint8_t>(REBASE_OPCODE_SET_TYPE_IMM | REBASE_TYPE_POINTER); 166 167 llvm::sort(locations, [](const Location &a, const Location &b) { 168 return a.getVA() < b.getVA(); 169 }); 170 for (const Location &loc : locations) { 171 if (const auto *isec = loc.section.dyn_cast<const InputSection *>()) { 172 encodeRebase(isec->parent, isec->outSecOff + loc.offset, lastRebase, os); 173 } else { 174 const auto *osec = loc.section.get<const OutputSection *>(); 175 encodeRebase(osec, loc.offset, lastRebase, os); 176 } 177 } 178 if (lastRebase.consecutiveCount != 0) 179 encodeDoRebase(lastRebase, os); 180 181 os << static_cast<uint8_t>(REBASE_OPCODE_DONE); 182 } 183 184 void RebaseSection::writeTo(uint8_t *buf) const { 185 memcpy(buf, contents.data(), contents.size()); 186 } 187 188 NonLazyPointerSectionBase::NonLazyPointerSectionBase(const char *segname, 189 const char *name) 190 : SyntheticSection(segname, name) { 191 align = WordSize; // vector of pointers / mimic ld64 192 flags = MachO::S_NON_LAZY_SYMBOL_POINTERS; 193 } 194 195 void NonLazyPointerSectionBase::addEntry(Symbol *sym) { 196 if (entries.insert(sym)) { 197 assert(!sym->isInGot()); 198 sym->gotIndex = entries.size() - 1; 199 200 addNonLazyBindingEntries(sym, this, sym->gotIndex * WordSize); 201 } 202 } 203 204 void NonLazyPointerSectionBase::writeTo(uint8_t *buf) const { 205 for (size_t i = 0, n = entries.size(); i < n; ++i) 206 if (auto *defined = dyn_cast<Defined>(entries[i])) 207 write64le(&buf[i * WordSize], defined->getVA()); 208 } 209 210 BindingSection::BindingSection() 211 : LinkEditSection(segment_names::linkEdit, section_names::binding) {} 212 213 namespace { 214 struct Binding { 215 OutputSegment *segment = nullptr; 216 uint64_t offset = 0; 217 int64_t addend = 0; 218 uint8_t ordinal = 0; 219 }; 220 } // namespace 221 222 // Encode a sequence of opcodes that tell dyld to write the address of symbol + 223 // addend at osec->addr + outSecOff. 224 // 225 // The bind opcode "interpreter" remembers the values of each binding field, so 226 // we only need to encode the differences between bindings. Hence the use of 227 // lastBinding. 228 static void encodeBinding(const Symbol *sym, const OutputSection *osec, 229 uint64_t outSecOff, int64_t addend, 230 bool isWeakBinding, Binding &lastBinding, 231 raw_svector_ostream &os) { 232 using namespace llvm::MachO; 233 OutputSegment *seg = osec->parent; 234 uint64_t offset = osec->getSegmentOffset() + outSecOff; 235 if (lastBinding.segment != seg) { 236 os << static_cast<uint8_t>(BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB | 237 seg->index); 238 encodeULEB128(offset, os); 239 lastBinding.segment = seg; 240 lastBinding.offset = offset; 241 } else if (lastBinding.offset != offset) { 242 os << static_cast<uint8_t>(BIND_OPCODE_ADD_ADDR_ULEB); 243 encodeULEB128(offset - lastBinding.offset, os); 244 lastBinding.offset = offset; 245 } 246 247 if (lastBinding.addend != addend) { 248 os << static_cast<uint8_t>(BIND_OPCODE_SET_ADDEND_SLEB); 249 encodeSLEB128(addend, os); 250 lastBinding.addend = addend; 251 } 252 253 uint8_t flags = BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM; 254 if (!isWeakBinding && sym->isWeakRef()) 255 flags |= BIND_SYMBOL_FLAGS_WEAK_IMPORT; 256 257 os << flags << sym->getName() << '\0' 258 << static_cast<uint8_t>(BIND_OPCODE_SET_TYPE_IMM | BIND_TYPE_POINTER) 259 << static_cast<uint8_t>(BIND_OPCODE_DO_BIND); 260 // DO_BIND causes dyld to both perform the binding and increment the offset 261 lastBinding.offset += WordSize; 262 } 263 264 // Non-weak bindings need to have their dylib ordinal encoded as well. 265 static void encodeDylibOrdinal(const DylibSymbol *dysym, Binding &lastBinding, 266 raw_svector_ostream &os) { 267 using namespace llvm::MachO; 268 if (lastBinding.ordinal != dysym->getFile()->ordinal) { 269 if (dysym->getFile()->ordinal <= BIND_IMMEDIATE_MASK) { 270 os << static_cast<uint8_t>(BIND_OPCODE_SET_DYLIB_ORDINAL_IMM | 271 dysym->getFile()->ordinal); 272 } else { 273 os << static_cast<uint8_t>(BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB); 274 encodeULEB128(dysym->getFile()->ordinal, os); 275 } 276 lastBinding.ordinal = dysym->getFile()->ordinal; 277 } 278 } 279 280 static void encodeWeakOverride(const Defined *defined, 281 raw_svector_ostream &os) { 282 using namespace llvm::MachO; 283 os << static_cast<uint8_t>(BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM | 284 BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) 285 << defined->getName() << '\0'; 286 } 287 288 // Emit bind opcodes, which are a stream of byte-sized opcodes that dyld 289 // interprets to update a record with the following fields: 290 // * segment index (of the segment to write the symbol addresses to, typically 291 // the __DATA_CONST segment which contains the GOT) 292 // * offset within the segment, indicating the next location to write a binding 293 // * symbol type 294 // * symbol library ordinal (the index of its library's LC_LOAD_DYLIB command) 295 // * symbol name 296 // * addend 297 // When dyld sees BIND_OPCODE_DO_BIND, it uses the current record state to bind 298 // a symbol in the GOT, and increments the segment offset to point to the next 299 // entry. It does *not* clear the record state after doing the bind, so 300 // subsequent opcodes only need to encode the differences between bindings. 301 void BindingSection::finalizeContents() { 302 raw_svector_ostream os{contents}; 303 Binding lastBinding; 304 305 // Since bindings are delta-encoded, sorting them allows for a more compact 306 // result. Note that sorting by address alone ensures that bindings for the 307 // same segment / section are located together. 308 llvm::sort(bindings, [](const BindingEntry &a, const BindingEntry &b) { 309 return a.target.getVA() < b.target.getVA(); 310 }); 311 for (const BindingEntry &b : bindings) { 312 encodeDylibOrdinal(b.dysym, lastBinding, os); 313 if (auto *isec = b.target.section.dyn_cast<const InputSection *>()) { 314 encodeBinding(b.dysym, isec->parent, isec->outSecOff + b.target.offset, 315 b.addend, /*isWeakBinding=*/false, lastBinding, os); 316 } else { 317 auto *osec = b.target.section.get<const OutputSection *>(); 318 encodeBinding(b.dysym, osec, b.target.offset, b.addend, 319 /*isWeakBinding=*/false, lastBinding, os); 320 } 321 } 322 if (!bindings.empty()) 323 os << static_cast<uint8_t>(MachO::BIND_OPCODE_DONE); 324 } 325 326 void BindingSection::writeTo(uint8_t *buf) const { 327 memcpy(buf, contents.data(), contents.size()); 328 } 329 330 WeakBindingSection::WeakBindingSection() 331 : LinkEditSection(segment_names::linkEdit, section_names::weakBinding) {} 332 333 void WeakBindingSection::finalizeContents() { 334 raw_svector_ostream os{contents}; 335 Binding lastBinding; 336 337 for (const Defined *defined : definitions) 338 encodeWeakOverride(defined, os); 339 340 // Since bindings are delta-encoded, sorting them allows for a more compact 341 // result. 342 llvm::sort(bindings, 343 [](const WeakBindingEntry &a, const WeakBindingEntry &b) { 344 return a.target.getVA() < b.target.getVA(); 345 }); 346 for (const WeakBindingEntry &b : bindings) { 347 if (auto *isec = b.target.section.dyn_cast<const InputSection *>()) { 348 encodeBinding(b.symbol, isec->parent, isec->outSecOff + b.target.offset, 349 b.addend, /*isWeakBinding=*/true, lastBinding, os); 350 } else { 351 auto *osec = b.target.section.get<const OutputSection *>(); 352 encodeBinding(b.symbol, osec, b.target.offset, b.addend, 353 /*isWeakBinding=*/true, lastBinding, os); 354 } 355 } 356 if (!bindings.empty() || !definitions.empty()) 357 os << static_cast<uint8_t>(MachO::BIND_OPCODE_DONE); 358 } 359 360 void WeakBindingSection::writeTo(uint8_t *buf) const { 361 memcpy(buf, contents.data(), contents.size()); 362 } 363 364 bool macho::needsBinding(const Symbol *sym) { 365 if (isa<DylibSymbol>(sym)) 366 return true; 367 if (const auto *defined = dyn_cast<Defined>(sym)) 368 return defined->isExternalWeakDef(); 369 return false; 370 } 371 372 void macho::addNonLazyBindingEntries(const Symbol *sym, 373 SectionPointerUnion section, 374 uint64_t offset, int64_t addend) { 375 if (auto *dysym = dyn_cast<DylibSymbol>(sym)) { 376 in.binding->addEntry(dysym, section, offset, addend); 377 if (dysym->isWeakDef()) 378 in.weakBinding->addEntry(sym, section, offset, addend); 379 } else if (auto *defined = dyn_cast<Defined>(sym)) { 380 in.rebase->addEntry(section, offset); 381 if (defined->isExternalWeakDef()) 382 in.weakBinding->addEntry(sym, section, offset, addend); 383 } else if (!isa<DSOHandle>(sym)) { 384 // Undefined symbols are filtered out in scanRelocations(); we should never 385 // get here 386 llvm_unreachable("cannot bind to an undefined symbol"); 387 } 388 // TODO: understand the DSOHandle case better. 389 // Is it bindable? Add a new test? 390 } 391 392 StubsSection::StubsSection() 393 : SyntheticSection(segment_names::text, "__stubs") { 394 flags = MachO::S_SYMBOL_STUBS | MachO::S_ATTR_SOME_INSTRUCTIONS | 395 MachO::S_ATTR_PURE_INSTRUCTIONS; 396 align = 4; // machine instructions / mimic ld64 397 reserved2 = target->stubSize; 398 } 399 400 uint64_t StubsSection::getSize() const { 401 return entries.size() * target->stubSize; 402 } 403 404 void StubsSection::writeTo(uint8_t *buf) const { 405 size_t off = 0; 406 for (const Symbol *sym : entries) { 407 target->writeStub(buf + off, *sym); 408 off += target->stubSize; 409 } 410 } 411 412 bool StubsSection::addEntry(Symbol *sym) { 413 bool inserted = entries.insert(sym); 414 if (inserted) 415 sym->stubsIndex = entries.size() - 1; 416 return inserted; 417 } 418 419 StubHelperSection::StubHelperSection() 420 : SyntheticSection(segment_names::text, "__stub_helper") { 421 flags = MachO::S_ATTR_SOME_INSTRUCTIONS | MachO::S_ATTR_PURE_INSTRUCTIONS; 422 align = 4; // machine instructions / mimic ld64 423 } 424 425 uint64_t StubHelperSection::getSize() const { 426 return target->stubHelperHeaderSize + 427 in.lazyBinding->getEntries().size() * target->stubHelperEntrySize; 428 } 429 430 bool StubHelperSection::isNeeded() const { return in.lazyBinding->isNeeded(); } 431 432 void StubHelperSection::writeTo(uint8_t *buf) const { 433 target->writeStubHelperHeader(buf); 434 size_t off = target->stubHelperHeaderSize; 435 for (const DylibSymbol *sym : in.lazyBinding->getEntries()) { 436 target->writeStubHelperEntry(buf + off, *sym, addr + off); 437 off += target->stubHelperEntrySize; 438 } 439 } 440 441 void StubHelperSection::setup() { 442 stubBinder = dyn_cast_or_null<DylibSymbol>(symtab->find("dyld_stub_binder")); 443 if (stubBinder == nullptr) { 444 error("symbol dyld_stub_binder not found (normally in libSystem.dylib). " 445 "Needed to perform lazy binding."); 446 return; 447 } 448 stubBinder->refState = RefState::Strong; 449 in.got->addEntry(stubBinder); 450 451 inputSections.push_back(in.imageLoaderCache); 452 dyldPrivate = make<Defined>("__dyld_private", nullptr, in.imageLoaderCache, 0, 453 /*isWeakDef=*/false, 454 /*isExternal=*/false, /*isPrivateExtern=*/false); 455 } 456 457 ImageLoaderCacheSection::ImageLoaderCacheSection() { 458 segname = segment_names::data; 459 name = "__data"; 460 uint8_t *arr = bAlloc.Allocate<uint8_t>(WordSize); 461 memset(arr, 0, WordSize); 462 data = {arr, WordSize}; 463 align = WordSize; // pointer / mimic ld64 464 } 465 466 LazyPointerSection::LazyPointerSection() 467 : SyntheticSection(segment_names::data, "__la_symbol_ptr") { 468 align = WordSize; // vector of pointers / mimic ld64 469 flags = MachO::S_LAZY_SYMBOL_POINTERS; 470 } 471 472 uint64_t LazyPointerSection::getSize() const { 473 return in.stubs->getEntries().size() * WordSize; 474 } 475 476 bool LazyPointerSection::isNeeded() const { 477 return !in.stubs->getEntries().empty(); 478 } 479 480 void LazyPointerSection::writeTo(uint8_t *buf) const { 481 size_t off = 0; 482 for (const Symbol *sym : in.stubs->getEntries()) { 483 if (const auto *dysym = dyn_cast<DylibSymbol>(sym)) { 484 if (dysym->hasStubsHelper()) { 485 uint64_t stubHelperOffset = 486 target->stubHelperHeaderSize + 487 dysym->stubsHelperIndex * target->stubHelperEntrySize; 488 write64le(buf + off, in.stubHelper->addr + stubHelperOffset); 489 } 490 } else { 491 write64le(buf + off, sym->getVA()); 492 } 493 off += WordSize; 494 } 495 } 496 497 LazyBindingSection::LazyBindingSection() 498 : LinkEditSection(segment_names::linkEdit, section_names::lazyBinding) {} 499 500 void LazyBindingSection::finalizeContents() { 501 // TODO: Just precompute output size here instead of writing to a temporary 502 // buffer 503 for (DylibSymbol *sym : entries) 504 sym->lazyBindOffset = encode(*sym); 505 } 506 507 void LazyBindingSection::writeTo(uint8_t *buf) const { 508 memcpy(buf, contents.data(), contents.size()); 509 } 510 511 void LazyBindingSection::addEntry(DylibSymbol *dysym) { 512 if (entries.insert(dysym)) { 513 dysym->stubsHelperIndex = entries.size() - 1; 514 in.rebase->addEntry(in.lazyPointers, dysym->stubsIndex * WordSize); 515 } 516 } 517 518 // Unlike the non-lazy binding section, the bind opcodes in this section aren't 519 // interpreted all at once. Rather, dyld will start interpreting opcodes at a 520 // given offset, typically only binding a single symbol before it finds a 521 // BIND_OPCODE_DONE terminator. As such, unlike in the non-lazy-binding case, 522 // we cannot encode just the differences between symbols; we have to emit the 523 // complete bind information for each symbol. 524 uint32_t LazyBindingSection::encode(const DylibSymbol &sym) { 525 uint32_t opstreamOffset = contents.size(); 526 OutputSegment *dataSeg = in.lazyPointers->parent; 527 os << static_cast<uint8_t>(MachO::BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB | 528 dataSeg->index); 529 uint64_t offset = in.lazyPointers->addr - dataSeg->firstSection()->addr + 530 sym.stubsIndex * WordSize; 531 encodeULEB128(offset, os); 532 if (sym.getFile()->ordinal <= MachO::BIND_IMMEDIATE_MASK) { 533 os << static_cast<uint8_t>(MachO::BIND_OPCODE_SET_DYLIB_ORDINAL_IMM | 534 sym.getFile()->ordinal); 535 } else { 536 os << static_cast<uint8_t>(MachO::BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB); 537 encodeULEB128(sym.getFile()->ordinal, os); 538 } 539 540 uint8_t flags = MachO::BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM; 541 if (sym.isWeakRef()) 542 flags |= MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT; 543 544 os << flags << sym.getName() << '\0' 545 << static_cast<uint8_t>(MachO::BIND_OPCODE_DO_BIND) 546 << static_cast<uint8_t>(MachO::BIND_OPCODE_DONE); 547 return opstreamOffset; 548 } 549 550 void macho::prepareBranchTarget(Symbol *sym) { 551 if (auto *dysym = dyn_cast<DylibSymbol>(sym)) { 552 if (in.stubs->addEntry(dysym)) { 553 if (sym->isWeakDef()) { 554 in.binding->addEntry(dysym, in.lazyPointers, 555 sym->stubsIndex * WordSize); 556 in.weakBinding->addEntry(sym, in.lazyPointers, 557 sym->stubsIndex * WordSize); 558 } else { 559 in.lazyBinding->addEntry(dysym); 560 } 561 } 562 } else if (auto *defined = dyn_cast<Defined>(sym)) { 563 if (defined->isExternalWeakDef()) { 564 if (in.stubs->addEntry(sym)) { 565 in.rebase->addEntry(in.lazyPointers, sym->stubsIndex * WordSize); 566 in.weakBinding->addEntry(sym, in.lazyPointers, 567 sym->stubsIndex * WordSize); 568 } 569 } 570 } 571 } 572 573 ExportSection::ExportSection() 574 : LinkEditSection(segment_names::linkEdit, section_names::export_) {} 575 576 void ExportSection::finalizeContents() { 577 trieBuilder.setImageBase(in.header->addr); 578 for (const Symbol *sym : symtab->getSymbols()) { 579 if (const auto *defined = dyn_cast<Defined>(sym)) { 580 if (defined->privateExtern) 581 continue; 582 trieBuilder.addSymbol(*defined); 583 hasWeakSymbol = hasWeakSymbol || sym->isWeakDef(); 584 } 585 } 586 size = trieBuilder.build(); 587 } 588 589 void ExportSection::writeTo(uint8_t *buf) const { trieBuilder.writeTo(buf); } 590 591 SymtabSection::SymtabSection(StringTableSection &stringTableSection) 592 : LinkEditSection(segment_names::linkEdit, section_names::symbolTable), 593 stringTableSection(stringTableSection) {} 594 595 uint64_t SymtabSection::getRawSize() const { 596 return getNumSymbols() * sizeof(structs::nlist_64); 597 } 598 599 void SymtabSection::emitBeginSourceStab(DWARFUnit *compileUnit) { 600 StabsEntry stab(MachO::N_SO); 601 SmallString<261> dir(compileUnit->getCompilationDir()); 602 StringRef sep = sys::path::get_separator(); 603 // We don't use `path::append` here because we want an empty `dir` to result 604 // in an absolute path. `append` would give us a relative path for that case. 605 if (!dir.endswith(sep)) 606 dir += sep; 607 stab.strx = stringTableSection.addString( 608 saver.save(dir + compileUnit->getUnitDIE().getShortName())); 609 stabs.emplace_back(std::move(stab)); 610 } 611 612 void SymtabSection::emitEndSourceStab() { 613 StabsEntry stab(MachO::N_SO); 614 stab.sect = 1; 615 stabs.emplace_back(std::move(stab)); 616 } 617 618 void SymtabSection::emitObjectFileStab(ObjFile *file) { 619 StabsEntry stab(MachO::N_OSO); 620 stab.sect = target->cpuSubtype; 621 SmallString<261> path(!file->archiveName.empty() ? file->archiveName 622 : file->getName()); 623 std::error_code ec = sys::fs::make_absolute(path); 624 if (ec) 625 fatal("failed to get absolute path for " + path); 626 627 if (!file->archiveName.empty()) 628 path.append({"(", file->getName(), ")"}); 629 630 stab.strx = stringTableSection.addString(saver.save(path.str())); 631 stab.desc = 1; 632 stab.value = file->modTime; 633 stabs.emplace_back(std::move(stab)); 634 } 635 636 void SymtabSection::emitEndFunStab(Defined *defined) { 637 StabsEntry stab(MachO::N_FUN); 638 // FIXME this should be the size of the symbol. Using the section size in 639 // lieu is only correct if .subsections_via_symbols is set. 640 stab.value = defined->isec->getSize(); 641 stabs.emplace_back(std::move(stab)); 642 } 643 644 void SymtabSection::emitStabs() { 645 std::vector<Defined *> symbolsNeedingStabs; 646 for (const SymtabEntry &entry : 647 concat<SymtabEntry>(localSymbols, externalSymbols)) { 648 Symbol *sym = entry.sym; 649 if (auto *defined = dyn_cast<Defined>(sym)) { 650 if (defined->isAbsolute()) 651 continue; 652 InputSection *isec = defined->isec; 653 ObjFile *file = dyn_cast_or_null<ObjFile>(isec->file); 654 if (!file || !file->compileUnit) 655 continue; 656 symbolsNeedingStabs.push_back(defined); 657 } 658 } 659 660 llvm::stable_sort(symbolsNeedingStabs, [&](Defined *a, Defined *b) { 661 return a->isec->file->id < b->isec->file->id; 662 }); 663 664 // Emit STABS symbols so that dsymutil and/or the debugger can map address 665 // regions in the final binary to the source and object files from which they 666 // originated. 667 InputFile *lastFile = nullptr; 668 for (Defined *defined : symbolsNeedingStabs) { 669 InputSection *isec = defined->isec; 670 ObjFile *file = dyn_cast<ObjFile>(isec->file); 671 assert(file); 672 673 if (lastFile == nullptr || lastFile != file) { 674 if (lastFile != nullptr) 675 emitEndSourceStab(); 676 lastFile = file; 677 678 emitBeginSourceStab(file->compileUnit); 679 emitObjectFileStab(file); 680 } 681 682 StabsEntry symStab; 683 symStab.sect = defined->isec->parent->index; 684 symStab.strx = stringTableSection.addString(defined->getName()); 685 symStab.value = defined->getVA(); 686 687 if (isCodeSection(isec)) { 688 symStab.type = MachO::N_FUN; 689 stabs.emplace_back(std::move(symStab)); 690 emitEndFunStab(defined); 691 } else { 692 symStab.type = defined->isExternal() ? MachO::N_GSYM : MachO::N_STSYM; 693 stabs.emplace_back(std::move(symStab)); 694 } 695 } 696 697 if (!stabs.empty()) 698 emitEndSourceStab(); 699 } 700 701 void SymtabSection::finalizeContents() { 702 auto addSymbol = [&](std::vector<SymtabEntry> &symbols, Symbol *sym) { 703 uint32_t strx = stringTableSection.addString(sym->getName()); 704 symbols.push_back({sym, strx}); 705 }; 706 707 // Local symbols aren't in the SymbolTable, so we walk the list of object 708 // files to gather them. 709 for (InputFile *file : inputFiles) { 710 if (auto *objFile = dyn_cast<ObjFile>(file)) { 711 for (Symbol *sym : objFile->symbols) { 712 // TODO: when we implement -dead_strip, we should filter out symbols 713 // that belong to dead sections. 714 if (auto *defined = dyn_cast<Defined>(sym)) { 715 if (!defined->isExternal()) { 716 StringRef name = defined->getName(); 717 if (!name.startswith("l") && !name.startswith("L")) 718 addSymbol(localSymbols, sym); 719 } 720 } 721 } 722 } 723 } 724 725 // __dyld_private is a local symbol too. It's linker-created and doesn't 726 // exist in any object file. 727 if (Defined* dyldPrivate = in.stubHelper->dyldPrivate) 728 addSymbol(localSymbols, dyldPrivate); 729 730 for (Symbol *sym : symtab->getSymbols()) { 731 if (auto *defined = dyn_cast<Defined>(sym)) { 732 assert(defined->isExternal()); 733 (void)defined; 734 addSymbol(externalSymbols, sym); 735 } else if (auto *dysym = dyn_cast<DylibSymbol>(sym)) { 736 if (dysym->isReferenced()) 737 addSymbol(undefinedSymbols, sym); 738 } 739 } 740 741 emitStabs(); 742 uint32_t symtabIndex = stabs.size(); 743 for (const SymtabEntry &entry : 744 concat<SymtabEntry>(localSymbols, externalSymbols, undefinedSymbols)) { 745 entry.sym->symtabIndex = symtabIndex++; 746 } 747 } 748 749 uint32_t SymtabSection::getNumSymbols() const { 750 return stabs.size() + localSymbols.size() + externalSymbols.size() + 751 undefinedSymbols.size(); 752 } 753 754 void SymtabSection::writeTo(uint8_t *buf) const { 755 auto *nList = reinterpret_cast<structs::nlist_64 *>(buf); 756 // Emit the stabs entries before the "real" symbols. We cannot emit them 757 // after as that would render Symbol::symtabIndex inaccurate. 758 for (const StabsEntry &entry : stabs) { 759 nList->n_strx = entry.strx; 760 nList->n_type = entry.type; 761 nList->n_sect = entry.sect; 762 nList->n_desc = entry.desc; 763 nList->n_value = entry.value; 764 ++nList; 765 } 766 767 for (const SymtabEntry &entry : concat<const SymtabEntry>( 768 localSymbols, externalSymbols, undefinedSymbols)) { 769 nList->n_strx = entry.strx; 770 // TODO populate n_desc with more flags 771 if (auto *defined = dyn_cast<Defined>(entry.sym)) { 772 uint8_t scope = 0; 773 if (defined->privateExtern) { 774 // Private external -- dylib scoped symbol. 775 // Promote to non-external at link time. 776 assert(defined->isExternal() && "invalid input file"); 777 scope = MachO::N_PEXT; 778 } else if (defined->isExternal()) { 779 // Normal global symbol. 780 scope = MachO::N_EXT; 781 } else { 782 // TU-local symbol from localSymbols. 783 scope = 0; 784 } 785 786 if (defined->isAbsolute()) { 787 nList->n_type = scope | MachO::N_ABS; 788 nList->n_sect = MachO::NO_SECT; 789 nList->n_value = defined->value; 790 } else { 791 nList->n_type = scope | MachO::N_SECT; 792 nList->n_sect = defined->isec->parent->index; 793 // For the N_SECT symbol type, n_value is the address of the symbol 794 nList->n_value = defined->getVA(); 795 } 796 nList->n_desc |= defined->isExternalWeakDef() ? MachO::N_WEAK_DEF : 0; 797 } else if (auto *dysym = dyn_cast<DylibSymbol>(entry.sym)) { 798 uint16_t n_desc = nList->n_desc; 799 MachO::SET_LIBRARY_ORDINAL(n_desc, dysym->getFile()->ordinal); 800 nList->n_type = MachO::N_EXT; 801 n_desc |= dysym->isWeakRef() ? MachO::N_WEAK_REF : 0; 802 nList->n_desc = n_desc; 803 } 804 ++nList; 805 } 806 } 807 808 IndirectSymtabSection::IndirectSymtabSection() 809 : LinkEditSection(segment_names::linkEdit, 810 section_names::indirectSymbolTable) {} 811 812 uint32_t IndirectSymtabSection::getNumSymbols() const { 813 return in.got->getEntries().size() + in.tlvPointers->getEntries().size() + 814 in.stubs->getEntries().size(); 815 } 816 817 bool IndirectSymtabSection::isNeeded() const { 818 return in.got->isNeeded() || in.tlvPointers->isNeeded() || 819 in.stubs->isNeeded(); 820 } 821 822 void IndirectSymtabSection::finalizeContents() { 823 uint32_t off = 0; 824 in.got->reserved1 = off; 825 off += in.got->getEntries().size(); 826 in.tlvPointers->reserved1 = off; 827 off += in.tlvPointers->getEntries().size(); 828 // There is a 1:1 correspondence between stubs and LazyPointerSection 829 // entries, so they can share the same sub-array in the table. 830 in.stubs->reserved1 = in.lazyPointers->reserved1 = off; 831 } 832 833 static uint32_t indirectValue(const Symbol *sym) { 834 return sym->symtabIndex != UINT32_MAX ? sym->symtabIndex 835 : MachO::INDIRECT_SYMBOL_LOCAL; 836 } 837 838 void IndirectSymtabSection::writeTo(uint8_t *buf) const { 839 uint32_t off = 0; 840 for (const Symbol *sym : in.got->getEntries()) { 841 write32le(buf + off * sizeof(uint32_t), indirectValue(sym)); 842 ++off; 843 } 844 for (const Symbol *sym : in.tlvPointers->getEntries()) { 845 write32le(buf + off * sizeof(uint32_t), indirectValue(sym)); 846 ++off; 847 } 848 for (const Symbol *sym : in.stubs->getEntries()) { 849 write32le(buf + off * sizeof(uint32_t), indirectValue(sym)); 850 ++off; 851 } 852 } 853 854 StringTableSection::StringTableSection() 855 : LinkEditSection(segment_names::linkEdit, section_names::stringTable) {} 856 857 uint32_t StringTableSection::addString(StringRef str) { 858 uint32_t strx = size; 859 strings.push_back(str); // TODO: consider deduplicating strings 860 size += str.size() + 1; // account for null terminator 861 return strx; 862 } 863 864 void StringTableSection::writeTo(uint8_t *buf) const { 865 uint32_t off = 0; 866 for (StringRef str : strings) { 867 memcpy(buf + off, str.data(), str.size()); 868 off += str.size() + 1; // account for null terminator 869 } 870 } 871