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 "ConcatOutputSection.h" 11 #include "Config.h" 12 #include "InputFiles.h" 13 #include "InputSection.h" 14 #include "MapFile.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 DataInCodeSection *dataInCodeSection = nullptr; 75 FunctionStartsSection *functionStartsSection = nullptr; 76 77 LCUuid *uuidCommand = nullptr; 78 OutputSegment *linkEditSegment = nullptr; 79 }; 80 81 // LC_DYLD_INFO_ONLY stores the offsets of symbol import/export information. 82 class LCDyldInfo final : public LoadCommand { 83 public: 84 LCDyldInfo(RebaseSection *rebaseSection, BindingSection *bindingSection, 85 WeakBindingSection *weakBindingSection, 86 LazyBindingSection *lazyBindingSection, 87 ExportSection *exportSection) 88 : rebaseSection(rebaseSection), bindingSection(bindingSection), 89 weakBindingSection(weakBindingSection), 90 lazyBindingSection(lazyBindingSection), exportSection(exportSection) {} 91 92 uint32_t getSize() const override { return sizeof(dyld_info_command); } 93 94 void writeTo(uint8_t *buf) const override { 95 auto *c = reinterpret_cast<dyld_info_command *>(buf); 96 c->cmd = LC_DYLD_INFO_ONLY; 97 c->cmdsize = getSize(); 98 if (rebaseSection->isNeeded()) { 99 c->rebase_off = rebaseSection->fileOff; 100 c->rebase_size = rebaseSection->getFileSize(); 101 } 102 if (bindingSection->isNeeded()) { 103 c->bind_off = bindingSection->fileOff; 104 c->bind_size = bindingSection->getFileSize(); 105 } 106 if (weakBindingSection->isNeeded()) { 107 c->weak_bind_off = weakBindingSection->fileOff; 108 c->weak_bind_size = weakBindingSection->getFileSize(); 109 } 110 if (lazyBindingSection->isNeeded()) { 111 c->lazy_bind_off = lazyBindingSection->fileOff; 112 c->lazy_bind_size = lazyBindingSection->getFileSize(); 113 } 114 if (exportSection->isNeeded()) { 115 c->export_off = exportSection->fileOff; 116 c->export_size = exportSection->getFileSize(); 117 } 118 } 119 120 RebaseSection *rebaseSection; 121 BindingSection *bindingSection; 122 WeakBindingSection *weakBindingSection; 123 LazyBindingSection *lazyBindingSection; 124 ExportSection *exportSection; 125 }; 126 127 class LCFunctionStarts final : public LoadCommand { 128 public: 129 explicit LCFunctionStarts(FunctionStartsSection *functionStartsSection) 130 : functionStartsSection(functionStartsSection) {} 131 132 uint32_t getSize() const override { return sizeof(linkedit_data_command); } 133 134 void writeTo(uint8_t *buf) const override { 135 auto *c = reinterpret_cast<linkedit_data_command *>(buf); 136 c->cmd = LC_FUNCTION_STARTS; 137 c->cmdsize = getSize(); 138 c->dataoff = functionStartsSection->fileOff; 139 c->datasize = functionStartsSection->getFileSize(); 140 } 141 142 private: 143 FunctionStartsSection *functionStartsSection; 144 }; 145 146 class LCDataInCode final : public LoadCommand { 147 public: 148 explicit LCDataInCode(DataInCodeSection *dataInCodeSection) 149 : dataInCodeSection(dataInCodeSection) {} 150 151 uint32_t getSize() const override { return sizeof(linkedit_data_command); } 152 153 void writeTo(uint8_t *buf) const override { 154 auto *c = reinterpret_cast<linkedit_data_command *>(buf); 155 c->cmd = LC_DATA_IN_CODE; 156 c->cmdsize = getSize(); 157 c->dataoff = dataInCodeSection->fileOff; 158 c->datasize = dataInCodeSection->getFileSize(); 159 } 160 161 private: 162 DataInCodeSection *dataInCodeSection; 163 }; 164 165 class LCDysymtab final : public LoadCommand { 166 public: 167 LCDysymtab(SymtabSection *symtabSection, 168 IndirectSymtabSection *indirectSymtabSection) 169 : symtabSection(symtabSection), 170 indirectSymtabSection(indirectSymtabSection) {} 171 172 uint32_t getSize() const override { return sizeof(dysymtab_command); } 173 174 void writeTo(uint8_t *buf) const override { 175 auto *c = reinterpret_cast<dysymtab_command *>(buf); 176 c->cmd = LC_DYSYMTAB; 177 c->cmdsize = getSize(); 178 179 c->ilocalsym = 0; 180 c->iextdefsym = c->nlocalsym = symtabSection->getNumLocalSymbols(); 181 c->nextdefsym = symtabSection->getNumExternalSymbols(); 182 c->iundefsym = c->iextdefsym + c->nextdefsym; 183 c->nundefsym = symtabSection->getNumUndefinedSymbols(); 184 185 c->indirectsymoff = indirectSymtabSection->fileOff; 186 c->nindirectsyms = indirectSymtabSection->getNumSymbols(); 187 } 188 189 SymtabSection *symtabSection; 190 IndirectSymtabSection *indirectSymtabSection; 191 }; 192 193 template <class LP> class LCSegment final : public LoadCommand { 194 public: 195 LCSegment(StringRef name, OutputSegment *seg) : name(name), seg(seg) {} 196 197 uint32_t getSize() const override { 198 return sizeof(typename LP::segment_command) + 199 seg->numNonHiddenSections() * sizeof(typename LP::section); 200 } 201 202 void writeTo(uint8_t *buf) const override { 203 using SegmentCommand = typename LP::segment_command; 204 using Section = typename LP::section; 205 206 auto *c = reinterpret_cast<SegmentCommand *>(buf); 207 buf += sizeof(SegmentCommand); 208 209 c->cmd = LP::segmentLCType; 210 c->cmdsize = getSize(); 211 memcpy(c->segname, name.data(), name.size()); 212 c->fileoff = seg->fileOff; 213 c->maxprot = seg->maxProt; 214 c->initprot = seg->initProt; 215 216 if (seg->getSections().empty()) 217 return; 218 219 c->vmaddr = seg->firstSection()->addr; 220 c->vmsize = seg->vmSize; 221 c->filesize = seg->fileSize; 222 c->nsects = seg->numNonHiddenSections(); 223 224 for (const OutputSection *osec : seg->getSections()) { 225 if (osec->isHidden()) 226 continue; 227 228 auto *sectHdr = reinterpret_cast<Section *>(buf); 229 buf += sizeof(Section); 230 231 memcpy(sectHdr->sectname, osec->name.data(), osec->name.size()); 232 memcpy(sectHdr->segname, name.data(), name.size()); 233 234 sectHdr->addr = osec->addr; 235 sectHdr->offset = osec->fileOff; 236 sectHdr->align = Log2_32(osec->align); 237 sectHdr->flags = osec->flags; 238 sectHdr->size = osec->getSize(); 239 sectHdr->reserved1 = osec->reserved1; 240 sectHdr->reserved2 = osec->reserved2; 241 } 242 } 243 244 private: 245 StringRef name; 246 OutputSegment *seg; 247 }; 248 249 class LCMain final : public LoadCommand { 250 uint32_t getSize() const override { 251 return sizeof(structs::entry_point_command); 252 } 253 254 void writeTo(uint8_t *buf) const override { 255 auto *c = reinterpret_cast<structs::entry_point_command *>(buf); 256 c->cmd = LC_MAIN; 257 c->cmdsize = getSize(); 258 259 if (config->entry->isInStubs()) 260 c->entryoff = 261 in.stubs->fileOff + config->entry->stubsIndex * target->stubSize; 262 else 263 c->entryoff = config->entry->getVA() - in.header->addr; 264 265 c->stacksize = 0; 266 } 267 }; 268 269 class LCSymtab final : public LoadCommand { 270 public: 271 LCSymtab(SymtabSection *symtabSection, StringTableSection *stringTableSection) 272 : symtabSection(symtabSection), stringTableSection(stringTableSection) {} 273 274 uint32_t getSize() const override { return sizeof(symtab_command); } 275 276 void writeTo(uint8_t *buf) const override { 277 auto *c = reinterpret_cast<symtab_command *>(buf); 278 c->cmd = LC_SYMTAB; 279 c->cmdsize = getSize(); 280 c->symoff = symtabSection->fileOff; 281 c->nsyms = symtabSection->getNumSymbols(); 282 c->stroff = stringTableSection->fileOff; 283 c->strsize = stringTableSection->getFileSize(); 284 } 285 286 SymtabSection *symtabSection = nullptr; 287 StringTableSection *stringTableSection = nullptr; 288 }; 289 290 // There are several dylib load commands that share the same structure: 291 // * LC_LOAD_DYLIB 292 // * LC_ID_DYLIB 293 // * LC_REEXPORT_DYLIB 294 class LCDylib final : public LoadCommand { 295 public: 296 LCDylib(LoadCommandType type, StringRef path, 297 uint32_t compatibilityVersion = 0, uint32_t currentVersion = 0) 298 : type(type), path(path), compatibilityVersion(compatibilityVersion), 299 currentVersion(currentVersion) { 300 instanceCount++; 301 } 302 303 uint32_t getSize() const override { 304 return alignTo(sizeof(dylib_command) + path.size() + 1, 8); 305 } 306 307 void writeTo(uint8_t *buf) const override { 308 auto *c = reinterpret_cast<dylib_command *>(buf); 309 buf += sizeof(dylib_command); 310 311 c->cmd = type; 312 c->cmdsize = getSize(); 313 c->dylib.name = sizeof(dylib_command); 314 c->dylib.timestamp = 0; 315 c->dylib.compatibility_version = compatibilityVersion; 316 c->dylib.current_version = currentVersion; 317 318 memcpy(buf, path.data(), path.size()); 319 buf[path.size()] = '\0'; 320 } 321 322 static uint32_t getInstanceCount() { return instanceCount; } 323 324 private: 325 LoadCommandType type; 326 StringRef path; 327 uint32_t compatibilityVersion; 328 uint32_t currentVersion; 329 static uint32_t instanceCount; 330 }; 331 332 uint32_t LCDylib::instanceCount = 0; 333 334 class LCLoadDylinker final : public LoadCommand { 335 public: 336 uint32_t getSize() const override { 337 return alignTo(sizeof(dylinker_command) + path.size() + 1, 8); 338 } 339 340 void writeTo(uint8_t *buf) const override { 341 auto *c = reinterpret_cast<dylinker_command *>(buf); 342 buf += sizeof(dylinker_command); 343 344 c->cmd = LC_LOAD_DYLINKER; 345 c->cmdsize = getSize(); 346 c->name = sizeof(dylinker_command); 347 348 memcpy(buf, path.data(), path.size()); 349 buf[path.size()] = '\0'; 350 } 351 352 private: 353 // Recent versions of Darwin won't run any binary that has dyld at a 354 // different location. 355 const StringRef path = "/usr/lib/dyld"; 356 }; 357 358 class LCRPath final : public LoadCommand { 359 public: 360 explicit LCRPath(StringRef path) : path(path) {} 361 362 uint32_t getSize() const override { 363 return alignTo(sizeof(rpath_command) + path.size() + 1, target->wordSize); 364 } 365 366 void writeTo(uint8_t *buf) const override { 367 auto *c = reinterpret_cast<rpath_command *>(buf); 368 buf += sizeof(rpath_command); 369 370 c->cmd = LC_RPATH; 371 c->cmdsize = getSize(); 372 c->path = sizeof(rpath_command); 373 374 memcpy(buf, path.data(), path.size()); 375 buf[path.size()] = '\0'; 376 } 377 378 private: 379 StringRef path; 380 }; 381 382 class LCMinVersion final : public LoadCommand { 383 public: 384 explicit LCMinVersion(const PlatformInfo &platformInfo) 385 : platformInfo(platformInfo) {} 386 387 uint32_t getSize() const override { return sizeof(version_min_command); } 388 389 void writeTo(uint8_t *buf) const override { 390 auto *c = reinterpret_cast<version_min_command *>(buf); 391 switch (platformInfo.target.Platform) { 392 case PlatformKind::macOS: 393 c->cmd = LC_VERSION_MIN_MACOSX; 394 break; 395 case PlatformKind::iOS: 396 case PlatformKind::iOSSimulator: 397 c->cmd = LC_VERSION_MIN_IPHONEOS; 398 break; 399 case PlatformKind::tvOS: 400 case PlatformKind::tvOSSimulator: 401 c->cmd = LC_VERSION_MIN_TVOS; 402 break; 403 case PlatformKind::watchOS: 404 case PlatformKind::watchOSSimulator: 405 c->cmd = LC_VERSION_MIN_WATCHOS; 406 break; 407 default: 408 llvm_unreachable("invalid platform"); 409 break; 410 } 411 c->cmdsize = getSize(); 412 c->version = encodeVersion(platformInfo.minimum); 413 c->sdk = encodeVersion(platformInfo.sdk); 414 } 415 416 private: 417 const PlatformInfo &platformInfo; 418 }; 419 420 class LCBuildVersion final : public LoadCommand { 421 public: 422 explicit LCBuildVersion(const PlatformInfo &platformInfo) 423 : platformInfo(platformInfo) {} 424 425 const int ntools = 1; 426 427 uint32_t getSize() const override { 428 return sizeof(build_version_command) + ntools * sizeof(build_tool_version); 429 } 430 431 void writeTo(uint8_t *buf) const override { 432 auto *c = reinterpret_cast<build_version_command *>(buf); 433 c->cmd = LC_BUILD_VERSION; 434 c->cmdsize = getSize(); 435 c->platform = static_cast<uint32_t>(platformInfo.target.Platform); 436 c->minos = encodeVersion(platformInfo.minimum); 437 c->sdk = encodeVersion(platformInfo.sdk); 438 c->ntools = ntools; 439 auto *t = reinterpret_cast<build_tool_version *>(&c[1]); 440 t->tool = TOOL_LD; 441 t->version = encodeVersion(llvm::VersionTuple( 442 LLVM_VERSION_MAJOR, LLVM_VERSION_MINOR, LLVM_VERSION_PATCH)); 443 } 444 445 private: 446 const PlatformInfo &platformInfo; 447 }; 448 449 // Stores a unique identifier for the output file based on an MD5 hash of its 450 // contents. In order to hash the contents, we must first write them, but 451 // LC_UUID itself must be part of the written contents in order for all the 452 // offsets to be calculated correctly. We resolve this circular paradox by 453 // first writing an LC_UUID with an all-zero UUID, then updating the UUID with 454 // its real value later. 455 class LCUuid final : public LoadCommand { 456 public: 457 uint32_t getSize() const override { return sizeof(uuid_command); } 458 459 void writeTo(uint8_t *buf) const override { 460 auto *c = reinterpret_cast<uuid_command *>(buf); 461 c->cmd = LC_UUID; 462 c->cmdsize = getSize(); 463 uuidBuf = c->uuid; 464 } 465 466 void writeUuid(uint64_t digest) const { 467 // xxhash only gives us 8 bytes, so put some fixed data in the other half. 468 static_assert(sizeof(uuid_command::uuid) == 16, "unexpected uuid size"); 469 memcpy(uuidBuf, "LLD\xa1UU1D", 8); 470 memcpy(uuidBuf + 8, &digest, 8); 471 472 // RFC 4122 conformance. We need to fix 4 bits in byte 6 and 2 bits in 473 // byte 8. Byte 6 is already fine due to the fixed data we put in. We don't 474 // want to lose bits of the digest in byte 8, so swap that with a byte of 475 // fixed data that happens to have the right bits set. 476 std::swap(uuidBuf[3], uuidBuf[8]); 477 478 // Claim that this is an MD5-based hash. It isn't, but this signals that 479 // this is not a time-based and not a random hash. MD5 seems like the least 480 // bad lie we can put here. 481 assert((uuidBuf[6] & 0xf0) == 0x30 && "See RFC 4122 Sections 4.2.2, 4.1.3"); 482 assert((uuidBuf[8] & 0xc0) == 0x80 && "See RFC 4122 Section 4.2.2"); 483 } 484 485 mutable uint8_t *uuidBuf; 486 }; 487 488 template <class LP> class LCEncryptionInfo final : public LoadCommand { 489 public: 490 uint32_t getSize() const override { 491 return sizeof(typename LP::encryption_info_command); 492 } 493 494 void writeTo(uint8_t *buf) const override { 495 using EncryptionInfo = typename LP::encryption_info_command; 496 auto *c = reinterpret_cast<EncryptionInfo *>(buf); 497 buf += sizeof(EncryptionInfo); 498 c->cmd = LP::encryptionInfoLCType; 499 c->cmdsize = getSize(); 500 c->cryptoff = in.header->getSize(); 501 auto it = find_if(outputSegments, [](const OutputSegment *seg) { 502 return seg->name == segment_names::text; 503 }); 504 assert(it != outputSegments.end()); 505 c->cryptsize = (*it)->fileSize - c->cryptoff; 506 } 507 }; 508 509 class LCCodeSignature final : public LoadCommand { 510 public: 511 LCCodeSignature(CodeSignatureSection *section) : section(section) {} 512 513 uint32_t getSize() const override { return sizeof(linkedit_data_command); } 514 515 void writeTo(uint8_t *buf) const override { 516 auto *c = reinterpret_cast<linkedit_data_command *>(buf); 517 c->cmd = LC_CODE_SIGNATURE; 518 c->cmdsize = getSize(); 519 c->dataoff = static_cast<uint32_t>(section->fileOff); 520 c->datasize = section->getSize(); 521 } 522 523 CodeSignatureSection *section; 524 }; 525 526 } // namespace 527 528 // Add stubs and bindings where necessary (e.g. if the symbol is a 529 // DylibSymbol.) 530 static void prepareBranchTarget(Symbol *sym) { 531 if (auto *dysym = dyn_cast<DylibSymbol>(sym)) { 532 if (in.stubs->addEntry(dysym)) { 533 if (sym->isWeakDef()) { 534 in.binding->addEntry(dysym, in.lazyPointers->isec, 535 sym->stubsIndex * target->wordSize); 536 in.weakBinding->addEntry(sym, in.lazyPointers->isec, 537 sym->stubsIndex * target->wordSize); 538 } else { 539 in.lazyBinding->addEntry(dysym); 540 } 541 } 542 } else if (auto *defined = dyn_cast<Defined>(sym)) { 543 if (defined->isExternalWeakDef()) { 544 if (in.stubs->addEntry(sym)) { 545 in.rebase->addEntry(in.lazyPointers->isec, 546 sym->stubsIndex * target->wordSize); 547 in.weakBinding->addEntry(sym, in.lazyPointers->isec, 548 sym->stubsIndex * target->wordSize); 549 } 550 } 551 } else { 552 llvm_unreachable("invalid branch target symbol type"); 553 } 554 } 555 556 // Can a symbol's address can only be resolved at runtime? 557 static bool needsBinding(const Symbol *sym) { 558 if (isa<DylibSymbol>(sym)) 559 return true; 560 if (const auto *defined = dyn_cast<Defined>(sym)) 561 return defined->isExternalWeakDef(); 562 return false; 563 } 564 565 static void prepareSymbolRelocation(Symbol *sym, const InputSection *isec, 566 const Reloc &r) { 567 const RelocAttrs &relocAttrs = target->getRelocAttrs(r.type); 568 569 if (relocAttrs.hasAttr(RelocAttrBits::BRANCH)) { 570 prepareBranchTarget(sym); 571 } else if (relocAttrs.hasAttr(RelocAttrBits::GOT)) { 572 if (relocAttrs.hasAttr(RelocAttrBits::POINTER) || needsBinding(sym)) 573 in.got->addEntry(sym); 574 } else if (relocAttrs.hasAttr(RelocAttrBits::TLV)) { 575 if (needsBinding(sym)) 576 in.tlvPointers->addEntry(sym); 577 } else if (relocAttrs.hasAttr(RelocAttrBits::UNSIGNED)) { 578 // References from thread-local variable sections are treated as offsets 579 // relative to the start of the referent section, and therefore have no 580 // need of rebase opcodes. 581 if (!(isThreadLocalVariables(isec->flags) && isa<Defined>(sym))) 582 addNonLazyBindingEntries(sym, isec, r.offset, r.addend); 583 } 584 } 585 586 void Writer::scanRelocations() { 587 TimeTraceScope timeScope("Scan relocations"); 588 for (InputSection *isec : inputSections) { 589 if (!isa<ConcatInputSection>(isec)) 590 continue; 591 auto concatIsec = cast<ConcatInputSection>(isec); 592 593 if (concatIsec->shouldOmitFromOutput()) 594 continue; 595 596 if (concatIsec->segname == segment_names::ld) { 597 in.unwindInfo->prepareRelocations(concatIsec); 598 continue; 599 } 600 601 for (auto it = isec->relocs.begin(); it != isec->relocs.end(); ++it) { 602 Reloc &r = *it; 603 if (target->hasAttr(r.type, RelocAttrBits::SUBTRAHEND)) { 604 // Skip over the following UNSIGNED relocation -- it's just there as the 605 // minuend, and doesn't have the usual UNSIGNED semantics. We don't want 606 // to emit rebase opcodes for it. 607 it++; 608 continue; 609 } 610 if (auto *sym = r.referent.dyn_cast<Symbol *>()) { 611 if (auto *undefined = dyn_cast<Undefined>(sym)) 612 treatUndefinedSymbol(*undefined); 613 // treatUndefinedSymbol() can replace sym with a DylibSymbol; re-check. 614 if (!isa<Undefined>(sym) && validateSymbolRelocation(sym, isec, r)) 615 prepareSymbolRelocation(sym, isec, r); 616 } else { 617 assert(r.referent.is<InputSection *>()); 618 if (!r.pcrel) 619 in.rebase->addEntry(isec, r.offset); 620 } 621 } 622 } 623 } 624 625 void Writer::scanSymbols() { 626 TimeTraceScope timeScope("Scan symbols"); 627 for (const Symbol *sym : symtab->getSymbols()) { 628 if (const auto *defined = dyn_cast<Defined>(sym)) { 629 if (defined->overridesWeakDef && defined->isLive()) 630 in.weakBinding->addNonWeakDefinition(defined); 631 } else if (const auto *dysym = dyn_cast<DylibSymbol>(sym)) { 632 // This branch intentionally doesn't check isLive(). 633 if (dysym->isDynamicLookup()) 634 continue; 635 dysym->getFile()->refState = 636 std::max(dysym->getFile()->refState, dysym->getRefState()); 637 } 638 } 639 } 640 641 // TODO: ld64 enforces the old load commands in a few other cases. 642 static bool useLCBuildVersion(const PlatformInfo &platformInfo) { 643 static const std::map<PlatformKind, llvm::VersionTuple> minVersion = { 644 {PlatformKind::macOS, llvm::VersionTuple(10, 14)}, 645 {PlatformKind::iOS, llvm::VersionTuple(12, 0)}, 646 {PlatformKind::iOSSimulator, llvm::VersionTuple(13, 0)}, 647 {PlatformKind::tvOS, llvm::VersionTuple(12, 0)}, 648 {PlatformKind::tvOSSimulator, llvm::VersionTuple(13, 0)}, 649 {PlatformKind::watchOS, llvm::VersionTuple(5, 0)}, 650 {PlatformKind::watchOSSimulator, llvm::VersionTuple(6, 0)}}; 651 auto it = minVersion.find(platformInfo.target.Platform); 652 return it == minVersion.end() ? true : platformInfo.minimum >= it->second; 653 } 654 655 template <class LP> void Writer::createLoadCommands() { 656 uint8_t segIndex = 0; 657 for (OutputSegment *seg : outputSegments) { 658 in.header->addLoadCommand(make<LCSegment<LP>>(seg->name, seg)); 659 seg->index = segIndex++; 660 } 661 662 in.header->addLoadCommand(make<LCDyldInfo>( 663 in.rebase, in.binding, in.weakBinding, in.lazyBinding, in.exports)); 664 in.header->addLoadCommand(make<LCSymtab>(symtabSection, stringTableSection)); 665 in.header->addLoadCommand( 666 make<LCDysymtab>(symtabSection, indirectSymtabSection)); 667 if (functionStartsSection) 668 in.header->addLoadCommand(make<LCFunctionStarts>(functionStartsSection)); 669 in.header->addLoadCommand(make<LCDataInCode>(dataInCodeSection)); 670 if (config->emitEncryptionInfo) 671 in.header->addLoadCommand(make<LCEncryptionInfo<LP>>()); 672 for (StringRef path : config->runtimePaths) 673 in.header->addLoadCommand(make<LCRPath>(path)); 674 675 switch (config->outputType) { 676 case MH_EXECUTE: 677 in.header->addLoadCommand(make<LCLoadDylinker>()); 678 in.header->addLoadCommand(make<LCMain>()); 679 break; 680 case MH_DYLIB: 681 in.header->addLoadCommand(make<LCDylib>(LC_ID_DYLIB, config->installName, 682 config->dylibCompatibilityVersion, 683 config->dylibCurrentVersion)); 684 break; 685 case MH_BUNDLE: 686 break; 687 default: 688 llvm_unreachable("unhandled output file type"); 689 } 690 691 uuidCommand = make<LCUuid>(); 692 in.header->addLoadCommand(uuidCommand); 693 694 if (useLCBuildVersion(config->platformInfo)) 695 in.header->addLoadCommand(make<LCBuildVersion>(config->platformInfo)); 696 else 697 in.header->addLoadCommand(make<LCMinVersion>(config->platformInfo)); 698 699 int64_t dylibOrdinal = 1; 700 DenseMap<StringRef, int64_t> ordinalForInstallName; 701 for (InputFile *file : inputFiles) { 702 if (auto *dylibFile = dyn_cast<DylibFile>(file)) { 703 if (dylibFile->isBundleLoader) { 704 dylibFile->ordinal = BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE; 705 // Shortcut since bundle-loader does not re-export the symbols. 706 707 dylibFile->reexport = false; 708 continue; 709 } 710 711 // Don't emit load commands for a dylib that is not referenced if: 712 // - it was added implicitly (via a reexport, an LC_LOAD_DYLINKER -- 713 // if it's on the linker command line, it's explicit) 714 // - or it's marked MH_DEAD_STRIPPABLE_DYLIB 715 // - or the flag -dead_strip_dylibs is used 716 // FIXME: `isReferenced()` is currently computed before dead code 717 // stripping, so references from dead code keep a dylib alive. This 718 // matches ld64, but it's something we should do better. 719 if (!dylibFile->isReferenced() && !dylibFile->forceNeeded && 720 (!dylibFile->explicitlyLinked || dylibFile->deadStrippable || 721 config->deadStripDylibs)) 722 continue; 723 724 // Several DylibFiles can have the same installName. Only emit a single 725 // load command for that installName and give all these DylibFiles the 726 // same ordinal. 727 // This can happen in several cases: 728 // - a new framework could change its installName to an older 729 // framework name via an $ld$ symbol depending on platform_version 730 // - symlinks (for example, libpthread.tbd is a symlink to libSystem.tbd; 731 // Foo.framework/Foo.tbd is usually a symlink to 732 // Foo.framework/Versions/Current/Foo.tbd, where 733 // Foo.framework/Versions/Current is usually a symlink to 734 // Foo.framework/Versions/A) 735 // - a framework can be linked both explicitly on the linker 736 // command line and implicitly as a reexport from a different 737 // framework. The re-export will usually point to the tbd file 738 // in Foo.framework/Versions/A/Foo.tbd, while the explicit link will 739 // usually find Foo.framework/Foo.tbd. These are usually symlinks, 740 // but in a --reproduce archive they will be identical but distinct 741 // files. 742 // In the first case, *semantically distinct* DylibFiles will have the 743 // same installName. 744 int64_t &ordinal = ordinalForInstallName[dylibFile->installName]; 745 if (ordinal) { 746 dylibFile->ordinal = ordinal; 747 continue; 748 } 749 750 ordinal = dylibFile->ordinal = dylibOrdinal++; 751 LoadCommandType lcType = 752 dylibFile->forceWeakImport || dylibFile->refState == RefState::Weak 753 ? LC_LOAD_WEAK_DYLIB 754 : LC_LOAD_DYLIB; 755 in.header->addLoadCommand(make<LCDylib>(lcType, dylibFile->installName, 756 dylibFile->compatibilityVersion, 757 dylibFile->currentVersion)); 758 759 if (dylibFile->reexport) 760 in.header->addLoadCommand( 761 make<LCDylib>(LC_REEXPORT_DYLIB, dylibFile->installName)); 762 } 763 } 764 765 if (codeSignatureSection) 766 in.header->addLoadCommand(make<LCCodeSignature>(codeSignatureSection)); 767 768 const uint32_t MACOS_MAXPATHLEN = 1024; 769 config->headerPad = std::max( 770 config->headerPad, (config->headerPadMaxInstallNames 771 ? LCDylib::getInstanceCount() * MACOS_MAXPATHLEN 772 : 0)); 773 } 774 775 static size_t getSymbolPriority(const SymbolPriorityEntry &entry, 776 const InputFile *f) { 777 // We don't use toString(InputFile *) here because it returns the full path 778 // for object files, and we only want the basename. 779 StringRef filename; 780 if (f->archiveName.empty()) 781 filename = path::filename(f->getName()); 782 else 783 filename = saver.save(path::filename(f->archiveName) + "(" + 784 path::filename(f->getName()) + ")"); 785 return std::max(entry.objectFiles.lookup(filename), entry.anyObjectFile); 786 } 787 788 // Each section gets assigned the priority of the highest-priority symbol it 789 // contains. 790 static DenseMap<const InputSection *, size_t> buildInputSectionPriorities() { 791 DenseMap<const InputSection *, size_t> sectionPriorities; 792 793 if (config->priorities.empty()) 794 return sectionPriorities; 795 796 auto addSym = [&](Defined &sym) { 797 auto it = config->priorities.find(sym.getName()); 798 if (it == config->priorities.end()) 799 return; 800 801 SymbolPriorityEntry &entry = it->second; 802 size_t &priority = sectionPriorities[sym.isec]; 803 priority = std::max(priority, getSymbolPriority(entry, sym.isec->file)); 804 }; 805 806 // TODO: Make sure this handles weak symbols correctly. 807 for (const InputFile *file : inputFiles) { 808 if (isa<ObjFile>(file)) 809 for (Symbol *sym : file->symbols) 810 if (auto *d = dyn_cast_or_null<Defined>(sym)) 811 addSym(*d); 812 } 813 814 return sectionPriorities; 815 } 816 817 // Sorting only can happen once all outputs have been collected. Here we sort 818 // segments, output sections within each segment, and input sections within each 819 // output segment. 820 static void sortSegmentsAndSections() { 821 TimeTraceScope timeScope("Sort segments and sections"); 822 sortOutputSegments(); 823 824 DenseMap<const InputSection *, size_t> isecPriorities = 825 buildInputSectionPriorities(); 826 827 uint32_t sectionIndex = 0; 828 for (OutputSegment *seg : outputSegments) { 829 seg->sortOutputSections(); 830 for (OutputSection *osec : seg->getSections()) { 831 // Now that the output sections are sorted, assign the final 832 // output section indices. 833 if (!osec->isHidden()) 834 osec->index = ++sectionIndex; 835 if (!firstTLVDataSection && isThreadLocalData(osec->flags)) 836 firstTLVDataSection = osec; 837 838 if (!isecPriorities.empty()) { 839 if (auto *merged = dyn_cast<ConcatOutputSection>(osec)) { 840 llvm::stable_sort(merged->inputs, 841 [&](InputSection *a, InputSection *b) { 842 return isecPriorities[a] > isecPriorities[b]; 843 }); 844 } 845 } 846 } 847 } 848 } 849 850 static NamePair maybeRenameSection(NamePair key) { 851 auto newNames = config->sectionRenameMap.find(key); 852 if (newNames != config->sectionRenameMap.end()) 853 return newNames->second; 854 auto newName = config->segmentRenameMap.find(key.first); 855 if (newName != config->segmentRenameMap.end()) 856 return std::make_pair(newName->second, key.second); 857 return key; 858 } 859 860 template <class LP> void Writer::createOutputSections() { 861 TimeTraceScope timeScope("Create output sections"); 862 // First, create hidden sections 863 stringTableSection = make<StringTableSection>(); 864 symtabSection = makeSymtabSection<LP>(*stringTableSection); 865 indirectSymtabSection = make<IndirectSymtabSection>(); 866 if (config->adhocCodesign) 867 codeSignatureSection = make<CodeSignatureSection>(); 868 dataInCodeSection = make<DataInCodeSection>(); 869 if (config->emitFunctionStarts) 870 functionStartsSection = make<FunctionStartsSection>(); 871 if (config->emitBitcodeBundle) 872 make<BitcodeBundleSection>(); 873 874 switch (config->outputType) { 875 case MH_EXECUTE: 876 make<PageZeroSection>(); 877 break; 878 case MH_DYLIB: 879 case MH_BUNDLE: 880 break; 881 default: 882 llvm_unreachable("unhandled output file type"); 883 } 884 885 // Then add input sections to output sections. 886 DenseMap<NamePair, ConcatOutputSection *> concatOutputSections; 887 for (const auto &p : enumerate(inputSections)) { 888 InputSection *isec = p.value(); 889 OutputSection *osec; 890 if (auto *concatIsec = dyn_cast<ConcatInputSection>(isec)) { 891 if (concatIsec->shouldOmitFromOutput()) 892 continue; 893 NamePair names = maybeRenameSection({isec->segname, isec->name}); 894 ConcatOutputSection *&concatOsec = concatOutputSections[names]; 895 if (concatOsec == nullptr) 896 concatOsec = make<ConcatOutputSection>(names.second); 897 concatOsec->addInput(concatIsec); 898 osec = concatOsec; 899 } else if (auto *cStringIsec = dyn_cast<CStringInputSection>(isec)) { 900 in.cStringSection->addInput(cStringIsec); 901 osec = in.cStringSection; 902 } else if (auto *litIsec = dyn_cast<WordLiteralInputSection>(isec)) { 903 in.wordLiteralSection->addInput(litIsec); 904 osec = in.wordLiteralSection; 905 } else { 906 llvm_unreachable("unhandled InputSection type"); 907 } 908 osec->inputOrder = std::min(osec->inputOrder, static_cast<int>(p.index())); 909 } 910 911 // Once all the inputs are added, we can finalize the output section 912 // properties and create the corresponding output segments. 913 for (const auto &it : concatOutputSections) { 914 StringRef segname = it.first.first; 915 ConcatOutputSection *osec = it.second; 916 if (segname == segment_names::ld) { 917 assert(osec->name == section_names::compactUnwind); 918 in.unwindInfo->setCompactUnwindSection(osec); 919 } else { 920 getOrCreateOutputSegment(segname)->addOutputSection(osec); 921 } 922 } 923 924 for (SyntheticSection *ssec : syntheticSections) { 925 auto it = concatOutputSections.find({ssec->segname, ssec->name}); 926 if (ssec->isNeeded()) { 927 if (it == concatOutputSections.end()) { 928 getOrCreateOutputSegment(ssec->segname)->addOutputSection(ssec); 929 } else { 930 fatal("section from " + toString(it->second->firstSection()->file) + 931 " conflicts with synthetic section " + ssec->segname + "," + 932 ssec->name); 933 } 934 } 935 } 936 937 // dyld requires __LINKEDIT segment to always exist (even if empty). 938 linkEditSegment = getOrCreateOutputSegment(segment_names::linkEdit); 939 } 940 941 void Writer::finalizeAddresses() { 942 TimeTraceScope timeScope("Finalize addresses"); 943 uint64_t pageSize = target->getPageSize(); 944 // Ensure that segments (and the sections they contain) are allocated 945 // addresses in ascending order, which dyld requires. 946 // 947 // Note that at this point, __LINKEDIT sections are empty, but we need to 948 // determine addresses of other segments/sections before generating its 949 // contents. 950 for (OutputSegment *seg : outputSegments) { 951 if (seg == linkEditSegment) 952 continue; 953 assignAddresses(seg); 954 // codesign / libstuff checks for segment ordering by verifying that 955 // `fileOff + fileSize == next segment fileOff`. So we call alignTo() before 956 // (instead of after) computing fileSize to ensure that the segments are 957 // contiguous. We handle addr / vmSize similarly for the same reason. 958 fileOff = alignTo(fileOff, pageSize); 959 addr = alignTo(addr, pageSize); 960 seg->vmSize = addr - seg->firstSection()->addr; 961 seg->fileSize = fileOff - seg->fileOff; 962 } 963 } 964 965 void Writer::finalizeLinkEditSegment() { 966 TimeTraceScope timeScope("Finalize __LINKEDIT segment"); 967 // Fill __LINKEDIT contents. 968 std::vector<LinkEditSection *> linkEditSections{ 969 in.rebase, 970 in.binding, 971 in.weakBinding, 972 in.lazyBinding, 973 in.exports, 974 symtabSection, 975 indirectSymtabSection, 976 dataInCodeSection, 977 functionStartsSection, 978 }; 979 parallelForEach(linkEditSections, [](LinkEditSection *osec) { 980 if (osec) 981 osec->finalizeContents(); 982 }); 983 984 // Now that __LINKEDIT is filled out, do a proper calculation of its 985 // addresses and offsets. 986 assignAddresses(linkEditSegment); 987 // No need to page-align fileOff / addr here since this is the last segment. 988 linkEditSegment->vmSize = addr - linkEditSegment->firstSection()->addr; 989 linkEditSegment->fileSize = fileOff - linkEditSegment->fileOff; 990 } 991 992 void Writer::assignAddresses(OutputSegment *seg) { 993 seg->fileOff = fileOff; 994 995 for (OutputSection *osec : seg->getSections()) { 996 if (!osec->isNeeded()) 997 continue; 998 addr = alignTo(addr, osec->align); 999 fileOff = alignTo(fileOff, osec->align); 1000 osec->addr = addr; 1001 osec->fileOff = isZeroFill(osec->flags) ? 0 : fileOff; 1002 osec->finalize(); 1003 1004 addr += osec->getSize(); 1005 fileOff += osec->getFileSize(); 1006 } 1007 } 1008 1009 void Writer::openFile() { 1010 Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr = 1011 FileOutputBuffer::create(config->outputFile, fileOff, 1012 FileOutputBuffer::F_executable); 1013 1014 if (!bufferOrErr) 1015 error("failed to open " + config->outputFile + ": " + 1016 llvm::toString(bufferOrErr.takeError())); 1017 else 1018 buffer = std::move(*bufferOrErr); 1019 } 1020 1021 void Writer::writeSections() { 1022 uint8_t *buf = buffer->getBufferStart(); 1023 for (const OutputSegment *seg : outputSegments) 1024 for (const OutputSection *osec : seg->getSections()) 1025 osec->writeTo(buf + osec->fileOff); 1026 } 1027 1028 // In order to utilize multiple cores, we first split the buffer into chunks, 1029 // compute a hash for each chunk, and then compute a hash value of the hash 1030 // values. 1031 void Writer::writeUuid() { 1032 TimeTraceScope timeScope("Computing UUID"); 1033 ArrayRef<uint8_t> data{buffer->getBufferStart(), buffer->getBufferEnd()}; 1034 unsigned chunkCount = parallel::strategy.compute_thread_count() * 10; 1035 // Round-up integer division 1036 size_t chunkSize = (data.size() + chunkCount - 1) / chunkCount; 1037 std::vector<ArrayRef<uint8_t>> chunks = split(data, chunkSize); 1038 std::vector<uint64_t> hashes(chunks.size()); 1039 parallelForEachN(0, chunks.size(), 1040 [&](size_t i) { hashes[i] = xxHash64(chunks[i]); }); 1041 uint64_t digest = xxHash64({reinterpret_cast<uint8_t *>(hashes.data()), 1042 hashes.size() * sizeof(uint64_t)}); 1043 uuidCommand->writeUuid(digest); 1044 } 1045 1046 void Writer::writeCodeSignature() { 1047 if (codeSignatureSection) 1048 codeSignatureSection->writeHashes(buffer->getBufferStart()); 1049 } 1050 1051 void Writer::writeOutputFile() { 1052 TimeTraceScope timeScope("Write output file"); 1053 openFile(); 1054 if (errorCount()) 1055 return; 1056 writeSections(); 1057 writeUuid(); 1058 writeCodeSignature(); 1059 1060 if (auto e = buffer->commit()) 1061 error("failed to write to the output file: " + toString(std::move(e))); 1062 } 1063 1064 template <class LP> void Writer::run() { 1065 if (config->entry && !isa<Undefined>(config->entry)) 1066 prepareBranchTarget(config->entry); 1067 scanRelocations(); 1068 if (in.stubHelper->isNeeded()) 1069 in.stubHelper->setup(); 1070 scanSymbols(); 1071 createOutputSections<LP>(); 1072 // After this point, we create no new segments; HOWEVER, we might 1073 // yet create branch-range extension thunks for architectures whose 1074 // hardware call instructions have limited range, e.g., ARM(64). 1075 // The thunks are created as InputSections interspersed among 1076 // the ordinary __TEXT,_text InputSections. 1077 sortSegmentsAndSections(); 1078 createLoadCommands<LP>(); 1079 finalizeAddresses(); 1080 finalizeLinkEditSegment(); 1081 writeMapFile(); 1082 writeOutputFile(); 1083 } 1084 1085 template <class LP> void macho::writeResult() { Writer().run<LP>(); } 1086 1087 void macho::createSyntheticSections() { 1088 in.header = make<MachHeaderSection>(); 1089 in.cStringSection = config->dedupLiterals ? make<CStringSection>() : nullptr; 1090 in.wordLiteralSection = 1091 config->dedupLiterals ? make<WordLiteralSection>() : nullptr; 1092 in.rebase = make<RebaseSection>(); 1093 in.binding = make<BindingSection>(); 1094 in.weakBinding = make<WeakBindingSection>(); 1095 in.lazyBinding = make<LazyBindingSection>(); 1096 in.exports = make<ExportSection>(); 1097 in.got = make<GotSection>(); 1098 in.tlvPointers = make<TlvPointerSection>(); 1099 in.lazyPointers = make<LazyPointerSection>(); 1100 in.stubs = make<StubsSection>(); 1101 in.stubHelper = make<StubHelperSection>(); 1102 in.unwindInfo = makeUnwindInfoSection(); 1103 1104 // This section contains space for just a single word, and will be used by 1105 // dyld to cache an address to the image loader it uses. 1106 uint8_t *arr = bAlloc.Allocate<uint8_t>(target->wordSize); 1107 memset(arr, 0, target->wordSize); 1108 in.imageLoaderCache = make<ConcatInputSection>( 1109 segment_names::data, section_names::data, /*file=*/nullptr, 1110 ArrayRef<uint8_t>{arr, target->wordSize}, 1111 /*align=*/target->wordSize, /*flags=*/S_REGULAR); 1112 // References from dyld are not visible to us, so ensure this section is 1113 // always treated as live. 1114 in.imageLoaderCache->live = true; 1115 } 1116 1117 OutputSection *macho::firstTLVDataSection = nullptr; 1118 1119 template void macho::writeResult<LP64>(); 1120 template void macho::writeResult<ILP32>(); 1121