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