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