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