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 #include "llvm/Support/SHA256.h" 28 29 #if defined(__APPLE__) 30 #include <sys/mman.h> 31 #endif 32 33 using namespace llvm; 34 using namespace llvm::MachO; 35 using namespace llvm::support; 36 using namespace llvm::support::endian; 37 using namespace lld; 38 using namespace lld::macho; 39 40 InStruct macho::in; 41 std::vector<SyntheticSection *> macho::syntheticSections; 42 43 SyntheticSection::SyntheticSection(const char *segname, const char *name) 44 : OutputSection(SyntheticKind, name), segname(segname) { 45 isec = make<InputSection>(); 46 isec->segname = segname; 47 isec->name = name; 48 isec->parent = this; 49 isec->outSecOff = 0; 50 syntheticSections.push_back(this); 51 } 52 53 // dyld3's MachOLoaded::getSlide() assumes that the __TEXT segment starts 54 // from the beginning of the file (i.e. the header). 55 MachHeaderSection::MachHeaderSection() 56 : SyntheticSection(segment_names::text, section_names::header) { 57 // XXX: This is a hack. (See D97007) 58 // Setting the index to 1 to pretend that this section is the text 59 // section. 60 index = 1; 61 } 62 63 void MachHeaderSection::addLoadCommand(LoadCommand *lc) { 64 loadCommands.push_back(lc); 65 sizeOfCmds += lc->getSize(); 66 } 67 68 // This serves to hide (type-erase) the template parameter from 69 // MachHeaderSection. 70 template <class LP> class MachHeaderSectionImpl : public MachHeaderSection { 71 public: 72 MachHeaderSectionImpl() = default; 73 uint64_t getSize() const override; 74 void writeTo(uint8_t *buf) const override; 75 }; 76 77 template <class LP> MachHeaderSection *macho::makeMachHeaderSection() { 78 return make<MachHeaderSectionImpl<LP>>(); 79 } 80 81 template <class LP> uint64_t MachHeaderSectionImpl<LP>::getSize() const { 82 return sizeof(typename LP::mach_header) + sizeOfCmds + config->headerPad; 83 } 84 85 static uint32_t cpuSubtype() { 86 uint32_t subtype = target->cpuSubtype; 87 88 if (config->outputType == MH_EXECUTE && !config->staticLink && 89 target->cpuSubtype == CPU_SUBTYPE_X86_64_ALL && 90 config->target.Platform == PlatformKind::macOS && 91 config->platformInfo.minimum >= VersionTuple(10, 5)) 92 subtype |= CPU_SUBTYPE_LIB64; 93 94 return subtype; 95 } 96 97 template <class LP> 98 void MachHeaderSectionImpl<LP>::writeTo(uint8_t *buf) const { 99 auto *hdr = reinterpret_cast<typename LP::mach_header *>(buf); 100 hdr->magic = LP::magic; 101 hdr->cputype = target->cpuType; 102 hdr->cpusubtype = cpuSubtype(); 103 hdr->filetype = config->outputType; 104 hdr->ncmds = loadCommands.size(); 105 hdr->sizeofcmds = sizeOfCmds; 106 hdr->flags = MH_DYLDLINK; 107 108 if (config->namespaceKind == NamespaceKind::twolevel) 109 hdr->flags |= MH_NOUNDEFS | MH_TWOLEVEL; 110 111 if (config->outputType == MH_DYLIB && !config->hasReexports) 112 hdr->flags |= MH_NO_REEXPORTED_DYLIBS; 113 114 if (config->markDeadStrippableDylib) 115 hdr->flags |= MH_DEAD_STRIPPABLE_DYLIB; 116 117 if (config->outputType == MH_EXECUTE && config->isPic) 118 hdr->flags |= MH_PIE; 119 120 if (in.exports->hasWeakSymbol || in.weakBinding->hasNonWeakDefinition()) 121 hdr->flags |= MH_WEAK_DEFINES; 122 123 if (in.exports->hasWeakSymbol || in.weakBinding->hasEntry()) 124 hdr->flags |= MH_BINDS_TO_WEAK; 125 126 for (const OutputSegment *seg : outputSegments) { 127 for (const OutputSection *osec : seg->getSections()) { 128 if (isThreadLocalVariables(osec->flags)) { 129 hdr->flags |= MH_HAS_TLV_DESCRIPTORS; 130 break; 131 } 132 } 133 } 134 135 uint8_t *p = reinterpret_cast<uint8_t *>(hdr + 1); 136 for (const LoadCommand *lc : loadCommands) { 137 lc->writeTo(p); 138 p += lc->getSize(); 139 } 140 } 141 142 PageZeroSection::PageZeroSection() 143 : SyntheticSection(segment_names::pageZero, section_names::pageZero) {} 144 145 RebaseSection::RebaseSection() 146 : LinkEditSection(segment_names::linkEdit, section_names::rebase) {} 147 148 namespace { 149 struct Rebase { 150 OutputSegment *segment = nullptr; 151 uint64_t offset = 0; 152 uint64_t consecutiveCount = 0; 153 }; 154 } // namespace 155 156 // Rebase opcodes allow us to describe a contiguous sequence of rebase location 157 // using a single DO_REBASE opcode. To take advantage of it, we delay emitting 158 // `DO_REBASE` until we have reached the end of a contiguous sequence. 159 static void encodeDoRebase(Rebase &rebase, raw_svector_ostream &os) { 160 assert(rebase.consecutiveCount != 0); 161 if (rebase.consecutiveCount <= REBASE_IMMEDIATE_MASK) { 162 os << static_cast<uint8_t>(REBASE_OPCODE_DO_REBASE_IMM_TIMES | 163 rebase.consecutiveCount); 164 } else { 165 os << static_cast<uint8_t>(REBASE_OPCODE_DO_REBASE_ULEB_TIMES); 166 encodeULEB128(rebase.consecutiveCount, os); 167 } 168 rebase.consecutiveCount = 0; 169 } 170 171 static void encodeRebase(const OutputSection *osec, uint64_t outSecOff, 172 Rebase &lastRebase, raw_svector_ostream &os) { 173 OutputSegment *seg = osec->parent; 174 uint64_t offset = osec->getSegmentOffset() + outSecOff; 175 if (lastRebase.segment != seg || lastRebase.offset != offset) { 176 if (lastRebase.consecutiveCount != 0) 177 encodeDoRebase(lastRebase, os); 178 179 if (lastRebase.segment != seg) { 180 os << static_cast<uint8_t>(REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB | 181 seg->index); 182 encodeULEB128(offset, os); 183 lastRebase.segment = seg; 184 lastRebase.offset = offset; 185 } else { 186 assert(lastRebase.offset != offset); 187 os << static_cast<uint8_t>(REBASE_OPCODE_ADD_ADDR_ULEB); 188 encodeULEB128(offset - lastRebase.offset, os); 189 lastRebase.offset = offset; 190 } 191 } 192 ++lastRebase.consecutiveCount; 193 // DO_REBASE causes dyld to both perform the binding and increment the offset 194 lastRebase.offset += target->wordSize; 195 } 196 197 void RebaseSection::finalizeContents() { 198 if (locations.empty()) 199 return; 200 201 raw_svector_ostream os{contents}; 202 Rebase lastRebase; 203 204 os << static_cast<uint8_t>(REBASE_OPCODE_SET_TYPE_IMM | REBASE_TYPE_POINTER); 205 206 llvm::sort(locations, [](const Location &a, const Location &b) { 207 return a.isec->getVA() < b.isec->getVA(); 208 }); 209 for (const Location &loc : locations) 210 encodeRebase(loc.isec->parent, loc.isec->outSecOff + loc.offset, lastRebase, 211 os); 212 if (lastRebase.consecutiveCount != 0) 213 encodeDoRebase(lastRebase, os); 214 215 os << static_cast<uint8_t>(REBASE_OPCODE_DONE); 216 } 217 218 void RebaseSection::writeTo(uint8_t *buf) const { 219 memcpy(buf, contents.data(), contents.size()); 220 } 221 222 NonLazyPointerSectionBase::NonLazyPointerSectionBase(const char *segname, 223 const char *name) 224 : SyntheticSection(segname, name) { 225 align = target->wordSize; 226 flags = S_NON_LAZY_SYMBOL_POINTERS; 227 } 228 229 void macho::addNonLazyBindingEntries(const Symbol *sym, 230 const InputSection *isec, uint64_t offset, 231 int64_t addend) { 232 if (const auto *dysym = dyn_cast<DylibSymbol>(sym)) { 233 in.binding->addEntry(dysym, isec, offset, addend); 234 if (dysym->isWeakDef()) 235 in.weakBinding->addEntry(sym, isec, offset, addend); 236 } else if (const auto *defined = dyn_cast<Defined>(sym)) { 237 in.rebase->addEntry(isec, offset); 238 if (defined->isExternalWeakDef()) 239 in.weakBinding->addEntry(sym, isec, offset, addend); 240 } else { 241 // Undefined symbols are filtered out in scanRelocations(); we should never 242 // get here 243 llvm_unreachable("cannot bind to an undefined symbol"); 244 } 245 } 246 247 void NonLazyPointerSectionBase::addEntry(Symbol *sym) { 248 if (entries.insert(sym)) { 249 assert(!sym->isInGot()); 250 sym->gotIndex = entries.size() - 1; 251 252 addNonLazyBindingEntries(sym, isec, sym->gotIndex * target->wordSize); 253 } 254 } 255 256 void NonLazyPointerSectionBase::writeTo(uint8_t *buf) const { 257 for (size_t i = 0, n = entries.size(); i < n; ++i) 258 if (auto *defined = dyn_cast<Defined>(entries[i])) 259 write64le(&buf[i * target->wordSize], defined->getVA()); 260 } 261 262 BindingSection::BindingSection() 263 : LinkEditSection(segment_names::linkEdit, section_names::binding) {} 264 265 namespace { 266 struct Binding { 267 OutputSegment *segment = nullptr; 268 uint64_t offset = 0; 269 int64_t addend = 0; 270 int16_t ordinal = 0; 271 }; 272 } // namespace 273 274 // Encode a sequence of opcodes that tell dyld to write the address of symbol + 275 // addend at osec->addr + outSecOff. 276 // 277 // The bind opcode "interpreter" remembers the values of each binding field, so 278 // we only need to encode the differences between bindings. Hence the use of 279 // lastBinding. 280 static void encodeBinding(const Symbol *sym, const OutputSection *osec, 281 uint64_t outSecOff, int64_t addend, 282 bool isWeakBinding, Binding &lastBinding, 283 raw_svector_ostream &os) { 284 OutputSegment *seg = osec->parent; 285 uint64_t offset = osec->getSegmentOffset() + outSecOff; 286 if (lastBinding.segment != seg) { 287 os << static_cast<uint8_t>(BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB | 288 seg->index); 289 encodeULEB128(offset, os); 290 lastBinding.segment = seg; 291 lastBinding.offset = offset; 292 } else if (lastBinding.offset != offset) { 293 os << static_cast<uint8_t>(BIND_OPCODE_ADD_ADDR_ULEB); 294 encodeULEB128(offset - lastBinding.offset, os); 295 lastBinding.offset = offset; 296 } 297 298 if (lastBinding.addend != addend) { 299 os << static_cast<uint8_t>(BIND_OPCODE_SET_ADDEND_SLEB); 300 encodeSLEB128(addend, os); 301 lastBinding.addend = addend; 302 } 303 304 uint8_t flags = BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM; 305 if (!isWeakBinding && sym->isWeakRef()) 306 flags |= BIND_SYMBOL_FLAGS_WEAK_IMPORT; 307 308 os << flags << sym->getName() << '\0' 309 << static_cast<uint8_t>(BIND_OPCODE_SET_TYPE_IMM | BIND_TYPE_POINTER) 310 << static_cast<uint8_t>(BIND_OPCODE_DO_BIND); 311 // DO_BIND causes dyld to both perform the binding and increment the offset 312 lastBinding.offset += target->wordSize; 313 } 314 315 // Non-weak bindings need to have their dylib ordinal encoded as well. 316 static int16_t ordinalForDylibSymbol(const DylibSymbol &dysym) { 317 return config->namespaceKind == NamespaceKind::flat || dysym.isDynamicLookup() 318 ? static_cast<int16_t>(BIND_SPECIAL_DYLIB_FLAT_LOOKUP) 319 : dysym.getFile()->ordinal; 320 } 321 322 static void encodeDylibOrdinal(int16_t ordinal, raw_svector_ostream &os) { 323 if (ordinal <= 0) { 324 os << static_cast<uint8_t>(BIND_OPCODE_SET_DYLIB_SPECIAL_IMM | 325 (ordinal & BIND_IMMEDIATE_MASK)); 326 } else if (ordinal <= BIND_IMMEDIATE_MASK) { 327 os << static_cast<uint8_t>(BIND_OPCODE_SET_DYLIB_ORDINAL_IMM | ordinal); 328 } else { 329 os << static_cast<uint8_t>(BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB); 330 encodeULEB128(ordinal, os); 331 } 332 } 333 334 static void encodeWeakOverride(const Defined *defined, 335 raw_svector_ostream &os) { 336 os << static_cast<uint8_t>(BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM | 337 BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) 338 << defined->getName() << '\0'; 339 } 340 341 // Emit bind opcodes, which are a stream of byte-sized opcodes that dyld 342 // interprets to update a record with the following fields: 343 // * segment index (of the segment to write the symbol addresses to, typically 344 // the __DATA_CONST segment which contains the GOT) 345 // * offset within the segment, indicating the next location to write a binding 346 // * symbol type 347 // * symbol library ordinal (the index of its library's LC_LOAD_DYLIB command) 348 // * symbol name 349 // * addend 350 // When dyld sees BIND_OPCODE_DO_BIND, it uses the current record state to bind 351 // a symbol in the GOT, and increments the segment offset to point to the next 352 // entry. It does *not* clear the record state after doing the bind, so 353 // subsequent opcodes only need to encode the differences between bindings. 354 void BindingSection::finalizeContents() { 355 raw_svector_ostream os{contents}; 356 Binding lastBinding; 357 358 // Since bindings are delta-encoded, sorting them allows for a more compact 359 // result. Note that sorting by address alone ensures that bindings for the 360 // same segment / section are located together. 361 llvm::sort(bindings, [](const BindingEntry &a, const BindingEntry &b) { 362 return a.target.getVA() < b.target.getVA(); 363 }); 364 for (const BindingEntry &b : bindings) { 365 int16_t ordinal = ordinalForDylibSymbol(*b.dysym); 366 if (ordinal != lastBinding.ordinal) { 367 encodeDylibOrdinal(ordinal, os); 368 lastBinding.ordinal = ordinal; 369 } 370 encodeBinding(b.dysym, b.target.isec->parent, 371 b.target.isec->outSecOff + b.target.offset, b.addend, 372 /*isWeakBinding=*/false, lastBinding, os); 373 } 374 if (!bindings.empty()) 375 os << static_cast<uint8_t>(BIND_OPCODE_DONE); 376 } 377 378 void BindingSection::writeTo(uint8_t *buf) const { 379 memcpy(buf, contents.data(), contents.size()); 380 } 381 382 WeakBindingSection::WeakBindingSection() 383 : LinkEditSection(segment_names::linkEdit, section_names::weakBinding) {} 384 385 void WeakBindingSection::finalizeContents() { 386 raw_svector_ostream os{contents}; 387 Binding lastBinding; 388 389 for (const Defined *defined : definitions) 390 encodeWeakOverride(defined, os); 391 392 // Since bindings are delta-encoded, sorting them allows for a more compact 393 // result. 394 llvm::sort(bindings, 395 [](const WeakBindingEntry &a, const WeakBindingEntry &b) { 396 return a.target.getVA() < b.target.getVA(); 397 }); 398 for (const WeakBindingEntry &b : bindings) 399 encodeBinding(b.symbol, b.target.isec->parent, 400 b.target.isec->outSecOff + b.target.offset, b.addend, 401 /*isWeakBinding=*/true, lastBinding, os); 402 if (!bindings.empty() || !definitions.empty()) 403 os << static_cast<uint8_t>(BIND_OPCODE_DONE); 404 } 405 406 void WeakBindingSection::writeTo(uint8_t *buf) const { 407 memcpy(buf, contents.data(), contents.size()); 408 } 409 410 StubsSection::StubsSection() 411 : SyntheticSection(segment_names::text, "__stubs") { 412 flags = S_SYMBOL_STUBS | S_ATTR_SOME_INSTRUCTIONS | S_ATTR_PURE_INSTRUCTIONS; 413 // The stubs section comprises machine instructions, which are aligned to 414 // 4 bytes on the archs we care about. 415 align = 4; 416 reserved2 = target->stubSize; 417 } 418 419 uint64_t StubsSection::getSize() const { 420 return entries.size() * target->stubSize; 421 } 422 423 void StubsSection::writeTo(uint8_t *buf) const { 424 size_t off = 0; 425 for (const Symbol *sym : entries) { 426 target->writeStub(buf + off, *sym); 427 off += target->stubSize; 428 } 429 } 430 431 bool StubsSection::addEntry(Symbol *sym) { 432 bool inserted = entries.insert(sym); 433 if (inserted) 434 sym->stubsIndex = entries.size() - 1; 435 return inserted; 436 } 437 438 StubHelperSection::StubHelperSection() 439 : SyntheticSection(segment_names::text, "__stub_helper") { 440 flags = S_ATTR_SOME_INSTRUCTIONS | S_ATTR_PURE_INSTRUCTIONS; 441 align = 4; // This section comprises machine instructions 442 } 443 444 uint64_t StubHelperSection::getSize() const { 445 return target->stubHelperHeaderSize + 446 in.lazyBinding->getEntries().size() * target->stubHelperEntrySize; 447 } 448 449 bool StubHelperSection::isNeeded() const { return in.lazyBinding->isNeeded(); } 450 451 void StubHelperSection::writeTo(uint8_t *buf) const { 452 target->writeStubHelperHeader(buf); 453 size_t off = target->stubHelperHeaderSize; 454 for (const DylibSymbol *sym : in.lazyBinding->getEntries()) { 455 target->writeStubHelperEntry(buf + off, *sym, addr + off); 456 off += target->stubHelperEntrySize; 457 } 458 } 459 460 void StubHelperSection::setup() { 461 stubBinder = dyn_cast_or_null<DylibSymbol>(symtab->find("dyld_stub_binder")); 462 if (stubBinder == nullptr) { 463 error("symbol dyld_stub_binder not found (normally in libSystem.dylib). " 464 "Needed to perform lazy binding."); 465 return; 466 } 467 stubBinder->refState = RefState::Strong; 468 in.got->addEntry(stubBinder); 469 470 inputSections.push_back(in.imageLoaderCache); 471 dyldPrivate = 472 make<Defined>("__dyld_private", nullptr, in.imageLoaderCache, 0, 0, 473 /*isWeakDef=*/false, 474 /*isExternal=*/false, /*isPrivateExtern=*/false); 475 } 476 477 ImageLoaderCacheSection::ImageLoaderCacheSection() { 478 segname = segment_names::data; 479 name = "__data"; 480 uint8_t *arr = bAlloc.Allocate<uint8_t>(target->wordSize); 481 memset(arr, 0, target->wordSize); 482 data = {arr, target->wordSize}; 483 align = target->wordSize; 484 } 485 486 LazyPointerSection::LazyPointerSection() 487 : SyntheticSection(segment_names::data, "__la_symbol_ptr") { 488 align = target->wordSize; 489 flags = S_LAZY_SYMBOL_POINTERS; 490 } 491 492 uint64_t LazyPointerSection::getSize() const { 493 return in.stubs->getEntries().size() * target->wordSize; 494 } 495 496 bool LazyPointerSection::isNeeded() const { 497 return !in.stubs->getEntries().empty(); 498 } 499 500 void LazyPointerSection::writeTo(uint8_t *buf) const { 501 size_t off = 0; 502 for (const Symbol *sym : in.stubs->getEntries()) { 503 if (const auto *dysym = dyn_cast<DylibSymbol>(sym)) { 504 if (dysym->hasStubsHelper()) { 505 uint64_t stubHelperOffset = 506 target->stubHelperHeaderSize + 507 dysym->stubsHelperIndex * target->stubHelperEntrySize; 508 write64le(buf + off, in.stubHelper->addr + stubHelperOffset); 509 } 510 } else { 511 write64le(buf + off, sym->getVA()); 512 } 513 off += target->wordSize; 514 } 515 } 516 517 LazyBindingSection::LazyBindingSection() 518 : LinkEditSection(segment_names::linkEdit, section_names::lazyBinding) {} 519 520 void LazyBindingSection::finalizeContents() { 521 // TODO: Just precompute output size here instead of writing to a temporary 522 // buffer 523 for (DylibSymbol *sym : entries) 524 sym->lazyBindOffset = encode(*sym); 525 } 526 527 void LazyBindingSection::writeTo(uint8_t *buf) const { 528 memcpy(buf, contents.data(), contents.size()); 529 } 530 531 void LazyBindingSection::addEntry(DylibSymbol *dysym) { 532 if (entries.insert(dysym)) { 533 dysym->stubsHelperIndex = entries.size() - 1; 534 in.rebase->addEntry(in.lazyPointers->isec, 535 dysym->stubsIndex * target->wordSize); 536 } 537 } 538 539 // Unlike the non-lazy binding section, the bind opcodes in this section aren't 540 // interpreted all at once. Rather, dyld will start interpreting opcodes at a 541 // given offset, typically only binding a single symbol before it finds a 542 // BIND_OPCODE_DONE terminator. As such, unlike in the non-lazy-binding case, 543 // we cannot encode just the differences between symbols; we have to emit the 544 // complete bind information for each symbol. 545 uint32_t LazyBindingSection::encode(const DylibSymbol &sym) { 546 uint32_t opstreamOffset = contents.size(); 547 OutputSegment *dataSeg = in.lazyPointers->parent; 548 os << static_cast<uint8_t>(BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB | 549 dataSeg->index); 550 uint64_t offset = in.lazyPointers->addr - dataSeg->firstSection()->addr + 551 sym.stubsIndex * target->wordSize; 552 encodeULEB128(offset, os); 553 encodeDylibOrdinal(ordinalForDylibSymbol(sym), os); 554 555 uint8_t flags = BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM; 556 if (sym.isWeakRef()) 557 flags |= BIND_SYMBOL_FLAGS_WEAK_IMPORT; 558 559 os << flags << sym.getName() << '\0' 560 << static_cast<uint8_t>(BIND_OPCODE_DO_BIND) 561 << static_cast<uint8_t>(BIND_OPCODE_DONE); 562 return opstreamOffset; 563 } 564 565 ExportSection::ExportSection() 566 : LinkEditSection(segment_names::linkEdit, section_names::export_) {} 567 568 static void validateExportSymbol(const Defined *defined) { 569 StringRef symbolName = defined->getName(); 570 if (defined->privateExtern && config->exportedSymbols.match(symbolName)) 571 error("cannot export hidden symbol " + symbolName + "\n>>> defined in " + 572 toString(defined->getFile())); 573 } 574 575 static bool shouldExportSymbol(const Defined *defined) { 576 if (defined->privateExtern) 577 return false; 578 // TODO: Is this a performance bottleneck? If a build has mostly 579 // global symbols in the input but uses -exported_symbols to filter 580 // out most of them, then it would be better to set the value of 581 // privateExtern at parse time instead of calling 582 // exportedSymbols.match() more than once. 583 // 584 // Measurements show that symbol ordering (which again looks up 585 // every symbol in a hashmap) is the biggest bottleneck when linking 586 // chromium_framework, so this will likely be worth optimizing. 587 return config->exportedSymbols.empty() 588 ? !config->unexportedSymbols.match(defined->getName()) 589 : config->exportedSymbols.match(defined->getName()); 590 } 591 592 void ExportSection::finalizeContents() { 593 trieBuilder.setImageBase(in.header->addr); 594 for (const Symbol *sym : symtab->getSymbols()) { 595 if (const auto *defined = dyn_cast<Defined>(sym)) { 596 validateExportSymbol(defined); 597 if (!shouldExportSymbol(defined)) 598 continue; 599 trieBuilder.addSymbol(*defined); 600 hasWeakSymbol = hasWeakSymbol || sym->isWeakDef(); 601 } 602 } 603 size = trieBuilder.build(); 604 } 605 606 void ExportSection::writeTo(uint8_t *buf) const { trieBuilder.writeTo(buf); } 607 608 FunctionStartsSection::FunctionStartsSection() 609 : LinkEditSection(segment_names::linkEdit, section_names::functionStarts) {} 610 611 void FunctionStartsSection::finalizeContents() { 612 raw_svector_ostream os{contents}; 613 uint64_t addr = in.header->addr; 614 for (const Symbol *sym : symtab->getSymbols()) { 615 if (const auto *defined = dyn_cast<Defined>(sym)) { 616 if (!defined->isec || !isCodeSection(defined->isec)) 617 continue; 618 // TODO: Add support for thumbs, in that case 619 // the lowest bit of nextAddr needs to be set to 1. 620 uint64_t nextAddr = defined->getVA(); 621 uint64_t delta = nextAddr - addr; 622 if (delta == 0) 623 continue; 624 encodeULEB128(delta, os); 625 addr = nextAddr; 626 } 627 } 628 os << '\0'; 629 } 630 631 void FunctionStartsSection::writeTo(uint8_t *buf) const { 632 memcpy(buf, contents.data(), contents.size()); 633 } 634 635 SymtabSection::SymtabSection(StringTableSection &stringTableSection) 636 : LinkEditSection(segment_names::linkEdit, section_names::symbolTable), 637 stringTableSection(stringTableSection) {} 638 639 void SymtabSection::emitBeginSourceStab(DWARFUnit *compileUnit) { 640 StabsEntry stab(N_SO); 641 SmallString<261> dir(compileUnit->getCompilationDir()); 642 StringRef sep = sys::path::get_separator(); 643 // We don't use `path::append` here because we want an empty `dir` to result 644 // in an absolute path. `append` would give us a relative path for that case. 645 if (!dir.endswith(sep)) 646 dir += sep; 647 stab.strx = stringTableSection.addString( 648 saver.save(dir + compileUnit->getUnitDIE().getShortName())); 649 stabs.emplace_back(std::move(stab)); 650 } 651 652 void SymtabSection::emitEndSourceStab() { 653 StabsEntry stab(N_SO); 654 stab.sect = 1; 655 stabs.emplace_back(std::move(stab)); 656 } 657 658 void SymtabSection::emitObjectFileStab(ObjFile *file) { 659 StabsEntry stab(N_OSO); 660 stab.sect = target->cpuSubtype; 661 SmallString<261> path(!file->archiveName.empty() ? file->archiveName 662 : file->getName()); 663 std::error_code ec = sys::fs::make_absolute(path); 664 if (ec) 665 fatal("failed to get absolute path for " + path); 666 667 if (!file->archiveName.empty()) 668 path.append({"(", file->getName(), ")"}); 669 670 stab.strx = stringTableSection.addString(saver.save(path.str())); 671 stab.desc = 1; 672 stab.value = file->modTime; 673 stabs.emplace_back(std::move(stab)); 674 } 675 676 void SymtabSection::emitEndFunStab(Defined *defined) { 677 StabsEntry stab(N_FUN); 678 stab.value = defined->size; 679 stabs.emplace_back(std::move(stab)); 680 } 681 682 void SymtabSection::emitStabs() { 683 for (const std::string &s : config->astPaths) { 684 StabsEntry astStab(N_AST); 685 astStab.strx = stringTableSection.addString(s); 686 stabs.emplace_back(std::move(astStab)); 687 } 688 689 std::vector<Defined *> symbolsNeedingStabs; 690 for (const SymtabEntry &entry : 691 concat<SymtabEntry>(localSymbols, externalSymbols)) { 692 Symbol *sym = entry.sym; 693 if (auto *defined = dyn_cast<Defined>(sym)) { 694 if (defined->isAbsolute()) 695 continue; 696 InputSection *isec = defined->isec; 697 ObjFile *file = dyn_cast_or_null<ObjFile>(isec->file); 698 if (!file || !file->compileUnit) 699 continue; 700 symbolsNeedingStabs.push_back(defined); 701 } 702 } 703 704 llvm::stable_sort(symbolsNeedingStabs, [&](Defined *a, Defined *b) { 705 return a->isec->file->id < b->isec->file->id; 706 }); 707 708 // Emit STABS symbols so that dsymutil and/or the debugger can map address 709 // regions in the final binary to the source and object files from which they 710 // originated. 711 InputFile *lastFile = nullptr; 712 for (Defined *defined : symbolsNeedingStabs) { 713 InputSection *isec = defined->isec; 714 ObjFile *file = cast<ObjFile>(isec->file); 715 716 if (lastFile == nullptr || lastFile != file) { 717 if (lastFile != nullptr) 718 emitEndSourceStab(); 719 lastFile = file; 720 721 emitBeginSourceStab(file->compileUnit); 722 emitObjectFileStab(file); 723 } 724 725 StabsEntry symStab; 726 symStab.sect = defined->isec->parent->index; 727 symStab.strx = stringTableSection.addString(defined->getName()); 728 symStab.value = defined->getVA(); 729 730 if (isCodeSection(isec)) { 731 symStab.type = N_FUN; 732 stabs.emplace_back(std::move(symStab)); 733 emitEndFunStab(defined); 734 } else { 735 symStab.type = defined->isExternal() ? N_GSYM : N_STSYM; 736 stabs.emplace_back(std::move(symStab)); 737 } 738 } 739 740 if (!stabs.empty()) 741 emitEndSourceStab(); 742 } 743 744 void SymtabSection::finalizeContents() { 745 auto addSymbol = [&](std::vector<SymtabEntry> &symbols, Symbol *sym) { 746 uint32_t strx = stringTableSection.addString(sym->getName()); 747 symbols.push_back({sym, strx}); 748 }; 749 750 // Local symbols aren't in the SymbolTable, so we walk the list of object 751 // files to gather them. 752 for (const InputFile *file : inputFiles) { 753 if (auto *objFile = dyn_cast<ObjFile>(file)) { 754 for (Symbol *sym : objFile->symbols) { 755 if (sym == nullptr) 756 continue; 757 // TODO: when we implement -dead_strip, we should filter out symbols 758 // that belong to dead sections. 759 if (auto *defined = dyn_cast<Defined>(sym)) { 760 if (!defined->isExternal()) { 761 StringRef name = defined->getName(); 762 if (!name.startswith("l") && !name.startswith("L")) 763 addSymbol(localSymbols, sym); 764 } 765 } 766 } 767 } 768 } 769 770 // __dyld_private is a local symbol too. It's linker-created and doesn't 771 // exist in any object file. 772 if (Defined *dyldPrivate = in.stubHelper->dyldPrivate) 773 addSymbol(localSymbols, dyldPrivate); 774 775 for (Symbol *sym : symtab->getSymbols()) { 776 if (auto *defined = dyn_cast<Defined>(sym)) { 777 if (!defined->includeInSymtab) 778 continue; 779 assert(defined->isExternal()); 780 addSymbol(externalSymbols, defined); 781 } else if (auto *dysym = dyn_cast<DylibSymbol>(sym)) { 782 if (dysym->isReferenced()) 783 addSymbol(undefinedSymbols, sym); 784 } 785 } 786 787 emitStabs(); 788 uint32_t symtabIndex = stabs.size(); 789 for (const SymtabEntry &entry : 790 concat<SymtabEntry>(localSymbols, externalSymbols, undefinedSymbols)) { 791 entry.sym->symtabIndex = symtabIndex++; 792 } 793 } 794 795 uint32_t SymtabSection::getNumSymbols() const { 796 return stabs.size() + localSymbols.size() + externalSymbols.size() + 797 undefinedSymbols.size(); 798 } 799 800 // This serves to hide (type-erase) the template parameter from SymtabSection. 801 template <class LP> class SymtabSectionImpl : public SymtabSection { 802 public: 803 SymtabSectionImpl(StringTableSection &stringTableSection) 804 : SymtabSection(stringTableSection) {} 805 uint64_t getRawSize() const override; 806 void writeTo(uint8_t *buf) const override; 807 }; 808 809 template <class LP> uint64_t SymtabSectionImpl<LP>::getRawSize() const { 810 return getNumSymbols() * sizeof(typename LP::nlist); 811 } 812 813 template <class LP> void SymtabSectionImpl<LP>::writeTo(uint8_t *buf) const { 814 auto *nList = reinterpret_cast<typename LP::nlist *>(buf); 815 // Emit the stabs entries before the "real" symbols. We cannot emit them 816 // after as that would render Symbol::symtabIndex inaccurate. 817 for (const StabsEntry &entry : stabs) { 818 nList->n_strx = entry.strx; 819 nList->n_type = entry.type; 820 nList->n_sect = entry.sect; 821 nList->n_desc = entry.desc; 822 nList->n_value = entry.value; 823 ++nList; 824 } 825 826 for (const SymtabEntry &entry : concat<const SymtabEntry>( 827 localSymbols, externalSymbols, undefinedSymbols)) { 828 nList->n_strx = entry.strx; 829 // TODO populate n_desc with more flags 830 if (auto *defined = dyn_cast<Defined>(entry.sym)) { 831 uint8_t scope = 0; 832 if (!shouldExportSymbol(defined)) { 833 // Private external -- dylib scoped symbol. 834 // Promote to non-external at link time. 835 assert(defined->isExternal() && "invalid input file"); 836 scope = N_PEXT; 837 } else if (defined->isExternal()) { 838 // Normal global symbol. 839 scope = N_EXT; 840 } else { 841 // TU-local symbol from localSymbols. 842 scope = 0; 843 } 844 845 if (defined->isAbsolute()) { 846 nList->n_type = scope | N_ABS; 847 nList->n_sect = NO_SECT; 848 nList->n_value = defined->value; 849 } else { 850 nList->n_type = scope | N_SECT; 851 nList->n_sect = defined->isec->parent->index; 852 // For the N_SECT symbol type, n_value is the address of the symbol 853 nList->n_value = defined->getVA(); 854 } 855 nList->n_desc |= defined->isExternalWeakDef() ? N_WEAK_DEF : 0; 856 } else if (auto *dysym = dyn_cast<DylibSymbol>(entry.sym)) { 857 uint16_t n_desc = nList->n_desc; 858 int16_t ordinal = ordinalForDylibSymbol(*dysym); 859 if (ordinal == BIND_SPECIAL_DYLIB_FLAT_LOOKUP) 860 SET_LIBRARY_ORDINAL(n_desc, DYNAMIC_LOOKUP_ORDINAL); 861 else if (ordinal == BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE) 862 SET_LIBRARY_ORDINAL(n_desc, EXECUTABLE_ORDINAL); 863 else { 864 assert(ordinal > 0); 865 SET_LIBRARY_ORDINAL(n_desc, static_cast<uint8_t>(ordinal)); 866 } 867 868 nList->n_type = N_EXT; 869 n_desc |= dysym->isWeakDef() ? N_WEAK_DEF : 0; 870 n_desc |= dysym->isWeakRef() ? N_WEAK_REF : 0; 871 nList->n_desc = n_desc; 872 } 873 ++nList; 874 } 875 } 876 877 template <class LP> 878 SymtabSection * 879 macho::makeSymtabSection(StringTableSection &stringTableSection) { 880 return make<SymtabSectionImpl<LP>>(stringTableSection); 881 } 882 883 IndirectSymtabSection::IndirectSymtabSection() 884 : LinkEditSection(segment_names::linkEdit, 885 section_names::indirectSymbolTable) {} 886 887 uint32_t IndirectSymtabSection::getNumSymbols() const { 888 return in.got->getEntries().size() + in.tlvPointers->getEntries().size() + 889 in.stubs->getEntries().size(); 890 } 891 892 bool IndirectSymtabSection::isNeeded() const { 893 return in.got->isNeeded() || in.tlvPointers->isNeeded() || 894 in.stubs->isNeeded(); 895 } 896 897 void IndirectSymtabSection::finalizeContents() { 898 uint32_t off = 0; 899 in.got->reserved1 = off; 900 off += in.got->getEntries().size(); 901 in.tlvPointers->reserved1 = off; 902 off += in.tlvPointers->getEntries().size(); 903 // There is a 1:1 correspondence between stubs and LazyPointerSection 904 // entries, so they can share the same sub-array in the table. 905 in.stubs->reserved1 = in.lazyPointers->reserved1 = off; 906 } 907 908 static uint32_t indirectValue(const Symbol *sym) { 909 return sym->symtabIndex != UINT32_MAX ? sym->symtabIndex 910 : INDIRECT_SYMBOL_LOCAL; 911 } 912 913 void IndirectSymtabSection::writeTo(uint8_t *buf) const { 914 uint32_t off = 0; 915 for (const Symbol *sym : in.got->getEntries()) { 916 write32le(buf + off * sizeof(uint32_t), indirectValue(sym)); 917 ++off; 918 } 919 for (const Symbol *sym : in.tlvPointers->getEntries()) { 920 write32le(buf + off * sizeof(uint32_t), indirectValue(sym)); 921 ++off; 922 } 923 for (const Symbol *sym : in.stubs->getEntries()) { 924 write32le(buf + off * sizeof(uint32_t), indirectValue(sym)); 925 ++off; 926 } 927 } 928 929 StringTableSection::StringTableSection() 930 : LinkEditSection(segment_names::linkEdit, section_names::stringTable) {} 931 932 uint32_t StringTableSection::addString(StringRef str) { 933 uint32_t strx = size; 934 strings.push_back(str); // TODO: consider deduplicating strings 935 size += str.size() + 1; // account for null terminator 936 return strx; 937 } 938 939 void StringTableSection::writeTo(uint8_t *buf) const { 940 uint32_t off = 0; 941 for (StringRef str : strings) { 942 memcpy(buf + off, str.data(), str.size()); 943 off += str.size() + 1; // account for null terminator 944 } 945 } 946 947 CodeSignatureSection::CodeSignatureSection() 948 : LinkEditSection(segment_names::linkEdit, section_names::codeSignature) { 949 align = 16; // required by libstuff 950 fileName = config->outputFile; 951 size_t slashIndex = fileName.rfind("/"); 952 if (slashIndex != std::string::npos) 953 fileName = fileName.drop_front(slashIndex + 1); 954 allHeadersSize = alignTo<16>(fixedHeadersSize + fileName.size() + 1); 955 fileNamePad = allHeadersSize - fixedHeadersSize - fileName.size(); 956 } 957 958 uint32_t CodeSignatureSection::getBlockCount() const { 959 return (fileOff + blockSize - 1) / blockSize; 960 } 961 962 uint64_t CodeSignatureSection::getRawSize() const { 963 return allHeadersSize + getBlockCount() * hashSize; 964 } 965 966 void CodeSignatureSection::writeHashes(uint8_t *buf) const { 967 uint8_t *code = buf; 968 uint8_t *codeEnd = buf + fileOff; 969 uint8_t *hashes = codeEnd + allHeadersSize; 970 while (code < codeEnd) { 971 StringRef block(reinterpret_cast<char *>(code), 972 std::min(codeEnd - code, static_cast<ssize_t>(blockSize))); 973 SHA256 hasher; 974 hasher.update(block); 975 StringRef hash = hasher.final(); 976 assert(hash.size() == hashSize); 977 memcpy(hashes, hash.data(), hashSize); 978 code += blockSize; 979 hashes += hashSize; 980 } 981 #if defined(__APPLE__) 982 // This is macOS-specific work-around and makes no sense for any 983 // other host OS. See https://openradar.appspot.com/FB8914231 984 // 985 // The macOS kernel maintains a signature-verification cache to 986 // quickly validate applications at time of execve(2). The trouble 987 // is that for the kernel creates the cache entry at the time of the 988 // mmap(2) call, before we have a chance to write either the code to 989 // sign or the signature header+hashes. The fix is to invalidate 990 // all cached data associated with the output file, thus discarding 991 // the bogus prematurely-cached signature. 992 msync(buf, fileOff + getSize(), MS_INVALIDATE); 993 #endif 994 } 995 996 void CodeSignatureSection::writeTo(uint8_t *buf) const { 997 uint32_t signatureSize = static_cast<uint32_t>(getSize()); 998 auto *superBlob = reinterpret_cast<CS_SuperBlob *>(buf); 999 write32be(&superBlob->magic, CSMAGIC_EMBEDDED_SIGNATURE); 1000 write32be(&superBlob->length, signatureSize); 1001 write32be(&superBlob->count, 1); 1002 auto *blobIndex = reinterpret_cast<CS_BlobIndex *>(&superBlob[1]); 1003 write32be(&blobIndex->type, CSSLOT_CODEDIRECTORY); 1004 write32be(&blobIndex->offset, blobHeadersSize); 1005 auto *codeDirectory = 1006 reinterpret_cast<CS_CodeDirectory *>(buf + blobHeadersSize); 1007 write32be(&codeDirectory->magic, CSMAGIC_CODEDIRECTORY); 1008 write32be(&codeDirectory->length, signatureSize - blobHeadersSize); 1009 write32be(&codeDirectory->version, CS_SUPPORTSEXECSEG); 1010 write32be(&codeDirectory->flags, CS_ADHOC | CS_LINKER_SIGNED); 1011 write32be(&codeDirectory->hashOffset, 1012 sizeof(CS_CodeDirectory) + fileName.size() + fileNamePad); 1013 write32be(&codeDirectory->identOffset, sizeof(CS_CodeDirectory)); 1014 codeDirectory->nSpecialSlots = 0; 1015 write32be(&codeDirectory->nCodeSlots, getBlockCount()); 1016 write32be(&codeDirectory->codeLimit, fileOff); 1017 codeDirectory->hashSize = static_cast<uint8_t>(hashSize); 1018 codeDirectory->hashType = kSecCodeSignatureHashSHA256; 1019 codeDirectory->platform = 0; 1020 codeDirectory->pageSize = blockSizeShift; 1021 codeDirectory->spare2 = 0; 1022 codeDirectory->scatterOffset = 0; 1023 codeDirectory->teamOffset = 0; 1024 codeDirectory->spare3 = 0; 1025 codeDirectory->codeLimit64 = 0; 1026 OutputSegment *textSeg = getOrCreateOutputSegment(segment_names::text); 1027 write64be(&codeDirectory->execSegBase, textSeg->fileOff); 1028 write64be(&codeDirectory->execSegLimit, textSeg->fileSize); 1029 write64be(&codeDirectory->execSegFlags, 1030 config->outputType == MH_EXECUTE ? CS_EXECSEG_MAIN_BINARY : 0); 1031 auto *id = reinterpret_cast<char *>(&codeDirectory[1]); 1032 memcpy(id, fileName.begin(), fileName.size()); 1033 memset(id + fileName.size(), 0, fileNamePad); 1034 } 1035 1036 void macho::createSyntheticSymbols() { 1037 auto addHeaderSymbol = [](const char *name) { 1038 symtab->addSynthetic(name, in.header->isec, 0, 1039 /*privateExtern=*/true, 1040 /*includeInSymtab*/ false); 1041 }; 1042 1043 switch (config->outputType) { 1044 // FIXME: Assign the right address value for these symbols 1045 // (rather than 0). But we need to do that after assignAddresses(). 1046 case MH_EXECUTE: 1047 // If linking PIE, __mh_execute_header is a defined symbol in 1048 // __TEXT, __text) 1049 // Otherwise, it's an absolute symbol. 1050 if (config->isPic) 1051 symtab->addSynthetic("__mh_execute_header", in.header->isec, 0, 1052 /*privateExtern*/ false, 1053 /*includeInSymbtab*/ true); 1054 else 1055 symtab->addSynthetic("__mh_execute_header", 1056 /*isec*/ nullptr, 0, 1057 /*privateExtern*/ false, 1058 /*includeInSymbtab*/ true); 1059 break; 1060 1061 // The following symbols are N_SECT symbols, even though the header is not 1062 // part of any section and that they are private to the bundle/dylib/object 1063 // they are part of. 1064 case MH_BUNDLE: 1065 addHeaderSymbol("__mh_bundle_header"); 1066 break; 1067 case MH_DYLIB: 1068 addHeaderSymbol("__mh_dylib_header"); 1069 break; 1070 case MH_DYLINKER: 1071 addHeaderSymbol("__mh_dylinker_header"); 1072 break; 1073 case MH_OBJECT: 1074 addHeaderSymbol("__mh_object_header"); 1075 break; 1076 default: 1077 llvm_unreachable("unexpected outputType"); 1078 break; 1079 } 1080 1081 // The Itanium C++ ABI requires dylibs to pass a pointer to __cxa_atexit 1082 // which does e.g. cleanup of static global variables. The ABI document 1083 // says that the pointer can point to any address in one of the dylib's 1084 // segments, but in practice ld64 seems to set it to point to the header, 1085 // so that's what's implemented here. 1086 addHeaderSymbol("___dso_handle"); 1087 } 1088 1089 template MachHeaderSection *macho::makeMachHeaderSection<LP64>(); 1090 template MachHeaderSection *macho::makeMachHeaderSection<ILP32>(); 1091 template SymtabSection *macho::makeSymtabSection<LP64>(StringTableSection &); 1092 template SymtabSection *macho::makeSymtabSection<ILP32>(StringTableSection &); 1093