1 //===- Writer.cpp ---------------------------------------------------------===// 2 // 3 // The LLVM Linker 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include "Writer.h" 11 #include "Config.h" 12 #include "DLL.h" 13 #include "InputFiles.h" 14 #include "MapFile.h" 15 #include "PDB.h" 16 #include "SymbolTable.h" 17 #include "Symbols.h" 18 #include "lld/Common/ErrorHandler.h" 19 #include "lld/Common/Memory.h" 20 #include "llvm/ADT/DenseMap.h" 21 #include "llvm/ADT/STLExtras.h" 22 #include "llvm/ADT/StringSwitch.h" 23 #include "llvm/Support/BinaryStreamReader.h" 24 #include "llvm/Support/Debug.h" 25 #include "llvm/Support/Endian.h" 26 #include "llvm/Support/FileOutputBuffer.h" 27 #include "llvm/Support/Parallel.h" 28 #include "llvm/Support/RandomNumberGenerator.h" 29 #include <algorithm> 30 #include <cstdio> 31 #include <map> 32 #include <memory> 33 #include <utility> 34 35 using namespace llvm; 36 using namespace llvm::COFF; 37 using namespace llvm::object; 38 using namespace llvm::support; 39 using namespace llvm::support::endian; 40 using namespace lld; 41 using namespace lld::coff; 42 43 static const int SectorSize = 512; 44 static const int DOSStubSize = 64; 45 static const int NumberfOfDataDirectory = 16; 46 47 namespace { 48 49 class DebugDirectoryChunk : public Chunk { 50 public: 51 DebugDirectoryChunk(const std::vector<Chunk *> &R) : Records(R) {} 52 53 size_t getSize() const override { 54 return Records.size() * sizeof(debug_directory); 55 } 56 57 void writeTo(uint8_t *B) const override { 58 auto *D = reinterpret_cast<debug_directory *>(B + OutputSectionOff); 59 60 for (const Chunk *Record : Records) { 61 D->Characteristics = 0; 62 D->TimeDateStamp = 0; 63 D->MajorVersion = 0; 64 D->MinorVersion = 0; 65 D->Type = COFF::IMAGE_DEBUG_TYPE_CODEVIEW; 66 D->SizeOfData = Record->getSize(); 67 D->AddressOfRawData = Record->getRVA(); 68 OutputSection *OS = Record->getOutputSection(); 69 uint64_t Offs = OS->getFileOff() + (Record->getRVA() - OS->getRVA()); 70 D->PointerToRawData = Offs; 71 72 ++D; 73 } 74 } 75 76 private: 77 const std::vector<Chunk *> &Records; 78 }; 79 80 class CVDebugRecordChunk : public Chunk { 81 public: 82 CVDebugRecordChunk() { 83 PDBAbsPath = Config->PDBPath; 84 if (!PDBAbsPath.empty()) 85 llvm::sys::fs::make_absolute(PDBAbsPath); 86 } 87 88 size_t getSize() const override { 89 return sizeof(codeview::DebugInfo) + PDBAbsPath.size() + 1; 90 } 91 92 void writeTo(uint8_t *B) const override { 93 // Save off the DebugInfo entry to backfill the file signature (build id) 94 // in Writer::writeBuildId 95 BuildId = reinterpret_cast<codeview::DebugInfo *>(B + OutputSectionOff); 96 97 // variable sized field (PDB Path) 98 char *P = reinterpret_cast<char *>(B + OutputSectionOff + sizeof(*BuildId)); 99 if (!PDBAbsPath.empty()) 100 memcpy(P, PDBAbsPath.data(), PDBAbsPath.size()); 101 P[PDBAbsPath.size()] = '\0'; 102 } 103 104 SmallString<128> PDBAbsPath; 105 mutable codeview::DebugInfo *BuildId = nullptr; 106 }; 107 108 // The writer writes a SymbolTable result to a file. 109 class Writer { 110 public: 111 Writer() : Buffer(errorHandler().OutputBuffer) {} 112 void run(); 113 114 private: 115 void createSections(); 116 void createMiscChunks(); 117 void createImportTables(); 118 void createExportTable(); 119 void assignAddresses(); 120 void removeEmptySections(); 121 void createSymbolAndStringTable(); 122 void openFile(StringRef OutputPath); 123 template <typename PEHeaderTy> void writeHeader(); 124 void createSEHTable(OutputSection *RData); 125 void setSectionPermissions(); 126 void writeSections(); 127 void writeBuildId(); 128 void sortExceptionTable(); 129 130 llvm::Optional<coff_symbol16> createSymbol(Defined *D); 131 size_t addEntryToStringTable(StringRef Str); 132 133 OutputSection *findSection(StringRef Name); 134 OutputSection *createSection(StringRef Name); 135 void addBaserels(OutputSection *Dest); 136 void addBaserelBlocks(OutputSection *Dest, std::vector<Baserel> &V); 137 138 uint32_t getSizeOfInitializedData(); 139 std::map<StringRef, std::vector<DefinedImportData *>> binImports(); 140 141 std::unique_ptr<FileOutputBuffer> &Buffer; 142 std::vector<OutputSection *> OutputSections; 143 std::vector<char> Strtab; 144 std::vector<llvm::object::coff_symbol16> OutputSymtab; 145 IdataContents Idata; 146 DelayLoadContents DelayIdata; 147 EdataContents Edata; 148 SEHTableChunk *SEHTable = nullptr; 149 150 Chunk *DebugDirectory = nullptr; 151 std::vector<Chunk *> DebugRecords; 152 CVDebugRecordChunk *BuildId = nullptr; 153 Optional<codeview::DebugInfo> PreviousBuildId; 154 ArrayRef<uint8_t> SectionTable; 155 156 uint64_t FileSize; 157 uint32_t PointerToSymbolTable = 0; 158 uint64_t SizeOfImage; 159 uint64_t SizeOfHeaders; 160 }; 161 } // anonymous namespace 162 163 namespace lld { 164 namespace coff { 165 166 void writeResult() { Writer().run(); } 167 168 void OutputSection::setRVA(uint64_t RVA) { 169 Header.VirtualAddress = RVA; 170 for (Chunk *C : Chunks) 171 C->setRVA(C->getRVA() + RVA); 172 } 173 174 void OutputSection::setFileOffset(uint64_t Off) { 175 // If a section has no actual data (i.e. BSS section), we want to 176 // set 0 to its PointerToRawData. Otherwise the output is rejected 177 // by the loader. 178 if (Header.SizeOfRawData == 0) 179 return; 180 Header.PointerToRawData = Off; 181 } 182 183 void OutputSection::addChunk(Chunk *C) { 184 Chunks.push_back(C); 185 C->setOutputSection(this); 186 uint64_t Off = Header.VirtualSize; 187 Off = alignTo(Off, C->Alignment); 188 C->setRVA(Off); 189 C->OutputSectionOff = Off; 190 Off += C->getSize(); 191 if (Off > UINT32_MAX) 192 error("section larger than 4 GiB: " + Name); 193 Header.VirtualSize = Off; 194 if (C->hasData()) 195 Header.SizeOfRawData = alignTo(Off, SectorSize); 196 } 197 198 void OutputSection::addPermissions(uint32_t C) { 199 Header.Characteristics |= C & PermMask; 200 } 201 202 void OutputSection::setPermissions(uint32_t C) { 203 Header.Characteristics = C & PermMask; 204 } 205 206 // Write the section header to a given buffer. 207 void OutputSection::writeHeaderTo(uint8_t *Buf) { 208 auto *Hdr = reinterpret_cast<coff_section *>(Buf); 209 *Hdr = Header; 210 if (StringTableOff) { 211 // If name is too long, write offset into the string table as a name. 212 sprintf(Hdr->Name, "/%d", StringTableOff); 213 } else { 214 assert(!Config->Debug || Name.size() <= COFF::NameSize || 215 (Hdr->Characteristics & IMAGE_SCN_MEM_DISCARDABLE) == 0); 216 strncpy(Hdr->Name, Name.data(), 217 std::min(Name.size(), (size_t)COFF::NameSize)); 218 } 219 } 220 221 } // namespace coff 222 } // namespace lld 223 224 // PDBs are matched against executables using a build id which consists of three 225 // components: 226 // 1. A 16-bit GUID 227 // 2. An age 228 // 3. A time stamp. 229 // 230 // Debuggers and symbol servers match executables against debug info by checking 231 // each of these components of the EXE/DLL against the corresponding value in 232 // the PDB and failing a match if any of the components differ. In the case of 233 // symbol servers, symbols are cached in a folder that is a function of the 234 // GUID. As a result, in order to avoid symbol cache pollution where every 235 // incremental build copies a new PDB to the symbol cache, we must try to re-use 236 // the existing GUID if one exists, but bump the age. This way the match will 237 // fail, so the symbol cache knows to use the new PDB, but the GUID matches, so 238 // it overwrites the existing item in the symbol cache rather than making a new 239 // one. 240 static Optional<codeview::DebugInfo> loadExistingBuildId(StringRef Path) { 241 // We don't need to incrementally update a previous build id if we're not 242 // writing codeview debug info. 243 if (!Config->Debug) 244 return None; 245 246 auto ExpectedBinary = llvm::object::createBinary(Path); 247 if (!ExpectedBinary) { 248 consumeError(ExpectedBinary.takeError()); 249 return None; 250 } 251 252 auto Binary = std::move(*ExpectedBinary); 253 if (!Binary.getBinary()->isCOFF()) 254 return None; 255 256 std::error_code EC; 257 COFFObjectFile File(Binary.getBinary()->getMemoryBufferRef(), EC); 258 if (EC) 259 return None; 260 261 // If the machine of the binary we're outputting doesn't match the machine 262 // of the existing binary, don't try to re-use the build id. 263 if (File.is64() != Config->is64() || File.getMachine() != Config->Machine) 264 return None; 265 266 for (const auto &DebugDir : File.debug_directories()) { 267 if (DebugDir.Type != IMAGE_DEBUG_TYPE_CODEVIEW) 268 continue; 269 270 const codeview::DebugInfo *ExistingDI = nullptr; 271 StringRef PDBFileName; 272 if (auto EC = File.getDebugPDBInfo(ExistingDI, PDBFileName)) { 273 (void)EC; 274 return None; 275 } 276 // We only support writing PDBs in v70 format. So if this is not a build 277 // id that we recognize / support, ignore it. 278 if (ExistingDI->Signature.CVSignature != OMF::Signature::PDB70) 279 return None; 280 return *ExistingDI; 281 } 282 return None; 283 } 284 285 // The main function of the writer. 286 void Writer::run() { 287 createSections(); 288 createMiscChunks(); 289 createImportTables(); 290 createExportTable(); 291 if (Config->Relocatable) 292 createSection(".reloc"); 293 assignAddresses(); 294 removeEmptySections(); 295 setSectionPermissions(); 296 createSymbolAndStringTable(); 297 298 // We must do this before opening the output file, as it depends on being able 299 // to read the contents of the existing output file. 300 PreviousBuildId = loadExistingBuildId(Config->OutputFile); 301 openFile(Config->OutputFile); 302 if (Config->is64()) { 303 writeHeader<pe32plus_header>(); 304 } else { 305 writeHeader<pe32_header>(); 306 } 307 writeSections(); 308 sortExceptionTable(); 309 writeBuildId(); 310 311 if (!Config->PDBPath.empty() && Config->Debug) { 312 313 assert(BuildId); 314 createPDB(Symtab, OutputSections, SectionTable, *BuildId->BuildId); 315 } 316 317 writeMapFile(OutputSections); 318 319 if (auto E = Buffer->commit()) 320 fatal("failed to write the output file: " + toString(std::move(E))); 321 } 322 323 static StringRef getOutputSection(StringRef Name) { 324 StringRef S = Name.split('$').first; 325 326 // Treat a later period as a separator for MinGW, for sections like 327 // ".ctors.01234". 328 S = S.substr(0, S.find('.', 1)); 329 330 auto It = Config->Merge.find(S); 331 if (It == Config->Merge.end()) 332 return S; 333 return It->second; 334 } 335 336 // Create output section objects and add them to OutputSections. 337 void Writer::createSections() { 338 // First, bin chunks by name. 339 std::map<StringRef, std::vector<Chunk *>> Map; 340 for (Chunk *C : Symtab->getChunks()) { 341 auto *SC = dyn_cast<SectionChunk>(C); 342 if (SC && !SC->isLive()) { 343 if (Config->Verbose) 344 SC->printDiscardedMessage(); 345 continue; 346 } 347 Map[C->getSectionName()].push_back(C); 348 } 349 350 // Then create an OutputSection for each section. 351 // '$' and all following characters in input section names are 352 // discarded when determining output section. So, .text$foo 353 // contributes to .text, for example. See PE/COFF spec 3.2. 354 SmallDenseMap<StringRef, OutputSection *> Sections; 355 for (auto Pair : Map) { 356 StringRef Name = getOutputSection(Pair.first); 357 OutputSection *&Sec = Sections[Name]; 358 if (!Sec) { 359 Sec = make<OutputSection>(Name); 360 OutputSections.push_back(Sec); 361 } 362 std::vector<Chunk *> &Chunks = Pair.second; 363 for (Chunk *C : Chunks) { 364 Sec->addChunk(C); 365 Sec->addPermissions(C->getPermissions()); 366 } 367 } 368 } 369 370 void Writer::createMiscChunks() { 371 OutputSection *RData = createSection(".rdata"); 372 373 // Create thunks for locally-dllimported symbols. 374 if (!Symtab->LocalImportChunks.empty()) { 375 for (Chunk *C : Symtab->LocalImportChunks) 376 RData->addChunk(C); 377 } 378 379 // Create Debug Information Chunks 380 if (Config->Debug) { 381 DebugDirectory = make<DebugDirectoryChunk>(DebugRecords); 382 383 // Make a CVDebugRecordChunk even when /DEBUG:CV is not specified. We 384 // output a PDB no matter what, and this chunk provides the only means of 385 // allowing a debugger to match a PDB and an executable. So we need it even 386 // if we're ultimately not going to write CodeView data to the PDB. 387 auto *CVChunk = make<CVDebugRecordChunk>(); 388 BuildId = CVChunk; 389 DebugRecords.push_back(CVChunk); 390 391 RData->addChunk(DebugDirectory); 392 for (Chunk *C : DebugRecords) 393 RData->addChunk(C); 394 } 395 396 createSEHTable(RData); 397 } 398 399 // Create .idata section for the DLL-imported symbol table. 400 // The format of this section is inherently Windows-specific. 401 // IdataContents class abstracted away the details for us, 402 // so we just let it create chunks and add them to the section. 403 void Writer::createImportTables() { 404 if (ImportFile::Instances.empty()) 405 return; 406 407 // Initialize DLLOrder so that import entries are ordered in 408 // the same order as in the command line. (That affects DLL 409 // initialization order, and this ordering is MSVC-compatible.) 410 for (ImportFile *File : ImportFile::Instances) { 411 if (!File->Live) 412 continue; 413 414 std::string DLL = StringRef(File->DLLName).lower(); 415 if (Config->DLLOrder.count(DLL) == 0) 416 Config->DLLOrder[DLL] = Config->DLLOrder.size(); 417 } 418 419 OutputSection *Text = createSection(".text"); 420 for (ImportFile *File : ImportFile::Instances) { 421 if (!File->Live) 422 continue; 423 424 if (DefinedImportThunk *Thunk = File->ThunkSym) 425 Text->addChunk(Thunk->getChunk()); 426 427 if (Config->DelayLoads.count(StringRef(File->DLLName).lower())) { 428 if (!File->ThunkSym) 429 fatal("cannot delay-load " + toString(File) + 430 " due to import of data: " + toString(*File->ImpSym)); 431 DelayIdata.add(File->ImpSym); 432 } else { 433 Idata.add(File->ImpSym); 434 } 435 } 436 437 if (!Idata.empty()) { 438 OutputSection *Sec = createSection(".idata"); 439 for (Chunk *C : Idata.getChunks()) 440 Sec->addChunk(C); 441 } 442 443 if (!DelayIdata.empty()) { 444 Defined *Helper = cast<Defined>(Config->DelayLoadHelper); 445 DelayIdata.create(Helper); 446 OutputSection *Sec = createSection(".didat"); 447 for (Chunk *C : DelayIdata.getChunks()) 448 Sec->addChunk(C); 449 Sec = createSection(".data"); 450 for (Chunk *C : DelayIdata.getDataChunks()) 451 Sec->addChunk(C); 452 Sec = createSection(".text"); 453 for (Chunk *C : DelayIdata.getCodeChunks()) 454 Sec->addChunk(C); 455 } 456 } 457 458 void Writer::createExportTable() { 459 if (Config->Exports.empty()) 460 return; 461 OutputSection *Sec = createSection(".edata"); 462 for (Chunk *C : Edata.Chunks) 463 Sec->addChunk(C); 464 } 465 466 // The Windows loader doesn't seem to like empty sections, 467 // so we remove them if any. 468 void Writer::removeEmptySections() { 469 auto IsEmpty = [](OutputSection *S) { return S->getVirtualSize() == 0; }; 470 OutputSections.erase( 471 std::remove_if(OutputSections.begin(), OutputSections.end(), IsEmpty), 472 OutputSections.end()); 473 uint32_t Idx = 1; 474 for (OutputSection *Sec : OutputSections) 475 Sec->SectionIndex = Idx++; 476 } 477 478 size_t Writer::addEntryToStringTable(StringRef Str) { 479 assert(Str.size() > COFF::NameSize); 480 size_t OffsetOfEntry = Strtab.size() + 4; // +4 for the size field 481 Strtab.insert(Strtab.end(), Str.begin(), Str.end()); 482 Strtab.push_back('\0'); 483 return OffsetOfEntry; 484 } 485 486 Optional<coff_symbol16> Writer::createSymbol(Defined *Def) { 487 // Relative symbols are unrepresentable in a COFF symbol table. 488 if (isa<DefinedSynthetic>(Def)) 489 return None; 490 491 // Don't write dead symbols or symbols in codeview sections to the symbol 492 // table. 493 if (!Def->isLive()) 494 return None; 495 if (auto *D = dyn_cast<DefinedRegular>(Def)) 496 if (D->getChunk()->isCodeView()) 497 return None; 498 499 coff_symbol16 Sym; 500 StringRef Name = Def->getName(); 501 if (Name.size() > COFF::NameSize) { 502 Sym.Name.Offset.Zeroes = 0; 503 Sym.Name.Offset.Offset = addEntryToStringTable(Name); 504 } else { 505 memset(Sym.Name.ShortName, 0, COFF::NameSize); 506 memcpy(Sym.Name.ShortName, Name.data(), Name.size()); 507 } 508 509 if (auto *D = dyn_cast<DefinedCOFF>(Def)) { 510 COFFSymbolRef Ref = D->getCOFFSymbol(); 511 Sym.Type = Ref.getType(); 512 Sym.StorageClass = Ref.getStorageClass(); 513 } else { 514 Sym.Type = IMAGE_SYM_TYPE_NULL; 515 Sym.StorageClass = IMAGE_SYM_CLASS_EXTERNAL; 516 } 517 Sym.NumberOfAuxSymbols = 0; 518 519 switch (Def->kind()) { 520 case Symbol::DefinedAbsoluteKind: 521 Sym.Value = Def->getRVA(); 522 Sym.SectionNumber = IMAGE_SYM_ABSOLUTE; 523 break; 524 default: { 525 uint64_t RVA = Def->getRVA(); 526 OutputSection *Sec = nullptr; 527 for (OutputSection *S : OutputSections) { 528 if (S->getRVA() > RVA) 529 break; 530 Sec = S; 531 } 532 Sym.Value = RVA - Sec->getRVA(); 533 Sym.SectionNumber = Sec->SectionIndex; 534 break; 535 } 536 } 537 return Sym; 538 } 539 540 void Writer::createSymbolAndStringTable() { 541 // Name field in the section table is 8 byte long. Longer names need 542 // to be written to the string table. First, construct string table. 543 for (OutputSection *Sec : OutputSections) { 544 StringRef Name = Sec->getName(); 545 if (Name.size() <= COFF::NameSize) 546 continue; 547 // If a section isn't discardable (i.e. will be mapped at runtime), 548 // prefer a truncated section name over a long section name in 549 // the string table that is unavailable at runtime. This is different from 550 // what link.exe does, but finding ".eh_fram" instead of "/4" is useful 551 // to libunwind. 552 if ((Sec->getPermissions() & IMAGE_SCN_MEM_DISCARDABLE) == 0) 553 continue; 554 Sec->setStringTableOff(addEntryToStringTable(Name)); 555 } 556 557 if (Config->DebugDwarf) { 558 for (ObjFile *File : ObjFile::Instances) { 559 for (Symbol *B : File->getSymbols()) { 560 auto *D = dyn_cast_or_null<Defined>(B); 561 if (!D || D->WrittenToSymtab) 562 continue; 563 D->WrittenToSymtab = true; 564 565 if (Optional<coff_symbol16> Sym = createSymbol(D)) 566 OutputSymtab.push_back(*Sym); 567 } 568 } 569 } 570 571 if (OutputSymtab.empty() && Strtab.empty()) 572 return; 573 574 OutputSection *LastSection = OutputSections.back(); 575 // We position the symbol table to be adjacent to the end of the last section. 576 uint64_t FileOff = LastSection->getFileOff() + 577 alignTo(LastSection->getRawSize(), SectorSize); 578 PointerToSymbolTable = FileOff; 579 FileOff += OutputSymtab.size() * sizeof(coff_symbol16); 580 FileOff += 4 + Strtab.size(); 581 FileSize = alignTo(FileOff, SectorSize); 582 } 583 584 // Visits all sections to assign incremental, non-overlapping RVAs and 585 // file offsets. 586 void Writer::assignAddresses() { 587 SizeOfHeaders = DOSStubSize + sizeof(PEMagic) + sizeof(coff_file_header) + 588 sizeof(data_directory) * NumberfOfDataDirectory + 589 sizeof(coff_section) * OutputSections.size(); 590 SizeOfHeaders += 591 Config->is64() ? sizeof(pe32plus_header) : sizeof(pe32_header); 592 SizeOfHeaders = alignTo(SizeOfHeaders, SectorSize); 593 uint64_t RVA = 0x1000; // The first page is kept unmapped. 594 FileSize = SizeOfHeaders; 595 // Move DISCARDABLE (or non-memory-mapped) sections to the end of file because 596 // the loader cannot handle holes. 597 std::stable_partition( 598 OutputSections.begin(), OutputSections.end(), [](OutputSection *S) { 599 return (S->getPermissions() & IMAGE_SCN_MEM_DISCARDABLE) == 0; 600 }); 601 for (OutputSection *Sec : OutputSections) { 602 if (Sec->getName() == ".reloc") 603 addBaserels(Sec); 604 Sec->setRVA(RVA); 605 Sec->setFileOffset(FileSize); 606 RVA += alignTo(Sec->getVirtualSize(), PageSize); 607 FileSize += alignTo(Sec->getRawSize(), SectorSize); 608 } 609 SizeOfImage = alignTo(RVA, PageSize); 610 } 611 612 template <typename PEHeaderTy> void Writer::writeHeader() { 613 // Write DOS stub 614 uint8_t *Buf = Buffer->getBufferStart(); 615 auto *DOS = reinterpret_cast<dos_header *>(Buf); 616 Buf += DOSStubSize; 617 DOS->Magic[0] = 'M'; 618 DOS->Magic[1] = 'Z'; 619 DOS->AddressOfRelocationTable = sizeof(dos_header); 620 DOS->AddressOfNewExeHeader = DOSStubSize; 621 622 // Write PE magic 623 memcpy(Buf, PEMagic, sizeof(PEMagic)); 624 Buf += sizeof(PEMagic); 625 626 // Write COFF header 627 auto *COFF = reinterpret_cast<coff_file_header *>(Buf); 628 Buf += sizeof(*COFF); 629 COFF->Machine = Config->Machine; 630 COFF->NumberOfSections = OutputSections.size(); 631 COFF->Characteristics = IMAGE_FILE_EXECUTABLE_IMAGE; 632 if (Config->LargeAddressAware) 633 COFF->Characteristics |= IMAGE_FILE_LARGE_ADDRESS_AWARE; 634 if (!Config->is64()) 635 COFF->Characteristics |= IMAGE_FILE_32BIT_MACHINE; 636 if (Config->DLL) 637 COFF->Characteristics |= IMAGE_FILE_DLL; 638 if (!Config->Relocatable) 639 COFF->Characteristics |= IMAGE_FILE_RELOCS_STRIPPED; 640 COFF->SizeOfOptionalHeader = 641 sizeof(PEHeaderTy) + sizeof(data_directory) * NumberfOfDataDirectory; 642 643 // Write PE header 644 auto *PE = reinterpret_cast<PEHeaderTy *>(Buf); 645 Buf += sizeof(*PE); 646 PE->Magic = Config->is64() ? PE32Header::PE32_PLUS : PE32Header::PE32; 647 648 // If {Major,Minor}LinkerVersion is left at 0.0, then for some 649 // reason signing the resulting PE file with Authenticode produces a 650 // signature that fails to validate on Windows 7 (but is OK on 10). 651 // Set it to 14.0, which is what VS2015 outputs, and which avoids 652 // that problem. 653 PE->MajorLinkerVersion = 14; 654 PE->MinorLinkerVersion = 0; 655 656 PE->ImageBase = Config->ImageBase; 657 PE->SectionAlignment = PageSize; 658 PE->FileAlignment = SectorSize; 659 PE->MajorImageVersion = Config->MajorImageVersion; 660 PE->MinorImageVersion = Config->MinorImageVersion; 661 PE->MajorOperatingSystemVersion = Config->MajorOSVersion; 662 PE->MinorOperatingSystemVersion = Config->MinorOSVersion; 663 PE->MajorSubsystemVersion = Config->MajorOSVersion; 664 PE->MinorSubsystemVersion = Config->MinorOSVersion; 665 PE->Subsystem = Config->Subsystem; 666 PE->SizeOfImage = SizeOfImage; 667 PE->SizeOfHeaders = SizeOfHeaders; 668 if (!Config->NoEntry) { 669 Defined *Entry = cast<Defined>(Config->Entry); 670 PE->AddressOfEntryPoint = Entry->getRVA(); 671 // Pointer to thumb code must have the LSB set, so adjust it. 672 if (Config->Machine == ARMNT) 673 PE->AddressOfEntryPoint |= 1; 674 } 675 PE->SizeOfStackReserve = Config->StackReserve; 676 PE->SizeOfStackCommit = Config->StackCommit; 677 PE->SizeOfHeapReserve = Config->HeapReserve; 678 PE->SizeOfHeapCommit = Config->HeapCommit; 679 if (Config->AppContainer) 680 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_APPCONTAINER; 681 if (Config->DynamicBase) 682 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE; 683 if (Config->HighEntropyVA) 684 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA; 685 if (!Config->AllowBind) 686 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_BIND; 687 if (Config->NxCompat) 688 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NX_COMPAT; 689 if (!Config->AllowIsolation) 690 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_ISOLATION; 691 if (Config->Machine == I386 && !SEHTable && 692 !Symtab->findUnderscore("_load_config_used")) 693 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_SEH; 694 if (Config->TerminalServerAware) 695 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_TERMINAL_SERVER_AWARE; 696 PE->NumberOfRvaAndSize = NumberfOfDataDirectory; 697 if (OutputSection *Text = findSection(".text")) { 698 PE->BaseOfCode = Text->getRVA(); 699 PE->SizeOfCode = Text->getRawSize(); 700 } 701 PE->SizeOfInitializedData = getSizeOfInitializedData(); 702 703 // Write data directory 704 auto *Dir = reinterpret_cast<data_directory *>(Buf); 705 Buf += sizeof(*Dir) * NumberfOfDataDirectory; 706 if (OutputSection *Sec = findSection(".edata")) { 707 Dir[EXPORT_TABLE].RelativeVirtualAddress = Sec->getRVA(); 708 Dir[EXPORT_TABLE].Size = Sec->getVirtualSize(); 709 } 710 if (!Idata.empty()) { 711 Dir[IMPORT_TABLE].RelativeVirtualAddress = Idata.getDirRVA(); 712 Dir[IMPORT_TABLE].Size = Idata.getDirSize(); 713 Dir[IAT].RelativeVirtualAddress = Idata.getIATRVA(); 714 Dir[IAT].Size = Idata.getIATSize(); 715 } 716 if (OutputSection *Sec = findSection(".rsrc")) { 717 Dir[RESOURCE_TABLE].RelativeVirtualAddress = Sec->getRVA(); 718 Dir[RESOURCE_TABLE].Size = Sec->getVirtualSize(); 719 } 720 if (OutputSection *Sec = findSection(".pdata")) { 721 Dir[EXCEPTION_TABLE].RelativeVirtualAddress = Sec->getRVA(); 722 Dir[EXCEPTION_TABLE].Size = Sec->getVirtualSize(); 723 } 724 if (OutputSection *Sec = findSection(".reloc")) { 725 Dir[BASE_RELOCATION_TABLE].RelativeVirtualAddress = Sec->getRVA(); 726 Dir[BASE_RELOCATION_TABLE].Size = Sec->getVirtualSize(); 727 } 728 if (Symbol *Sym = Symtab->findUnderscore("_tls_used")) { 729 if (Defined *B = dyn_cast<Defined>(Sym)) { 730 Dir[TLS_TABLE].RelativeVirtualAddress = B->getRVA(); 731 Dir[TLS_TABLE].Size = Config->is64() 732 ? sizeof(object::coff_tls_directory64) 733 : sizeof(object::coff_tls_directory32); 734 } 735 } 736 if (Config->Debug) { 737 Dir[DEBUG_DIRECTORY].RelativeVirtualAddress = DebugDirectory->getRVA(); 738 Dir[DEBUG_DIRECTORY].Size = DebugDirectory->getSize(); 739 } 740 if (Symbol *Sym = Symtab->findUnderscore("_load_config_used")) { 741 if (auto *B = dyn_cast<DefinedRegular>(Sym)) { 742 SectionChunk *SC = B->getChunk(); 743 assert(B->getRVA() >= SC->getRVA()); 744 uint64_t OffsetInChunk = B->getRVA() - SC->getRVA(); 745 if (!SC->hasData() || OffsetInChunk + 4 > SC->getSize()) 746 fatal("_load_config_used is malformed"); 747 748 ArrayRef<uint8_t> SecContents = SC->getContents(); 749 uint32_t LoadConfigSize = 750 *reinterpret_cast<const ulittle32_t *>(&SecContents[OffsetInChunk]); 751 if (OffsetInChunk + LoadConfigSize > SC->getSize()) 752 fatal("_load_config_used is too large"); 753 Dir[LOAD_CONFIG_TABLE].RelativeVirtualAddress = B->getRVA(); 754 Dir[LOAD_CONFIG_TABLE].Size = LoadConfigSize; 755 } 756 } 757 if (!DelayIdata.empty()) { 758 Dir[DELAY_IMPORT_DESCRIPTOR].RelativeVirtualAddress = 759 DelayIdata.getDirRVA(); 760 Dir[DELAY_IMPORT_DESCRIPTOR].Size = DelayIdata.getDirSize(); 761 } 762 763 // Write section table 764 for (OutputSection *Sec : OutputSections) { 765 Sec->writeHeaderTo(Buf); 766 Buf += sizeof(coff_section); 767 } 768 SectionTable = ArrayRef<uint8_t>( 769 Buf - OutputSections.size() * sizeof(coff_section), Buf); 770 771 if (OutputSymtab.empty() && Strtab.empty()) 772 return; 773 774 COFF->PointerToSymbolTable = PointerToSymbolTable; 775 uint32_t NumberOfSymbols = OutputSymtab.size(); 776 COFF->NumberOfSymbols = NumberOfSymbols; 777 auto *SymbolTable = reinterpret_cast<coff_symbol16 *>( 778 Buffer->getBufferStart() + COFF->PointerToSymbolTable); 779 for (size_t I = 0; I != NumberOfSymbols; ++I) 780 SymbolTable[I] = OutputSymtab[I]; 781 // Create the string table, it follows immediately after the symbol table. 782 // The first 4 bytes is length including itself. 783 Buf = reinterpret_cast<uint8_t *>(&SymbolTable[NumberOfSymbols]); 784 write32le(Buf, Strtab.size() + 4); 785 if (!Strtab.empty()) 786 memcpy(Buf + 4, Strtab.data(), Strtab.size()); 787 } 788 789 void Writer::openFile(StringRef Path) { 790 Buffer = CHECK( 791 FileOutputBuffer::create(Path, FileSize, FileOutputBuffer::F_executable), 792 "failed to open " + Path); 793 } 794 795 void Writer::createSEHTable(OutputSection *RData) { 796 // Create SEH table. x86-only. 797 if (Config->Machine != I386) 798 return; 799 800 std::set<Defined *> Handlers; 801 802 for (ObjFile *File : ObjFile::Instances) { 803 if (!File->SEHCompat) 804 return; 805 for (uint32_t I : File->SXData) 806 if (Symbol *B = File->getSymbol(I)) 807 if (B->isLive()) 808 Handlers.insert(cast<Defined>(B)); 809 } 810 811 if (Handlers.empty()) 812 return; 813 814 SEHTable = make<SEHTableChunk>(Handlers); 815 RData->addChunk(SEHTable); 816 817 // Replace the absolute table symbol with a synthetic symbol pointing to the 818 // SEHTable chunk so that we can emit base relocations for it and resolve 819 // section relative relocations. 820 Symbol *T = Symtab->find("___safe_se_handler_table"); 821 Symbol *C = Symtab->find("___safe_se_handler_count"); 822 replaceSymbol<DefinedSynthetic>(T, T->getName(), SEHTable); 823 cast<DefinedAbsolute>(C)->setVA(SEHTable->getSize() / 4); 824 } 825 826 // Handles /section options to allow users to overwrite 827 // section attributes. 828 void Writer::setSectionPermissions() { 829 for (auto &P : Config->Section) { 830 StringRef Name = P.first; 831 uint32_t Perm = P.second; 832 if (auto *Sec = findSection(Name)) 833 Sec->setPermissions(Perm); 834 } 835 } 836 837 // Write section contents to a mmap'ed file. 838 void Writer::writeSections() { 839 // Record the section index that should be used when resolving a section 840 // relocation against an absolute symbol. 841 DefinedAbsolute::OutputSectionIndex = OutputSections.size() + 1; 842 843 uint8_t *Buf = Buffer->getBufferStart(); 844 for (OutputSection *Sec : OutputSections) { 845 uint8_t *SecBuf = Buf + Sec->getFileOff(); 846 // Fill gaps between functions in .text with INT3 instructions 847 // instead of leaving as NUL bytes (which can be interpreted as 848 // ADD instructions). 849 if (Sec->getPermissions() & IMAGE_SCN_CNT_CODE) 850 memset(SecBuf, 0xCC, Sec->getRawSize()); 851 for_each(parallel::par, Sec->getChunks().begin(), Sec->getChunks().end(), 852 [&](Chunk *C) { C->writeTo(SecBuf); }); 853 } 854 } 855 856 void Writer::writeBuildId() { 857 // If we're not writing a build id (e.g. because /debug is not specified), 858 // then just return; 859 if (!Config->Debug) 860 return; 861 862 assert(BuildId && "BuildId is not set!"); 863 864 if (PreviousBuildId.hasValue()) { 865 *BuildId->BuildId = *PreviousBuildId; 866 BuildId->BuildId->PDB70.Age = BuildId->BuildId->PDB70.Age + 1; 867 return; 868 } 869 870 BuildId->BuildId->Signature.CVSignature = OMF::Signature::PDB70; 871 BuildId->BuildId->PDB70.Age = 1; 872 llvm::getRandomBytes(BuildId->BuildId->PDB70.Signature, 16); 873 } 874 875 // Sort .pdata section contents according to PE/COFF spec 5.5. 876 void Writer::sortExceptionTable() { 877 OutputSection *Sec = findSection(".pdata"); 878 if (!Sec) 879 return; 880 // We assume .pdata contains function table entries only. 881 uint8_t *Begin = Buffer->getBufferStart() + Sec->getFileOff(); 882 uint8_t *End = Begin + Sec->getVirtualSize(); 883 if (Config->Machine == AMD64) { 884 struct Entry { ulittle32_t Begin, End, Unwind; }; 885 sort(parallel::par, (Entry *)Begin, (Entry *)End, 886 [](const Entry &A, const Entry &B) { return A.Begin < B.Begin; }); 887 return; 888 } 889 if (Config->Machine == ARMNT || Config->Machine == ARM64) { 890 struct Entry { ulittle32_t Begin, Unwind; }; 891 sort(parallel::par, (Entry *)Begin, (Entry *)End, 892 [](const Entry &A, const Entry &B) { return A.Begin < B.Begin; }); 893 return; 894 } 895 errs() << "warning: don't know how to handle .pdata.\n"; 896 } 897 898 OutputSection *Writer::findSection(StringRef Name) { 899 for (OutputSection *Sec : OutputSections) 900 if (Sec->getName() == Name) 901 return Sec; 902 return nullptr; 903 } 904 905 uint32_t Writer::getSizeOfInitializedData() { 906 uint32_t Res = 0; 907 for (OutputSection *S : OutputSections) 908 if (S->getPermissions() & IMAGE_SCN_CNT_INITIALIZED_DATA) 909 Res += S->getRawSize(); 910 return Res; 911 } 912 913 // Returns an existing section or create a new one if not found. 914 OutputSection *Writer::createSection(StringRef Name) { 915 if (auto *Sec = findSection(Name)) 916 return Sec; 917 const auto DATA = IMAGE_SCN_CNT_INITIALIZED_DATA; 918 const auto BSS = IMAGE_SCN_CNT_UNINITIALIZED_DATA; 919 const auto CODE = IMAGE_SCN_CNT_CODE; 920 const auto DISCARDABLE = IMAGE_SCN_MEM_DISCARDABLE; 921 const auto R = IMAGE_SCN_MEM_READ; 922 const auto W = IMAGE_SCN_MEM_WRITE; 923 const auto X = IMAGE_SCN_MEM_EXECUTE; 924 uint32_t Perms = StringSwitch<uint32_t>(Name) 925 .Case(".bss", BSS | R | W) 926 .Case(".data", DATA | R | W) 927 .Cases(".didat", ".edata", ".idata", ".rdata", DATA | R) 928 .Case(".reloc", DATA | DISCARDABLE | R) 929 .Case(".text", CODE | R | X) 930 .Default(0); 931 if (!Perms) 932 llvm_unreachable("unknown section name"); 933 auto Sec = make<OutputSection>(Name); 934 Sec->addPermissions(Perms); 935 OutputSections.push_back(Sec); 936 return Sec; 937 } 938 939 // Dest is .reloc section. Add contents to that section. 940 void Writer::addBaserels(OutputSection *Dest) { 941 std::vector<Baserel> V; 942 for (OutputSection *Sec : OutputSections) { 943 if (Sec == Dest) 944 continue; 945 // Collect all locations for base relocations. 946 for (Chunk *C : Sec->getChunks()) 947 C->getBaserels(&V); 948 // Add the addresses to .reloc section. 949 if (!V.empty()) 950 addBaserelBlocks(Dest, V); 951 V.clear(); 952 } 953 } 954 955 // Add addresses to .reloc section. Note that addresses are grouped by page. 956 void Writer::addBaserelBlocks(OutputSection *Dest, std::vector<Baserel> &V) { 957 const uint32_t Mask = ~uint32_t(PageSize - 1); 958 uint32_t Page = V[0].RVA & Mask; 959 size_t I = 0, J = 1; 960 for (size_t E = V.size(); J < E; ++J) { 961 uint32_t P = V[J].RVA & Mask; 962 if (P == Page) 963 continue; 964 Dest->addChunk(make<BaserelChunk>(Page, &V[I], &V[0] + J)); 965 I = J; 966 Page = P; 967 } 968 if (I == J) 969 return; 970 Dest->addChunk(make<BaserelChunk>(Page, &V[I], &V[0] + J)); 971 } 972