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) {
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) {
381 if (DefinedImportThunk *Thunk = File->ThunkSym)
382 Text->addChunk(Thunk->getChunk());
384 if (Config->DelayLoads.count(StringRef(File->DLLName).lower())) {
386 fatal("cannot delay-load " + toString(File) +
387 " due to import of data: " + toString(*File->ImpSym));
388 DelayIdata.add(File->ImpSym);
390 Idata.add(File->ImpSym);
394 if (!Idata.empty()) {
395 OutputSection *Sec = createSection(".idata");
396 for (Chunk *C : Idata.getChunks())
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())
406 Sec = createSection(".data");
407 for (Chunk *C : DelayIdata.getDataChunks())
409 Sec = createSection(".text");
410 for (Chunk *C : DelayIdata.getCodeChunks())
415 void Writer::createExportTable() {
416 if (Config->Exports.empty())
418 OutputSection *Sec = createSection(".edata");
419 for (Chunk *C : Edata.Chunks)
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());
431 for (OutputSection *Sec : OutputSections)
432 Sec->SectionIndex = Idx++;
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;
443 Optional<coff_symbol16> Writer::createSymbol(Defined *Def) {
444 // Relative symbols are unrepresentable in a COFF symbol table.
445 if (isa<DefinedRelative>(Def))
448 if (auto *D = dyn_cast<DefinedRegular>(Def))
449 if (!D->getChunk()->isLive())
452 if (auto *Sym = dyn_cast<DefinedImportData>(Def))
453 if (!Sym->File->Live)
456 if (auto *Sym = dyn_cast<DefinedImportThunk>(Def))
457 if (!Sym->WrappedSym->File->Live)
461 StringRef Name = Def->getName();
462 if (Name.size() > COFF::NameSize) {
463 Sym.Name.Offset.Zeroes = 0;
464 Sym.Name.Offset.Offset = addEntryToStringTable(Name);
466 memset(Sym.Name.ShortName, 0, COFF::NameSize);
467 memcpy(Sym.Name.ShortName, Name.data(), Name.size());
470 if (auto *D = dyn_cast<DefinedCOFF>(Def)) {
471 COFFSymbolRef Ref = D->getCOFFSymbol();
472 Sym.Type = Ref.getType();
473 Sym.StorageClass = Ref.getStorageClass();
475 Sym.Type = IMAGE_SYM_TYPE_NULL;
476 Sym.StorageClass = IMAGE_SYM_CLASS_EXTERNAL;
478 Sym.NumberOfAuxSymbols = 0;
480 switch (Def->kind()) {
481 case SymbolBody::DefinedAbsoluteKind:
482 Sym.Value = Def->getRVA();
483 Sym.SectionNumber = IMAGE_SYM_ABSOLUTE;
486 uint64_t RVA = Def->getRVA();
487 OutputSection *Sec = nullptr;
488 for (OutputSection *S : OutputSections) {
489 if (S->getRVA() > RVA)
493 Sym.Value = RVA - Sec->getRVA();
494 Sym.SectionNumber = Sec->SectionIndex;
501 void Writer::createSymbolAndStringTable() {
502 if (!Config->Debug || !Config->WriteSymtab)
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)
511 Sec->setStringTableOff(addEntryToStringTable(Name));
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)
519 D->WrittenToSymtab = true;
521 if (Optional<coff_symbol16> Sym = createSymbol(D))
522 OutputSymtab.push_back(*Sym);
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);
535 FileOff += Strtab.size() + 4;
536 FileSize = alignTo(FileOff, SectorSize);
539 // Visits all sections to assign incremental, non-overlapping RVAs and
541 void Writer::assignAddresses() {
542 SizeOfHeaders = DOSStubSize + sizeof(PEMagic) + sizeof(coff_file_header) +
543 sizeof(data_directory) * NumberfOfDataDirectory +
544 sizeof(coff_section) * OutputSections.size();
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;
556 for (OutputSection *Sec : OutputSections) {
557 if (Sec->getName() == ".reloc")
560 Sec->setFileOffset(FileSize);
561 RVA += alignTo(Sec->getVirtualSize(), PageSize);
562 FileSize += alignTo(Sec->getRawSize(), SectorSize);
564 SizeOfImage = SizeOfHeaders + alignTo(RVA - 0x1000, PageSize);
567 template <typename PEHeaderTy> void Writer::writeHeader() {
569 uint8_t *Buf = Buffer->getBufferStart();
570 auto *DOS = reinterpret_cast<dos_header *>(Buf);
574 DOS->AddressOfRelocationTable = sizeof(dos_header);
575 DOS->AddressOfNewExeHeader = DOSStubSize;
578 memcpy(Buf, PEMagic, sizeof(PEMagic));
579 Buf += sizeof(PEMagic);
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;
590 COFF->Characteristics |= IMAGE_FILE_32BIT_MACHINE;
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;
599 auto *PE = reinterpret_cast<PEHeaderTy *>(Buf);
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;
621 PE->SizeOfStackReserve = Config->StackReserve;
622 PE->SizeOfStackCommit = Config->StackCommit;
623 PE->SizeOfHeapReserve = Config->HeapReserve;
624 PE->SizeOfHeapCommit = Config->HeapCommit;
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;
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();
649 PE->SizeOfInitializedData = getSizeOfInitializedData();
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();
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();
664 if (OutputSection *Sec = findSection(".rsrc")) {
665 Dir[RESOURCE_TABLE].RelativeVirtualAddress = Sec->getRVA();
666 Dir[RESOURCE_TABLE].Size = Sec->getVirtualSize();
668 if (OutputSection *Sec = findSection(".pdata")) {
669 Dir[EXCEPTION_TABLE].RelativeVirtualAddress = Sec->getRVA();
670 Dir[EXCEPTION_TABLE].Size = Sec->getVirtualSize();
672 if (OutputSection *Sec = findSection(".reloc")) {
673 Dir[BASE_RELOCATION_TABLE].RelativeVirtualAddress = Sec->getRVA();
674 Dir[BASE_RELOCATION_TABLE].Size = Sec->getVirtualSize();
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);
685 Dir[DEBUG_DIRECTORY].RelativeVirtualAddress = DebugDirectory->getRVA();
686 Dir[DEBUG_DIRECTORY].Size = DebugDirectory->getSize();
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");
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;
705 if (!DelayIdata.empty()) {
706 Dir[DELAY_IMPORT_DESCRIPTOR].RelativeVirtualAddress =
707 DelayIdata.getDirRVA();
708 Dir[DELAY_IMPORT_DESCRIPTOR].Size = DelayIdata.getDirSize();
711 // Write section table
712 for (OutputSection *Sec : OutputSections) {
713 Sec->writeHeaderTo(Buf);
714 Buf += sizeof(coff_section);
716 SectionTable = ArrayRef<uint8_t>(
717 Buf - OutputSections.size() * sizeof(coff_section), Buf);
719 if (OutputSymtab.empty())
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);
734 memcpy(Buf + 4, Strtab.data(), Strtab.size());
737 void Writer::openFile(StringRef Path) {
739 FileOutputBuffer::create(Path, FileSize, FileOutputBuffer::F_executable),
740 "failed to open " + Path);
743 void Writer::fixSafeSEHSymbols() {
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);
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);
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); });
778 // Sort .pdata section contents according to PE/COFF spec 5.5.
779 void Writer::sortExceptionTable() {
780 OutputSection *Sec = findSection(".pdata");
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; });
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; });
798 errs() << "warning: don't know how to handle .pdata.\n";
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)
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");
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);
817 // TODO(compnerd) track the Age
818 BuildId->DI->PDB70.Age = 1;
821 OutputSection *Writer::findSection(StringRef Name) {
822 for (OutputSection *Sec : OutputSections)
823 if (Sec->getName() == Name)
828 uint32_t Writer::getSizeOfInitializedData() {
830 for (OutputSection *S : OutputSections)
831 if (S->getPermissions() & IMAGE_SCN_CNT_INITIALIZED_DATA)
832 Res += S->getRawSize();
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))
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)
855 llvm_unreachable("unknown section name");
856 auto Sec = make<OutputSection>(Name);
857 Sec->addPermissions(Perms);
858 OutputSections.push_back(Sec);
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) {
868 // Collect all locations for base relocations.
869 for (Chunk *C : Sec->getChunks())
871 // Add the addresses to .reloc section.
873 addBaserelBlocks(Dest, V);
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;
883 for (size_t E = V.size(); J < E; ++J) {
884 uint32_t P = V[J].RVA & Mask;
887 Dest->addChunk(make<BaserelChunk>(Page, &V[I], &V[0] + J));
893 Dest->addChunk(make<BaserelChunk>(Page, &V[I], &V[0] + J));