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