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