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