1 //===- Writer.cpp ---------------------------------------------------------===//
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
14 #include "InputFiles.h"
18 #include "SymbolTable.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"
36 using namespace llvm::COFF;
37 using namespace llvm::object;
38 using namespace llvm::support;
39 using namespace llvm::support::endian;
41 using namespace lld::coff;
43 static const int SectorSize = 512;
44 static const int DOSStubSize = 64;
45 static const int NumberfOfDataDirectory = 16;
49 class DebugDirectoryChunk : public Chunk {
51 DebugDirectoryChunk(const std::vector<Chunk *> &R) : Records(R) {}
53 size_t getSize() const override {
54 return Records.size() * sizeof(debug_directory);
57 void writeTo(uint8_t *B) const override {
58 auto *D = reinterpret_cast<debug_directory *>(B + OutputSectionOff);
60 for (const Chunk *Record : Records) {
61 D->Characteristics = 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;
76 const std::vector<Chunk *> &Records;
79 class CVDebugRecordChunk : public Chunk {
80 size_t getSize() const override {
81 return sizeof(codeview::DebugInfo) + Config->PDBPath.size() + 1;
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);
89 DI->Signature.CVSignature = OMF::Signature::PDB70;
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';
99 mutable codeview::DebugInfo *DI = nullptr;
102 // The writer writes a SymbolTable result to a file.
105 Writer(SymbolTable *T) : Symtab(T) {}
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();
124 llvm::Optional<coff_symbol16> createSymbol(Defined *D);
125 size_t addEntryToStringTable(StringRef Str);
127 OutputSection *findSection(StringRef Name);
128 OutputSection *createSection(StringRef Name);
129 void addBaserels(OutputSection *Dest);
130 void addBaserelBlocks(OutputSection *Dest, std::vector<Baserel> &V);
132 uint32_t getSizeOfInitializedData();
133 std::map<StringRef, std::vector<DefinedImportData *>> binImports();
136 std::unique_ptr<FileOutputBuffer> Buffer;
137 std::vector<OutputSection *> OutputSections;
138 std::vector<char> Strtab;
139 std::vector<llvm::object::coff_symbol16> OutputSymtab;
141 DelayLoadContents DelayIdata;
143 SEHTableChunk *SEHTable = nullptr;
145 Chunk *DebugDirectory = nullptr;
146 std::vector<Chunk *> DebugRecords;
147 CVDebugRecordChunk *BuildId = nullptr;
148 ArrayRef<uint8_t> SectionTable;
151 uint32_t PointerToSymbolTable = 0;
152 uint64_t SizeOfImage;
153 uint64_t SizeOfHeaders;
155 } // anonymous namespace
160 void writeResult(SymbolTable *T) { Writer(T).run(); }
162 void OutputSection::setRVA(uint64_t RVA) {
163 Header.VirtualAddress = RVA;
164 for (Chunk *C : Chunks)
165 C->setRVA(C->getRVA() + RVA);
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
172 if (Header.SizeOfRawData == 0)
174 Header.PointerToRawData = Off;
177 void OutputSection::addChunk(Chunk *C) {
179 C->setOutputSection(this);
180 uint64_t Off = Header.VirtualSize;
181 Off = alignTo(Off, C->getAlign());
183 C->OutputSectionOff = Off;
185 Header.VirtualSize = Off;
187 Header.SizeOfRawData = alignTo(Off, SectorSize);
190 void OutputSection::addPermissions(uint32_t C) {
191 Header.Characteristics |= C & PermMask;
194 void OutputSection::setPermissions(uint32_t C) {
195 Header.Characteristics = C & PermMask;
198 // Write the section header to a given buffer.
199 void OutputSection::writeHeaderTo(uint8_t *Buf) {
200 auto *Hdr = reinterpret_cast<coff_section *>(Buf);
202 if (StringTableOff) {
203 // If name is too long, write offset into the string table as a name.
204 sprintf(Hdr->Name, "/%d", StringTableOff);
206 assert(!Config->Debug || Name.size() <= COFF::NameSize);
207 strncpy(Hdr->Name, Name.data(),
208 std::min(Name.size(), (size_t)COFF::NameSize));
215 // The main function of the writer.
219 createImportTables();
221 if (Config->Relocatable)
222 createSection(".reloc");
224 removeEmptySections();
225 setSectionPermissions();
226 createSymbolAndStringTable();
227 openFile(Config->OutputFile);
228 if (Config->is64()) {
229 writeHeader<pe32plus_header>();
231 writeHeader<pe32_header>();
235 sortExceptionTable();
238 if (!Config->PDBPath.empty() && Config->Debug) {
239 const llvm::codeview::DebugInfo *DI = nullptr;
240 if (Config->DebugTypes & static_cast<unsigned>(coff::DebugType::CV))
242 createPDB(Config->PDBPath, Symtab, SectionTable, DI);
245 writeMapFile(OutputSections);
247 if (auto EC = Buffer->commit())
248 fatal(EC, "failed to write the output file");
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())
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()) {
267 SC->printDiscardedMessage();
270 Map[C->getSectionName()].push_back(C);
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];
282 Sec = make<OutputSection>(Name);
283 OutputSections.push_back(Sec);
285 std::vector<Chunk *> &Chunks = Pair.second;
286 for (Chunk *C : Chunks) {
288 Sec->addPermissions(C->getPermissions());
293 void Writer::createMiscChunks() {
294 OutputSection *RData = createSection(".rdata");
296 // Create thunks for locally-dllimported symbols.
297 if (!Symtab->LocalImportChunks.empty()) {
298 for (Chunk *C : Symtab->LocalImportChunks)
302 // Create Debug Information Chunks
304 DebugDirectory = make<DebugDirectoryChunk>(DebugRecords);
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>();
311 DebugRecords.push_back(Chunk);
314 RData->addChunk(DebugDirectory);
315 for (Chunk *C : DebugRecords)
319 // Create SEH table. x86-only.
320 if (Config->Machine != I386)
323 std::set<Defined *> Handlers;
325 for (lld::coff::ObjectFile *File : Symtab->ObjectFiles) {
326 if (!File->SEHCompat)
328 for (SymbolBody *B : File->SEHandlers) {
329 // Make sure the handler is still live. Assume all handlers are regular
331 auto *D = dyn_cast<DefinedRegular>(B);
332 if (D && D->getChunk()->isLive())
337 if (!Handlers.empty()) {
338 SEHTable = make<SEHTableChunk>(Handlers);
339 RData->addChunk(SEHTable);
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())
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) {
358 std::string DLL = StringRef(File->DLLName).lower();
359 if (Config->DLLOrder.count(DLL) == 0)
360 Config->DLLOrder[DLL] = Config->DLLOrder.size();
363 OutputSection *Text = createSection(".text");
364 for (ImportFile *File : Symtab->ImportFiles) {
368 if (DefinedImportThunk *Thunk = File->ThunkSym)
369 Text->addChunk(Thunk->getChunk());
371 if (Config->DelayLoads.count(StringRef(File->DLLName).lower())) {
373 fatal("cannot delay-load " + toString(File) +
374 " due to import of data: " + toString(*File->ImpSym));
375 DelayIdata.add(File->ImpSym);
377 Idata.add(File->ImpSym);
381 if (!Idata.empty()) {
382 OutputSection *Sec = createSection(".idata");
383 for (Chunk *C : Idata.getChunks())
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())
393 Sec = createSection(".data");
394 for (Chunk *C : DelayIdata.getDataChunks())
396 Sec = createSection(".text");
397 for (Chunk *C : DelayIdata.getCodeChunks())
402 void Writer::createExportTable() {
403 if (Config->Exports.empty())
405 OutputSection *Sec = createSection(".edata");
406 for (Chunk *C : Edata.Chunks)
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());
418 for (OutputSection *Sec : OutputSections)
419 Sec->SectionIndex = Idx++;
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;
430 Optional<coff_symbol16> Writer::createSymbol(Defined *Def) {
431 // Relative symbols are unrepresentable in a COFF symbol table.
432 if (isa<DefinedSynthetic>(Def))
435 if (auto *D = dyn_cast<DefinedRegular>(Def)) {
436 // Don't write dead symbols or symbols in codeview sections to the symbol
438 if (!D->getChunk()->isLive() || D->getChunk()->isCodeView())
442 if (auto *Sym = dyn_cast<DefinedImportData>(Def))
443 if (!Sym->File->Live)
446 if (auto *Sym = dyn_cast<DefinedImportThunk>(Def))
447 if (!Sym->WrappedSym->File->Live)
451 StringRef Name = Def->getName();
452 if (Name.size() > COFF::NameSize) {
453 Sym.Name.Offset.Zeroes = 0;
454 Sym.Name.Offset.Offset = addEntryToStringTable(Name);
456 memset(Sym.Name.ShortName, 0, COFF::NameSize);
457 memcpy(Sym.Name.ShortName, Name.data(), Name.size());
460 if (auto *D = dyn_cast<DefinedCOFF>(Def)) {
461 COFFSymbolRef Ref = D->getCOFFSymbol();
462 Sym.Type = Ref.getType();
463 Sym.StorageClass = Ref.getStorageClass();
465 Sym.Type = IMAGE_SYM_TYPE_NULL;
466 Sym.StorageClass = IMAGE_SYM_CLASS_EXTERNAL;
468 Sym.NumberOfAuxSymbols = 0;
470 switch (Def->kind()) {
471 case SymbolBody::DefinedAbsoluteKind:
472 Sym.Value = Def->getRVA();
473 Sym.SectionNumber = IMAGE_SYM_ABSOLUTE;
476 uint64_t RVA = Def->getRVA();
477 OutputSection *Sec = nullptr;
478 for (OutputSection *S : OutputSections) {
479 if (S->getRVA() > RVA)
483 Sym.Value = RVA - Sec->getRVA();
484 Sym.SectionNumber = Sec->SectionIndex;
491 void Writer::createSymbolAndStringTable() {
492 if (!Config->Debug || !Config->WriteSymtab)
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)
501 Sec->setStringTableOff(addEntryToStringTable(Name));
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)
509 D->WrittenToSymtab = true;
511 if (Optional<coff_symbol16> Sym = createSymbol(D))
512 OutputSymtab.push_back(*Sym);
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);
525 FileOff += Strtab.size() + 4;
526 FileSize = alignTo(FileOff, SectorSize);
529 // Visits all sections to assign incremental, non-overlapping RVAs and
531 void Writer::assignAddresses() {
532 SizeOfHeaders = DOSStubSize + sizeof(PEMagic) + sizeof(coff_file_header) +
533 sizeof(data_directory) * NumberfOfDataDirectory +
534 sizeof(coff_section) * OutputSections.size();
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;
546 for (OutputSection *Sec : OutputSections) {
547 if (Sec->getName() == ".reloc")
550 Sec->setFileOffset(FileSize);
551 RVA += alignTo(Sec->getVirtualSize(), PageSize);
552 FileSize += alignTo(Sec->getRawSize(), SectorSize);
554 SizeOfImage = SizeOfHeaders + alignTo(RVA - 0x1000, PageSize);
557 template <typename PEHeaderTy> void Writer::writeHeader() {
559 uint8_t *Buf = Buffer->getBufferStart();
560 auto *DOS = reinterpret_cast<dos_header *>(Buf);
564 DOS->AddressOfRelocationTable = sizeof(dos_header);
565 DOS->AddressOfNewExeHeader = DOSStubSize;
568 memcpy(Buf, PEMagic, sizeof(PEMagic));
569 Buf += sizeof(PEMagic);
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;
580 COFF->Characteristics |= IMAGE_FILE_32BIT_MACHINE;
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;
589 auto *PE = reinterpret_cast<PEHeaderTy *>(Buf);
591 PE->Magic = Config->is64() ? PE32Header::PE32_PLUS : PE32Header::PE32;
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
598 PE->MajorLinkerVersion = 14;
599 PE->MinorLinkerVersion = 0;
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;
620 PE->SizeOfStackReserve = Config->StackReserve;
621 PE->SizeOfStackCommit = Config->StackCommit;
622 PE->SizeOfHeapReserve = Config->HeapReserve;
623 PE->SizeOfHeapCommit = Config->HeapCommit;
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;
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();
648 PE->SizeOfInitializedData = getSizeOfInitializedData();
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();
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();
663 if (OutputSection *Sec = findSection(".rsrc")) {
664 Dir[RESOURCE_TABLE].RelativeVirtualAddress = Sec->getRVA();
665 Dir[RESOURCE_TABLE].Size = Sec->getVirtualSize();
667 if (OutputSection *Sec = findSection(".pdata")) {
668 Dir[EXCEPTION_TABLE].RelativeVirtualAddress = Sec->getRVA();
669 Dir[EXCEPTION_TABLE].Size = Sec->getVirtualSize();
671 if (OutputSection *Sec = findSection(".reloc")) {
672 Dir[BASE_RELOCATION_TABLE].RelativeVirtualAddress = Sec->getRVA();
673 Dir[BASE_RELOCATION_TABLE].Size = Sec->getVirtualSize();
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);
684 Dir[DEBUG_DIRECTORY].RelativeVirtualAddress = DebugDirectory->getRVA();
685 Dir[DEBUG_DIRECTORY].Size = DebugDirectory->getSize();
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");
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;
704 if (!DelayIdata.empty()) {
705 Dir[DELAY_IMPORT_DESCRIPTOR].RelativeVirtualAddress =
706 DelayIdata.getDirRVA();
707 Dir[DELAY_IMPORT_DESCRIPTOR].Size = DelayIdata.getDirSize();
710 // Write section table
711 for (OutputSection *Sec : OutputSections) {
712 Sec->writeHeaderTo(Buf);
713 Buf += sizeof(coff_section);
715 SectionTable = ArrayRef<uint8_t>(
716 Buf - OutputSections.size() * sizeof(coff_section), Buf);
718 if (OutputSymtab.empty())
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);
733 memcpy(Buf + 4, Strtab.data(), Strtab.size());
736 void Writer::openFile(StringRef Path) {
738 FileOutputBuffer::create(Path, FileSize, FileOutputBuffer::F_executable),
739 "failed to open " + Path);
742 void Writer::fixSafeSEHSymbols() {
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);
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);
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;
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); });
784 // Sort .pdata section contents according to PE/COFF spec 5.5.
785 void Writer::sortExceptionTable() {
786 OutputSection *Sec = findSection(".pdata");
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; });
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; });
804 errs() << "warning: don't know how to handle .pdata.\n";
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)
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");
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);
823 // TODO(compnerd) track the Age
824 BuildId->DI->PDB70.Age = 1;
827 OutputSection *Writer::findSection(StringRef Name) {
828 for (OutputSection *Sec : OutputSections)
829 if (Sec->getName() == Name)
834 uint32_t Writer::getSizeOfInitializedData() {
836 for (OutputSection *S : OutputSections)
837 if (S->getPermissions() & IMAGE_SCN_CNT_INITIALIZED_DATA)
838 Res += S->getRawSize();
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))
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)
861 llvm_unreachable("unknown section name");
862 auto Sec = make<OutputSection>(Name);
863 Sec->addPermissions(Perms);
864 OutputSections.push_back(Sec);
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) {
874 // Collect all locations for base relocations.
875 for (Chunk *C : Sec->getChunks())
877 // Add the addresses to .reloc section.
879 addBaserelBlocks(Dest, V);
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;
889 for (size_t E = V.size(); J < E; ++J) {
890 uint32_t P = V[J].RVA & Mask;
893 Dest->addChunk(make<BaserelChunk>(Page, &V[I], &V[0] + J));
899 Dest->addChunk(make<BaserelChunk>(Page, &V[I], &V[0] + J));