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"
17 #include "SymbolTable.h"
19 #include "lld/Core/Parallel.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/RandomNumberGenerator.h"
27 #include "llvm/Support/raw_ostream.h"
35 using namespace llvm::COFF;
36 using namespace llvm::object;
37 using namespace llvm::support;
38 using namespace llvm::support::endian;
40 using namespace lld::coff;
42 static const int PageSize = 4096;
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 // OutputSection represents a section in an output file. It's a
167 // container of chunks. OutputSection and Chunk are 1:N relationship.
168 // Chunks cannot belong to more than one OutputSections. The writer
169 // creates multiple OutputSections and assign them unique,
170 // non-overlapping file offsets and RVAs.
171 class OutputSection {
173 OutputSection(StringRef N) : Name(N), Header({}) {}
174 void setRVA(uint64_t);
175 void setFileOffset(uint64_t);
176 void addChunk(Chunk *C);
177 StringRef getName() { return Name; }
178 std::vector<Chunk *> &getChunks() { return Chunks; }
179 void addPermissions(uint32_t C);
180 void setPermissions(uint32_t C);
181 uint32_t getPermissions() { return Header.Characteristics & PermMask; }
182 uint32_t getCharacteristics() { return Header.Characteristics; }
183 uint64_t getRVA() { return Header.VirtualAddress; }
184 uint64_t getFileOff() { return Header.PointerToRawData; }
185 void writeHeaderTo(uint8_t *Buf);
187 // Returns the size of this section in an executable memory image.
188 // This may be smaller than the raw size (the raw size is multiple
189 // of disk sector size, so there may be padding at end), or may be
190 // larger (if that's the case, the loader reserves spaces after end
192 uint64_t getVirtualSize() { return Header.VirtualSize; }
194 // Returns the size of the section in the output file.
195 uint64_t getRawSize() { return Header.SizeOfRawData; }
197 // Set offset into the string table storing this section name.
198 // Used only when the name is longer than 8 bytes.
199 void setStringTableOff(uint32_t V) { StringTableOff = V; }
201 // N.B. The section index is one based.
202 uint32_t SectionIndex = 0;
207 uint32_t StringTableOff = 0;
208 std::vector<Chunk *> Chunks;
211 void OutputSection::setRVA(uint64_t RVA) {
212 Header.VirtualAddress = RVA;
213 for (Chunk *C : Chunks)
214 C->setRVA(C->getRVA() + RVA);
217 void OutputSection::setFileOffset(uint64_t Off) {
218 // If a section has no actual data (i.e. BSS section), we want to
219 // set 0 to its PointerToRawData. Otherwise the output is rejected
221 if (Header.SizeOfRawData == 0)
223 Header.PointerToRawData = Off;
226 void OutputSection::addChunk(Chunk *C) {
228 C->setOutputSection(this);
229 uint64_t Off = Header.VirtualSize;
230 Off = alignTo(Off, C->getAlign());
232 C->setOutputSectionOff(Off);
234 Header.VirtualSize = Off;
236 Header.SizeOfRawData = alignTo(Off, SectorSize);
239 void OutputSection::addPermissions(uint32_t C) {
240 Header.Characteristics |= C & PermMask;
243 void OutputSection::setPermissions(uint32_t C) {
244 Header.Characteristics = C & PermMask;
247 // Write the section header to a given buffer.
248 void OutputSection::writeHeaderTo(uint8_t *Buf) {
249 auto *Hdr = reinterpret_cast<coff_section *>(Buf);
251 if (StringTableOff) {
252 // If name is too long, write offset into the string table as a name.
253 sprintf(Hdr->Name, "/%d", StringTableOff);
255 assert(!Config->Debug || Name.size() <= COFF::NameSize);
256 strncpy(Hdr->Name, Name.data(),
257 std::min(Name.size(), (size_t)COFF::NameSize));
261 uint64_t Defined::getSecrel() {
262 if (auto *D = dyn_cast<DefinedRegular>(this))
263 return getRVA() - D->getChunk()->getOutputSection()->getRVA();
264 fatal("SECREL relocation points to a non-regular symbol");
267 uint64_t Defined::getSectionIndex() {
268 if (auto *D = dyn_cast<DefinedRegular>(this))
269 return D->getChunk()->getOutputSection()->SectionIndex;
270 fatal("SECTION relocation points to a non-regular symbol");
273 bool Defined::isExecutable() {
274 const auto X = IMAGE_SCN_MEM_EXECUTE;
275 if (auto *D = dyn_cast<DefinedRegular>(this))
276 return D->getChunk()->getOutputSection()->getPermissions() & X;
277 return isa<DefinedImportThunk>(this);
283 // The main function of the writer.
287 createImportTables();
289 if (Config->Relocatable)
290 createSection(".reloc");
292 removeEmptySections();
293 setSectionPermissions();
294 createSymbolAndStringTable();
295 openFile(Config->OutputFile);
296 if (Config->is64()) {
297 writeHeader<pe32plus_header>();
299 writeHeader<pe32_header>();
303 sortExceptionTable();
306 if (!Config->PDBPath.empty())
307 createPDB(Config->PDBPath, Symtab, SectionTable, BuildId->DI);
309 if (auto EC = Buffer->commit())
310 fatal(EC, "failed to write the output file");
313 static StringRef getOutputSection(StringRef Name) {
314 StringRef S = Name.split('$').first;
315 auto It = Config->Merge.find(S);
316 if (It == Config->Merge.end())
321 // Create output section objects and add them to OutputSections.
322 void Writer::createSections() {
323 // First, bin chunks by name.
324 std::map<StringRef, std::vector<Chunk *>> Map;
325 for (Chunk *C : Symtab->getChunks()) {
326 auto *SC = dyn_cast<SectionChunk>(C);
327 if (SC && !SC->isLive()) {
329 SC->printDiscardedMessage();
332 Map[C->getSectionName()].push_back(C);
335 // Then create an OutputSection for each section.
336 // '$' and all following characters in input section names are
337 // discarded when determining output section. So, .text$foo
338 // contributes to .text, for example. See PE/COFF spec 3.2.
339 SmallDenseMap<StringRef, OutputSection *> Sections;
340 for (auto Pair : Map) {
341 StringRef Name = getOutputSection(Pair.first);
342 OutputSection *&Sec = Sections[Name];
344 Sec = make<OutputSection>(Name);
345 OutputSections.push_back(Sec);
347 std::vector<Chunk *> &Chunks = Pair.second;
348 for (Chunk *C : Chunks) {
350 Sec->addPermissions(C->getPermissions());
355 void Writer::createMiscChunks() {
356 OutputSection *RData = createSection(".rdata");
358 // Create thunks for locally-dllimported symbols.
359 if (!Symtab->LocalImportChunks.empty()) {
360 for (Chunk *C : Symtab->LocalImportChunks)
364 // Create Debug Information Chunks
366 DebugDirectory = llvm::make_unique<DebugDirectoryChunk>(DebugRecords);
368 // TODO(compnerd) create a coffgrp entry if DebugType::CV is not enabled
369 if (Config->DebugTypes & static_cast<unsigned>(coff::DebugType::CV)) {
370 auto Chunk = llvm::make_unique<CVDebugRecordChunk>();
372 BuildId = Chunk.get();
373 DebugRecords.push_back(std::move(Chunk));
376 RData->addChunk(DebugDirectory.get());
377 for (const std::unique_ptr<Chunk> &C : DebugRecords)
378 RData->addChunk(C.get());
381 // Create SEH table. x86-only.
382 if (Config->Machine != I386)
385 std::set<Defined *> Handlers;
387 for (lld::coff::ObjectFile *File : Symtab->ObjectFiles) {
388 if (!File->SEHCompat)
390 for (SymbolBody *B : File->SEHandlers)
391 Handlers.insert(cast<Defined>(B));
394 SEHTable.reset(new SEHTableChunk(Handlers));
395 RData->addChunk(SEHTable.get());
398 // Create .idata section for the DLL-imported symbol table.
399 // The format of this section is inherently Windows-specific.
400 // IdataContents class abstracted away the details for us,
401 // so we just let it create chunks and add them to the section.
402 void Writer::createImportTables() {
403 if (Symtab->ImportFiles.empty())
406 // Initialize DLLOrder so that import entries are ordered in
407 // the same order as in the command line. (That affects DLL
408 // initialization order, and this ordering is MSVC-compatible.)
409 for (ImportFile *File : Symtab->ImportFiles) {
410 std::string DLL = StringRef(File->DLLName).lower();
411 if (Config->DLLOrder.count(DLL) == 0)
412 Config->DLLOrder[DLL] = Config->DLLOrder.size();
415 OutputSection *Text = createSection(".text");
416 for (ImportFile *File : Symtab->ImportFiles) {
417 if (DefinedImportThunk *Thunk = File->ThunkSym)
418 Text->addChunk(Thunk->getChunk());
419 if (Config->DelayLoads.count(StringRef(File->DLLName).lower())) {
420 DelayIdata.add(File->ImpSym);
422 Idata.add(File->ImpSym);
425 if (!Idata.empty()) {
426 OutputSection *Sec = createSection(".idata");
427 for (Chunk *C : Idata.getChunks())
430 if (!DelayIdata.empty()) {
431 Defined *Helper = cast<Defined>(Config->DelayLoadHelper);
432 DelayIdata.create(Helper);
433 OutputSection *Sec = createSection(".didat");
434 for (Chunk *C : DelayIdata.getChunks())
436 Sec = createSection(".data");
437 for (Chunk *C : DelayIdata.getDataChunks())
439 Sec = createSection(".text");
440 for (std::unique_ptr<Chunk> &C : DelayIdata.getCodeChunks())
441 Sec->addChunk(C.get());
445 void Writer::createExportTable() {
446 if (Config->Exports.empty())
448 OutputSection *Sec = createSection(".edata");
449 for (std::unique_ptr<Chunk> &C : Edata.Chunks)
450 Sec->addChunk(C.get());
453 // The Windows loader doesn't seem to like empty sections,
454 // so we remove them if any.
455 void Writer::removeEmptySections() {
456 auto IsEmpty = [](OutputSection *S) { return S->getVirtualSize() == 0; };
457 OutputSections.erase(
458 std::remove_if(OutputSections.begin(), OutputSections.end(), IsEmpty),
459 OutputSections.end());
461 for (OutputSection *Sec : OutputSections)
462 Sec->SectionIndex = Idx++;
465 size_t Writer::addEntryToStringTable(StringRef Str) {
466 assert(Str.size() > COFF::NameSize);
467 size_t OffsetOfEntry = Strtab.size() + 4; // +4 for the size field
468 Strtab.insert(Strtab.end(), Str.begin(), Str.end());
469 Strtab.push_back('\0');
470 return OffsetOfEntry;
473 Optional<coff_symbol16> Writer::createSymbol(Defined *Def) {
474 // Relative symbols are unrepresentable in a COFF symbol table.
475 if (isa<DefinedRelative>(Def))
478 if (auto *D = dyn_cast<DefinedRegular>(Def))
479 if (!D->getChunk()->isLive())
483 StringRef Name = Def->getName();
484 if (Name.size() > COFF::NameSize) {
485 Sym.Name.Offset.Zeroes = 0;
486 Sym.Name.Offset.Offset = addEntryToStringTable(Name);
488 memset(Sym.Name.ShortName, 0, COFF::NameSize);
489 memcpy(Sym.Name.ShortName, Name.data(), Name.size());
492 if (auto *D = dyn_cast<DefinedCOFF>(Def)) {
493 COFFSymbolRef Ref = D->getCOFFSymbol();
494 Sym.Type = Ref.getType();
495 Sym.StorageClass = Ref.getStorageClass();
497 Sym.Type = IMAGE_SYM_TYPE_NULL;
498 Sym.StorageClass = IMAGE_SYM_CLASS_EXTERNAL;
500 Sym.NumberOfAuxSymbols = 0;
502 switch (Def->kind()) {
503 case SymbolBody::DefinedAbsoluteKind:
504 Sym.Value = Def->getRVA();
505 Sym.SectionNumber = IMAGE_SYM_ABSOLUTE;
508 uint64_t RVA = Def->getRVA();
509 OutputSection *Sec = nullptr;
510 for (OutputSection *S : OutputSections) {
511 if (S->getRVA() > RVA)
515 Sym.Value = RVA - Sec->getRVA();
516 Sym.SectionNumber = Sec->SectionIndex;
523 void Writer::createSymbolAndStringTable() {
524 if (!Config->Debug || !Config->WriteSymtab)
527 // Name field in the section table is 8 byte long. Longer names need
528 // to be written to the string table. First, construct string table.
529 for (OutputSection *Sec : OutputSections) {
530 StringRef Name = Sec->getName();
531 if (Name.size() <= COFF::NameSize)
533 Sec->setStringTableOff(addEntryToStringTable(Name));
536 for (lld::coff::ObjectFile *File : Symtab->ObjectFiles)
537 for (SymbolBody *B : File->getSymbols())
538 if (auto *D = dyn_cast<Defined>(B))
539 if (!D->WrittenToSymtab) {
540 D->WrittenToSymtab = true;
541 if (Optional<coff_symbol16> Sym = createSymbol(D))
542 OutputSymtab.push_back(*Sym);
545 OutputSection *LastSection = OutputSections.back();
546 // We position the symbol table to be adjacent to the end of the last section.
547 uint64_t FileOff = LastSection->getFileOff() +
548 alignTo(LastSection->getRawSize(), SectorSize);
549 if (!OutputSymtab.empty()) {
550 PointerToSymbolTable = FileOff;
551 FileOff += OutputSymtab.size() * sizeof(coff_symbol16);
554 FileOff += Strtab.size() + 4;
555 FileSize = alignTo(FileOff, SectorSize);
558 // Visits all sections to assign incremental, non-overlapping RVAs and
560 void Writer::assignAddresses() {
561 SizeOfHeaders = DOSStubSize + sizeof(PEMagic) + sizeof(coff_file_header) +
562 sizeof(data_directory) * NumberfOfDataDirectory +
563 sizeof(coff_section) * OutputSections.size();
565 Config->is64() ? sizeof(pe32plus_header) : sizeof(pe32_header);
566 SizeOfHeaders = alignTo(SizeOfHeaders, SectorSize);
567 uint64_t RVA = 0x1000; // The first page is kept unmapped.
568 FileSize = SizeOfHeaders;
569 // Move DISCARDABLE (or non-memory-mapped) sections to the end of file because
570 // the loader cannot handle holes.
571 std::stable_partition(
572 OutputSections.begin(), OutputSections.end(), [](OutputSection *S) {
573 return (S->getPermissions() & IMAGE_SCN_MEM_DISCARDABLE) == 0;
575 for (OutputSection *Sec : OutputSections) {
576 if (Sec->getName() == ".reloc")
579 Sec->setFileOffset(FileSize);
580 RVA += alignTo(Sec->getVirtualSize(), PageSize);
581 FileSize += alignTo(Sec->getRawSize(), SectorSize);
583 SizeOfImage = SizeOfHeaders + alignTo(RVA - 0x1000, PageSize);
586 template <typename PEHeaderTy> void Writer::writeHeader() {
588 uint8_t *Buf = Buffer->getBufferStart();
589 auto *DOS = reinterpret_cast<dos_header *>(Buf);
593 DOS->AddressOfRelocationTable = sizeof(dos_header);
594 DOS->AddressOfNewExeHeader = DOSStubSize;
597 memcpy(Buf, PEMagic, sizeof(PEMagic));
598 Buf += sizeof(PEMagic);
601 auto *COFF = reinterpret_cast<coff_file_header *>(Buf);
602 Buf += sizeof(*COFF);
603 COFF->Machine = Config->Machine;
604 COFF->NumberOfSections = OutputSections.size();
605 COFF->Characteristics = IMAGE_FILE_EXECUTABLE_IMAGE;
606 if (Config->LargeAddressAware)
607 COFF->Characteristics |= IMAGE_FILE_LARGE_ADDRESS_AWARE;
609 COFF->Characteristics |= IMAGE_FILE_32BIT_MACHINE;
611 COFF->Characteristics |= IMAGE_FILE_DLL;
612 if (!Config->Relocatable)
613 COFF->Characteristics |= IMAGE_FILE_RELOCS_STRIPPED;
614 COFF->SizeOfOptionalHeader =
615 sizeof(PEHeaderTy) + sizeof(data_directory) * NumberfOfDataDirectory;
618 auto *PE = reinterpret_cast<PEHeaderTy *>(Buf);
620 PE->Magic = Config->is64() ? PE32Header::PE32_PLUS : PE32Header::PE32;
621 PE->ImageBase = Config->ImageBase;
622 PE->SectionAlignment = PageSize;
623 PE->FileAlignment = SectorSize;
624 PE->MajorImageVersion = Config->MajorImageVersion;
625 PE->MinorImageVersion = Config->MinorImageVersion;
626 PE->MajorOperatingSystemVersion = Config->MajorOSVersion;
627 PE->MinorOperatingSystemVersion = Config->MinorOSVersion;
628 PE->MajorSubsystemVersion = Config->MajorOSVersion;
629 PE->MinorSubsystemVersion = Config->MinorOSVersion;
630 PE->Subsystem = Config->Subsystem;
631 PE->SizeOfImage = SizeOfImage;
632 PE->SizeOfHeaders = SizeOfHeaders;
633 if (!Config->NoEntry) {
634 Defined *Entry = cast<Defined>(Config->Entry);
635 PE->AddressOfEntryPoint = Entry->getRVA();
636 // Pointer to thumb code must have the LSB set, so adjust it.
637 if (Config->Machine == ARMNT)
638 PE->AddressOfEntryPoint |= 1;
640 PE->SizeOfStackReserve = Config->StackReserve;
641 PE->SizeOfStackCommit = Config->StackCommit;
642 PE->SizeOfHeapReserve = Config->HeapReserve;
643 PE->SizeOfHeapCommit = Config->HeapCommit;
644 if (Config->DynamicBase)
645 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE;
646 if (Config->HighEntropyVA)
647 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA;
648 if (!Config->AllowBind)
649 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_BIND;
650 if (Config->NxCompat)
651 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NX_COMPAT;
652 if (!Config->AllowIsolation)
653 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_ISOLATION;
654 if (Config->TerminalServerAware)
655 PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_TERMINAL_SERVER_AWARE;
656 PE->NumberOfRvaAndSize = NumberfOfDataDirectory;
657 if (OutputSection *Text = findSection(".text")) {
658 PE->BaseOfCode = Text->getRVA();
659 PE->SizeOfCode = Text->getRawSize();
661 PE->SizeOfInitializedData = getSizeOfInitializedData();
663 // Write data directory
664 auto *Dir = reinterpret_cast<data_directory *>(Buf);
665 Buf += sizeof(*Dir) * NumberfOfDataDirectory;
666 if (OutputSection *Sec = findSection(".edata")) {
667 Dir[EXPORT_TABLE].RelativeVirtualAddress = Sec->getRVA();
668 Dir[EXPORT_TABLE].Size = Sec->getVirtualSize();
670 if (!Idata.empty()) {
671 Dir[IMPORT_TABLE].RelativeVirtualAddress = Idata.getDirRVA();
672 Dir[IMPORT_TABLE].Size = Idata.getDirSize();
673 Dir[IAT].RelativeVirtualAddress = Idata.getIATRVA();
674 Dir[IAT].Size = Idata.getIATSize();
676 if (OutputSection *Sec = findSection(".rsrc")) {
677 Dir[RESOURCE_TABLE].RelativeVirtualAddress = Sec->getRVA();
678 Dir[RESOURCE_TABLE].Size = Sec->getVirtualSize();
680 if (OutputSection *Sec = findSection(".pdata")) {
681 Dir[EXCEPTION_TABLE].RelativeVirtualAddress = Sec->getRVA();
682 Dir[EXCEPTION_TABLE].Size = Sec->getVirtualSize();
684 if (OutputSection *Sec = findSection(".reloc")) {
685 Dir[BASE_RELOCATION_TABLE].RelativeVirtualAddress = Sec->getRVA();
686 Dir[BASE_RELOCATION_TABLE].Size = Sec->getVirtualSize();
688 if (Symbol *Sym = Symtab->findUnderscore("_tls_used")) {
689 if (Defined *B = dyn_cast<Defined>(Sym->body())) {
690 Dir[TLS_TABLE].RelativeVirtualAddress = B->getRVA();
691 Dir[TLS_TABLE].Size = Config->is64()
692 ? sizeof(object::coff_tls_directory64)
693 : sizeof(object::coff_tls_directory32);
697 Dir[DEBUG_DIRECTORY].RelativeVirtualAddress = DebugDirectory->getRVA();
698 Dir[DEBUG_DIRECTORY].Size = DebugDirectory->getSize();
700 if (Symbol *Sym = Symtab->findUnderscore("_load_config_used")) {
701 if (auto *B = dyn_cast<DefinedRegular>(Sym->body())) {
702 SectionChunk *SC = B->getChunk();
703 assert(B->getRVA() >= SC->getRVA());
704 uint64_t OffsetInChunk = B->getRVA() - SC->getRVA();
705 if (!SC->hasData() || OffsetInChunk + 4 > SC->getSize())
706 fatal("_load_config_used is malformed");
708 ArrayRef<uint8_t> SecContents = SC->getContents();
709 uint32_t LoadConfigSize =
710 *reinterpret_cast<const ulittle32_t *>(&SecContents[OffsetInChunk]);
711 if (OffsetInChunk + LoadConfigSize > SC->getSize())
712 fatal("_load_config_used is too large");
713 Dir[LOAD_CONFIG_TABLE].RelativeVirtualAddress = B->getRVA();
714 Dir[LOAD_CONFIG_TABLE].Size = LoadConfigSize;
717 if (!DelayIdata.empty()) {
718 Dir[DELAY_IMPORT_DESCRIPTOR].RelativeVirtualAddress =
719 DelayIdata.getDirRVA();
720 Dir[DELAY_IMPORT_DESCRIPTOR].Size = DelayIdata.getDirSize();
723 // Write section table
724 for (OutputSection *Sec : OutputSections) {
725 Sec->writeHeaderTo(Buf);
726 Buf += sizeof(coff_section);
728 SectionTable = ArrayRef<uint8_t>(
729 Buf - OutputSections.size() * sizeof(coff_section), Buf);
731 if (OutputSymtab.empty())
734 COFF->PointerToSymbolTable = PointerToSymbolTable;
735 uint32_t NumberOfSymbols = OutputSymtab.size();
736 COFF->NumberOfSymbols = NumberOfSymbols;
737 auto *SymbolTable = reinterpret_cast<coff_symbol16 *>(
738 Buffer->getBufferStart() + COFF->PointerToSymbolTable);
739 for (size_t I = 0; I != NumberOfSymbols; ++I)
740 SymbolTable[I] = OutputSymtab[I];
741 // Create the string table, it follows immediately after the symbol table.
742 // The first 4 bytes is length including itself.
743 Buf = reinterpret_cast<uint8_t *>(&SymbolTable[NumberOfSymbols]);
744 write32le(Buf, Strtab.size() + 4);
746 memcpy(Buf + 4, Strtab.data(), Strtab.size());
749 void Writer::openFile(StringRef Path) {
751 FileOutputBuffer::create(Path, FileSize, FileOutputBuffer::F_executable),
752 "failed to open " + Path);
755 void Writer::fixSafeSEHSymbols() {
758 if (auto *T = dyn_cast<DefinedRelative>(Config->SEHTable->body()))
759 T->setRVA(SEHTable->getRVA());
760 if (auto *C = dyn_cast<DefinedAbsolute>(Config->SEHCount->body()))
761 C->setVA(SEHTable->getSize() / 4);
764 // Handles /section options to allow users to overwrite
765 // section attributes.
766 void Writer::setSectionPermissions() {
767 for (auto &P : Config->Section) {
768 StringRef Name = P.first;
769 uint32_t Perm = P.second;
770 if (auto *Sec = findSection(Name))
771 Sec->setPermissions(Perm);
775 // Write section contents to a mmap'ed file.
776 void Writer::writeSections() {
777 uint8_t *Buf = Buffer->getBufferStart();
778 for (OutputSection *Sec : OutputSections) {
779 uint8_t *SecBuf = Buf + Sec->getFileOff();
780 // Fill gaps between functions in .text with INT3 instructions
781 // instead of leaving as NUL bytes (which can be interpreted as
782 // ADD instructions).
783 if (Sec->getPermissions() & IMAGE_SCN_CNT_CODE)
784 memset(SecBuf, 0xCC, Sec->getRawSize());
785 parallel_for_each(Sec->getChunks().begin(), Sec->getChunks().end(),
786 [&](Chunk *C) { C->writeTo(SecBuf); });
790 // Sort .pdata section contents according to PE/COFF spec 5.5.
791 void Writer::sortExceptionTable() {
792 OutputSection *Sec = findSection(".pdata");
795 // We assume .pdata contains function table entries only.
796 uint8_t *Begin = Buffer->getBufferStart() + Sec->getFileOff();
797 uint8_t *End = Begin + Sec->getVirtualSize();
798 if (Config->Machine == AMD64) {
799 struct Entry { ulittle32_t Begin, End, Unwind; };
801 (Entry *)Begin, (Entry *)End,
802 [](const Entry &A, const Entry &B) { return A.Begin < B.Begin; });
805 if (Config->Machine == ARMNT) {
806 struct Entry { ulittle32_t Begin, Unwind; };
808 (Entry *)Begin, (Entry *)End,
809 [](const Entry &A, const Entry &B) { return A.Begin < B.Begin; });
812 errs() << "warning: don't know how to handle .pdata.\n";
815 // Backfill the CVSignature in a PDB70 Debug Record. This backfilling allows us
816 // to get reproducible builds.
817 void Writer::writeBuildId() {
818 // There is nothing to backfill if BuildId was not setup.
819 if (BuildId == nullptr)
825 Hash.update(ArrayRef<uint8_t>{Buffer->getBufferStart(),
826 Buffer->getBufferEnd()});
829 assert(BuildId->DI->Signature.CVSignature == OMF::Signature::PDB70 &&
830 "only PDB 7.0 is supported");
831 assert(sizeof(Res) == sizeof(BuildId->DI->PDB70.Signature) &&
832 "signature size mismatch");
833 memcpy(BuildId->DI->PDB70.Signature, Res,
834 sizeof(codeview::PDB70DebugInfo::Signature));
835 // TODO(compnerd) track the Age
836 BuildId->DI->PDB70.Age = 1;
839 OutputSection *Writer::findSection(StringRef Name) {
840 for (OutputSection *Sec : OutputSections)
841 if (Sec->getName() == Name)
846 uint32_t Writer::getSizeOfInitializedData() {
848 for (OutputSection *S : OutputSections)
849 if (S->getPermissions() & IMAGE_SCN_CNT_INITIALIZED_DATA)
850 Res += S->getRawSize();
854 // Returns an existing section or create a new one if not found.
855 OutputSection *Writer::createSection(StringRef Name) {
856 if (auto *Sec = findSection(Name))
858 const auto DATA = IMAGE_SCN_CNT_INITIALIZED_DATA;
859 const auto BSS = IMAGE_SCN_CNT_UNINITIALIZED_DATA;
860 const auto CODE = IMAGE_SCN_CNT_CODE;
861 const auto DISCARDABLE = IMAGE_SCN_MEM_DISCARDABLE;
862 const auto R = IMAGE_SCN_MEM_READ;
863 const auto W = IMAGE_SCN_MEM_WRITE;
864 const auto X = IMAGE_SCN_MEM_EXECUTE;
865 uint32_t Perms = StringSwitch<uint32_t>(Name)
866 .Case(".bss", BSS | R | W)
867 .Case(".data", DATA | R | W)
868 .Cases(".didat", ".edata", ".idata", ".rdata", DATA | R)
869 .Case(".reloc", DATA | DISCARDABLE | R)
870 .Case(".text", CODE | R | X)
873 llvm_unreachable("unknown section name");
874 auto Sec = make<OutputSection>(Name);
875 Sec->addPermissions(Perms);
876 OutputSections.push_back(Sec);
880 // Dest is .reloc section. Add contents to that section.
881 void Writer::addBaserels(OutputSection *Dest) {
882 std::vector<Baserel> V;
883 for (OutputSection *Sec : OutputSections) {
886 // Collect all locations for base relocations.
887 for (Chunk *C : Sec->getChunks())
889 // Add the addresses to .reloc section.
891 addBaserelBlocks(Dest, V);
896 // Add addresses to .reloc section. Note that addresses are grouped by page.
897 void Writer::addBaserelBlocks(OutputSection *Dest, std::vector<Baserel> &V) {
898 const uint32_t Mask = ~uint32_t(PageSize - 1);
899 uint32_t Page = V[0].RVA & Mask;
901 for (size_t E = V.size(); J < E; ++J) {
902 uint32_t P = V[J].RVA & Mask;
905 Dest->addChunk(make<BaserelChunk>(Page, &V[I], &V[0] + J));
911 Dest->addChunk(make<BaserelChunk>(Page, &V[I], &V[0] + J));