1 //===- Writer.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 "Writer.h" 10 #include "Config.h" 11 #include "InputFiles.h" 12 #include "InputSection.h" 13 #include "MergedOutputSection.h" 14 #include "OutputSection.h" 15 #include "OutputSegment.h" 16 #include "SymbolTable.h" 17 #include "Symbols.h" 18 #include "SyntheticSections.h" 19 #include "Target.h" 20 #include "UnwindInfoSection.h" 21 22 #include "lld/Common/ErrorHandler.h" 23 #include "lld/Common/Memory.h" 24 #include "llvm/BinaryFormat/MachO.h" 25 #include "llvm/Config/llvm-config.h" 26 #include "llvm/Support/LEB128.h" 27 #include "llvm/Support/MathExtras.h" 28 #include "llvm/Support/Path.h" 29 #include "llvm/Support/xxhash.h" 30 31 #include <algorithm> 32 33 using namespace llvm; 34 using namespace llvm::MachO; 35 using namespace llvm::sys; 36 using namespace lld; 37 using namespace lld::macho; 38 39 namespace { 40 class LCUuid; 41 42 class Writer { 43 public: 44 Writer() : buffer(errorHandler().outputBuffer) {} 45 46 void scanRelocations(); 47 void scanSymbols(); 48 void createOutputSections(); 49 void createLoadCommands(); 50 void assignAddresses(OutputSegment *); 51 52 void openFile(); 53 void writeSections(); 54 void writeUuid(); 55 void writeCodeSignature(); 56 57 void run(); 58 59 std::unique_ptr<FileOutputBuffer> &buffer; 60 uint64_t addr = 0; 61 uint64_t fileOff = 0; 62 MachHeaderSection *header = nullptr; 63 StringTableSection *stringTableSection = nullptr; 64 SymtabSection *symtabSection = nullptr; 65 IndirectSymtabSection *indirectSymtabSection = nullptr; 66 CodeSignatureSection *codeSignatureSection = nullptr; 67 UnwindInfoSection *unwindInfoSection = nullptr; 68 LCUuid *uuidCommand = nullptr; 69 }; 70 71 // LC_DYLD_INFO_ONLY stores the offsets of symbol import/export information. 72 class LCDyldInfo : public LoadCommand { 73 public: 74 LCDyldInfo(RebaseSection *rebaseSection, BindingSection *bindingSection, 75 WeakBindingSection *weakBindingSection, 76 LazyBindingSection *lazyBindingSection, 77 ExportSection *exportSection) 78 : rebaseSection(rebaseSection), bindingSection(bindingSection), 79 weakBindingSection(weakBindingSection), 80 lazyBindingSection(lazyBindingSection), exportSection(exportSection) {} 81 82 uint32_t getSize() const override { return sizeof(dyld_info_command); } 83 84 void writeTo(uint8_t *buf) const override { 85 auto *c = reinterpret_cast<dyld_info_command *>(buf); 86 c->cmd = LC_DYLD_INFO_ONLY; 87 c->cmdsize = getSize(); 88 if (rebaseSection->isNeeded()) { 89 c->rebase_off = rebaseSection->fileOff; 90 c->rebase_size = rebaseSection->getFileSize(); 91 } 92 if (bindingSection->isNeeded()) { 93 c->bind_off = bindingSection->fileOff; 94 c->bind_size = bindingSection->getFileSize(); 95 } 96 if (weakBindingSection->isNeeded()) { 97 c->weak_bind_off = weakBindingSection->fileOff; 98 c->weak_bind_size = weakBindingSection->getFileSize(); 99 } 100 if (lazyBindingSection->isNeeded()) { 101 c->lazy_bind_off = lazyBindingSection->fileOff; 102 c->lazy_bind_size = lazyBindingSection->getFileSize(); 103 } 104 if (exportSection->isNeeded()) { 105 c->export_off = exportSection->fileOff; 106 c->export_size = exportSection->getFileSize(); 107 } 108 } 109 110 RebaseSection *rebaseSection; 111 BindingSection *bindingSection; 112 WeakBindingSection *weakBindingSection; 113 LazyBindingSection *lazyBindingSection; 114 ExportSection *exportSection; 115 }; 116 117 class LCDysymtab : public LoadCommand { 118 public: 119 LCDysymtab(SymtabSection *symtabSection, 120 IndirectSymtabSection *indirectSymtabSection) 121 : symtabSection(symtabSection), 122 indirectSymtabSection(indirectSymtabSection) {} 123 124 uint32_t getSize() const override { return sizeof(dysymtab_command); } 125 126 void writeTo(uint8_t *buf) const override { 127 auto *c = reinterpret_cast<dysymtab_command *>(buf); 128 c->cmd = LC_DYSYMTAB; 129 c->cmdsize = getSize(); 130 131 c->ilocalsym = 0; 132 c->iextdefsym = c->nlocalsym = symtabSection->getNumLocalSymbols(); 133 c->nextdefsym = symtabSection->getNumExternalSymbols(); 134 c->iundefsym = c->iextdefsym + c->nextdefsym; 135 c->nundefsym = symtabSection->getNumUndefinedSymbols(); 136 137 c->indirectsymoff = indirectSymtabSection->fileOff; 138 c->nindirectsyms = indirectSymtabSection->getNumSymbols(); 139 } 140 141 SymtabSection *symtabSection; 142 IndirectSymtabSection *indirectSymtabSection; 143 }; 144 145 class LCSegment : public LoadCommand { 146 public: 147 LCSegment(StringRef name, OutputSegment *seg) : name(name), seg(seg) {} 148 149 uint32_t getSize() const override { 150 return sizeof(segment_command_64) + 151 seg->numNonHiddenSections() * sizeof(section_64); 152 } 153 154 void writeTo(uint8_t *buf) const override { 155 auto *c = reinterpret_cast<segment_command_64 *>(buf); 156 buf += sizeof(segment_command_64); 157 158 c->cmd = LC_SEGMENT_64; 159 c->cmdsize = getSize(); 160 memcpy(c->segname, name.data(), name.size()); 161 c->fileoff = seg->fileOff; 162 c->maxprot = seg->maxProt; 163 c->initprot = seg->initProt; 164 165 if (seg->getSections().empty()) 166 return; 167 168 c->vmaddr = seg->firstSection()->addr; 169 c->vmsize = 170 seg->lastSection()->addr + seg->lastSection()->getSize() - c->vmaddr; 171 c->nsects = seg->numNonHiddenSections(); 172 173 for (OutputSection *osec : seg->getSections()) { 174 if (!isZeroFill(osec->flags)) { 175 assert(osec->fileOff >= seg->fileOff); 176 c->filesize = std::max( 177 c->filesize, osec->fileOff + osec->getFileSize() - seg->fileOff); 178 } 179 180 if (osec->isHidden()) 181 continue; 182 183 auto *sectHdr = reinterpret_cast<section_64 *>(buf); 184 buf += sizeof(section_64); 185 186 memcpy(sectHdr->sectname, osec->name.data(), osec->name.size()); 187 memcpy(sectHdr->segname, name.data(), name.size()); 188 189 sectHdr->addr = osec->addr; 190 sectHdr->offset = osec->fileOff; 191 sectHdr->align = Log2_32(osec->align); 192 sectHdr->flags = osec->flags; 193 sectHdr->size = osec->getSize(); 194 sectHdr->reserved1 = osec->reserved1; 195 sectHdr->reserved2 = osec->reserved2; 196 } 197 } 198 199 private: 200 StringRef name; 201 OutputSegment *seg; 202 }; 203 204 class LCMain : public LoadCommand { 205 uint32_t getSize() const override { return sizeof(entry_point_command); } 206 207 void writeTo(uint8_t *buf) const override { 208 auto *c = reinterpret_cast<entry_point_command *>(buf); 209 c->cmd = LC_MAIN; 210 c->cmdsize = getSize(); 211 212 if (config->entry->isInStubs()) 213 c->entryoff = 214 in.stubs->fileOff + config->entry->stubsIndex * target->stubSize; 215 else 216 c->entryoff = config->entry->getFileOffset(); 217 218 c->stacksize = 0; 219 } 220 }; 221 222 class LCSymtab : public LoadCommand { 223 public: 224 LCSymtab(SymtabSection *symtabSection, StringTableSection *stringTableSection) 225 : symtabSection(symtabSection), stringTableSection(stringTableSection) {} 226 227 uint32_t getSize() const override { return sizeof(symtab_command); } 228 229 void writeTo(uint8_t *buf) const override { 230 auto *c = reinterpret_cast<symtab_command *>(buf); 231 c->cmd = LC_SYMTAB; 232 c->cmdsize = getSize(); 233 c->symoff = symtabSection->fileOff; 234 c->nsyms = symtabSection->getNumSymbols(); 235 c->stroff = stringTableSection->fileOff; 236 c->strsize = stringTableSection->getFileSize(); 237 } 238 239 SymtabSection *symtabSection = nullptr; 240 StringTableSection *stringTableSection = nullptr; 241 }; 242 243 // There are several dylib load commands that share the same structure: 244 // * LC_LOAD_DYLIB 245 // * LC_ID_DYLIB 246 // * LC_REEXPORT_DYLIB 247 class LCDylib : public LoadCommand { 248 public: 249 LCDylib(LoadCommandType type, StringRef path, 250 uint32_t compatibilityVersion = 0, uint32_t currentVersion = 0) 251 : type(type), path(path), compatibilityVersion(compatibilityVersion), 252 currentVersion(currentVersion) { 253 instanceCount++; 254 } 255 256 uint32_t getSize() const override { 257 return alignTo(sizeof(dylib_command) + path.size() + 1, 8); 258 } 259 260 void writeTo(uint8_t *buf) const override { 261 auto *c = reinterpret_cast<dylib_command *>(buf); 262 buf += sizeof(dylib_command); 263 264 c->cmd = type; 265 c->cmdsize = getSize(); 266 c->dylib.name = sizeof(dylib_command); 267 c->dylib.timestamp = 0; 268 c->dylib.compatibility_version = compatibilityVersion; 269 c->dylib.current_version = currentVersion; 270 271 memcpy(buf, path.data(), path.size()); 272 buf[path.size()] = '\0'; 273 } 274 275 static uint32_t getInstanceCount() { return instanceCount; } 276 277 private: 278 LoadCommandType type; 279 StringRef path; 280 uint32_t compatibilityVersion; 281 uint32_t currentVersion; 282 static uint32_t instanceCount; 283 }; 284 285 uint32_t LCDylib::instanceCount = 0; 286 287 class LCLoadDylinker : public LoadCommand { 288 public: 289 uint32_t getSize() const override { 290 return alignTo(sizeof(dylinker_command) + path.size() + 1, 8); 291 } 292 293 void writeTo(uint8_t *buf) const override { 294 auto *c = reinterpret_cast<dylinker_command *>(buf); 295 buf += sizeof(dylinker_command); 296 297 c->cmd = LC_LOAD_DYLINKER; 298 c->cmdsize = getSize(); 299 c->name = sizeof(dylinker_command); 300 301 memcpy(buf, path.data(), path.size()); 302 buf[path.size()] = '\0'; 303 } 304 305 private: 306 // Recent versions of Darwin won't run any binary that has dyld at a 307 // different location. 308 const StringRef path = "/usr/lib/dyld"; 309 }; 310 311 class LCRPath : public LoadCommand { 312 public: 313 LCRPath(StringRef path) : path(path) {} 314 315 uint32_t getSize() const override { 316 return alignTo(sizeof(rpath_command) + path.size() + 1, WordSize); 317 } 318 319 void writeTo(uint8_t *buf) const override { 320 auto *c = reinterpret_cast<rpath_command *>(buf); 321 buf += sizeof(rpath_command); 322 323 c->cmd = LC_RPATH; 324 c->cmdsize = getSize(); 325 c->path = sizeof(rpath_command); 326 327 memcpy(buf, path.data(), path.size()); 328 buf[path.size()] = '\0'; 329 } 330 331 private: 332 StringRef path; 333 }; 334 335 class LCBuildVersion : public LoadCommand { 336 public: 337 LCBuildVersion(const PlatformInfo &platform) : platform(platform) {} 338 339 const int ntools = 1; 340 341 uint32_t getSize() const override { 342 return sizeof(build_version_command) + ntools * sizeof(build_tool_version); 343 } 344 345 void writeTo(uint8_t *buf) const override { 346 auto *c = reinterpret_cast<build_version_command *>(buf); 347 c->cmd = LC_BUILD_VERSION; 348 c->cmdsize = getSize(); 349 c->platform = static_cast<uint32_t>(platform.kind); 350 c->minos = ((platform.minimum.getMajor() << 020) | 351 (platform.minimum.getMinor().getValueOr(0) << 010) | 352 platform.minimum.getSubminor().getValueOr(0)); 353 c->sdk = ((platform.sdk.getMajor() << 020) | 354 (platform.sdk.getMinor().getValueOr(0) << 010) | 355 platform.sdk.getSubminor().getValueOr(0)); 356 c->ntools = ntools; 357 auto *t = reinterpret_cast<build_tool_version *>(&c[1]); 358 t->tool = TOOL_LD; 359 t->version = (LLVM_VERSION_MAJOR << 020) | (LLVM_VERSION_MINOR << 010) | 360 LLVM_VERSION_PATCH; 361 } 362 363 const PlatformInfo &platform; 364 }; 365 366 // Stores a unique identifier for the output file based on an MD5 hash of its 367 // contents. In order to hash the contents, we must first write them, but 368 // LC_UUID itself must be part of the written contents in order for all the 369 // offsets to be calculated correctly. We resolve this circular paradox by 370 // first writing an LC_UUID with an all-zero UUID, then updating the UUID with 371 // its real value later. 372 class LCUuid : public LoadCommand { 373 public: 374 uint32_t getSize() const override { return sizeof(uuid_command); } 375 376 void writeTo(uint8_t *buf) const override { 377 auto *c = reinterpret_cast<uuid_command *>(buf); 378 c->cmd = LC_UUID; 379 c->cmdsize = getSize(); 380 uuidBuf = c->uuid; 381 } 382 383 void writeUuid(uint64_t digest) const { 384 // xxhash only gives us 8 bytes, so put some fixed data in the other half. 385 static_assert(sizeof(uuid_command::uuid) == 16, "unexpected uuid size"); 386 memcpy(uuidBuf, "LLD\xa1UU1D", 8); 387 memcpy(uuidBuf + 8, &digest, 8); 388 389 // RFC 4122 conformance. We need to fix 4 bits in byte 6 and 2 bits in 390 // byte 8. Byte 6 is already fine due to the fixed data we put in. We don't 391 // want to lose bits of the digest in byte 8, so swap that with a byte of 392 // fixed data that happens to have the right bits set. 393 std::swap(uuidBuf[3], uuidBuf[8]); 394 395 // Claim that this is an MD5-based hash. It isn't, but this signals that 396 // this is not a time-based and not a random hash. MD5 seems like the least 397 // bad lie we can put here. 398 assert((uuidBuf[6] & 0xf0) == 0x30 && "See RFC 4122 Sections 4.2.2, 4.1.3"); 399 assert((uuidBuf[8] & 0xc0) == 0x80 && "See RFC 4122 Section 4.2.2"); 400 } 401 402 mutable uint8_t *uuidBuf; 403 }; 404 405 class LCCodeSignature : public LoadCommand { 406 public: 407 LCCodeSignature(CodeSignatureSection *section) : section(section) {} 408 409 uint32_t getSize() const override { return sizeof(linkedit_data_command); } 410 411 void writeTo(uint8_t *buf) const override { 412 auto *c = reinterpret_cast<linkedit_data_command *>(buf); 413 c->cmd = LC_CODE_SIGNATURE; 414 c->cmdsize = getSize(); 415 c->dataoff = static_cast<uint32_t>(section->fileOff); 416 c->datasize = section->getSize(); 417 } 418 419 CodeSignatureSection *section; 420 }; 421 422 } // namespace 423 424 static void prepareSymbolRelocation(lld::macho::Symbol *sym, 425 const InputSection *isec, const Reloc &r) { 426 const TargetInfo::RelocAttrs &relocAttrs = target->getRelocAttrs(r.type); 427 428 if (relocAttrs.hasAttr(RelocAttrBits::BRANCH)) { 429 prepareBranchTarget(sym); 430 } else if (relocAttrs.hasAttr(RelocAttrBits::GOT)) { 431 if (relocAttrs.hasAttr(RelocAttrBits::POINTER) || needsBinding(sym)) 432 in.got->addEntry(sym); 433 } else if (relocAttrs.hasAttr(RelocAttrBits::TLV)) { 434 if (needsBinding(sym)) 435 in.tlvPointers->addEntry(sym); 436 } else if (relocAttrs.hasAttr(RelocAttrBits::UNSIGNED)) { 437 // References from thread-local variable sections are treated as offsets 438 // relative to the start of the referent section, and therefore have no 439 // need of rebase opcodes. 440 if (!(isThreadLocalVariables(isec->flags) && isa<Defined>(sym))) 441 addNonLazyBindingEntries(sym, isec, r.offset, r.addend); 442 } 443 } 444 445 void Writer::scanRelocations() { 446 for (InputSection *isec : inputSections) { 447 if (isec->segname == segment_names::ld) { 448 prepareCompactUnwind(isec); 449 continue; 450 } 451 452 for (auto it = isec->relocs.begin(); it != isec->relocs.end(); ++it) { 453 Reloc &r = *it; 454 if (target->hasAttr(r.type, RelocAttrBits::SUBTRAHEND)) { 455 // Skip over the following UNSIGNED relocation -- it's just there as the 456 // minuend, and doesn't have the usual UNSIGNED semantics. We don't want 457 // to emit rebase opcodes for it. 458 it = std::next(it); 459 assert(isa<Defined>(it->referent.dyn_cast<lld::macho::Symbol *>())); 460 continue; 461 } 462 if (auto *sym = r.referent.dyn_cast<lld::macho::Symbol *>()) { 463 if (auto *undefined = dyn_cast<Undefined>(sym)) 464 treatUndefinedSymbol(*undefined); 465 else if (target->validateSymbolRelocation(sym, isec, r)) 466 prepareSymbolRelocation(sym, isec, r); 467 } else { 468 assert(r.referent.is<InputSection *>()); 469 if (!r.pcrel) 470 in.rebase->addEntry(isec, r.offset); 471 } 472 } 473 } 474 } 475 476 void Writer::scanSymbols() { 477 for (const macho::Symbol *sym : symtab->getSymbols()) { 478 if (const auto *defined = dyn_cast<Defined>(sym)) { 479 if (defined->overridesWeakDef) 480 in.weakBinding->addNonWeakDefinition(defined); 481 } else if (const auto *dysym = dyn_cast<DylibSymbol>(sym)) { 482 if (dysym->isDynamicLookup()) 483 continue; 484 dysym->getFile()->refState = 485 std::max(dysym->getFile()->refState, dysym->refState); 486 } 487 } 488 } 489 490 void Writer::createLoadCommands() { 491 uint8_t segIndex = 0; 492 for (OutputSegment *seg : outputSegments) { 493 in.header->addLoadCommand(make<LCSegment>(seg->name, seg)); 494 seg->index = segIndex++; 495 } 496 497 in.header->addLoadCommand(make<LCDyldInfo>( 498 in.rebase, in.binding, in.weakBinding, in.lazyBinding, in.exports)); 499 in.header->addLoadCommand(make<LCSymtab>(symtabSection, stringTableSection)); 500 in.header->addLoadCommand( 501 make<LCDysymtab>(symtabSection, indirectSymtabSection)); 502 for (StringRef path : config->runtimePaths) 503 in.header->addLoadCommand(make<LCRPath>(path)); 504 505 switch (config->outputType) { 506 case MH_EXECUTE: 507 in.header->addLoadCommand(make<LCLoadDylinker>()); 508 in.header->addLoadCommand(make<LCMain>()); 509 break; 510 case MH_DYLIB: 511 in.header->addLoadCommand(make<LCDylib>(LC_ID_DYLIB, config->installName, 512 config->dylibCompatibilityVersion, 513 config->dylibCurrentVersion)); 514 break; 515 case MH_BUNDLE: 516 break; 517 default: 518 llvm_unreachable("unhandled output file type"); 519 } 520 521 uuidCommand = make<LCUuid>(); 522 in.header->addLoadCommand(uuidCommand); 523 524 in.header->addLoadCommand(make<LCBuildVersion>(config->platform)); 525 526 int64_t dylibOrdinal = 1; 527 for (InputFile *file : inputFiles) { 528 if (auto *dylibFile = dyn_cast<DylibFile>(file)) { 529 if (dylibFile->isBundleLoader) { 530 dylibFile->ordinal = MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE; 531 // Shortcut since bundle-loader does not re-export the symbols. 532 533 dylibFile->reexport = false; 534 continue; 535 } 536 537 dylibFile->ordinal = dylibOrdinal++; 538 LoadCommandType lcType = 539 dylibFile->forceWeakImport || dylibFile->refState == RefState::Weak 540 ? LC_LOAD_WEAK_DYLIB 541 : LC_LOAD_DYLIB; 542 in.header->addLoadCommand(make<LCDylib>(lcType, dylibFile->dylibName, 543 dylibFile->compatibilityVersion, 544 dylibFile->currentVersion)); 545 546 if (dylibFile->reexport) 547 in.header->addLoadCommand( 548 make<LCDylib>(LC_REEXPORT_DYLIB, dylibFile->dylibName)); 549 } 550 } 551 552 if (codeSignatureSection) 553 in.header->addLoadCommand(make<LCCodeSignature>(codeSignatureSection)); 554 555 const uint32_t MACOS_MAXPATHLEN = 1024; 556 config->headerPad = std::max( 557 config->headerPad, (config->headerPadMaxInstallNames 558 ? LCDylib::getInstanceCount() * MACOS_MAXPATHLEN 559 : 0)); 560 } 561 562 static size_t getSymbolPriority(const SymbolPriorityEntry &entry, 563 const InputFile *f) { 564 // We don't use toString(InputFile *) here because it returns the full path 565 // for object files, and we only want the basename. 566 StringRef filename; 567 if (f->archiveName.empty()) 568 filename = path::filename(f->getName()); 569 else 570 filename = saver.save(path::filename(f->archiveName) + "(" + 571 path::filename(f->getName()) + ")"); 572 return std::max(entry.objectFiles.lookup(filename), entry.anyObjectFile); 573 } 574 575 // Each section gets assigned the priority of the highest-priority symbol it 576 // contains. 577 static DenseMap<const InputSection *, size_t> buildInputSectionPriorities() { 578 DenseMap<const InputSection *, size_t> sectionPriorities; 579 580 if (config->priorities.empty()) 581 return sectionPriorities; 582 583 auto addSym = [&](Defined &sym) { 584 auto it = config->priorities.find(sym.getName()); 585 if (it == config->priorities.end()) 586 return; 587 588 SymbolPriorityEntry &entry = it->second; 589 size_t &priority = sectionPriorities[sym.isec]; 590 priority = std::max(priority, getSymbolPriority(entry, sym.isec->file)); 591 }; 592 593 // TODO: Make sure this handles weak symbols correctly. 594 for (InputFile *file : inputFiles) 595 if (isa<ObjFile>(file)) 596 for (lld::macho::Symbol *sym : file->symbols) 597 if (auto *d = dyn_cast<Defined>(sym)) 598 addSym(*d); 599 600 return sectionPriorities; 601 } 602 603 static int segmentOrder(OutputSegment *seg) { 604 return StringSwitch<int>(seg->name) 605 .Case(segment_names::pageZero, -4) 606 .Case(segment_names::text, -3) 607 .Case(segment_names::dataConst, -2) 608 .Case(segment_names::data, -1) 609 // Make sure __LINKEDIT is the last segment (i.e. all its hidden 610 // sections must be ordered after other sections). 611 .Case(segment_names::linkEdit, std::numeric_limits<int>::max()) 612 .Default(0); 613 } 614 615 static int sectionOrder(OutputSection *osec) { 616 StringRef segname = osec->parent->name; 617 // Sections are uniquely identified by their segment + section name. 618 if (segname == segment_names::text) { 619 return StringSwitch<int>(osec->name) 620 .Case(section_names::header, -4) 621 .Case(section_names::text, -3) 622 .Case(section_names::stubs, -2) 623 .Case(section_names::stubHelper, -1) 624 .Case(section_names::unwindInfo, std::numeric_limits<int>::max() - 1) 625 .Case(section_names::ehFrame, std::numeric_limits<int>::max()) 626 .Default(0); 627 } else if (segname == segment_names::data) { 628 // For each thread spawned, dyld will initialize its TLVs by copying the 629 // address range from the start of the first thread-local data section to 630 // the end of the last one. We therefore arrange these sections contiguously 631 // to minimize the amount of memory used. Additionally, since zerofill 632 // sections must be at the end of their segments, and since TLV data 633 // sections can be zerofills, we end up putting all TLV data sections at the 634 // end of the segment. 635 switch (sectionType(osec->flags)) { 636 case S_THREAD_LOCAL_REGULAR: 637 return std::numeric_limits<int>::max() - 2; 638 case S_THREAD_LOCAL_ZEROFILL: 639 return std::numeric_limits<int>::max() - 1; 640 case S_ZEROFILL: 641 return std::numeric_limits<int>::max(); 642 default: 643 return StringSwitch<int>(osec->name) 644 .Case(section_names::laSymbolPtr, -2) 645 .Case(section_names::data, -1) 646 .Default(0); 647 } 648 } else if (segname == segment_names::linkEdit) { 649 return StringSwitch<int>(osec->name) 650 .Case(section_names::rebase, -8) 651 .Case(section_names::binding, -7) 652 .Case(section_names::weakBinding, -6) 653 .Case(section_names::lazyBinding, -5) 654 .Case(section_names::export_, -4) 655 .Case(section_names::symbolTable, -3) 656 .Case(section_names::indirectSymbolTable, -2) 657 .Case(section_names::stringTable, -1) 658 .Case(section_names::codeSignature, std::numeric_limits<int>::max()) 659 .Default(0); 660 } 661 // ZeroFill sections must always be the at the end of their segments, 662 // otherwise subsequent sections may get overwritten with zeroes at runtime. 663 if (sectionType(osec->flags) == S_ZEROFILL) 664 return std::numeric_limits<int>::max(); 665 return 0; 666 } 667 668 template <typename T, typename F> 669 static std::function<bool(T, T)> compareByOrder(F ord) { 670 return [=](T a, T b) { return ord(a) < ord(b); }; 671 } 672 673 // Sorting only can happen once all outputs have been collected. Here we sort 674 // segments, output sections within each segment, and input sections within each 675 // output segment. 676 static void sortSegmentsAndSections() { 677 llvm::stable_sort(outputSegments, 678 compareByOrder<OutputSegment *>(segmentOrder)); 679 680 DenseMap<const InputSection *, size_t> isecPriorities = 681 buildInputSectionPriorities(); 682 683 uint32_t sectionIndex = 0; 684 for (OutputSegment *seg : outputSegments) { 685 seg->sortOutputSections(compareByOrder<OutputSection *>(sectionOrder)); 686 for (OutputSection *osec : seg->getSections()) { 687 // Now that the output sections are sorted, assign the final 688 // output section indices. 689 if (!osec->isHidden()) 690 osec->index = ++sectionIndex; 691 692 if (!firstTLVDataSection && isThreadLocalData(osec->flags)) 693 firstTLVDataSection = osec; 694 695 if (!isecPriorities.empty()) { 696 if (auto *merged = dyn_cast<MergedOutputSection>(osec)) { 697 llvm::stable_sort(merged->inputs, 698 [&](InputSection *a, InputSection *b) { 699 return isecPriorities[a] > isecPriorities[b]; 700 }); 701 } 702 } 703 } 704 } 705 } 706 707 static NamePair maybeRenameSection(NamePair key) { 708 auto newNames = config->sectionRenameMap.find(key); 709 if (newNames != config->sectionRenameMap.end()) 710 return newNames->second; 711 auto newName = config->segmentRenameMap.find(key.first); 712 if (newName != config->segmentRenameMap.end()) 713 return std::make_pair(newName->second, key.second); 714 return key; 715 } 716 717 void Writer::createOutputSections() { 718 // First, create hidden sections 719 stringTableSection = make<StringTableSection>(); 720 unwindInfoSection = make<UnwindInfoSection>(); // TODO(gkm): only when no -r 721 symtabSection = make<SymtabSection>(*stringTableSection); 722 indirectSymtabSection = make<IndirectSymtabSection>(); 723 if (config->outputType == MH_EXECUTE && 724 (config->arch == AK_arm64 || config->arch == AK_arm64e)) 725 codeSignatureSection = make<CodeSignatureSection>(); 726 727 switch (config->outputType) { 728 case MH_EXECUTE: 729 make<PageZeroSection>(); 730 break; 731 case MH_DYLIB: 732 case MH_BUNDLE: 733 break; 734 default: 735 llvm_unreachable("unhandled output file type"); 736 } 737 738 // Then merge input sections into output sections. 739 MapVector<NamePair, MergedOutputSection *> mergedOutputSections; 740 for (InputSection *isec : inputSections) { 741 NamePair names = maybeRenameSection({isec->segname, isec->name}); 742 MergedOutputSection *&osec = mergedOutputSections[names]; 743 if (osec == nullptr) 744 osec = make<MergedOutputSection>(names.second); 745 osec->mergeInput(isec); 746 } 747 748 for (const auto &it : mergedOutputSections) { 749 StringRef segname = it.first.first; 750 MergedOutputSection *osec = it.second; 751 if (unwindInfoSection && segname == segment_names::ld) { 752 assert(osec->name == section_names::compactUnwind); 753 unwindInfoSection->setCompactUnwindSection(osec); 754 } else { 755 getOrCreateOutputSegment(segname)->addOutputSection(osec); 756 } 757 } 758 759 for (SyntheticSection *ssec : syntheticSections) { 760 auto it = mergedOutputSections.find({ssec->segname, ssec->name}); 761 if (it == mergedOutputSections.end()) { 762 if (ssec->isNeeded()) 763 getOrCreateOutputSegment(ssec->segname)->addOutputSection(ssec); 764 } else { 765 error("section from " + toString(it->second->firstSection()->file) + 766 " conflicts with synthetic section " + ssec->segname + "," + 767 ssec->name); 768 } 769 } 770 } 771 772 void Writer::assignAddresses(OutputSegment *seg) { 773 uint64_t pageSize = target->getPageSize(); 774 addr = alignTo(addr, pageSize); 775 fileOff = alignTo(fileOff, pageSize); 776 seg->fileOff = fileOff; 777 778 for (OutputSection *osec : seg->getSections()) { 779 if (!osec->isNeeded()) 780 continue; 781 addr = alignTo(addr, osec->align); 782 fileOff = alignTo(fileOff, osec->align); 783 osec->addr = addr; 784 osec->fileOff = isZeroFill(osec->flags) ? 0 : fileOff; 785 osec->finalize(); 786 787 addr += osec->getSize(); 788 fileOff += osec->getFileSize(); 789 } 790 seg->fileSize = fileOff - seg->fileOff; 791 } 792 793 void Writer::openFile() { 794 Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr = 795 FileOutputBuffer::create(config->outputFile, fileOff, 796 FileOutputBuffer::F_executable); 797 798 if (!bufferOrErr) 799 error("failed to open " + config->outputFile + ": " + 800 llvm::toString(bufferOrErr.takeError())); 801 else 802 buffer = std::move(*bufferOrErr); 803 } 804 805 void Writer::writeSections() { 806 uint8_t *buf = buffer->getBufferStart(); 807 for (OutputSegment *seg : outputSegments) 808 for (OutputSection *osec : seg->getSections()) 809 osec->writeTo(buf + osec->fileOff); 810 } 811 812 void Writer::writeUuid() { 813 uint64_t digest = 814 xxHash64({buffer->getBufferStart(), buffer->getBufferEnd()}); 815 uuidCommand->writeUuid(digest); 816 } 817 818 void Writer::writeCodeSignature() { 819 if (codeSignatureSection) 820 codeSignatureSection->writeHashes(buffer->getBufferStart()); 821 } 822 823 void Writer::run() { 824 // dyld requires __LINKEDIT segment to always exist (even if empty). 825 OutputSegment *linkEditSegment = 826 getOrCreateOutputSegment(segment_names::linkEdit); 827 828 prepareBranchTarget(config->entry); 829 scanRelocations(); 830 if (in.stubHelper->isNeeded()) 831 in.stubHelper->setup(); 832 scanSymbols(); 833 834 // Sort and assign sections to their respective segments. No more sections nor 835 // segments may be created after these methods run. 836 createOutputSections(); 837 sortSegmentsAndSections(); 838 839 createLoadCommands(); 840 841 // Ensure that segments (and the sections they contain) are allocated 842 // addresses in ascending order, which dyld requires. 843 // 844 // Note that at this point, __LINKEDIT sections are empty, but we need to 845 // determine addresses of other segments/sections before generating its 846 // contents. 847 for (OutputSegment *seg : outputSegments) 848 if (seg != linkEditSegment) 849 assignAddresses(seg); 850 851 // Fill __LINKEDIT contents. 852 in.rebase->finalizeContents(); 853 in.binding->finalizeContents(); 854 in.weakBinding->finalizeContents(); 855 in.lazyBinding->finalizeContents(); 856 in.exports->finalizeContents(); 857 symtabSection->finalizeContents(); 858 indirectSymtabSection->finalizeContents(); 859 860 // Now that __LINKEDIT is filled out, do a proper calculation of its 861 // addresses and offsets. 862 assignAddresses(linkEditSegment); 863 864 openFile(); 865 if (errorCount()) 866 return; 867 868 writeSections(); 869 writeUuid(); 870 writeCodeSignature(); 871 872 if (auto e = buffer->commit()) 873 error("failed to write to the output file: " + toString(std::move(e))); 874 } 875 876 void macho::writeResult() { Writer().run(); } 877 878 void macho::createSyntheticSections() { 879 in.header = make<MachHeaderSection>(); 880 in.rebase = make<RebaseSection>(); 881 in.binding = make<BindingSection>(); 882 in.weakBinding = make<WeakBindingSection>(); 883 in.lazyBinding = make<LazyBindingSection>(); 884 in.exports = make<ExportSection>(); 885 in.got = make<GotSection>(); 886 in.tlvPointers = make<TlvPointerSection>(); 887 in.lazyPointers = make<LazyPointerSection>(); 888 in.stubs = make<StubsSection>(); 889 in.stubHelper = make<StubHelperSection>(); 890 in.imageLoaderCache = make<ImageLoaderCacheSection>(); 891 } 892 893 OutputSection *macho::firstTLVDataSection = nullptr; 894