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 "OutputSegment.h" 14 #include "SymbolTable.h" 15 #include "Symbols.h" 16 #include "SyntheticSections.h" 17 #include "Target.h" 18 19 #include "lld/Common/ErrorHandler.h" 20 #include "lld/Common/Memory.h" 21 #include "llvm/BinaryFormat/MachO.h" 22 #include "llvm/Support/LEB128.h" 23 #include "llvm/Support/MathExtras.h" 24 25 using namespace llvm; 26 using namespace llvm::MachO; 27 using namespace lld; 28 using namespace lld::macho; 29 30 namespace { 31 class LCLinkEdit; 32 class LCDyldInfo; 33 class LCSymtab; 34 35 class Writer { 36 public: 37 Writer() : buffer(errorHandler().outputBuffer) {} 38 39 void scanRelocations(); 40 void createHiddenSections(); 41 void sortSections(); 42 void createLoadCommands(); 43 void assignAddresses(OutputSegment *); 44 void createSymtabContents(); 45 46 void openFile(); 47 void writeSections(); 48 49 void run(); 50 51 std::unique_ptr<FileOutputBuffer> &buffer; 52 uint64_t addr = 0; 53 uint64_t fileOff = 0; 54 MachHeaderSection *headerSection = nullptr; 55 BindingSection *bindingSection = nullptr; 56 ExportSection *exportSection = nullptr; 57 StringTableSection *stringTableSection = nullptr; 58 SymtabSection *symtabSection = nullptr; 59 }; 60 61 // LC_DYLD_INFO_ONLY stores the offsets of symbol import/export information. 62 class LCDyldInfo : public LoadCommand { 63 public: 64 LCDyldInfo(BindingSection *bindingSection, ExportSection *exportSection) 65 : bindingSection(bindingSection), exportSection(exportSection) {} 66 67 uint32_t getSize() const override { return sizeof(dyld_info_command); } 68 69 void writeTo(uint8_t *buf) const override { 70 auto *c = reinterpret_cast<dyld_info_command *>(buf); 71 c->cmd = LC_DYLD_INFO_ONLY; 72 c->cmdsize = getSize(); 73 if (bindingSection->isNeeded()) { 74 c->bind_off = bindingSection->getFileOffset(); 75 c->bind_size = bindingSection->getFileSize(); 76 } 77 if (exportSection->isNeeded()) { 78 c->export_off = exportSection->getFileOffset(); 79 c->export_size = exportSection->getFileSize(); 80 } 81 } 82 83 BindingSection *bindingSection; 84 ExportSection *exportSection; 85 }; 86 87 class LCDysymtab : public LoadCommand { 88 public: 89 uint32_t getSize() const override { return sizeof(dysymtab_command); } 90 91 void writeTo(uint8_t *buf) const override { 92 auto *c = reinterpret_cast<dysymtab_command *>(buf); 93 c->cmd = LC_DYSYMTAB; 94 c->cmdsize = getSize(); 95 } 96 }; 97 98 class LCSegment : public LoadCommand { 99 public: 100 LCSegment(StringRef name, OutputSegment *seg) : name(name), seg(seg) {} 101 102 uint32_t getSize() const override { 103 return sizeof(segment_command_64) + 104 seg->numNonHiddenSections * sizeof(section_64); 105 } 106 107 void writeTo(uint8_t *buf) const override { 108 auto *c = reinterpret_cast<segment_command_64 *>(buf); 109 buf += sizeof(segment_command_64); 110 111 c->cmd = LC_SEGMENT_64; 112 c->cmdsize = getSize(); 113 memcpy(c->segname, name.data(), name.size()); 114 c->fileoff = seg->fileOff; 115 c->maxprot = seg->maxProt; 116 c->initprot = seg->initProt; 117 118 if (seg->getSections().empty()) 119 return; 120 121 c->vmaddr = seg->firstSection()->addr; 122 c->vmsize = 123 seg->lastSection()->addr + seg->lastSection()->getSize() - c->vmaddr; 124 c->nsects = seg->numNonHiddenSections; 125 126 for (auto &p : seg->getSections()) { 127 StringRef s = p.first; 128 ArrayRef<InputSection *> sections = p.second; 129 for (InputSection *isec : sections) 130 c->filesize += isec->getFileSize(); 131 if (sections[0]->isHidden()) 132 continue; 133 134 auto *sectHdr = reinterpret_cast<section_64 *>(buf); 135 buf += sizeof(section_64); 136 137 memcpy(sectHdr->sectname, s.data(), s.size()); 138 memcpy(sectHdr->segname, name.data(), name.size()); 139 140 sectHdr->addr = sections[0]->addr; 141 sectHdr->offset = sections[0]->getFileOffset(); 142 sectHdr->align = sections[0]->align; 143 uint32_t maxAlign = 0; 144 for (const InputSection *section : sections) 145 maxAlign = std::max(maxAlign, section->align); 146 sectHdr->align = Log2_32(maxAlign); 147 sectHdr->flags = sections[0]->flags; 148 sectHdr->size = sections.back()->addr + sections.back()->getSize() - 149 sections[0]->addr; 150 } 151 } 152 153 private: 154 StringRef name; 155 OutputSegment *seg; 156 }; 157 158 class LCMain : public LoadCommand { 159 uint32_t getSize() const override { return sizeof(entry_point_command); } 160 161 void writeTo(uint8_t *buf) const override { 162 auto *c = reinterpret_cast<entry_point_command *>(buf); 163 c->cmd = LC_MAIN; 164 c->cmdsize = getSize(); 165 c->entryoff = config->entry->getVA() - ImageBase; 166 c->stacksize = 0; 167 } 168 }; 169 170 class LCSymtab : public LoadCommand { 171 public: 172 LCSymtab(SymtabSection *symtabSection, StringTableSection *stringTableSection) 173 : symtabSection(symtabSection), stringTableSection(stringTableSection) {} 174 175 uint32_t getSize() const override { return sizeof(symtab_command); } 176 177 void writeTo(uint8_t *buf) const override { 178 auto *c = reinterpret_cast<symtab_command *>(buf); 179 c->cmd = LC_SYMTAB; 180 c->cmdsize = getSize(); 181 c->symoff = symtabSection->getFileOffset(); 182 c->nsyms = symtabSection->getNumSymbols(); 183 c->stroff = stringTableSection->getFileOffset(); 184 c->strsize = stringTableSection->getFileSize(); 185 } 186 187 SymtabSection *symtabSection = nullptr; 188 StringTableSection *stringTableSection = nullptr; 189 }; 190 191 class LCLoadDylib : public LoadCommand { 192 public: 193 LCLoadDylib(StringRef path) : path(path) {} 194 195 uint32_t getSize() const override { 196 return alignTo(sizeof(dylib_command) + path.size() + 1, 8); 197 } 198 199 void writeTo(uint8_t *buf) const override { 200 auto *c = reinterpret_cast<dylib_command *>(buf); 201 buf += sizeof(dylib_command); 202 203 c->cmd = LC_LOAD_DYLIB; 204 c->cmdsize = getSize(); 205 c->dylib.name = sizeof(dylib_command); 206 207 memcpy(buf, path.data(), path.size()); 208 buf[path.size()] = '\0'; 209 } 210 211 private: 212 StringRef path; 213 }; 214 215 class LCIdDylib : public LoadCommand { 216 public: 217 LCIdDylib(StringRef name) : name(name) {} 218 219 uint32_t getSize() const override { 220 return alignTo(sizeof(dylib_command) + name.size() + 1, 8); 221 } 222 223 void writeTo(uint8_t *buf) const override { 224 auto *c = reinterpret_cast<dylib_command *>(buf); 225 buf += sizeof(dylib_command); 226 227 c->cmd = LC_ID_DYLIB; 228 c->cmdsize = getSize(); 229 c->dylib.name = sizeof(dylib_command); 230 231 memcpy(buf, name.data(), name.size()); 232 buf[name.size()] = '\0'; 233 } 234 235 private: 236 StringRef name; 237 }; 238 239 class LCLoadDylinker : public LoadCommand { 240 public: 241 uint32_t getSize() const override { 242 return alignTo(sizeof(dylinker_command) + path.size() + 1, 8); 243 } 244 245 void writeTo(uint8_t *buf) const override { 246 auto *c = reinterpret_cast<dylinker_command *>(buf); 247 buf += sizeof(dylinker_command); 248 249 c->cmd = LC_LOAD_DYLINKER; 250 c->cmdsize = getSize(); 251 c->name = sizeof(dylinker_command); 252 253 memcpy(buf, path.data(), path.size()); 254 buf[path.size()] = '\0'; 255 } 256 257 private: 258 // Recent versions of Darwin won't run any binary that has dyld at a 259 // different location. 260 const StringRef path = "/usr/lib/dyld"; 261 }; 262 263 class SectionComparator { 264 public: 265 struct OrderInfo { 266 uint32_t segmentOrder; 267 DenseMap<StringRef, uint32_t> sectionOrdering; 268 }; 269 270 SectionComparator() { 271 // This defines the order of segments and the sections within each segment. 272 // Segments that are not mentioned here will end up at defaultPosition; 273 // sections that are not mentioned will end up at the end of the section 274 // list for their given segment. 275 std::vector<std::pair<StringRef, std::vector<StringRef>>> ordering{ 276 {segment_names::pageZero, {}}, 277 {segment_names::text, {section_names::header}}, 278 {defaultPosition, {}}, 279 // Make sure __LINKEDIT is the last segment (i.e. all its hidden 280 // sections must be ordered after other sections). 281 {segment_names::linkEdit, 282 { 283 section_names::binding, 284 section_names::export_, 285 section_names::symbolTable, 286 section_names::stringTable, 287 }}, 288 }; 289 290 for (uint32_t i = 0, n = ordering.size(); i < n; ++i) { 291 auto &p = ordering[i]; 292 StringRef segname = p.first; 293 const std::vector<StringRef> §Ordering = p.second; 294 OrderInfo &info = orderMap[segname]; 295 info.segmentOrder = i; 296 for (uint32_t j = 0, m = sectOrdering.size(); j < m; ++j) 297 info.sectionOrdering[sectOrdering[j]] = j; 298 } 299 } 300 301 // Return a {segmentOrder, sectionOrder} pair. Using this as a key will 302 // ensure that all sections in the same segment are sorted contiguously. 303 std::pair<uint32_t, uint32_t> order(const InputSection *isec) { 304 auto it = orderMap.find(isec->segname); 305 if (it == orderMap.end()) 306 return {orderMap[defaultPosition].segmentOrder, 0}; 307 OrderInfo &info = it->second; 308 auto sectIt = info.sectionOrdering.find(isec->name); 309 if (sectIt != info.sectionOrdering.end()) 310 return {info.segmentOrder, sectIt->second}; 311 return {info.segmentOrder, info.sectionOrdering.size()}; 312 } 313 314 bool operator()(const InputSection *a, const InputSection *b) { 315 return order(a) < order(b); 316 } 317 318 private: 319 const StringRef defaultPosition = StringRef(); 320 DenseMap<StringRef, OrderInfo> orderMap; 321 }; 322 323 } // namespace 324 325 template <typename SectionType, typename... ArgT> 326 SectionType *createInputSection(ArgT &&... args) { 327 auto *section = make<SectionType>(std::forward<ArgT>(args)...); 328 inputSections.push_back(section); 329 return section; 330 } 331 332 void Writer::scanRelocations() { 333 for (InputSection *sect : inputSections) 334 for (Reloc &r : sect->relocs) 335 if (auto *s = r.target.dyn_cast<Symbol *>()) 336 if (auto *dylibSymbol = dyn_cast<DylibSymbol>(s)) 337 in.got->addEntry(*dylibSymbol); 338 } 339 340 void Writer::createLoadCommands() { 341 headerSection->addLoadCommand( 342 make<LCDyldInfo>(bindingSection, exportSection)); 343 headerSection->addLoadCommand( 344 make<LCSymtab>(symtabSection, stringTableSection)); 345 headerSection->addLoadCommand(make<LCDysymtab>()); 346 347 switch (config->outputType) { 348 case MH_EXECUTE: 349 headerSection->addLoadCommand(make<LCMain>()); 350 headerSection->addLoadCommand(make<LCLoadDylinker>()); 351 break; 352 case MH_DYLIB: 353 headerSection->addLoadCommand(make<LCIdDylib>(config->installName)); 354 break; 355 default: 356 llvm_unreachable("unhandled output file type"); 357 } 358 359 uint8_t segIndex = 0; 360 for (OutputSegment *seg : outputSegments) { 361 if (seg->isNeeded()) { 362 headerSection->addLoadCommand(make<LCSegment>(seg->name, seg)); 363 seg->index = segIndex++; 364 } 365 } 366 367 uint64_t dylibOrdinal = 1; 368 for (InputFile *file : inputFiles) { 369 if (auto *dylibFile = dyn_cast<DylibFile>(file)) { 370 headerSection->addLoadCommand(make<LCLoadDylib>(dylibFile->dylibName)); 371 dylibFile->ordinal = dylibOrdinal++; 372 } 373 } 374 375 // TODO: dyld requires libSystem to be loaded. libSystem is a universal 376 // binary and we don't have support for that yet, so mock it out here. 377 headerSection->addLoadCommand( 378 make<LCLoadDylib>("/usr/lib/libSystem.B.dylib")); 379 } 380 381 void Writer::createHiddenSections() { 382 headerSection = createInputSection<MachHeaderSection>(); 383 bindingSection = createInputSection<BindingSection>(); 384 stringTableSection = createInputSection<StringTableSection>(); 385 symtabSection = createInputSection<SymtabSection>(*stringTableSection); 386 exportSection = createInputSection<ExportSection>(); 387 388 switch (config->outputType) { 389 case MH_EXECUTE: 390 createInputSection<PageZeroSection>(); 391 break; 392 case MH_DYLIB: 393 break; 394 default: 395 llvm_unreachable("unhandled output file type"); 396 } 397 } 398 399 void Writer::sortSections() { 400 llvm::stable_sort(inputSections, SectionComparator()); 401 402 // TODO This is wrong; input sections ought to be grouped into 403 // output sections, which are then organized like this. 404 uint32_t sectionIndex = 0; 405 // Add input sections to output segments. 406 for (InputSection *isec : inputSections) { 407 if (isec->isNeeded()) { 408 if (!isec->isHidden()) 409 isec->sectionIndex = ++sectionIndex; 410 getOrCreateOutputSegment(isec->segname)->addSection(isec); 411 } 412 } 413 } 414 415 void Writer::assignAddresses(OutputSegment *seg) { 416 addr = alignTo(addr, PageSize); 417 fileOff = alignTo(fileOff, PageSize); 418 seg->fileOff = fileOff; 419 420 for (auto &p : seg->getSections()) { 421 ArrayRef<InputSection *> sections = p.second; 422 for (InputSection *isec : sections) { 423 addr = alignTo(addr, isec->align); 424 // We must align the file offsets too to avoid misaligned writes of 425 // structs. 426 fileOff = alignTo(fileOff, isec->align); 427 isec->addr = addr; 428 addr += isec->getSize(); 429 fileOff += isec->getFileSize(); 430 } 431 } 432 } 433 434 void Writer::openFile() { 435 Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr = 436 FileOutputBuffer::create(config->outputFile, fileOff, 437 FileOutputBuffer::F_executable); 438 439 if (!bufferOrErr) 440 error("failed to open " + config->outputFile + ": " + 441 llvm::toString(bufferOrErr.takeError())); 442 else 443 buffer = std::move(*bufferOrErr); 444 } 445 446 void Writer::writeSections() { 447 uint8_t *buf = buffer->getBufferStart(); 448 for (OutputSegment *seg : outputSegments) { 449 uint64_t fileOff = seg->fileOff; 450 for (auto § : seg->getSections()) { 451 for (InputSection *isec : sect.second) { 452 fileOff = alignTo(fileOff, isec->align); 453 isec->writeTo(buf + fileOff); 454 fileOff += isec->getFileSize(); 455 } 456 } 457 } 458 } 459 460 void Writer::run() { 461 scanRelocations(); 462 createHiddenSections(); 463 // Sort and assign sections to their respective segments. No more sections can 464 // be created after this method runs. 465 sortSections(); 466 // dyld requires __LINKEDIT segment to always exist (even if empty). 467 getOrCreateOutputSegment(segment_names::linkEdit); 468 // No more segments can be created after this method runs. 469 createLoadCommands(); 470 471 // Ensure that segments (and the sections they contain) are allocated 472 // addresses in ascending order, which dyld requires. 473 // 474 // Note that at this point, __LINKEDIT sections are empty, but we need to 475 // determine addresses of other segments/sections before generating its 476 // contents. 477 for (OutputSegment *seg : outputSegments) 478 assignAddresses(seg); 479 480 // Fill __LINKEDIT contents. 481 bindingSection->finalizeContents(); 482 exportSection->finalizeContents(); 483 symtabSection->finalizeContents(); 484 485 // Now that __LINKEDIT is filled out, do a proper calculation of its 486 // addresses and offsets. We don't have to recalculate the other segments 487 // since sortSections() ensures that __LINKEDIT is the last segment. 488 assignAddresses(getOutputSegment(segment_names::linkEdit)); 489 490 openFile(); 491 if (errorCount()) 492 return; 493 494 writeSections(); 495 496 if (auto e = buffer->commit()) 497 error("failed to write to the output file: " + toString(std::move(e))); 498 } 499 500 void macho::writeResult() { Writer().run(); } 501 502 void macho::createSyntheticSections() { 503 in.got = createInputSection<GotSection>(); 504 } 505