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();
123 void applyRelocations();
125 llvm::Optional<coff_symbol16> createSymbol(Defined *D);
126 size_t addEntryToStringTable(StringRef Str);
128 OutputSection *findSection(StringRef Name);
129 OutputSection *createSection(StringRef Name);
130 void addBaserels(OutputSection *Dest);
131 void addBaserelBlocks(OutputSection *Dest, std::vector<Baserel> &V);
133 uint32_t getSizeOfInitializedData();
134 std::map<StringRef, std::vector<DefinedImportData *>> binImports();
137 std::unique_ptr<FileOutputBuffer> Buffer;
138 std::vector<OutputSection *> OutputSections;
139 std::vector<char> Strtab;
140 std::vector<llvm::object::coff_symbol16> OutputSymtab;
142 DelayLoadContents DelayIdata;
144 SEHTableChunk *SEHTable = nullptr;
146 Chunk *DebugDirectory = nullptr;
147 std::vector<Chunk *> DebugRecords;
148 CVDebugRecordChunk *BuildId = nullptr;
149 ArrayRef<uint8_t> SectionTable;
152 uint32_t PointerToSymbolTable = 0;
153 uint64_t SizeOfImage;
154 uint64_t SizeOfHeaders;
156 } // anonymous namespace
161 void writeResult(SymbolTable *T) { Writer(T).run(); }
163 void OutputSection::setRVA(uint64_t RVA) {
164 Header.VirtualAddress = RVA;
165 for (Chunk *C : Chunks)
166 C->setRVA(C->getRVA() + RVA);
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
173 if (Header.SizeOfRawData == 0)
175 Header.PointerToRawData = Off;
178 void OutputSection::addChunk(Chunk *C) {
180 C->setOutputSection(this);
181 uint64_t Off = Header.VirtualSize;
182 Off = alignTo(Off, C->getAlign());
184 C->setOutputSectionOff(Off);
186 Header.VirtualSize = Off;
188 Header.SizeOfRawData = alignTo(Off, SectorSize);
191 void OutputSection::addPermissions(uint32_t C) {
192 Header.Characteristics |= C & PermMask;
195 void OutputSection::setPermissions(uint32_t C) {
196 Header.Characteristics = C & PermMask;
199 // Write the section header to a given buffer.
200 void OutputSection::writeHeaderTo(uint8_t *Buf) {
201 auto *Hdr = reinterpret_cast<coff_section *>(Buf);
203 if (StringTableOff) {
204 // If name is too long, write offset into the string table as a name.
205 sprintf(Hdr->Name, "/%d", StringTableOff);
207 assert(!Config->Debug || Name.size() <= COFF::NameSize);
208 strncpy(Hdr->Name, Name.data(),
209 std::min(Name.size(), (size_t)COFF::NameSize));
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");
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");
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);
235 // The main function of the writer.
239 createImportTables();
241 if (Config->Relocatable)
242 createSection(".reloc");
244 removeEmptySections();
245 setSectionPermissions();
246 createSymbolAndStringTable();
247 openFile(Config->OutputFile);
248 if (Config->is64()) {
249 writeHeader<pe32plus_header>();
251 writeHeader<pe32_header>();
255 sortExceptionTable();
258 if (!Config->PDBPath.empty() && Config->Debug) {
259 const llvm::codeview::DebugInfo *DI = nullptr;
260 if (Config->DebugTypes & static_cast<unsigned>(coff::DebugType::CV))
262 createPDB(Config->PDBPath, Symtab, SectionTable, DI);
265 writeMapFile(OutputSections);
267 if (auto EC = Buffer->commit())
268 fatal(EC, "failed to write the output file");
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())
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()) {
287 SC->printDiscardedMessage();
290 Map[C->getSectionName()].push_back(C);
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];
302 Sec = make<OutputSection>(Name);
303 OutputSections.push_back(Sec);
305 std::vector<Chunk *> &Chunks = Pair.second;
306 for (Chunk *C : Chunks) {
308 Sec->addPermissions(C->getPermissions());
313 void Writer::createMiscChunks() {
314 OutputSection *RData = createSection(".rdata");
316 // Create thunks for locally-dllimported symbols.
317 if (!Symtab->LocalImportChunks.empty()) {
318 for (Chunk *C : Symtab->LocalImportChunks)
322 // Create Debug Information Chunks
324 DebugDirectory = make<DebugDirectoryChunk>(DebugRecords);
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>();
331 DebugRecords.push_back(Chunk);
334 RData->addChunk(DebugDirectory);
335 for (Chunk *C : DebugRecords)
339 // Create SEH table. x86-only.
340 if (Config->Machine != I386)
343 std::set<Defined *> Handlers;
345 for (lld::coff::ObjectFile *File : Symtab->ObjectFiles) {
346 if (!File->SEHCompat)
348 for (SymbolBody *B : File->SEHandlers)
349 Handlers.insert(cast<Defined>(B));
352 SEHTable = make<SEHTableChunk>(Handlers);
353 RData->addChunk(SEHTable);
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())
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 std::string DLL = StringRef(File->DLLName).lower();
369 if (Config->DLLOrder.count(DLL) == 0)
370 Config->DLLOrder[DLL] = Config->DLLOrder.size();
373 OutputSection *Text = createSection(".text");
374 for (ImportFile *File : Symtab->ImportFiles) {
375 if (DefinedImportThunk *Thunk = File->ThunkSym)
376 Text->addChunk(Thunk->getChunk());
377 if (Config->DelayLoads.count(StringRef(File->DLLName).lower())) {
378 DelayIdata.add(File->ImpSym);
380 Idata.add(File->ImpSym);
383 if (!Idata.empty()) {
384 OutputSection *Sec = createSection(".idata");
385 for (Chunk *C : Idata.getChunks())
388 if (!DelayIdata.empty()) {
389 Defined *Helper = cast<Defined>(Config->DelayLoadHelper);
390 DelayIdata.create(Helper);
391 OutputSection *Sec = createSection(".didat");
392 for (Chunk *C : DelayIdata.getChunks())
394 Sec = createSection(".data");
395 for (Chunk *C : DelayIdata.getDataChunks())
397 Sec = createSection(".text");
398 for (Chunk *C : DelayIdata.getCodeChunks())
403 void Writer::createExportTable() {
404 if (Config->Exports.empty())
406 OutputSection *Sec = createSection(".edata");
407 for (Chunk *C : Edata.Chunks)
411 // The Windows loader doesn't seem to like empty sections,
412 // so we remove them if any.
413 void Writer::removeEmptySections() {
414 auto IsEmpty = [](OutputSection *S) { return S->getVirtualSize() == 0; };
415 OutputSections.erase(
416 std::remove_if(OutputSections.begin(), OutputSections.end(), IsEmpty),
417 OutputSections.end());
419 for (OutputSection *Sec : OutputSections)
420 Sec->SectionIndex = Idx++;
423 size_t Writer::addEntryToStringTable(StringRef Str) {
424 assert(Str.size() > COFF::NameSize);
425 size_t OffsetOfEntry = Strtab.size() + 4; // +4 for the size field
426 Strtab.insert(Strtab.end(), Str.begin(), Str.end());
427 Strtab.push_back('\0');
428 return OffsetOfEntry;
431 Optional<coff_symbol16> Writer::createSymbol(Defined *Def) {
432 // Relative symbols are unrepresentable in a COFF symbol table.
433 if (isa<DefinedRelative>(Def))
436 if (auto *D = dyn_cast<DefinedRegular>(Def))
437 if (!D->getChunk()->isLive())
441 StringRef Name = Def->getName();
442 if (Name.size() > COFF::NameSize) {
443 Sym.Name.Offset.Zeroes = 0;
444 Sym.Name.Offset.Offset = addEntryToStringTable(Name);
446 memset(Sym.Name.ShortName, 0, COFF::NameSize);
447 memcpy(Sym.Name.ShortName, Name.data(), Name.size());
450 if (auto *D = dyn_cast<DefinedCOFF>(Def)) {
451 COFFSymbolRef Ref = D->getCOFFSymbol();
452 Sym.Type = Ref.getType();
453 Sym.StorageClass = Ref.getStorageClass();
455 Sym.Type = IMAGE_SYM_TYPE_NULL;
456 Sym.StorageClass = IMAGE_SYM_CLASS_EXTERNAL;
458 Sym.NumberOfAuxSymbols = 0;
460 switch (Def->kind()) {
461 case SymbolBody::DefinedAbsoluteKind:
462 Sym.Value = Def->getRVA();
463 Sym.SectionNumber = IMAGE_SYM_ABSOLUTE;
466 uint64_t RVA = Def->getRVA();
467 OutputSection *Sec = nullptr;
468 for (OutputSection *S : OutputSections) {
469 if (S->getRVA() > RVA)
473 Sym.Value = RVA - Sec->getRVA();
474 Sym.SectionNumber = Sec->SectionIndex;
481 void Writer::createSymbolAndStringTable() {
482 if (!Config->Debug || !Config->WriteSymtab)
485 // Name field in the section table is 8 byte long. Longer names need
486 // to be written to the string table. First, construct string table.
487 for (OutputSection *Sec : OutputSections) {
488 StringRef Name = Sec->getName();
489 if (Name.size() <= COFF::NameSize)
491 Sec->setStringTableOff(addEntryToStringTable(Name));
494 for (lld::coff::ObjectFile *File : Symtab->ObjectFiles)
495 for (SymbolBody *B : File->getSymbols())
496 if (auto *D = dyn_cast<Defined>(B))
497 if (!D->WrittenToSymtab) {
498 D->WrittenToSymtab = true;
499 if (Optional<coff_symbol16> Sym = createSymbol(D))
500 OutputSymtab.push_back(*Sym);
503 OutputSection *LastSection = OutputSections.back();
504 // We position the symbol table to be adjacent to the end of the last section.
505 uint64_t FileOff = LastSection->getFileOff() +
506 alignTo(LastSection->getRawSize(), SectorSize);
507 if (!OutputSymtab.empty()) {
508 PointerToSymbolTable = FileOff;
509 FileOff += OutputSymtab.size() * sizeof(coff_symbol16);
512 FileOff += Strtab.size() + 4;
513 FileSize = alignTo(FileOff, SectorSize);
516 // Visits all sections to assign incremental, non-overlapping RVAs and
518 void Writer::assignAddresses() {
519 SizeOfHeaders = DOSStubSize + sizeof(PEMagic) + sizeof(coff_file_header) +
520 sizeof(data_directory) * NumberfOfDataDirectory +
521 sizeof(coff_section) * OutputSections.size();
523 Config->is64() ? sizeof(pe32plus_header) : sizeof(pe32_header);
524 SizeOfHeaders = alignTo(SizeOfHeaders, SectorSize);
525 uint64_t RVA = 0x1000; // The first page is kept unmapped.
526 FileSize = SizeOfHeaders;
527 // Move DISCARDABLE (or non-memory-mapped) sections to the end of file because
528 // the loader cannot handle holes.
529 std::stable_partition(
530 OutputSections.begin(), OutputSections.end(), [](OutputSection *S) {
531 return (S->getPermissions() & IMAGE_SCN_MEM_DISCARDABLE) == 0;
533 for (OutputSection *Sec : OutputSections) {
534 if (Sec->getName() == ".reloc")
537 Sec->setFileOffset(FileSize);
538 RVA += alignTo(Sec->getVirtualSize(), PageSize);
539 FileSize += alignTo(Sec->getRawSize(), SectorSize);
541 SizeOfImage = SizeOfHeaders + alignTo(RVA - 0x1000, PageSize);
544 template <typename PEHeaderTy> void Writer::writeHeader() {
546 uint8_t *Buf = Buffer->getBufferStart();
547 auto *DOS = reinterpret_cast<dos_header *>(Buf);
551 DOS->AddressOfRelocationTable = sizeof(dos_header);
552 DOS->AddressOfNewExeHeader = DOSStubSize;
555 memcpy(Buf, PEMagic, sizeof(PEMagic));
556 Buf += sizeof(PEMagic);
559 auto *COFF = reinterpret_cast<coff_file_header *>(Buf);
560 Buf += sizeof(*COFF);
561 COFF->Machine = Config->Machine;
562 COFF->NumberOfSections = OutputSections.size();
563 COFF->Characteristics = IMAGE_FILE_EXECUTABLE_IMAGE;
564 if (Config->LargeAddressAware)
565 COFF->Characteristics |= IMAGE_FILE_LARGE_ADDRESS_AWARE;
567 COFF->Characteristics |= IMAGE_FILE_32BIT_MACHINE;
569 COFF->Characteristics |= IMAGE_FILE_DLL;
570 if (!Config->Relocatable)
571 COFF->Characteristics |= IMAGE_FILE_RELOCS_STRIPPED;
572 COFF->SizeOfOptionalHeader =
573 sizeof(PEHeaderTy) + sizeof(data_directory) * NumberfOfDataDirectory;
576 auto *PE = reinterpret_cast<PEHeaderTy *>(Buf);
578 PE->Magic = Config->is64() ? PE32Header::PE32_PLUS : PE32Header::PE32;
579 PE->ImageBase = Config->ImageBase;
580 PE->SectionAlignment = PageSize;
581 PE->FileAlignment = SectorSize;
582 PE->MajorImageVersion = Config->MajorImageVersion;
583 PE->MinorImageVersion = Config->MinorImageVersion;
584 PE->MajorOperatingSystemVersion = Config->MajorOSVersion;
585 PE->MinorOperatingSystemVersion = Config->MinorOSVersion;
586 PE->MajorSubsystemVersion = Config->MajorOSVersion;
587 PE->MinorSubsystemVersion = Config->MinorOSVersion;
588 PE->Subsystem = Config->Subsystem;
589 PE->SizeOfImage = SizeOfImage;
590 PE->SizeOfHeaders = SizeOfHeaders;
591 if (!Config->NoEntry) {
592 Defined *Entry = cast<Defined>(Config->Entry);
593 PE->AddressOfEntryPoint = Entry->getRVA();
594 // Pointer to thumb code must have the LSB set, so adjust it.
595 if (Config->Machine == ARMNT)
596 PE->AddressOfEntryPoint |= 1;
598 PE->SizeOfStackReserve = Config->StackReserve;
599 PE->SizeOfStackCommit = Config->StackCommit;
600 PE->SizeOfHeapReserve = Config->HeapReserve;
601 PE->SizeOfHeapCommit = Config->HeapCommit;
603 // Import Descriptor Tables and Import Address Tables are merged
604 // in our output. That's not compatible with the Binding feature
605 // that is sort of prelinking. Setting this flag to make it clear
606 // that our outputs are not for the Binding.
607 PE->DLLCharacteristics = IMAGE_DLL_CHARACTERISTICS_NO_BIND;
609 if (Config->AppContainer)
610 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_APPCONTAINER;
611 if (Config->DynamicBase)
612 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE;
613 if (Config->HighEntropyVA)
614 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA;
615 if (Config->NxCompat)
616 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NX_COMPAT;
617 if (!Config->AllowIsolation)
618 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_ISOLATION;
619 if (Config->TerminalServerAware)
620 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_TERMINAL_SERVER_AWARE;
621 PE->NumberOfRvaAndSize = NumberfOfDataDirectory;
622 if (OutputSection *Text = findSection(".text")) {
623 PE->BaseOfCode = Text->getRVA();
624 PE->SizeOfCode = Text->getRawSize();
626 PE->SizeOfInitializedData = getSizeOfInitializedData();
628 // Write data directory
629 auto *Dir = reinterpret_cast<data_directory *>(Buf);
630 Buf += sizeof(*Dir) * NumberfOfDataDirectory;
631 if (OutputSection *Sec = findSection(".edata")) {
632 Dir[EXPORT_TABLE].RelativeVirtualAddress = Sec->getRVA();
633 Dir[EXPORT_TABLE].Size = Sec->getVirtualSize();
635 if (!Idata.empty()) {
636 Dir[IMPORT_TABLE].RelativeVirtualAddress = Idata.getDirRVA();
637 Dir[IMPORT_TABLE].Size = Idata.getDirSize();
638 Dir[IAT].RelativeVirtualAddress = Idata.getIATRVA();
639 Dir[IAT].Size = Idata.getIATSize();
641 if (OutputSection *Sec = findSection(".rsrc")) {
642 Dir[RESOURCE_TABLE].RelativeVirtualAddress = Sec->getRVA();
643 Dir[RESOURCE_TABLE].Size = Sec->getVirtualSize();
645 if (OutputSection *Sec = findSection(".pdata")) {
646 Dir[EXCEPTION_TABLE].RelativeVirtualAddress = Sec->getRVA();
647 Dir[EXCEPTION_TABLE].Size = Sec->getVirtualSize();
649 if (OutputSection *Sec = findSection(".reloc")) {
650 Dir[BASE_RELOCATION_TABLE].RelativeVirtualAddress = Sec->getRVA();
651 Dir[BASE_RELOCATION_TABLE].Size = Sec->getVirtualSize();
653 if (Symbol *Sym = Symtab->findUnderscore("_tls_used")) {
654 if (Defined *B = dyn_cast<Defined>(Sym->body())) {
655 Dir[TLS_TABLE].RelativeVirtualAddress = B->getRVA();
656 Dir[TLS_TABLE].Size = Config->is64()
657 ? sizeof(object::coff_tls_directory64)
658 : sizeof(object::coff_tls_directory32);
662 Dir[DEBUG_DIRECTORY].RelativeVirtualAddress = DebugDirectory->getRVA();
663 Dir[DEBUG_DIRECTORY].Size = DebugDirectory->getSize();
665 if (Symbol *Sym = Symtab->findUnderscore("_load_config_used")) {
666 if (auto *B = dyn_cast<DefinedRegular>(Sym->body())) {
667 SectionChunk *SC = B->getChunk();
668 assert(B->getRVA() >= SC->getRVA());
669 uint64_t OffsetInChunk = B->getRVA() - SC->getRVA();
670 if (!SC->hasData() || OffsetInChunk + 4 > SC->getSize())
671 fatal("_load_config_used is malformed");
673 ArrayRef<uint8_t> SecContents = SC->getContents();
674 uint32_t LoadConfigSize =
675 *reinterpret_cast<const ulittle32_t *>(&SecContents[OffsetInChunk]);
676 if (OffsetInChunk + LoadConfigSize > SC->getSize())
677 fatal("_load_config_used is too large");
678 Dir[LOAD_CONFIG_TABLE].RelativeVirtualAddress = B->getRVA();
679 Dir[LOAD_CONFIG_TABLE].Size = LoadConfigSize;
682 if (!DelayIdata.empty()) {
683 Dir[DELAY_IMPORT_DESCRIPTOR].RelativeVirtualAddress =
684 DelayIdata.getDirRVA();
685 Dir[DELAY_IMPORT_DESCRIPTOR].Size = DelayIdata.getDirSize();
688 // Write section table
689 for (OutputSection *Sec : OutputSections) {
690 Sec->writeHeaderTo(Buf);
691 Buf += sizeof(coff_section);
693 SectionTable = ArrayRef<uint8_t>(
694 Buf - OutputSections.size() * sizeof(coff_section), Buf);
696 if (OutputSymtab.empty())
699 COFF->PointerToSymbolTable = PointerToSymbolTable;
700 uint32_t NumberOfSymbols = OutputSymtab.size();
701 COFF->NumberOfSymbols = NumberOfSymbols;
702 auto *SymbolTable = reinterpret_cast<coff_symbol16 *>(
703 Buffer->getBufferStart() + COFF->PointerToSymbolTable);
704 for (size_t I = 0; I != NumberOfSymbols; ++I)
705 SymbolTable[I] = OutputSymtab[I];
706 // Create the string table, it follows immediately after the symbol table.
707 // The first 4 bytes is length including itself.
708 Buf = reinterpret_cast<uint8_t *>(&SymbolTable[NumberOfSymbols]);
709 write32le(Buf, Strtab.size() + 4);
711 memcpy(Buf + 4, Strtab.data(), Strtab.size());
714 void Writer::openFile(StringRef Path) {
716 FileOutputBuffer::create(Path, FileSize, FileOutputBuffer::F_executable),
717 "failed to open " + Path);
720 void Writer::fixSafeSEHSymbols() {
723 if (auto *T = dyn_cast<DefinedRelative>(Config->SEHTable->body()))
724 T->setRVA(SEHTable->getRVA());
725 if (auto *C = dyn_cast<DefinedAbsolute>(Config->SEHCount->body()))
726 C->setVA(SEHTable->getSize() / 4);
729 // Handles /section options to allow users to overwrite
730 // section attributes.
731 void Writer::setSectionPermissions() {
732 for (auto &P : Config->Section) {
733 StringRef Name = P.first;
734 uint32_t Perm = P.second;
735 if (auto *Sec = findSection(Name))
736 Sec->setPermissions(Perm);
740 // Write section contents to a mmap'ed file.
741 void Writer::writeSections() {
742 uint8_t *Buf = Buffer->getBufferStart();
743 for (OutputSection *Sec : OutputSections) {
744 uint8_t *SecBuf = Buf + Sec->getFileOff();
745 // Fill gaps between functions in .text with INT3 instructions
746 // instead of leaving as NUL bytes (which can be interpreted as
747 // ADD instructions).
748 if (Sec->getPermissions() & IMAGE_SCN_CNT_CODE)
749 memset(SecBuf, 0xCC, Sec->getRawSize());
750 for_each(parallel::par, Sec->getChunks().begin(), Sec->getChunks().end(),
751 [&](Chunk *C) { C->writeTo(SecBuf); });
755 // Sort .pdata section contents according to PE/COFF spec 5.5.
756 void Writer::sortExceptionTable() {
757 OutputSection *Sec = findSection(".pdata");
760 // We assume .pdata contains function table entries only.
761 uint8_t *Begin = Buffer->getBufferStart() + Sec->getFileOff();
762 uint8_t *End = Begin + Sec->getVirtualSize();
763 if (Config->Machine == AMD64) {
764 struct Entry { ulittle32_t Begin, End, Unwind; };
765 sort(parallel::par, (Entry *)Begin, (Entry *)End,
766 [](const Entry &A, const Entry &B) { return A.Begin < B.Begin; });
769 if (Config->Machine == ARMNT) {
770 struct Entry { ulittle32_t Begin, Unwind; };
771 sort(parallel::par, (Entry *)Begin, (Entry *)End,
772 [](const Entry &A, const Entry &B) { return A.Begin < B.Begin; });
775 errs() << "warning: don't know how to handle .pdata.\n";
778 // Backfill the CVSignature in a PDB70 Debug Record. This backfilling allows us
779 // to get reproducible builds.
780 void Writer::writeBuildId() {
781 // There is nothing to backfill if BuildId was not setup.
782 if (BuildId == nullptr)
788 Hash.update(ArrayRef<uint8_t>{Buffer->getBufferStart(),
789 Buffer->getBufferEnd()});
792 assert(BuildId->DI->Signature.CVSignature == OMF::Signature::PDB70 &&
793 "only PDB 7.0 is supported");
794 assert(sizeof(Res) == sizeof(BuildId->DI->PDB70.Signature) &&
795 "signature size mismatch");
796 memcpy(BuildId->DI->PDB70.Signature, Res.Bytes.data(),
797 sizeof(codeview::PDB70DebugInfo::Signature));
798 // TODO(compnerd) track the Age
799 BuildId->DI->PDB70.Age = 1;
802 OutputSection *Writer::findSection(StringRef Name) {
803 for (OutputSection *Sec : OutputSections)
804 if (Sec->getName() == Name)
809 uint32_t Writer::getSizeOfInitializedData() {
811 for (OutputSection *S : OutputSections)
812 if (S->getPermissions() & IMAGE_SCN_CNT_INITIALIZED_DATA)
813 Res += S->getRawSize();
817 // Returns an existing section or create a new one if not found.
818 OutputSection *Writer::createSection(StringRef Name) {
819 if (auto *Sec = findSection(Name))
821 const auto DATA = IMAGE_SCN_CNT_INITIALIZED_DATA;
822 const auto BSS = IMAGE_SCN_CNT_UNINITIALIZED_DATA;
823 const auto CODE = IMAGE_SCN_CNT_CODE;
824 const auto DISCARDABLE = IMAGE_SCN_MEM_DISCARDABLE;
825 const auto R = IMAGE_SCN_MEM_READ;
826 const auto W = IMAGE_SCN_MEM_WRITE;
827 const auto X = IMAGE_SCN_MEM_EXECUTE;
828 uint32_t Perms = StringSwitch<uint32_t>(Name)
829 .Case(".bss", BSS | R | W)
830 .Case(".data", DATA | R | W)
831 .Cases(".didat", ".edata", ".idata", ".rdata", DATA | R)
832 .Case(".reloc", DATA | DISCARDABLE | R)
833 .Case(".text", CODE | R | X)
836 llvm_unreachable("unknown section name");
837 auto Sec = make<OutputSection>(Name);
838 Sec->addPermissions(Perms);
839 OutputSections.push_back(Sec);
843 // Dest is .reloc section. Add contents to that section.
844 void Writer::addBaserels(OutputSection *Dest) {
845 std::vector<Baserel> V;
846 for (OutputSection *Sec : OutputSections) {
849 // Collect all locations for base relocations.
850 for (Chunk *C : Sec->getChunks())
852 // Add the addresses to .reloc section.
854 addBaserelBlocks(Dest, V);
859 // Add addresses to .reloc section. Note that addresses are grouped by page.
860 void Writer::addBaserelBlocks(OutputSection *Dest, std::vector<Baserel> &V) {
861 const uint32_t Mask = ~uint32_t(PageSize - 1);
862 uint32_t Page = V[0].RVA & Mask;
864 for (size_t E = V.size(); J < E; ++J) {
865 uint32_t P = V[J].RVA & Mask;
868 Dest->addChunk(make<BaserelChunk>(Page, &V[I], &V[0] + J));
874 Dest->addChunk(make<BaserelChunk>(Page, &V[I], &V[0] + J));