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