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