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, section_names::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, section_names::stubHelper) { 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 = section_names::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, section_names::lazySymbolPtr) { 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 assert(defined->isExternal() && "invalid input file"); 590 return false; 591 } 592 // TODO: Is this a performance bottleneck? If a build has mostly 593 // global symbols in the input but uses -exported_symbols to filter 594 // out most of them, then it would be better to set the value of 595 // privateExtern at parse time instead of calling 596 // exportedSymbols.match() more than once. 597 // 598 // Measurements show that symbol ordering (which again looks up 599 // every symbol in a hashmap) is the biggest bottleneck when linking 600 // chromium_framework, so this will likely be worth optimizing. 601 return config->exportedSymbols.empty() 602 ? !config->unexportedSymbols.match(defined->getName()) 603 : config->exportedSymbols.match(defined->getName()); 604 } 605 606 void ExportSection::finalizeContents() { 607 trieBuilder.setImageBase(in.header->addr); 608 for (const Symbol *sym : symtab->getSymbols()) { 609 if (const auto *defined = dyn_cast<Defined>(sym)) { 610 validateExportSymbol(defined); 611 if (!shouldExportSymbol(defined)) 612 continue; 613 trieBuilder.addSymbol(*defined); 614 hasWeakSymbol = hasWeakSymbol || sym->isWeakDef(); 615 } 616 } 617 size = trieBuilder.build(); 618 } 619 620 void ExportSection::writeTo(uint8_t *buf) const { trieBuilder.writeTo(buf); } 621 622 FunctionStartsSection::FunctionStartsSection() 623 : LinkEditSection(segment_names::linkEdit, section_names::functionStarts) {} 624 625 void FunctionStartsSection::finalizeContents() { 626 raw_svector_ostream os{contents}; 627 uint64_t addr = in.header->addr; 628 for (const Symbol *sym : symtab->getSymbols()) { 629 if (const auto *defined = dyn_cast<Defined>(sym)) { 630 if (!defined->isec || !isCodeSection(defined->isec)) 631 continue; 632 // TODO: Add support for thumbs, in that case 633 // the lowest bit of nextAddr needs to be set to 1. 634 uint64_t nextAddr = defined->getVA(); 635 uint64_t delta = nextAddr - addr; 636 if (delta == 0) 637 continue; 638 encodeULEB128(delta, os); 639 addr = nextAddr; 640 } 641 } 642 os << '\0'; 643 } 644 645 void FunctionStartsSection::writeTo(uint8_t *buf) const { 646 memcpy(buf, contents.data(), contents.size()); 647 } 648 649 SymtabSection::SymtabSection(StringTableSection &stringTableSection) 650 : LinkEditSection(segment_names::linkEdit, section_names::symbolTable), 651 stringTableSection(stringTableSection) {} 652 653 void SymtabSection::emitBeginSourceStab(DWARFUnit *compileUnit) { 654 StabsEntry stab(N_SO); 655 SmallString<261> dir(compileUnit->getCompilationDir()); 656 StringRef sep = sys::path::get_separator(); 657 // We don't use `path::append` here because we want an empty `dir` to result 658 // in an absolute path. `append` would give us a relative path for that case. 659 if (!dir.endswith(sep)) 660 dir += sep; 661 stab.strx = stringTableSection.addString( 662 saver.save(dir + compileUnit->getUnitDIE().getShortName())); 663 stabs.emplace_back(std::move(stab)); 664 } 665 666 void SymtabSection::emitEndSourceStab() { 667 StabsEntry stab(N_SO); 668 stab.sect = 1; 669 stabs.emplace_back(std::move(stab)); 670 } 671 672 void SymtabSection::emitObjectFileStab(ObjFile *file) { 673 StabsEntry stab(N_OSO); 674 stab.sect = target->cpuSubtype; 675 SmallString<261> path(!file->archiveName.empty() ? file->archiveName 676 : file->getName()); 677 std::error_code ec = sys::fs::make_absolute(path); 678 if (ec) 679 fatal("failed to get absolute path for " + path); 680 681 if (!file->archiveName.empty()) 682 path.append({"(", file->getName(), ")"}); 683 684 stab.strx = stringTableSection.addString(saver.save(path.str())); 685 stab.desc = 1; 686 stab.value = file->modTime; 687 stabs.emplace_back(std::move(stab)); 688 } 689 690 void SymtabSection::emitEndFunStab(Defined *defined) { 691 StabsEntry stab(N_FUN); 692 stab.value = defined->size; 693 stabs.emplace_back(std::move(stab)); 694 } 695 696 void SymtabSection::emitStabs() { 697 for (const std::string &s : config->astPaths) { 698 StabsEntry astStab(N_AST); 699 astStab.strx = stringTableSection.addString(s); 700 stabs.emplace_back(std::move(astStab)); 701 } 702 703 std::vector<Defined *> symbolsNeedingStabs; 704 for (const SymtabEntry &entry : 705 concat<SymtabEntry>(localSymbols, externalSymbols)) { 706 Symbol *sym = entry.sym; 707 if (auto *defined = dyn_cast<Defined>(sym)) { 708 if (defined->isAbsolute()) 709 continue; 710 InputSection *isec = defined->isec; 711 ObjFile *file = dyn_cast_or_null<ObjFile>(isec->file); 712 if (!file || !file->compileUnit) 713 continue; 714 symbolsNeedingStabs.push_back(defined); 715 } 716 } 717 718 llvm::stable_sort(symbolsNeedingStabs, [&](Defined *a, Defined *b) { 719 return a->isec->file->id < b->isec->file->id; 720 }); 721 722 // Emit STABS symbols so that dsymutil and/or the debugger can map address 723 // regions in the final binary to the source and object files from which they 724 // originated. 725 InputFile *lastFile = nullptr; 726 for (Defined *defined : symbolsNeedingStabs) { 727 InputSection *isec = defined->isec; 728 ObjFile *file = cast<ObjFile>(isec->file); 729 730 if (lastFile == nullptr || lastFile != file) { 731 if (lastFile != nullptr) 732 emitEndSourceStab(); 733 lastFile = file; 734 735 emitBeginSourceStab(file->compileUnit); 736 emitObjectFileStab(file); 737 } 738 739 StabsEntry symStab; 740 symStab.sect = defined->isec->parent->index; 741 symStab.strx = stringTableSection.addString(defined->getName()); 742 symStab.value = defined->getVA(); 743 744 if (isCodeSection(isec)) { 745 symStab.type = N_FUN; 746 stabs.emplace_back(std::move(symStab)); 747 emitEndFunStab(defined); 748 } else { 749 symStab.type = defined->isExternal() ? N_GSYM : N_STSYM; 750 stabs.emplace_back(std::move(symStab)); 751 } 752 } 753 754 if (!stabs.empty()) 755 emitEndSourceStab(); 756 } 757 758 void SymtabSection::finalizeContents() { 759 auto addSymbol = [&](std::vector<SymtabEntry> &symbols, Symbol *sym) { 760 uint32_t strx = stringTableSection.addString(sym->getName()); 761 symbols.push_back({sym, strx}); 762 }; 763 764 // Local symbols aren't in the SymbolTable, so we walk the list of object 765 // files to gather them. 766 for (const InputFile *file : inputFiles) { 767 if (auto *objFile = dyn_cast<ObjFile>(file)) { 768 for (Symbol *sym : objFile->symbols) { 769 if (sym == nullptr) 770 continue; 771 // TODO: when we implement -dead_strip, we should filter out symbols 772 // that belong to dead sections. 773 if (auto *defined = dyn_cast<Defined>(sym)) { 774 if (!defined->isExternal()) { 775 StringRef name = defined->getName(); 776 if (!name.startswith("l") && !name.startswith("L")) 777 addSymbol(localSymbols, sym); 778 } 779 } 780 } 781 } 782 } 783 784 // __dyld_private is a local symbol too. It's linker-created and doesn't 785 // exist in any object file. 786 if (Defined *dyldPrivate = in.stubHelper->dyldPrivate) 787 addSymbol(localSymbols, dyldPrivate); 788 789 for (Symbol *sym : symtab->getSymbols()) { 790 if (auto *defined = dyn_cast<Defined>(sym)) { 791 if (!defined->includeInSymtab) 792 continue; 793 assert(defined->isExternal()); 794 addSymbol(externalSymbols, defined); 795 } else if (auto *dysym = dyn_cast<DylibSymbol>(sym)) { 796 if (dysym->isReferenced()) 797 addSymbol(undefinedSymbols, sym); 798 } 799 } 800 801 emitStabs(); 802 uint32_t symtabIndex = stabs.size(); 803 for (const SymtabEntry &entry : 804 concat<SymtabEntry>(localSymbols, externalSymbols, undefinedSymbols)) { 805 entry.sym->symtabIndex = symtabIndex++; 806 } 807 } 808 809 uint32_t SymtabSection::getNumSymbols() const { 810 return stabs.size() + localSymbols.size() + externalSymbols.size() + 811 undefinedSymbols.size(); 812 } 813 814 // This serves to hide (type-erase) the template parameter from SymtabSection. 815 template <class LP> class SymtabSectionImpl : public SymtabSection { 816 public: 817 SymtabSectionImpl(StringTableSection &stringTableSection) 818 : SymtabSection(stringTableSection) {} 819 uint64_t getRawSize() const override; 820 void writeTo(uint8_t *buf) const override; 821 }; 822 823 template <class LP> uint64_t SymtabSectionImpl<LP>::getRawSize() const { 824 return getNumSymbols() * sizeof(typename LP::nlist); 825 } 826 827 template <class LP> void SymtabSectionImpl<LP>::writeTo(uint8_t *buf) const { 828 auto *nList = reinterpret_cast<typename LP::nlist *>(buf); 829 // Emit the stabs entries before the "real" symbols. We cannot emit them 830 // after as that would render Symbol::symtabIndex inaccurate. 831 for (const StabsEntry &entry : stabs) { 832 nList->n_strx = entry.strx; 833 nList->n_type = entry.type; 834 nList->n_sect = entry.sect; 835 nList->n_desc = entry.desc; 836 nList->n_value = entry.value; 837 ++nList; 838 } 839 840 for (const SymtabEntry &entry : concat<const SymtabEntry>( 841 localSymbols, externalSymbols, undefinedSymbols)) { 842 nList->n_strx = entry.strx; 843 // TODO populate n_desc with more flags 844 if (auto *defined = dyn_cast<Defined>(entry.sym)) { 845 uint8_t scope = 0; 846 if (!shouldExportSymbol(defined)) { 847 // Private external -- dylib scoped symbol. 848 // Promote to non-external at link time. 849 scope = N_PEXT; 850 } else if (defined->isExternal()) { 851 // Normal global symbol. 852 scope = N_EXT; 853 } else { 854 // TU-local symbol from localSymbols. 855 scope = 0; 856 } 857 858 if (defined->isAbsolute()) { 859 nList->n_type = scope | N_ABS; 860 nList->n_sect = NO_SECT; 861 nList->n_value = defined->value; 862 } else { 863 nList->n_type = scope | N_SECT; 864 nList->n_sect = defined->isec->parent->index; 865 // For the N_SECT symbol type, n_value is the address of the symbol 866 nList->n_value = defined->getVA(); 867 } 868 nList->n_desc |= defined->isExternalWeakDef() ? N_WEAK_DEF : 0; 869 } else if (auto *dysym = dyn_cast<DylibSymbol>(entry.sym)) { 870 uint16_t n_desc = nList->n_desc; 871 int16_t ordinal = ordinalForDylibSymbol(*dysym); 872 if (ordinal == BIND_SPECIAL_DYLIB_FLAT_LOOKUP) 873 SET_LIBRARY_ORDINAL(n_desc, DYNAMIC_LOOKUP_ORDINAL); 874 else if (ordinal == BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE) 875 SET_LIBRARY_ORDINAL(n_desc, EXECUTABLE_ORDINAL); 876 else { 877 assert(ordinal > 0); 878 SET_LIBRARY_ORDINAL(n_desc, static_cast<uint8_t>(ordinal)); 879 } 880 881 nList->n_type = N_EXT; 882 n_desc |= dysym->isWeakDef() ? N_WEAK_DEF : 0; 883 n_desc |= dysym->isWeakRef() ? N_WEAK_REF : 0; 884 nList->n_desc = n_desc; 885 } 886 ++nList; 887 } 888 } 889 890 template <class LP> 891 SymtabSection * 892 macho::makeSymtabSection(StringTableSection &stringTableSection) { 893 return make<SymtabSectionImpl<LP>>(stringTableSection); 894 } 895 896 IndirectSymtabSection::IndirectSymtabSection() 897 : LinkEditSection(segment_names::linkEdit, 898 section_names::indirectSymbolTable) {} 899 900 uint32_t IndirectSymtabSection::getNumSymbols() const { 901 return in.got->getEntries().size() + in.tlvPointers->getEntries().size() + 902 in.stubs->getEntries().size(); 903 } 904 905 bool IndirectSymtabSection::isNeeded() const { 906 return in.got->isNeeded() || in.tlvPointers->isNeeded() || 907 in.stubs->isNeeded(); 908 } 909 910 void IndirectSymtabSection::finalizeContents() { 911 uint32_t off = 0; 912 in.got->reserved1 = off; 913 off += in.got->getEntries().size(); 914 in.tlvPointers->reserved1 = off; 915 off += in.tlvPointers->getEntries().size(); 916 // There is a 1:1 correspondence between stubs and LazyPointerSection 917 // entries, so they can share the same sub-array in the table. 918 in.stubs->reserved1 = in.lazyPointers->reserved1 = off; 919 } 920 921 static uint32_t indirectValue(const Symbol *sym) { 922 return sym->symtabIndex != UINT32_MAX ? sym->symtabIndex 923 : INDIRECT_SYMBOL_LOCAL; 924 } 925 926 void IndirectSymtabSection::writeTo(uint8_t *buf) const { 927 uint32_t off = 0; 928 for (const Symbol *sym : in.got->getEntries()) { 929 write32le(buf + off * sizeof(uint32_t), indirectValue(sym)); 930 ++off; 931 } 932 for (const Symbol *sym : in.tlvPointers->getEntries()) { 933 write32le(buf + off * sizeof(uint32_t), indirectValue(sym)); 934 ++off; 935 } 936 for (const Symbol *sym : in.stubs->getEntries()) { 937 write32le(buf + off * sizeof(uint32_t), indirectValue(sym)); 938 ++off; 939 } 940 } 941 942 StringTableSection::StringTableSection() 943 : LinkEditSection(segment_names::linkEdit, section_names::stringTable) {} 944 945 uint32_t StringTableSection::addString(StringRef str) { 946 uint32_t strx = size; 947 strings.push_back(str); // TODO: consider deduplicating strings 948 size += str.size() + 1; // account for null terminator 949 return strx; 950 } 951 952 void StringTableSection::writeTo(uint8_t *buf) const { 953 uint32_t off = 0; 954 for (StringRef str : strings) { 955 memcpy(buf + off, str.data(), str.size()); 956 off += str.size() + 1; // account for null terminator 957 } 958 } 959 960 CodeSignatureSection::CodeSignatureSection() 961 : LinkEditSection(segment_names::linkEdit, section_names::codeSignature) { 962 align = 16; // required by libstuff 963 fileName = config->outputFile; 964 size_t slashIndex = fileName.rfind("/"); 965 if (slashIndex != std::string::npos) 966 fileName = fileName.drop_front(slashIndex + 1); 967 allHeadersSize = alignTo<16>(fixedHeadersSize + fileName.size() + 1); 968 fileNamePad = allHeadersSize - fixedHeadersSize - fileName.size(); 969 } 970 971 uint32_t CodeSignatureSection::getBlockCount() const { 972 return (fileOff + blockSize - 1) / blockSize; 973 } 974 975 uint64_t CodeSignatureSection::getRawSize() const { 976 return allHeadersSize + getBlockCount() * hashSize; 977 } 978 979 void CodeSignatureSection::writeHashes(uint8_t *buf) const { 980 uint8_t *code = buf; 981 uint8_t *codeEnd = buf + fileOff; 982 uint8_t *hashes = codeEnd + allHeadersSize; 983 while (code < codeEnd) { 984 StringRef block(reinterpret_cast<char *>(code), 985 std::min(codeEnd - code, static_cast<ssize_t>(blockSize))); 986 SHA256 hasher; 987 hasher.update(block); 988 StringRef hash = hasher.final(); 989 assert(hash.size() == hashSize); 990 memcpy(hashes, hash.data(), hashSize); 991 code += blockSize; 992 hashes += hashSize; 993 } 994 #if defined(__APPLE__) 995 // This is macOS-specific work-around and makes no sense for any 996 // other host OS. See https://openradar.appspot.com/FB8914231 997 // 998 // The macOS kernel maintains a signature-verification cache to 999 // quickly validate applications at time of execve(2). The trouble 1000 // is that for the kernel creates the cache entry at the time of the 1001 // mmap(2) call, before we have a chance to write either the code to 1002 // sign or the signature header+hashes. The fix is to invalidate 1003 // all cached data associated with the output file, thus discarding 1004 // the bogus prematurely-cached signature. 1005 msync(buf, fileOff + getSize(), MS_INVALIDATE); 1006 #endif 1007 } 1008 1009 void CodeSignatureSection::writeTo(uint8_t *buf) const { 1010 uint32_t signatureSize = static_cast<uint32_t>(getSize()); 1011 auto *superBlob = reinterpret_cast<CS_SuperBlob *>(buf); 1012 write32be(&superBlob->magic, CSMAGIC_EMBEDDED_SIGNATURE); 1013 write32be(&superBlob->length, signatureSize); 1014 write32be(&superBlob->count, 1); 1015 auto *blobIndex = reinterpret_cast<CS_BlobIndex *>(&superBlob[1]); 1016 write32be(&blobIndex->type, CSSLOT_CODEDIRECTORY); 1017 write32be(&blobIndex->offset, blobHeadersSize); 1018 auto *codeDirectory = 1019 reinterpret_cast<CS_CodeDirectory *>(buf + blobHeadersSize); 1020 write32be(&codeDirectory->magic, CSMAGIC_CODEDIRECTORY); 1021 write32be(&codeDirectory->length, signatureSize - blobHeadersSize); 1022 write32be(&codeDirectory->version, CS_SUPPORTSEXECSEG); 1023 write32be(&codeDirectory->flags, CS_ADHOC | CS_LINKER_SIGNED); 1024 write32be(&codeDirectory->hashOffset, 1025 sizeof(CS_CodeDirectory) + fileName.size() + fileNamePad); 1026 write32be(&codeDirectory->identOffset, sizeof(CS_CodeDirectory)); 1027 codeDirectory->nSpecialSlots = 0; 1028 write32be(&codeDirectory->nCodeSlots, getBlockCount()); 1029 write32be(&codeDirectory->codeLimit, fileOff); 1030 codeDirectory->hashSize = static_cast<uint8_t>(hashSize); 1031 codeDirectory->hashType = kSecCodeSignatureHashSHA256; 1032 codeDirectory->platform = 0; 1033 codeDirectory->pageSize = blockSizeShift; 1034 codeDirectory->spare2 = 0; 1035 codeDirectory->scatterOffset = 0; 1036 codeDirectory->teamOffset = 0; 1037 codeDirectory->spare3 = 0; 1038 codeDirectory->codeLimit64 = 0; 1039 OutputSegment *textSeg = getOrCreateOutputSegment(segment_names::text); 1040 write64be(&codeDirectory->execSegBase, textSeg->fileOff); 1041 write64be(&codeDirectory->execSegLimit, textSeg->fileSize); 1042 write64be(&codeDirectory->execSegFlags, 1043 config->outputType == MH_EXECUTE ? CS_EXECSEG_MAIN_BINARY : 0); 1044 auto *id = reinterpret_cast<char *>(&codeDirectory[1]); 1045 memcpy(id, fileName.begin(), fileName.size()); 1046 memset(id + fileName.size(), 0, fileNamePad); 1047 } 1048 1049 BitcodeBundleSection::BitcodeBundleSection() 1050 : SyntheticSection(segment_names::llvm, section_names::bitcodeBundle) {} 1051 1052 class ErrorCodeWrapper { 1053 public: 1054 explicit ErrorCodeWrapper(std::error_code ec) : errorCode(ec.value()) {} 1055 explicit ErrorCodeWrapper(int ec) : errorCode(ec) {} 1056 operator int() const { return errorCode; } 1057 1058 private: 1059 int errorCode; 1060 }; 1061 1062 #define CHECK_EC(exp) \ 1063 do { \ 1064 ErrorCodeWrapper ec(exp); \ 1065 if (ec) \ 1066 fatal(Twine("operation failed with error code ") + Twine(ec) + ": " + \ 1067 #exp); \ 1068 } while (0); 1069 1070 void BitcodeBundleSection::finalize() { 1071 #ifdef HAVE_LIBXAR 1072 using namespace llvm::sys::fs; 1073 CHECK_EC(createTemporaryFile("bitcode-bundle", "xar", xarPath)); 1074 1075 xar_t xar(xar_open(xarPath.data(), O_RDWR)); 1076 if (!xar) 1077 fatal("failed to open XAR temporary file at " + xarPath); 1078 CHECK_EC(xar_opt_set(xar, XAR_OPT_COMPRESSION, XAR_OPT_VAL_NONE)); 1079 // FIXME: add more data to XAR 1080 CHECK_EC(xar_close(xar)); 1081 1082 file_size(xarPath, xarSize); 1083 #endif // defined(HAVE_LIBXAR) 1084 } 1085 1086 void BitcodeBundleSection::writeTo(uint8_t *buf) const { 1087 using namespace llvm::sys::fs; 1088 file_t handle = 1089 CHECK(openNativeFile(xarPath, CD_OpenExisting, FA_Read, OF_None), 1090 "failed to open XAR file"); 1091 std::error_code ec; 1092 mapped_file_region xarMap(handle, mapped_file_region::mapmode::readonly, 1093 xarSize, 0, ec); 1094 if (ec) 1095 fatal("failed to map XAR file"); 1096 memcpy(buf, xarMap.const_data(), xarSize); 1097 1098 closeFile(handle); 1099 remove(xarPath); 1100 } 1101 1102 void macho::createSyntheticSymbols() { 1103 auto addHeaderSymbol = [](const char *name) { 1104 symtab->addSynthetic(name, in.header->isec, 0, 1105 /*privateExtern=*/true, 1106 /*includeInSymtab=*/false); 1107 }; 1108 1109 switch (config->outputType) { 1110 // FIXME: Assign the right address value for these symbols 1111 // (rather than 0). But we need to do that after assignAddresses(). 1112 case MH_EXECUTE: 1113 // If linking PIE, __mh_execute_header is a defined symbol in 1114 // __TEXT, __text) 1115 // Otherwise, it's an absolute symbol. 1116 if (config->isPic) 1117 symtab->addSynthetic("__mh_execute_header", in.header->isec, 0, 1118 /*privateExtern=*/false, 1119 /*includeInSymtab=*/true); 1120 else 1121 symtab->addSynthetic("__mh_execute_header", 1122 /*isec*/ nullptr, 0, 1123 /*privateExtern=*/false, 1124 /*includeInSymtab=*/true); 1125 break; 1126 1127 // The following symbols are N_SECT symbols, even though the header is not 1128 // part of any section and that they are private to the bundle/dylib/object 1129 // they are part of. 1130 case MH_BUNDLE: 1131 addHeaderSymbol("__mh_bundle_header"); 1132 break; 1133 case MH_DYLIB: 1134 addHeaderSymbol("__mh_dylib_header"); 1135 break; 1136 case MH_DYLINKER: 1137 addHeaderSymbol("__mh_dylinker_header"); 1138 break; 1139 case MH_OBJECT: 1140 addHeaderSymbol("__mh_object_header"); 1141 break; 1142 default: 1143 llvm_unreachable("unexpected outputType"); 1144 break; 1145 } 1146 1147 // The Itanium C++ ABI requires dylibs to pass a pointer to __cxa_atexit 1148 // which does e.g. cleanup of static global variables. The ABI document 1149 // says that the pointer can point to any address in one of the dylib's 1150 // segments, but in practice ld64 seems to set it to point to the header, 1151 // so that's what's implemented here. 1152 addHeaderSymbol("___dso_handle"); 1153 } 1154 1155 template MachHeaderSection *macho::makeMachHeaderSection<LP64>(); 1156 template MachHeaderSection *macho::makeMachHeaderSection<ILP32>(); 1157 template SymtabSection *macho::makeSymtabSection<LP64>(StringTableSection &); 1158 template SymtabSection *macho::makeSymtabSection<ILP32>(StringTableSection &); 1159