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