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 "ConcatOutputSection.h" 11 #include "Config.h" 12 #include "ExportTrie.h" 13 #include "InputFiles.h" 14 #include "MachOStructs.h" 15 #include "OutputSegment.h" 16 #include "SymbolTable.h" 17 #include "Symbols.h" 18 19 #include "lld/Common/CommonLinkerContext.h" 20 #include "llvm/ADT/STLExtras.h" 21 #include "llvm/Config/llvm-config.h" 22 #include "llvm/Support/EndianStream.h" 23 #include "llvm/Support/FileSystem.h" 24 #include "llvm/Support/LEB128.h" 25 #include "llvm/Support/Parallel.h" 26 #include "llvm/Support/Path.h" 27 28 #if defined(__APPLE__) 29 #include <sys/mman.h> 30 31 #define COMMON_DIGEST_FOR_OPENSSL 32 #include <CommonCrypto/CommonDigest.h> 33 #else 34 #include "llvm/Support/SHA256.h" 35 #endif 36 37 #ifdef LLVM_HAVE_LIBXAR 38 #include <fcntl.h> 39 extern "C" { 40 #include <xar/xar.h> 41 } 42 #endif 43 44 using namespace llvm; 45 using namespace llvm::MachO; 46 using namespace llvm::support; 47 using namespace llvm::support::endian; 48 using namespace lld; 49 using namespace lld::macho; 50 51 // Reads `len` bytes at data and writes the 32-byte SHA256 checksum to `output`. 52 static void sha256(const uint8_t *data, size_t len, uint8_t *output) { 53 #if defined(__APPLE__) 54 // FIXME: Make LLVM's SHA256 faster and use it unconditionally. See PR56121 55 // for some notes on this. 56 CC_SHA256(data, len, output); 57 #else 58 ArrayRef<uint8_t> block(data, len); 59 std::array<uint8_t, 32> hash = SHA256::hash(block); 60 assert(hash.size() == CodeSignatureSection::hashSize); 61 memcpy(output, hash.data(), hash.size()); 62 #endif 63 } 64 65 InStruct macho::in; 66 std::vector<SyntheticSection *> macho::syntheticSections; 67 68 SyntheticSection::SyntheticSection(const char *segname, const char *name) 69 : OutputSection(SyntheticKind, name) { 70 std::tie(this->segname, this->name) = maybeRenameSection({segname, name}); 71 isec = makeSyntheticInputSection(segname, name); 72 isec->parent = this; 73 syntheticSections.push_back(this); 74 } 75 76 // dyld3's MachOLoaded::getSlide() assumes that the __TEXT segment starts 77 // from the beginning of the file (i.e. the header). 78 MachHeaderSection::MachHeaderSection() 79 : SyntheticSection(segment_names::text, section_names::header) { 80 // XXX: This is a hack. (See D97007) 81 // Setting the index to 1 to pretend that this section is the text 82 // section. 83 index = 1; 84 isec->isFinal = true; 85 } 86 87 void MachHeaderSection::addLoadCommand(LoadCommand *lc) { 88 loadCommands.push_back(lc); 89 sizeOfCmds += lc->getSize(); 90 } 91 92 uint64_t MachHeaderSection::getSize() const { 93 uint64_t size = target->headerSize + sizeOfCmds + config->headerPad; 94 // If we are emitting an encryptable binary, our load commands must have a 95 // separate (non-encrypted) page to themselves. 96 if (config->emitEncryptionInfo) 97 size = alignTo(size, target->getPageSize()); 98 return size; 99 } 100 101 static uint32_t cpuSubtype() { 102 uint32_t subtype = target->cpuSubtype; 103 104 if (config->outputType == MH_EXECUTE && !config->staticLink && 105 target->cpuSubtype == CPU_SUBTYPE_X86_64_ALL && 106 config->platform() == PLATFORM_MACOS && 107 config->platformInfo.minimum >= VersionTuple(10, 5)) 108 subtype |= CPU_SUBTYPE_LIB64; 109 110 return subtype; 111 } 112 113 void MachHeaderSection::writeTo(uint8_t *buf) const { 114 auto *hdr = reinterpret_cast<mach_header *>(buf); 115 hdr->magic = target->magic; 116 hdr->cputype = target->cpuType; 117 hdr->cpusubtype = cpuSubtype(); 118 hdr->filetype = config->outputType; 119 hdr->ncmds = loadCommands.size(); 120 hdr->sizeofcmds = sizeOfCmds; 121 hdr->flags = MH_DYLDLINK; 122 123 if (config->namespaceKind == NamespaceKind::twolevel) 124 hdr->flags |= MH_NOUNDEFS | MH_TWOLEVEL; 125 126 if (config->outputType == MH_DYLIB && !config->hasReexports) 127 hdr->flags |= MH_NO_REEXPORTED_DYLIBS; 128 129 if (config->markDeadStrippableDylib) 130 hdr->flags |= MH_DEAD_STRIPPABLE_DYLIB; 131 132 if (config->outputType == MH_EXECUTE && config->isPic) 133 hdr->flags |= MH_PIE; 134 135 if (config->outputType == MH_DYLIB && config->applicationExtension) 136 hdr->flags |= MH_APP_EXTENSION_SAFE; 137 138 if (in.exports->hasWeakSymbol || in.weakBinding->hasNonWeakDefinition()) 139 hdr->flags |= MH_WEAK_DEFINES; 140 141 if (in.exports->hasWeakSymbol || in.weakBinding->hasEntry()) 142 hdr->flags |= MH_BINDS_TO_WEAK; 143 144 for (const OutputSegment *seg : outputSegments) { 145 for (const OutputSection *osec : seg->getSections()) { 146 if (isThreadLocalVariables(osec->flags)) { 147 hdr->flags |= MH_HAS_TLV_DESCRIPTORS; 148 break; 149 } 150 } 151 } 152 153 uint8_t *p = reinterpret_cast<uint8_t *>(hdr) + target->headerSize; 154 for (const LoadCommand *lc : loadCommands) { 155 lc->writeTo(p); 156 p += lc->getSize(); 157 } 158 } 159 160 PageZeroSection::PageZeroSection() 161 : SyntheticSection(segment_names::pageZero, section_names::pageZero) {} 162 163 RebaseSection::RebaseSection() 164 : LinkEditSection(segment_names::linkEdit, section_names::rebase) {} 165 166 namespace { 167 struct Rebase { 168 OutputSegment *segment = nullptr; 169 uint64_t offset = 0; 170 uint64_t consecutiveCount = 0; 171 }; 172 } // namespace 173 174 // Rebase opcodes allow us to describe a contiguous sequence of rebase location 175 // using a single DO_REBASE opcode. To take advantage of it, we delay emitting 176 // `DO_REBASE` until we have reached the end of a contiguous sequence. 177 static void encodeDoRebase(Rebase &rebase, raw_svector_ostream &os) { 178 assert(rebase.consecutiveCount != 0); 179 if (rebase.consecutiveCount <= REBASE_IMMEDIATE_MASK) { 180 os << static_cast<uint8_t>(REBASE_OPCODE_DO_REBASE_IMM_TIMES | 181 rebase.consecutiveCount); 182 } else { 183 os << static_cast<uint8_t>(REBASE_OPCODE_DO_REBASE_ULEB_TIMES); 184 encodeULEB128(rebase.consecutiveCount, os); 185 } 186 rebase.consecutiveCount = 0; 187 } 188 189 static void encodeRebase(const OutputSection *osec, uint64_t outSecOff, 190 Rebase &lastRebase, raw_svector_ostream &os) { 191 OutputSegment *seg = osec->parent; 192 uint64_t offset = osec->getSegmentOffset() + outSecOff; 193 if (lastRebase.segment != seg || lastRebase.offset != offset) { 194 if (lastRebase.consecutiveCount != 0) 195 encodeDoRebase(lastRebase, os); 196 197 if (lastRebase.segment != seg) { 198 os << static_cast<uint8_t>(REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB | 199 seg->index); 200 encodeULEB128(offset, os); 201 lastRebase.segment = seg; 202 lastRebase.offset = offset; 203 } else { 204 assert(lastRebase.offset != offset); 205 uint64_t delta = offset - lastRebase.offset; 206 // For unknown reasons, ld64 checks if the scaled offset is strictly less 207 // than REBASE_IMMEDIATE_MASK instead of allowing equality. We match this 208 // behavior as a precaution. 209 if ((delta % target->wordSize == 0) && 210 (delta / target->wordSize < REBASE_IMMEDIATE_MASK)) { 211 os << static_cast<uint8_t>(REBASE_OPCODE_ADD_ADDR_IMM_SCALED | 212 (delta / target->wordSize)); 213 } else { 214 os << static_cast<uint8_t>(REBASE_OPCODE_ADD_ADDR_ULEB); 215 encodeULEB128(delta, os); 216 } 217 lastRebase.offset = offset; 218 } 219 } 220 ++lastRebase.consecutiveCount; 221 // DO_REBASE causes dyld to both perform the binding and increment the offset 222 lastRebase.offset += target->wordSize; 223 } 224 225 void RebaseSection::finalizeContents() { 226 if (locations.empty()) 227 return; 228 229 raw_svector_ostream os{contents}; 230 Rebase lastRebase; 231 232 os << static_cast<uint8_t>(REBASE_OPCODE_SET_TYPE_IMM | REBASE_TYPE_POINTER); 233 234 llvm::sort(locations, [](const Location &a, const Location &b) { 235 return a.isec->getVA(a.offset) < b.isec->getVA(b.offset); 236 }); 237 for (const Location &loc : locations) 238 encodeRebase(loc.isec->parent, loc.isec->getOffset(loc.offset), lastRebase, 239 os); 240 if (lastRebase.consecutiveCount != 0) 241 encodeDoRebase(lastRebase, os); 242 243 os << static_cast<uint8_t>(REBASE_OPCODE_DONE); 244 } 245 246 void RebaseSection::writeTo(uint8_t *buf) const { 247 memcpy(buf, contents.data(), contents.size()); 248 } 249 250 NonLazyPointerSectionBase::NonLazyPointerSectionBase(const char *segname, 251 const char *name) 252 : SyntheticSection(segname, name) { 253 align = target->wordSize; 254 } 255 256 void macho::addNonLazyBindingEntries(const Symbol *sym, 257 const InputSection *isec, uint64_t offset, 258 int64_t addend) { 259 if (const auto *dysym = dyn_cast<DylibSymbol>(sym)) { 260 in.binding->addEntry(dysym, isec, offset, addend); 261 if (dysym->isWeakDef()) 262 in.weakBinding->addEntry(sym, isec, offset, addend); 263 } else if (const auto *defined = dyn_cast<Defined>(sym)) { 264 in.rebase->addEntry(isec, offset); 265 if (defined->isExternalWeakDef()) 266 in.weakBinding->addEntry(sym, isec, offset, addend); 267 else if (defined->interposable) 268 in.binding->addEntry(sym, isec, offset, addend); 269 } else { 270 // Undefined symbols are filtered out in scanRelocations(); we should never 271 // get here 272 llvm_unreachable("cannot bind to an undefined symbol"); 273 } 274 } 275 276 void NonLazyPointerSectionBase::addEntry(Symbol *sym) { 277 if (entries.insert(sym)) { 278 assert(!sym->isInGot()); 279 sym->gotIndex = entries.size() - 1; 280 281 addNonLazyBindingEntries(sym, isec, sym->gotIndex * target->wordSize); 282 } 283 } 284 285 void NonLazyPointerSectionBase::writeTo(uint8_t *buf) const { 286 for (size_t i = 0, n = entries.size(); i < n; ++i) 287 if (auto *defined = dyn_cast<Defined>(entries[i])) 288 write64le(&buf[i * target->wordSize], defined->getVA()); 289 } 290 291 GotSection::GotSection() 292 : NonLazyPointerSectionBase(segment_names::data, section_names::got) { 293 flags = S_NON_LAZY_SYMBOL_POINTERS; 294 } 295 296 TlvPointerSection::TlvPointerSection() 297 : NonLazyPointerSectionBase(segment_names::data, 298 section_names::threadPtrs) { 299 flags = S_THREAD_LOCAL_VARIABLE_POINTERS; 300 } 301 302 BindingSection::BindingSection() 303 : LinkEditSection(segment_names::linkEdit, section_names::binding) {} 304 305 namespace { 306 struct Binding { 307 OutputSegment *segment = nullptr; 308 uint64_t offset = 0; 309 int64_t addend = 0; 310 }; 311 struct BindIR { 312 // Default value of 0xF0 is not valid opcode and should make the program 313 // scream instead of accidentally writing "valid" values. 314 uint8_t opcode = 0xF0; 315 uint64_t data = 0; 316 uint64_t consecutiveCount = 0; 317 }; 318 } // namespace 319 320 // Encode a sequence of opcodes that tell dyld to write the address of symbol + 321 // addend at osec->addr + outSecOff. 322 // 323 // The bind opcode "interpreter" remembers the values of each binding field, so 324 // we only need to encode the differences between bindings. Hence the use of 325 // lastBinding. 326 static void encodeBinding(const OutputSection *osec, uint64_t outSecOff, 327 int64_t addend, Binding &lastBinding, 328 std::vector<BindIR> &opcodes) { 329 OutputSegment *seg = osec->parent; 330 uint64_t offset = osec->getSegmentOffset() + outSecOff; 331 if (lastBinding.segment != seg) { 332 opcodes.push_back( 333 {static_cast<uint8_t>(BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB | 334 seg->index), 335 offset}); 336 lastBinding.segment = seg; 337 lastBinding.offset = offset; 338 } else if (lastBinding.offset != offset) { 339 opcodes.push_back({BIND_OPCODE_ADD_ADDR_ULEB, offset - lastBinding.offset}); 340 lastBinding.offset = offset; 341 } 342 343 if (lastBinding.addend != addend) { 344 opcodes.push_back( 345 {BIND_OPCODE_SET_ADDEND_SLEB, static_cast<uint64_t>(addend)}); 346 lastBinding.addend = addend; 347 } 348 349 opcodes.push_back({BIND_OPCODE_DO_BIND, 0}); 350 // DO_BIND causes dyld to both perform the binding and increment the offset 351 lastBinding.offset += target->wordSize; 352 } 353 354 static void optimizeOpcodes(std::vector<BindIR> &opcodes) { 355 // Pass 1: Combine bind/add pairs 356 size_t i; 357 int pWrite = 0; 358 for (i = 1; i < opcodes.size(); ++i, ++pWrite) { 359 if ((opcodes[i].opcode == BIND_OPCODE_ADD_ADDR_ULEB) && 360 (opcodes[i - 1].opcode == BIND_OPCODE_DO_BIND)) { 361 opcodes[pWrite].opcode = BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB; 362 opcodes[pWrite].data = opcodes[i].data; 363 ++i; 364 } else { 365 opcodes[pWrite] = opcodes[i - 1]; 366 } 367 } 368 if (i == opcodes.size()) 369 opcodes[pWrite] = opcodes[i - 1]; 370 opcodes.resize(pWrite + 1); 371 372 // Pass 2: Compress two or more bind_add opcodes 373 pWrite = 0; 374 for (i = 1; i < opcodes.size(); ++i, ++pWrite) { 375 if ((opcodes[i].opcode == BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB) && 376 (opcodes[i - 1].opcode == BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB) && 377 (opcodes[i].data == opcodes[i - 1].data)) { 378 opcodes[pWrite].opcode = BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB; 379 opcodes[pWrite].consecutiveCount = 2; 380 opcodes[pWrite].data = opcodes[i].data; 381 ++i; 382 while (i < opcodes.size() && 383 (opcodes[i].opcode == BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB) && 384 (opcodes[i].data == opcodes[i - 1].data)) { 385 opcodes[pWrite].consecutiveCount++; 386 ++i; 387 } 388 } else { 389 opcodes[pWrite] = opcodes[i - 1]; 390 } 391 } 392 if (i == opcodes.size()) 393 opcodes[pWrite] = opcodes[i - 1]; 394 opcodes.resize(pWrite + 1); 395 396 // Pass 3: Use immediate encodings 397 // Every binding is the size of one pointer. If the next binding is a 398 // multiple of wordSize away that is within BIND_IMMEDIATE_MASK, the 399 // opcode can be scaled by wordSize into a single byte and dyld will 400 // expand it to the correct address. 401 for (auto &p : opcodes) { 402 // It's unclear why the check needs to be less than BIND_IMMEDIATE_MASK, 403 // but ld64 currently does this. This could be a potential bug, but 404 // for now, perform the same behavior to prevent mysterious bugs. 405 if ((p.opcode == BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB) && 406 ((p.data / target->wordSize) < BIND_IMMEDIATE_MASK) && 407 ((p.data % target->wordSize) == 0)) { 408 p.opcode = BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED; 409 p.data /= target->wordSize; 410 } 411 } 412 } 413 414 static void flushOpcodes(const BindIR &op, raw_svector_ostream &os) { 415 uint8_t opcode = op.opcode & BIND_OPCODE_MASK; 416 switch (opcode) { 417 case BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: 418 case BIND_OPCODE_ADD_ADDR_ULEB: 419 case BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB: 420 os << op.opcode; 421 encodeULEB128(op.data, os); 422 break; 423 case BIND_OPCODE_SET_ADDEND_SLEB: 424 os << op.opcode; 425 encodeSLEB128(static_cast<int64_t>(op.data), os); 426 break; 427 case BIND_OPCODE_DO_BIND: 428 os << op.opcode; 429 break; 430 case BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB: 431 os << op.opcode; 432 encodeULEB128(op.consecutiveCount, os); 433 encodeULEB128(op.data, os); 434 break; 435 case BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED: 436 os << static_cast<uint8_t>(op.opcode | op.data); 437 break; 438 default: 439 llvm_unreachable("cannot bind to an unrecognized symbol"); 440 } 441 } 442 443 // Non-weak bindings need to have their dylib ordinal encoded as well. 444 static int16_t ordinalForDylibSymbol(const DylibSymbol &dysym) { 445 if (config->namespaceKind == NamespaceKind::flat || dysym.isDynamicLookup()) 446 return static_cast<int16_t>(BIND_SPECIAL_DYLIB_FLAT_LOOKUP); 447 assert(dysym.getFile()->isReferenced()); 448 return dysym.getFile()->ordinal; 449 } 450 451 static int16_t ordinalForSymbol(const Symbol &sym) { 452 if (const auto *dysym = dyn_cast<DylibSymbol>(&sym)) 453 return ordinalForDylibSymbol(*dysym); 454 assert(cast<Defined>(&sym)->interposable); 455 return BIND_SPECIAL_DYLIB_FLAT_LOOKUP; 456 } 457 458 static void encodeDylibOrdinal(int16_t ordinal, raw_svector_ostream &os) { 459 if (ordinal <= 0) { 460 os << static_cast<uint8_t>(BIND_OPCODE_SET_DYLIB_SPECIAL_IMM | 461 (ordinal & BIND_IMMEDIATE_MASK)); 462 } else if (ordinal <= BIND_IMMEDIATE_MASK) { 463 os << static_cast<uint8_t>(BIND_OPCODE_SET_DYLIB_ORDINAL_IMM | ordinal); 464 } else { 465 os << static_cast<uint8_t>(BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB); 466 encodeULEB128(ordinal, os); 467 } 468 } 469 470 static void encodeWeakOverride(const Defined *defined, 471 raw_svector_ostream &os) { 472 os << static_cast<uint8_t>(BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM | 473 BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) 474 << defined->getName() << '\0'; 475 } 476 477 // Organize the bindings so we can encoded them with fewer opcodes. 478 // 479 // First, all bindings for a given symbol should be grouped together. 480 // BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM is the largest opcode (since it 481 // has an associated symbol string), so we only want to emit it once per symbol. 482 // 483 // Within each group, we sort the bindings by address. Since bindings are 484 // delta-encoded, sorting them allows for a more compact result. Note that 485 // sorting by address alone ensures that bindings for the same segment / section 486 // are located together, minimizing the number of times we have to emit 487 // BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB. 488 // 489 // Finally, we sort the symbols by the address of their first binding, again 490 // to facilitate the delta-encoding process. 491 template <class Sym> 492 std::vector<std::pair<const Sym *, std::vector<BindingEntry>>> 493 sortBindings(const BindingsMap<const Sym *> &bindingsMap) { 494 std::vector<std::pair<const Sym *, std::vector<BindingEntry>>> bindingsVec( 495 bindingsMap.begin(), bindingsMap.end()); 496 for (auto &p : bindingsVec) { 497 std::vector<BindingEntry> &bindings = p.second; 498 llvm::sort(bindings, [](const BindingEntry &a, const BindingEntry &b) { 499 return a.target.getVA() < b.target.getVA(); 500 }); 501 } 502 llvm::sort(bindingsVec, [](const auto &a, const auto &b) { 503 return a.second[0].target.getVA() < b.second[0].target.getVA(); 504 }); 505 return bindingsVec; 506 } 507 508 // Emit bind opcodes, which are a stream of byte-sized opcodes that dyld 509 // interprets to update a record with the following fields: 510 // * segment index (of the segment to write the symbol addresses to, typically 511 // the __DATA_CONST segment which contains the GOT) 512 // * offset within the segment, indicating the next location to write a binding 513 // * symbol type 514 // * symbol library ordinal (the index of its library's LC_LOAD_DYLIB command) 515 // * symbol name 516 // * addend 517 // When dyld sees BIND_OPCODE_DO_BIND, it uses the current record state to bind 518 // a symbol in the GOT, and increments the segment offset to point to the next 519 // entry. It does *not* clear the record state after doing the bind, so 520 // subsequent opcodes only need to encode the differences between bindings. 521 void BindingSection::finalizeContents() { 522 raw_svector_ostream os{contents}; 523 Binding lastBinding; 524 int16_t lastOrdinal = 0; 525 526 for (auto &p : sortBindings(bindingsMap)) { 527 const Symbol *sym = p.first; 528 std::vector<BindingEntry> &bindings = p.second; 529 uint8_t flags = BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM; 530 if (sym->isWeakRef()) 531 flags |= BIND_SYMBOL_FLAGS_WEAK_IMPORT; 532 os << flags << sym->getName() << '\0' 533 << static_cast<uint8_t>(BIND_OPCODE_SET_TYPE_IMM | BIND_TYPE_POINTER); 534 int16_t ordinal = ordinalForSymbol(*sym); 535 if (ordinal != lastOrdinal) { 536 encodeDylibOrdinal(ordinal, os); 537 lastOrdinal = ordinal; 538 } 539 std::vector<BindIR> opcodes; 540 for (const BindingEntry &b : bindings) 541 encodeBinding(b.target.isec->parent, 542 b.target.isec->getOffset(b.target.offset), b.addend, 543 lastBinding, opcodes); 544 if (config->optimize > 1) 545 optimizeOpcodes(opcodes); 546 for (const auto &op : opcodes) 547 flushOpcodes(op, os); 548 } 549 if (!bindingsMap.empty()) 550 os << static_cast<uint8_t>(BIND_OPCODE_DONE); 551 } 552 553 void BindingSection::writeTo(uint8_t *buf) const { 554 memcpy(buf, contents.data(), contents.size()); 555 } 556 557 WeakBindingSection::WeakBindingSection() 558 : LinkEditSection(segment_names::linkEdit, section_names::weakBinding) {} 559 560 void WeakBindingSection::finalizeContents() { 561 raw_svector_ostream os{contents}; 562 Binding lastBinding; 563 564 for (const Defined *defined : definitions) 565 encodeWeakOverride(defined, os); 566 567 for (auto &p : sortBindings(bindingsMap)) { 568 const Symbol *sym = p.first; 569 std::vector<BindingEntry> &bindings = p.second; 570 os << static_cast<uint8_t>(BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM) 571 << sym->getName() << '\0' 572 << static_cast<uint8_t>(BIND_OPCODE_SET_TYPE_IMM | BIND_TYPE_POINTER); 573 std::vector<BindIR> opcodes; 574 for (const BindingEntry &b : bindings) 575 encodeBinding(b.target.isec->parent, 576 b.target.isec->getOffset(b.target.offset), b.addend, 577 lastBinding, opcodes); 578 if (config->optimize > 1) 579 optimizeOpcodes(opcodes); 580 for (const auto &op : opcodes) 581 flushOpcodes(op, os); 582 } 583 if (!bindingsMap.empty() || !definitions.empty()) 584 os << static_cast<uint8_t>(BIND_OPCODE_DONE); 585 } 586 587 void WeakBindingSection::writeTo(uint8_t *buf) const { 588 memcpy(buf, contents.data(), contents.size()); 589 } 590 591 StubsSection::StubsSection() 592 : SyntheticSection(segment_names::text, section_names::stubs) { 593 flags = S_SYMBOL_STUBS | S_ATTR_SOME_INSTRUCTIONS | S_ATTR_PURE_INSTRUCTIONS; 594 // The stubs section comprises machine instructions, which are aligned to 595 // 4 bytes on the archs we care about. 596 align = 4; 597 reserved2 = target->stubSize; 598 } 599 600 uint64_t StubsSection::getSize() const { 601 return entries.size() * target->stubSize; 602 } 603 604 void StubsSection::writeTo(uint8_t *buf) const { 605 size_t off = 0; 606 for (const Symbol *sym : entries) { 607 target->writeStub(buf + off, *sym); 608 off += target->stubSize; 609 } 610 } 611 612 void StubsSection::finalize() { isFinal = true; } 613 614 bool StubsSection::addEntry(Symbol *sym) { 615 bool inserted = entries.insert(sym); 616 if (inserted) 617 sym->stubsIndex = entries.size() - 1; 618 return inserted; 619 } 620 621 StubHelperSection::StubHelperSection() 622 : SyntheticSection(segment_names::text, section_names::stubHelper) { 623 flags = S_ATTR_SOME_INSTRUCTIONS | S_ATTR_PURE_INSTRUCTIONS; 624 align = 4; // This section comprises machine instructions 625 } 626 627 uint64_t StubHelperSection::getSize() const { 628 return target->stubHelperHeaderSize + 629 in.lazyBinding->getEntries().size() * target->stubHelperEntrySize; 630 } 631 632 bool StubHelperSection::isNeeded() const { return in.lazyBinding->isNeeded(); } 633 634 void StubHelperSection::writeTo(uint8_t *buf) const { 635 target->writeStubHelperHeader(buf); 636 size_t off = target->stubHelperHeaderSize; 637 for (const Symbol *sym : in.lazyBinding->getEntries()) { 638 target->writeStubHelperEntry(buf + off, *sym, addr + off); 639 off += target->stubHelperEntrySize; 640 } 641 } 642 643 void StubHelperSection::setup() { 644 Symbol *binder = symtab->addUndefined("dyld_stub_binder", /*file=*/nullptr, 645 /*isWeakRef=*/false); 646 if (auto *undefined = dyn_cast<Undefined>(binder)) 647 treatUndefinedSymbol(*undefined, 648 "lazy binding (normally in libSystem.dylib)"); 649 650 // treatUndefinedSymbol() can replace binder with a DylibSymbol; re-check. 651 stubBinder = dyn_cast_or_null<DylibSymbol>(binder); 652 if (stubBinder == nullptr) 653 return; 654 655 in.got->addEntry(stubBinder); 656 657 in.imageLoaderCache->parent = 658 ConcatOutputSection::getOrCreateForInput(in.imageLoaderCache); 659 inputSections.push_back(in.imageLoaderCache); 660 // Since this isn't in the symbol table or in any input file, the noDeadStrip 661 // argument doesn't matter. 662 dyldPrivate = 663 make<Defined>("__dyld_private", nullptr, in.imageLoaderCache, 0, 0, 664 /*isWeakDef=*/false, 665 /*isExternal=*/false, /*isPrivateExtern=*/false, 666 /*includeInSymtab=*/true, 667 /*isThumb=*/false, /*isReferencedDynamically=*/false, 668 /*noDeadStrip=*/false); 669 dyldPrivate->used = true; 670 } 671 672 LazyPointerSection::LazyPointerSection() 673 : SyntheticSection(segment_names::data, section_names::lazySymbolPtr) { 674 align = target->wordSize; 675 flags = S_LAZY_SYMBOL_POINTERS; 676 } 677 678 uint64_t LazyPointerSection::getSize() const { 679 return in.stubs->getEntries().size() * target->wordSize; 680 } 681 682 bool LazyPointerSection::isNeeded() const { 683 return !in.stubs->getEntries().empty(); 684 } 685 686 void LazyPointerSection::writeTo(uint8_t *buf) const { 687 size_t off = 0; 688 for (const Symbol *sym : in.stubs->getEntries()) { 689 if (const auto *dysym = dyn_cast<DylibSymbol>(sym)) { 690 if (dysym->hasStubsHelper()) { 691 uint64_t stubHelperOffset = 692 target->stubHelperHeaderSize + 693 dysym->stubsHelperIndex * target->stubHelperEntrySize; 694 write64le(buf + off, in.stubHelper->addr + stubHelperOffset); 695 } 696 } else { 697 write64le(buf + off, sym->getVA()); 698 } 699 off += target->wordSize; 700 } 701 } 702 703 LazyBindingSection::LazyBindingSection() 704 : LinkEditSection(segment_names::linkEdit, section_names::lazyBinding) {} 705 706 void LazyBindingSection::finalizeContents() { 707 // TODO: Just precompute output size here instead of writing to a temporary 708 // buffer 709 for (Symbol *sym : entries) 710 sym->lazyBindOffset = encode(*sym); 711 } 712 713 void LazyBindingSection::writeTo(uint8_t *buf) const { 714 memcpy(buf, contents.data(), contents.size()); 715 } 716 717 void LazyBindingSection::addEntry(Symbol *sym) { 718 if (entries.insert(sym)) { 719 sym->stubsHelperIndex = entries.size() - 1; 720 in.rebase->addEntry(in.lazyPointers->isec, 721 sym->stubsIndex * target->wordSize); 722 } 723 } 724 725 // Unlike the non-lazy binding section, the bind opcodes in this section aren't 726 // interpreted all at once. Rather, dyld will start interpreting opcodes at a 727 // given offset, typically only binding a single symbol before it finds a 728 // BIND_OPCODE_DONE terminator. As such, unlike in the non-lazy-binding case, 729 // we cannot encode just the differences between symbols; we have to emit the 730 // complete bind information for each symbol. 731 uint32_t LazyBindingSection::encode(const Symbol &sym) { 732 uint32_t opstreamOffset = contents.size(); 733 OutputSegment *dataSeg = in.lazyPointers->parent; 734 os << static_cast<uint8_t>(BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB | 735 dataSeg->index); 736 uint64_t offset = 737 in.lazyPointers->addr - dataSeg->addr + sym.stubsIndex * target->wordSize; 738 encodeULEB128(offset, os); 739 encodeDylibOrdinal(ordinalForSymbol(sym), os); 740 741 uint8_t flags = BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM; 742 if (sym.isWeakRef()) 743 flags |= BIND_SYMBOL_FLAGS_WEAK_IMPORT; 744 745 os << flags << sym.getName() << '\0' 746 << static_cast<uint8_t>(BIND_OPCODE_DO_BIND) 747 << static_cast<uint8_t>(BIND_OPCODE_DONE); 748 return opstreamOffset; 749 } 750 751 ExportSection::ExportSection() 752 : LinkEditSection(segment_names::linkEdit, section_names::export_) {} 753 754 void ExportSection::finalizeContents() { 755 trieBuilder.setImageBase(in.header->addr); 756 for (const Symbol *sym : symtab->getSymbols()) { 757 if (const auto *defined = dyn_cast<Defined>(sym)) { 758 if (defined->privateExtern || !defined->isLive()) 759 continue; 760 trieBuilder.addSymbol(*defined); 761 hasWeakSymbol = hasWeakSymbol || sym->isWeakDef(); 762 } 763 } 764 size = trieBuilder.build(); 765 } 766 767 void ExportSection::writeTo(uint8_t *buf) const { trieBuilder.writeTo(buf); } 768 769 DataInCodeSection::DataInCodeSection() 770 : LinkEditSection(segment_names::linkEdit, section_names::dataInCode) {} 771 772 template <class LP> 773 static std::vector<MachO::data_in_code_entry> collectDataInCodeEntries() { 774 std::vector<MachO::data_in_code_entry> dataInCodeEntries; 775 for (const InputFile *inputFile : inputFiles) { 776 if (!isa<ObjFile>(inputFile)) 777 continue; 778 const ObjFile *objFile = cast<ObjFile>(inputFile); 779 ArrayRef<MachO::data_in_code_entry> entries = objFile->getDataInCode(); 780 if (entries.empty()) 781 continue; 782 783 assert(is_sorted(dataInCodeEntries, [](const data_in_code_entry &lhs, 784 const data_in_code_entry &rhs) { 785 return lhs.offset < rhs.offset; 786 })); 787 // For each code subsection find 'data in code' entries residing in it. 788 // Compute the new offset values as 789 // <offset within subsection> + <subsection address> - <__TEXT address>. 790 for (const Section *section : objFile->sections) { 791 for (const Subsection &subsec : section->subsections) { 792 const InputSection *isec = subsec.isec; 793 if (!isCodeSection(isec)) 794 continue; 795 if (cast<ConcatInputSection>(isec)->shouldOmitFromOutput()) 796 continue; 797 const uint64_t beginAddr = section->addr + subsec.offset; 798 auto it = llvm::lower_bound( 799 entries, beginAddr, 800 [](const MachO::data_in_code_entry &entry, uint64_t addr) { 801 return entry.offset < addr; 802 }); 803 const uint64_t endAddr = beginAddr + isec->getSize(); 804 for (const auto end = entries.end(); 805 it != end && it->offset + it->length <= endAddr; ++it) 806 dataInCodeEntries.push_back( 807 {static_cast<uint32_t>(isec->getVA(it->offset - beginAddr) - 808 in.header->addr), 809 it->length, it->kind}); 810 } 811 } 812 } 813 return dataInCodeEntries; 814 } 815 816 void DataInCodeSection::finalizeContents() { 817 entries = target->wordSize == 8 ? collectDataInCodeEntries<LP64>() 818 : collectDataInCodeEntries<ILP32>(); 819 } 820 821 void DataInCodeSection::writeTo(uint8_t *buf) const { 822 if (!entries.empty()) 823 memcpy(buf, entries.data(), getRawSize()); 824 } 825 826 FunctionStartsSection::FunctionStartsSection() 827 : LinkEditSection(segment_names::linkEdit, section_names::functionStarts) {} 828 829 void FunctionStartsSection::finalizeContents() { 830 raw_svector_ostream os{contents}; 831 std::vector<uint64_t> addrs; 832 for (const InputFile *file : inputFiles) { 833 if (auto *objFile = dyn_cast<ObjFile>(file)) { 834 for (const Symbol *sym : objFile->symbols) { 835 if (const auto *defined = dyn_cast_or_null<Defined>(sym)) { 836 if (!defined->isec || !isCodeSection(defined->isec) || 837 !defined->isLive()) 838 continue; 839 // TODO: Add support for thumbs, in that case 840 // the lowest bit of nextAddr needs to be set to 1. 841 addrs.push_back(defined->getVA()); 842 } 843 } 844 } 845 } 846 llvm::sort(addrs); 847 uint64_t addr = in.header->addr; 848 for (uint64_t nextAddr : addrs) { 849 uint64_t delta = nextAddr - addr; 850 if (delta == 0) 851 continue; 852 encodeULEB128(delta, os); 853 addr = nextAddr; 854 } 855 os << '\0'; 856 } 857 858 void FunctionStartsSection::writeTo(uint8_t *buf) const { 859 memcpy(buf, contents.data(), contents.size()); 860 } 861 862 SymtabSection::SymtabSection(StringTableSection &stringTableSection) 863 : LinkEditSection(segment_names::linkEdit, section_names::symbolTable), 864 stringTableSection(stringTableSection) {} 865 866 void SymtabSection::emitBeginSourceStab(StringRef sourceFile) { 867 StabsEntry stab(N_SO); 868 stab.strx = stringTableSection.addString(saver().save(sourceFile)); 869 stabs.emplace_back(std::move(stab)); 870 } 871 872 void SymtabSection::emitEndSourceStab() { 873 StabsEntry stab(N_SO); 874 stab.sect = 1; 875 stabs.emplace_back(std::move(stab)); 876 } 877 878 void SymtabSection::emitObjectFileStab(ObjFile *file) { 879 StabsEntry stab(N_OSO); 880 stab.sect = target->cpuSubtype; 881 SmallString<261> path(!file->archiveName.empty() ? file->archiveName 882 : file->getName()); 883 std::error_code ec = sys::fs::make_absolute(path); 884 if (ec) 885 fatal("failed to get absolute path for " + path); 886 887 if (!file->archiveName.empty()) 888 path.append({"(", file->getName(), ")"}); 889 890 StringRef adjustedPath = saver().save(path.str()); 891 adjustedPath.consume_front(config->osoPrefix); 892 893 stab.strx = stringTableSection.addString(adjustedPath); 894 stab.desc = 1; 895 stab.value = file->modTime; 896 stabs.emplace_back(std::move(stab)); 897 } 898 899 void SymtabSection::emitEndFunStab(Defined *defined) { 900 StabsEntry stab(N_FUN); 901 stab.value = defined->size; 902 stabs.emplace_back(std::move(stab)); 903 } 904 905 void SymtabSection::emitStabs() { 906 if (config->omitDebugInfo) 907 return; 908 909 for (const std::string &s : config->astPaths) { 910 StabsEntry astStab(N_AST); 911 astStab.strx = stringTableSection.addString(s); 912 stabs.emplace_back(std::move(astStab)); 913 } 914 915 // Cache the file ID for each symbol in an std::pair for faster sorting. 916 using SortingPair = std::pair<Defined *, int>; 917 std::vector<SortingPair> symbolsNeedingStabs; 918 for (const SymtabEntry &entry : 919 concat<SymtabEntry>(localSymbols, externalSymbols)) { 920 Symbol *sym = entry.sym; 921 assert(sym->isLive() && 922 "dead symbols should not be in localSymbols, externalSymbols"); 923 if (auto *defined = dyn_cast<Defined>(sym)) { 924 // Excluded symbols should have been filtered out in finalizeContents(). 925 assert(defined->includeInSymtab); 926 927 if (defined->isAbsolute()) 928 continue; 929 930 // Constant-folded symbols go in the executable's symbol table, but don't 931 // get a stabs entry. 932 if (defined->wasIdenticalCodeFolded) 933 continue; 934 935 InputSection *isec = defined->isec; 936 ObjFile *file = dyn_cast_or_null<ObjFile>(isec->getFile()); 937 if (!file || !file->compileUnit) 938 continue; 939 940 symbolsNeedingStabs.emplace_back(defined, defined->isec->getFile()->id); 941 } 942 } 943 944 llvm::stable_sort(symbolsNeedingStabs, 945 [&](const SortingPair &a, const SortingPair &b) { 946 return a.second < b.second; 947 }); 948 949 // Emit STABS symbols so that dsymutil and/or the debugger can map address 950 // regions in the final binary to the source and object files from which they 951 // originated. 952 InputFile *lastFile = nullptr; 953 for (SortingPair &pair : symbolsNeedingStabs) { 954 Defined *defined = pair.first; 955 InputSection *isec = defined->isec; 956 ObjFile *file = cast<ObjFile>(isec->getFile()); 957 958 if (lastFile == nullptr || lastFile != file) { 959 if (lastFile != nullptr) 960 emitEndSourceStab(); 961 lastFile = file; 962 963 emitBeginSourceStab(file->sourceFile()); 964 emitObjectFileStab(file); 965 } 966 967 StabsEntry symStab; 968 symStab.sect = defined->isec->parent->index; 969 symStab.strx = stringTableSection.addString(defined->getName()); 970 symStab.value = defined->getVA(); 971 972 if (isCodeSection(isec)) { 973 symStab.type = N_FUN; 974 stabs.emplace_back(std::move(symStab)); 975 emitEndFunStab(defined); 976 } else { 977 symStab.type = defined->isExternal() ? N_GSYM : N_STSYM; 978 stabs.emplace_back(std::move(symStab)); 979 } 980 } 981 982 if (!stabs.empty()) 983 emitEndSourceStab(); 984 } 985 986 void SymtabSection::finalizeContents() { 987 auto addSymbol = [&](std::vector<SymtabEntry> &symbols, Symbol *sym) { 988 uint32_t strx = stringTableSection.addString(sym->getName()); 989 symbols.push_back({sym, strx}); 990 }; 991 992 std::function<void(Symbol *)> localSymbolsHandler; 993 switch (config->localSymbolsPresence) { 994 case SymtabPresence::All: 995 localSymbolsHandler = [&](Symbol *sym) { addSymbol(localSymbols, sym); }; 996 break; 997 case SymtabPresence::None: 998 localSymbolsHandler = [&](Symbol *) { /* Do nothing*/ }; 999 break; 1000 case SymtabPresence::SelectivelyIncluded: 1001 localSymbolsHandler = [&](Symbol *sym) { 1002 if (config->localSymbolPatterns.match(sym->getName())) 1003 addSymbol(localSymbols, sym); 1004 }; 1005 break; 1006 case SymtabPresence::SelectivelyExcluded: 1007 localSymbolsHandler = [&](Symbol *sym) { 1008 if (!config->localSymbolPatterns.match(sym->getName())) 1009 addSymbol(localSymbols, sym); 1010 }; 1011 break; 1012 } 1013 1014 // Local symbols aren't in the SymbolTable, so we walk the list of object 1015 // files to gather them. 1016 // But if `-x` is set, then we don't need to. localSymbolsHandler() will do 1017 // the right thing regardless, but this check is a perf optimization because 1018 // iterating through all the input files and their symbols is expensive. 1019 if (config->localSymbolsPresence != SymtabPresence::None) { 1020 for (const InputFile *file : inputFiles) { 1021 if (auto *objFile = dyn_cast<ObjFile>(file)) { 1022 for (Symbol *sym : objFile->symbols) { 1023 if (auto *defined = dyn_cast_or_null<Defined>(sym)) { 1024 if (defined->isExternal() || !defined->isLive() || 1025 !defined->includeInSymtab) 1026 continue; 1027 localSymbolsHandler(sym); 1028 } 1029 } 1030 } 1031 } 1032 } 1033 1034 // __dyld_private is a local symbol too. It's linker-created and doesn't 1035 // exist in any object file. 1036 if (Defined *dyldPrivate = in.stubHelper->dyldPrivate) 1037 localSymbolsHandler(dyldPrivate); 1038 1039 for (Symbol *sym : symtab->getSymbols()) { 1040 if (!sym->isLive()) 1041 continue; 1042 if (auto *defined = dyn_cast<Defined>(sym)) { 1043 if (!defined->includeInSymtab) 1044 continue; 1045 assert(defined->isExternal()); 1046 if (defined->privateExtern) 1047 localSymbolsHandler(defined); 1048 else 1049 addSymbol(externalSymbols, defined); 1050 } else if (auto *dysym = dyn_cast<DylibSymbol>(sym)) { 1051 if (dysym->isReferenced()) 1052 addSymbol(undefinedSymbols, sym); 1053 } 1054 } 1055 1056 emitStabs(); 1057 uint32_t symtabIndex = stabs.size(); 1058 for (const SymtabEntry &entry : 1059 concat<SymtabEntry>(localSymbols, externalSymbols, undefinedSymbols)) { 1060 entry.sym->symtabIndex = symtabIndex++; 1061 } 1062 } 1063 1064 uint32_t SymtabSection::getNumSymbols() const { 1065 return stabs.size() + localSymbols.size() + externalSymbols.size() + 1066 undefinedSymbols.size(); 1067 } 1068 1069 // This serves to hide (type-erase) the template parameter from SymtabSection. 1070 template <class LP> class SymtabSectionImpl final : public SymtabSection { 1071 public: 1072 SymtabSectionImpl(StringTableSection &stringTableSection) 1073 : SymtabSection(stringTableSection) {} 1074 uint64_t getRawSize() const override; 1075 void writeTo(uint8_t *buf) const override; 1076 }; 1077 1078 template <class LP> uint64_t SymtabSectionImpl<LP>::getRawSize() const { 1079 return getNumSymbols() * sizeof(typename LP::nlist); 1080 } 1081 1082 template <class LP> void SymtabSectionImpl<LP>::writeTo(uint8_t *buf) const { 1083 auto *nList = reinterpret_cast<typename LP::nlist *>(buf); 1084 // Emit the stabs entries before the "real" symbols. We cannot emit them 1085 // after as that would render Symbol::symtabIndex inaccurate. 1086 for (const StabsEntry &entry : stabs) { 1087 nList->n_strx = entry.strx; 1088 nList->n_type = entry.type; 1089 nList->n_sect = entry.sect; 1090 nList->n_desc = entry.desc; 1091 nList->n_value = entry.value; 1092 ++nList; 1093 } 1094 1095 for (const SymtabEntry &entry : concat<const SymtabEntry>( 1096 localSymbols, externalSymbols, undefinedSymbols)) { 1097 nList->n_strx = entry.strx; 1098 // TODO populate n_desc with more flags 1099 if (auto *defined = dyn_cast<Defined>(entry.sym)) { 1100 uint8_t scope = 0; 1101 if (defined->privateExtern) { 1102 // Private external -- dylib scoped symbol. 1103 // Promote to non-external at link time. 1104 scope = N_PEXT; 1105 } else if (defined->isExternal()) { 1106 // Normal global symbol. 1107 scope = N_EXT; 1108 } else { 1109 // TU-local symbol from localSymbols. 1110 scope = 0; 1111 } 1112 1113 if (defined->isAbsolute()) { 1114 nList->n_type = scope | N_ABS; 1115 nList->n_sect = NO_SECT; 1116 nList->n_value = defined->value; 1117 } else { 1118 nList->n_type = scope | N_SECT; 1119 nList->n_sect = defined->isec->parent->index; 1120 // For the N_SECT symbol type, n_value is the address of the symbol 1121 nList->n_value = defined->getVA(); 1122 } 1123 nList->n_desc |= defined->thumb ? N_ARM_THUMB_DEF : 0; 1124 nList->n_desc |= defined->isExternalWeakDef() ? N_WEAK_DEF : 0; 1125 nList->n_desc |= 1126 defined->referencedDynamically ? REFERENCED_DYNAMICALLY : 0; 1127 } else if (auto *dysym = dyn_cast<DylibSymbol>(entry.sym)) { 1128 uint16_t n_desc = nList->n_desc; 1129 int16_t ordinal = ordinalForDylibSymbol(*dysym); 1130 if (ordinal == BIND_SPECIAL_DYLIB_FLAT_LOOKUP) 1131 SET_LIBRARY_ORDINAL(n_desc, DYNAMIC_LOOKUP_ORDINAL); 1132 else if (ordinal == BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE) 1133 SET_LIBRARY_ORDINAL(n_desc, EXECUTABLE_ORDINAL); 1134 else { 1135 assert(ordinal > 0); 1136 SET_LIBRARY_ORDINAL(n_desc, static_cast<uint8_t>(ordinal)); 1137 } 1138 1139 nList->n_type = N_EXT; 1140 n_desc |= dysym->isWeakDef() ? N_WEAK_DEF : 0; 1141 n_desc |= dysym->isWeakRef() ? N_WEAK_REF : 0; 1142 nList->n_desc = n_desc; 1143 } 1144 ++nList; 1145 } 1146 } 1147 1148 template <class LP> 1149 SymtabSection * 1150 macho::makeSymtabSection(StringTableSection &stringTableSection) { 1151 return make<SymtabSectionImpl<LP>>(stringTableSection); 1152 } 1153 1154 IndirectSymtabSection::IndirectSymtabSection() 1155 : LinkEditSection(segment_names::linkEdit, 1156 section_names::indirectSymbolTable) {} 1157 1158 uint32_t IndirectSymtabSection::getNumSymbols() const { 1159 return in.got->getEntries().size() + in.tlvPointers->getEntries().size() + 1160 2 * in.stubs->getEntries().size(); 1161 } 1162 1163 bool IndirectSymtabSection::isNeeded() const { 1164 return in.got->isNeeded() || in.tlvPointers->isNeeded() || 1165 in.stubs->isNeeded(); 1166 } 1167 1168 void IndirectSymtabSection::finalizeContents() { 1169 uint32_t off = 0; 1170 in.got->reserved1 = off; 1171 off += in.got->getEntries().size(); 1172 in.tlvPointers->reserved1 = off; 1173 off += in.tlvPointers->getEntries().size(); 1174 in.stubs->reserved1 = off; 1175 off += in.stubs->getEntries().size(); 1176 in.lazyPointers->reserved1 = off; 1177 } 1178 1179 static uint32_t indirectValue(const Symbol *sym) { 1180 if (sym->symtabIndex == UINT32_MAX) 1181 return INDIRECT_SYMBOL_LOCAL; 1182 if (auto *defined = dyn_cast<Defined>(sym)) 1183 if (defined->privateExtern) 1184 return INDIRECT_SYMBOL_LOCAL; 1185 return sym->symtabIndex; 1186 } 1187 1188 void IndirectSymtabSection::writeTo(uint8_t *buf) const { 1189 uint32_t off = 0; 1190 for (const Symbol *sym : in.got->getEntries()) { 1191 write32le(buf + off * sizeof(uint32_t), indirectValue(sym)); 1192 ++off; 1193 } 1194 for (const Symbol *sym : in.tlvPointers->getEntries()) { 1195 write32le(buf + off * sizeof(uint32_t), indirectValue(sym)); 1196 ++off; 1197 } 1198 for (const Symbol *sym : in.stubs->getEntries()) { 1199 write32le(buf + off * sizeof(uint32_t), indirectValue(sym)); 1200 ++off; 1201 } 1202 // There is a 1:1 correspondence between stubs and LazyPointerSection 1203 // entries. But giving __stubs and __la_symbol_ptr the same reserved1 1204 // (the offset into the indirect symbol table) so that they both refer 1205 // to the same range of offsets confuses `strip`, so write the stubs 1206 // symbol table offsets a second time. 1207 for (const Symbol *sym : in.stubs->getEntries()) { 1208 write32le(buf + off * sizeof(uint32_t), indirectValue(sym)); 1209 ++off; 1210 } 1211 } 1212 1213 StringTableSection::StringTableSection() 1214 : LinkEditSection(segment_names::linkEdit, section_names::stringTable) {} 1215 1216 uint32_t StringTableSection::addString(StringRef str) { 1217 uint32_t strx = size; 1218 strings.push_back(str); // TODO: consider deduplicating strings 1219 size += str.size() + 1; // account for null terminator 1220 return strx; 1221 } 1222 1223 void StringTableSection::writeTo(uint8_t *buf) const { 1224 uint32_t off = 0; 1225 for (StringRef str : strings) { 1226 memcpy(buf + off, str.data(), str.size()); 1227 off += str.size() + 1; // account for null terminator 1228 } 1229 } 1230 1231 static_assert((CodeSignatureSection::blobHeadersSize % 8) == 0, ""); 1232 static_assert((CodeSignatureSection::fixedHeadersSize % 8) == 0, ""); 1233 1234 CodeSignatureSection::CodeSignatureSection() 1235 : LinkEditSection(segment_names::linkEdit, section_names::codeSignature) { 1236 align = 16; // required by libstuff 1237 // FIXME: Consider using finalOutput instead of outputFile. 1238 fileName = config->outputFile; 1239 size_t slashIndex = fileName.rfind("/"); 1240 if (slashIndex != std::string::npos) 1241 fileName = fileName.drop_front(slashIndex + 1); 1242 1243 // NOTE: Any changes to these calculations should be repeated 1244 // in llvm-objcopy's MachOLayoutBuilder::layoutTail. 1245 allHeadersSize = alignTo<16>(fixedHeadersSize + fileName.size() + 1); 1246 fileNamePad = allHeadersSize - fixedHeadersSize - fileName.size(); 1247 } 1248 1249 uint32_t CodeSignatureSection::getBlockCount() const { 1250 return (fileOff + blockSize - 1) / blockSize; 1251 } 1252 1253 uint64_t CodeSignatureSection::getRawSize() const { 1254 return allHeadersSize + getBlockCount() * hashSize; 1255 } 1256 1257 void CodeSignatureSection::writeHashes(uint8_t *buf) const { 1258 // NOTE: Changes to this functionality should be repeated in llvm-objcopy's 1259 // MachOWriter::writeSignatureData. 1260 uint8_t *hashes = buf + fileOff + allHeadersSize; 1261 parallelFor(0, getBlockCount(), [&](size_t i) { 1262 sha256(buf + i * blockSize, 1263 std::min(static_cast<size_t>(fileOff - i * blockSize), 1264 static_cast<size_t>(blockSize)), 1265 hashes + i * hashSize); 1266 }); 1267 #if defined(__APPLE__) 1268 // This is macOS-specific work-around and makes no sense for any 1269 // other host OS. See https://openradar.appspot.com/FB8914231 1270 // 1271 // The macOS kernel maintains a signature-verification cache to 1272 // quickly validate applications at time of execve(2). The trouble 1273 // is that for the kernel creates the cache entry at the time of the 1274 // mmap(2) call, before we have a chance to write either the code to 1275 // sign or the signature header+hashes. The fix is to invalidate 1276 // all cached data associated with the output file, thus discarding 1277 // the bogus prematurely-cached signature. 1278 msync(buf, fileOff + getSize(), MS_INVALIDATE); 1279 #endif 1280 } 1281 1282 void CodeSignatureSection::writeTo(uint8_t *buf) const { 1283 // NOTE: Changes to this functionality should be repeated in llvm-objcopy's 1284 // MachOWriter::writeSignatureData. 1285 uint32_t signatureSize = static_cast<uint32_t>(getSize()); 1286 auto *superBlob = reinterpret_cast<CS_SuperBlob *>(buf); 1287 write32be(&superBlob->magic, CSMAGIC_EMBEDDED_SIGNATURE); 1288 write32be(&superBlob->length, signatureSize); 1289 write32be(&superBlob->count, 1); 1290 auto *blobIndex = reinterpret_cast<CS_BlobIndex *>(&superBlob[1]); 1291 write32be(&blobIndex->type, CSSLOT_CODEDIRECTORY); 1292 write32be(&blobIndex->offset, blobHeadersSize); 1293 auto *codeDirectory = 1294 reinterpret_cast<CS_CodeDirectory *>(buf + blobHeadersSize); 1295 write32be(&codeDirectory->magic, CSMAGIC_CODEDIRECTORY); 1296 write32be(&codeDirectory->length, signatureSize - blobHeadersSize); 1297 write32be(&codeDirectory->version, CS_SUPPORTSEXECSEG); 1298 write32be(&codeDirectory->flags, CS_ADHOC | CS_LINKER_SIGNED); 1299 write32be(&codeDirectory->hashOffset, 1300 sizeof(CS_CodeDirectory) + fileName.size() + fileNamePad); 1301 write32be(&codeDirectory->identOffset, sizeof(CS_CodeDirectory)); 1302 codeDirectory->nSpecialSlots = 0; 1303 write32be(&codeDirectory->nCodeSlots, getBlockCount()); 1304 write32be(&codeDirectory->codeLimit, fileOff); 1305 codeDirectory->hashSize = static_cast<uint8_t>(hashSize); 1306 codeDirectory->hashType = kSecCodeSignatureHashSHA256; 1307 codeDirectory->platform = 0; 1308 codeDirectory->pageSize = blockSizeShift; 1309 codeDirectory->spare2 = 0; 1310 codeDirectory->scatterOffset = 0; 1311 codeDirectory->teamOffset = 0; 1312 codeDirectory->spare3 = 0; 1313 codeDirectory->codeLimit64 = 0; 1314 OutputSegment *textSeg = getOrCreateOutputSegment(segment_names::text); 1315 write64be(&codeDirectory->execSegBase, textSeg->fileOff); 1316 write64be(&codeDirectory->execSegLimit, textSeg->fileSize); 1317 write64be(&codeDirectory->execSegFlags, 1318 config->outputType == MH_EXECUTE ? CS_EXECSEG_MAIN_BINARY : 0); 1319 auto *id = reinterpret_cast<char *>(&codeDirectory[1]); 1320 memcpy(id, fileName.begin(), fileName.size()); 1321 memset(id + fileName.size(), 0, fileNamePad); 1322 } 1323 1324 BitcodeBundleSection::BitcodeBundleSection() 1325 : SyntheticSection(segment_names::llvm, section_names::bitcodeBundle) {} 1326 1327 class ErrorCodeWrapper { 1328 public: 1329 explicit ErrorCodeWrapper(std::error_code ec) : errorCode(ec.value()) {} 1330 explicit ErrorCodeWrapper(int ec) : errorCode(ec) {} 1331 operator int() const { return errorCode; } 1332 1333 private: 1334 int errorCode; 1335 }; 1336 1337 #define CHECK_EC(exp) \ 1338 do { \ 1339 ErrorCodeWrapper ec(exp); \ 1340 if (ec) \ 1341 fatal(Twine("operation failed with error code ") + Twine(ec) + ": " + \ 1342 #exp); \ 1343 } while (0); 1344 1345 void BitcodeBundleSection::finalize() { 1346 #ifdef LLVM_HAVE_LIBXAR 1347 using namespace llvm::sys::fs; 1348 CHECK_EC(createTemporaryFile("bitcode-bundle", "xar", xarPath)); 1349 1350 #pragma clang diagnostic push 1351 #pragma clang diagnostic ignored "-Wdeprecated-declarations" 1352 xar_t xar(xar_open(xarPath.data(), O_RDWR)); 1353 #pragma clang diagnostic pop 1354 if (!xar) 1355 fatal("failed to open XAR temporary file at " + xarPath); 1356 CHECK_EC(xar_opt_set(xar, XAR_OPT_COMPRESSION, XAR_OPT_VAL_NONE)); 1357 // FIXME: add more data to XAR 1358 CHECK_EC(xar_close(xar)); 1359 1360 file_size(xarPath, xarSize); 1361 #endif // defined(LLVM_HAVE_LIBXAR) 1362 } 1363 1364 void BitcodeBundleSection::writeTo(uint8_t *buf) const { 1365 using namespace llvm::sys::fs; 1366 file_t handle = 1367 CHECK(openNativeFile(xarPath, CD_OpenExisting, FA_Read, OF_None), 1368 "failed to open XAR file"); 1369 std::error_code ec; 1370 mapped_file_region xarMap(handle, mapped_file_region::mapmode::readonly, 1371 xarSize, 0, ec); 1372 if (ec) 1373 fatal("failed to map XAR file"); 1374 memcpy(buf, xarMap.const_data(), xarSize); 1375 1376 closeFile(handle); 1377 remove(xarPath); 1378 } 1379 1380 CStringSection::CStringSection() 1381 : SyntheticSection(segment_names::text, section_names::cString) { 1382 flags = S_CSTRING_LITERALS; 1383 } 1384 1385 void CStringSection::addInput(CStringInputSection *isec) { 1386 isec->parent = this; 1387 inputs.push_back(isec); 1388 if (isec->align > align) 1389 align = isec->align; 1390 } 1391 1392 void CStringSection::writeTo(uint8_t *buf) const { 1393 for (const CStringInputSection *isec : inputs) { 1394 for (size_t i = 0, e = isec->pieces.size(); i != e; ++i) { 1395 if (!isec->pieces[i].live) 1396 continue; 1397 StringRef string = isec->getStringRef(i); 1398 memcpy(buf + isec->pieces[i].outSecOff, string.data(), string.size()); 1399 } 1400 } 1401 } 1402 1403 void CStringSection::finalizeContents() { 1404 uint64_t offset = 0; 1405 for (CStringInputSection *isec : inputs) { 1406 for (size_t i = 0, e = isec->pieces.size(); i != e; ++i) { 1407 if (!isec->pieces[i].live) 1408 continue; 1409 // See comment above DeduplicatedCStringSection for how alignment is 1410 // handled. 1411 uint32_t pieceAlign = 1412 1 << countTrailingZeros(isec->align | isec->pieces[i].inSecOff); 1413 offset = alignTo(offset, pieceAlign); 1414 isec->pieces[i].outSecOff = offset; 1415 isec->isFinal = true; 1416 StringRef string = isec->getStringRef(i); 1417 offset += string.size(); 1418 } 1419 } 1420 size = offset; 1421 } 1422 1423 // Mergeable cstring literals are found under the __TEXT,__cstring section. In 1424 // contrast to ELF, which puts strings that need different alignments into 1425 // different sections, clang's Mach-O backend puts them all in one section. 1426 // Strings that need to be aligned have the .p2align directive emitted before 1427 // them, which simply translates into zero padding in the object file. In other 1428 // words, we have to infer the desired alignment of these cstrings from their 1429 // addresses. 1430 // 1431 // We differ slightly from ld64 in how we've chosen to align these cstrings. 1432 // Both LLD and ld64 preserve the number of trailing zeros in each cstring's 1433 // address in the input object files. When deduplicating identical cstrings, 1434 // both linkers pick the cstring whose address has more trailing zeros, and 1435 // preserve the alignment of that address in the final binary. However, ld64 1436 // goes a step further and also preserves the offset of the cstring from the 1437 // last section-aligned address. I.e. if a cstring is at offset 18 in the 1438 // input, with a section alignment of 16, then both LLD and ld64 will ensure the 1439 // final address is 2-byte aligned (since 18 == 16 + 2). But ld64 will also 1440 // ensure that the final address is of the form 16 * k + 2 for some k. 1441 // 1442 // Note that ld64's heuristic means that a dedup'ed cstring's final address is 1443 // dependent on the order of the input object files. E.g. if in addition to the 1444 // cstring at offset 18 above, we have a duplicate one in another file with a 1445 // `.cstring` section alignment of 2 and an offset of zero, then ld64 will pick 1446 // the cstring from the object file earlier on the command line (since both have 1447 // the same number of trailing zeros in their address). So the final cstring may 1448 // either be at some address `16 * k + 2` or at some address `2 * k`. 1449 // 1450 // I've opted not to follow this behavior primarily for implementation 1451 // simplicity, and secondarily to save a few more bytes. It's not clear to me 1452 // that preserving the section alignment + offset is ever necessary, and there 1453 // are many cases that are clearly redundant. In particular, if an x86_64 object 1454 // file contains some strings that are accessed via SIMD instructions, then the 1455 // .cstring section in the object file will be 16-byte-aligned (since SIMD 1456 // requires its operand addresses to be 16-byte aligned). However, there will 1457 // typically also be other cstrings in the same file that aren't used via SIMD 1458 // and don't need this alignment. They will be emitted at some arbitrary address 1459 // `A`, but ld64 will treat them as being 16-byte aligned with an offset of `16 1460 // % A`. 1461 void DeduplicatedCStringSection::finalizeContents() { 1462 // Find the largest alignment required for each string. 1463 for (const CStringInputSection *isec : inputs) { 1464 for (size_t i = 0, e = isec->pieces.size(); i != e; ++i) { 1465 const StringPiece &piece = isec->pieces[i]; 1466 if (!piece.live) 1467 continue; 1468 auto s = isec->getCachedHashStringRef(i); 1469 assert(isec->align != 0); 1470 uint8_t trailingZeros = countTrailingZeros(isec->align | piece.inSecOff); 1471 auto it = stringOffsetMap.insert( 1472 std::make_pair(s, StringOffset(trailingZeros))); 1473 if (!it.second && it.first->second.trailingZeros < trailingZeros) 1474 it.first->second.trailingZeros = trailingZeros; 1475 } 1476 } 1477 1478 // Assign an offset for each string and save it to the corresponding 1479 // StringPieces for easy access. 1480 for (CStringInputSection *isec : inputs) { 1481 for (size_t i = 0, e = isec->pieces.size(); i != e; ++i) { 1482 if (!isec->pieces[i].live) 1483 continue; 1484 auto s = isec->getCachedHashStringRef(i); 1485 auto it = stringOffsetMap.find(s); 1486 assert(it != stringOffsetMap.end()); 1487 StringOffset &offsetInfo = it->second; 1488 if (offsetInfo.outSecOff == UINT64_MAX) { 1489 offsetInfo.outSecOff = alignTo(size, 1ULL << offsetInfo.trailingZeros); 1490 size = offsetInfo.outSecOff + s.size(); 1491 } 1492 isec->pieces[i].outSecOff = offsetInfo.outSecOff; 1493 } 1494 isec->isFinal = true; 1495 } 1496 } 1497 1498 void DeduplicatedCStringSection::writeTo(uint8_t *buf) const { 1499 for (const auto &p : stringOffsetMap) { 1500 StringRef data = p.first.val(); 1501 uint64_t off = p.second.outSecOff; 1502 if (!data.empty()) 1503 memcpy(buf + off, data.data(), data.size()); 1504 } 1505 } 1506 1507 // This section is actually emitted as __TEXT,__const by ld64, but clang may 1508 // emit input sections of that name, and LLD doesn't currently support mixing 1509 // synthetic and concat-type OutputSections. To work around this, I've given 1510 // our merged-literals section a different name. 1511 WordLiteralSection::WordLiteralSection() 1512 : SyntheticSection(segment_names::text, section_names::literals) { 1513 align = 16; 1514 } 1515 1516 void WordLiteralSection::addInput(WordLiteralInputSection *isec) { 1517 isec->parent = this; 1518 inputs.push_back(isec); 1519 } 1520 1521 void WordLiteralSection::finalizeContents() { 1522 for (WordLiteralInputSection *isec : inputs) { 1523 // We do all processing of the InputSection here, so it will be effectively 1524 // finalized. 1525 isec->isFinal = true; 1526 const uint8_t *buf = isec->data.data(); 1527 switch (sectionType(isec->getFlags())) { 1528 case S_4BYTE_LITERALS: { 1529 for (size_t off = 0, e = isec->data.size(); off < e; off += 4) { 1530 if (!isec->isLive(off)) 1531 continue; 1532 uint32_t value = *reinterpret_cast<const uint32_t *>(buf + off); 1533 literal4Map.emplace(value, literal4Map.size()); 1534 } 1535 break; 1536 } 1537 case S_8BYTE_LITERALS: { 1538 for (size_t off = 0, e = isec->data.size(); off < e; off += 8) { 1539 if (!isec->isLive(off)) 1540 continue; 1541 uint64_t value = *reinterpret_cast<const uint64_t *>(buf + off); 1542 literal8Map.emplace(value, literal8Map.size()); 1543 } 1544 break; 1545 } 1546 case S_16BYTE_LITERALS: { 1547 for (size_t off = 0, e = isec->data.size(); off < e; off += 16) { 1548 if (!isec->isLive(off)) 1549 continue; 1550 UInt128 value = *reinterpret_cast<const UInt128 *>(buf + off); 1551 literal16Map.emplace(value, literal16Map.size()); 1552 } 1553 break; 1554 } 1555 default: 1556 llvm_unreachable("invalid literal section type"); 1557 } 1558 } 1559 } 1560 1561 void WordLiteralSection::writeTo(uint8_t *buf) const { 1562 // Note that we don't attempt to do any endianness conversion in addInput(), 1563 // so we don't do it here either -- just write out the original value, 1564 // byte-for-byte. 1565 for (const auto &p : literal16Map) 1566 memcpy(buf + p.second * 16, &p.first, 16); 1567 buf += literal16Map.size() * 16; 1568 1569 for (const auto &p : literal8Map) 1570 memcpy(buf + p.second * 8, &p.first, 8); 1571 buf += literal8Map.size() * 8; 1572 1573 for (const auto &p : literal4Map) 1574 memcpy(buf + p.second * 4, &p.first, 4); 1575 } 1576 1577 void macho::createSyntheticSymbols() { 1578 auto addHeaderSymbol = [](const char *name) { 1579 symtab->addSynthetic(name, in.header->isec, /*value=*/0, 1580 /*isPrivateExtern=*/true, /*includeInSymtab=*/false, 1581 /*referencedDynamically=*/false); 1582 }; 1583 1584 switch (config->outputType) { 1585 // FIXME: Assign the right address value for these symbols 1586 // (rather than 0). But we need to do that after assignAddresses(). 1587 case MH_EXECUTE: 1588 // If linking PIE, __mh_execute_header is a defined symbol in 1589 // __TEXT, __text) 1590 // Otherwise, it's an absolute symbol. 1591 if (config->isPic) 1592 symtab->addSynthetic("__mh_execute_header", in.header->isec, /*value=*/0, 1593 /*isPrivateExtern=*/false, /*includeInSymtab=*/true, 1594 /*referencedDynamically=*/true); 1595 else 1596 symtab->addSynthetic("__mh_execute_header", /*isec=*/nullptr, /*value=*/0, 1597 /*isPrivateExtern=*/false, /*includeInSymtab=*/true, 1598 /*referencedDynamically=*/true); 1599 break; 1600 1601 // The following symbols are N_SECT symbols, even though the header is not 1602 // part of any section and that they are private to the bundle/dylib/object 1603 // they are part of. 1604 case MH_BUNDLE: 1605 addHeaderSymbol("__mh_bundle_header"); 1606 break; 1607 case MH_DYLIB: 1608 addHeaderSymbol("__mh_dylib_header"); 1609 break; 1610 case MH_DYLINKER: 1611 addHeaderSymbol("__mh_dylinker_header"); 1612 break; 1613 case MH_OBJECT: 1614 addHeaderSymbol("__mh_object_header"); 1615 break; 1616 default: 1617 llvm_unreachable("unexpected outputType"); 1618 break; 1619 } 1620 1621 // The Itanium C++ ABI requires dylibs to pass a pointer to __cxa_atexit 1622 // which does e.g. cleanup of static global variables. The ABI document 1623 // says that the pointer can point to any address in one of the dylib's 1624 // segments, but in practice ld64 seems to set it to point to the header, 1625 // so that's what's implemented here. 1626 addHeaderSymbol("___dso_handle"); 1627 } 1628 1629 template SymtabSection *macho::makeSymtabSection<LP64>(StringTableSection &); 1630 template SymtabSection *macho::makeSymtabSection<ILP32>(StringTableSection &); 1631