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