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 "CallGraphSort.h" 11 #include "Config.h" 12 #include "DLL.h" 13 #include "InputFiles.h" 14 #include "LLDMapFile.h" 15 #include "MapFile.h" 16 #include "PDB.h" 17 #include "SymbolTable.h" 18 #include "Symbols.h" 19 #include "lld/Common/ErrorHandler.h" 20 #include "lld/Common/Memory.h" 21 #include "lld/Common/Timer.h" 22 #include "llvm/ADT/DenseMap.h" 23 #include "llvm/ADT/STLExtras.h" 24 #include "llvm/ADT/StringSet.h" 25 #include "llvm/ADT/StringSwitch.h" 26 #include "llvm/Support/BinaryStreamReader.h" 27 #include "llvm/Support/Debug.h" 28 #include "llvm/Support/Endian.h" 29 #include "llvm/Support/FileOutputBuffer.h" 30 #include "llvm/Support/Parallel.h" 31 #include "llvm/Support/Path.h" 32 #include "llvm/Support/RandomNumberGenerator.h" 33 #include "llvm/Support/xxhash.h" 34 #include <algorithm> 35 #include <cstdio> 36 #include <map> 37 #include <memory> 38 #include <utility> 39 40 using namespace llvm; 41 using namespace llvm::COFF; 42 using namespace llvm::object; 43 using namespace llvm::support; 44 using namespace llvm::support::endian; 45 using namespace lld; 46 using namespace lld::coff; 47 48 /* To re-generate DOSProgram: 49 $ cat > /tmp/DOSProgram.asm 50 org 0 51 ; Copy cs to ds. 52 push cs 53 pop ds 54 ; Point ds:dx at the $-terminated string. 55 mov dx, str 56 ; Int 21/AH=09h: Write string to standard output. 57 mov ah, 0x9 58 int 0x21 59 ; Int 21/AH=4Ch: Exit with return code (in AL). 60 mov ax, 0x4C01 61 int 0x21 62 str: 63 db 'This program cannot be run in DOS mode.$' 64 align 8, db 0 65 $ nasm -fbin /tmp/DOSProgram.asm -o /tmp/DOSProgram.bin 66 $ xxd -i /tmp/DOSProgram.bin 67 */ 68 static unsigned char dosProgram[] = { 69 0x0e, 0x1f, 0xba, 0x0e, 0x00, 0xb4, 0x09, 0xcd, 0x21, 0xb8, 0x01, 0x4c, 70 0xcd, 0x21, 0x54, 0x68, 0x69, 0x73, 0x20, 0x70, 0x72, 0x6f, 0x67, 0x72, 71 0x61, 0x6d, 0x20, 0x63, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x20, 0x62, 0x65, 72 0x20, 0x72, 0x75, 0x6e, 0x20, 0x69, 0x6e, 0x20, 0x44, 0x4f, 0x53, 0x20, 73 0x6d, 0x6f, 0x64, 0x65, 0x2e, 0x24, 0x00, 0x00 74 }; 75 static_assert(sizeof(dosProgram) % 8 == 0, 76 "DOSProgram size must be multiple of 8"); 77 78 static const int dosStubSize = sizeof(dos_header) + sizeof(dosProgram); 79 static_assert(dosStubSize % 8 == 0, "DOSStub size must be multiple of 8"); 80 81 static const int numberOfDataDirectory = 16; 82 83 // Global vector of all output sections. After output sections are finalized, 84 // this can be indexed by Chunk::getOutputSection. 85 static std::vector<OutputSection *> outputSections; 86 87 OutputSection *Chunk::getOutputSection() const { 88 return osidx == 0 ? nullptr : outputSections[osidx - 1]; 89 } 90 91 void OutputSection::clear() { outputSections.clear(); } 92 93 namespace { 94 95 class DebugDirectoryChunk : public NonSectionChunk { 96 public: 97 DebugDirectoryChunk(const std::vector<std::pair<COFF::DebugType, Chunk *>> &r, 98 bool writeRepro) 99 : records(r), writeRepro(writeRepro) {} 100 101 size_t getSize() const override { 102 return (records.size() + int(writeRepro)) * sizeof(debug_directory); 103 } 104 105 void writeTo(uint8_t *b) const override { 106 auto *d = reinterpret_cast<debug_directory *>(b); 107 108 for (const std::pair<COFF::DebugType, Chunk *>& record : records) { 109 Chunk *c = record.second; 110 OutputSection *os = c->getOutputSection(); 111 uint64_t offs = os->getFileOff() + (c->getRVA() - os->getRVA()); 112 fillEntry(d, record.first, c->getSize(), c->getRVA(), offs); 113 ++d; 114 } 115 116 if (writeRepro) { 117 // FIXME: The COFF spec allows either a 0-sized entry to just say 118 // "the timestamp field is really a hash", or a 4-byte size field 119 // followed by that many bytes containing a longer hash (with the 120 // lowest 4 bytes usually being the timestamp in little-endian order). 121 // Consider storing the full 8 bytes computed by xxHash64 here. 122 fillEntry(d, COFF::IMAGE_DEBUG_TYPE_REPRO, 0, 0, 0); 123 } 124 } 125 126 void setTimeDateStamp(uint32_t timeDateStamp) { 127 for (support::ulittle32_t *tds : timeDateStamps) 128 *tds = timeDateStamp; 129 } 130 131 private: 132 void fillEntry(debug_directory *d, COFF::DebugType debugType, size_t size, 133 uint64_t rva, uint64_t offs) const { 134 d->Characteristics = 0; 135 d->TimeDateStamp = 0; 136 d->MajorVersion = 0; 137 d->MinorVersion = 0; 138 d->Type = debugType; 139 d->SizeOfData = size; 140 d->AddressOfRawData = rva; 141 d->PointerToRawData = offs; 142 143 timeDateStamps.push_back(&d->TimeDateStamp); 144 } 145 146 mutable std::vector<support::ulittle32_t *> timeDateStamps; 147 const std::vector<std::pair<COFF::DebugType, Chunk *>> &records; 148 bool writeRepro; 149 }; 150 151 class CVDebugRecordChunk : public NonSectionChunk { 152 public: 153 size_t getSize() const override { 154 return sizeof(codeview::DebugInfo) + config->pdbAltPath.size() + 1; 155 } 156 157 void writeTo(uint8_t *b) const override { 158 // Save off the DebugInfo entry to backfill the file signature (build id) 159 // in Writer::writeBuildId 160 buildId = reinterpret_cast<codeview::DebugInfo *>(b); 161 162 // variable sized field (PDB Path) 163 char *p = reinterpret_cast<char *>(b + sizeof(*buildId)); 164 if (!config->pdbAltPath.empty()) 165 memcpy(p, config->pdbAltPath.data(), config->pdbAltPath.size()); 166 p[config->pdbAltPath.size()] = '\0'; 167 } 168 169 mutable codeview::DebugInfo *buildId = nullptr; 170 }; 171 172 class ExtendedDllCharacteristicsChunk : public NonSectionChunk { 173 public: 174 ExtendedDllCharacteristicsChunk(uint32_t c) : characteristics(c) {} 175 176 size_t getSize() const override { return 4; } 177 178 void writeTo(uint8_t *buf) const override { write32le(buf, characteristics); } 179 180 uint32_t characteristics = 0; 181 }; 182 183 // PartialSection represents a group of chunks that contribute to an 184 // OutputSection. Collating a collection of PartialSections of same name and 185 // characteristics constitutes the OutputSection. 186 class PartialSectionKey { 187 public: 188 StringRef name; 189 unsigned characteristics; 190 191 bool operator<(const PartialSectionKey &other) const { 192 int c = name.compare(other.name); 193 if (c == 1) 194 return false; 195 if (c == 0) 196 return characteristics < other.characteristics; 197 return true; 198 } 199 }; 200 201 // The writer writes a SymbolTable result to a file. 202 class Writer { 203 public: 204 Writer() : buffer(errorHandler().outputBuffer) {} 205 void run(); 206 207 private: 208 void createSections(); 209 void createMiscChunks(); 210 void createImportTables(); 211 void appendImportThunks(); 212 void locateImportTables(); 213 void createExportTable(); 214 void mergeSections(); 215 void removeUnusedSections(); 216 void assignAddresses(); 217 void finalizeAddresses(); 218 void removeEmptySections(); 219 void assignOutputSectionIndices(); 220 void createSymbolAndStringTable(); 221 void openFile(StringRef outputPath); 222 template <typename PEHeaderTy> void writeHeader(); 223 void createSEHTable(); 224 void createRuntimePseudoRelocs(); 225 void insertCtorDtorSymbols(); 226 void createGuardCFTables(); 227 void markSymbolsForRVATable(ObjFile *file, 228 ArrayRef<SectionChunk *> symIdxChunks, 229 SymbolRVASet &tableSymbols); 230 void maybeAddRVATable(SymbolRVASet tableSymbols, StringRef tableSym, 231 StringRef countSym); 232 void setSectionPermissions(); 233 void writeSections(); 234 void writeBuildId(); 235 void sortSections(); 236 void sortExceptionTable(); 237 void sortCRTSectionChunks(std::vector<Chunk *> &chunks); 238 void addSyntheticIdata(); 239 void fixPartialSectionChars(StringRef name, uint32_t chars); 240 bool fixGnuImportChunks(); 241 PartialSection *createPartialSection(StringRef name, uint32_t outChars); 242 PartialSection *findPartialSection(StringRef name, uint32_t outChars); 243 244 llvm::Optional<coff_symbol16> createSymbol(Defined *d); 245 size_t addEntryToStringTable(StringRef str); 246 247 OutputSection *findSection(StringRef name); 248 void addBaserels(); 249 void addBaserelBlocks(std::vector<Baserel> &v); 250 251 uint32_t getSizeOfInitializedData(); 252 253 std::unique_ptr<FileOutputBuffer> &buffer; 254 std::map<PartialSectionKey, PartialSection *> partialSections; 255 std::vector<char> strtab; 256 std::vector<llvm::object::coff_symbol16> outputSymtab; 257 IdataContents idata; 258 Chunk *importTableStart = nullptr; 259 uint64_t importTableSize = 0; 260 Chunk *edataStart = nullptr; 261 Chunk *edataEnd = nullptr; 262 Chunk *iatStart = nullptr; 263 uint64_t iatSize = 0; 264 DelayLoadContents delayIdata; 265 EdataContents edata; 266 bool setNoSEHCharacteristic = false; 267 268 DebugDirectoryChunk *debugDirectory = nullptr; 269 std::vector<std::pair<COFF::DebugType, Chunk *>> debugRecords; 270 CVDebugRecordChunk *buildId = nullptr; 271 ArrayRef<uint8_t> sectionTable; 272 273 uint64_t fileSize; 274 uint32_t pointerToSymbolTable = 0; 275 uint64_t sizeOfImage; 276 uint64_t sizeOfHeaders; 277 278 OutputSection *textSec; 279 OutputSection *rdataSec; 280 OutputSection *buildidSec; 281 OutputSection *dataSec; 282 OutputSection *pdataSec; 283 OutputSection *idataSec; 284 OutputSection *edataSec; 285 OutputSection *didatSec; 286 OutputSection *rsrcSec; 287 OutputSection *relocSec; 288 OutputSection *ctorsSec; 289 OutputSection *dtorsSec; 290 291 // The first and last .pdata sections in the output file. 292 // 293 // We need to keep track of the location of .pdata in whichever section it 294 // gets merged into so that we can sort its contents and emit a correct data 295 // directory entry for the exception table. This is also the case for some 296 // other sections (such as .edata) but because the contents of those sections 297 // are entirely linker-generated we can keep track of their locations using 298 // the chunks that the linker creates. All .pdata chunks come from input 299 // files, so we need to keep track of them separately. 300 Chunk *firstPdata = nullptr; 301 Chunk *lastPdata; 302 }; 303 } // anonymous namespace 304 305 static Timer codeLayoutTimer("Code Layout", Timer::root()); 306 static Timer diskCommitTimer("Commit Output File", Timer::root()); 307 308 void lld::coff::writeResult() { Writer().run(); } 309 310 void OutputSection::addChunk(Chunk *c) { 311 chunks.push_back(c); 312 } 313 314 void OutputSection::insertChunkAtStart(Chunk *c) { 315 chunks.insert(chunks.begin(), c); 316 } 317 318 void OutputSection::setPermissions(uint32_t c) { 319 header.Characteristics &= ~permMask; 320 header.Characteristics |= c; 321 } 322 323 void OutputSection::merge(OutputSection *other) { 324 chunks.insert(chunks.end(), other->chunks.begin(), other->chunks.end()); 325 other->chunks.clear(); 326 contribSections.insert(contribSections.end(), other->contribSections.begin(), 327 other->contribSections.end()); 328 other->contribSections.clear(); 329 } 330 331 // Write the section header to a given buffer. 332 void OutputSection::writeHeaderTo(uint8_t *buf) { 333 auto *hdr = reinterpret_cast<coff_section *>(buf); 334 *hdr = header; 335 if (stringTableOff) { 336 // If name is too long, write offset into the string table as a name. 337 sprintf(hdr->Name, "/%d", stringTableOff); 338 } else { 339 assert(!config->debug || name.size() <= COFF::NameSize || 340 (hdr->Characteristics & IMAGE_SCN_MEM_DISCARDABLE) == 0); 341 strncpy(hdr->Name, name.data(), 342 std::min(name.size(), (size_t)COFF::NameSize)); 343 } 344 } 345 346 void OutputSection::addContributingPartialSection(PartialSection *sec) { 347 contribSections.push_back(sec); 348 } 349 350 // Check whether the target address S is in range from a relocation 351 // of type relType at address P. 352 static bool isInRange(uint16_t relType, uint64_t s, uint64_t p, int margin) { 353 if (config->machine == ARMNT) { 354 int64_t diff = AbsoluteDifference(s, p + 4) + margin; 355 switch (relType) { 356 case IMAGE_REL_ARM_BRANCH20T: 357 return isInt<21>(diff); 358 case IMAGE_REL_ARM_BRANCH24T: 359 case IMAGE_REL_ARM_BLX23T: 360 return isInt<25>(diff); 361 default: 362 return true; 363 } 364 } else if (config->machine == ARM64) { 365 int64_t diff = AbsoluteDifference(s, p) + margin; 366 switch (relType) { 367 case IMAGE_REL_ARM64_BRANCH26: 368 return isInt<28>(diff); 369 case IMAGE_REL_ARM64_BRANCH19: 370 return isInt<21>(diff); 371 case IMAGE_REL_ARM64_BRANCH14: 372 return isInt<16>(diff); 373 default: 374 return true; 375 } 376 } else { 377 llvm_unreachable("Unexpected architecture"); 378 } 379 } 380 381 // Return the last thunk for the given target if it is in range, 382 // or create a new one. 383 static std::pair<Defined *, bool> 384 getThunk(DenseMap<uint64_t, Defined *> &lastThunks, Defined *target, uint64_t p, 385 uint16_t type, int margin) { 386 Defined *&lastThunk = lastThunks[target->getRVA()]; 387 if (lastThunk && isInRange(type, lastThunk->getRVA(), p, margin)) 388 return {lastThunk, false}; 389 Chunk *c; 390 switch (config->machine) { 391 case ARMNT: 392 c = make<RangeExtensionThunkARM>(target); 393 break; 394 case ARM64: 395 c = make<RangeExtensionThunkARM64>(target); 396 break; 397 default: 398 llvm_unreachable("Unexpected architecture"); 399 } 400 Defined *d = make<DefinedSynthetic>("", c); 401 lastThunk = d; 402 return {d, true}; 403 } 404 405 // This checks all relocations, and for any relocation which isn't in range 406 // it adds a thunk after the section chunk that contains the relocation. 407 // If the latest thunk for the specific target is in range, that is used 408 // instead of creating a new thunk. All range checks are done with the 409 // specified margin, to make sure that relocations that originally are in 410 // range, but only barely, also get thunks - in case other added thunks makes 411 // the target go out of range. 412 // 413 // After adding thunks, we verify that all relocations are in range (with 414 // no extra margin requirements). If this failed, we restart (throwing away 415 // the previously created thunks) and retry with a wider margin. 416 static bool createThunks(OutputSection *os, int margin) { 417 bool addressesChanged = false; 418 DenseMap<uint64_t, Defined *> lastThunks; 419 DenseMap<std::pair<ObjFile *, Defined *>, uint32_t> thunkSymtabIndices; 420 size_t thunksSize = 0; 421 // Recheck Chunks.size() each iteration, since we can insert more 422 // elements into it. 423 for (size_t i = 0; i != os->chunks.size(); ++i) { 424 SectionChunk *sc = dyn_cast_or_null<SectionChunk>(os->chunks[i]); 425 if (!sc) 426 continue; 427 size_t thunkInsertionSpot = i + 1; 428 429 // Try to get a good enough estimate of where new thunks will be placed. 430 // Offset this by the size of the new thunks added so far, to make the 431 // estimate slightly better. 432 size_t thunkInsertionRVA = sc->getRVA() + sc->getSize() + thunksSize; 433 ObjFile *file = sc->file; 434 std::vector<std::pair<uint32_t, uint32_t>> relocReplacements; 435 ArrayRef<coff_relocation> originalRelocs = 436 file->getCOFFObj()->getRelocations(sc->header); 437 for (size_t j = 0, e = originalRelocs.size(); j < e; ++j) { 438 const coff_relocation &rel = originalRelocs[j]; 439 Symbol *relocTarget = file->getSymbol(rel.SymbolTableIndex); 440 441 // The estimate of the source address P should be pretty accurate, 442 // but we don't know whether the target Symbol address should be 443 // offset by thunksSize or not (or by some of thunksSize but not all of 444 // it), giving us some uncertainty once we have added one thunk. 445 uint64_t p = sc->getRVA() + rel.VirtualAddress + thunksSize; 446 447 Defined *sym = dyn_cast_or_null<Defined>(relocTarget); 448 if (!sym) 449 continue; 450 451 uint64_t s = sym->getRVA(); 452 453 if (isInRange(rel.Type, s, p, margin)) 454 continue; 455 456 // If the target isn't in range, hook it up to an existing or new 457 // thunk. 458 Defined *thunk; 459 bool wasNew; 460 std::tie(thunk, wasNew) = getThunk(lastThunks, sym, p, rel.Type, margin); 461 if (wasNew) { 462 Chunk *thunkChunk = thunk->getChunk(); 463 thunkChunk->setRVA( 464 thunkInsertionRVA); // Estimate of where it will be located. 465 os->chunks.insert(os->chunks.begin() + thunkInsertionSpot, thunkChunk); 466 thunkInsertionSpot++; 467 thunksSize += thunkChunk->getSize(); 468 thunkInsertionRVA += thunkChunk->getSize(); 469 addressesChanged = true; 470 } 471 472 // To redirect the relocation, add a symbol to the parent object file's 473 // symbol table, and replace the relocation symbol table index with the 474 // new index. 475 auto insertion = thunkSymtabIndices.insert({{file, thunk}, ~0U}); 476 uint32_t &thunkSymbolIndex = insertion.first->second; 477 if (insertion.second) 478 thunkSymbolIndex = file->addRangeThunkSymbol(thunk); 479 relocReplacements.push_back({j, thunkSymbolIndex}); 480 } 481 482 // Get a writable copy of this section's relocations so they can be 483 // modified. If the relocations point into the object file, allocate new 484 // memory. Otherwise, this must be previously allocated memory that can be 485 // modified in place. 486 ArrayRef<coff_relocation> curRelocs = sc->getRelocs(); 487 MutableArrayRef<coff_relocation> newRelocs; 488 if (originalRelocs.data() == curRelocs.data()) { 489 newRelocs = makeMutableArrayRef( 490 bAlloc.Allocate<coff_relocation>(originalRelocs.size()), 491 originalRelocs.size()); 492 } else { 493 newRelocs = makeMutableArrayRef( 494 const_cast<coff_relocation *>(curRelocs.data()), curRelocs.size()); 495 } 496 497 // Copy each relocation, but replace the symbol table indices which need 498 // thunks. 499 auto nextReplacement = relocReplacements.begin(); 500 auto endReplacement = relocReplacements.end(); 501 for (size_t i = 0, e = originalRelocs.size(); i != e; ++i) { 502 newRelocs[i] = originalRelocs[i]; 503 if (nextReplacement != endReplacement && nextReplacement->first == i) { 504 newRelocs[i].SymbolTableIndex = nextReplacement->second; 505 ++nextReplacement; 506 } 507 } 508 509 sc->setRelocs(newRelocs); 510 } 511 return addressesChanged; 512 } 513 514 // Verify that all relocations are in range, with no extra margin requirements. 515 static bool verifyRanges(const std::vector<Chunk *> chunks) { 516 for (Chunk *c : chunks) { 517 SectionChunk *sc = dyn_cast_or_null<SectionChunk>(c); 518 if (!sc) 519 continue; 520 521 ArrayRef<coff_relocation> relocs = sc->getRelocs(); 522 for (size_t j = 0, e = relocs.size(); j < e; ++j) { 523 const coff_relocation &rel = relocs[j]; 524 Symbol *relocTarget = sc->file->getSymbol(rel.SymbolTableIndex); 525 526 Defined *sym = dyn_cast_or_null<Defined>(relocTarget); 527 if (!sym) 528 continue; 529 530 uint64_t p = sc->getRVA() + rel.VirtualAddress; 531 uint64_t s = sym->getRVA(); 532 533 if (!isInRange(rel.Type, s, p, 0)) 534 return false; 535 } 536 } 537 return true; 538 } 539 540 // Assign addresses and add thunks if necessary. 541 void Writer::finalizeAddresses() { 542 assignAddresses(); 543 if (config->machine != ARMNT && config->machine != ARM64) 544 return; 545 546 size_t origNumChunks = 0; 547 for (OutputSection *sec : outputSections) { 548 sec->origChunks = sec->chunks; 549 origNumChunks += sec->chunks.size(); 550 } 551 552 int pass = 0; 553 int margin = 1024 * 100; 554 while (true) { 555 // First check whether we need thunks at all, or if the previous pass of 556 // adding them turned out ok. 557 bool rangesOk = true; 558 size_t numChunks = 0; 559 for (OutputSection *sec : outputSections) { 560 if (!verifyRanges(sec->chunks)) { 561 rangesOk = false; 562 break; 563 } 564 numChunks += sec->chunks.size(); 565 } 566 if (rangesOk) { 567 if (pass > 0) 568 log("Added " + Twine(numChunks - origNumChunks) + " thunks with " + 569 "margin " + Twine(margin) + " in " + Twine(pass) + " passes"); 570 return; 571 } 572 573 if (pass >= 10) 574 fatal("adding thunks hasn't converged after " + Twine(pass) + " passes"); 575 576 if (pass > 0) { 577 // If the previous pass didn't work out, reset everything back to the 578 // original conditions before retrying with a wider margin. This should 579 // ideally never happen under real circumstances. 580 for (OutputSection *sec : outputSections) 581 sec->chunks = sec->origChunks; 582 margin *= 2; 583 } 584 585 // Try adding thunks everywhere where it is needed, with a margin 586 // to avoid things going out of range due to the added thunks. 587 bool addressesChanged = false; 588 for (OutputSection *sec : outputSections) 589 addressesChanged |= createThunks(sec, margin); 590 // If the verification above thought we needed thunks, we should have 591 // added some. 592 assert(addressesChanged); 593 594 // Recalculate the layout for the whole image (and verify the ranges at 595 // the start of the next round). 596 assignAddresses(); 597 598 pass++; 599 } 600 } 601 602 // The main function of the writer. 603 void Writer::run() { 604 ScopedTimer t1(codeLayoutTimer); 605 606 createImportTables(); 607 createSections(); 608 createMiscChunks(); 609 appendImportThunks(); 610 createExportTable(); 611 mergeSections(); 612 removeUnusedSections(); 613 finalizeAddresses(); 614 removeEmptySections(); 615 assignOutputSectionIndices(); 616 setSectionPermissions(); 617 createSymbolAndStringTable(); 618 619 if (fileSize > UINT32_MAX) 620 fatal("image size (" + Twine(fileSize) + ") " + 621 "exceeds maximum allowable size (" + Twine(UINT32_MAX) + ")"); 622 623 openFile(config->outputFile); 624 if (config->is64()) { 625 writeHeader<pe32plus_header>(); 626 } else { 627 writeHeader<pe32_header>(); 628 } 629 writeSections(); 630 sortExceptionTable(); 631 632 t1.stop(); 633 634 if (!config->pdbPath.empty() && config->debug) { 635 assert(buildId); 636 createPDB(symtab, outputSections, sectionTable, buildId->buildId); 637 } 638 writeBuildId(); 639 640 writeLLDMapFile(outputSections); 641 writeMapFile(outputSections); 642 643 if (errorCount()) 644 return; 645 646 ScopedTimer t2(diskCommitTimer); 647 if (auto e = buffer->commit()) 648 fatal("failed to write the output file: " + toString(std::move(e))); 649 } 650 651 static StringRef getOutputSectionName(StringRef name) { 652 StringRef s = name.split('$').first; 653 654 // Treat a later period as a separator for MinGW, for sections like 655 // ".ctors.01234". 656 return s.substr(0, s.find('.', 1)); 657 } 658 659 // For /order. 660 static void sortBySectionOrder(std::vector<Chunk *> &chunks) { 661 auto getPriority = [](const Chunk *c) { 662 if (auto *sec = dyn_cast<SectionChunk>(c)) 663 if (sec->sym) 664 return config->order.lookup(sec->sym->getName()); 665 return 0; 666 }; 667 668 llvm::stable_sort(chunks, [=](const Chunk *a, const Chunk *b) { 669 return getPriority(a) < getPriority(b); 670 }); 671 } 672 673 // Change the characteristics of existing PartialSections that belong to the 674 // section Name to Chars. 675 void Writer::fixPartialSectionChars(StringRef name, uint32_t chars) { 676 for (auto it : partialSections) { 677 PartialSection *pSec = it.second; 678 StringRef curName = pSec->name; 679 if (!curName.consume_front(name) || 680 (!curName.empty() && !curName.startswith("$"))) 681 continue; 682 if (pSec->characteristics == chars) 683 continue; 684 PartialSection *destSec = createPartialSection(pSec->name, chars); 685 destSec->chunks.insert(destSec->chunks.end(), pSec->chunks.begin(), 686 pSec->chunks.end()); 687 pSec->chunks.clear(); 688 } 689 } 690 691 // Sort concrete section chunks from GNU import libraries. 692 // 693 // GNU binutils doesn't use short import files, but instead produces import 694 // libraries that consist of object files, with section chunks for the .idata$* 695 // sections. These are linked just as regular static libraries. Each import 696 // library consists of one header object, one object file for every imported 697 // symbol, and one trailer object. In order for the .idata tables/lists to 698 // be formed correctly, the section chunks within each .idata$* section need 699 // to be grouped by library, and sorted alphabetically within each library 700 // (which makes sure the header comes first and the trailer last). 701 bool Writer::fixGnuImportChunks() { 702 uint32_t rdata = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ; 703 704 // Make sure all .idata$* section chunks are mapped as RDATA in order to 705 // be sorted into the same sections as our own synthesized .idata chunks. 706 fixPartialSectionChars(".idata", rdata); 707 708 bool hasIdata = false; 709 // Sort all .idata$* chunks, grouping chunks from the same library, 710 // with alphabetical ordering of the object fils within a library. 711 for (auto it : partialSections) { 712 PartialSection *pSec = it.second; 713 if (!pSec->name.startswith(".idata")) 714 continue; 715 716 if (!pSec->chunks.empty()) 717 hasIdata = true; 718 llvm::stable_sort(pSec->chunks, [&](Chunk *s, Chunk *t) { 719 SectionChunk *sc1 = dyn_cast_or_null<SectionChunk>(s); 720 SectionChunk *sc2 = dyn_cast_or_null<SectionChunk>(t); 721 if (!sc1 || !sc2) { 722 // if SC1, order them ascending. If SC2 or both null, 723 // S is not less than T. 724 return sc1 != nullptr; 725 } 726 // Make a string with "libraryname/objectfile" for sorting, achieving 727 // both grouping by library and sorting of objects within a library, 728 // at once. 729 std::string key1 = 730 (sc1->file->parentName + "/" + sc1->file->getName()).str(); 731 std::string key2 = 732 (sc2->file->parentName + "/" + sc2->file->getName()).str(); 733 return key1 < key2; 734 }); 735 } 736 return hasIdata; 737 } 738 739 // Add generated idata chunks, for imported symbols and DLLs, and a 740 // terminator in .idata$2. 741 void Writer::addSyntheticIdata() { 742 uint32_t rdata = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ; 743 idata.create(); 744 745 // Add the .idata content in the right section groups, to allow 746 // chunks from other linked in object files to be grouped together. 747 // See Microsoft PE/COFF spec 5.4 for details. 748 auto add = [&](StringRef n, std::vector<Chunk *> &v) { 749 PartialSection *pSec = createPartialSection(n, rdata); 750 pSec->chunks.insert(pSec->chunks.end(), v.begin(), v.end()); 751 }; 752 753 // The loader assumes a specific order of data. 754 // Add each type in the correct order. 755 add(".idata$2", idata.dirs); 756 add(".idata$4", idata.lookups); 757 add(".idata$5", idata.addresses); 758 if (!idata.hints.empty()) 759 add(".idata$6", idata.hints); 760 add(".idata$7", idata.dllNames); 761 } 762 763 // Locate the first Chunk and size of the import directory list and the 764 // IAT. 765 void Writer::locateImportTables() { 766 uint32_t rdata = IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ; 767 768 if (PartialSection *importDirs = findPartialSection(".idata$2", rdata)) { 769 if (!importDirs->chunks.empty()) 770 importTableStart = importDirs->chunks.front(); 771 for (Chunk *c : importDirs->chunks) 772 importTableSize += c->getSize(); 773 } 774 775 if (PartialSection *importAddresses = findPartialSection(".idata$5", rdata)) { 776 if (!importAddresses->chunks.empty()) 777 iatStart = importAddresses->chunks.front(); 778 for (Chunk *c : importAddresses->chunks) 779 iatSize += c->getSize(); 780 } 781 } 782 783 // Return whether a SectionChunk's suffix (the dollar and any trailing 784 // suffix) should be removed and sorted into the main suffixless 785 // PartialSection. 786 static bool shouldStripSectionSuffix(SectionChunk *sc, StringRef name) { 787 // On MinGW, comdat groups are formed by putting the comdat group name 788 // after the '$' in the section name. For .eh_frame$<symbol>, that must 789 // still be sorted before the .eh_frame trailer from crtend.o, thus just 790 // strip the section name trailer. For other sections, such as 791 // .tls$$<symbol> (where non-comdat .tls symbols are otherwise stored in 792 // ".tls$"), they must be strictly sorted after .tls. And for the 793 // hypothetical case of comdat .CRT$XCU, we definitely need to keep the 794 // suffix for sorting. Thus, to play it safe, only strip the suffix for 795 // the standard sections. 796 if (!config->mingw) 797 return false; 798 if (!sc || !sc->isCOMDAT()) 799 return false; 800 return name.startswith(".text$") || name.startswith(".data$") || 801 name.startswith(".rdata$") || name.startswith(".pdata$") || 802 name.startswith(".xdata$") || name.startswith(".eh_frame$"); 803 } 804 805 void Writer::sortSections() { 806 if (!config->callGraphProfile.empty()) { 807 DenseMap<const SectionChunk *, int> order = computeCallGraphProfileOrder(); 808 for (auto it : order) { 809 if (DefinedRegular *sym = it.first->sym) 810 config->order[sym->getName()] = it.second; 811 } 812 } 813 if (!config->order.empty()) 814 for (auto it : partialSections) 815 sortBySectionOrder(it.second->chunks); 816 } 817 818 // Create output section objects and add them to OutputSections. 819 void Writer::createSections() { 820 // First, create the builtin sections. 821 const uint32_t data = IMAGE_SCN_CNT_INITIALIZED_DATA; 822 const uint32_t bss = IMAGE_SCN_CNT_UNINITIALIZED_DATA; 823 const uint32_t code = IMAGE_SCN_CNT_CODE; 824 const uint32_t discardable = IMAGE_SCN_MEM_DISCARDABLE; 825 const uint32_t r = IMAGE_SCN_MEM_READ; 826 const uint32_t w = IMAGE_SCN_MEM_WRITE; 827 const uint32_t x = IMAGE_SCN_MEM_EXECUTE; 828 829 SmallDenseMap<std::pair<StringRef, uint32_t>, OutputSection *> sections; 830 auto createSection = [&](StringRef name, uint32_t outChars) { 831 OutputSection *&sec = sections[{name, outChars}]; 832 if (!sec) { 833 sec = make<OutputSection>(name, outChars); 834 outputSections.push_back(sec); 835 } 836 return sec; 837 }; 838 839 // Try to match the section order used by link.exe. 840 textSec = createSection(".text", code | r | x); 841 createSection(".bss", bss | r | w); 842 rdataSec = createSection(".rdata", data | r); 843 buildidSec = createSection(".buildid", data | r); 844 dataSec = createSection(".data", data | r | w); 845 pdataSec = createSection(".pdata", data | r); 846 idataSec = createSection(".idata", data | r); 847 edataSec = createSection(".edata", data | r); 848 didatSec = createSection(".didat", data | r); 849 rsrcSec = createSection(".rsrc", data | r); 850 relocSec = createSection(".reloc", data | discardable | r); 851 ctorsSec = createSection(".ctors", data | r | w); 852 dtorsSec = createSection(".dtors", data | r | w); 853 854 // Then bin chunks by name and output characteristics. 855 for (Chunk *c : symtab->getChunks()) { 856 auto *sc = dyn_cast<SectionChunk>(c); 857 if (sc && !sc->live) { 858 if (config->verbose) 859 sc->printDiscardedMessage(); 860 continue; 861 } 862 StringRef name = c->getSectionName(); 863 if (shouldStripSectionSuffix(sc, name)) 864 name = name.split('$').first; 865 PartialSection *pSec = createPartialSection(name, 866 c->getOutputCharacteristics()); 867 pSec->chunks.push_back(c); 868 } 869 870 fixPartialSectionChars(".rsrc", data | r); 871 fixPartialSectionChars(".edata", data | r); 872 // Even in non MinGW cases, we might need to link against GNU import 873 // libraries. 874 bool hasIdata = fixGnuImportChunks(); 875 if (!idata.empty()) 876 hasIdata = true; 877 878 if (hasIdata) 879 addSyntheticIdata(); 880 881 sortSections(); 882 883 if (hasIdata) 884 locateImportTables(); 885 886 // Then create an OutputSection for each section. 887 // '$' and all following characters in input section names are 888 // discarded when determining output section. So, .text$foo 889 // contributes to .text, for example. See PE/COFF spec 3.2. 890 for (auto it : partialSections) { 891 PartialSection *pSec = it.second; 892 StringRef name = getOutputSectionName(pSec->name); 893 uint32_t outChars = pSec->characteristics; 894 895 if (name == ".CRT") { 896 // In link.exe, there is a special case for the I386 target where .CRT 897 // sections are treated as if they have output characteristics DATA | R if 898 // their characteristics are DATA | R | W. This implements the same 899 // special case for all architectures. 900 outChars = data | r; 901 902 log("Processing section " + pSec->name + " -> " + name); 903 904 sortCRTSectionChunks(pSec->chunks); 905 } 906 907 OutputSection *sec = createSection(name, outChars); 908 for (Chunk *c : pSec->chunks) 909 sec->addChunk(c); 910 911 sec->addContributingPartialSection(pSec); 912 } 913 914 // Finally, move some output sections to the end. 915 auto sectionOrder = [&](const OutputSection *s) { 916 // Move DISCARDABLE (or non-memory-mapped) sections to the end of file 917 // because the loader cannot handle holes. Stripping can remove other 918 // discardable ones than .reloc, which is first of them (created early). 919 if (s->header.Characteristics & IMAGE_SCN_MEM_DISCARDABLE) 920 return 2; 921 // .rsrc should come at the end of the non-discardable sections because its 922 // size may change by the Win32 UpdateResources() function, causing 923 // subsequent sections to move (see https://crbug.com/827082). 924 if (s == rsrcSec) 925 return 1; 926 return 0; 927 }; 928 llvm::stable_sort(outputSections, 929 [&](const OutputSection *s, const OutputSection *t) { 930 return sectionOrder(s) < sectionOrder(t); 931 }); 932 } 933 934 void Writer::createMiscChunks() { 935 for (MergeChunk *p : MergeChunk::instances) { 936 if (p) { 937 p->finalizeContents(); 938 rdataSec->addChunk(p); 939 } 940 } 941 942 // Create thunks for locally-dllimported symbols. 943 if (!symtab->localImportChunks.empty()) { 944 for (Chunk *c : symtab->localImportChunks) 945 rdataSec->addChunk(c); 946 } 947 948 // Create Debug Information Chunks 949 OutputSection *debugInfoSec = config->mingw ? buildidSec : rdataSec; 950 if (config->debug || config->repro || config->cetCompat) { 951 debugDirectory = make<DebugDirectoryChunk>(debugRecords, config->repro); 952 debugDirectory->setAlignment(4); 953 debugInfoSec->addChunk(debugDirectory); 954 } 955 956 if (config->debug) { 957 // Make a CVDebugRecordChunk even when /DEBUG:CV is not specified. We 958 // output a PDB no matter what, and this chunk provides the only means of 959 // allowing a debugger to match a PDB and an executable. So we need it even 960 // if we're ultimately not going to write CodeView data to the PDB. 961 buildId = make<CVDebugRecordChunk>(); 962 debugRecords.push_back({COFF::IMAGE_DEBUG_TYPE_CODEVIEW, buildId}); 963 } 964 965 if (config->cetCompat) { 966 ExtendedDllCharacteristicsChunk *extendedDllChars = 967 make<ExtendedDllCharacteristicsChunk>( 968 IMAGE_DLL_CHARACTERISTICS_EX_CET_COMPAT); 969 debugRecords.push_back( 970 {COFF::IMAGE_DEBUG_TYPE_EX_DLLCHARACTERISTICS, extendedDllChars}); 971 } 972 973 if (debugRecords.size() > 0) { 974 for (std::pair<COFF::DebugType, Chunk *> r : debugRecords) 975 debugInfoSec->addChunk(r.second); 976 } 977 978 // Create SEH table. x86-only. 979 if (config->safeSEH) 980 createSEHTable(); 981 982 // Create /guard:cf tables if requested. 983 if (config->guardCF != GuardCFLevel::Off) 984 createGuardCFTables(); 985 986 if (config->autoImport) 987 createRuntimePseudoRelocs(); 988 989 if (config->mingw) 990 insertCtorDtorSymbols(); 991 } 992 993 // Create .idata section for the DLL-imported symbol table. 994 // The format of this section is inherently Windows-specific. 995 // IdataContents class abstracted away the details for us, 996 // so we just let it create chunks and add them to the section. 997 void Writer::createImportTables() { 998 // Initialize DLLOrder so that import entries are ordered in 999 // the same order as in the command line. (That affects DLL 1000 // initialization order, and this ordering is MSVC-compatible.) 1001 for (ImportFile *file : ImportFile::instances) { 1002 if (!file->live) 1003 continue; 1004 1005 std::string dll = StringRef(file->dllName).lower(); 1006 if (config->dllOrder.count(dll) == 0) 1007 config->dllOrder[dll] = config->dllOrder.size(); 1008 1009 if (file->impSym && !isa<DefinedImportData>(file->impSym)) 1010 fatal(toString(*file->impSym) + " was replaced"); 1011 DefinedImportData *impSym = cast_or_null<DefinedImportData>(file->impSym); 1012 if (config->delayLoads.count(StringRef(file->dllName).lower())) { 1013 if (!file->thunkSym) 1014 fatal("cannot delay-load " + toString(file) + 1015 " due to import of data: " + toString(*impSym)); 1016 delayIdata.add(impSym); 1017 } else { 1018 idata.add(impSym); 1019 } 1020 } 1021 } 1022 1023 void Writer::appendImportThunks() { 1024 if (ImportFile::instances.empty()) 1025 return; 1026 1027 for (ImportFile *file : ImportFile::instances) { 1028 if (!file->live) 1029 continue; 1030 1031 if (!file->thunkSym) 1032 continue; 1033 1034 if (!isa<DefinedImportThunk>(file->thunkSym)) 1035 fatal(toString(*file->thunkSym) + " was replaced"); 1036 DefinedImportThunk *thunk = cast<DefinedImportThunk>(file->thunkSym); 1037 if (file->thunkLive) 1038 textSec->addChunk(thunk->getChunk()); 1039 } 1040 1041 if (!delayIdata.empty()) { 1042 Defined *helper = cast<Defined>(config->delayLoadHelper); 1043 delayIdata.create(helper); 1044 for (Chunk *c : delayIdata.getChunks()) 1045 didatSec->addChunk(c); 1046 for (Chunk *c : delayIdata.getDataChunks()) 1047 dataSec->addChunk(c); 1048 for (Chunk *c : delayIdata.getCodeChunks()) 1049 textSec->addChunk(c); 1050 } 1051 } 1052 1053 void Writer::createExportTable() { 1054 if (!edataSec->chunks.empty()) { 1055 // Allow using a custom built export table from input object files, instead 1056 // of having the linker synthesize the tables. 1057 if (config->hadExplicitExports) 1058 warn("literal .edata sections override exports"); 1059 } else if (!config->exports.empty()) { 1060 for (Chunk *c : edata.chunks) 1061 edataSec->addChunk(c); 1062 } 1063 if (!edataSec->chunks.empty()) { 1064 edataStart = edataSec->chunks.front(); 1065 edataEnd = edataSec->chunks.back(); 1066 } 1067 } 1068 1069 void Writer::removeUnusedSections() { 1070 // Remove sections that we can be sure won't get content, to avoid 1071 // allocating space for their section headers. 1072 auto isUnused = [this](OutputSection *s) { 1073 if (s == relocSec) 1074 return false; // This section is populated later. 1075 // MergeChunks have zero size at this point, as their size is finalized 1076 // later. Only remove sections that have no Chunks at all. 1077 return s->chunks.empty(); 1078 }; 1079 outputSections.erase( 1080 std::remove_if(outputSections.begin(), outputSections.end(), isUnused), 1081 outputSections.end()); 1082 } 1083 1084 // The Windows loader doesn't seem to like empty sections, 1085 // so we remove them if any. 1086 void Writer::removeEmptySections() { 1087 auto isEmpty = [](OutputSection *s) { return s->getVirtualSize() == 0; }; 1088 outputSections.erase( 1089 std::remove_if(outputSections.begin(), outputSections.end(), isEmpty), 1090 outputSections.end()); 1091 } 1092 1093 void Writer::assignOutputSectionIndices() { 1094 // Assign final output section indices, and assign each chunk to its output 1095 // section. 1096 uint32_t idx = 1; 1097 for (OutputSection *os : outputSections) { 1098 os->sectionIndex = idx; 1099 for (Chunk *c : os->chunks) 1100 c->setOutputSectionIdx(idx); 1101 ++idx; 1102 } 1103 1104 // Merge chunks are containers of chunks, so assign those an output section 1105 // too. 1106 for (MergeChunk *mc : MergeChunk::instances) 1107 if (mc) 1108 for (SectionChunk *sc : mc->sections) 1109 if (sc && sc->live) 1110 sc->setOutputSectionIdx(mc->getOutputSectionIdx()); 1111 } 1112 1113 size_t Writer::addEntryToStringTable(StringRef str) { 1114 assert(str.size() > COFF::NameSize); 1115 size_t offsetOfEntry = strtab.size() + 4; // +4 for the size field 1116 strtab.insert(strtab.end(), str.begin(), str.end()); 1117 strtab.push_back('\0'); 1118 return offsetOfEntry; 1119 } 1120 1121 Optional<coff_symbol16> Writer::createSymbol(Defined *def) { 1122 coff_symbol16 sym; 1123 switch (def->kind()) { 1124 case Symbol::DefinedAbsoluteKind: 1125 sym.Value = def->getRVA(); 1126 sym.SectionNumber = IMAGE_SYM_ABSOLUTE; 1127 break; 1128 case Symbol::DefinedSyntheticKind: 1129 // Relative symbols are unrepresentable in a COFF symbol table. 1130 return None; 1131 default: { 1132 // Don't write symbols that won't be written to the output to the symbol 1133 // table. 1134 Chunk *c = def->getChunk(); 1135 if (!c) 1136 return None; 1137 OutputSection *os = c->getOutputSection(); 1138 if (!os) 1139 return None; 1140 1141 sym.Value = def->getRVA() - os->getRVA(); 1142 sym.SectionNumber = os->sectionIndex; 1143 break; 1144 } 1145 } 1146 1147 // Symbols that are runtime pseudo relocations don't point to the actual 1148 // symbol data itself (as they are imported), but points to the IAT entry 1149 // instead. Avoid emitting them to the symbol table, as they can confuse 1150 // debuggers. 1151 if (def->isRuntimePseudoReloc) 1152 return None; 1153 1154 StringRef name = def->getName(); 1155 if (name.size() > COFF::NameSize) { 1156 sym.Name.Offset.Zeroes = 0; 1157 sym.Name.Offset.Offset = addEntryToStringTable(name); 1158 } else { 1159 memset(sym.Name.ShortName, 0, COFF::NameSize); 1160 memcpy(sym.Name.ShortName, name.data(), name.size()); 1161 } 1162 1163 if (auto *d = dyn_cast<DefinedCOFF>(def)) { 1164 COFFSymbolRef ref = d->getCOFFSymbol(); 1165 sym.Type = ref.getType(); 1166 sym.StorageClass = ref.getStorageClass(); 1167 } else { 1168 sym.Type = IMAGE_SYM_TYPE_NULL; 1169 sym.StorageClass = IMAGE_SYM_CLASS_EXTERNAL; 1170 } 1171 sym.NumberOfAuxSymbols = 0; 1172 return sym; 1173 } 1174 1175 void Writer::createSymbolAndStringTable() { 1176 // PE/COFF images are limited to 8 byte section names. Longer names can be 1177 // supported by writing a non-standard string table, but this string table is 1178 // not mapped at runtime and the long names will therefore be inaccessible. 1179 // link.exe always truncates section names to 8 bytes, whereas binutils always 1180 // preserves long section names via the string table. LLD adopts a hybrid 1181 // solution where discardable sections have long names preserved and 1182 // non-discardable sections have their names truncated, to ensure that any 1183 // section which is mapped at runtime also has its name mapped at runtime. 1184 for (OutputSection *sec : outputSections) { 1185 if (sec->name.size() <= COFF::NameSize) 1186 continue; 1187 if ((sec->header.Characteristics & IMAGE_SCN_MEM_DISCARDABLE) == 0) 1188 continue; 1189 if (config->warnLongSectionNames) { 1190 warn("section name " + sec->name + 1191 " is longer than 8 characters and will use a non-standard string " 1192 "table"); 1193 } 1194 sec->setStringTableOff(addEntryToStringTable(sec->name)); 1195 } 1196 1197 if (config->debugDwarf || config->debugSymtab) { 1198 for (ObjFile *file : ObjFile::instances) { 1199 for (Symbol *b : file->getSymbols()) { 1200 auto *d = dyn_cast_or_null<Defined>(b); 1201 if (!d || d->writtenToSymtab) 1202 continue; 1203 d->writtenToSymtab = true; 1204 1205 if (Optional<coff_symbol16> sym = createSymbol(d)) 1206 outputSymtab.push_back(*sym); 1207 } 1208 } 1209 } 1210 1211 if (outputSymtab.empty() && strtab.empty()) 1212 return; 1213 1214 // We position the symbol table to be adjacent to the end of the last section. 1215 uint64_t fileOff = fileSize; 1216 pointerToSymbolTable = fileOff; 1217 fileOff += outputSymtab.size() * sizeof(coff_symbol16); 1218 fileOff += 4 + strtab.size(); 1219 fileSize = alignTo(fileOff, config->fileAlign); 1220 } 1221 1222 void Writer::mergeSections() { 1223 if (!pdataSec->chunks.empty()) { 1224 firstPdata = pdataSec->chunks.front(); 1225 lastPdata = pdataSec->chunks.back(); 1226 } 1227 1228 for (auto &p : config->merge) { 1229 StringRef toName = p.second; 1230 if (p.first == toName) 1231 continue; 1232 StringSet<> names; 1233 while (1) { 1234 if (!names.insert(toName).second) 1235 fatal("/merge: cycle found for section '" + p.first + "'"); 1236 auto i = config->merge.find(toName); 1237 if (i == config->merge.end()) 1238 break; 1239 toName = i->second; 1240 } 1241 OutputSection *from = findSection(p.first); 1242 OutputSection *to = findSection(toName); 1243 if (!from) 1244 continue; 1245 if (!to) { 1246 from->name = toName; 1247 continue; 1248 } 1249 to->merge(from); 1250 } 1251 } 1252 1253 // Visits all sections to assign incremental, non-overlapping RVAs and 1254 // file offsets. 1255 void Writer::assignAddresses() { 1256 sizeOfHeaders = dosStubSize + sizeof(PEMagic) + sizeof(coff_file_header) + 1257 sizeof(data_directory) * numberOfDataDirectory + 1258 sizeof(coff_section) * outputSections.size(); 1259 sizeOfHeaders += 1260 config->is64() ? sizeof(pe32plus_header) : sizeof(pe32_header); 1261 sizeOfHeaders = alignTo(sizeOfHeaders, config->fileAlign); 1262 fileSize = sizeOfHeaders; 1263 1264 // The first page is kept unmapped. 1265 uint64_t rva = alignTo(sizeOfHeaders, config->align); 1266 1267 for (OutputSection *sec : outputSections) { 1268 if (sec == relocSec) 1269 addBaserels(); 1270 uint64_t rawSize = 0, virtualSize = 0; 1271 sec->header.VirtualAddress = rva; 1272 1273 // If /FUNCTIONPADMIN is used, functions are padded in order to create a 1274 // hotpatchable image. 1275 const bool isCodeSection = 1276 (sec->header.Characteristics & IMAGE_SCN_CNT_CODE) && 1277 (sec->header.Characteristics & IMAGE_SCN_MEM_READ) && 1278 (sec->header.Characteristics & IMAGE_SCN_MEM_EXECUTE); 1279 uint32_t padding = isCodeSection ? config->functionPadMin : 0; 1280 1281 for (Chunk *c : sec->chunks) { 1282 if (padding && c->isHotPatchable()) 1283 virtualSize += padding; 1284 virtualSize = alignTo(virtualSize, c->getAlignment()); 1285 c->setRVA(rva + virtualSize); 1286 virtualSize += c->getSize(); 1287 if (c->hasData) 1288 rawSize = alignTo(virtualSize, config->fileAlign); 1289 } 1290 if (virtualSize > UINT32_MAX) 1291 error("section larger than 4 GiB: " + sec->name); 1292 sec->header.VirtualSize = virtualSize; 1293 sec->header.SizeOfRawData = rawSize; 1294 if (rawSize != 0) 1295 sec->header.PointerToRawData = fileSize; 1296 rva += alignTo(virtualSize, config->align); 1297 fileSize += alignTo(rawSize, config->fileAlign); 1298 } 1299 sizeOfImage = alignTo(rva, config->align); 1300 1301 // Assign addresses to sections in MergeChunks. 1302 for (MergeChunk *mc : MergeChunk::instances) 1303 if (mc) 1304 mc->assignSubsectionRVAs(); 1305 } 1306 1307 template <typename PEHeaderTy> void Writer::writeHeader() { 1308 // Write DOS header. For backwards compatibility, the first part of a PE/COFF 1309 // executable consists of an MS-DOS MZ executable. If the executable is run 1310 // under DOS, that program gets run (usually to just print an error message). 1311 // When run under Windows, the loader looks at AddressOfNewExeHeader and uses 1312 // the PE header instead. 1313 uint8_t *buf = buffer->getBufferStart(); 1314 auto *dos = reinterpret_cast<dos_header *>(buf); 1315 buf += sizeof(dos_header); 1316 dos->Magic[0] = 'M'; 1317 dos->Magic[1] = 'Z'; 1318 dos->UsedBytesInTheLastPage = dosStubSize % 512; 1319 dos->FileSizeInPages = divideCeil(dosStubSize, 512); 1320 dos->HeaderSizeInParagraphs = sizeof(dos_header) / 16; 1321 1322 dos->AddressOfRelocationTable = sizeof(dos_header); 1323 dos->AddressOfNewExeHeader = dosStubSize; 1324 1325 // Write DOS program. 1326 memcpy(buf, dosProgram, sizeof(dosProgram)); 1327 buf += sizeof(dosProgram); 1328 1329 // Write PE magic 1330 memcpy(buf, PEMagic, sizeof(PEMagic)); 1331 buf += sizeof(PEMagic); 1332 1333 // Write COFF header 1334 auto *coff = reinterpret_cast<coff_file_header *>(buf); 1335 buf += sizeof(*coff); 1336 coff->Machine = config->machine; 1337 coff->NumberOfSections = outputSections.size(); 1338 coff->Characteristics = IMAGE_FILE_EXECUTABLE_IMAGE; 1339 if (config->largeAddressAware) 1340 coff->Characteristics |= IMAGE_FILE_LARGE_ADDRESS_AWARE; 1341 if (!config->is64()) 1342 coff->Characteristics |= IMAGE_FILE_32BIT_MACHINE; 1343 if (config->dll) 1344 coff->Characteristics |= IMAGE_FILE_DLL; 1345 if (config->driverUponly) 1346 coff->Characteristics |= IMAGE_FILE_UP_SYSTEM_ONLY; 1347 if (!config->relocatable) 1348 coff->Characteristics |= IMAGE_FILE_RELOCS_STRIPPED; 1349 if (config->swaprunCD) 1350 coff->Characteristics |= IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP; 1351 if (config->swaprunNet) 1352 coff->Characteristics |= IMAGE_FILE_NET_RUN_FROM_SWAP; 1353 coff->SizeOfOptionalHeader = 1354 sizeof(PEHeaderTy) + sizeof(data_directory) * numberOfDataDirectory; 1355 1356 // Write PE header 1357 auto *pe = reinterpret_cast<PEHeaderTy *>(buf); 1358 buf += sizeof(*pe); 1359 pe->Magic = config->is64() ? PE32Header::PE32_PLUS : PE32Header::PE32; 1360 1361 // If {Major,Minor}LinkerVersion is left at 0.0, then for some 1362 // reason signing the resulting PE file with Authenticode produces a 1363 // signature that fails to validate on Windows 7 (but is OK on 10). 1364 // Set it to 14.0, which is what VS2015 outputs, and which avoids 1365 // that problem. 1366 pe->MajorLinkerVersion = 14; 1367 pe->MinorLinkerVersion = 0; 1368 1369 pe->ImageBase = config->imageBase; 1370 pe->SectionAlignment = config->align; 1371 pe->FileAlignment = config->fileAlign; 1372 pe->MajorImageVersion = config->majorImageVersion; 1373 pe->MinorImageVersion = config->minorImageVersion; 1374 pe->MajorOperatingSystemVersion = config->majorOSVersion; 1375 pe->MinorOperatingSystemVersion = config->minorOSVersion; 1376 pe->MajorSubsystemVersion = config->majorSubsystemVersion; 1377 pe->MinorSubsystemVersion = config->minorSubsystemVersion; 1378 pe->Subsystem = config->subsystem; 1379 pe->SizeOfImage = sizeOfImage; 1380 pe->SizeOfHeaders = sizeOfHeaders; 1381 if (!config->noEntry) { 1382 Defined *entry = cast<Defined>(config->entry); 1383 pe->AddressOfEntryPoint = entry->getRVA(); 1384 // Pointer to thumb code must have the LSB set, so adjust it. 1385 if (config->machine == ARMNT) 1386 pe->AddressOfEntryPoint |= 1; 1387 } 1388 pe->SizeOfStackReserve = config->stackReserve; 1389 pe->SizeOfStackCommit = config->stackCommit; 1390 pe->SizeOfHeapReserve = config->heapReserve; 1391 pe->SizeOfHeapCommit = config->heapCommit; 1392 if (config->appContainer) 1393 pe->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_APPCONTAINER; 1394 if (config->driverWdm) 1395 pe->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_WDM_DRIVER; 1396 if (config->dynamicBase) 1397 pe->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE; 1398 if (config->highEntropyVA) 1399 pe->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA; 1400 if (!config->allowBind) 1401 pe->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_BIND; 1402 if (config->nxCompat) 1403 pe->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NX_COMPAT; 1404 if (!config->allowIsolation) 1405 pe->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_ISOLATION; 1406 if (config->guardCF != GuardCFLevel::Off) 1407 pe->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_GUARD_CF; 1408 if (config->integrityCheck) 1409 pe->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY; 1410 if (setNoSEHCharacteristic || config->noSEH) 1411 pe->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_SEH; 1412 if (config->terminalServerAware) 1413 pe->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_TERMINAL_SERVER_AWARE; 1414 pe->NumberOfRvaAndSize = numberOfDataDirectory; 1415 if (textSec->getVirtualSize()) { 1416 pe->BaseOfCode = textSec->getRVA(); 1417 pe->SizeOfCode = textSec->getRawSize(); 1418 } 1419 pe->SizeOfInitializedData = getSizeOfInitializedData(); 1420 1421 // Write data directory 1422 auto *dir = reinterpret_cast<data_directory *>(buf); 1423 buf += sizeof(*dir) * numberOfDataDirectory; 1424 if (edataStart) { 1425 dir[EXPORT_TABLE].RelativeVirtualAddress = edataStart->getRVA(); 1426 dir[EXPORT_TABLE].Size = 1427 edataEnd->getRVA() + edataEnd->getSize() - edataStart->getRVA(); 1428 } 1429 if (importTableStart) { 1430 dir[IMPORT_TABLE].RelativeVirtualAddress = importTableStart->getRVA(); 1431 dir[IMPORT_TABLE].Size = importTableSize; 1432 } 1433 if (iatStart) { 1434 dir[IAT].RelativeVirtualAddress = iatStart->getRVA(); 1435 dir[IAT].Size = iatSize; 1436 } 1437 if (rsrcSec->getVirtualSize()) { 1438 dir[RESOURCE_TABLE].RelativeVirtualAddress = rsrcSec->getRVA(); 1439 dir[RESOURCE_TABLE].Size = rsrcSec->getVirtualSize(); 1440 } 1441 if (firstPdata) { 1442 dir[EXCEPTION_TABLE].RelativeVirtualAddress = firstPdata->getRVA(); 1443 dir[EXCEPTION_TABLE].Size = 1444 lastPdata->getRVA() + lastPdata->getSize() - firstPdata->getRVA(); 1445 } 1446 if (relocSec->getVirtualSize()) { 1447 dir[BASE_RELOCATION_TABLE].RelativeVirtualAddress = relocSec->getRVA(); 1448 dir[BASE_RELOCATION_TABLE].Size = relocSec->getVirtualSize(); 1449 } 1450 if (Symbol *sym = symtab->findUnderscore("_tls_used")) { 1451 if (Defined *b = dyn_cast<Defined>(sym)) { 1452 dir[TLS_TABLE].RelativeVirtualAddress = b->getRVA(); 1453 dir[TLS_TABLE].Size = config->is64() 1454 ? sizeof(object::coff_tls_directory64) 1455 : sizeof(object::coff_tls_directory32); 1456 } 1457 } 1458 if (debugDirectory) { 1459 dir[DEBUG_DIRECTORY].RelativeVirtualAddress = debugDirectory->getRVA(); 1460 dir[DEBUG_DIRECTORY].Size = debugDirectory->getSize(); 1461 } 1462 if (Symbol *sym = symtab->findUnderscore("_load_config_used")) { 1463 if (auto *b = dyn_cast<DefinedRegular>(sym)) { 1464 SectionChunk *sc = b->getChunk(); 1465 assert(b->getRVA() >= sc->getRVA()); 1466 uint64_t offsetInChunk = b->getRVA() - sc->getRVA(); 1467 if (!sc->hasData || offsetInChunk + 4 > sc->getSize()) 1468 fatal("_load_config_used is malformed"); 1469 1470 ArrayRef<uint8_t> secContents = sc->getContents(); 1471 uint32_t loadConfigSize = 1472 *reinterpret_cast<const ulittle32_t *>(&secContents[offsetInChunk]); 1473 if (offsetInChunk + loadConfigSize > sc->getSize()) 1474 fatal("_load_config_used is too large"); 1475 dir[LOAD_CONFIG_TABLE].RelativeVirtualAddress = b->getRVA(); 1476 dir[LOAD_CONFIG_TABLE].Size = loadConfigSize; 1477 } 1478 } 1479 if (!delayIdata.empty()) { 1480 dir[DELAY_IMPORT_DESCRIPTOR].RelativeVirtualAddress = 1481 delayIdata.getDirRVA(); 1482 dir[DELAY_IMPORT_DESCRIPTOR].Size = delayIdata.getDirSize(); 1483 } 1484 1485 // Write section table 1486 for (OutputSection *sec : outputSections) { 1487 sec->writeHeaderTo(buf); 1488 buf += sizeof(coff_section); 1489 } 1490 sectionTable = ArrayRef<uint8_t>( 1491 buf - outputSections.size() * sizeof(coff_section), buf); 1492 1493 if (outputSymtab.empty() && strtab.empty()) 1494 return; 1495 1496 coff->PointerToSymbolTable = pointerToSymbolTable; 1497 uint32_t numberOfSymbols = outputSymtab.size(); 1498 coff->NumberOfSymbols = numberOfSymbols; 1499 auto *symbolTable = reinterpret_cast<coff_symbol16 *>( 1500 buffer->getBufferStart() + coff->PointerToSymbolTable); 1501 for (size_t i = 0; i != numberOfSymbols; ++i) 1502 symbolTable[i] = outputSymtab[i]; 1503 // Create the string table, it follows immediately after the symbol table. 1504 // The first 4 bytes is length including itself. 1505 buf = reinterpret_cast<uint8_t *>(&symbolTable[numberOfSymbols]); 1506 write32le(buf, strtab.size() + 4); 1507 if (!strtab.empty()) 1508 memcpy(buf + 4, strtab.data(), strtab.size()); 1509 } 1510 1511 void Writer::openFile(StringRef path) { 1512 buffer = CHECK( 1513 FileOutputBuffer::create(path, fileSize, FileOutputBuffer::F_executable), 1514 "failed to open " + path); 1515 } 1516 1517 void Writer::createSEHTable() { 1518 SymbolRVASet handlers; 1519 for (ObjFile *file : ObjFile::instances) { 1520 if (!file->hasSafeSEH()) 1521 error("/safeseh: " + file->getName() + " is not compatible with SEH"); 1522 markSymbolsForRVATable(file, file->getSXDataChunks(), handlers); 1523 } 1524 1525 // Set the "no SEH" characteristic if there really were no handlers, or if 1526 // there is no load config object to point to the table of handlers. 1527 setNoSEHCharacteristic = 1528 handlers.empty() || !symtab->findUnderscore("_load_config_used"); 1529 1530 maybeAddRVATable(std::move(handlers), "__safe_se_handler_table", 1531 "__safe_se_handler_count"); 1532 } 1533 1534 // Add a symbol to an RVA set. Two symbols may have the same RVA, but an RVA set 1535 // cannot contain duplicates. Therefore, the set is uniqued by Chunk and the 1536 // symbol's offset into that Chunk. 1537 static void addSymbolToRVASet(SymbolRVASet &rvaSet, Defined *s) { 1538 Chunk *c = s->getChunk(); 1539 if (auto *sc = dyn_cast<SectionChunk>(c)) 1540 c = sc->repl; // Look through ICF replacement. 1541 uint32_t off = s->getRVA() - (c ? c->getRVA() : 0); 1542 rvaSet.insert({c, off}); 1543 } 1544 1545 // Given a symbol, add it to the GFIDs table if it is a live, defined, function 1546 // symbol in an executable section. 1547 static void maybeAddAddressTakenFunction(SymbolRVASet &addressTakenSyms, 1548 Symbol *s) { 1549 if (!s) 1550 return; 1551 1552 switch (s->kind()) { 1553 case Symbol::DefinedLocalImportKind: 1554 case Symbol::DefinedImportDataKind: 1555 // Defines an __imp_ pointer, so it is data, so it is ignored. 1556 break; 1557 case Symbol::DefinedCommonKind: 1558 // Common is always data, so it is ignored. 1559 break; 1560 case Symbol::DefinedAbsoluteKind: 1561 case Symbol::DefinedSyntheticKind: 1562 // Absolute is never code, synthetic generally isn't and usually isn't 1563 // determinable. 1564 break; 1565 case Symbol::LazyArchiveKind: 1566 case Symbol::LazyObjectKind: 1567 case Symbol::UndefinedKind: 1568 // Undefined symbols resolve to zero, so they don't have an RVA. Lazy 1569 // symbols shouldn't have relocations. 1570 break; 1571 1572 case Symbol::DefinedImportThunkKind: 1573 // Thunks are always code, include them. 1574 addSymbolToRVASet(addressTakenSyms, cast<Defined>(s)); 1575 break; 1576 1577 case Symbol::DefinedRegularKind: { 1578 // This is a regular, defined, symbol from a COFF file. Mark the symbol as 1579 // address taken if the symbol type is function and it's in an executable 1580 // section. 1581 auto *d = cast<DefinedRegular>(s); 1582 if (d->getCOFFSymbol().getComplexType() == COFF::IMAGE_SYM_DTYPE_FUNCTION) { 1583 SectionChunk *sc = dyn_cast<SectionChunk>(d->getChunk()); 1584 if (sc && sc->live && 1585 sc->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE) 1586 addSymbolToRVASet(addressTakenSyms, d); 1587 } 1588 break; 1589 } 1590 } 1591 } 1592 1593 // Visit all relocations from all section contributions of this object file and 1594 // mark the relocation target as address-taken. 1595 static void markSymbolsWithRelocations(ObjFile *file, 1596 SymbolRVASet &usedSymbols) { 1597 for (Chunk *c : file->getChunks()) { 1598 // We only care about live section chunks. Common chunks and other chunks 1599 // don't generally contain relocations. 1600 SectionChunk *sc = dyn_cast<SectionChunk>(c); 1601 if (!sc || !sc->live) 1602 continue; 1603 1604 for (const coff_relocation &reloc : sc->getRelocs()) { 1605 if (config->machine == I386 && reloc.Type == COFF::IMAGE_REL_I386_REL32) 1606 // Ignore relative relocations on x86. On x86_64 they can't be ignored 1607 // since they're also used to compute absolute addresses. 1608 continue; 1609 1610 Symbol *ref = sc->file->getSymbol(reloc.SymbolTableIndex); 1611 maybeAddAddressTakenFunction(usedSymbols, ref); 1612 } 1613 } 1614 } 1615 1616 // Create the guard function id table. This is a table of RVAs of all 1617 // address-taken functions. It is sorted and uniqued, just like the safe SEH 1618 // table. 1619 void Writer::createGuardCFTables() { 1620 SymbolRVASet addressTakenSyms; 1621 SymbolRVASet longJmpTargets; 1622 for (ObjFile *file : ObjFile::instances) { 1623 // If the object was compiled with /guard:cf, the address taken symbols 1624 // are in .gfids$y sections, and the longjmp targets are in .gljmp$y 1625 // sections. If the object was not compiled with /guard:cf, we assume there 1626 // were no setjmp targets, and that all code symbols with relocations are 1627 // possibly address-taken. 1628 if (file->hasGuardCF()) { 1629 markSymbolsForRVATable(file, file->getGuardFidChunks(), addressTakenSyms); 1630 markSymbolsForRVATable(file, file->getGuardLJmpChunks(), longJmpTargets); 1631 } else { 1632 markSymbolsWithRelocations(file, addressTakenSyms); 1633 } 1634 } 1635 1636 // Mark the image entry as address-taken. 1637 if (config->entry) 1638 maybeAddAddressTakenFunction(addressTakenSyms, config->entry); 1639 1640 // Mark exported symbols in executable sections as address-taken. 1641 for (Export &e : config->exports) 1642 maybeAddAddressTakenFunction(addressTakenSyms, e.sym); 1643 1644 // Ensure sections referenced in the gfid table are 16-byte aligned. 1645 for (const ChunkAndOffset &c : addressTakenSyms) 1646 if (c.inputChunk->getAlignment() < 16) 1647 c.inputChunk->setAlignment(16); 1648 1649 maybeAddRVATable(std::move(addressTakenSyms), "__guard_fids_table", 1650 "__guard_fids_count"); 1651 1652 // Add the longjmp target table unless the user told us not to. 1653 if (config->guardCF == GuardCFLevel::Full) 1654 maybeAddRVATable(std::move(longJmpTargets), "__guard_longjmp_table", 1655 "__guard_longjmp_count"); 1656 1657 // Set __guard_flags, which will be used in the load config to indicate that 1658 // /guard:cf was enabled. 1659 uint32_t guardFlags = uint32_t(coff_guard_flags::CFInstrumented) | 1660 uint32_t(coff_guard_flags::HasFidTable); 1661 if (config->guardCF == GuardCFLevel::Full) 1662 guardFlags |= uint32_t(coff_guard_flags::HasLongJmpTable); 1663 Symbol *flagSym = symtab->findUnderscore("__guard_flags"); 1664 cast<DefinedAbsolute>(flagSym)->setVA(guardFlags); 1665 } 1666 1667 // Take a list of input sections containing symbol table indices and add those 1668 // symbols to an RVA table. The challenge is that symbol RVAs are not known and 1669 // depend on the table size, so we can't directly build a set of integers. 1670 void Writer::markSymbolsForRVATable(ObjFile *file, 1671 ArrayRef<SectionChunk *> symIdxChunks, 1672 SymbolRVASet &tableSymbols) { 1673 for (SectionChunk *c : symIdxChunks) { 1674 // Skip sections discarded by linker GC. This comes up when a .gfids section 1675 // is associated with something like a vtable and the vtable is discarded. 1676 // In this case, the associated gfids section is discarded, and we don't 1677 // mark the virtual member functions as address-taken by the vtable. 1678 if (!c->live) 1679 continue; 1680 1681 // Validate that the contents look like symbol table indices. 1682 ArrayRef<uint8_t> data = c->getContents(); 1683 if (data.size() % 4 != 0) { 1684 warn("ignoring " + c->getSectionName() + 1685 " symbol table index section in object " + toString(file)); 1686 continue; 1687 } 1688 1689 // Read each symbol table index and check if that symbol was included in the 1690 // final link. If so, add it to the table symbol set. 1691 ArrayRef<ulittle32_t> symIndices( 1692 reinterpret_cast<const ulittle32_t *>(data.data()), data.size() / 4); 1693 ArrayRef<Symbol *> objSymbols = file->getSymbols(); 1694 for (uint32_t symIndex : symIndices) { 1695 if (symIndex >= objSymbols.size()) { 1696 warn("ignoring invalid symbol table index in section " + 1697 c->getSectionName() + " in object " + toString(file)); 1698 continue; 1699 } 1700 if (Symbol *s = objSymbols[symIndex]) { 1701 if (s->isLive()) 1702 addSymbolToRVASet(tableSymbols, cast<Defined>(s)); 1703 } 1704 } 1705 } 1706 } 1707 1708 // Replace the absolute table symbol with a synthetic symbol pointing to 1709 // tableChunk so that we can emit base relocations for it and resolve section 1710 // relative relocations. 1711 void Writer::maybeAddRVATable(SymbolRVASet tableSymbols, StringRef tableSym, 1712 StringRef countSym) { 1713 if (tableSymbols.empty()) 1714 return; 1715 1716 RVATableChunk *tableChunk = make<RVATableChunk>(std::move(tableSymbols)); 1717 rdataSec->addChunk(tableChunk); 1718 1719 Symbol *t = symtab->findUnderscore(tableSym); 1720 Symbol *c = symtab->findUnderscore(countSym); 1721 replaceSymbol<DefinedSynthetic>(t, t->getName(), tableChunk); 1722 cast<DefinedAbsolute>(c)->setVA(tableChunk->getSize() / 4); 1723 } 1724 1725 // MinGW specific. Gather all relocations that are imported from a DLL even 1726 // though the code didn't expect it to, produce the table that the runtime 1727 // uses for fixing them up, and provide the synthetic symbols that the 1728 // runtime uses for finding the table. 1729 void Writer::createRuntimePseudoRelocs() { 1730 std::vector<RuntimePseudoReloc> rels; 1731 1732 for (Chunk *c : symtab->getChunks()) { 1733 auto *sc = dyn_cast<SectionChunk>(c); 1734 if (!sc || !sc->live) 1735 continue; 1736 sc->getRuntimePseudoRelocs(rels); 1737 } 1738 1739 if (!config->pseudoRelocs) { 1740 // Not writing any pseudo relocs; if some were needed, error out and 1741 // indicate what required them. 1742 for (const RuntimePseudoReloc &rpr : rels) 1743 error("automatic dllimport of " + rpr.sym->getName() + " in " + 1744 toString(rpr.target->file) + " requires pseudo relocations"); 1745 return; 1746 } 1747 1748 if (!rels.empty()) 1749 log("Writing " + Twine(rels.size()) + " runtime pseudo relocations"); 1750 PseudoRelocTableChunk *table = make<PseudoRelocTableChunk>(rels); 1751 rdataSec->addChunk(table); 1752 EmptyChunk *endOfList = make<EmptyChunk>(); 1753 rdataSec->addChunk(endOfList); 1754 1755 Symbol *headSym = symtab->findUnderscore("__RUNTIME_PSEUDO_RELOC_LIST__"); 1756 Symbol *endSym = symtab->findUnderscore("__RUNTIME_PSEUDO_RELOC_LIST_END__"); 1757 replaceSymbol<DefinedSynthetic>(headSym, headSym->getName(), table); 1758 replaceSymbol<DefinedSynthetic>(endSym, endSym->getName(), endOfList); 1759 } 1760 1761 // MinGW specific. 1762 // The MinGW .ctors and .dtors lists have sentinels at each end; 1763 // a (uintptr_t)-1 at the start and a (uintptr_t)0 at the end. 1764 // There's a symbol pointing to the start sentinel pointer, __CTOR_LIST__ 1765 // and __DTOR_LIST__ respectively. 1766 void Writer::insertCtorDtorSymbols() { 1767 AbsolutePointerChunk *ctorListHead = make<AbsolutePointerChunk>(-1); 1768 AbsolutePointerChunk *ctorListEnd = make<AbsolutePointerChunk>(0); 1769 AbsolutePointerChunk *dtorListHead = make<AbsolutePointerChunk>(-1); 1770 AbsolutePointerChunk *dtorListEnd = make<AbsolutePointerChunk>(0); 1771 ctorsSec->insertChunkAtStart(ctorListHead); 1772 ctorsSec->addChunk(ctorListEnd); 1773 dtorsSec->insertChunkAtStart(dtorListHead); 1774 dtorsSec->addChunk(dtorListEnd); 1775 1776 Symbol *ctorListSym = symtab->findUnderscore("__CTOR_LIST__"); 1777 Symbol *dtorListSym = symtab->findUnderscore("__DTOR_LIST__"); 1778 replaceSymbol<DefinedSynthetic>(ctorListSym, ctorListSym->getName(), 1779 ctorListHead); 1780 replaceSymbol<DefinedSynthetic>(dtorListSym, dtorListSym->getName(), 1781 dtorListHead); 1782 } 1783 1784 // Handles /section options to allow users to overwrite 1785 // section attributes. 1786 void Writer::setSectionPermissions() { 1787 for (auto &p : config->section) { 1788 StringRef name = p.first; 1789 uint32_t perm = p.second; 1790 for (OutputSection *sec : outputSections) 1791 if (sec->name == name) 1792 sec->setPermissions(perm); 1793 } 1794 } 1795 1796 // Write section contents to a mmap'ed file. 1797 void Writer::writeSections() { 1798 // Record the number of sections to apply section index relocations 1799 // against absolute symbols. See applySecIdx in Chunks.cpp.. 1800 DefinedAbsolute::numOutputSections = outputSections.size(); 1801 1802 uint8_t *buf = buffer->getBufferStart(); 1803 for (OutputSection *sec : outputSections) { 1804 uint8_t *secBuf = buf + sec->getFileOff(); 1805 // Fill gaps between functions in .text with INT3 instructions 1806 // instead of leaving as NUL bytes (which can be interpreted as 1807 // ADD instructions). 1808 if (sec->header.Characteristics & IMAGE_SCN_CNT_CODE) 1809 memset(secBuf, 0xCC, sec->getRawSize()); 1810 parallelForEach(sec->chunks, [&](Chunk *c) { 1811 c->writeTo(secBuf + c->getRVA() - sec->getRVA()); 1812 }); 1813 } 1814 } 1815 1816 void Writer::writeBuildId() { 1817 // There are two important parts to the build ID. 1818 // 1) If building with debug info, the COFF debug directory contains a 1819 // timestamp as well as a Guid and Age of the PDB. 1820 // 2) In all cases, the PE COFF file header also contains a timestamp. 1821 // For reproducibility, instead of a timestamp we want to use a hash of the 1822 // PE contents. 1823 if (config->debug) { 1824 assert(buildId && "BuildId is not set!"); 1825 // BuildId->BuildId was filled in when the PDB was written. 1826 } 1827 1828 // At this point the only fields in the COFF file which remain unset are the 1829 // "timestamp" in the COFF file header, and the ones in the coff debug 1830 // directory. Now we can hash the file and write that hash to the various 1831 // timestamp fields in the file. 1832 StringRef outputFileData( 1833 reinterpret_cast<const char *>(buffer->getBufferStart()), 1834 buffer->getBufferSize()); 1835 1836 uint32_t timestamp = config->timestamp; 1837 uint64_t hash = 0; 1838 bool generateSyntheticBuildId = 1839 config->mingw && config->debug && config->pdbPath.empty(); 1840 1841 if (config->repro || generateSyntheticBuildId) 1842 hash = xxHash64(outputFileData); 1843 1844 if (config->repro) 1845 timestamp = static_cast<uint32_t>(hash); 1846 1847 if (generateSyntheticBuildId) { 1848 // For MinGW builds without a PDB file, we still generate a build id 1849 // to allow associating a crash dump to the executable. 1850 buildId->buildId->PDB70.CVSignature = OMF::Signature::PDB70; 1851 buildId->buildId->PDB70.Age = 1; 1852 memcpy(buildId->buildId->PDB70.Signature, &hash, 8); 1853 // xxhash only gives us 8 bytes, so put some fixed data in the other half. 1854 memcpy(&buildId->buildId->PDB70.Signature[8], "LLD PDB.", 8); 1855 } 1856 1857 if (debugDirectory) 1858 debugDirectory->setTimeDateStamp(timestamp); 1859 1860 uint8_t *buf = buffer->getBufferStart(); 1861 buf += dosStubSize + sizeof(PEMagic); 1862 object::coff_file_header *coffHeader = 1863 reinterpret_cast<coff_file_header *>(buf); 1864 coffHeader->TimeDateStamp = timestamp; 1865 } 1866 1867 // Sort .pdata section contents according to PE/COFF spec 5.5. 1868 void Writer::sortExceptionTable() { 1869 if (!firstPdata) 1870 return; 1871 // We assume .pdata contains function table entries only. 1872 auto bufAddr = [&](Chunk *c) { 1873 OutputSection *os = c->getOutputSection(); 1874 return buffer->getBufferStart() + os->getFileOff() + c->getRVA() - 1875 os->getRVA(); 1876 }; 1877 uint8_t *begin = bufAddr(firstPdata); 1878 uint8_t *end = bufAddr(lastPdata) + lastPdata->getSize(); 1879 if (config->machine == AMD64) { 1880 struct Entry { ulittle32_t begin, end, unwind; }; 1881 if ((end - begin) % sizeof(Entry) != 0) { 1882 fatal("unexpected .pdata size: " + Twine(end - begin) + 1883 " is not a multiple of " + Twine(sizeof(Entry))); 1884 } 1885 parallelSort( 1886 MutableArrayRef<Entry>((Entry *)begin, (Entry *)end), 1887 [](const Entry &a, const Entry &b) { return a.begin < b.begin; }); 1888 return; 1889 } 1890 if (config->machine == ARMNT || config->machine == ARM64) { 1891 struct Entry { ulittle32_t begin, unwind; }; 1892 if ((end - begin) % sizeof(Entry) != 0) { 1893 fatal("unexpected .pdata size: " + Twine(end - begin) + 1894 " is not a multiple of " + Twine(sizeof(Entry))); 1895 } 1896 parallelSort( 1897 MutableArrayRef<Entry>((Entry *)begin, (Entry *)end), 1898 [](const Entry &a, const Entry &b) { return a.begin < b.begin; }); 1899 return; 1900 } 1901 lld::errs() << "warning: don't know how to handle .pdata.\n"; 1902 } 1903 1904 // The CRT section contains, among other things, the array of function 1905 // pointers that initialize every global variable that is not trivially 1906 // constructed. The CRT calls them one after the other prior to invoking 1907 // main(). 1908 // 1909 // As per C++ spec, 3.6.2/2.3, 1910 // "Variables with ordered initialization defined within a single 1911 // translation unit shall be initialized in the order of their definitions 1912 // in the translation unit" 1913 // 1914 // It is therefore critical to sort the chunks containing the function 1915 // pointers in the order that they are listed in the object file (top to 1916 // bottom), otherwise global objects might not be initialized in the 1917 // correct order. 1918 void Writer::sortCRTSectionChunks(std::vector<Chunk *> &chunks) { 1919 auto sectionChunkOrder = [](const Chunk *a, const Chunk *b) { 1920 auto sa = dyn_cast<SectionChunk>(a); 1921 auto sb = dyn_cast<SectionChunk>(b); 1922 assert(sa && sb && "Non-section chunks in CRT section!"); 1923 1924 StringRef sAObj = sa->file->mb.getBufferIdentifier(); 1925 StringRef sBObj = sb->file->mb.getBufferIdentifier(); 1926 1927 return sAObj == sBObj && sa->getSectionNumber() < sb->getSectionNumber(); 1928 }; 1929 llvm::stable_sort(chunks, sectionChunkOrder); 1930 1931 if (config->verbose) { 1932 for (auto &c : chunks) { 1933 auto sc = dyn_cast<SectionChunk>(c); 1934 log(" " + sc->file->mb.getBufferIdentifier().str() + 1935 ", SectionID: " + Twine(sc->getSectionNumber())); 1936 } 1937 } 1938 } 1939 1940 OutputSection *Writer::findSection(StringRef name) { 1941 for (OutputSection *sec : outputSections) 1942 if (sec->name == name) 1943 return sec; 1944 return nullptr; 1945 } 1946 1947 uint32_t Writer::getSizeOfInitializedData() { 1948 uint32_t res = 0; 1949 for (OutputSection *s : outputSections) 1950 if (s->header.Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA) 1951 res += s->getRawSize(); 1952 return res; 1953 } 1954 1955 // Add base relocations to .reloc section. 1956 void Writer::addBaserels() { 1957 if (!config->relocatable) 1958 return; 1959 relocSec->chunks.clear(); 1960 std::vector<Baserel> v; 1961 for (OutputSection *sec : outputSections) { 1962 if (sec->header.Characteristics & IMAGE_SCN_MEM_DISCARDABLE) 1963 continue; 1964 // Collect all locations for base relocations. 1965 for (Chunk *c : sec->chunks) 1966 c->getBaserels(&v); 1967 // Add the addresses to .reloc section. 1968 if (!v.empty()) 1969 addBaserelBlocks(v); 1970 v.clear(); 1971 } 1972 } 1973 1974 // Add addresses to .reloc section. Note that addresses are grouped by page. 1975 void Writer::addBaserelBlocks(std::vector<Baserel> &v) { 1976 const uint32_t mask = ~uint32_t(pageSize - 1); 1977 uint32_t page = v[0].rva & mask; 1978 size_t i = 0, j = 1; 1979 for (size_t e = v.size(); j < e; ++j) { 1980 uint32_t p = v[j].rva & mask; 1981 if (p == page) 1982 continue; 1983 relocSec->addChunk(make<BaserelChunk>(page, &v[i], &v[0] + j)); 1984 i = j; 1985 page = p; 1986 } 1987 if (i == j) 1988 return; 1989 relocSec->addChunk(make<BaserelChunk>(page, &v[i], &v[0] + j)); 1990 } 1991 1992 PartialSection *Writer::createPartialSection(StringRef name, 1993 uint32_t outChars) { 1994 PartialSection *&pSec = partialSections[{name, outChars}]; 1995 if (pSec) 1996 return pSec; 1997 pSec = make<PartialSection>(name, outChars); 1998 return pSec; 1999 } 2000 2001 PartialSection *Writer::findPartialSection(StringRef name, uint32_t outChars) { 2002 auto it = partialSections.find({name, outChars}); 2003 if (it != partialSections.end()) 2004 return it->second; 2005 return nullptr; 2006 } 2007