xref: /llvm-project-15.0.7/lld/COFF/Writer.cpp (revision decf22e5)
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 "InputFiles.h"
14 #include "MapFile.h"
15 #include "PDB.h"
16 #include "SymbolTable.h"
17 #include "Symbols.h"
18 #include "lld/Common/ErrorHandler.h"
19 #include "lld/Common/Memory.h"
20 #include "lld/Common/Timer.h"
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/StringSwitch.h"
24 #include "llvm/Support/BinaryStreamReader.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/Endian.h"
27 #include "llvm/Support/FileOutputBuffer.h"
28 #include "llvm/Support/Parallel.h"
29 #include "llvm/Support/RandomNumberGenerator.h"
30 #include <algorithm>
31 #include <cstdio>
32 #include <map>
33 #include <memory>
34 #include <utility>
35 
36 using namespace llvm;
37 using namespace llvm::COFF;
38 using namespace llvm::object;
39 using namespace llvm::support;
40 using namespace llvm::support::endian;
41 using namespace lld;
42 using namespace lld::coff;
43 
44 static const int SectorSize = 512;
45 static const int DOSStubSize = 64;
46 static const int NumberfOfDataDirectory = 16;
47 
48 namespace {
49 
50 class DebugDirectoryChunk : public Chunk {
51 public:
52   DebugDirectoryChunk(const std::vector<Chunk *> &R) : Records(R) {}
53 
54   size_t getSize() const override {
55     return Records.size() * sizeof(debug_directory);
56   }
57 
58   void writeTo(uint8_t *B) const override {
59     auto *D = reinterpret_cast<debug_directory *>(B + OutputSectionOff);
60 
61     for (const Chunk *Record : Records) {
62       D->Characteristics = 0;
63       D->TimeDateStamp = 0;
64       D->MajorVersion = 0;
65       D->MinorVersion = 0;
66       D->Type = COFF::IMAGE_DEBUG_TYPE_CODEVIEW;
67       D->SizeOfData = Record->getSize();
68       D->AddressOfRawData = Record->getRVA();
69       OutputSection *OS = Record->getOutputSection();
70       uint64_t Offs = OS->getFileOff() + (Record->getRVA() - OS->getRVA());
71       D->PointerToRawData = Offs;
72 
73       ++D;
74     }
75   }
76 
77 private:
78   const std::vector<Chunk *> &Records;
79 };
80 
81 class CVDebugRecordChunk : public Chunk {
82 public:
83   CVDebugRecordChunk() {
84     PDBAbsPath = Config->PDBPath;
85     if (!PDBAbsPath.empty())
86       llvm::sys::fs::make_absolute(PDBAbsPath);
87   }
88 
89   size_t getSize() const override {
90     return sizeof(codeview::DebugInfo) + PDBAbsPath.size() + 1;
91   }
92 
93   void writeTo(uint8_t *B) const override {
94     // Save off the DebugInfo entry to backfill the file signature (build id)
95     // in Writer::writeBuildId
96     BuildId = reinterpret_cast<codeview::DebugInfo *>(B + OutputSectionOff);
97 
98     // variable sized field (PDB Path)
99     char *P = reinterpret_cast<char *>(B + OutputSectionOff + sizeof(*BuildId));
100     if (!PDBAbsPath.empty())
101       memcpy(P, PDBAbsPath.data(), PDBAbsPath.size());
102     P[PDBAbsPath.size()] = '\0';
103   }
104 
105   SmallString<128> PDBAbsPath;
106   mutable codeview::DebugInfo *BuildId = nullptr;
107 };
108 
109 // The writer writes a SymbolTable result to a file.
110 class Writer {
111 public:
112   Writer() : Buffer(errorHandler().OutputBuffer) {}
113   void run();
114 
115 private:
116   void createSections();
117   void createMiscChunks();
118   void createImportTables();
119   void createExportTable();
120   void assignAddresses();
121   void removeEmptySections();
122   void createSymbolAndStringTable();
123   void openFile(StringRef OutputPath);
124   template <typename PEHeaderTy> void writeHeader();
125   void createSEHTable(OutputSection *RData);
126   void setSectionPermissions();
127   void writeSections();
128   void writeBuildId();
129   void sortExceptionTable();
130 
131   llvm::Optional<coff_symbol16> createSymbol(Defined *D);
132   size_t addEntryToStringTable(StringRef Str);
133 
134   OutputSection *findSection(StringRef Name);
135   OutputSection *createSection(StringRef Name);
136   void addBaserels(OutputSection *Dest);
137   void addBaserelBlocks(OutputSection *Dest, std::vector<Baserel> &V);
138 
139   uint32_t getSizeOfInitializedData();
140   std::map<StringRef, std::vector<DefinedImportData *>> binImports();
141 
142   std::unique_ptr<FileOutputBuffer> &Buffer;
143   std::vector<OutputSection *> OutputSections;
144   std::vector<char> Strtab;
145   std::vector<llvm::object::coff_symbol16> OutputSymtab;
146   IdataContents Idata;
147   DelayLoadContents DelayIdata;
148   EdataContents Edata;
149   SEHTableChunk *SEHTable = nullptr;
150 
151   Chunk *DebugDirectory = nullptr;
152   std::vector<Chunk *> DebugRecords;
153   CVDebugRecordChunk *BuildId = nullptr;
154   Optional<codeview::DebugInfo> PreviousBuildId;
155   ArrayRef<uint8_t> SectionTable;
156 
157   uint64_t FileSize;
158   uint32_t PointerToSymbolTable = 0;
159   uint64_t SizeOfImage;
160   uint64_t SizeOfHeaders;
161 };
162 } // anonymous namespace
163 
164 namespace lld {
165 namespace coff {
166 
167 static Timer CodeLayoutTimer("Code Layout", Timer::root());
168 static Timer DiskCommitTimer("Commit Output File", Timer::root());
169 
170 void writeResult() { Writer().run(); }
171 
172 void OutputSection::setRVA(uint64_t RVA) {
173   Header.VirtualAddress = RVA;
174   for (Chunk *C : Chunks)
175     C->setRVA(C->getRVA() + RVA);
176 }
177 
178 void OutputSection::setFileOffset(uint64_t Off) {
179   // If a section has no actual data (i.e. BSS section), we want to
180   // set 0 to its PointerToRawData. Otherwise the output is rejected
181   // by the loader.
182   if (Header.SizeOfRawData == 0)
183     return;
184 
185   // It is possible that this assignment could cause an overflow of the u32,
186   // but that should be caught by the FileSize check in OutputSection::run().
187   Header.PointerToRawData = Off;
188 }
189 
190 void OutputSection::addChunk(Chunk *C) {
191   Chunks.push_back(C);
192   C->setOutputSection(this);
193   uint64_t Off = Header.VirtualSize;
194   Off = alignTo(Off, C->Alignment);
195   C->setRVA(Off);
196   C->OutputSectionOff = Off;
197   Off += C->getSize();
198   if (Off > UINT32_MAX)
199     error("section larger than 4 GiB: " + Name);
200   Header.VirtualSize = Off;
201   if (C->hasData())
202     Header.SizeOfRawData = alignTo(Off, SectorSize);
203 }
204 
205 void OutputSection::addPermissions(uint32_t C) {
206   Header.Characteristics |= C & PermMask;
207 }
208 
209 void OutputSection::setPermissions(uint32_t C) {
210   Header.Characteristics = C & PermMask;
211 }
212 
213 // Write the section header to a given buffer.
214 void OutputSection::writeHeaderTo(uint8_t *Buf) {
215   auto *Hdr = reinterpret_cast<coff_section *>(Buf);
216   *Hdr = Header;
217   if (StringTableOff) {
218     // If name is too long, write offset into the string table as a name.
219     sprintf(Hdr->Name, "/%d", StringTableOff);
220   } else {
221     assert(!Config->Debug || Name.size() <= COFF::NameSize ||
222            (Hdr->Characteristics & IMAGE_SCN_MEM_DISCARDABLE) == 0);
223     strncpy(Hdr->Name, Name.data(),
224             std::min(Name.size(), (size_t)COFF::NameSize));
225   }
226 }
227 
228 } // namespace coff
229 } // namespace lld
230 
231 // PDBs are matched against executables using a build id which consists of three
232 // components:
233 //   1. A 16-bit GUID
234 //   2. An age
235 //   3. A time stamp.
236 //
237 // Debuggers and symbol servers match executables against debug info by checking
238 // each of these components of the EXE/DLL against the corresponding value in
239 // the PDB and failing a match if any of the components differ.  In the case of
240 // symbol servers, symbols are cached in a folder that is a function of the
241 // GUID.  As a result, in order to avoid symbol cache pollution where every
242 // incremental build copies a new PDB to the symbol cache, we must try to re-use
243 // the existing GUID if one exists, but bump the age.  This way the match will
244 // fail, so the symbol cache knows to use the new PDB, but the GUID matches, so
245 // it overwrites the existing item in the symbol cache rather than making a new
246 // one.
247 static Optional<codeview::DebugInfo> loadExistingBuildId(StringRef Path) {
248   // We don't need to incrementally update a previous build id if we're not
249   // writing codeview debug info.
250   if (!Config->Debug)
251     return None;
252 
253   auto ExpectedBinary = llvm::object::createBinary(Path);
254   if (!ExpectedBinary) {
255     consumeError(ExpectedBinary.takeError());
256     return None;
257   }
258 
259   auto Binary = std::move(*ExpectedBinary);
260   if (!Binary.getBinary()->isCOFF())
261     return None;
262 
263   std::error_code EC;
264   COFFObjectFile File(Binary.getBinary()->getMemoryBufferRef(), EC);
265   if (EC)
266     return None;
267 
268   // If the machine of the binary we're outputting doesn't match the machine
269   // of the existing binary, don't try to re-use the build id.
270   if (File.is64() != Config->is64() || File.getMachine() != Config->Machine)
271     return None;
272 
273   for (const auto &DebugDir : File.debug_directories()) {
274     if (DebugDir.Type != IMAGE_DEBUG_TYPE_CODEVIEW)
275       continue;
276 
277     const codeview::DebugInfo *ExistingDI = nullptr;
278     StringRef PDBFileName;
279     if (auto EC = File.getDebugPDBInfo(ExistingDI, PDBFileName)) {
280       (void)EC;
281       return None;
282     }
283     // We only support writing PDBs in v70 format.  So if this is not a build
284     // id that we recognize / support, ignore it.
285     if (ExistingDI->Signature.CVSignature != OMF::Signature::PDB70)
286       return None;
287     return *ExistingDI;
288   }
289   return None;
290 }
291 
292 // The main function of the writer.
293 void Writer::run() {
294   ScopedTimer T1(CodeLayoutTimer);
295 
296   createSections();
297   createMiscChunks();
298   createImportTables();
299   createExportTable();
300   if (Config->Relocatable)
301     createSection(".reloc");
302   assignAddresses();
303   removeEmptySections();
304   setSectionPermissions();
305   createSymbolAndStringTable();
306 
307   if (FileSize > UINT32_MAX)
308     fatal("image size (" + Twine(FileSize) + ") " +
309         "exceeds maximum allowable size (" + Twine(UINT32_MAX) + ")");
310 
311   // We must do this before opening the output file, as it depends on being able
312   // to read the contents of the existing output file.
313   PreviousBuildId = loadExistingBuildId(Config->OutputFile);
314   openFile(Config->OutputFile);
315   if (Config->is64()) {
316     writeHeader<pe32plus_header>();
317   } else {
318     writeHeader<pe32_header>();
319   }
320   writeSections();
321   sortExceptionTable();
322   writeBuildId();
323 
324   T1.stop();
325 
326   if (!Config->PDBPath.empty() && Config->Debug) {
327     assert(BuildId);
328     createPDB(Symtab, OutputSections, SectionTable, *BuildId->BuildId);
329   }
330 
331   writeMapFile(OutputSections);
332 
333   ScopedTimer T2(DiskCommitTimer);
334   if (auto E = Buffer->commit())
335     fatal("failed to write the output file: " + toString(std::move(E)));
336 }
337 
338 static StringRef getOutputSection(StringRef Name) {
339   StringRef S = Name.split('$').first;
340 
341   // Treat a later period as a separator for MinGW, for sections like
342   // ".ctors.01234".
343   S = S.substr(0, S.find('.', 1));
344 
345   auto It = Config->Merge.find(S);
346   if (It == Config->Merge.end())
347     return S;
348   return It->second;
349 }
350 
351 // Create output section objects and add them to OutputSections.
352 void Writer::createSections() {
353   // First, bin chunks by name.
354   std::map<StringRef, std::vector<Chunk *>> Map;
355   for (Chunk *C : Symtab->getChunks()) {
356     auto *SC = dyn_cast<SectionChunk>(C);
357     if (SC && !SC->isLive()) {
358       if (Config->Verbose)
359         SC->printDiscardedMessage();
360       continue;
361     }
362     Map[C->getSectionName()].push_back(C);
363   }
364 
365   // Then create an OutputSection for each section.
366   // '$' and all following characters in input section names are
367   // discarded when determining output section. So, .text$foo
368   // contributes to .text, for example. See PE/COFF spec 3.2.
369   SmallDenseMap<StringRef, OutputSection *> Sections;
370   for (auto Pair : Map) {
371     StringRef Name = getOutputSection(Pair.first);
372     OutputSection *&Sec = Sections[Name];
373     if (!Sec) {
374       Sec = make<OutputSection>(Name);
375       OutputSections.push_back(Sec);
376     }
377     std::vector<Chunk *> &Chunks = Pair.second;
378     for (Chunk *C : Chunks) {
379       Sec->addChunk(C);
380       Sec->addPermissions(C->getPermissions());
381     }
382   }
383 }
384 
385 void Writer::createMiscChunks() {
386   OutputSection *RData = createSection(".rdata");
387 
388   // Create thunks for locally-dllimported symbols.
389   if (!Symtab->LocalImportChunks.empty()) {
390     for (Chunk *C : Symtab->LocalImportChunks)
391       RData->addChunk(C);
392   }
393 
394   // Create Debug Information Chunks
395   if (Config->Debug) {
396     DebugDirectory = make<DebugDirectoryChunk>(DebugRecords);
397 
398     // Make a CVDebugRecordChunk even when /DEBUG:CV is not specified.  We
399     // output a PDB no matter what, and this chunk provides the only means of
400     // allowing a debugger to match a PDB and an executable.  So we need it even
401     // if we're ultimately not going to write CodeView data to the PDB.
402     auto *CVChunk = make<CVDebugRecordChunk>();
403     BuildId = CVChunk;
404     DebugRecords.push_back(CVChunk);
405 
406     RData->addChunk(DebugDirectory);
407     for (Chunk *C : DebugRecords)
408       RData->addChunk(C);
409   }
410 
411   createSEHTable(RData);
412 }
413 
414 // Create .idata section for the DLL-imported symbol table.
415 // The format of this section is inherently Windows-specific.
416 // IdataContents class abstracted away the details for us,
417 // so we just let it create chunks and add them to the section.
418 void Writer::createImportTables() {
419   if (ImportFile::Instances.empty())
420     return;
421 
422   // Initialize DLLOrder so that import entries are ordered in
423   // the same order as in the command line. (That affects DLL
424   // initialization order, and this ordering is MSVC-compatible.)
425   for (ImportFile *File : ImportFile::Instances) {
426     if (!File->Live)
427       continue;
428 
429     std::string DLL = StringRef(File->DLLName).lower();
430     if (Config->DLLOrder.count(DLL) == 0)
431       Config->DLLOrder[DLL] = Config->DLLOrder.size();
432   }
433 
434   OutputSection *Text = createSection(".text");
435   for (ImportFile *File : ImportFile::Instances) {
436     if (!File->Live)
437       continue;
438 
439     if (DefinedImportThunk *Thunk = File->ThunkSym)
440       Text->addChunk(Thunk->getChunk());
441 
442     if (Config->DelayLoads.count(StringRef(File->DLLName).lower())) {
443       if (!File->ThunkSym)
444         fatal("cannot delay-load " + toString(File) +
445               " due to import of data: " + toString(*File->ImpSym));
446       DelayIdata.add(File->ImpSym);
447     } else {
448       Idata.add(File->ImpSym);
449     }
450   }
451 
452   if (!Idata.empty()) {
453     OutputSection *Sec = createSection(".idata");
454     for (Chunk *C : Idata.getChunks())
455       Sec->addChunk(C);
456   }
457 
458   if (!DelayIdata.empty()) {
459     Defined *Helper = cast<Defined>(Config->DelayLoadHelper);
460     DelayIdata.create(Helper);
461     OutputSection *Sec = createSection(".didat");
462     for (Chunk *C : DelayIdata.getChunks())
463       Sec->addChunk(C);
464     Sec = createSection(".data");
465     for (Chunk *C : DelayIdata.getDataChunks())
466       Sec->addChunk(C);
467     Sec = createSection(".text");
468     for (Chunk *C : DelayIdata.getCodeChunks())
469       Sec->addChunk(C);
470   }
471 }
472 
473 void Writer::createExportTable() {
474   if (Config->Exports.empty())
475     return;
476   OutputSection *Sec = createSection(".edata");
477   for (Chunk *C : Edata.Chunks)
478     Sec->addChunk(C);
479 }
480 
481 // The Windows loader doesn't seem to like empty sections,
482 // so we remove them if any.
483 void Writer::removeEmptySections() {
484   auto IsEmpty = [](OutputSection *S) { return S->getVirtualSize() == 0; };
485   OutputSections.erase(
486       std::remove_if(OutputSections.begin(), OutputSections.end(), IsEmpty),
487       OutputSections.end());
488   uint32_t Idx = 1;
489   for (OutputSection *Sec : OutputSections)
490     Sec->SectionIndex = Idx++;
491 }
492 
493 size_t Writer::addEntryToStringTable(StringRef Str) {
494   assert(Str.size() > COFF::NameSize);
495   size_t OffsetOfEntry = Strtab.size() + 4; // +4 for the size field
496   Strtab.insert(Strtab.end(), Str.begin(), Str.end());
497   Strtab.push_back('\0');
498   return OffsetOfEntry;
499 }
500 
501 Optional<coff_symbol16> Writer::createSymbol(Defined *Def) {
502   // Relative symbols are unrepresentable in a COFF symbol table.
503   if (isa<DefinedSynthetic>(Def))
504     return None;
505 
506   // Don't write dead symbols or symbols in codeview sections to the symbol
507   // table.
508   if (!Def->isLive())
509     return None;
510   if (auto *D = dyn_cast<DefinedRegular>(Def))
511     if (D->getChunk()->isCodeView())
512       return None;
513 
514   coff_symbol16 Sym;
515   StringRef Name = Def->getName();
516   if (Name.size() > COFF::NameSize) {
517     Sym.Name.Offset.Zeroes = 0;
518     Sym.Name.Offset.Offset = addEntryToStringTable(Name);
519   } else {
520     memset(Sym.Name.ShortName, 0, COFF::NameSize);
521     memcpy(Sym.Name.ShortName, Name.data(), Name.size());
522   }
523 
524   if (auto *D = dyn_cast<DefinedCOFF>(Def)) {
525     COFFSymbolRef Ref = D->getCOFFSymbol();
526     Sym.Type = Ref.getType();
527     Sym.StorageClass = Ref.getStorageClass();
528   } else {
529     Sym.Type = IMAGE_SYM_TYPE_NULL;
530     Sym.StorageClass = IMAGE_SYM_CLASS_EXTERNAL;
531   }
532   Sym.NumberOfAuxSymbols = 0;
533 
534   switch (Def->kind()) {
535   case Symbol::DefinedAbsoluteKind:
536     Sym.Value = Def->getRVA();
537     Sym.SectionNumber = IMAGE_SYM_ABSOLUTE;
538     break;
539   default: {
540     uint64_t RVA = Def->getRVA();
541     OutputSection *Sec = nullptr;
542     for (OutputSection *S : OutputSections) {
543       if (S->getRVA() > RVA)
544         break;
545       Sec = S;
546     }
547     Sym.Value = RVA - Sec->getRVA();
548     Sym.SectionNumber = Sec->SectionIndex;
549     break;
550   }
551   }
552   return Sym;
553 }
554 
555 void Writer::createSymbolAndStringTable() {
556   // Name field in the section table is 8 byte long. Longer names need
557   // to be written to the string table. First, construct string table.
558   for (OutputSection *Sec : OutputSections) {
559     StringRef Name = Sec->getName();
560     if (Name.size() <= COFF::NameSize)
561       continue;
562     // If a section isn't discardable (i.e. will be mapped at runtime),
563     // prefer a truncated section name over a long section name in
564     // the string table that is unavailable at runtime. This is different from
565     // what link.exe does, but finding ".eh_fram" instead of "/4" is useful
566     // to libunwind.
567     if ((Sec->getPermissions() & IMAGE_SCN_MEM_DISCARDABLE) == 0)
568       continue;
569     Sec->setStringTableOff(addEntryToStringTable(Name));
570   }
571 
572   if (Config->DebugDwarf) {
573     for (ObjFile *File : ObjFile::Instances) {
574       for (Symbol *B : File->getSymbols()) {
575         auto *D = dyn_cast_or_null<Defined>(B);
576         if (!D || D->WrittenToSymtab)
577           continue;
578         D->WrittenToSymtab = true;
579 
580         if (Optional<coff_symbol16> Sym = createSymbol(D))
581           OutputSymtab.push_back(*Sym);
582       }
583     }
584   }
585 
586   if (OutputSymtab.empty() && Strtab.empty())
587     return;
588 
589   // We position the symbol table to be adjacent to the end of the last section.
590   uint64_t FileOff = FileSize;
591   PointerToSymbolTable = FileOff;
592   FileOff += OutputSymtab.size() * sizeof(coff_symbol16);
593   FileOff += 4 + Strtab.size();
594   FileSize = alignTo(FileOff, SectorSize);
595 }
596 
597 // Visits all sections to assign incremental, non-overlapping RVAs and
598 // file offsets.
599 void Writer::assignAddresses() {
600   SizeOfHeaders = DOSStubSize + sizeof(PEMagic) + sizeof(coff_file_header) +
601                   sizeof(data_directory) * NumberfOfDataDirectory +
602                   sizeof(coff_section) * OutputSections.size();
603   SizeOfHeaders +=
604       Config->is64() ? sizeof(pe32plus_header) : sizeof(pe32_header);
605   SizeOfHeaders = alignTo(SizeOfHeaders, SectorSize);
606   uint64_t RVA = PageSize; // The first page is kept unmapped.
607   FileSize = SizeOfHeaders;
608   // Move DISCARDABLE (or non-memory-mapped) sections to the end of file because
609   // the loader cannot handle holes.
610   std::stable_partition(
611       OutputSections.begin(), OutputSections.end(), [](OutputSection *S) {
612         return (S->getPermissions() & IMAGE_SCN_MEM_DISCARDABLE) == 0;
613       });
614   for (OutputSection *Sec : OutputSections) {
615     if (Sec->getName() == ".reloc")
616       addBaserels(Sec);
617     Sec->setRVA(RVA);
618     Sec->setFileOffset(FileSize);
619     RVA += alignTo(Sec->getVirtualSize(), PageSize);
620     FileSize += alignTo(Sec->getRawSize(), SectorSize);
621   }
622   SizeOfImage = alignTo(RVA, PageSize);
623 }
624 
625 template <typename PEHeaderTy> void Writer::writeHeader() {
626   // Write DOS stub
627   uint8_t *Buf = Buffer->getBufferStart();
628   auto *DOS = reinterpret_cast<dos_header *>(Buf);
629   Buf += DOSStubSize;
630   DOS->Magic[0] = 'M';
631   DOS->Magic[1] = 'Z';
632   DOS->AddressOfRelocationTable = sizeof(dos_header);
633   DOS->AddressOfNewExeHeader = DOSStubSize;
634 
635   // Write PE magic
636   memcpy(Buf, PEMagic, sizeof(PEMagic));
637   Buf += sizeof(PEMagic);
638 
639   // Write COFF header
640   auto *COFF = reinterpret_cast<coff_file_header *>(Buf);
641   Buf += sizeof(*COFF);
642   COFF->Machine = Config->Machine;
643   COFF->NumberOfSections = OutputSections.size();
644   COFF->Characteristics = IMAGE_FILE_EXECUTABLE_IMAGE;
645   if (Config->LargeAddressAware)
646     COFF->Characteristics |= IMAGE_FILE_LARGE_ADDRESS_AWARE;
647   if (!Config->is64())
648     COFF->Characteristics |= IMAGE_FILE_32BIT_MACHINE;
649   if (Config->DLL)
650     COFF->Characteristics |= IMAGE_FILE_DLL;
651   if (!Config->Relocatable)
652     COFF->Characteristics |= IMAGE_FILE_RELOCS_STRIPPED;
653   COFF->SizeOfOptionalHeader =
654       sizeof(PEHeaderTy) + sizeof(data_directory) * NumberfOfDataDirectory;
655 
656   // Write PE header
657   auto *PE = reinterpret_cast<PEHeaderTy *>(Buf);
658   Buf += sizeof(*PE);
659   PE->Magic = Config->is64() ? PE32Header::PE32_PLUS : PE32Header::PE32;
660 
661   // If {Major,Minor}LinkerVersion is left at 0.0, then for some
662   // reason signing the resulting PE file with Authenticode produces a
663   // signature that fails to validate on Windows 7 (but is OK on 10).
664   // Set it to 14.0, which is what VS2015 outputs, and which avoids
665   // that problem.
666   PE->MajorLinkerVersion = 14;
667   PE->MinorLinkerVersion = 0;
668 
669   PE->ImageBase = Config->ImageBase;
670   PE->SectionAlignment = PageSize;
671   PE->FileAlignment = SectorSize;
672   PE->MajorImageVersion = Config->MajorImageVersion;
673   PE->MinorImageVersion = Config->MinorImageVersion;
674   PE->MajorOperatingSystemVersion = Config->MajorOSVersion;
675   PE->MinorOperatingSystemVersion = Config->MinorOSVersion;
676   PE->MajorSubsystemVersion = Config->MajorOSVersion;
677   PE->MinorSubsystemVersion = Config->MinorOSVersion;
678   PE->Subsystem = Config->Subsystem;
679   PE->SizeOfImage = SizeOfImage;
680   PE->SizeOfHeaders = SizeOfHeaders;
681   if (!Config->NoEntry) {
682     Defined *Entry = cast<Defined>(Config->Entry);
683     PE->AddressOfEntryPoint = Entry->getRVA();
684     // Pointer to thumb code must have the LSB set, so adjust it.
685     if (Config->Machine == ARMNT)
686       PE->AddressOfEntryPoint |= 1;
687   }
688   PE->SizeOfStackReserve = Config->StackReserve;
689   PE->SizeOfStackCommit = Config->StackCommit;
690   PE->SizeOfHeapReserve = Config->HeapReserve;
691   PE->SizeOfHeapCommit = Config->HeapCommit;
692   if (Config->AppContainer)
693     PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_APPCONTAINER;
694   if (Config->DynamicBase)
695     PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE;
696   if (Config->HighEntropyVA)
697     PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA;
698   if (!Config->AllowBind)
699     PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_BIND;
700   if (Config->NxCompat)
701     PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NX_COMPAT;
702   if (!Config->AllowIsolation)
703     PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_ISOLATION;
704   if (Config->Machine == I386 && !SEHTable &&
705       !Symtab->findUnderscore("_load_config_used"))
706     PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_SEH;
707   if (Config->TerminalServerAware)
708     PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_TERMINAL_SERVER_AWARE;
709   PE->NumberOfRvaAndSize = NumberfOfDataDirectory;
710   if (OutputSection *Text = findSection(".text")) {
711     PE->BaseOfCode = Text->getRVA();
712     PE->SizeOfCode = Text->getRawSize();
713   }
714   PE->SizeOfInitializedData = getSizeOfInitializedData();
715 
716   // Write data directory
717   auto *Dir = reinterpret_cast<data_directory *>(Buf);
718   Buf += sizeof(*Dir) * NumberfOfDataDirectory;
719   if (OutputSection *Sec = findSection(".edata")) {
720     Dir[EXPORT_TABLE].RelativeVirtualAddress = Sec->getRVA();
721     Dir[EXPORT_TABLE].Size = Sec->getVirtualSize();
722   }
723   if (!Idata.empty()) {
724     Dir[IMPORT_TABLE].RelativeVirtualAddress = Idata.getDirRVA();
725     Dir[IMPORT_TABLE].Size = Idata.getDirSize();
726     Dir[IAT].RelativeVirtualAddress = Idata.getIATRVA();
727     Dir[IAT].Size = Idata.getIATSize();
728   }
729   if (OutputSection *Sec = findSection(".rsrc")) {
730     Dir[RESOURCE_TABLE].RelativeVirtualAddress = Sec->getRVA();
731     Dir[RESOURCE_TABLE].Size = Sec->getVirtualSize();
732   }
733   if (OutputSection *Sec = findSection(".pdata")) {
734     Dir[EXCEPTION_TABLE].RelativeVirtualAddress = Sec->getRVA();
735     Dir[EXCEPTION_TABLE].Size = Sec->getVirtualSize();
736   }
737   if (OutputSection *Sec = findSection(".reloc")) {
738     Dir[BASE_RELOCATION_TABLE].RelativeVirtualAddress = Sec->getRVA();
739     Dir[BASE_RELOCATION_TABLE].Size = Sec->getVirtualSize();
740   }
741   if (Symbol *Sym = Symtab->findUnderscore("_tls_used")) {
742     if (Defined *B = dyn_cast<Defined>(Sym)) {
743       Dir[TLS_TABLE].RelativeVirtualAddress = B->getRVA();
744       Dir[TLS_TABLE].Size = Config->is64()
745                                 ? sizeof(object::coff_tls_directory64)
746                                 : sizeof(object::coff_tls_directory32);
747     }
748   }
749   if (Config->Debug) {
750     Dir[DEBUG_DIRECTORY].RelativeVirtualAddress = DebugDirectory->getRVA();
751     Dir[DEBUG_DIRECTORY].Size = DebugDirectory->getSize();
752   }
753   if (Symbol *Sym = Symtab->findUnderscore("_load_config_used")) {
754     if (auto *B = dyn_cast<DefinedRegular>(Sym)) {
755       SectionChunk *SC = B->getChunk();
756       assert(B->getRVA() >= SC->getRVA());
757       uint64_t OffsetInChunk = B->getRVA() - SC->getRVA();
758       if (!SC->hasData() || OffsetInChunk + 4 > SC->getSize())
759         fatal("_load_config_used is malformed");
760 
761       ArrayRef<uint8_t> SecContents = SC->getContents();
762       uint32_t LoadConfigSize =
763           *reinterpret_cast<const ulittle32_t *>(&SecContents[OffsetInChunk]);
764       if (OffsetInChunk + LoadConfigSize > SC->getSize())
765         fatal("_load_config_used is too large");
766       Dir[LOAD_CONFIG_TABLE].RelativeVirtualAddress = B->getRVA();
767       Dir[LOAD_CONFIG_TABLE].Size = LoadConfigSize;
768     }
769   }
770   if (!DelayIdata.empty()) {
771     Dir[DELAY_IMPORT_DESCRIPTOR].RelativeVirtualAddress =
772         DelayIdata.getDirRVA();
773     Dir[DELAY_IMPORT_DESCRIPTOR].Size = DelayIdata.getDirSize();
774   }
775 
776   // Write section table
777   for (OutputSection *Sec : OutputSections) {
778     Sec->writeHeaderTo(Buf);
779     Buf += sizeof(coff_section);
780   }
781   SectionTable = ArrayRef<uint8_t>(
782       Buf - OutputSections.size() * sizeof(coff_section), Buf);
783 
784   if (OutputSymtab.empty() && Strtab.empty())
785     return;
786 
787   COFF->PointerToSymbolTable = PointerToSymbolTable;
788   uint32_t NumberOfSymbols = OutputSymtab.size();
789   COFF->NumberOfSymbols = NumberOfSymbols;
790   auto *SymbolTable = reinterpret_cast<coff_symbol16 *>(
791       Buffer->getBufferStart() + COFF->PointerToSymbolTable);
792   for (size_t I = 0; I != NumberOfSymbols; ++I)
793     SymbolTable[I] = OutputSymtab[I];
794   // Create the string table, it follows immediately after the symbol table.
795   // The first 4 bytes is length including itself.
796   Buf = reinterpret_cast<uint8_t *>(&SymbolTable[NumberOfSymbols]);
797   write32le(Buf, Strtab.size() + 4);
798   if (!Strtab.empty())
799     memcpy(Buf + 4, Strtab.data(), Strtab.size());
800 }
801 
802 void Writer::openFile(StringRef Path) {
803   Buffer = CHECK(
804       FileOutputBuffer::create(Path, FileSize, FileOutputBuffer::F_executable),
805       "failed to open " + Path);
806 }
807 
808 void Writer::createSEHTable(OutputSection *RData) {
809   // Create SEH table. x86-only.
810   if (Config->Machine != I386)
811     return;
812 
813   std::set<Defined *> Handlers;
814 
815   for (ObjFile *File : ObjFile::Instances) {
816     if (!File->SEHCompat)
817       return;
818     for (uint32_t I : File->SXData)
819       if (Symbol *B = File->getSymbol(I))
820         if (B->isLive())
821           Handlers.insert(cast<Defined>(B));
822   }
823 
824   if (Handlers.empty())
825     return;
826 
827   SEHTable = make<SEHTableChunk>(Handlers);
828   RData->addChunk(SEHTable);
829 
830   // Replace the absolute table symbol with a synthetic symbol pointing to the
831   // SEHTable chunk so that we can emit base relocations for it and resolve
832   // section relative relocations.
833   Symbol *T = Symtab->find("___safe_se_handler_table");
834   Symbol *C = Symtab->find("___safe_se_handler_count");
835   replaceSymbol<DefinedSynthetic>(T, T->getName(), SEHTable);
836   cast<DefinedAbsolute>(C)->setVA(SEHTable->getSize() / 4);
837 }
838 
839 // Handles /section options to allow users to overwrite
840 // section attributes.
841 void Writer::setSectionPermissions() {
842   for (auto &P : Config->Section) {
843     StringRef Name = P.first;
844     uint32_t Perm = P.second;
845     if (auto *Sec = findSection(Name))
846       Sec->setPermissions(Perm);
847   }
848 }
849 
850 // Write section contents to a mmap'ed file.
851 void Writer::writeSections() {
852   // Record the section index that should be used when resolving a section
853   // relocation against an absolute symbol.
854   DefinedAbsolute::OutputSectionIndex = OutputSections.size() + 1;
855 
856   uint8_t *Buf = Buffer->getBufferStart();
857   for (OutputSection *Sec : OutputSections) {
858     uint8_t *SecBuf = Buf + Sec->getFileOff();
859     // Fill gaps between functions in .text with INT3 instructions
860     // instead of leaving as NUL bytes (which can be interpreted as
861     // ADD instructions).
862     if (Sec->getPermissions() & IMAGE_SCN_CNT_CODE)
863       memset(SecBuf, 0xCC, Sec->getRawSize());
864     for_each(parallel::par, Sec->getChunks().begin(), Sec->getChunks().end(),
865              [&](Chunk *C) { C->writeTo(SecBuf); });
866   }
867 }
868 
869 void Writer::writeBuildId() {
870   // If we're not writing a build id (e.g. because /debug is not specified),
871   // then just return;
872   if (!Config->Debug)
873     return;
874 
875   assert(BuildId && "BuildId is not set!");
876 
877   if (PreviousBuildId.hasValue()) {
878     *BuildId->BuildId = *PreviousBuildId;
879     BuildId->BuildId->PDB70.Age = BuildId->BuildId->PDB70.Age + 1;
880     return;
881   }
882 
883   BuildId->BuildId->Signature.CVSignature = OMF::Signature::PDB70;
884   BuildId->BuildId->PDB70.Age = 1;
885   llvm::getRandomBytes(BuildId->BuildId->PDB70.Signature, 16);
886 }
887 
888 // Sort .pdata section contents according to PE/COFF spec 5.5.
889 void Writer::sortExceptionTable() {
890   OutputSection *Sec = findSection(".pdata");
891   if (!Sec)
892     return;
893   // We assume .pdata contains function table entries only.
894   uint8_t *Begin = Buffer->getBufferStart() + Sec->getFileOff();
895   uint8_t *End = Begin + Sec->getVirtualSize();
896   if (Config->Machine == AMD64) {
897     struct Entry { ulittle32_t Begin, End, Unwind; };
898     sort(parallel::par, (Entry *)Begin, (Entry *)End,
899          [](const Entry &A, const Entry &B) { return A.Begin < B.Begin; });
900     return;
901   }
902   if (Config->Machine == ARMNT || Config->Machine == ARM64) {
903     struct Entry { ulittle32_t Begin, Unwind; };
904     sort(parallel::par, (Entry *)Begin, (Entry *)End,
905          [](const Entry &A, const Entry &B) { return A.Begin < B.Begin; });
906     return;
907   }
908   errs() << "warning: don't know how to handle .pdata.\n";
909 }
910 
911 OutputSection *Writer::findSection(StringRef Name) {
912   for (OutputSection *Sec : OutputSections)
913     if (Sec->getName() == Name)
914       return Sec;
915   return nullptr;
916 }
917 
918 uint32_t Writer::getSizeOfInitializedData() {
919   uint32_t Res = 0;
920   for (OutputSection *S : OutputSections)
921     if (S->getPermissions() & IMAGE_SCN_CNT_INITIALIZED_DATA)
922       Res += S->getRawSize();
923   return Res;
924 }
925 
926 // Returns an existing section or create a new one if not found.
927 OutputSection *Writer::createSection(StringRef Name) {
928   if (auto *Sec = findSection(Name))
929     return Sec;
930   const auto DATA = IMAGE_SCN_CNT_INITIALIZED_DATA;
931   const auto BSS = IMAGE_SCN_CNT_UNINITIALIZED_DATA;
932   const auto CODE = IMAGE_SCN_CNT_CODE;
933   const auto DISCARDABLE = IMAGE_SCN_MEM_DISCARDABLE;
934   const auto R = IMAGE_SCN_MEM_READ;
935   const auto W = IMAGE_SCN_MEM_WRITE;
936   const auto X = IMAGE_SCN_MEM_EXECUTE;
937   uint32_t Perms = StringSwitch<uint32_t>(Name)
938                        .Case(".bss", BSS | R | W)
939                        .Case(".data", DATA | R | W)
940                        .Cases(".didat", ".edata", ".idata", ".rdata", DATA | R)
941                        .Case(".reloc", DATA | DISCARDABLE | R)
942                        .Case(".text", CODE | R | X)
943                        .Default(0);
944   if (!Perms)
945     llvm_unreachable("unknown section name");
946   auto Sec = make<OutputSection>(Name);
947   Sec->addPermissions(Perms);
948   OutputSections.push_back(Sec);
949   return Sec;
950 }
951 
952 // Dest is .reloc section. Add contents to that section.
953 void Writer::addBaserels(OutputSection *Dest) {
954   std::vector<Baserel> V;
955   for (OutputSection *Sec : OutputSections) {
956     if (Sec == Dest)
957       continue;
958     // Collect all locations for base relocations.
959     for (Chunk *C : Sec->getChunks())
960       C->getBaserels(&V);
961     // Add the addresses to .reloc section.
962     if (!V.empty())
963       addBaserelBlocks(Dest, V);
964     V.clear();
965   }
966 }
967 
968 // Add addresses to .reloc section. Note that addresses are grouped by page.
969 void Writer::addBaserelBlocks(OutputSection *Dest, std::vector<Baserel> &V) {
970   const uint32_t Mask = ~uint32_t(PageSize - 1);
971   uint32_t Page = V[0].RVA & Mask;
972   size_t I = 0, J = 1;
973   for (size_t E = V.size(); J < E; ++J) {
974     uint32_t P = V[J].RVA & Mask;
975     if (P == Page)
976       continue;
977     Dest->addChunk(make<BaserelChunk>(Page, &V[I], &V[0] + J));
978     I = J;
979     Page = P;
980   }
981   if (I == J)
982     return;
983   Dest->addChunk(make<BaserelChunk>(Page, &V[I], &V[0] + J));
984 }
985