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 "Config.h" 11 #include "InputFiles.h" 12 #include "InputSection.h" 13 #include "MergedOutputSection.h" 14 #include "OutputSection.h" 15 #include "OutputSegment.h" 16 #include "SymbolTable.h" 17 #include "Symbols.h" 18 #include "SyntheticSections.h" 19 #include "Target.h" 20 21 #include "lld/Common/ErrorHandler.h" 22 #include "lld/Common/Memory.h" 23 #include "llvm/BinaryFormat/MachO.h" 24 #include "llvm/Config/llvm-config.h" 25 #include "llvm/Support/LEB128.h" 26 #include "llvm/Support/MathExtras.h" 27 #include "llvm/Support/Path.h" 28 29 using namespace llvm; 30 using namespace llvm::MachO; 31 using namespace lld; 32 using namespace lld::macho; 33 34 namespace { 35 class LCLinkEdit; 36 class LCDyldInfo; 37 class LCSymtab; 38 39 class Writer { 40 public: 41 Writer() : buffer(errorHandler().outputBuffer) {} 42 43 void scanRelocations(); 44 void createOutputSections(); 45 void createLoadCommands(); 46 void assignAddresses(OutputSegment *); 47 void createSymtabContents(); 48 49 void openFile(); 50 void writeSections(); 51 52 void run(); 53 54 std::unique_ptr<FileOutputBuffer> &buffer; 55 uint64_t addr = 0; 56 uint64_t fileOff = 0; 57 MachHeaderSection *header = nullptr; 58 LazyBindingSection *lazyBindingSection = nullptr; 59 ExportSection *exportSection = nullptr; 60 StringTableSection *stringTableSection = nullptr; 61 SymtabSection *symtabSection = nullptr; 62 }; 63 64 // LC_DYLD_INFO_ONLY stores the offsets of symbol import/export information. 65 class LCDyldInfo : public LoadCommand { 66 public: 67 LCDyldInfo(BindingSection *bindingSection, 68 WeakBindingSection *weakBindingSection, 69 LazyBindingSection *lazyBindingSection, 70 ExportSection *exportSection) 71 : bindingSection(bindingSection), weakBindingSection(weakBindingSection), 72 lazyBindingSection(lazyBindingSection), exportSection(exportSection) {} 73 74 uint32_t getSize() const override { return sizeof(dyld_info_command); } 75 76 void writeTo(uint8_t *buf) const override { 77 auto *c = reinterpret_cast<dyld_info_command *>(buf); 78 c->cmd = LC_DYLD_INFO_ONLY; 79 c->cmdsize = getSize(); 80 if (bindingSection->isNeeded()) { 81 c->bind_off = bindingSection->fileOff; 82 c->bind_size = bindingSection->getFileSize(); 83 } 84 if (weakBindingSection->isNeeded()) { 85 c->weak_bind_off = weakBindingSection->fileOff; 86 c->weak_bind_size = weakBindingSection->getFileSize(); 87 } 88 if (lazyBindingSection->isNeeded()) { 89 c->lazy_bind_off = lazyBindingSection->fileOff; 90 c->lazy_bind_size = lazyBindingSection->getFileSize(); 91 } 92 if (exportSection->isNeeded()) { 93 c->export_off = exportSection->fileOff; 94 c->export_size = exportSection->getFileSize(); 95 } 96 } 97 98 BindingSection *bindingSection; 99 WeakBindingSection *weakBindingSection; 100 LazyBindingSection *lazyBindingSection; 101 ExportSection *exportSection; 102 }; 103 104 class LCDysymtab : public LoadCommand { 105 public: 106 uint32_t getSize() const override { return sizeof(dysymtab_command); } 107 108 void writeTo(uint8_t *buf) const override { 109 auto *c = reinterpret_cast<dysymtab_command *>(buf); 110 c->cmd = LC_DYSYMTAB; 111 c->cmdsize = getSize(); 112 } 113 }; 114 115 class LCSegment : public LoadCommand { 116 public: 117 LCSegment(StringRef name, OutputSegment *seg) : name(name), seg(seg) {} 118 119 uint32_t getSize() const override { 120 return sizeof(segment_command_64) + 121 seg->numNonHiddenSections() * sizeof(section_64); 122 } 123 124 void writeTo(uint8_t *buf) const override { 125 auto *c = reinterpret_cast<segment_command_64 *>(buf); 126 buf += sizeof(segment_command_64); 127 128 c->cmd = LC_SEGMENT_64; 129 c->cmdsize = getSize(); 130 memcpy(c->segname, name.data(), name.size()); 131 c->fileoff = seg->fileOff; 132 c->maxprot = seg->maxProt; 133 c->initprot = seg->initProt; 134 135 if (seg->getSections().empty()) 136 return; 137 138 c->vmaddr = seg->firstSection()->addr; 139 c->vmsize = 140 seg->lastSection()->addr + seg->lastSection()->getSize() - c->vmaddr; 141 c->nsects = seg->numNonHiddenSections(); 142 143 for (OutputSection *osec : seg->getSections()) { 144 if (!isZeroFill(osec->flags)) { 145 assert(osec->fileOff >= seg->fileOff); 146 c->filesize = std::max( 147 c->filesize, osec->fileOff + osec->getFileSize() - seg->fileOff); 148 } 149 150 if (osec->isHidden()) 151 continue; 152 153 auto *sectHdr = reinterpret_cast<section_64 *>(buf); 154 buf += sizeof(section_64); 155 156 memcpy(sectHdr->sectname, osec->name.data(), osec->name.size()); 157 memcpy(sectHdr->segname, name.data(), name.size()); 158 159 sectHdr->addr = osec->addr; 160 sectHdr->offset = osec->fileOff; 161 sectHdr->align = Log2_32(osec->align); 162 sectHdr->flags = osec->flags; 163 sectHdr->size = osec->getSize(); 164 } 165 } 166 167 private: 168 StringRef name; 169 OutputSegment *seg; 170 }; 171 172 class LCMain : public LoadCommand { 173 uint32_t getSize() const override { return sizeof(entry_point_command); } 174 175 void writeTo(uint8_t *buf) const override { 176 auto *c = reinterpret_cast<entry_point_command *>(buf); 177 c->cmd = LC_MAIN; 178 c->cmdsize = getSize(); 179 c->entryoff = config->entry->getFileOffset(); 180 c->stacksize = 0; 181 } 182 }; 183 184 class LCSymtab : public LoadCommand { 185 public: 186 LCSymtab(SymtabSection *symtabSection, StringTableSection *stringTableSection) 187 : symtabSection(symtabSection), stringTableSection(stringTableSection) {} 188 189 uint32_t getSize() const override { return sizeof(symtab_command); } 190 191 void writeTo(uint8_t *buf) const override { 192 auto *c = reinterpret_cast<symtab_command *>(buf); 193 c->cmd = LC_SYMTAB; 194 c->cmdsize = getSize(); 195 c->symoff = symtabSection->fileOff; 196 c->nsyms = symtabSection->getNumSymbols(); 197 c->stroff = stringTableSection->fileOff; 198 c->strsize = stringTableSection->getFileSize(); 199 } 200 201 SymtabSection *symtabSection = nullptr; 202 StringTableSection *stringTableSection = nullptr; 203 }; 204 205 // There are several dylib load commands that share the same structure: 206 // * LC_LOAD_DYLIB 207 // * LC_ID_DYLIB 208 // * LC_REEXPORT_DYLIB 209 class LCDylib : public LoadCommand { 210 public: 211 LCDylib(LoadCommandType type, StringRef path) : type(type), path(path) {} 212 213 uint32_t getSize() const override { 214 return alignTo(sizeof(dylib_command) + path.size() + 1, 8); 215 } 216 217 void writeTo(uint8_t *buf) const override { 218 auto *c = reinterpret_cast<dylib_command *>(buf); 219 buf += sizeof(dylib_command); 220 221 c->cmd = type; 222 c->cmdsize = getSize(); 223 c->dylib.name = sizeof(dylib_command); 224 225 memcpy(buf, path.data(), path.size()); 226 buf[path.size()] = '\0'; 227 } 228 229 private: 230 LoadCommandType type; 231 StringRef path; 232 }; 233 234 class LCLoadDylinker : public LoadCommand { 235 public: 236 uint32_t getSize() const override { 237 return alignTo(sizeof(dylinker_command) + path.size() + 1, 8); 238 } 239 240 void writeTo(uint8_t *buf) const override { 241 auto *c = reinterpret_cast<dylinker_command *>(buf); 242 buf += sizeof(dylinker_command); 243 244 c->cmd = LC_LOAD_DYLINKER; 245 c->cmdsize = getSize(); 246 c->name = sizeof(dylinker_command); 247 248 memcpy(buf, path.data(), path.size()); 249 buf[path.size()] = '\0'; 250 } 251 252 private: 253 // Recent versions of Darwin won't run any binary that has dyld at a 254 // different location. 255 const StringRef path = "/usr/lib/dyld"; 256 }; 257 258 class LCRPath : public LoadCommand { 259 public: 260 LCRPath(StringRef path) : path(path) {} 261 262 uint32_t getSize() const override { 263 return alignTo(sizeof(rpath_command) + path.size() + 1, WordSize); 264 } 265 266 void writeTo(uint8_t *buf) const override { 267 auto *c = reinterpret_cast<rpath_command *>(buf); 268 buf += sizeof(rpath_command); 269 270 c->cmd = LC_RPATH; 271 c->cmdsize = getSize(); 272 c->path = sizeof(rpath_command); 273 274 memcpy(buf, path.data(), path.size()); 275 buf[path.size()] = '\0'; 276 } 277 278 private: 279 StringRef path; 280 }; 281 282 class LCBuildVersion : public LoadCommand { 283 public: 284 LCBuildVersion(const PlatformInfo &platform) : platform(platform) {} 285 286 const int ntools = 1; 287 288 uint32_t getSize() const override { 289 return sizeof(build_version_command) + ntools * sizeof(build_tool_version); 290 } 291 292 void writeTo(uint8_t *buf) const override { 293 auto *c = reinterpret_cast<build_version_command *>(buf); 294 c->cmd = LC_BUILD_VERSION; 295 c->cmdsize = getSize(); 296 c->platform = static_cast<uint32_t>(platform.kind); 297 c->minos = ((platform.minimum.getMajor() << 020) | 298 (platform.minimum.getMinor().getValueOr(0) << 010) | 299 platform.minimum.getSubminor().getValueOr(0)); 300 c->sdk = ((platform.sdk.getMajor() << 020) | 301 (platform.sdk.getMinor().getValueOr(0) << 010) | 302 platform.sdk.getSubminor().getValueOr(0)); 303 c->ntools = ntools; 304 auto *t = reinterpret_cast<build_tool_version *>(&c[1]); 305 t->tool = TOOL_LD; 306 t->version = (LLVM_VERSION_MAJOR << 020) | (LLVM_VERSION_MINOR << 010) | 307 LLVM_VERSION_PATCH; 308 } 309 310 const PlatformInfo &platform; 311 }; 312 313 } // namespace 314 315 void Writer::scanRelocations() { 316 for (InputSection *isec : inputSections) { 317 for (Reloc &r : isec->relocs) { 318 if (auto *s = r.target.dyn_cast<lld::macho::Symbol *>()) { 319 if (isa<Undefined>(s)) 320 error("undefined symbol " + s->getName() + ", referenced from " + 321 sys::path::filename(isec->file->getName())); 322 else 323 target->prepareSymbolRelocation(s, isec, r); 324 } 325 } 326 } 327 } 328 329 void Writer::createLoadCommands() { 330 in.header->addLoadCommand(make<LCDyldInfo>( 331 in.binding, in.weakBinding, lazyBindingSection, exportSection)); 332 in.header->addLoadCommand(make<LCSymtab>(symtabSection, stringTableSection)); 333 in.header->addLoadCommand(make<LCDysymtab>()); 334 for (StringRef path : config->runtimePaths) 335 in.header->addLoadCommand(make<LCRPath>(path)); 336 337 switch (config->outputType) { 338 case MH_EXECUTE: 339 in.header->addLoadCommand(make<LCMain>()); 340 in.header->addLoadCommand(make<LCLoadDylinker>()); 341 break; 342 case MH_DYLIB: 343 in.header->addLoadCommand(make<LCDylib>(LC_ID_DYLIB, config->installName)); 344 break; 345 default: 346 llvm_unreachable("unhandled output file type"); 347 } 348 349 in.header->addLoadCommand(make<LCBuildVersion>(config->platform)); 350 351 uint8_t segIndex = 0; 352 for (OutputSegment *seg : outputSegments) { 353 in.header->addLoadCommand(make<LCSegment>(seg->name, seg)); 354 seg->index = segIndex++; 355 } 356 357 uint64_t dylibOrdinal = 1; 358 for (InputFile *file : inputFiles) { 359 if (auto *dylibFile = dyn_cast<DylibFile>(file)) { 360 in.header->addLoadCommand( 361 make<LCDylib>(LC_LOAD_DYLIB, dylibFile->dylibName)); 362 dylibFile->ordinal = dylibOrdinal++; 363 364 if (dylibFile->reexport) 365 in.header->addLoadCommand( 366 make<LCDylib>(LC_REEXPORT_DYLIB, dylibFile->dylibName)); 367 } 368 } 369 } 370 371 static size_t getSymbolPriority(const SymbolPriorityEntry &entry, 372 const InputFile &file) { 373 return std::max(entry.objectFiles.lookup(sys::path::filename(file.getName())), 374 entry.anyObjectFile); 375 } 376 377 // Each section gets assigned the priority of the highest-priority symbol it 378 // contains. 379 static DenseMap<const InputSection *, size_t> buildInputSectionPriorities() { 380 DenseMap<const InputSection *, size_t> sectionPriorities; 381 382 if (config->priorities.empty()) 383 return sectionPriorities; 384 385 auto addSym = [&](Defined &sym) { 386 auto it = config->priorities.find(sym.getName()); 387 if (it == config->priorities.end()) 388 return; 389 390 SymbolPriorityEntry &entry = it->second; 391 size_t &priority = sectionPriorities[sym.isec]; 392 priority = std::max(priority, getSymbolPriority(entry, *sym.isec->file)); 393 }; 394 395 // TODO: Make sure this handles weak symbols correctly. 396 for (InputFile *file : inputFiles) 397 if (isa<ObjFile>(file) || isa<ArchiveFile>(file)) 398 for (lld::macho::Symbol *sym : file->symbols) 399 if (auto *d = dyn_cast<Defined>(sym)) 400 addSym(*d); 401 402 return sectionPriorities; 403 } 404 405 static int segmentOrder(OutputSegment *seg) { 406 return StringSwitch<int>(seg->name) 407 .Case(segment_names::pageZero, -2) 408 .Case(segment_names::text, -1) 409 // Make sure __LINKEDIT is the last segment (i.e. all its hidden 410 // sections must be ordered after other sections). 411 .Case(segment_names::linkEdit, std::numeric_limits<int>::max()) 412 .Default(0); 413 } 414 415 static int sectionOrder(OutputSection *osec) { 416 StringRef segname = osec->parent->name; 417 // Sections are uniquely identified by their segment + section name. 418 if (segname == segment_names::text) { 419 if (osec->name == section_names::header) 420 return -1; 421 } else if (segname == segment_names::linkEdit) { 422 return StringSwitch<int>(osec->name) 423 .Case(section_names::binding, -6) 424 .Case(section_names::weakBinding, -5) 425 .Case(section_names::lazyBinding, -4) 426 .Case(section_names::export_, -3) 427 .Case(section_names::symbolTable, -2) 428 .Case(section_names::stringTable, -1) 429 .Default(0); 430 } 431 // ZeroFill sections must always be the at the end of their segments, 432 // otherwise subsequent sections may get overwritten with zeroes at runtime. 433 if (isZeroFill(osec->flags)) 434 return std::numeric_limits<int>::max(); 435 return 0; 436 } 437 438 template <typename T, typename F> 439 static std::function<bool(T, T)> compareByOrder(F ord) { 440 return [=](T a, T b) { return ord(a) < ord(b); }; 441 } 442 443 // Sorting only can happen once all outputs have been collected. Here we sort 444 // segments, output sections within each segment, and input sections within each 445 // output segment. 446 static void sortSegmentsAndSections() { 447 llvm::stable_sort(outputSegments, 448 compareByOrder<OutputSegment *>(segmentOrder)); 449 450 DenseMap<const InputSection *, size_t> isecPriorities = 451 buildInputSectionPriorities(); 452 453 uint32_t sectionIndex = 0; 454 for (OutputSegment *seg : outputSegments) { 455 seg->sortOutputSections(compareByOrder<OutputSection *>(sectionOrder)); 456 for (auto *osec : seg->getSections()) { 457 // Now that the output sections are sorted, assign the final 458 // output section indices. 459 if (!osec->isHidden()) 460 osec->index = ++sectionIndex; 461 462 if (!isecPriorities.empty()) { 463 if (auto *merged = dyn_cast<MergedOutputSection>(osec)) { 464 llvm::stable_sort(merged->inputs, 465 [&](InputSection *a, InputSection *b) { 466 return isecPriorities[a] > isecPriorities[b]; 467 }); 468 } 469 } 470 } 471 } 472 } 473 474 void Writer::createOutputSections() { 475 // First, create hidden sections 476 lazyBindingSection = make<LazyBindingSection>(); 477 stringTableSection = make<StringTableSection>(); 478 symtabSection = make<SymtabSection>(*stringTableSection); 479 exportSection = make<ExportSection>(); 480 481 switch (config->outputType) { 482 case MH_EXECUTE: 483 make<PageZeroSection>(); 484 break; 485 case MH_DYLIB: 486 break; 487 default: 488 llvm_unreachable("unhandled output file type"); 489 } 490 491 // Then merge input sections into output sections. 492 MapVector<std::pair<StringRef, StringRef>, MergedOutputSection *> 493 mergedOutputSections; 494 for (InputSection *isec : inputSections) { 495 MergedOutputSection *&osec = 496 mergedOutputSections[{isec->segname, isec->name}]; 497 if (osec == nullptr) 498 osec = make<MergedOutputSection>(isec->name); 499 osec->mergeInput(isec); 500 } 501 502 for (const auto &it : mergedOutputSections) { 503 StringRef segname = it.first.first; 504 MergedOutputSection *osec = it.second; 505 getOrCreateOutputSegment(segname)->addOutputSection(osec); 506 } 507 508 for (SyntheticSection *ssec : syntheticSections) { 509 auto it = mergedOutputSections.find({ssec->segname, ssec->name}); 510 if (it == mergedOutputSections.end()) { 511 if (ssec->isNeeded()) 512 getOrCreateOutputSegment(ssec->segname)->addOutputSection(ssec); 513 } else { 514 error("section from " + it->second->firstSection()->file->getName() + 515 " conflicts with synthetic section " + ssec->segname + "," + 516 ssec->name); 517 } 518 } 519 } 520 521 void Writer::assignAddresses(OutputSegment *seg) { 522 addr = alignTo(addr, PageSize); 523 fileOff = alignTo(fileOff, PageSize); 524 seg->fileOff = fileOff; 525 526 for (auto *osec : seg->getSections()) { 527 if (!osec->isNeeded()) 528 continue; 529 addr = alignTo(addr, osec->align); 530 fileOff = alignTo(fileOff, osec->align); 531 osec->addr = addr; 532 osec->fileOff = isZeroFill(osec->flags) ? 0 : fileOff; 533 osec->finalize(); 534 535 addr += osec->getSize(); 536 fileOff += osec->getFileSize(); 537 } 538 } 539 540 void Writer::openFile() { 541 Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr = 542 FileOutputBuffer::create(config->outputFile, fileOff, 543 FileOutputBuffer::F_executable); 544 545 if (!bufferOrErr) 546 error("failed to open " + config->outputFile + ": " + 547 llvm::toString(bufferOrErr.takeError())); 548 else 549 buffer = std::move(*bufferOrErr); 550 } 551 552 void Writer::writeSections() { 553 uint8_t *buf = buffer->getBufferStart(); 554 for (OutputSegment *seg : outputSegments) 555 for (OutputSection *osec : seg->getSections()) 556 osec->writeTo(buf + osec->fileOff); 557 } 558 559 void Writer::run() { 560 // dyld requires __LINKEDIT segment to always exist (even if empty). 561 OutputSegment *linkEditSegment = 562 getOrCreateOutputSegment(segment_names::linkEdit); 563 564 scanRelocations(); 565 if (in.stubHelper->isNeeded()) 566 in.stubHelper->setup(); 567 568 // Sort and assign sections to their respective segments. No more sections nor 569 // segments may be created after these methods run. 570 createOutputSections(); 571 sortSegmentsAndSections(); 572 573 createLoadCommands(); 574 575 // Ensure that segments (and the sections they contain) are allocated 576 // addresses in ascending order, which dyld requires. 577 // 578 // Note that at this point, __LINKEDIT sections are empty, but we need to 579 // determine addresses of other segments/sections before generating its 580 // contents. 581 for (OutputSegment *seg : outputSegments) 582 if (seg != linkEditSegment) 583 assignAddresses(seg); 584 585 // Fill __LINKEDIT contents. 586 in.binding->finalizeContents(); 587 in.weakBinding->finalizeContents(); 588 lazyBindingSection->finalizeContents(); 589 exportSection->finalizeContents(); 590 symtabSection->finalizeContents(); 591 592 // Now that __LINKEDIT is filled out, do a proper calculation of its 593 // addresses and offsets. 594 assignAddresses(linkEditSegment); 595 596 openFile(); 597 if (errorCount()) 598 return; 599 600 writeSections(); 601 602 if (auto e = buffer->commit()) 603 error("failed to write to the output file: " + toString(std::move(e))); 604 } 605 606 void macho::writeResult() { Writer().run(); } 607 608 void macho::createSyntheticSections() { 609 in.header = make<MachHeaderSection>(); 610 in.binding = make<BindingSection>(); 611 in.weakBinding = make<WeakBindingSection>(); 612 in.got = make<GotSection>(); 613 in.tlvPointers = make<TlvPointerSection>(); 614 in.lazyPointers = make<LazyPointerSection>(); 615 in.stubs = make<StubsSection>(); 616 in.stubHelper = make<StubHelperSection>(); 617 in.imageLoaderCache = make<ImageLoaderCacheSection>(); 618 } 619