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(PlatformKind platform, const PlatformInfo &platformInfo) 338 : platform(platform), platformInfo(platformInfo) {} 339 340 const int ntools = 1; 341 342 uint32_t getSize() const override { 343 return sizeof(build_version_command) + ntools * sizeof(build_tool_version); 344 } 345 346 void writeTo(uint8_t *buf) const override { 347 auto *c = reinterpret_cast<build_version_command *>(buf); 348 c->cmd = LC_BUILD_VERSION; 349 c->cmdsize = getSize(); 350 c->platform = static_cast<uint32_t>(platform); 351 c->minos = ((platformInfo.minimum.getMajor() << 020) | 352 (platformInfo.minimum.getMinor().getValueOr(0) << 010) | 353 platformInfo.minimum.getSubminor().getValueOr(0)); 354 c->sdk = ((platformInfo.sdk.getMajor() << 020) | 355 (platformInfo.sdk.getMinor().getValueOr(0) << 010) | 356 platformInfo.sdk.getSubminor().getValueOr(0)); 357 c->ntools = ntools; 358 auto *t = reinterpret_cast<build_tool_version *>(&c[1]); 359 t->tool = TOOL_LD; 360 t->version = (LLVM_VERSION_MAJOR << 020) | (LLVM_VERSION_MINOR << 010) | 361 LLVM_VERSION_PATCH; 362 } 363 364 PlatformKind platform; 365 const PlatformInfo &platformInfo; 366 }; 367 368 // Stores a unique identifier for the output file based on an MD5 hash of its 369 // contents. In order to hash the contents, we must first write them, but 370 // LC_UUID itself must be part of the written contents in order for all the 371 // offsets to be calculated correctly. We resolve this circular paradox by 372 // first writing an LC_UUID with an all-zero UUID, then updating the UUID with 373 // its real value later. 374 class LCUuid : public LoadCommand { 375 public: 376 uint32_t getSize() const override { return sizeof(uuid_command); } 377 378 void writeTo(uint8_t *buf) const override { 379 auto *c = reinterpret_cast<uuid_command *>(buf); 380 c->cmd = LC_UUID; 381 c->cmdsize = getSize(); 382 uuidBuf = c->uuid; 383 } 384 385 void writeUuid(uint64_t digest) const { 386 // xxhash only gives us 8 bytes, so put some fixed data in the other half. 387 static_assert(sizeof(uuid_command::uuid) == 16, "unexpected uuid size"); 388 memcpy(uuidBuf, "LLD\xa1UU1D", 8); 389 memcpy(uuidBuf + 8, &digest, 8); 390 391 // RFC 4122 conformance. We need to fix 4 bits in byte 6 and 2 bits in 392 // byte 8. Byte 6 is already fine due to the fixed data we put in. We don't 393 // want to lose bits of the digest in byte 8, so swap that with a byte of 394 // fixed data that happens to have the right bits set. 395 std::swap(uuidBuf[3], uuidBuf[8]); 396 397 // Claim that this is an MD5-based hash. It isn't, but this signals that 398 // this is not a time-based and not a random hash. MD5 seems like the least 399 // bad lie we can put here. 400 assert((uuidBuf[6] & 0xf0) == 0x30 && "See RFC 4122 Sections 4.2.2, 4.1.3"); 401 assert((uuidBuf[8] & 0xc0) == 0x80 && "See RFC 4122 Section 4.2.2"); 402 } 403 404 mutable uint8_t *uuidBuf; 405 }; 406 407 class LCCodeSignature : public LoadCommand { 408 public: 409 LCCodeSignature(CodeSignatureSection *section) : section(section) {} 410 411 uint32_t getSize() const override { return sizeof(linkedit_data_command); } 412 413 void writeTo(uint8_t *buf) const override { 414 auto *c = reinterpret_cast<linkedit_data_command *>(buf); 415 c->cmd = LC_CODE_SIGNATURE; 416 c->cmdsize = getSize(); 417 c->dataoff = static_cast<uint32_t>(section->fileOff); 418 c->datasize = section->getSize(); 419 } 420 421 CodeSignatureSection *section; 422 }; 423 424 } // namespace 425 426 static void prepareSymbolRelocation(lld::macho::Symbol *sym, 427 const InputSection *isec, const Reloc &r) { 428 const TargetInfo::RelocAttrs &relocAttrs = target->getRelocAttrs(r.type); 429 430 if (relocAttrs.hasAttr(RelocAttrBits::BRANCH)) { 431 prepareBranchTarget(sym); 432 } else if (relocAttrs.hasAttr(RelocAttrBits::GOT)) { 433 if (relocAttrs.hasAttr(RelocAttrBits::POINTER) || needsBinding(sym)) 434 in.got->addEntry(sym); 435 } else if (relocAttrs.hasAttr(RelocAttrBits::TLV)) { 436 if (needsBinding(sym)) 437 in.tlvPointers->addEntry(sym); 438 } else if (relocAttrs.hasAttr(RelocAttrBits::UNSIGNED)) { 439 // References from thread-local variable sections are treated as offsets 440 // relative to the start of the referent section, and therefore have no 441 // need of rebase opcodes. 442 if (!(isThreadLocalVariables(isec->flags) && isa<Defined>(sym))) 443 addNonLazyBindingEntries(sym, isec, r.offset, r.addend); 444 } 445 } 446 447 void Writer::scanRelocations() { 448 for (InputSection *isec : inputSections) { 449 if (isec->segname == segment_names::ld) { 450 prepareCompactUnwind(isec); 451 continue; 452 } 453 454 for (auto it = isec->relocs.begin(); it != isec->relocs.end(); ++it) { 455 Reloc &r = *it; 456 if (target->hasAttr(r.type, RelocAttrBits::SUBTRAHEND)) { 457 // Skip over the following UNSIGNED relocation -- it's just there as the 458 // minuend, and doesn't have the usual UNSIGNED semantics. We don't want 459 // to emit rebase opcodes for it. 460 it = std::next(it); 461 assert(isa<Defined>(it->referent.dyn_cast<lld::macho::Symbol *>())); 462 continue; 463 } 464 if (auto *sym = r.referent.dyn_cast<lld::macho::Symbol *>()) { 465 if (auto *undefined = dyn_cast<Undefined>(sym)) 466 treatUndefinedSymbol(*undefined); 467 // treatUndefinedSymbol() can replace sym with a DylibSymbol; re-check. 468 if (!isa<Undefined>(sym) && 469 target->validateSymbolRelocation(sym, isec, r)) 470 prepareSymbolRelocation(sym, isec, r); 471 } else { 472 assert(r.referent.is<InputSection *>()); 473 if (!r.pcrel) 474 in.rebase->addEntry(isec, r.offset); 475 } 476 } 477 } 478 } 479 480 void Writer::scanSymbols() { 481 for (const macho::Symbol *sym : symtab->getSymbols()) { 482 if (const auto *defined = dyn_cast<Defined>(sym)) { 483 if (defined->overridesWeakDef) 484 in.weakBinding->addNonWeakDefinition(defined); 485 } else if (const auto *dysym = dyn_cast<DylibSymbol>(sym)) { 486 if (dysym->isDynamicLookup()) 487 continue; 488 dysym->getFile()->refState = 489 std::max(dysym->getFile()->refState, dysym->refState); 490 } 491 } 492 } 493 494 void Writer::createLoadCommands() { 495 uint8_t segIndex = 0; 496 for (OutputSegment *seg : outputSegments) { 497 in.header->addLoadCommand(make<LCSegment>(seg->name, seg)); 498 seg->index = segIndex++; 499 } 500 501 in.header->addLoadCommand(make<LCDyldInfo>( 502 in.rebase, in.binding, in.weakBinding, in.lazyBinding, in.exports)); 503 in.header->addLoadCommand(make<LCSymtab>(symtabSection, stringTableSection)); 504 in.header->addLoadCommand( 505 make<LCDysymtab>(symtabSection, indirectSymtabSection)); 506 for (StringRef path : config->runtimePaths) 507 in.header->addLoadCommand(make<LCRPath>(path)); 508 509 switch (config->outputType) { 510 case MH_EXECUTE: 511 in.header->addLoadCommand(make<LCLoadDylinker>()); 512 in.header->addLoadCommand(make<LCMain>()); 513 break; 514 case MH_DYLIB: 515 in.header->addLoadCommand(make<LCDylib>(LC_ID_DYLIB, config->installName, 516 config->dylibCompatibilityVersion, 517 config->dylibCurrentVersion)); 518 break; 519 case MH_BUNDLE: 520 break; 521 default: 522 llvm_unreachable("unhandled output file type"); 523 } 524 525 uuidCommand = make<LCUuid>(); 526 in.header->addLoadCommand(uuidCommand); 527 528 in.header->addLoadCommand( 529 make<LCBuildVersion>(config->target.Platform, config->platformInfo)); 530 531 int64_t dylibOrdinal = 1; 532 for (InputFile *file : inputFiles) { 533 if (auto *dylibFile = dyn_cast<DylibFile>(file)) { 534 if (dylibFile->isBundleLoader) { 535 dylibFile->ordinal = MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE; 536 // Shortcut since bundle-loader does not re-export the symbols. 537 538 dylibFile->reexport = false; 539 continue; 540 } 541 542 dylibFile->ordinal = dylibOrdinal++; 543 LoadCommandType lcType = 544 dylibFile->forceWeakImport || dylibFile->refState == RefState::Weak 545 ? LC_LOAD_WEAK_DYLIB 546 : LC_LOAD_DYLIB; 547 in.header->addLoadCommand(make<LCDylib>(lcType, dylibFile->dylibName, 548 dylibFile->compatibilityVersion, 549 dylibFile->currentVersion)); 550 551 if (dylibFile->reexport) 552 in.header->addLoadCommand( 553 make<LCDylib>(LC_REEXPORT_DYLIB, dylibFile->dylibName)); 554 } 555 } 556 557 if (codeSignatureSection) 558 in.header->addLoadCommand(make<LCCodeSignature>(codeSignatureSection)); 559 560 const uint32_t MACOS_MAXPATHLEN = 1024; 561 config->headerPad = std::max( 562 config->headerPad, (config->headerPadMaxInstallNames 563 ? LCDylib::getInstanceCount() * MACOS_MAXPATHLEN 564 : 0)); 565 } 566 567 static size_t getSymbolPriority(const SymbolPriorityEntry &entry, 568 const InputFile *f) { 569 // We don't use toString(InputFile *) here because it returns the full path 570 // for object files, and we only want the basename. 571 StringRef filename; 572 if (f->archiveName.empty()) 573 filename = path::filename(f->getName()); 574 else 575 filename = saver.save(path::filename(f->archiveName) + "(" + 576 path::filename(f->getName()) + ")"); 577 return std::max(entry.objectFiles.lookup(filename), entry.anyObjectFile); 578 } 579 580 // Each section gets assigned the priority of the highest-priority symbol it 581 // contains. 582 static DenseMap<const InputSection *, size_t> buildInputSectionPriorities() { 583 DenseMap<const InputSection *, size_t> sectionPriorities; 584 585 if (config->priorities.empty()) 586 return sectionPriorities; 587 588 auto addSym = [&](Defined &sym) { 589 auto it = config->priorities.find(sym.getName()); 590 if (it == config->priorities.end()) 591 return; 592 593 SymbolPriorityEntry &entry = it->second; 594 size_t &priority = sectionPriorities[sym.isec]; 595 priority = std::max(priority, getSymbolPriority(entry, sym.isec->file)); 596 }; 597 598 // TODO: Make sure this handles weak symbols correctly. 599 for (InputFile *file : inputFiles) 600 if (isa<ObjFile>(file)) 601 for (lld::macho::Symbol *sym : file->symbols) 602 if (auto *d = dyn_cast<Defined>(sym)) 603 addSym(*d); 604 605 return sectionPriorities; 606 } 607 608 static int segmentOrder(OutputSegment *seg) { 609 return StringSwitch<int>(seg->name) 610 .Case(segment_names::pageZero, -4) 611 .Case(segment_names::text, -3) 612 .Case(segment_names::dataConst, -2) 613 .Case(segment_names::data, -1) 614 // Make sure __LINKEDIT is the last segment (i.e. all its hidden 615 // sections must be ordered after other sections). 616 .Case(segment_names::linkEdit, std::numeric_limits<int>::max()) 617 .Default(0); 618 } 619 620 static int sectionOrder(OutputSection *osec) { 621 StringRef segname = osec->parent->name; 622 // Sections are uniquely identified by their segment + section name. 623 if (segname == segment_names::text) { 624 return StringSwitch<int>(osec->name) 625 .Case(section_names::header, -4) 626 .Case(section_names::text, -3) 627 .Case(section_names::stubs, -2) 628 .Case(section_names::stubHelper, -1) 629 .Case(section_names::unwindInfo, std::numeric_limits<int>::max() - 1) 630 .Case(section_names::ehFrame, std::numeric_limits<int>::max()) 631 .Default(0); 632 } else if (segname == segment_names::data) { 633 // For each thread spawned, dyld will initialize its TLVs by copying the 634 // address range from the start of the first thread-local data section to 635 // the end of the last one. We therefore arrange these sections contiguously 636 // to minimize the amount of memory used. Additionally, since zerofill 637 // sections must be at the end of their segments, and since TLV data 638 // sections can be zerofills, we end up putting all TLV data sections at the 639 // end of the segment. 640 switch (sectionType(osec->flags)) { 641 case S_THREAD_LOCAL_REGULAR: 642 return std::numeric_limits<int>::max() - 2; 643 case S_THREAD_LOCAL_ZEROFILL: 644 return std::numeric_limits<int>::max() - 1; 645 case S_ZEROFILL: 646 return std::numeric_limits<int>::max(); 647 default: 648 return StringSwitch<int>(osec->name) 649 .Case(section_names::laSymbolPtr, -2) 650 .Case(section_names::data, -1) 651 .Default(0); 652 } 653 } else if (segname == segment_names::linkEdit) { 654 return StringSwitch<int>(osec->name) 655 .Case(section_names::rebase, -8) 656 .Case(section_names::binding, -7) 657 .Case(section_names::weakBinding, -6) 658 .Case(section_names::lazyBinding, -5) 659 .Case(section_names::export_, -4) 660 .Case(section_names::symbolTable, -3) 661 .Case(section_names::indirectSymbolTable, -2) 662 .Case(section_names::stringTable, -1) 663 .Case(section_names::codeSignature, std::numeric_limits<int>::max()) 664 .Default(0); 665 } 666 // ZeroFill sections must always be the at the end of their segments, 667 // otherwise subsequent sections may get overwritten with zeroes at runtime. 668 if (sectionType(osec->flags) == S_ZEROFILL) 669 return std::numeric_limits<int>::max(); 670 return 0; 671 } 672 673 template <typename T, typename F> 674 static std::function<bool(T, T)> compareByOrder(F ord) { 675 return [=](T a, T b) { return ord(a) < ord(b); }; 676 } 677 678 // Sorting only can happen once all outputs have been collected. Here we sort 679 // segments, output sections within each segment, and input sections within each 680 // output segment. 681 static void sortSegmentsAndSections() { 682 llvm::stable_sort(outputSegments, 683 compareByOrder<OutputSegment *>(segmentOrder)); 684 685 DenseMap<const InputSection *, size_t> isecPriorities = 686 buildInputSectionPriorities(); 687 688 uint32_t sectionIndex = 0; 689 for (OutputSegment *seg : outputSegments) { 690 seg->sortOutputSections(compareByOrder<OutputSection *>(sectionOrder)); 691 for (OutputSection *osec : seg->getSections()) { 692 // Now that the output sections are sorted, assign the final 693 // output section indices. 694 if (!osec->isHidden()) 695 osec->index = ++sectionIndex; 696 697 if (!firstTLVDataSection && isThreadLocalData(osec->flags)) 698 firstTLVDataSection = osec; 699 700 if (!isecPriorities.empty()) { 701 if (auto *merged = dyn_cast<MergedOutputSection>(osec)) { 702 llvm::stable_sort(merged->inputs, 703 [&](InputSection *a, InputSection *b) { 704 return isecPriorities[a] > isecPriorities[b]; 705 }); 706 } 707 } 708 } 709 } 710 } 711 712 static NamePair maybeRenameSection(NamePair key) { 713 auto newNames = config->sectionRenameMap.find(key); 714 if (newNames != config->sectionRenameMap.end()) 715 return newNames->second; 716 auto newName = config->segmentRenameMap.find(key.first); 717 if (newName != config->segmentRenameMap.end()) 718 return std::make_pair(newName->second, key.second); 719 return key; 720 } 721 722 void Writer::createOutputSections() { 723 // First, create hidden sections 724 stringTableSection = make<StringTableSection>(); 725 unwindInfoSection = make<UnwindInfoSection>(); // TODO(gkm): only when no -r 726 symtabSection = make<SymtabSection>(*stringTableSection); 727 indirectSymtabSection = make<IndirectSymtabSection>(); 728 if (config->adhocCodesign) 729 codeSignatureSection = make<CodeSignatureSection>(); 730 731 switch (config->outputType) { 732 case MH_EXECUTE: 733 make<PageZeroSection>(); 734 break; 735 case MH_DYLIB: 736 case MH_BUNDLE: 737 break; 738 default: 739 llvm_unreachable("unhandled output file type"); 740 } 741 742 // Then merge input sections into output sections. 743 MapVector<NamePair, MergedOutputSection *> mergedOutputSections; 744 for (InputSection *isec : inputSections) { 745 NamePair names = maybeRenameSection({isec->segname, isec->name}); 746 MergedOutputSection *&osec = mergedOutputSections[names]; 747 if (osec == nullptr) 748 osec = make<MergedOutputSection>(names.second); 749 osec->mergeInput(isec); 750 } 751 752 for (const auto &it : mergedOutputSections) { 753 StringRef segname = it.first.first; 754 MergedOutputSection *osec = it.second; 755 if (unwindInfoSection && segname == segment_names::ld) { 756 assert(osec->name == section_names::compactUnwind); 757 unwindInfoSection->setCompactUnwindSection(osec); 758 } else { 759 getOrCreateOutputSegment(segname)->addOutputSection(osec); 760 } 761 } 762 763 for (SyntheticSection *ssec : syntheticSections) { 764 auto it = mergedOutputSections.find({ssec->segname, ssec->name}); 765 if (it == mergedOutputSections.end()) { 766 if (ssec->isNeeded()) 767 getOrCreateOutputSegment(ssec->segname)->addOutputSection(ssec); 768 } else { 769 error("section from " + toString(it->second->firstSection()->file) + 770 " conflicts with synthetic section " + ssec->segname + "," + 771 ssec->name); 772 } 773 } 774 } 775 776 void Writer::assignAddresses(OutputSegment *seg) { 777 uint64_t pageSize = target->getPageSize(); 778 addr = alignTo(addr, pageSize); 779 fileOff = alignTo(fileOff, pageSize); 780 seg->fileOff = fileOff; 781 782 for (OutputSection *osec : seg->getSections()) { 783 if (!osec->isNeeded()) 784 continue; 785 addr = alignTo(addr, osec->align); 786 fileOff = alignTo(fileOff, osec->align); 787 osec->addr = addr; 788 osec->fileOff = isZeroFill(osec->flags) ? 0 : fileOff; 789 osec->finalize(); 790 791 addr += osec->getSize(); 792 fileOff += osec->getFileSize(); 793 } 794 seg->fileSize = fileOff - seg->fileOff; 795 } 796 797 void Writer::openFile() { 798 Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr = 799 FileOutputBuffer::create(config->outputFile, fileOff, 800 FileOutputBuffer::F_executable); 801 802 if (!bufferOrErr) 803 error("failed to open " + config->outputFile + ": " + 804 llvm::toString(bufferOrErr.takeError())); 805 else 806 buffer = std::move(*bufferOrErr); 807 } 808 809 void Writer::writeSections() { 810 uint8_t *buf = buffer->getBufferStart(); 811 for (OutputSegment *seg : outputSegments) 812 for (OutputSection *osec : seg->getSections()) 813 osec->writeTo(buf + osec->fileOff); 814 } 815 816 void Writer::writeUuid() { 817 uint64_t digest = 818 xxHash64({buffer->getBufferStart(), buffer->getBufferEnd()}); 819 uuidCommand->writeUuid(digest); 820 } 821 822 void Writer::writeCodeSignature() { 823 if (codeSignatureSection) 824 codeSignatureSection->writeHashes(buffer->getBufferStart()); 825 } 826 827 void Writer::run() { 828 // dyld requires __LINKEDIT segment to always exist (even if empty). 829 OutputSegment *linkEditSegment = 830 getOrCreateOutputSegment(segment_names::linkEdit); 831 832 prepareBranchTarget(config->entry); 833 scanRelocations(); 834 if (in.stubHelper->isNeeded()) 835 in.stubHelper->setup(); 836 scanSymbols(); 837 838 // Sort and assign sections to their respective segments. No more sections nor 839 // segments may be created after these methods run. 840 createOutputSections(); 841 sortSegmentsAndSections(); 842 843 createLoadCommands(); 844 845 // Ensure that segments (and the sections they contain) are allocated 846 // addresses in ascending order, which dyld requires. 847 // 848 // Note that at this point, __LINKEDIT sections are empty, but we need to 849 // determine addresses of other segments/sections before generating its 850 // contents. 851 for (OutputSegment *seg : outputSegments) 852 if (seg != linkEditSegment) 853 assignAddresses(seg); 854 855 // Fill __LINKEDIT contents. 856 in.rebase->finalizeContents(); 857 in.binding->finalizeContents(); 858 in.weakBinding->finalizeContents(); 859 in.lazyBinding->finalizeContents(); 860 in.exports->finalizeContents(); 861 symtabSection->finalizeContents(); 862 indirectSymtabSection->finalizeContents(); 863 864 // Now that __LINKEDIT is filled out, do a proper calculation of its 865 // addresses and offsets. 866 assignAddresses(linkEditSegment); 867 868 openFile(); 869 if (errorCount()) 870 return; 871 872 writeSections(); 873 writeUuid(); 874 writeCodeSignature(); 875 876 if (auto e = buffer->commit()) 877 error("failed to write to the output file: " + toString(std::move(e))); 878 } 879 880 void macho::writeResult() { Writer().run(); } 881 882 void macho::createSyntheticSections() { 883 in.header = make<MachHeaderSection>(); 884 in.rebase = make<RebaseSection>(); 885 in.binding = make<BindingSection>(); 886 in.weakBinding = make<WeakBindingSection>(); 887 in.lazyBinding = make<LazyBindingSection>(); 888 in.exports = make<ExportSection>(); 889 in.got = make<GotSection>(); 890 in.tlvPointers = make<TlvPointerSection>(); 891 in.lazyPointers = make<LazyPointerSection>(); 892 in.stubs = make<StubsSection>(); 893 in.stubHelper = make<StubHelperSection>(); 894 in.imageLoaderCache = make<ImageLoaderCacheSection>(); 895 } 896 897 OutputSection *macho::firstTLVDataSection = nullptr; 898