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