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 // treatUndefinedSymbol() can replace sym with a DylibSymbol; re-check. 466 if (!isa<Undefined>(sym) && 467 target->validateSymbolRelocation(sym, isec, r)) 468 prepareSymbolRelocation(sym, isec, r); 469 } else { 470 assert(r.referent.is<InputSection *>()); 471 if (!r.pcrel) 472 in.rebase->addEntry(isec, r.offset); 473 } 474 } 475 } 476 } 477 478 void Writer::scanSymbols() { 479 for (const macho::Symbol *sym : symtab->getSymbols()) { 480 if (const auto *defined = dyn_cast<Defined>(sym)) { 481 if (defined->overridesWeakDef) 482 in.weakBinding->addNonWeakDefinition(defined); 483 } else if (const auto *dysym = dyn_cast<DylibSymbol>(sym)) { 484 if (dysym->isDynamicLookup()) 485 continue; 486 dysym->getFile()->refState = 487 std::max(dysym->getFile()->refState, dysym->refState); 488 } 489 } 490 } 491 492 void Writer::createLoadCommands() { 493 uint8_t segIndex = 0; 494 for (OutputSegment *seg : outputSegments) { 495 in.header->addLoadCommand(make<LCSegment>(seg->name, seg)); 496 seg->index = segIndex++; 497 } 498 499 in.header->addLoadCommand(make<LCDyldInfo>( 500 in.rebase, in.binding, in.weakBinding, in.lazyBinding, in.exports)); 501 in.header->addLoadCommand(make<LCSymtab>(symtabSection, stringTableSection)); 502 in.header->addLoadCommand( 503 make<LCDysymtab>(symtabSection, indirectSymtabSection)); 504 for (StringRef path : config->runtimePaths) 505 in.header->addLoadCommand(make<LCRPath>(path)); 506 507 switch (config->outputType) { 508 case MH_EXECUTE: 509 in.header->addLoadCommand(make<LCLoadDylinker>()); 510 in.header->addLoadCommand(make<LCMain>()); 511 break; 512 case MH_DYLIB: 513 in.header->addLoadCommand(make<LCDylib>(LC_ID_DYLIB, config->installName, 514 config->dylibCompatibilityVersion, 515 config->dylibCurrentVersion)); 516 break; 517 case MH_BUNDLE: 518 break; 519 default: 520 llvm_unreachable("unhandled output file type"); 521 } 522 523 uuidCommand = make<LCUuid>(); 524 in.header->addLoadCommand(uuidCommand); 525 526 in.header->addLoadCommand(make<LCBuildVersion>(config->platform)); 527 528 int64_t dylibOrdinal = 1; 529 for (InputFile *file : inputFiles) { 530 if (auto *dylibFile = dyn_cast<DylibFile>(file)) { 531 if (dylibFile->isBundleLoader) { 532 dylibFile->ordinal = MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE; 533 // Shortcut since bundle-loader does not re-export the symbols. 534 535 dylibFile->reexport = false; 536 continue; 537 } 538 539 dylibFile->ordinal = dylibOrdinal++; 540 LoadCommandType lcType = 541 dylibFile->forceWeakImport || dylibFile->refState == RefState::Weak 542 ? LC_LOAD_WEAK_DYLIB 543 : LC_LOAD_DYLIB; 544 in.header->addLoadCommand(make<LCDylib>(lcType, dylibFile->dylibName, 545 dylibFile->compatibilityVersion, 546 dylibFile->currentVersion)); 547 548 if (dylibFile->reexport) 549 in.header->addLoadCommand( 550 make<LCDylib>(LC_REEXPORT_DYLIB, dylibFile->dylibName)); 551 } 552 } 553 554 if (codeSignatureSection) 555 in.header->addLoadCommand(make<LCCodeSignature>(codeSignatureSection)); 556 557 const uint32_t MACOS_MAXPATHLEN = 1024; 558 config->headerPad = std::max( 559 config->headerPad, (config->headerPadMaxInstallNames 560 ? LCDylib::getInstanceCount() * MACOS_MAXPATHLEN 561 : 0)); 562 } 563 564 static size_t getSymbolPriority(const SymbolPriorityEntry &entry, 565 const InputFile *f) { 566 // We don't use toString(InputFile *) here because it returns the full path 567 // for object files, and we only want the basename. 568 StringRef filename; 569 if (f->archiveName.empty()) 570 filename = path::filename(f->getName()); 571 else 572 filename = saver.save(path::filename(f->archiveName) + "(" + 573 path::filename(f->getName()) + ")"); 574 return std::max(entry.objectFiles.lookup(filename), entry.anyObjectFile); 575 } 576 577 // Each section gets assigned the priority of the highest-priority symbol it 578 // contains. 579 static DenseMap<const InputSection *, size_t> buildInputSectionPriorities() { 580 DenseMap<const InputSection *, size_t> sectionPriorities; 581 582 if (config->priorities.empty()) 583 return sectionPriorities; 584 585 auto addSym = [&](Defined &sym) { 586 auto it = config->priorities.find(sym.getName()); 587 if (it == config->priorities.end()) 588 return; 589 590 SymbolPriorityEntry &entry = it->second; 591 size_t &priority = sectionPriorities[sym.isec]; 592 priority = std::max(priority, getSymbolPriority(entry, sym.isec->file)); 593 }; 594 595 // TODO: Make sure this handles weak symbols correctly. 596 for (InputFile *file : inputFiles) 597 if (isa<ObjFile>(file)) 598 for (lld::macho::Symbol *sym : file->symbols) 599 if (auto *d = dyn_cast<Defined>(sym)) 600 addSym(*d); 601 602 return sectionPriorities; 603 } 604 605 static int segmentOrder(OutputSegment *seg) { 606 return StringSwitch<int>(seg->name) 607 .Case(segment_names::pageZero, -4) 608 .Case(segment_names::text, -3) 609 .Case(segment_names::dataConst, -2) 610 .Case(segment_names::data, -1) 611 // Make sure __LINKEDIT is the last segment (i.e. all its hidden 612 // sections must be ordered after other sections). 613 .Case(segment_names::linkEdit, std::numeric_limits<int>::max()) 614 .Default(0); 615 } 616 617 static int sectionOrder(OutputSection *osec) { 618 StringRef segname = osec->parent->name; 619 // Sections are uniquely identified by their segment + section name. 620 if (segname == segment_names::text) { 621 return StringSwitch<int>(osec->name) 622 .Case(section_names::header, -4) 623 .Case(section_names::text, -3) 624 .Case(section_names::stubs, -2) 625 .Case(section_names::stubHelper, -1) 626 .Case(section_names::unwindInfo, std::numeric_limits<int>::max() - 1) 627 .Case(section_names::ehFrame, std::numeric_limits<int>::max()) 628 .Default(0); 629 } else if (segname == segment_names::data) { 630 // For each thread spawned, dyld will initialize its TLVs by copying the 631 // address range from the start of the first thread-local data section to 632 // the end of the last one. We therefore arrange these sections contiguously 633 // to minimize the amount of memory used. Additionally, since zerofill 634 // sections must be at the end of their segments, and since TLV data 635 // sections can be zerofills, we end up putting all TLV data sections at the 636 // end of the segment. 637 switch (sectionType(osec->flags)) { 638 case S_THREAD_LOCAL_REGULAR: 639 return std::numeric_limits<int>::max() - 2; 640 case S_THREAD_LOCAL_ZEROFILL: 641 return std::numeric_limits<int>::max() - 1; 642 case S_ZEROFILL: 643 return std::numeric_limits<int>::max(); 644 default: 645 return StringSwitch<int>(osec->name) 646 .Case(section_names::laSymbolPtr, -2) 647 .Case(section_names::data, -1) 648 .Default(0); 649 } 650 } else if (segname == segment_names::linkEdit) { 651 return StringSwitch<int>(osec->name) 652 .Case(section_names::rebase, -8) 653 .Case(section_names::binding, -7) 654 .Case(section_names::weakBinding, -6) 655 .Case(section_names::lazyBinding, -5) 656 .Case(section_names::export_, -4) 657 .Case(section_names::symbolTable, -3) 658 .Case(section_names::indirectSymbolTable, -2) 659 .Case(section_names::stringTable, -1) 660 .Case(section_names::codeSignature, std::numeric_limits<int>::max()) 661 .Default(0); 662 } 663 // ZeroFill sections must always be the at the end of their segments, 664 // otherwise subsequent sections may get overwritten with zeroes at runtime. 665 if (sectionType(osec->flags) == S_ZEROFILL) 666 return std::numeric_limits<int>::max(); 667 return 0; 668 } 669 670 template <typename T, typename F> 671 static std::function<bool(T, T)> compareByOrder(F ord) { 672 return [=](T a, T b) { return ord(a) < ord(b); }; 673 } 674 675 // Sorting only can happen once all outputs have been collected. Here we sort 676 // segments, output sections within each segment, and input sections within each 677 // output segment. 678 static void sortSegmentsAndSections() { 679 llvm::stable_sort(outputSegments, 680 compareByOrder<OutputSegment *>(segmentOrder)); 681 682 DenseMap<const InputSection *, size_t> isecPriorities = 683 buildInputSectionPriorities(); 684 685 uint32_t sectionIndex = 0; 686 for (OutputSegment *seg : outputSegments) { 687 seg->sortOutputSections(compareByOrder<OutputSection *>(sectionOrder)); 688 for (OutputSection *osec : seg->getSections()) { 689 // Now that the output sections are sorted, assign the final 690 // output section indices. 691 if (!osec->isHidden()) 692 osec->index = ++sectionIndex; 693 694 if (!firstTLVDataSection && isThreadLocalData(osec->flags)) 695 firstTLVDataSection = osec; 696 697 if (!isecPriorities.empty()) { 698 if (auto *merged = dyn_cast<MergedOutputSection>(osec)) { 699 llvm::stable_sort(merged->inputs, 700 [&](InputSection *a, InputSection *b) { 701 return isecPriorities[a] > isecPriorities[b]; 702 }); 703 } 704 } 705 } 706 } 707 } 708 709 static NamePair maybeRenameSection(NamePair key) { 710 auto newNames = config->sectionRenameMap.find(key); 711 if (newNames != config->sectionRenameMap.end()) 712 return newNames->second; 713 auto newName = config->segmentRenameMap.find(key.first); 714 if (newName != config->segmentRenameMap.end()) 715 return std::make_pair(newName->second, key.second); 716 return key; 717 } 718 719 void Writer::createOutputSections() { 720 // First, create hidden sections 721 stringTableSection = make<StringTableSection>(); 722 unwindInfoSection = make<UnwindInfoSection>(); // TODO(gkm): only when no -r 723 symtabSection = make<SymtabSection>(*stringTableSection); 724 indirectSymtabSection = make<IndirectSymtabSection>(); 725 if (config->outputType == MH_EXECUTE && 726 (config->arch == AK_arm64 || config->arch == AK_arm64e)) 727 codeSignatureSection = make<CodeSignatureSection>(); 728 729 switch (config->outputType) { 730 case MH_EXECUTE: 731 make<PageZeroSection>(); 732 break; 733 case MH_DYLIB: 734 case MH_BUNDLE: 735 break; 736 default: 737 llvm_unreachable("unhandled output file type"); 738 } 739 740 // Then merge input sections into output sections. 741 MapVector<NamePair, MergedOutputSection *> mergedOutputSections; 742 for (InputSection *isec : inputSections) { 743 NamePair names = maybeRenameSection({isec->segname, isec->name}); 744 MergedOutputSection *&osec = mergedOutputSections[names]; 745 if (osec == nullptr) 746 osec = make<MergedOutputSection>(names.second); 747 osec->mergeInput(isec); 748 } 749 750 for (const auto &it : mergedOutputSections) { 751 StringRef segname = it.first.first; 752 MergedOutputSection *osec = it.second; 753 if (unwindInfoSection && segname == segment_names::ld) { 754 assert(osec->name == section_names::compactUnwind); 755 unwindInfoSection->setCompactUnwindSection(osec); 756 } else { 757 getOrCreateOutputSegment(segname)->addOutputSection(osec); 758 } 759 } 760 761 for (SyntheticSection *ssec : syntheticSections) { 762 auto it = mergedOutputSections.find({ssec->segname, ssec->name}); 763 if (it == mergedOutputSections.end()) { 764 if (ssec->isNeeded()) 765 getOrCreateOutputSegment(ssec->segname)->addOutputSection(ssec); 766 } else { 767 error("section from " + toString(it->second->firstSection()->file) + 768 " conflicts with synthetic section " + ssec->segname + "," + 769 ssec->name); 770 } 771 } 772 } 773 774 void Writer::assignAddresses(OutputSegment *seg) { 775 uint64_t pageSize = target->getPageSize(); 776 addr = alignTo(addr, pageSize); 777 fileOff = alignTo(fileOff, pageSize); 778 seg->fileOff = fileOff; 779 780 for (OutputSection *osec : seg->getSections()) { 781 if (!osec->isNeeded()) 782 continue; 783 addr = alignTo(addr, osec->align); 784 fileOff = alignTo(fileOff, osec->align); 785 osec->addr = addr; 786 osec->fileOff = isZeroFill(osec->flags) ? 0 : fileOff; 787 osec->finalize(); 788 789 addr += osec->getSize(); 790 fileOff += osec->getFileSize(); 791 } 792 seg->fileSize = fileOff - seg->fileOff; 793 } 794 795 void Writer::openFile() { 796 Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr = 797 FileOutputBuffer::create(config->outputFile, fileOff, 798 FileOutputBuffer::F_executable); 799 800 if (!bufferOrErr) 801 error("failed to open " + config->outputFile + ": " + 802 llvm::toString(bufferOrErr.takeError())); 803 else 804 buffer = std::move(*bufferOrErr); 805 } 806 807 void Writer::writeSections() { 808 uint8_t *buf = buffer->getBufferStart(); 809 for (OutputSegment *seg : outputSegments) 810 for (OutputSection *osec : seg->getSections()) 811 osec->writeTo(buf + osec->fileOff); 812 } 813 814 void Writer::writeUuid() { 815 uint64_t digest = 816 xxHash64({buffer->getBufferStart(), buffer->getBufferEnd()}); 817 uuidCommand->writeUuid(digest); 818 } 819 820 void Writer::writeCodeSignature() { 821 if (codeSignatureSection) 822 codeSignatureSection->writeHashes(buffer->getBufferStart()); 823 } 824 825 void Writer::run() { 826 // dyld requires __LINKEDIT segment to always exist (even if empty). 827 OutputSegment *linkEditSegment = 828 getOrCreateOutputSegment(segment_names::linkEdit); 829 830 prepareBranchTarget(config->entry); 831 scanRelocations(); 832 if (in.stubHelper->isNeeded()) 833 in.stubHelper->setup(); 834 scanSymbols(); 835 836 // Sort and assign sections to their respective segments. No more sections nor 837 // segments may be created after these methods run. 838 createOutputSections(); 839 sortSegmentsAndSections(); 840 841 createLoadCommands(); 842 843 // Ensure that segments (and the sections they contain) are allocated 844 // addresses in ascending order, which dyld requires. 845 // 846 // Note that at this point, __LINKEDIT sections are empty, but we need to 847 // determine addresses of other segments/sections before generating its 848 // contents. 849 for (OutputSegment *seg : outputSegments) 850 if (seg != linkEditSegment) 851 assignAddresses(seg); 852 853 // Fill __LINKEDIT contents. 854 in.rebase->finalizeContents(); 855 in.binding->finalizeContents(); 856 in.weakBinding->finalizeContents(); 857 in.lazyBinding->finalizeContents(); 858 in.exports->finalizeContents(); 859 symtabSection->finalizeContents(); 860 indirectSymtabSection->finalizeContents(); 861 862 // Now that __LINKEDIT is filled out, do a proper calculation of its 863 // addresses and offsets. 864 assignAddresses(linkEditSegment); 865 866 openFile(); 867 if (errorCount()) 868 return; 869 870 writeSections(); 871 writeUuid(); 872 writeCodeSignature(); 873 874 if (auto e = buffer->commit()) 875 error("failed to write to the output file: " + toString(std::move(e))); 876 } 877 878 void macho::writeResult() { Writer().run(); } 879 880 void macho::createSyntheticSections() { 881 in.header = make<MachHeaderSection>(); 882 in.rebase = make<RebaseSection>(); 883 in.binding = make<BindingSection>(); 884 in.weakBinding = make<WeakBindingSection>(); 885 in.lazyBinding = make<LazyBindingSection>(); 886 in.exports = make<ExportSection>(); 887 in.got = make<GotSection>(); 888 in.tlvPointers = make<TlvPointerSection>(); 889 in.lazyPointers = make<LazyPointerSection>(); 890 in.stubs = make<StubsSection>(); 891 in.stubHelper = make<StubHelperSection>(); 892 in.imageLoaderCache = make<ImageLoaderCacheSection>(); 893 } 894 895 OutputSection *macho::firstTLVDataSection = nullptr; 896