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