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