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<std::unique_ptr<Chunk>> &R)
54 size_t getSize() const override {
55 return Records.size() * sizeof(debug_directory);
58 void writeTo(uint8_t *B) const override {
59 auto *D = reinterpret_cast<debug_directory *>(B + OutputSectionOff);
61 for (const std::unique_ptr<Chunk> &Record : Records) {
62 D->Characteristics = 0;
66 D->Type = COFF::IMAGE_DEBUG_TYPE_CODEVIEW;
67 D->SizeOfData = Record->getSize();
68 D->AddressOfRawData = Record->getRVA();
69 // TODO(compnerd) get the file offset
70 D->PointerToRawData = 0;
77 const std::vector<std::unique_ptr<Chunk>> &Records;
80 class CVDebugRecordChunk : public Chunk {
81 size_t getSize() const override {
82 return sizeof(codeview::DebugInfo) + Config->PDBPath.size() + 1;
85 void writeTo(uint8_t *B) const override {
86 // Save off the DebugInfo entry to backfill the file signature (build id)
87 // in Writer::writeBuildId
88 DI = reinterpret_cast<codeview::DebugInfo *>(B + OutputSectionOff);
90 DI->Signature.CVSignature = OMF::Signature::PDB70;
92 // variable sized field (PDB Path)
93 auto *P = reinterpret_cast<char *>(B + OutputSectionOff + sizeof(*DI));
94 if (!Config->PDBPath.empty())
95 memcpy(P, Config->PDBPath.data(), Config->PDBPath.size());
96 P[Config->PDBPath.size()] = '\0';
100 mutable codeview::DebugInfo *DI = nullptr;
103 // The writer writes a SymbolTable result to a file.
106 Writer(SymbolTable *T) : Symtab(T) {}
110 void createSections();
111 void createMiscChunks();
112 void createImportTables();
113 void createExportTable();
114 void assignAddresses();
115 void removeEmptySections();
116 void createSymbolAndStringTable();
117 void openFile(StringRef OutputPath);
118 template <typename PEHeaderTy> void writeHeader();
119 void fixSafeSEHSymbols();
120 void setSectionPermissions();
121 void writeSections();
122 void sortExceptionTable();
124 void applyRelocations();
126 llvm::Optional<coff_symbol16> createSymbol(Defined *D);
127 size_t addEntryToStringTable(StringRef Str);
129 OutputSection *findSection(StringRef Name);
130 OutputSection *createSection(StringRef Name);
131 void addBaserels(OutputSection *Dest);
132 void addBaserelBlocks(OutputSection *Dest, std::vector<Baserel> &V);
134 uint32_t getSizeOfInitializedData();
135 std::map<StringRef, std::vector<DefinedImportData *>> binImports();
138 std::unique_ptr<FileOutputBuffer> Buffer;
139 std::vector<OutputSection *> OutputSections;
140 std::vector<char> Strtab;
141 std::vector<llvm::object::coff_symbol16> OutputSymtab;
143 DelayLoadContents DelayIdata;
145 std::unique_ptr<SEHTableChunk> SEHTable;
147 std::unique_ptr<Chunk> DebugDirectory;
148 std::vector<std::unique_ptr<Chunk>> DebugRecords;
149 CVDebugRecordChunk *BuildId = nullptr;
150 ArrayRef<uint8_t> SectionTable;
153 uint32_t PointerToSymbolTable = 0;
154 uint64_t SizeOfImage;
155 uint64_t SizeOfHeaders;
157 std::vector<std::unique_ptr<Chunk>> Chunks;
159 } // anonymous namespace
164 void writeResult(SymbolTable *T) { Writer(T).run(); }
166 void OutputSection::setRVA(uint64_t RVA) {
167 Header.VirtualAddress = RVA;
168 for (Chunk *C : Chunks)
169 C->setRVA(C->getRVA() + RVA);
172 void OutputSection::setFileOffset(uint64_t Off) {
173 // If a section has no actual data (i.e. BSS section), we want to
174 // set 0 to its PointerToRawData. Otherwise the output is rejected
176 if (Header.SizeOfRawData == 0)
178 Header.PointerToRawData = Off;
181 void OutputSection::addChunk(Chunk *C) {
183 C->setOutputSection(this);
184 uint64_t Off = Header.VirtualSize;
185 Off = alignTo(Off, C->getAlign());
187 C->setOutputSectionOff(Off);
189 Header.VirtualSize = Off;
191 Header.SizeOfRawData = alignTo(Off, SectorSize);
194 void OutputSection::addPermissions(uint32_t C) {
195 Header.Characteristics |= C & PermMask;
198 void OutputSection::setPermissions(uint32_t C) {
199 Header.Characteristics = C & PermMask;
202 // Write the section header to a given buffer.
203 void OutputSection::writeHeaderTo(uint8_t *Buf) {
204 auto *Hdr = reinterpret_cast<coff_section *>(Buf);
206 if (StringTableOff) {
207 // If name is too long, write offset into the string table as a name.
208 sprintf(Hdr->Name, "/%d", StringTableOff);
210 assert(!Config->Debug || Name.size() <= COFF::NameSize);
211 strncpy(Hdr->Name, Name.data(),
212 std::min(Name.size(), (size_t)COFF::NameSize));
216 uint64_t Defined::getSecrel() {
217 if (auto *D = dyn_cast<DefinedRegular>(this))
218 return getRVA() - D->getChunk()->getOutputSection()->getRVA();
219 fatal("SECREL relocation points to a non-regular symbol");
222 uint64_t Defined::getSectionIndex() {
223 if (auto *D = dyn_cast<DefinedRegular>(this))
224 return D->getChunk()->getOutputSection()->SectionIndex;
225 fatal("SECTION relocation points to a non-regular symbol");
228 bool Defined::isExecutable() {
229 const auto X = IMAGE_SCN_MEM_EXECUTE;
230 if (auto *D = dyn_cast<DefinedRegular>(this))
231 return D->getChunk()->getOutputSection()->getPermissions() & X;
232 return isa<DefinedImportThunk>(this);
238 // The main function of the writer.
242 createImportTables();
244 if (Config->Relocatable)
245 createSection(".reloc");
247 removeEmptySections();
248 setSectionPermissions();
249 createSymbolAndStringTable();
250 openFile(Config->OutputFile);
251 if (Config->is64()) {
252 writeHeader<pe32plus_header>();
254 writeHeader<pe32_header>();
258 sortExceptionTable();
261 if (!Config->PDBPath.empty()) {
262 const llvm::codeview::DebugInfo *DI = nullptr;
263 if (Config->DebugTypes & static_cast<unsigned>(coff::DebugType::CV))
265 createPDB(Config->PDBPath, Symtab, SectionTable, DI);
268 writeMapFile(OutputSections);
270 if (auto EC = Buffer->commit())
271 fatal(EC, "failed to write the output file");
274 static StringRef getOutputSection(StringRef Name) {
275 StringRef S = Name.split('$').first;
276 auto It = Config->Merge.find(S);
277 if (It == Config->Merge.end())
282 // Create output section objects and add them to OutputSections.
283 void Writer::createSections() {
284 // First, bin chunks by name.
285 std::map<StringRef, std::vector<Chunk *>> Map;
286 for (Chunk *C : Symtab->getChunks()) {
287 auto *SC = dyn_cast<SectionChunk>(C);
288 if (SC && !SC->isLive()) {
290 SC->printDiscardedMessage();
293 Map[C->getSectionName()].push_back(C);
296 // Then create an OutputSection for each section.
297 // '$' and all following characters in input section names are
298 // discarded when determining output section. So, .text$foo
299 // contributes to .text, for example. See PE/COFF spec 3.2.
300 SmallDenseMap<StringRef, OutputSection *> Sections;
301 for (auto Pair : Map) {
302 StringRef Name = getOutputSection(Pair.first);
303 OutputSection *&Sec = Sections[Name];
305 Sec = make<OutputSection>(Name);
306 OutputSections.push_back(Sec);
308 std::vector<Chunk *> &Chunks = Pair.second;
309 for (Chunk *C : Chunks) {
311 Sec->addPermissions(C->getPermissions());
316 void Writer::createMiscChunks() {
317 OutputSection *RData = createSection(".rdata");
319 // Create thunks for locally-dllimported symbols.
320 if (!Symtab->LocalImportChunks.empty()) {
321 for (Chunk *C : Symtab->LocalImportChunks)
325 // Create Debug Information Chunks
327 DebugDirectory = llvm::make_unique<DebugDirectoryChunk>(DebugRecords);
329 // TODO(compnerd) create a coffgrp entry if DebugType::CV is not enabled
330 if (Config->DebugTypes & static_cast<unsigned>(coff::DebugType::CV)) {
331 auto Chunk = llvm::make_unique<CVDebugRecordChunk>();
333 BuildId = Chunk.get();
334 DebugRecords.push_back(std::move(Chunk));
337 RData->addChunk(DebugDirectory.get());
338 for (const std::unique_ptr<Chunk> &C : DebugRecords)
339 RData->addChunk(C.get());
342 // Create SEH table. x86-only.
343 if (Config->Machine != I386)
346 std::set<Defined *> Handlers;
348 for (lld::coff::ObjectFile *File : Symtab->ObjectFiles) {
349 if (!File->SEHCompat)
351 for (SymbolBody *B : File->SEHandlers)
352 Handlers.insert(cast<Defined>(B));
355 SEHTable.reset(new SEHTableChunk(Handlers));
356 RData->addChunk(SEHTable.get());
359 // Create .idata section for the DLL-imported symbol table.
360 // The format of this section is inherently Windows-specific.
361 // IdataContents class abstracted away the details for us,
362 // so we just let it create chunks and add them to the section.
363 void Writer::createImportTables() {
364 if (Symtab->ImportFiles.empty())
367 // Initialize DLLOrder so that import entries are ordered in
368 // the same order as in the command line. (That affects DLL
369 // initialization order, and this ordering is MSVC-compatible.)
370 for (ImportFile *File : Symtab->ImportFiles) {
371 std::string DLL = StringRef(File->DLLName).lower();
372 if (Config->DLLOrder.count(DLL) == 0)
373 Config->DLLOrder[DLL] = Config->DLLOrder.size();
376 OutputSection *Text = createSection(".text");
377 for (ImportFile *File : Symtab->ImportFiles) {
378 if (DefinedImportThunk *Thunk = File->ThunkSym)
379 Text->addChunk(Thunk->getChunk());
380 if (Config->DelayLoads.count(StringRef(File->DLLName).lower())) {
381 DelayIdata.add(File->ImpSym);
383 Idata.add(File->ImpSym);
386 if (!Idata.empty()) {
387 OutputSection *Sec = createSection(".idata");
388 for (Chunk *C : Idata.getChunks())
391 if (!DelayIdata.empty()) {
392 Defined *Helper = cast<Defined>(Config->DelayLoadHelper);
393 DelayIdata.create(Helper);
394 OutputSection *Sec = createSection(".didat");
395 for (Chunk *C : DelayIdata.getChunks())
397 Sec = createSection(".data");
398 for (Chunk *C : DelayIdata.getDataChunks())
400 Sec = createSection(".text");
401 for (std::unique_ptr<Chunk> &C : DelayIdata.getCodeChunks())
402 Sec->addChunk(C.get());
406 void Writer::createExportTable() {
407 if (Config->Exports.empty())
409 OutputSection *Sec = createSection(".edata");
410 for (std::unique_ptr<Chunk> &C : Edata.Chunks)
411 Sec->addChunk(C.get());
414 // The Windows loader doesn't seem to like empty sections,
415 // so we remove them if any.
416 void Writer::removeEmptySections() {
417 auto IsEmpty = [](OutputSection *S) { return S->getVirtualSize() == 0; };
418 OutputSections.erase(
419 std::remove_if(OutputSections.begin(), OutputSections.end(), IsEmpty),
420 OutputSections.end());
422 for (OutputSection *Sec : OutputSections)
423 Sec->SectionIndex = Idx++;
426 size_t Writer::addEntryToStringTable(StringRef Str) {
427 assert(Str.size() > COFF::NameSize);
428 size_t OffsetOfEntry = Strtab.size() + 4; // +4 for the size field
429 Strtab.insert(Strtab.end(), Str.begin(), Str.end());
430 Strtab.push_back('\0');
431 return OffsetOfEntry;
434 Optional<coff_symbol16> Writer::createSymbol(Defined *Def) {
435 // Relative symbols are unrepresentable in a COFF symbol table.
436 if (isa<DefinedRelative>(Def))
439 if (auto *D = dyn_cast<DefinedRegular>(Def))
440 if (!D->getChunk()->isLive())
444 StringRef Name = Def->getName();
445 if (Name.size() > COFF::NameSize) {
446 Sym.Name.Offset.Zeroes = 0;
447 Sym.Name.Offset.Offset = addEntryToStringTable(Name);
449 memset(Sym.Name.ShortName, 0, COFF::NameSize);
450 memcpy(Sym.Name.ShortName, Name.data(), Name.size());
453 if (auto *D = dyn_cast<DefinedCOFF>(Def)) {
454 COFFSymbolRef Ref = D->getCOFFSymbol();
455 Sym.Type = Ref.getType();
456 Sym.StorageClass = Ref.getStorageClass();
458 Sym.Type = IMAGE_SYM_TYPE_NULL;
459 Sym.StorageClass = IMAGE_SYM_CLASS_EXTERNAL;
461 Sym.NumberOfAuxSymbols = 0;
463 switch (Def->kind()) {
464 case SymbolBody::DefinedAbsoluteKind:
465 Sym.Value = Def->getRVA();
466 Sym.SectionNumber = IMAGE_SYM_ABSOLUTE;
469 uint64_t RVA = Def->getRVA();
470 OutputSection *Sec = nullptr;
471 for (OutputSection *S : OutputSections) {
472 if (S->getRVA() > RVA)
476 Sym.Value = RVA - Sec->getRVA();
477 Sym.SectionNumber = Sec->SectionIndex;
484 void Writer::createSymbolAndStringTable() {
485 if (!Config->Debug || !Config->WriteSymtab)
488 // Name field in the section table is 8 byte long. Longer names need
489 // to be written to the string table. First, construct string table.
490 for (OutputSection *Sec : OutputSections) {
491 StringRef Name = Sec->getName();
492 if (Name.size() <= COFF::NameSize)
494 Sec->setStringTableOff(addEntryToStringTable(Name));
497 for (lld::coff::ObjectFile *File : Symtab->ObjectFiles)
498 for (SymbolBody *B : File->getSymbols())
499 if (auto *D = dyn_cast<Defined>(B))
500 if (!D->WrittenToSymtab) {
501 D->WrittenToSymtab = true;
502 if (Optional<coff_symbol16> Sym = createSymbol(D))
503 OutputSymtab.push_back(*Sym);
506 OutputSection *LastSection = OutputSections.back();
507 // We position the symbol table to be adjacent to the end of the last section.
508 uint64_t FileOff = LastSection->getFileOff() +
509 alignTo(LastSection->getRawSize(), SectorSize);
510 if (!OutputSymtab.empty()) {
511 PointerToSymbolTable = FileOff;
512 FileOff += OutputSymtab.size() * sizeof(coff_symbol16);
515 FileOff += Strtab.size() + 4;
516 FileSize = alignTo(FileOff, SectorSize);
519 // Visits all sections to assign incremental, non-overlapping RVAs and
521 void Writer::assignAddresses() {
522 SizeOfHeaders = DOSStubSize + sizeof(PEMagic) + sizeof(coff_file_header) +
523 sizeof(data_directory) * NumberfOfDataDirectory +
524 sizeof(coff_section) * OutputSections.size();
526 Config->is64() ? sizeof(pe32plus_header) : sizeof(pe32_header);
527 SizeOfHeaders = alignTo(SizeOfHeaders, SectorSize);
528 uint64_t RVA = 0x1000; // The first page is kept unmapped.
529 FileSize = SizeOfHeaders;
530 // Move DISCARDABLE (or non-memory-mapped) sections to the end of file because
531 // the loader cannot handle holes.
532 std::stable_partition(
533 OutputSections.begin(), OutputSections.end(), [](OutputSection *S) {
534 return (S->getPermissions() & IMAGE_SCN_MEM_DISCARDABLE) == 0;
536 for (OutputSection *Sec : OutputSections) {
537 if (Sec->getName() == ".reloc")
540 Sec->setFileOffset(FileSize);
541 RVA += alignTo(Sec->getVirtualSize(), PageSize);
542 FileSize += alignTo(Sec->getRawSize(), SectorSize);
544 SizeOfImage = SizeOfHeaders + alignTo(RVA - 0x1000, PageSize);
547 template <typename PEHeaderTy> void Writer::writeHeader() {
549 uint8_t *Buf = Buffer->getBufferStart();
550 auto *DOS = reinterpret_cast<dos_header *>(Buf);
554 DOS->AddressOfRelocationTable = sizeof(dos_header);
555 DOS->AddressOfNewExeHeader = DOSStubSize;
558 memcpy(Buf, PEMagic, sizeof(PEMagic));
559 Buf += sizeof(PEMagic);
562 auto *COFF = reinterpret_cast<coff_file_header *>(Buf);
563 Buf += sizeof(*COFF);
564 COFF->Machine = Config->Machine;
565 COFF->NumberOfSections = OutputSections.size();
566 COFF->Characteristics = IMAGE_FILE_EXECUTABLE_IMAGE;
567 if (Config->LargeAddressAware)
568 COFF->Characteristics |= IMAGE_FILE_LARGE_ADDRESS_AWARE;
570 COFF->Characteristics |= IMAGE_FILE_32BIT_MACHINE;
572 COFF->Characteristics |= IMAGE_FILE_DLL;
573 if (!Config->Relocatable)
574 COFF->Characteristics |= IMAGE_FILE_RELOCS_STRIPPED;
575 COFF->SizeOfOptionalHeader =
576 sizeof(PEHeaderTy) + sizeof(data_directory) * NumberfOfDataDirectory;
579 auto *PE = reinterpret_cast<PEHeaderTy *>(Buf);
581 PE->Magic = Config->is64() ? PE32Header::PE32_PLUS : PE32Header::PE32;
582 PE->ImageBase = Config->ImageBase;
583 PE->SectionAlignment = PageSize;
584 PE->FileAlignment = SectorSize;
585 PE->MajorImageVersion = Config->MajorImageVersion;
586 PE->MinorImageVersion = Config->MinorImageVersion;
587 PE->MajorOperatingSystemVersion = Config->MajorOSVersion;
588 PE->MinorOperatingSystemVersion = Config->MinorOSVersion;
589 PE->MajorSubsystemVersion = Config->MajorOSVersion;
590 PE->MinorSubsystemVersion = Config->MinorOSVersion;
591 PE->Subsystem = Config->Subsystem;
592 PE->SizeOfImage = SizeOfImage;
593 PE->SizeOfHeaders = SizeOfHeaders;
594 if (!Config->NoEntry) {
595 Defined *Entry = cast<Defined>(Config->Entry);
596 PE->AddressOfEntryPoint = Entry->getRVA();
597 // Pointer to thumb code must have the LSB set, so adjust it.
598 if (Config->Machine == ARMNT)
599 PE->AddressOfEntryPoint |= 1;
601 PE->SizeOfStackReserve = Config->StackReserve;
602 PE->SizeOfStackCommit = Config->StackCommit;
603 PE->SizeOfHeapReserve = Config->HeapReserve;
604 PE->SizeOfHeapCommit = Config->HeapCommit;
605 if (Config->AppContainer)
606 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_APPCONTAINER;
607 if (Config->DynamicBase)
608 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE;
609 if (Config->HighEntropyVA)
610 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA;
611 if (!Config->AllowBind)
612 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_BIND;
613 if (Config->NxCompat)
614 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NX_COMPAT;
615 if (!Config->AllowIsolation)
616 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_ISOLATION;
617 if (Config->TerminalServerAware)
618 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_TERMINAL_SERVER_AWARE;
619 PE->NumberOfRvaAndSize = NumberfOfDataDirectory;
620 if (OutputSection *Text = findSection(".text")) {
621 PE->BaseOfCode = Text->getRVA();
622 PE->SizeOfCode = Text->getRawSize();
624 PE->SizeOfInitializedData = getSizeOfInitializedData();
626 // Write data directory
627 auto *Dir = reinterpret_cast<data_directory *>(Buf);
628 Buf += sizeof(*Dir) * NumberfOfDataDirectory;
629 if (OutputSection *Sec = findSection(".edata")) {
630 Dir[EXPORT_TABLE].RelativeVirtualAddress = Sec->getRVA();
631 Dir[EXPORT_TABLE].Size = Sec->getVirtualSize();
633 if (!Idata.empty()) {
634 Dir[IMPORT_TABLE].RelativeVirtualAddress = Idata.getDirRVA();
635 Dir[IMPORT_TABLE].Size = Idata.getDirSize();
636 Dir[IAT].RelativeVirtualAddress = Idata.getIATRVA();
637 Dir[IAT].Size = Idata.getIATSize();
639 if (OutputSection *Sec = findSection(".rsrc")) {
640 Dir[RESOURCE_TABLE].RelativeVirtualAddress = Sec->getRVA();
641 Dir[RESOURCE_TABLE].Size = Sec->getVirtualSize();
643 if (OutputSection *Sec = findSection(".pdata")) {
644 Dir[EXCEPTION_TABLE].RelativeVirtualAddress = Sec->getRVA();
645 Dir[EXCEPTION_TABLE].Size = Sec->getVirtualSize();
647 if (OutputSection *Sec = findSection(".reloc")) {
648 Dir[BASE_RELOCATION_TABLE].RelativeVirtualAddress = Sec->getRVA();
649 Dir[BASE_RELOCATION_TABLE].Size = Sec->getVirtualSize();
651 if (Symbol *Sym = Symtab->findUnderscore("_tls_used")) {
652 if (Defined *B = dyn_cast<Defined>(Sym->body())) {
653 Dir[TLS_TABLE].RelativeVirtualAddress = B->getRVA();
654 Dir[TLS_TABLE].Size = Config->is64()
655 ? sizeof(object::coff_tls_directory64)
656 : sizeof(object::coff_tls_directory32);
660 Dir[DEBUG_DIRECTORY].RelativeVirtualAddress = DebugDirectory->getRVA();
661 Dir[DEBUG_DIRECTORY].Size = DebugDirectory->getSize();
663 if (Symbol *Sym = Symtab->findUnderscore("_load_config_used")) {
664 if (auto *B = dyn_cast<DefinedRegular>(Sym->body())) {
665 SectionChunk *SC = B->getChunk();
666 assert(B->getRVA() >= SC->getRVA());
667 uint64_t OffsetInChunk = B->getRVA() - SC->getRVA();
668 if (!SC->hasData() || OffsetInChunk + 4 > SC->getSize())
669 fatal("_load_config_used is malformed");
671 ArrayRef<uint8_t> SecContents = SC->getContents();
672 uint32_t LoadConfigSize =
673 *reinterpret_cast<const ulittle32_t *>(&SecContents[OffsetInChunk]);
674 if (OffsetInChunk + LoadConfigSize > SC->getSize())
675 fatal("_load_config_used is too large");
676 Dir[LOAD_CONFIG_TABLE].RelativeVirtualAddress = B->getRVA();
677 Dir[LOAD_CONFIG_TABLE].Size = LoadConfigSize;
680 if (!DelayIdata.empty()) {
681 Dir[DELAY_IMPORT_DESCRIPTOR].RelativeVirtualAddress =
682 DelayIdata.getDirRVA();
683 Dir[DELAY_IMPORT_DESCRIPTOR].Size = DelayIdata.getDirSize();
686 // Write section table
687 for (OutputSection *Sec : OutputSections) {
688 Sec->writeHeaderTo(Buf);
689 Buf += sizeof(coff_section);
691 SectionTable = ArrayRef<uint8_t>(
692 Buf - OutputSections.size() * sizeof(coff_section), Buf);
694 if (OutputSymtab.empty())
697 COFF->PointerToSymbolTable = PointerToSymbolTable;
698 uint32_t NumberOfSymbols = OutputSymtab.size();
699 COFF->NumberOfSymbols = NumberOfSymbols;
700 auto *SymbolTable = reinterpret_cast<coff_symbol16 *>(
701 Buffer->getBufferStart() + COFF->PointerToSymbolTable);
702 for (size_t I = 0; I != NumberOfSymbols; ++I)
703 SymbolTable[I] = OutputSymtab[I];
704 // Create the string table, it follows immediately after the symbol table.
705 // The first 4 bytes is length including itself.
706 Buf = reinterpret_cast<uint8_t *>(&SymbolTable[NumberOfSymbols]);
707 write32le(Buf, Strtab.size() + 4);
709 memcpy(Buf + 4, Strtab.data(), Strtab.size());
712 void Writer::openFile(StringRef Path) {
714 FileOutputBuffer::create(Path, FileSize, FileOutputBuffer::F_executable),
715 "failed to open " + Path);
718 void Writer::fixSafeSEHSymbols() {
721 if (auto *T = dyn_cast<DefinedRelative>(Config->SEHTable->body()))
722 T->setRVA(SEHTable->getRVA());
723 if (auto *C = dyn_cast<DefinedAbsolute>(Config->SEHCount->body()))
724 C->setVA(SEHTable->getSize() / 4);
727 // Handles /section options to allow users to overwrite
728 // section attributes.
729 void Writer::setSectionPermissions() {
730 for (auto &P : Config->Section) {
731 StringRef Name = P.first;
732 uint32_t Perm = P.second;
733 if (auto *Sec = findSection(Name))
734 Sec->setPermissions(Perm);
738 // Write section contents to a mmap'ed file.
739 void Writer::writeSections() {
740 uint8_t *Buf = Buffer->getBufferStart();
741 for (OutputSection *Sec : OutputSections) {
742 uint8_t *SecBuf = Buf + Sec->getFileOff();
743 // Fill gaps between functions in .text with INT3 instructions
744 // instead of leaving as NUL bytes (which can be interpreted as
745 // ADD instructions).
746 if (Sec->getPermissions() & IMAGE_SCN_CNT_CODE)
747 memset(SecBuf, 0xCC, Sec->getRawSize());
748 for_each(parallel::par, Sec->getChunks().begin(), Sec->getChunks().end(),
749 [&](Chunk *C) { C->writeTo(SecBuf); });
753 // Sort .pdata section contents according to PE/COFF spec 5.5.
754 void Writer::sortExceptionTable() {
755 OutputSection *Sec = findSection(".pdata");
758 // We assume .pdata contains function table entries only.
759 uint8_t *Begin = Buffer->getBufferStart() + Sec->getFileOff();
760 uint8_t *End = Begin + Sec->getVirtualSize();
761 if (Config->Machine == AMD64) {
762 struct Entry { ulittle32_t Begin, End, Unwind; };
763 sort(parallel::par, (Entry *)Begin, (Entry *)End,
764 [](const Entry &A, const Entry &B) { return A.Begin < B.Begin; });
767 if (Config->Machine == ARMNT) {
768 struct Entry { ulittle32_t Begin, Unwind; };
769 sort(parallel::par, (Entry *)Begin, (Entry *)End,
770 [](const Entry &A, const Entry &B) { return A.Begin < B.Begin; });
773 errs() << "warning: don't know how to handle .pdata.\n";
776 // Backfill the CVSignature in a PDB70 Debug Record. This backfilling allows us
777 // to get reproducible builds.
778 void Writer::writeBuildId() {
779 // There is nothing to backfill if BuildId was not setup.
780 if (BuildId == nullptr)
786 Hash.update(ArrayRef<uint8_t>{Buffer->getBufferStart(),
787 Buffer->getBufferEnd()});
790 assert(BuildId->DI->Signature.CVSignature == OMF::Signature::PDB70 &&
791 "only PDB 7.0 is supported");
792 assert(sizeof(Res) == sizeof(BuildId->DI->PDB70.Signature) &&
793 "signature size mismatch");
794 memcpy(BuildId->DI->PDB70.Signature, Res.Bytes.data(),
795 sizeof(codeview::PDB70DebugInfo::Signature));
796 // TODO(compnerd) track the Age
797 BuildId->DI->PDB70.Age = 1;
800 OutputSection *Writer::findSection(StringRef Name) {
801 for (OutputSection *Sec : OutputSections)
802 if (Sec->getName() == Name)
807 uint32_t Writer::getSizeOfInitializedData() {
809 for (OutputSection *S : OutputSections)
810 if (S->getPermissions() & IMAGE_SCN_CNT_INITIALIZED_DATA)
811 Res += S->getRawSize();
815 // Returns an existing section or create a new one if not found.
816 OutputSection *Writer::createSection(StringRef Name) {
817 if (auto *Sec = findSection(Name))
819 const auto DATA = IMAGE_SCN_CNT_INITIALIZED_DATA;
820 const auto BSS = IMAGE_SCN_CNT_UNINITIALIZED_DATA;
821 const auto CODE = IMAGE_SCN_CNT_CODE;
822 const auto DISCARDABLE = IMAGE_SCN_MEM_DISCARDABLE;
823 const auto R = IMAGE_SCN_MEM_READ;
824 const auto W = IMAGE_SCN_MEM_WRITE;
825 const auto X = IMAGE_SCN_MEM_EXECUTE;
826 uint32_t Perms = StringSwitch<uint32_t>(Name)
827 .Case(".bss", BSS | R | W)
828 .Case(".data", DATA | R | W)
829 .Cases(".didat", ".edata", ".idata", ".rdata", DATA | R)
830 .Case(".reloc", DATA | DISCARDABLE | R)
831 .Case(".text", CODE | R | X)
834 llvm_unreachable("unknown section name");
835 auto Sec = make<OutputSection>(Name);
836 Sec->addPermissions(Perms);
837 OutputSections.push_back(Sec);
841 // Dest is .reloc section. Add contents to that section.
842 void Writer::addBaserels(OutputSection *Dest) {
843 std::vector<Baserel> V;
844 for (OutputSection *Sec : OutputSections) {
847 // Collect all locations for base relocations.
848 for (Chunk *C : Sec->getChunks())
850 // Add the addresses to .reloc section.
852 addBaserelBlocks(Dest, V);
857 // Add addresses to .reloc section. Note that addresses are grouped by page.
858 void Writer::addBaserelBlocks(OutputSection *Dest, std::vector<Baserel> &V) {
859 const uint32_t Mask = ~uint32_t(PageSize - 1);
860 uint32_t Page = V[0].RVA & Mask;
862 for (size_t E = V.size(); J < E; ++J) {
863 uint32_t P = V[J].RVA & Mask;
866 Dest->addChunk(make<BaserelChunk>(Page, &V[I], &V[0] + J));
872 Dest->addChunk(make<BaserelChunk>(Page, &V[I], &V[0] + J));