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