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