xref: /llvm-project-15.0.7/lld/COFF/Writer.cpp (revision ec315f10)
1 //===- Writer.cpp ---------------------------------------------------------===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "Config.h"
11 #include "DLL.h"
12 #include "Error.h"
13 #include "InputFiles.h"
14 #include "SymbolTable.h"
15 #include "Symbols.h"
16 #include "Writer.h"
17 #include "lld/Core/Parallel.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/StringSwitch.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/Endian.h"
23 #include "llvm/Support/FileOutputBuffer.h"
24 #include "llvm/Support/RandomNumberGenerator.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include <algorithm>
27 #include <cstdio>
28 #include <map>
29 #include <memory>
30 #include <utility>
31 
32 using namespace llvm;
33 using namespace llvm::COFF;
34 using namespace llvm::object;
35 using namespace llvm::support;
36 using namespace llvm::support::endian;
37 using namespace lld;
38 using namespace lld::coff;
39 
40 static const int PageSize = 4096;
41 static const int SectorSize = 512;
42 static const int DOSStubSize = 64;
43 static const int NumberfOfDataDirectory = 16;
44 
45 namespace {
46 
47 class DebugDirectoryChunk : public Chunk {
48 public:
49   DebugDirectoryChunk(const std::vector<std::unique_ptr<Chunk>> &R)
50       : Records(R) {}
51 
52   size_t getSize() const override {
53     return Records.size() * sizeof(debug_directory);
54   }
55 
56   void writeTo(uint8_t *B) const override {
57     auto *D = reinterpret_cast<debug_directory *>(B + OutputSectionOff);
58 
59     for (const std::unique_ptr<Chunk> &Record : Records) {
60       D->Characteristics = 0;
61       D->TimeDateStamp = 0;
62       D->MajorVersion = 0;
63       D->MinorVersion = 0;
64       D->Type = COFF::IMAGE_DEBUG_TYPE_CODEVIEW;
65       D->SizeOfData = Record->getSize();
66       D->AddressOfRawData = Record->getRVA();
67       // TODO(compnerd) get the file offset
68       D->PointerToRawData = 0;
69 
70       ++D;
71     }
72   }
73 
74 private:
75   const std::vector<std::unique_ptr<Chunk>> &Records;
76 };
77 
78 class CVDebugRecordChunk : public Chunk {
79   size_t getSize() const override {
80     return sizeof(codeview::DebugInfo) + Config->PDBPath.size() + 1;
81   }
82 
83   void writeTo(uint8_t *B) const override {
84     // Save off the DebugInfo entry to backfill the file signature (build id)
85     // in Writer::writeBuildId
86     DI = reinterpret_cast<codeview::DebugInfo *>(B + OutputSectionOff);
87 
88     DI->Signature.CVSignature = OMF::Signature::PDB70;
89 
90     // variable sized field (PDB Path)
91     auto *P = reinterpret_cast<char *>(B + OutputSectionOff + sizeof(*DI));
92     if (!Config->PDBPath.empty())
93       memcpy(P, Config->PDBPath.data(), Config->PDBPath.size());
94     P[Config->PDBPath.size()] = '\0';
95   }
96 
97 public:
98   mutable codeview::DebugInfo *DI = nullptr;
99 };
100 
101 // The writer writes a SymbolTable result to a file.
102 class Writer {
103 public:
104   Writer(SymbolTable *T) : Symtab(T) {}
105   void run();
106 
107 private:
108   void createSections();
109   void createMiscChunks();
110   void createImportTables();
111   void createExportTable();
112   void assignAddresses();
113   void removeEmptySections();
114   void createSymbolAndStringTable();
115   void openFile(StringRef OutputPath);
116   template <typename PEHeaderTy> void writeHeader();
117   void fixSafeSEHSymbols();
118   void setSectionPermissions();
119   void writeSections();
120   void sortExceptionTable();
121   void writeBuildId();
122   void applyRelocations();
123 
124   llvm::Optional<coff_symbol16> createSymbol(Defined *D);
125   size_t addEntryToStringTable(StringRef Str);
126 
127   OutputSection *findSection(StringRef Name);
128   OutputSection *createSection(StringRef Name);
129   void addBaserels(OutputSection *Dest);
130   void addBaserelBlocks(OutputSection *Dest, std::vector<Baserel> &V);
131 
132   uint32_t getSizeOfInitializedData();
133   std::map<StringRef, std::vector<DefinedImportData *>> binImports();
134 
135   SymbolTable *Symtab;
136   std::unique_ptr<llvm::FileOutputBuffer> Buffer;
137   llvm::SpecificBumpPtrAllocator<OutputSection> CAlloc;
138   llvm::SpecificBumpPtrAllocator<BaserelChunk> BAlloc;
139   std::vector<OutputSection *> OutputSections;
140   std::vector<char> Strtab;
141   std::vector<llvm::object::coff_symbol16> OutputSymtab;
142   IdataContents Idata;
143   DelayLoadContents DelayIdata;
144   EdataContents Edata;
145   std::unique_ptr<SEHTableChunk> SEHTable;
146 
147   std::unique_ptr<Chunk> DebugDirectory;
148   std::vector<std::unique_ptr<Chunk>> DebugRecords;
149   CVDebugRecordChunk *BuildId = nullptr;
150 
151   uint64_t FileSize;
152   uint32_t PointerToSymbolTable = 0;
153   uint64_t SizeOfImage;
154   uint64_t SizeOfHeaders;
155 
156   std::vector<std::unique_ptr<Chunk>> Chunks;
157 };
158 } // anonymous namespace
159 
160 namespace lld {
161 namespace coff {
162 
163 void writeResult(SymbolTable *T) { Writer(T).run(); }
164 
165 // OutputSection represents a section in an output file. It's a
166 // container of chunks. OutputSection and Chunk are 1:N relationship.
167 // Chunks cannot belong to more than one OutputSections. The writer
168 // creates multiple OutputSections and assign them unique,
169 // non-overlapping file offsets and RVAs.
170 class OutputSection {
171 public:
172   OutputSection(StringRef N) : Name(N), Header({}) {}
173   void setRVA(uint64_t);
174   void setFileOffset(uint64_t);
175   void addChunk(Chunk *C);
176   StringRef getName() { return Name; }
177   std::vector<Chunk *> &getChunks() { return Chunks; }
178   void addPermissions(uint32_t C);
179   void setPermissions(uint32_t C);
180   uint32_t getPermissions() { return Header.Characteristics & PermMask; }
181   uint32_t getCharacteristics() { return Header.Characteristics; }
182   uint64_t getRVA() { return Header.VirtualAddress; }
183   uint64_t getFileOff() { return Header.PointerToRawData; }
184   void writeHeaderTo(uint8_t *Buf);
185 
186   // Returns the size of this section in an executable memory image.
187   // This may be smaller than the raw size (the raw size is multiple
188   // of disk sector size, so there may be padding at end), or may be
189   // larger (if that's the case, the loader reserves spaces after end
190   // of raw data).
191   uint64_t getVirtualSize() { return Header.VirtualSize; }
192 
193   // Returns the size of the section in the output file.
194   uint64_t getRawSize() { return Header.SizeOfRawData; }
195 
196   // Set offset into the string table storing this section name.
197   // Used only when the name is longer than 8 bytes.
198   void setStringTableOff(uint32_t V) { StringTableOff = V; }
199 
200   // N.B. The section index is one based.
201   uint32_t SectionIndex = 0;
202 
203 private:
204   StringRef Name;
205   coff_section Header;
206   uint32_t StringTableOff = 0;
207   std::vector<Chunk *> Chunks;
208 };
209 
210 void OutputSection::setRVA(uint64_t RVA) {
211   Header.VirtualAddress = RVA;
212   for (Chunk *C : Chunks)
213     C->setRVA(C->getRVA() + RVA);
214 }
215 
216 void OutputSection::setFileOffset(uint64_t Off) {
217   // If a section has no actual data (i.e. BSS section), we want to
218   // set 0 to its PointerToRawData. Otherwise the output is rejected
219   // by the loader.
220   if (Header.SizeOfRawData == 0)
221     return;
222   Header.PointerToRawData = Off;
223 }
224 
225 void OutputSection::addChunk(Chunk *C) {
226   Chunks.push_back(C);
227   C->setOutputSection(this);
228   uint64_t Off = Header.VirtualSize;
229   Off = alignTo(Off, C->getAlign());
230   C->setRVA(Off);
231   C->setOutputSectionOff(Off);
232   Off += C->getSize();
233   Header.VirtualSize = Off;
234   if (C->hasData())
235     Header.SizeOfRawData = alignTo(Off, SectorSize);
236 }
237 
238 void OutputSection::addPermissions(uint32_t C) {
239   Header.Characteristics |= C & PermMask;
240 }
241 
242 void OutputSection::setPermissions(uint32_t C) {
243   Header.Characteristics = C & PermMask;
244 }
245 
246 // Write the section header to a given buffer.
247 void OutputSection::writeHeaderTo(uint8_t *Buf) {
248   auto *Hdr = reinterpret_cast<coff_section *>(Buf);
249   *Hdr = Header;
250   if (StringTableOff) {
251     // If name is too long, write offset into the string table as a name.
252     sprintf(Hdr->Name, "/%d", StringTableOff);
253   } else {
254     assert(!Config->Debug || Name.size() <= COFF::NameSize);
255     strncpy(Hdr->Name, Name.data(),
256             std::min(Name.size(), (size_t)COFF::NameSize));
257   }
258 }
259 
260 uint64_t Defined::getSecrel() {
261   if (auto *D = dyn_cast<DefinedRegular>(this))
262     return getRVA() - D->getChunk()->getOutputSection()->getRVA();
263   fatal("SECREL relocation points to a non-regular symbol");
264 }
265 
266 uint64_t Defined::getSectionIndex() {
267   if (auto *D = dyn_cast<DefinedRegular>(this))
268     return D->getChunk()->getOutputSection()->SectionIndex;
269   fatal("SECTION relocation points to a non-regular symbol");
270 }
271 
272 bool Defined::isExecutable() {
273   const auto X = IMAGE_SCN_MEM_EXECUTE;
274   if (auto *D = dyn_cast<DefinedRegular>(this))
275     return D->getChunk()->getOutputSection()->getPermissions() & X;
276   return isa<DefinedImportThunk>(this);
277 }
278 
279 } // namespace coff
280 } // namespace lld
281 
282 // The main function of the writer.
283 void Writer::run() {
284   createSections();
285   createMiscChunks();
286   createImportTables();
287   createExportTable();
288   if (Config->Relocatable)
289     createSection(".reloc");
290   assignAddresses();
291   removeEmptySections();
292   setSectionPermissions();
293   createSymbolAndStringTable();
294   openFile(Config->OutputFile);
295   if (Config->is64()) {
296     writeHeader<pe32plus_header>();
297   } else {
298     writeHeader<pe32_header>();
299   }
300   fixSafeSEHSymbols();
301   writeSections();
302   sortExceptionTable();
303   writeBuildId();
304   if (auto EC = Buffer->commit())
305     fatal(EC, "failed to write the output file");
306 }
307 
308 static StringRef getOutputSection(StringRef Name) {
309   StringRef S = Name.split('$').first;
310   auto It = Config->Merge.find(S);
311   if (It == Config->Merge.end())
312     return S;
313   return It->second;
314 }
315 
316 // Create output section objects and add them to OutputSections.
317 void Writer::createSections() {
318   // First, bin chunks by name.
319   std::map<StringRef, std::vector<Chunk *>> Map;
320   for (Chunk *C : Symtab->getChunks()) {
321     auto *SC = dyn_cast<SectionChunk>(C);
322     if (SC && !SC->isLive()) {
323       if (Config->Verbose)
324         SC->printDiscardedMessage();
325       continue;
326     }
327     Map[C->getSectionName()].push_back(C);
328   }
329 
330   // Then create an OutputSection for each section.
331   // '$' and all following characters in input section names are
332   // discarded when determining output section. So, .text$foo
333   // contributes to .text, for example. See PE/COFF spec 3.2.
334   SmallDenseMap<StringRef, OutputSection *> Sections;
335   for (auto Pair : Map) {
336     StringRef Name = getOutputSection(Pair.first);
337     OutputSection *&Sec = Sections[Name];
338     if (!Sec) {
339       Sec = new (CAlloc.Allocate()) OutputSection(Name);
340       OutputSections.push_back(Sec);
341     }
342     std::vector<Chunk *> &Chunks = Pair.second;
343     for (Chunk *C : Chunks) {
344       Sec->addChunk(C);
345       Sec->addPermissions(C->getPermissions());
346     }
347   }
348 }
349 
350 void Writer::createMiscChunks() {
351   OutputSection *RData = createSection(".rdata");
352 
353   // Create thunks for locally-dllimported symbols.
354   if (!Symtab->LocalImportChunks.empty()) {
355     for (Chunk *C : Symtab->LocalImportChunks)
356       RData->addChunk(C);
357   }
358 
359   // Create Debug Information Chunks
360   if (Config->Debug) {
361     DebugDirectory = llvm::make_unique<DebugDirectoryChunk>(DebugRecords);
362 
363     // TODO(compnerd) create a coffgrp entry if DebugType::CV is not enabled
364     if (Config->DebugTypes & static_cast<unsigned>(coff::DebugType::CV)) {
365       auto Chunk = llvm::make_unique<CVDebugRecordChunk>();
366 
367       BuildId = Chunk.get();
368       DebugRecords.push_back(std::move(Chunk));
369     }
370 
371     RData->addChunk(DebugDirectory.get());
372     for (const std::unique_ptr<Chunk> &C : DebugRecords)
373       RData->addChunk(C.get());
374   }
375 
376   // Create SEH table. x86-only.
377   if (Config->Machine != I386)
378     return;
379 
380   std::set<Defined *> Handlers;
381 
382   for (lld::coff::ObjectFile *File : Symtab->ObjectFiles) {
383     if (!File->SEHCompat)
384       return;
385     for (SymbolBody *B : File->SEHandlers)
386       Handlers.insert(cast<Defined>(B->repl()));
387   }
388 
389   SEHTable.reset(new SEHTableChunk(Handlers));
390   RData->addChunk(SEHTable.get());
391 }
392 
393 // Create .idata section for the DLL-imported symbol table.
394 // The format of this section is inherently Windows-specific.
395 // IdataContents class abstracted away the details for us,
396 // so we just let it create chunks and add them to the section.
397 void Writer::createImportTables() {
398   if (Symtab->ImportFiles.empty())
399     return;
400 
401   // Initialize DLLOrder so that import entries are ordered in
402   // the same order as in the command line. (That affects DLL
403   // initialization order, and this ordering is MSVC-compatible.)
404   for (ImportFile *File : Symtab->ImportFiles) {
405     std::string DLL = StringRef(File->DLLName).lower();
406     if (Config->DLLOrder.count(DLL) == 0)
407       Config->DLLOrder[DLL] = Config->DLLOrder.size();
408   }
409 
410   OutputSection *Text = createSection(".text");
411   for (ImportFile *File : Symtab->ImportFiles) {
412     if (DefinedImportThunk *Thunk = File->ThunkSym)
413       Text->addChunk(Thunk->getChunk());
414     if (Config->DelayLoads.count(StringRef(File->DLLName).lower())) {
415       DelayIdata.add(File->ImpSym);
416     } else {
417       Idata.add(File->ImpSym);
418     }
419   }
420   if (!Idata.empty()) {
421     OutputSection *Sec = createSection(".idata");
422     for (Chunk *C : Idata.getChunks())
423       Sec->addChunk(C);
424   }
425   if (!DelayIdata.empty()) {
426     Defined *Helper = cast<Defined>(Config->DelayLoadHelper->repl());
427     DelayIdata.create(Helper);
428     OutputSection *Sec = createSection(".didat");
429     for (Chunk *C : DelayIdata.getChunks())
430       Sec->addChunk(C);
431     Sec = createSection(".data");
432     for (Chunk *C : DelayIdata.getDataChunks())
433       Sec->addChunk(C);
434     Sec = createSection(".text");
435     for (std::unique_ptr<Chunk> &C : DelayIdata.getCodeChunks())
436       Sec->addChunk(C.get());
437   }
438 }
439 
440 void Writer::createExportTable() {
441   if (Config->Exports.empty())
442     return;
443   OutputSection *Sec = createSection(".edata");
444   for (std::unique_ptr<Chunk> &C : Edata.Chunks)
445     Sec->addChunk(C.get());
446 }
447 
448 // The Windows loader doesn't seem to like empty sections,
449 // so we remove them if any.
450 void Writer::removeEmptySections() {
451   auto IsEmpty = [](OutputSection *S) { return S->getVirtualSize() == 0; };
452   OutputSections.erase(
453       std::remove_if(OutputSections.begin(), OutputSections.end(), IsEmpty),
454       OutputSections.end());
455   uint32_t Idx = 1;
456   for (OutputSection *Sec : OutputSections)
457     Sec->SectionIndex = Idx++;
458 }
459 
460 size_t Writer::addEntryToStringTable(StringRef Str) {
461   assert(Str.size() > COFF::NameSize);
462   size_t OffsetOfEntry = Strtab.size() + 4; // +4 for the size field
463   Strtab.insert(Strtab.end(), Str.begin(), Str.end());
464   Strtab.push_back('\0');
465   return OffsetOfEntry;
466 }
467 
468 Optional<coff_symbol16> Writer::createSymbol(Defined *Def) {
469   if (auto *D = dyn_cast<DefinedRegular>(Def))
470     if (!D->getChunk()->isLive())
471       return None;
472 
473   coff_symbol16 Sym;
474   StringRef Name = Def->getName();
475   if (Name.size() > COFF::NameSize) {
476     Sym.Name.Offset.Zeroes = 0;
477     Sym.Name.Offset.Offset = addEntryToStringTable(Name);
478   } else {
479     memset(Sym.Name.ShortName, 0, COFF::NameSize);
480     memcpy(Sym.Name.ShortName, Name.data(), Name.size());
481   }
482 
483   if (auto *D = dyn_cast<DefinedCOFF>(Def)) {
484     COFFSymbolRef Ref = D->getCOFFSymbol();
485     Sym.Type = Ref.getType();
486     Sym.StorageClass = Ref.getStorageClass();
487   } else {
488     Sym.Type = IMAGE_SYM_TYPE_NULL;
489     Sym.StorageClass = IMAGE_SYM_CLASS_EXTERNAL;
490   }
491   Sym.NumberOfAuxSymbols = 0;
492 
493   switch (Def->kind()) {
494   case SymbolBody::DefinedAbsoluteKind:
495   case SymbolBody::DefinedRelativeKind:
496     Sym.Value = Def->getRVA();
497     Sym.SectionNumber = IMAGE_SYM_ABSOLUTE;
498     break;
499   default: {
500     uint64_t RVA = Def->getRVA();
501     OutputSection *Sec = nullptr;
502     for (OutputSection *S : OutputSections) {
503       if (S->getRVA() > RVA)
504         break;
505       Sec = S;
506     }
507     Sym.Value = RVA - Sec->getRVA();
508     Sym.SectionNumber = Sec->SectionIndex;
509     break;
510   }
511   }
512   return Sym;
513 }
514 
515 void Writer::createSymbolAndStringTable() {
516   if (!Config->Debug || !Config->WriteSymtab)
517     return;
518 
519   // Name field in the section table is 8 byte long. Longer names need
520   // to be written to the string table. First, construct string table.
521   for (OutputSection *Sec : OutputSections) {
522     StringRef Name = Sec->getName();
523     if (Name.size() <= COFF::NameSize)
524       continue;
525     Sec->setStringTableOff(addEntryToStringTable(Name));
526   }
527 
528   for (lld::coff::ObjectFile *File : Symtab->ObjectFiles)
529     for (SymbolBody *B : File->getSymbols())
530       if (auto *D = dyn_cast<Defined>(B))
531         if (Optional<coff_symbol16> Sym = createSymbol(D))
532           OutputSymtab.push_back(*Sym);
533 
534   for (ImportFile *File : Symtab->ImportFiles)
535     for (SymbolBody *B : File->getSymbols())
536       if (Optional<coff_symbol16> Sym = createSymbol(cast<Defined>(B)))
537         OutputSymtab.push_back(*Sym);
538 
539   OutputSection *LastSection = OutputSections.back();
540   // We position the symbol table to be adjacent to the end of the last section.
541   uint64_t FileOff = LastSection->getFileOff() +
542                      alignTo(LastSection->getRawSize(), SectorSize);
543   if (!OutputSymtab.empty()) {
544     PointerToSymbolTable = FileOff;
545     FileOff += OutputSymtab.size() * sizeof(coff_symbol16);
546   }
547   if (!Strtab.empty())
548     FileOff += Strtab.size() + 4;
549   FileSize = alignTo(FileOff, SectorSize);
550 }
551 
552 // Visits all sections to assign incremental, non-overlapping RVAs and
553 // file offsets.
554 void Writer::assignAddresses() {
555   SizeOfHeaders = DOSStubSize + sizeof(PEMagic) + sizeof(coff_file_header) +
556                   sizeof(data_directory) * NumberfOfDataDirectory +
557                   sizeof(coff_section) * OutputSections.size();
558   SizeOfHeaders +=
559       Config->is64() ? sizeof(pe32plus_header) : sizeof(pe32_header);
560   SizeOfHeaders = alignTo(SizeOfHeaders, SectorSize);
561   uint64_t RVA = 0x1000; // The first page is kept unmapped.
562   FileSize = SizeOfHeaders;
563   // Move DISCARDABLE (or non-memory-mapped) sections to the end of file because
564   // the loader cannot handle holes.
565   std::stable_partition(
566       OutputSections.begin(), OutputSections.end(), [](OutputSection *S) {
567         return (S->getPermissions() & IMAGE_SCN_MEM_DISCARDABLE) == 0;
568       });
569   for (OutputSection *Sec : OutputSections) {
570     if (Sec->getName() == ".reloc")
571       addBaserels(Sec);
572     Sec->setRVA(RVA);
573     Sec->setFileOffset(FileSize);
574     RVA += alignTo(Sec->getVirtualSize(), PageSize);
575     FileSize += alignTo(Sec->getRawSize(), SectorSize);
576   }
577   SizeOfImage = SizeOfHeaders + alignTo(RVA - 0x1000, PageSize);
578 }
579 
580 template <typename PEHeaderTy> void Writer::writeHeader() {
581   // Write DOS stub
582   uint8_t *Buf = Buffer->getBufferStart();
583   auto *DOS = reinterpret_cast<dos_header *>(Buf);
584   Buf += DOSStubSize;
585   DOS->Magic[0] = 'M';
586   DOS->Magic[1] = 'Z';
587   DOS->AddressOfRelocationTable = sizeof(dos_header);
588   DOS->AddressOfNewExeHeader = DOSStubSize;
589 
590   // Write PE magic
591   memcpy(Buf, PEMagic, sizeof(PEMagic));
592   Buf += sizeof(PEMagic);
593 
594   // Write COFF header
595   auto *COFF = reinterpret_cast<coff_file_header *>(Buf);
596   Buf += sizeof(*COFF);
597   COFF->Machine = Config->Machine;
598   COFF->NumberOfSections = OutputSections.size();
599   COFF->Characteristics = IMAGE_FILE_EXECUTABLE_IMAGE;
600   if (Config->LargeAddressAware)
601     COFF->Characteristics |= IMAGE_FILE_LARGE_ADDRESS_AWARE;
602   if (!Config->is64())
603     COFF->Characteristics |= IMAGE_FILE_32BIT_MACHINE;
604   if (Config->DLL)
605     COFF->Characteristics |= IMAGE_FILE_DLL;
606   if (!Config->Relocatable)
607     COFF->Characteristics |= IMAGE_FILE_RELOCS_STRIPPED;
608   COFF->SizeOfOptionalHeader =
609       sizeof(PEHeaderTy) + sizeof(data_directory) * NumberfOfDataDirectory;
610 
611   // Write PE header
612   auto *PE = reinterpret_cast<PEHeaderTy *>(Buf);
613   Buf += sizeof(*PE);
614   PE->Magic = Config->is64() ? PE32Header::PE32_PLUS : PE32Header::PE32;
615   PE->ImageBase = Config->ImageBase;
616   PE->SectionAlignment = PageSize;
617   PE->FileAlignment = SectorSize;
618   PE->MajorImageVersion = Config->MajorImageVersion;
619   PE->MinorImageVersion = Config->MinorImageVersion;
620   PE->MajorOperatingSystemVersion = Config->MajorOSVersion;
621   PE->MinorOperatingSystemVersion = Config->MinorOSVersion;
622   PE->MajorSubsystemVersion = Config->MajorOSVersion;
623   PE->MinorSubsystemVersion = Config->MinorOSVersion;
624   PE->Subsystem = Config->Subsystem;
625   PE->SizeOfImage = SizeOfImage;
626   PE->SizeOfHeaders = SizeOfHeaders;
627   if (!Config->NoEntry) {
628     Defined *Entry = cast<Defined>(Config->Entry->repl());
629     PE->AddressOfEntryPoint = Entry->getRVA();
630     // Pointer to thumb code must have the LSB set, so adjust it.
631     if (Config->Machine == ARMNT)
632       PE->AddressOfEntryPoint |= 1;
633   }
634   PE->SizeOfStackReserve = Config->StackReserve;
635   PE->SizeOfStackCommit = Config->StackCommit;
636   PE->SizeOfHeapReserve = Config->HeapReserve;
637   PE->SizeOfHeapCommit = Config->HeapCommit;
638   if (Config->DynamicBase)
639     PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE;
640   if (Config->HighEntropyVA)
641     PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA;
642   if (!Config->AllowBind)
643     PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_BIND;
644   if (Config->NxCompat)
645     PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NX_COMPAT;
646   if (!Config->AllowIsolation)
647     PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_ISOLATION;
648   if (Config->TerminalServerAware)
649     PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_TERMINAL_SERVER_AWARE;
650   PE->NumberOfRvaAndSize = NumberfOfDataDirectory;
651   if (OutputSection *Text = findSection(".text")) {
652     PE->BaseOfCode = Text->getRVA();
653     PE->SizeOfCode = Text->getRawSize();
654   }
655   PE->SizeOfInitializedData = getSizeOfInitializedData();
656 
657   // Write data directory
658   auto *Dir = reinterpret_cast<data_directory *>(Buf);
659   Buf += sizeof(*Dir) * NumberfOfDataDirectory;
660   if (OutputSection *Sec = findSection(".edata")) {
661     Dir[EXPORT_TABLE].RelativeVirtualAddress = Sec->getRVA();
662     Dir[EXPORT_TABLE].Size = Sec->getVirtualSize();
663   }
664   if (!Idata.empty()) {
665     Dir[IMPORT_TABLE].RelativeVirtualAddress = Idata.getDirRVA();
666     Dir[IMPORT_TABLE].Size = Idata.getDirSize();
667     Dir[IAT].RelativeVirtualAddress = Idata.getIATRVA();
668     Dir[IAT].Size = Idata.getIATSize();
669   }
670   if (OutputSection *Sec = findSection(".rsrc")) {
671     Dir[RESOURCE_TABLE].RelativeVirtualAddress = Sec->getRVA();
672     Dir[RESOURCE_TABLE].Size = Sec->getVirtualSize();
673   }
674   if (OutputSection *Sec = findSection(".pdata")) {
675     Dir[EXCEPTION_TABLE].RelativeVirtualAddress = Sec->getRVA();
676     Dir[EXCEPTION_TABLE].Size = Sec->getVirtualSize();
677   }
678   if (OutputSection *Sec = findSection(".reloc")) {
679     Dir[BASE_RELOCATION_TABLE].RelativeVirtualAddress = Sec->getRVA();
680     Dir[BASE_RELOCATION_TABLE].Size = Sec->getVirtualSize();
681   }
682   if (Symbol *Sym = Symtab->findUnderscore("_tls_used")) {
683     if (Defined *B = dyn_cast<Defined>(Sym->Body)) {
684       Dir[TLS_TABLE].RelativeVirtualAddress = B->getRVA();
685       Dir[TLS_TABLE].Size = Config->is64()
686                                 ? sizeof(object::coff_tls_directory64)
687                                 : sizeof(object::coff_tls_directory32);
688     }
689   }
690   if (Config->Debug) {
691     Dir[DEBUG_DIRECTORY].RelativeVirtualAddress = DebugDirectory->getRVA();
692     Dir[DEBUG_DIRECTORY].Size = DebugDirectory->getSize();
693   }
694   if (Symbol *Sym = Symtab->findUnderscore("_load_config_used")) {
695     if (auto *B = dyn_cast<DefinedRegular>(Sym->Body)) {
696       SectionChunk *SC = B->getChunk();
697       assert(B->getRVA() >= SC->getRVA());
698       uint64_t OffsetInChunk = B->getRVA() - SC->getRVA();
699       if (!SC->hasData() || OffsetInChunk + 4 > SC->getSize())
700         fatal("_load_config_used is malformed");
701 
702       ArrayRef<uint8_t> SecContents = SC->getContents();
703       uint32_t LoadConfigSize =
704           *reinterpret_cast<const ulittle32_t *>(&SecContents[OffsetInChunk]);
705       if (OffsetInChunk + LoadConfigSize > SC->getSize())
706         fatal("_load_config_used is too large");
707       Dir[LOAD_CONFIG_TABLE].RelativeVirtualAddress = B->getRVA();
708       Dir[LOAD_CONFIG_TABLE].Size = LoadConfigSize;
709     }
710   }
711   if (!DelayIdata.empty()) {
712     Dir[DELAY_IMPORT_DESCRIPTOR].RelativeVirtualAddress =
713         DelayIdata.getDirRVA();
714     Dir[DELAY_IMPORT_DESCRIPTOR].Size = DelayIdata.getDirSize();
715   }
716 
717   // Write section table
718   for (OutputSection *Sec : OutputSections) {
719     Sec->writeHeaderTo(Buf);
720     Buf += sizeof(coff_section);
721   }
722 
723   if (OutputSymtab.empty())
724     return;
725 
726   COFF->PointerToSymbolTable = PointerToSymbolTable;
727   uint32_t NumberOfSymbols = OutputSymtab.size();
728   COFF->NumberOfSymbols = NumberOfSymbols;
729   auto *SymbolTable = reinterpret_cast<coff_symbol16 *>(
730       Buffer->getBufferStart() + COFF->PointerToSymbolTable);
731   for (size_t I = 0; I != NumberOfSymbols; ++I)
732     SymbolTable[I] = OutputSymtab[I];
733   // Create the string table, it follows immediately after the symbol table.
734   // The first 4 bytes is length including itself.
735   Buf = reinterpret_cast<uint8_t *>(&SymbolTable[NumberOfSymbols]);
736   write32le(Buf, Strtab.size() + 4);
737   if (!Strtab.empty())
738     memcpy(Buf + 4, Strtab.data(), Strtab.size());
739 }
740 
741 void Writer::openFile(StringRef Path) {
742   Buffer = check(
743       FileOutputBuffer::create(Path, FileSize, FileOutputBuffer::F_executable),
744       "failed to open " + Path);
745 }
746 
747 void Writer::fixSafeSEHSymbols() {
748   if (!SEHTable)
749     return;
750   Config->SEHTable->setRVA(SEHTable->getRVA());
751   Config->SEHCount->setVA(SEHTable->getSize() / 4);
752 }
753 
754 // Handles /section options to allow users to overwrite
755 // section attributes.
756 void Writer::setSectionPermissions() {
757   for (auto &P : Config->Section) {
758     StringRef Name = P.first;
759     uint32_t Perm = P.second;
760     if (auto *Sec = findSection(Name))
761       Sec->setPermissions(Perm);
762   }
763 }
764 
765 // Write section contents to a mmap'ed file.
766 void Writer::writeSections() {
767   uint8_t *Buf = Buffer->getBufferStart();
768   for (OutputSection *Sec : OutputSections) {
769     uint8_t *SecBuf = Buf + Sec->getFileOff();
770     // Fill gaps between functions in .text with INT3 instructions
771     // instead of leaving as NUL bytes (which can be interpreted as
772     // ADD instructions).
773     if (Sec->getPermissions() & IMAGE_SCN_CNT_CODE)
774       memset(SecBuf, 0xCC, Sec->getRawSize());
775     parallel_for_each(Sec->getChunks().begin(), Sec->getChunks().end(),
776                       [&](Chunk *C) { C->writeTo(SecBuf); });
777   }
778 }
779 
780 // Sort .pdata section contents according to PE/COFF spec 5.5.
781 void Writer::sortExceptionTable() {
782   OutputSection *Sec = findSection(".pdata");
783   if (!Sec)
784     return;
785   // We assume .pdata contains function table entries only.
786   uint8_t *Begin = Buffer->getBufferStart() + Sec->getFileOff();
787   uint8_t *End = Begin + Sec->getVirtualSize();
788   if (Config->Machine == AMD64) {
789     struct Entry { ulittle32_t Begin, End, Unwind; };
790     parallel_sort(
791         (Entry *)Begin, (Entry *)End,
792         [](const Entry &A, const Entry &B) { return A.Begin < B.Begin; });
793     return;
794   }
795   if (Config->Machine == ARMNT) {
796     struct Entry { ulittle32_t Begin, Unwind; };
797     parallel_sort(
798         (Entry *)Begin, (Entry *)End,
799         [](const Entry &A, const Entry &B) { return A.Begin < B.Begin; });
800     return;
801   }
802   errs() << "warning: don't know how to handle .pdata.\n";
803 }
804 
805 // Backfill the CVSignature in a PDB70 Debug Record.  This backfilling allows us
806 // to get reproducible builds.
807 void Writer::writeBuildId() {
808   // There is nothing to backfill if BuildId was not setup.
809   if (BuildId == nullptr)
810     return;
811 
812   MD5 Hash;
813   MD5::MD5Result Res;
814 
815   Hash.update(ArrayRef<uint8_t>{Buffer->getBufferStart(),
816                                 Buffer->getBufferEnd()});
817   Hash.final(Res);
818 
819   assert(BuildId->DI->Signature.CVSignature == OMF::Signature::PDB70 &&
820          "only PDB 7.0 is supported");
821   memcpy(BuildId->DI->PDB70.Signature, Res, 16);
822   // TODO(compnerd) track the Age
823   BuildId->DI->PDB70.Age = 1;
824 }
825 
826 OutputSection *Writer::findSection(StringRef Name) {
827   for (OutputSection *Sec : OutputSections)
828     if (Sec->getName() == Name)
829       return Sec;
830   return nullptr;
831 }
832 
833 uint32_t Writer::getSizeOfInitializedData() {
834   uint32_t Res = 0;
835   for (OutputSection *S : OutputSections)
836     if (S->getPermissions() & IMAGE_SCN_CNT_INITIALIZED_DATA)
837       Res += S->getRawSize();
838   return Res;
839 }
840 
841 // Returns an existing section or create a new one if not found.
842 OutputSection *Writer::createSection(StringRef Name) {
843   if (auto *Sec = findSection(Name))
844     return Sec;
845   const auto DATA = IMAGE_SCN_CNT_INITIALIZED_DATA;
846   const auto BSS = IMAGE_SCN_CNT_UNINITIALIZED_DATA;
847   const auto CODE = IMAGE_SCN_CNT_CODE;
848   const auto DISCARDABLE = IMAGE_SCN_MEM_DISCARDABLE;
849   const auto R = IMAGE_SCN_MEM_READ;
850   const auto W = IMAGE_SCN_MEM_WRITE;
851   const auto X = IMAGE_SCN_MEM_EXECUTE;
852   uint32_t Perms = StringSwitch<uint32_t>(Name)
853                        .Case(".bss", BSS | R | W)
854                        .Case(".data", DATA | R | W)
855                        .Case(".didat", DATA | R)
856                        .Case(".edata", DATA | R)
857                        .Case(".idata", DATA | R)
858                        .Case(".rdata", DATA | R)
859                        .Case(".reloc", DATA | DISCARDABLE | R)
860                        .Case(".text", CODE | R | X)
861                        .Default(0);
862   if (!Perms)
863     llvm_unreachable("unknown section name");
864   auto Sec = new (CAlloc.Allocate()) OutputSection(Name);
865   Sec->addPermissions(Perms);
866   OutputSections.push_back(Sec);
867   return Sec;
868 }
869 
870 // Dest is .reloc section. Add contents to that section.
871 void Writer::addBaserels(OutputSection *Dest) {
872   std::vector<Baserel> V;
873   for (OutputSection *Sec : OutputSections) {
874     if (Sec == Dest)
875       continue;
876     // Collect all locations for base relocations.
877     for (Chunk *C : Sec->getChunks())
878       C->getBaserels(&V);
879     // Add the addresses to .reloc section.
880     if (!V.empty())
881       addBaserelBlocks(Dest, V);
882     V.clear();
883   }
884 }
885 
886 // Add addresses to .reloc section. Note that addresses are grouped by page.
887 void Writer::addBaserelBlocks(OutputSection *Dest, std::vector<Baserel> &V) {
888   const uint32_t Mask = ~uint32_t(PageSize - 1);
889   uint32_t Page = V[0].RVA & Mask;
890   size_t I = 0, J = 1;
891   for (size_t E = V.size(); J < E; ++J) {
892     uint32_t P = V[J].RVA & Mask;
893     if (P == Page)
894       continue;
895     BaserelChunk *Buf = BAlloc.Allocate();
896     Dest->addChunk(new (Buf) BaserelChunk(Page, &V[I], &V[0] + J));
897     I = J;
898     Page = P;
899   }
900   if (I == J)
901     return;
902   BaserelChunk *Buf = BAlloc.Allocate();
903   Dest->addChunk(new (Buf) BaserelChunk(Page, &V[I], &V[0] + J));
904 }
905