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