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