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