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 BindingSection *bindingSection = 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 (auto &p : seg->getSections()) { 138 StringRef s = p.first; 139 OutputSection *section = p.second; 140 c->filesize += section->getFileSize(); 141 142 if (section->isHidden()) 143 continue; 144 145 auto *sectHdr = reinterpret_cast<section_64 *>(buf); 146 buf += sizeof(section_64); 147 148 memcpy(sectHdr->sectname, s.data(), s.size()); 149 memcpy(sectHdr->segname, name.data(), name.size()); 150 151 sectHdr->addr = section->addr; 152 sectHdr->offset = section->fileOff; 153 sectHdr->align = Log2_32(section->align); 154 sectHdr->flags = section->flags; 155 sectHdr->size = section->getSize(); 156 } 157 } 158 159 private: 160 StringRef name; 161 OutputSegment *seg; 162 }; 163 164 class LCMain : public LoadCommand { 165 uint32_t getSize() const override { return sizeof(entry_point_command); } 166 167 void writeTo(uint8_t *buf) const override { 168 auto *c = reinterpret_cast<entry_point_command *>(buf); 169 c->cmd = LC_MAIN; 170 c->cmdsize = getSize(); 171 c->entryoff = config->entry->getFileOffset(); 172 c->stacksize = 0; 173 } 174 }; 175 176 class LCSymtab : public LoadCommand { 177 public: 178 LCSymtab(SymtabSection *symtabSection, StringTableSection *stringTableSection) 179 : symtabSection(symtabSection), stringTableSection(stringTableSection) {} 180 181 uint32_t getSize() const override { return sizeof(symtab_command); } 182 183 void writeTo(uint8_t *buf) const override { 184 auto *c = reinterpret_cast<symtab_command *>(buf); 185 c->cmd = LC_SYMTAB; 186 c->cmdsize = getSize(); 187 c->symoff = symtabSection->fileOff; 188 c->nsyms = symtabSection->getNumSymbols(); 189 c->stroff = stringTableSection->fileOff; 190 c->strsize = stringTableSection->getFileSize(); 191 } 192 193 SymtabSection *symtabSection = nullptr; 194 StringTableSection *stringTableSection = nullptr; 195 }; 196 197 // There are several dylib load commands that share the same structure: 198 // * LC_LOAD_DYLIB 199 // * LC_ID_DYLIB 200 // * LC_REEXPORT_DYLIB 201 class LCDylib : public LoadCommand { 202 public: 203 LCDylib(LoadCommandType type, StringRef path) : type(type), path(path) {} 204 205 uint32_t getSize() const override { 206 return alignTo(sizeof(dylib_command) + path.size() + 1, 8); 207 } 208 209 void writeTo(uint8_t *buf) const override { 210 auto *c = reinterpret_cast<dylib_command *>(buf); 211 buf += sizeof(dylib_command); 212 213 c->cmd = type; 214 c->cmdsize = getSize(); 215 c->dylib.name = sizeof(dylib_command); 216 217 memcpy(buf, path.data(), path.size()); 218 buf[path.size()] = '\0'; 219 } 220 221 private: 222 LoadCommandType type; 223 StringRef path; 224 }; 225 226 class LCLoadDylinker : public LoadCommand { 227 public: 228 uint32_t getSize() const override { 229 return alignTo(sizeof(dylinker_command) + path.size() + 1, 8); 230 } 231 232 void writeTo(uint8_t *buf) const override { 233 auto *c = reinterpret_cast<dylinker_command *>(buf); 234 buf += sizeof(dylinker_command); 235 236 c->cmd = LC_LOAD_DYLINKER; 237 c->cmdsize = getSize(); 238 c->name = sizeof(dylinker_command); 239 240 memcpy(buf, path.data(), path.size()); 241 buf[path.size()] = '\0'; 242 } 243 244 private: 245 // Recent versions of Darwin won't run any binary that has dyld at a 246 // different location. 247 const StringRef path = "/usr/lib/dyld"; 248 }; 249 } // namespace 250 251 void Writer::scanRelocations() { 252 for (InputSection *isec : inputSections) { 253 for (Reloc &r : isec->relocs) { 254 if (auto *s = r.target.dyn_cast<lld::macho::Symbol *>()) { 255 if (isa<Undefined>(s)) 256 error("undefined symbol " + s->getName() + ", referenced from " + 257 sys::path::filename(isec->file->getName())); 258 else if (auto *dylibSymbol = dyn_cast<DylibSymbol>(s)) 259 target->prepareDylibSymbolRelocation(*dylibSymbol, r.type); 260 } 261 } 262 } 263 } 264 265 void Writer::createLoadCommands() { 266 headerSection->addLoadCommand( 267 make<LCDyldInfo>(bindingSection, lazyBindingSection, exportSection)); 268 headerSection->addLoadCommand( 269 make<LCSymtab>(symtabSection, stringTableSection)); 270 headerSection->addLoadCommand(make<LCDysymtab>()); 271 272 switch (config->outputType) { 273 case MH_EXECUTE: 274 headerSection->addLoadCommand(make<LCMain>()); 275 headerSection->addLoadCommand(make<LCLoadDylinker>()); 276 break; 277 case MH_DYLIB: 278 headerSection->addLoadCommand( 279 make<LCDylib>(LC_ID_DYLIB, config->installName)); 280 break; 281 default: 282 llvm_unreachable("unhandled output file type"); 283 } 284 285 uint8_t segIndex = 0; 286 for (OutputSegment *seg : outputSegments) { 287 headerSection->addLoadCommand(make<LCSegment>(seg->name, seg)); 288 seg->index = segIndex++; 289 } 290 291 uint64_t dylibOrdinal = 1; 292 for (InputFile *file : inputFiles) { 293 if (auto *dylibFile = dyn_cast<DylibFile>(file)) { 294 headerSection->addLoadCommand( 295 make<LCDylib>(LC_LOAD_DYLIB, dylibFile->dylibName)); 296 dylibFile->ordinal = dylibOrdinal++; 297 298 if (dylibFile->reexport) 299 headerSection->addLoadCommand( 300 make<LCDylib>(LC_REEXPORT_DYLIB, dylibFile->dylibName)); 301 } 302 } 303 } 304 305 static size_t getSymbolPriority(const SymbolPriorityEntry &entry, 306 const InputFile &file) { 307 return std::max(entry.objectFiles.lookup(sys::path::filename(file.getName())), 308 entry.anyObjectFile); 309 } 310 311 // Each section gets assigned the priority of the highest-priority symbol it 312 // contains. 313 static DenseMap<const InputSection *, size_t> buildInputSectionPriorities() { 314 DenseMap<const InputSection *, size_t> sectionPriorities; 315 316 if (config->priorities.empty()) 317 return sectionPriorities; 318 319 auto addSym = [&](Defined &sym) { 320 auto it = config->priorities.find(sym.getName()); 321 if (it == config->priorities.end()) 322 return; 323 324 SymbolPriorityEntry &entry = it->second; 325 size_t &priority = sectionPriorities[sym.isec]; 326 priority = std::max(priority, getSymbolPriority(entry, *sym.isec->file)); 327 }; 328 329 // TODO: Make sure this handles weak symbols correctly. 330 for (InputFile *file : inputFiles) 331 if (isa<ObjFile>(file) || isa<ArchiveFile>(file)) 332 for (lld::macho::Symbol *sym : file->symbols) 333 if (auto *d = dyn_cast<Defined>(sym)) 334 addSym(*d); 335 336 return sectionPriorities; 337 } 338 339 // Sorting only can happen once all outputs have been collected. Here we sort 340 // segments, output sections within each segment, and input sections within each 341 // output segment. 342 static void sortSegmentsAndSections() { 343 auto comparator = OutputSegmentComparator(); 344 llvm::stable_sort(outputSegments, comparator); 345 346 DenseMap<const InputSection *, size_t> isecPriorities = 347 buildInputSectionPriorities(); 348 349 uint32_t sectionIndex = 0; 350 for (OutputSegment *seg : outputSegments) { 351 seg->sortOutputSections(&comparator); 352 for (auto &p : seg->getSections()) { 353 OutputSection *section = p.second; 354 // Now that the output sections are sorted, assign the final 355 // output section indices. 356 if (!section->isHidden()) 357 section->index = ++sectionIndex; 358 359 if (!isecPriorities.empty()) { 360 if (auto *merged = dyn_cast<MergedOutputSection>(section)) { 361 llvm::stable_sort(merged->inputs, 362 [&](InputSection *a, InputSection *b) { 363 return isecPriorities[a] > isecPriorities[b]; 364 }); 365 } 366 } 367 } 368 } 369 } 370 371 void Writer::createOutputSections() { 372 // First, create hidden sections 373 headerSection = make<MachHeaderSection>(); 374 bindingSection = make<BindingSection>(); 375 lazyBindingSection = make<LazyBindingSection>(); 376 stringTableSection = make<StringTableSection>(); 377 symtabSection = make<SymtabSection>(*stringTableSection); 378 exportSection = make<ExportSection>(); 379 380 switch (config->outputType) { 381 case MH_EXECUTE: 382 make<PageZeroSection>(); 383 break; 384 case MH_DYLIB: 385 break; 386 default: 387 llvm_unreachable("unhandled output file type"); 388 } 389 390 // Then merge input sections into output sections/segments. 391 for (InputSection *isec : inputSections) { 392 getOrCreateOutputSegment(isec->segname) 393 ->getOrCreateOutputSection(isec->name) 394 ->mergeInput(isec); 395 } 396 397 // Remove unneeded segments and sections. 398 // TODO: Avoid creating unneeded segments in the first place 399 for (auto it = outputSegments.begin(); it != outputSegments.end();) { 400 OutputSegment *seg = *it; 401 seg->removeUnneededSections(); 402 if (!seg->isNeeded()) 403 it = outputSegments.erase(it); 404 else 405 ++it; 406 } 407 } 408 409 void Writer::assignAddresses(OutputSegment *seg) { 410 addr = alignTo(addr, PageSize); 411 fileOff = alignTo(fileOff, PageSize); 412 seg->fileOff = fileOff; 413 414 for (auto &p : seg->getSections()) { 415 OutputSection *section = p.second; 416 addr = alignTo(addr, section->align); 417 fileOff = alignTo(fileOff, section->align); 418 section->addr = addr; 419 section->fileOff = fileOff; 420 section->finalize(); 421 422 addr += section->getSize(); 423 fileOff += section->getFileSize(); 424 } 425 } 426 427 void Writer::openFile() { 428 Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr = 429 FileOutputBuffer::create(config->outputFile, fileOff, 430 FileOutputBuffer::F_executable); 431 432 if (!bufferOrErr) 433 error("failed to open " + config->outputFile + ": " + 434 llvm::toString(bufferOrErr.takeError())); 435 else 436 buffer = std::move(*bufferOrErr); 437 } 438 439 void Writer::writeSections() { 440 uint8_t *buf = buffer->getBufferStart(); 441 for (OutputSegment *seg : outputSegments) { 442 for (auto &p : seg->getSections()) { 443 OutputSection *section = p.second; 444 section->writeTo(buf + section->fileOff); 445 } 446 } 447 } 448 449 void Writer::run() { 450 // dyld requires __LINKEDIT segment to always exist (even if empty). 451 OutputSegment *linkEditSegment = 452 getOrCreateOutputSegment(segment_names::linkEdit); 453 454 scanRelocations(); 455 if (in.stubHelper->isNeeded()) 456 in.stubHelper->setup(); 457 458 // Sort and assign sections to their respective segments. No more sections nor 459 // segments may be created after these methods run. 460 createOutputSections(); 461 sortSegmentsAndSections(); 462 463 createLoadCommands(); 464 465 // Ensure that segments (and the sections they contain) are allocated 466 // addresses in ascending order, which dyld requires. 467 // 468 // Note that at this point, __LINKEDIT sections are empty, but we need to 469 // determine addresses of other segments/sections before generating its 470 // contents. 471 for (OutputSegment *seg : outputSegments) 472 if (seg != linkEditSegment) 473 assignAddresses(seg); 474 475 // Fill __LINKEDIT contents. 476 bindingSection->finalizeContents(); 477 lazyBindingSection->finalizeContents(); 478 exportSection->finalizeContents(); 479 symtabSection->finalizeContents(); 480 481 // Now that __LINKEDIT is filled out, do a proper calculation of its 482 // addresses and offsets. 483 assignAddresses(linkEditSegment); 484 485 openFile(); 486 if (errorCount()) 487 return; 488 489 writeSections(); 490 491 if (auto e = buffer->commit()) 492 error("failed to write to the output file: " + toString(std::move(e))); 493 } 494 495 void macho::writeResult() { Writer().run(); } 496 497 void macho::createSyntheticSections() { 498 in.got = make<GotSection>(); 499 in.lazyPointers = make<LazyPointerSection>(); 500 in.stubs = make<StubsSection>(); 501 in.stubHelper = make<StubHelperSection>(); 502 in.imageLoaderCache = make<ImageLoaderCacheSection>(); 503 } 504