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