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