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 "CallGraphSort.h" 11 #include "ConcatOutputSection.h" 12 #include "Config.h" 13 #include "InputFiles.h" 14 #include "InputSection.h" 15 #include "MapFile.h" 16 #include "OutputSection.h" 17 #include "OutputSegment.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/ErrorHandler.h" 26 #include "lld/Common/Memory.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 c->platform = static_cast<uint32_t>(platformInfo.target.Platform); 463 c->minos = encodeVersion(platformInfo.minimum); 464 c->sdk = encodeVersion(platformInfo.sdk); 465 c->ntools = ntools; 466 auto *t = reinterpret_cast<build_tool_version *>(&c[1]); 467 t->tool = TOOL_LD; 468 t->version = encodeVersion(VersionTuple( 469 LLVM_VERSION_MAJOR, LLVM_VERSION_MINOR, LLVM_VERSION_PATCH)); 470 } 471 472 private: 473 const PlatformInfo &platformInfo; 474 }; 475 476 // Stores a unique identifier for the output file based on an MD5 hash of its 477 // contents. In order to hash the contents, we must first write them, but 478 // LC_UUID itself must be part of the written contents in order for all the 479 // offsets to be calculated correctly. We resolve this circular paradox by 480 // first writing an LC_UUID with an all-zero UUID, then updating the UUID with 481 // its real value later. 482 class LCUuid final : public LoadCommand { 483 public: 484 uint32_t getSize() const override { return sizeof(uuid_command); } 485 486 void writeTo(uint8_t *buf) const override { 487 auto *c = reinterpret_cast<uuid_command *>(buf); 488 c->cmd = LC_UUID; 489 c->cmdsize = getSize(); 490 uuidBuf = c->uuid; 491 } 492 493 void writeUuid(uint64_t digest) const { 494 // xxhash only gives us 8 bytes, so put some fixed data in the other half. 495 static_assert(sizeof(uuid_command::uuid) == 16, "unexpected uuid size"); 496 memcpy(uuidBuf, "LLD\xa1UU1D", 8); 497 memcpy(uuidBuf + 8, &digest, 8); 498 499 // RFC 4122 conformance. We need to fix 4 bits in byte 6 and 2 bits in 500 // byte 8. Byte 6 is already fine due to the fixed data we put in. We don't 501 // want to lose bits of the digest in byte 8, so swap that with a byte of 502 // fixed data that happens to have the right bits set. 503 std::swap(uuidBuf[3], uuidBuf[8]); 504 505 // Claim that this is an MD5-based hash. It isn't, but this signals that 506 // this is not a time-based and not a random hash. MD5 seems like the least 507 // bad lie we can put here. 508 assert((uuidBuf[6] & 0xf0) == 0x30 && "See RFC 4122 Sections 4.2.2, 4.1.3"); 509 assert((uuidBuf[8] & 0xc0) == 0x80 && "See RFC 4122 Section 4.2.2"); 510 } 511 512 mutable uint8_t *uuidBuf; 513 }; 514 515 template <class LP> class LCEncryptionInfo final : public LoadCommand { 516 public: 517 uint32_t getSize() const override { 518 return sizeof(typename LP::encryption_info_command); 519 } 520 521 void writeTo(uint8_t *buf) const override { 522 using EncryptionInfo = typename LP::encryption_info_command; 523 auto *c = reinterpret_cast<EncryptionInfo *>(buf); 524 buf += sizeof(EncryptionInfo); 525 c->cmd = LP::encryptionInfoLCType; 526 c->cmdsize = getSize(); 527 c->cryptoff = in.header->getSize(); 528 auto it = find_if(outputSegments, [](const OutputSegment *seg) { 529 return seg->name == segment_names::text; 530 }); 531 assert(it != outputSegments.end()); 532 c->cryptsize = (*it)->fileSize - c->cryptoff; 533 } 534 }; 535 536 class LCCodeSignature final : public LoadCommand { 537 public: 538 LCCodeSignature(CodeSignatureSection *section) : section(section) {} 539 540 uint32_t getSize() const override { return sizeof(linkedit_data_command); } 541 542 void writeTo(uint8_t *buf) const override { 543 auto *c = reinterpret_cast<linkedit_data_command *>(buf); 544 c->cmd = LC_CODE_SIGNATURE; 545 c->cmdsize = getSize(); 546 c->dataoff = static_cast<uint32_t>(section->fileOff); 547 c->datasize = section->getSize(); 548 } 549 550 CodeSignatureSection *section; 551 }; 552 553 } // namespace 554 555 void Writer::treatSpecialUndefineds() { 556 if (config->entry) 557 if (auto *undefined = dyn_cast<Undefined>(config->entry)) 558 treatUndefinedSymbol(*undefined, "the entry point"); 559 560 // FIXME: This prints symbols that are undefined both in input files and 561 // via -u flag twice. 562 for (const Symbol *sym : config->explicitUndefineds) { 563 if (const auto *undefined = dyn_cast<Undefined>(sym)) 564 treatUndefinedSymbol(*undefined, "-u"); 565 } 566 // Literal exported-symbol names must be defined, but glob 567 // patterns need not match. 568 for (const CachedHashStringRef &cachedName : 569 config->exportedSymbols.literals) { 570 if (const Symbol *sym = symtab->find(cachedName)) 571 if (const auto *undefined = dyn_cast<Undefined>(sym)) 572 treatUndefinedSymbol(*undefined, "-exported_symbol(s_list)"); 573 } 574 } 575 576 // Add stubs and bindings where necessary (e.g. if the symbol is a 577 // DylibSymbol.) 578 static void prepareBranchTarget(Symbol *sym) { 579 if (auto *dysym = dyn_cast<DylibSymbol>(sym)) { 580 if (in.stubs->addEntry(dysym)) { 581 if (sym->isWeakDef()) { 582 in.binding->addEntry(dysym, in.lazyPointers->isec, 583 sym->stubsIndex * target->wordSize); 584 in.weakBinding->addEntry(sym, in.lazyPointers->isec, 585 sym->stubsIndex * target->wordSize); 586 } else { 587 in.lazyBinding->addEntry(dysym); 588 } 589 } 590 } else if (auto *defined = dyn_cast<Defined>(sym)) { 591 if (defined->isExternalWeakDef()) { 592 if (in.stubs->addEntry(sym)) { 593 in.rebase->addEntry(in.lazyPointers->isec, 594 sym->stubsIndex * target->wordSize); 595 in.weakBinding->addEntry(sym, in.lazyPointers->isec, 596 sym->stubsIndex * target->wordSize); 597 } 598 } 599 } else { 600 llvm_unreachable("invalid branch target symbol type"); 601 } 602 } 603 604 // Can a symbol's address can only be resolved at runtime? 605 static bool needsBinding(const Symbol *sym) { 606 if (isa<DylibSymbol>(sym)) 607 return true; 608 if (const auto *defined = dyn_cast<Defined>(sym)) 609 return defined->isExternalWeakDef(); 610 return false; 611 } 612 613 static void prepareSymbolRelocation(Symbol *sym, const InputSection *isec, 614 const Reloc &r) { 615 assert(sym->isLive()); 616 const RelocAttrs &relocAttrs = target->getRelocAttrs(r.type); 617 618 if (relocAttrs.hasAttr(RelocAttrBits::BRANCH)) { 619 prepareBranchTarget(sym); 620 } else if (relocAttrs.hasAttr(RelocAttrBits::GOT)) { 621 if (relocAttrs.hasAttr(RelocAttrBits::POINTER) || needsBinding(sym)) 622 in.got->addEntry(sym); 623 } else if (relocAttrs.hasAttr(RelocAttrBits::TLV)) { 624 if (needsBinding(sym)) 625 in.tlvPointers->addEntry(sym); 626 } else if (relocAttrs.hasAttr(RelocAttrBits::UNSIGNED)) { 627 // References from thread-local variable sections are treated as offsets 628 // relative to the start of the referent section, and therefore have no 629 // need of rebase opcodes. 630 if (!(isThreadLocalVariables(isec->getFlags()) && isa<Defined>(sym))) 631 addNonLazyBindingEntries(sym, isec, r.offset, r.addend); 632 } 633 } 634 635 void Writer::scanRelocations() { 636 TimeTraceScope timeScope("Scan relocations"); 637 638 // This can't use a for-each loop: It calls treatUndefinedSymbol(), which can 639 // add to inputSections, which invalidates inputSections's iterators. 640 for (size_t i = 0; i < inputSections.size(); ++i) { 641 ConcatInputSection *isec = inputSections[i]; 642 643 if (isec->shouldOmitFromOutput()) 644 continue; 645 646 for (auto it = isec->relocs.begin(); it != isec->relocs.end(); ++it) { 647 Reloc &r = *it; 648 if (target->hasAttr(r.type, RelocAttrBits::SUBTRAHEND)) { 649 // Skip over the following UNSIGNED relocation -- it's just there as the 650 // minuend, and doesn't have the usual UNSIGNED semantics. We don't want 651 // to emit rebase opcodes for it. 652 it++; 653 continue; 654 } 655 if (auto *sym = r.referent.dyn_cast<Symbol *>()) { 656 if (auto *undefined = dyn_cast<Undefined>(sym)) 657 treatUndefinedSymbol(*undefined); 658 // treatUndefinedSymbol() can replace sym with a DylibSymbol; re-check. 659 if (!isa<Undefined>(sym) && validateSymbolRelocation(sym, isec, r)) 660 prepareSymbolRelocation(sym, isec, r); 661 } else { 662 // Canonicalize the referent so that later accesses in Writer won't 663 // have to worry about it. Perhaps we should do this for Defined::isec 664 // too... 665 auto *referentIsec = r.referent.get<InputSection *>(); 666 r.referent = referentIsec->canonical(); 667 if (!r.pcrel) 668 in.rebase->addEntry(isec, r.offset); 669 } 670 } 671 } 672 673 in.unwindInfo->prepareRelocations(); 674 } 675 676 void Writer::scanSymbols() { 677 TimeTraceScope timeScope("Scan symbols"); 678 for (Symbol *sym : symtab->getSymbols()) { 679 if (auto *defined = dyn_cast<Defined>(sym)) { 680 if (!defined->isLive()) 681 continue; 682 defined->canonicalize(); 683 if (defined->overridesWeakDef) 684 in.weakBinding->addNonWeakDefinition(defined); 685 if (!defined->isAbsolute() && isCodeSection(defined->isec)) 686 in.unwindInfo->addSymbol(defined); 687 } else if (const auto *dysym = dyn_cast<DylibSymbol>(sym)) { 688 // This branch intentionally doesn't check isLive(). 689 if (dysym->isDynamicLookup()) 690 continue; 691 dysym->getFile()->refState = 692 std::max(dysym->getFile()->refState, dysym->getRefState()); 693 } 694 } 695 696 for (const InputFile *file : inputFiles) { 697 if (auto *objFile = dyn_cast<ObjFile>(file)) 698 for (Symbol *sym : objFile->symbols) { 699 if (auto *defined = dyn_cast_or_null<Defined>(sym)) { 700 if (!defined->isLive()) 701 continue; 702 defined->canonicalize(); 703 if (!defined->isExternal() && !defined->isAbsolute() && 704 isCodeSection(defined->isec)) 705 in.unwindInfo->addSymbol(defined); 706 } 707 } 708 } 709 } 710 711 // TODO: ld64 enforces the old load commands in a few other cases. 712 static bool useLCBuildVersion(const PlatformInfo &platformInfo) { 713 static const std::vector<std::pair<PlatformType, VersionTuple>> minVersion = { 714 {PLATFORM_MACOS, VersionTuple(10, 14)}, 715 {PLATFORM_IOS, VersionTuple(12, 0)}, 716 {PLATFORM_IOSSIMULATOR, VersionTuple(13, 0)}, 717 {PLATFORM_TVOS, VersionTuple(12, 0)}, 718 {PLATFORM_TVOSSIMULATOR, VersionTuple(13, 0)}, 719 {PLATFORM_WATCHOS, VersionTuple(5, 0)}, 720 {PLATFORM_WATCHOSSIMULATOR, VersionTuple(6, 0)}}; 721 auto it = llvm::find_if(minVersion, [&](const auto &p) { 722 return p.first == platformInfo.target.Platform; 723 }); 724 return it == minVersion.end() ? true : platformInfo.minimum >= it->second; 725 } 726 727 template <class LP> void Writer::createLoadCommands() { 728 uint8_t segIndex = 0; 729 for (OutputSegment *seg : outputSegments) { 730 in.header->addLoadCommand(make<LCSegment<LP>>(seg->name, seg)); 731 seg->index = segIndex++; 732 } 733 734 in.header->addLoadCommand(make<LCDyldInfo>( 735 in.rebase, in.binding, in.weakBinding, in.lazyBinding, in.exports)); 736 in.header->addLoadCommand(make<LCSymtab>(symtabSection, stringTableSection)); 737 in.header->addLoadCommand( 738 make<LCDysymtab>(symtabSection, indirectSymtabSection)); 739 if (!config->umbrella.empty()) 740 in.header->addLoadCommand(make<LCSubFramework>(config->umbrella)); 741 if (config->emitEncryptionInfo) 742 in.header->addLoadCommand(make<LCEncryptionInfo<LP>>()); 743 for (StringRef path : config->runtimePaths) 744 in.header->addLoadCommand(make<LCRPath>(path)); 745 746 switch (config->outputType) { 747 case MH_EXECUTE: 748 in.header->addLoadCommand(make<LCLoadDylinker>()); 749 break; 750 case MH_DYLIB: 751 in.header->addLoadCommand(make<LCDylib>(LC_ID_DYLIB, config->installName, 752 config->dylibCompatibilityVersion, 753 config->dylibCurrentVersion)); 754 break; 755 case MH_BUNDLE: 756 break; 757 default: 758 llvm_unreachable("unhandled output file type"); 759 } 760 761 uuidCommand = make<LCUuid>(); 762 in.header->addLoadCommand(uuidCommand); 763 764 if (useLCBuildVersion(config->platformInfo)) 765 in.header->addLoadCommand(make<LCBuildVersion>(config->platformInfo)); 766 else 767 in.header->addLoadCommand(make<LCMinVersion>(config->platformInfo)); 768 769 // This is down here to match ld64's load command order. 770 if (config->outputType == MH_EXECUTE) 771 in.header->addLoadCommand(make<LCMain>()); 772 773 int64_t dylibOrdinal = 1; 774 DenseMap<StringRef, int64_t> ordinalForInstallName; 775 for (InputFile *file : inputFiles) { 776 if (auto *dylibFile = dyn_cast<DylibFile>(file)) { 777 if (dylibFile->isBundleLoader) { 778 dylibFile->ordinal = BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE; 779 // Shortcut since bundle-loader does not re-export the symbols. 780 781 dylibFile->reexport = false; 782 continue; 783 } 784 785 // Don't emit load commands for a dylib that is not referenced if: 786 // - it was added implicitly (via a reexport, an LC_LOAD_DYLINKER -- 787 // if it's on the linker command line, it's explicit) 788 // - or it's marked MH_DEAD_STRIPPABLE_DYLIB 789 // - or the flag -dead_strip_dylibs is used 790 // FIXME: `isReferenced()` is currently computed before dead code 791 // stripping, so references from dead code keep a dylib alive. This 792 // matches ld64, but it's something we should do better. 793 if (!dylibFile->isReferenced() && !dylibFile->forceNeeded && 794 (!dylibFile->explicitlyLinked || dylibFile->deadStrippable || 795 config->deadStripDylibs)) 796 continue; 797 798 // Several DylibFiles can have the same installName. Only emit a single 799 // load command for that installName and give all these DylibFiles the 800 // same ordinal. 801 // This can happen in several cases: 802 // - a new framework could change its installName to an older 803 // framework name via an $ld$ symbol depending on platform_version 804 // - symlinks (for example, libpthread.tbd is a symlink to libSystem.tbd; 805 // Foo.framework/Foo.tbd is usually a symlink to 806 // Foo.framework/Versions/Current/Foo.tbd, where 807 // Foo.framework/Versions/Current is usually a symlink to 808 // Foo.framework/Versions/A) 809 // - a framework can be linked both explicitly on the linker 810 // command line and implicitly as a reexport from a different 811 // framework. The re-export will usually point to the tbd file 812 // in Foo.framework/Versions/A/Foo.tbd, while the explicit link will 813 // usually find Foo.framework/Foo.tbd. These are usually symlinks, 814 // but in a --reproduce archive they will be identical but distinct 815 // files. 816 // In the first case, *semantically distinct* DylibFiles will have the 817 // same installName. 818 int64_t &ordinal = ordinalForInstallName[dylibFile->installName]; 819 if (ordinal) { 820 dylibFile->ordinal = ordinal; 821 continue; 822 } 823 824 ordinal = dylibFile->ordinal = dylibOrdinal++; 825 LoadCommandType lcType = 826 dylibFile->forceWeakImport || dylibFile->refState == RefState::Weak 827 ? LC_LOAD_WEAK_DYLIB 828 : LC_LOAD_DYLIB; 829 in.header->addLoadCommand(make<LCDylib>(lcType, dylibFile->installName, 830 dylibFile->compatibilityVersion, 831 dylibFile->currentVersion)); 832 833 if (dylibFile->reexport) 834 in.header->addLoadCommand( 835 make<LCDylib>(LC_REEXPORT_DYLIB, dylibFile->installName)); 836 } 837 } 838 839 if (functionStartsSection) 840 in.header->addLoadCommand(make<LCFunctionStarts>(functionStartsSection)); 841 if (dataInCodeSection) 842 in.header->addLoadCommand(make<LCDataInCode>(dataInCodeSection)); 843 if (codeSignatureSection) 844 in.header->addLoadCommand(make<LCCodeSignature>(codeSignatureSection)); 845 846 const uint32_t MACOS_MAXPATHLEN = 1024; 847 config->headerPad = std::max( 848 config->headerPad, (config->headerPadMaxInstallNames 849 ? LCDylib::getInstanceCount() * MACOS_MAXPATHLEN 850 : 0)); 851 } 852 853 static size_t getSymbolPriority(const SymbolPriorityEntry &entry, 854 const InputFile *f) { 855 // We don't use toString(InputFile *) here because it returns the full path 856 // for object files, and we only want the basename. 857 StringRef filename; 858 if (f->archiveName.empty()) 859 filename = path::filename(f->getName()); 860 else 861 filename = saver.save(path::filename(f->archiveName) + "(" + 862 path::filename(f->getName()) + ")"); 863 return std::max(entry.objectFiles.lookup(filename), entry.anyObjectFile); 864 } 865 866 // Each section gets assigned the priority of the highest-priority symbol it 867 // contains. 868 static DenseMap<const InputSection *, size_t> buildInputSectionPriorities() { 869 if (config->callGraphProfileSort) 870 return computeCallGraphProfileOrder(); 871 DenseMap<const InputSection *, size_t> sectionPriorities; 872 873 if (config->priorities.empty()) 874 return sectionPriorities; 875 876 auto addSym = [&](Defined &sym) { 877 if (sym.isAbsolute()) 878 return; 879 880 auto it = config->priorities.find(sym.getName()); 881 if (it == config->priorities.end()) 882 return; 883 884 SymbolPriorityEntry &entry = it->second; 885 size_t &priority = sectionPriorities[sym.isec]; 886 priority = 887 std::max(priority, getSymbolPriority(entry, sym.isec->getFile())); 888 }; 889 890 // TODO: Make sure this handles weak symbols correctly. 891 for (const InputFile *file : inputFiles) { 892 if (isa<ObjFile>(file)) 893 for (Symbol *sym : file->symbols) 894 if (auto *d = dyn_cast_or_null<Defined>(sym)) 895 addSym(*d); 896 } 897 898 return sectionPriorities; 899 } 900 901 // Sorting only can happen once all outputs have been collected. Here we sort 902 // segments, output sections within each segment, and input sections within each 903 // output segment. 904 static void sortSegmentsAndSections() { 905 TimeTraceScope timeScope("Sort segments and sections"); 906 sortOutputSegments(); 907 908 DenseMap<const InputSection *, size_t> isecPriorities = 909 buildInputSectionPriorities(); 910 911 uint32_t sectionIndex = 0; 912 for (OutputSegment *seg : outputSegments) { 913 seg->sortOutputSections(); 914 // References from thread-local variable sections are treated as offsets 915 // relative to the start of the thread-local data memory area, which 916 // is initialized via copying all the TLV data sections (which are all 917 // contiguous). If later data sections require a greater alignment than 918 // earlier ones, the offsets of data within those sections won't be 919 // guaranteed to aligned unless we normalize alignments. We therefore use 920 // the largest alignment for all TLV data sections. 921 uint32_t tlvAlign = 0; 922 for (const OutputSection *osec : seg->getSections()) 923 if (isThreadLocalData(osec->flags) && osec->align > tlvAlign) 924 tlvAlign = osec->align; 925 926 for (OutputSection *osec : seg->getSections()) { 927 // Now that the output sections are sorted, assign the final 928 // output section indices. 929 if (!osec->isHidden()) 930 osec->index = ++sectionIndex; 931 if (isThreadLocalData(osec->flags)) { 932 if (!firstTLVDataSection) 933 firstTLVDataSection = osec; 934 osec->align = tlvAlign; 935 } 936 937 if (!isecPriorities.empty()) { 938 if (auto *merged = dyn_cast<ConcatOutputSection>(osec)) { 939 llvm::stable_sort(merged->inputs, 940 [&](InputSection *a, InputSection *b) { 941 return isecPriorities[a] > isecPriorities[b]; 942 }); 943 } 944 } 945 } 946 } 947 } 948 949 template <class LP> void Writer::createOutputSections() { 950 TimeTraceScope timeScope("Create output sections"); 951 // First, create hidden sections 952 stringTableSection = make<StringTableSection>(); 953 symtabSection = makeSymtabSection<LP>(*stringTableSection); 954 indirectSymtabSection = make<IndirectSymtabSection>(); 955 if (config->adhocCodesign) 956 codeSignatureSection = make<CodeSignatureSection>(); 957 if (config->emitDataInCodeInfo) 958 dataInCodeSection = make<DataInCodeSection>(); 959 if (config->emitFunctionStarts) 960 functionStartsSection = make<FunctionStartsSection>(); 961 if (config->emitBitcodeBundle) 962 make<BitcodeBundleSection>(); 963 964 switch (config->outputType) { 965 case MH_EXECUTE: 966 make<PageZeroSection>(); 967 break; 968 case MH_DYLIB: 969 case MH_BUNDLE: 970 break; 971 default: 972 llvm_unreachable("unhandled output file type"); 973 } 974 975 // Then add input sections to output sections. 976 for (ConcatInputSection *isec : inputSections) { 977 if (isec->shouldOmitFromOutput()) 978 continue; 979 ConcatOutputSection *osec = cast<ConcatOutputSection>(isec->parent); 980 osec->addInput(isec); 981 osec->inputOrder = 982 std::min(osec->inputOrder, static_cast<int>(isec->outSecOff)); 983 } 984 985 // Once all the inputs are added, we can finalize the output section 986 // properties and create the corresponding output segments. 987 for (const auto &it : concatOutputSections) { 988 StringRef segname = it.first.first; 989 ConcatOutputSection *osec = it.second; 990 assert(segname != segment_names::ld); 991 if (osec->isNeeded()) 992 getOrCreateOutputSegment(segname)->addOutputSection(osec); 993 } 994 995 for (SyntheticSection *ssec : syntheticSections) { 996 auto it = concatOutputSections.find({ssec->segname, ssec->name}); 997 // We add all LinkEdit sections here because we don't know if they are 998 // needed until their finalizeContents() methods get called later. While 999 // this means that we add some redundant sections to __LINKEDIT, there is 1000 // is no redundancy in the output, as we do not emit section headers for 1001 // any LinkEdit sections. 1002 if (ssec->isNeeded() || ssec->segname == segment_names::linkEdit) { 1003 if (it == concatOutputSections.end()) { 1004 getOrCreateOutputSegment(ssec->segname)->addOutputSection(ssec); 1005 } else { 1006 fatal("section from " + 1007 toString(it->second->firstSection()->getFile()) + 1008 " conflicts with synthetic section " + ssec->segname + "," + 1009 ssec->name); 1010 } 1011 } 1012 } 1013 1014 // dyld requires __LINKEDIT segment to always exist (even if empty). 1015 linkEditSegment = getOrCreateOutputSegment(segment_names::linkEdit); 1016 } 1017 1018 void Writer::finalizeAddresses() { 1019 TimeTraceScope timeScope("Finalize addresses"); 1020 uint64_t pageSize = target->getPageSize(); 1021 // Ensure that segments (and the sections they contain) are allocated 1022 // addresses in ascending order, which dyld requires. 1023 // 1024 // Note that at this point, __LINKEDIT sections are empty, but we need to 1025 // determine addresses of other segments/sections before generating its 1026 // contents. 1027 for (OutputSegment *seg : outputSegments) { 1028 if (seg == linkEditSegment) 1029 continue; 1030 seg->addr = addr; 1031 assignAddresses(seg); 1032 // codesign / libstuff checks for segment ordering by verifying that 1033 // `fileOff + fileSize == next segment fileOff`. So we call alignTo() before 1034 // (instead of after) computing fileSize to ensure that the segments are 1035 // contiguous. We handle addr / vmSize similarly for the same reason. 1036 fileOff = alignTo(fileOff, pageSize); 1037 addr = alignTo(addr, pageSize); 1038 seg->vmSize = addr - seg->addr; 1039 seg->fileSize = fileOff - seg->fileOff; 1040 seg->assignAddressesToStartEndSymbols(); 1041 } 1042 } 1043 1044 void Writer::finalizeLinkEditSegment() { 1045 TimeTraceScope timeScope("Finalize __LINKEDIT segment"); 1046 // Fill __LINKEDIT contents. 1047 std::vector<LinkEditSection *> linkEditSections{ 1048 in.rebase, 1049 in.binding, 1050 in.weakBinding, 1051 in.lazyBinding, 1052 in.exports, 1053 symtabSection, 1054 indirectSymtabSection, 1055 dataInCodeSection, 1056 functionStartsSection, 1057 }; 1058 SmallVector<std::shared_future<void>> threadFutures; 1059 threadFutures.reserve(linkEditSections.size()); 1060 for (LinkEditSection *osec : linkEditSections) 1061 if (osec) 1062 threadFutures.emplace_back(threadPool.async( 1063 [](LinkEditSection *osec) { osec->finalizeContents(); }, osec)); 1064 for (std::shared_future<void> &future : threadFutures) 1065 future.wait(); 1066 1067 // Now that __LINKEDIT is filled out, do a proper calculation of its 1068 // addresses and offsets. 1069 linkEditSegment->addr = addr; 1070 assignAddresses(linkEditSegment); 1071 // No need to page-align fileOff / addr here since this is the last segment. 1072 linkEditSegment->vmSize = addr - linkEditSegment->addr; 1073 linkEditSegment->fileSize = fileOff - linkEditSegment->fileOff; 1074 } 1075 1076 void Writer::assignAddresses(OutputSegment *seg) { 1077 seg->fileOff = fileOff; 1078 1079 for (OutputSection *osec : seg->getSections()) { 1080 if (!osec->isNeeded()) 1081 continue; 1082 addr = alignTo(addr, osec->align); 1083 fileOff = alignTo(fileOff, osec->align); 1084 osec->addr = addr; 1085 osec->fileOff = isZeroFill(osec->flags) ? 0 : fileOff; 1086 osec->finalize(); 1087 osec->assignAddressesToStartEndSymbols(); 1088 1089 addr += osec->getSize(); 1090 fileOff += osec->getFileSize(); 1091 } 1092 } 1093 1094 void Writer::openFile() { 1095 Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr = 1096 FileOutputBuffer::create(config->outputFile, fileOff, 1097 FileOutputBuffer::F_executable); 1098 1099 if (!bufferOrErr) 1100 error("failed to open " + config->outputFile + ": " + 1101 llvm::toString(bufferOrErr.takeError())); 1102 else 1103 buffer = std::move(*bufferOrErr); 1104 } 1105 1106 void Writer::writeSections() { 1107 uint8_t *buf = buffer->getBufferStart(); 1108 for (const OutputSegment *seg : outputSegments) 1109 for (const OutputSection *osec : seg->getSections()) 1110 osec->writeTo(buf + osec->fileOff); 1111 } 1112 1113 // In order to utilize multiple cores, we first split the buffer into chunks, 1114 // compute a hash for each chunk, and then compute a hash value of the hash 1115 // values. 1116 void Writer::writeUuid() { 1117 TimeTraceScope timeScope("Computing UUID"); 1118 1119 ArrayRef<uint8_t> data{buffer->getBufferStart(), buffer->getBufferEnd()}; 1120 unsigned chunkCount = parallel::strategy.compute_thread_count() * 10; 1121 // Round-up integer division 1122 size_t chunkSize = (data.size() + chunkCount - 1) / chunkCount; 1123 std::vector<ArrayRef<uint8_t>> chunks = split(data, chunkSize); 1124 std::vector<uint64_t> hashes(chunks.size()); 1125 SmallVector<std::shared_future<void>> threadFutures; 1126 threadFutures.reserve(chunks.size()); 1127 for (size_t i = 0; i < chunks.size(); ++i) 1128 threadFutures.emplace_back(threadPool.async( 1129 [&](size_t j) { hashes[j] = xxHash64(chunks[j]); }, i)); 1130 for (std::shared_future<void> &future : threadFutures) 1131 future.wait(); 1132 1133 uint64_t digest = xxHash64({reinterpret_cast<uint8_t *>(hashes.data()), 1134 hashes.size() * sizeof(uint64_t)}); 1135 uuidCommand->writeUuid(digest); 1136 } 1137 1138 void Writer::writeCodeSignature() { 1139 if (codeSignatureSection) 1140 codeSignatureSection->writeHashes(buffer->getBufferStart()); 1141 } 1142 1143 void Writer::writeOutputFile() { 1144 TimeTraceScope timeScope("Write output file"); 1145 openFile(); 1146 if (errorCount()) 1147 return; 1148 writeSections(); 1149 writeUuid(); 1150 writeCodeSignature(); 1151 1152 if (auto e = buffer->commit()) 1153 error("failed to write to the output file: " + toString(std::move(e))); 1154 } 1155 1156 template <class LP> void Writer::run() { 1157 treatSpecialUndefineds(); 1158 if (config->entry && !isa<Undefined>(config->entry)) 1159 prepareBranchTarget(config->entry); 1160 // Canonicalization of all pointers to InputSections should be handled by 1161 // these two methods. 1162 scanSymbols(); 1163 scanRelocations(); 1164 1165 // Do not proceed if there was an undefined symbol. 1166 if (errorCount()) 1167 return; 1168 1169 if (in.stubHelper->isNeeded()) 1170 in.stubHelper->setup(); 1171 createOutputSections<LP>(); 1172 1173 // After this point, we create no new segments; HOWEVER, we might 1174 // yet create branch-range extension thunks for architectures whose 1175 // hardware call instructions have limited range, e.g., ARM(64). 1176 // The thunks are created as InputSections interspersed among 1177 // the ordinary __TEXT,_text InputSections. 1178 sortSegmentsAndSections(); 1179 createLoadCommands<LP>(); 1180 finalizeAddresses(); 1181 threadPool.async([&] { 1182 if (LLVM_ENABLE_THREADS && config->timeTraceEnabled) 1183 timeTraceProfilerInitialize(config->timeTraceGranularity, "writeMapFile"); 1184 writeMapFile(); 1185 if (LLVM_ENABLE_THREADS && config->timeTraceEnabled) 1186 timeTraceProfilerFinishThread(); 1187 }); 1188 finalizeLinkEditSegment(); 1189 writeOutputFile(); 1190 } 1191 1192 template <class LP> void macho::writeResult() { Writer().run<LP>(); } 1193 1194 void macho::resetWriter() { LCDylib::resetInstanceCount(); } 1195 1196 void macho::createSyntheticSections() { 1197 in.header = make<MachHeaderSection>(); 1198 if (config->dedupLiterals) { 1199 in.cStringSection = make<DeduplicatedCStringSection>(); 1200 } else { 1201 in.cStringSection = make<CStringSection>(); 1202 } 1203 in.wordLiteralSection = 1204 config->dedupLiterals ? make<WordLiteralSection>() : nullptr; 1205 in.rebase = make<RebaseSection>(); 1206 in.binding = make<BindingSection>(); 1207 in.weakBinding = make<WeakBindingSection>(); 1208 in.lazyBinding = make<LazyBindingSection>(); 1209 in.exports = make<ExportSection>(); 1210 in.got = make<GotSection>(); 1211 in.tlvPointers = make<TlvPointerSection>(); 1212 in.lazyPointers = make<LazyPointerSection>(); 1213 in.stubs = make<StubsSection>(); 1214 in.stubHelper = make<StubHelperSection>(); 1215 in.unwindInfo = makeUnwindInfoSection(); 1216 1217 // This section contains space for just a single word, and will be used by 1218 // dyld to cache an address to the image loader it uses. 1219 uint8_t *arr = bAlloc.Allocate<uint8_t>(target->wordSize); 1220 memset(arr, 0, target->wordSize); 1221 in.imageLoaderCache = make<ConcatInputSection>( 1222 segment_names::data, section_names::data, /*file=*/nullptr, 1223 ArrayRef<uint8_t>{arr, target->wordSize}, 1224 /*align=*/target->wordSize, /*flags=*/S_REGULAR); 1225 // References from dyld are not visible to us, so ensure this section is 1226 // always treated as live. 1227 in.imageLoaderCache->live = true; 1228 } 1229 1230 OutputSection *macho::firstTLVDataSection = nullptr; 1231 1232 template void macho::writeResult<LP64>(); 1233 template void macho::writeResult<ILP32>(); 1234