xref: /llvm-project-15.0.7/lld/COFF/Writer.cpp (revision f4bf4227)
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 "Memory.h"
16 #include "PDB.h"
17 #include "SymbolTable.h"
18 #include "Symbols.h"
19 #include "lld/Common/ErrorHandler.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   void run();
112 
113 private:
114   void createSections();
115   void createMiscChunks();
116   void createImportTables();
117   void createExportTable();
118   void assignAddresses();
119   void removeEmptySections();
120   void createSymbolAndStringTable();
121   void openFile(StringRef OutputPath);
122   template <typename PEHeaderTy> void writeHeader();
123   void fixSafeSEHSymbols();
124   void setSectionPermissions();
125   void writeSections();
126   void writeBuildId();
127   void sortExceptionTable();
128 
129   llvm::Optional<coff_symbol16> createSymbol(Defined *D);
130   size_t addEntryToStringTable(StringRef Str);
131 
132   OutputSection *findSection(StringRef Name);
133   OutputSection *createSection(StringRef Name);
134   void addBaserels(OutputSection *Dest);
135   void addBaserelBlocks(OutputSection *Dest, std::vector<Baserel> &V);
136 
137   uint32_t getSizeOfInitializedData();
138   std::map<StringRef, std::vector<DefinedImportData *>> binImports();
139 
140   std::unique_ptr<FileOutputBuffer> Buffer;
141   std::vector<OutputSection *> OutputSections;
142   std::vector<char> Strtab;
143   std::vector<llvm::object::coff_symbol16> OutputSymtab;
144   IdataContents Idata;
145   DelayLoadContents DelayIdata;
146   EdataContents Edata;
147   SEHTableChunk *SEHTable = nullptr;
148 
149   Chunk *DebugDirectory = nullptr;
150   std::vector<Chunk *> DebugRecords;
151   CVDebugRecordChunk *BuildId = nullptr;
152   Optional<codeview::DebugInfo> PreviousBuildId;
153   ArrayRef<uint8_t> SectionTable;
154 
155   uint64_t FileSize;
156   uint32_t PointerToSymbolTable = 0;
157   uint64_t SizeOfImage;
158   uint64_t SizeOfHeaders;
159 };
160 } // anonymous namespace
161 
162 namespace lld {
163 namespace coff {
164 
165 void writeResult() { Writer().run(); }
166 
167 void OutputSection::setRVA(uint64_t RVA) {
168   Header.VirtualAddress = RVA;
169   for (Chunk *C : Chunks)
170     C->setRVA(C->getRVA() + RVA);
171 }
172 
173 void OutputSection::setFileOffset(uint64_t Off) {
174   // If a section has no actual data (i.e. BSS section), we want to
175   // set 0 to its PointerToRawData. Otherwise the output is rejected
176   // by the loader.
177   if (Header.SizeOfRawData == 0)
178     return;
179   Header.PointerToRawData = Off;
180 }
181 
182 void OutputSection::addChunk(Chunk *C) {
183   Chunks.push_back(C);
184   C->setOutputSection(this);
185   uint64_t Off = Header.VirtualSize;
186   Off = alignTo(Off, C->Alignment);
187   C->setRVA(Off);
188   C->OutputSectionOff = Off;
189   Off += C->getSize();
190   if (Off > UINT32_MAX)
191     error("section larger than 4 GiB: " + Name);
192   Header.VirtualSize = Off;
193   if (C->hasData())
194     Header.SizeOfRawData = alignTo(Off, SectorSize);
195 }
196 
197 void OutputSection::addPermissions(uint32_t C) {
198   Header.Characteristics |= C & PermMask;
199 }
200 
201 void OutputSection::setPermissions(uint32_t C) {
202   Header.Characteristics = C & PermMask;
203 }
204 
205 // Write the section header to a given buffer.
206 void OutputSection::writeHeaderTo(uint8_t *Buf) {
207   auto *Hdr = reinterpret_cast<coff_section *>(Buf);
208   *Hdr = Header;
209   if (StringTableOff) {
210     // If name is too long, write offset into the string table as a name.
211     sprintf(Hdr->Name, "/%d", StringTableOff);
212   } else {
213     assert(!Config->Debug || Name.size() <= COFF::NameSize);
214     strncpy(Hdr->Name, Name.data(),
215             std::min(Name.size(), (size_t)COFF::NameSize));
216   }
217 }
218 
219 } // namespace coff
220 } // namespace lld
221 
222 // PDBs are matched against executables using a build id which consists of three
223 // components:
224 //   1. A 16-bit GUID
225 //   2. An age
226 //   3. A time stamp.
227 //
228 // Debuggers and symbol servers match executables against debug info by checking
229 // each of these components of the EXE/DLL against the corresponding value in
230 // the PDB and failing a match if any of the components differ.  In the case of
231 // symbol servers, symbols are cached in a folder that is a function of the
232 // GUID.  As a result, in order to avoid symbol cache pollution where every
233 // incremental build copies a new PDB to the symbol cache, we must try to re-use
234 // the existing GUID if one exists, but bump the age.  This way the match will
235 // fail, so the symbol cache knows to use the new PDB, but the GUID matches, so
236 // it overwrites the existing item in the symbol cache rather than making a new
237 // one.
238 static Optional<codeview::DebugInfo> loadExistingBuildId(StringRef Path) {
239   // We don't need to incrementally update a previous build id if we're not
240   // writing codeview debug info.
241   if (!Config->Debug)
242     return None;
243 
244   auto ExpectedBinary = llvm::object::createBinary(Path);
245   if (!ExpectedBinary) {
246     consumeError(ExpectedBinary.takeError());
247     return None;
248   }
249 
250   auto Binary = std::move(*ExpectedBinary);
251   if (!Binary.getBinary()->isCOFF())
252     return None;
253 
254   std::error_code EC;
255   COFFObjectFile File(Binary.getBinary()->getMemoryBufferRef(), EC);
256   if (EC)
257     return None;
258 
259   // If the machine of the binary we're outputting doesn't match the machine
260   // of the existing binary, don't try to re-use the build id.
261   if (File.is64() != Config->is64() || File.getMachine() != Config->Machine)
262     return None;
263 
264   for (const auto &DebugDir : File.debug_directories()) {
265     if (DebugDir.Type != IMAGE_DEBUG_TYPE_CODEVIEW)
266       continue;
267 
268     const codeview::DebugInfo *ExistingDI = nullptr;
269     StringRef PDBFileName;
270     if (auto EC = File.getDebugPDBInfo(ExistingDI, PDBFileName)) {
271       (void)EC;
272       return None;
273     }
274     // We only support writing PDBs in v70 format.  So if this is not a build
275     // id that we recognize / support, ignore it.
276     if (ExistingDI->Signature.CVSignature != OMF::Signature::PDB70)
277       return None;
278     return *ExistingDI;
279   }
280   return None;
281 }
282 
283 // The main function of the writer.
284 void Writer::run() {
285   createSections();
286   createMiscChunks();
287   createImportTables();
288   createExportTable();
289   if (Config->Relocatable)
290     createSection(".reloc");
291   assignAddresses();
292   removeEmptySections();
293   setSectionPermissions();
294   createSymbolAndStringTable();
295 
296   // We must do this before opening the output file, as it depends on being able
297   // to read the contents of the existing output file.
298   PreviousBuildId = loadExistingBuildId(Config->OutputFile);
299   openFile(Config->OutputFile);
300   if (Config->is64()) {
301     writeHeader<pe32plus_header>();
302   } else {
303     writeHeader<pe32_header>();
304   }
305   fixSafeSEHSymbols();
306   writeSections();
307   sortExceptionTable();
308   writeBuildId();
309 
310   if (!Config->PDBPath.empty() && Config->Debug) {
311 
312     assert(BuildId);
313     createPDB(Symtab, OutputSections, SectionTable, *BuildId->BuildId);
314   }
315 
316   writeMapFile(OutputSections);
317 
318   if (auto EC = Buffer->commit())
319     fatal("failed to write the output file: " + EC.message());
320 }
321 
322 static StringRef getOutputSection(StringRef Name) {
323   StringRef S = Name.split('$').first;
324   auto It = Config->Merge.find(S);
325   if (It == Config->Merge.end())
326     return S;
327   return It->second;
328 }
329 
330 // Create output section objects and add them to OutputSections.
331 void Writer::createSections() {
332   // First, bin chunks by name.
333   std::map<StringRef, std::vector<Chunk *>> Map;
334   for (Chunk *C : Symtab->getChunks()) {
335     auto *SC = dyn_cast<SectionChunk>(C);
336     if (SC && !SC->isLive()) {
337       if (Config->Verbose)
338         SC->printDiscardedMessage();
339       continue;
340     }
341     Map[C->getSectionName()].push_back(C);
342   }
343 
344   // Then create an OutputSection for each section.
345   // '$' and all following characters in input section names are
346   // discarded when determining output section. So, .text$foo
347   // contributes to .text, for example. See PE/COFF spec 3.2.
348   SmallDenseMap<StringRef, OutputSection *> Sections;
349   for (auto Pair : Map) {
350     StringRef Name = getOutputSection(Pair.first);
351     OutputSection *&Sec = Sections[Name];
352     if (!Sec) {
353       Sec = make<OutputSection>(Name);
354       OutputSections.push_back(Sec);
355     }
356     std::vector<Chunk *> &Chunks = Pair.second;
357     for (Chunk *C : Chunks) {
358       Sec->addChunk(C);
359       Sec->addPermissions(C->getPermissions());
360     }
361   }
362 }
363 
364 void Writer::createMiscChunks() {
365   OutputSection *RData = createSection(".rdata");
366 
367   // Create thunks for locally-dllimported symbols.
368   if (!Symtab->LocalImportChunks.empty()) {
369     for (Chunk *C : Symtab->LocalImportChunks)
370       RData->addChunk(C);
371   }
372 
373   // Create Debug Information Chunks
374   if (Config->Debug) {
375     DebugDirectory = make<DebugDirectoryChunk>(DebugRecords);
376 
377     // Make a CVDebugRecordChunk even when /DEBUG:CV is not specified.  We
378     // output a PDB no matter what, and this chunk provides the only means of
379     // allowing a debugger to match a PDB and an executable.  So we need it even
380     // if we're ultimately not going to write CodeView data to the PDB.
381     auto *CVChunk = make<CVDebugRecordChunk>();
382     BuildId = CVChunk;
383     DebugRecords.push_back(CVChunk);
384 
385     RData->addChunk(DebugDirectory);
386     for (Chunk *C : DebugRecords)
387       RData->addChunk(C);
388   }
389 
390   // Create SEH table. x86-only.
391   if (Config->Machine != I386)
392     return;
393 
394   std::set<Defined *> Handlers;
395 
396   for (ObjFile *File : ObjFile::Instances) {
397     if (!File->SEHCompat)
398       return;
399     for (Symbol *B : File->SEHandlers) {
400       // Make sure the handler is still live. Assume all handlers are regular
401       // symbols.
402       auto *D = dyn_cast<DefinedRegular>(B);
403       if (D && D->getChunk()->isLive())
404         Handlers.insert(D);
405     }
406   }
407 
408   if (!Handlers.empty()) {
409     SEHTable = make<SEHTableChunk>(Handlers);
410     RData->addChunk(SEHTable);
411   }
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   if (!Config->Debug || !Config->WriteSymtab)
557     return;
558 
559   // Name field in the section table is 8 byte long. Longer names need
560   // to be written to the string table. First, construct string table.
561   for (OutputSection *Sec : OutputSections) {
562     StringRef Name = Sec->getName();
563     if (Name.size() <= COFF::NameSize)
564       continue;
565     Sec->setStringTableOff(addEntryToStringTable(Name));
566   }
567 
568   for (ObjFile *File : ObjFile::Instances) {
569     for (Symbol *B : File->getSymbols()) {
570       auto *D = dyn_cast<Defined>(B);
571       if (!D || D->WrittenToSymtab)
572         continue;
573       D->WrittenToSymtab = true;
574 
575       if (Optional<coff_symbol16> Sym = createSymbol(D))
576         OutputSymtab.push_back(*Sym);
577     }
578   }
579 
580   OutputSection *LastSection = OutputSections.back();
581   // We position the symbol table to be adjacent to the end of the last section.
582   uint64_t FileOff = LastSection->getFileOff() +
583                      alignTo(LastSection->getRawSize(), SectorSize);
584   if (!OutputSymtab.empty()) {
585     PointerToSymbolTable = FileOff;
586     FileOff += OutputSymtab.size() * sizeof(coff_symbol16);
587   }
588   if (!Strtab.empty())
589     FileOff += Strtab.size() + 4;
590   FileSize = alignTo(FileOff, SectorSize);
591 }
592 
593 // Visits all sections to assign incremental, non-overlapping RVAs and
594 // file offsets.
595 void Writer::assignAddresses() {
596   SizeOfHeaders = DOSStubSize + sizeof(PEMagic) + sizeof(coff_file_header) +
597                   sizeof(data_directory) * NumberfOfDataDirectory +
598                   sizeof(coff_section) * OutputSections.size();
599   SizeOfHeaders +=
600       Config->is64() ? sizeof(pe32plus_header) : sizeof(pe32_header);
601   SizeOfHeaders = alignTo(SizeOfHeaders, SectorSize);
602   uint64_t RVA = 0x1000; // The first page is kept unmapped.
603   FileSize = SizeOfHeaders;
604   // Move DISCARDABLE (or non-memory-mapped) sections to the end of file because
605   // the loader cannot handle holes.
606   std::stable_partition(
607       OutputSections.begin(), OutputSections.end(), [](OutputSection *S) {
608         return (S->getPermissions() & IMAGE_SCN_MEM_DISCARDABLE) == 0;
609       });
610   for (OutputSection *Sec : OutputSections) {
611     if (Sec->getName() == ".reloc")
612       addBaserels(Sec);
613     Sec->setRVA(RVA);
614     Sec->setFileOffset(FileSize);
615     RVA += alignTo(Sec->getVirtualSize(), PageSize);
616     FileSize += alignTo(Sec->getRawSize(), SectorSize);
617   }
618   SizeOfImage = alignTo(RVA, PageSize);
619 }
620 
621 template <typename PEHeaderTy> void Writer::writeHeader() {
622   // Write DOS stub
623   uint8_t *Buf = Buffer->getBufferStart();
624   auto *DOS = reinterpret_cast<dos_header *>(Buf);
625   Buf += DOSStubSize;
626   DOS->Magic[0] = 'M';
627   DOS->Magic[1] = 'Z';
628   DOS->AddressOfRelocationTable = sizeof(dos_header);
629   DOS->AddressOfNewExeHeader = DOSStubSize;
630 
631   // Write PE magic
632   memcpy(Buf, PEMagic, sizeof(PEMagic));
633   Buf += sizeof(PEMagic);
634 
635   // Write COFF header
636   auto *COFF = reinterpret_cast<coff_file_header *>(Buf);
637   Buf += sizeof(*COFF);
638   COFF->Machine = Config->Machine;
639   COFF->NumberOfSections = OutputSections.size();
640   COFF->Characteristics = IMAGE_FILE_EXECUTABLE_IMAGE;
641   if (Config->LargeAddressAware)
642     COFF->Characteristics |= IMAGE_FILE_LARGE_ADDRESS_AWARE;
643   if (!Config->is64())
644     COFF->Characteristics |= IMAGE_FILE_32BIT_MACHINE;
645   if (Config->DLL)
646     COFF->Characteristics |= IMAGE_FILE_DLL;
647   if (!Config->Relocatable)
648     COFF->Characteristics |= IMAGE_FILE_RELOCS_STRIPPED;
649   COFF->SizeOfOptionalHeader =
650       sizeof(PEHeaderTy) + sizeof(data_directory) * NumberfOfDataDirectory;
651 
652   // Write PE header
653   auto *PE = reinterpret_cast<PEHeaderTy *>(Buf);
654   Buf += sizeof(*PE);
655   PE->Magic = Config->is64() ? PE32Header::PE32_PLUS : PE32Header::PE32;
656 
657   // If {Major,Minor}LinkerVersion is left at 0.0, then for some
658   // reason signing the resulting PE file with Authenticode produces a
659   // signature that fails to validate on Windows 7 (but is OK on 10).
660   // Set it to 14.0, which is what VS2015 outputs, and which avoids
661   // that problem.
662   PE->MajorLinkerVersion = 14;
663   PE->MinorLinkerVersion = 0;
664 
665   PE->ImageBase = Config->ImageBase;
666   PE->SectionAlignment = PageSize;
667   PE->FileAlignment = SectorSize;
668   PE->MajorImageVersion = Config->MajorImageVersion;
669   PE->MinorImageVersion = Config->MinorImageVersion;
670   PE->MajorOperatingSystemVersion = Config->MajorOSVersion;
671   PE->MinorOperatingSystemVersion = Config->MinorOSVersion;
672   PE->MajorSubsystemVersion = Config->MajorOSVersion;
673   PE->MinorSubsystemVersion = Config->MinorOSVersion;
674   PE->Subsystem = Config->Subsystem;
675   PE->SizeOfImage = SizeOfImage;
676   PE->SizeOfHeaders = SizeOfHeaders;
677   if (!Config->NoEntry) {
678     Defined *Entry = cast<Defined>(Config->Entry);
679     PE->AddressOfEntryPoint = Entry->getRVA();
680     // Pointer to thumb code must have the LSB set, so adjust it.
681     if (Config->Machine == ARMNT)
682       PE->AddressOfEntryPoint |= 1;
683   }
684   PE->SizeOfStackReserve = Config->StackReserve;
685   PE->SizeOfStackCommit = Config->StackCommit;
686   PE->SizeOfHeapReserve = Config->HeapReserve;
687   PE->SizeOfHeapCommit = Config->HeapCommit;
688   if (Config->AppContainer)
689     PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_APPCONTAINER;
690   if (Config->DynamicBase)
691     PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE;
692   if (Config->HighEntropyVA)
693     PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA;
694   if (!Config->AllowBind)
695     PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_BIND;
696   if (Config->NxCompat)
697     PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NX_COMPAT;
698   if (!Config->AllowIsolation)
699     PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_ISOLATION;
700   if (Config->TerminalServerAware)
701     PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_TERMINAL_SERVER_AWARE;
702   PE->NumberOfRvaAndSize = NumberfOfDataDirectory;
703   if (OutputSection *Text = findSection(".text")) {
704     PE->BaseOfCode = Text->getRVA();
705     PE->SizeOfCode = Text->getRawSize();
706   }
707   PE->SizeOfInitializedData = getSizeOfInitializedData();
708 
709   // Write data directory
710   auto *Dir = reinterpret_cast<data_directory *>(Buf);
711   Buf += sizeof(*Dir) * NumberfOfDataDirectory;
712   if (OutputSection *Sec = findSection(".edata")) {
713     Dir[EXPORT_TABLE].RelativeVirtualAddress = Sec->getRVA();
714     Dir[EXPORT_TABLE].Size = Sec->getVirtualSize();
715   }
716   if (!Idata.empty()) {
717     Dir[IMPORT_TABLE].RelativeVirtualAddress = Idata.getDirRVA();
718     Dir[IMPORT_TABLE].Size = Idata.getDirSize();
719     Dir[IAT].RelativeVirtualAddress = Idata.getIATRVA();
720     Dir[IAT].Size = Idata.getIATSize();
721   }
722   if (OutputSection *Sec = findSection(".rsrc")) {
723     Dir[RESOURCE_TABLE].RelativeVirtualAddress = Sec->getRVA();
724     Dir[RESOURCE_TABLE].Size = Sec->getVirtualSize();
725   }
726   if (OutputSection *Sec = findSection(".pdata")) {
727     Dir[EXCEPTION_TABLE].RelativeVirtualAddress = Sec->getRVA();
728     Dir[EXCEPTION_TABLE].Size = Sec->getVirtualSize();
729   }
730   if (OutputSection *Sec = findSection(".reloc")) {
731     Dir[BASE_RELOCATION_TABLE].RelativeVirtualAddress = Sec->getRVA();
732     Dir[BASE_RELOCATION_TABLE].Size = Sec->getVirtualSize();
733   }
734   if (Symbol *Sym = Symtab->findUnderscore("_tls_used")) {
735     if (Defined *B = dyn_cast<Defined>(Sym)) {
736       Dir[TLS_TABLE].RelativeVirtualAddress = B->getRVA();
737       Dir[TLS_TABLE].Size = Config->is64()
738                                 ? sizeof(object::coff_tls_directory64)
739                                 : sizeof(object::coff_tls_directory32);
740     }
741   }
742   if (Config->Debug) {
743     Dir[DEBUG_DIRECTORY].RelativeVirtualAddress = DebugDirectory->getRVA();
744     Dir[DEBUG_DIRECTORY].Size = DebugDirectory->getSize();
745   }
746   if (Symbol *Sym = Symtab->findUnderscore("_load_config_used")) {
747     if (auto *B = dyn_cast<DefinedRegular>(Sym)) {
748       SectionChunk *SC = B->getChunk();
749       assert(B->getRVA() >= SC->getRVA());
750       uint64_t OffsetInChunk = B->getRVA() - SC->getRVA();
751       if (!SC->hasData() || OffsetInChunk + 4 > SC->getSize())
752         fatal("_load_config_used is malformed");
753 
754       ArrayRef<uint8_t> SecContents = SC->getContents();
755       uint32_t LoadConfigSize =
756           *reinterpret_cast<const ulittle32_t *>(&SecContents[OffsetInChunk]);
757       if (OffsetInChunk + LoadConfigSize > SC->getSize())
758         fatal("_load_config_used is too large");
759       Dir[LOAD_CONFIG_TABLE].RelativeVirtualAddress = B->getRVA();
760       Dir[LOAD_CONFIG_TABLE].Size = LoadConfigSize;
761     }
762   }
763   if (!DelayIdata.empty()) {
764     Dir[DELAY_IMPORT_DESCRIPTOR].RelativeVirtualAddress =
765         DelayIdata.getDirRVA();
766     Dir[DELAY_IMPORT_DESCRIPTOR].Size = DelayIdata.getDirSize();
767   }
768 
769   // Write section table
770   for (OutputSection *Sec : OutputSections) {
771     Sec->writeHeaderTo(Buf);
772     Buf += sizeof(coff_section);
773   }
774   SectionTable = ArrayRef<uint8_t>(
775       Buf - OutputSections.size() * sizeof(coff_section), Buf);
776 
777   if (OutputSymtab.empty())
778     return;
779 
780   COFF->PointerToSymbolTable = PointerToSymbolTable;
781   uint32_t NumberOfSymbols = OutputSymtab.size();
782   COFF->NumberOfSymbols = NumberOfSymbols;
783   auto *SymbolTable = reinterpret_cast<coff_symbol16 *>(
784       Buffer->getBufferStart() + COFF->PointerToSymbolTable);
785   for (size_t I = 0; I != NumberOfSymbols; ++I)
786     SymbolTable[I] = OutputSymtab[I];
787   // Create the string table, it follows immediately after the symbol table.
788   // The first 4 bytes is length including itself.
789   Buf = reinterpret_cast<uint8_t *>(&SymbolTable[NumberOfSymbols]);
790   write32le(Buf, Strtab.size() + 4);
791   if (!Strtab.empty())
792     memcpy(Buf + 4, Strtab.data(), Strtab.size());
793 }
794 
795 void Writer::openFile(StringRef Path) {
796   Buffer = check(
797       FileOutputBuffer::create(Path, FileSize, FileOutputBuffer::F_executable),
798       "failed to open " + Path);
799 }
800 
801 void Writer::fixSafeSEHSymbols() {
802   if (!SEHTable)
803     return;
804   // Replace the absolute table symbol with a synthetic symbol pointing to the
805   // SEHTable chunk so that we can emit base relocations for it and resolve
806   // section relative relocations.
807   Symbol *T = Symtab->find("___safe_se_handler_table");
808   Symbol *C = Symtab->find("___safe_se_handler_count");
809   replaceSymbol<DefinedSynthetic>(T, T->getName(), SEHTable);
810   cast<DefinedAbsolute>(C)->setVA(SEHTable->getSize() / 4);
811 }
812 
813 // Handles /section options to allow users to overwrite
814 // section attributes.
815 void Writer::setSectionPermissions() {
816   for (auto &P : Config->Section) {
817     StringRef Name = P.first;
818     uint32_t Perm = P.second;
819     if (auto *Sec = findSection(Name))
820       Sec->setPermissions(Perm);
821   }
822 }
823 
824 // Write section contents to a mmap'ed file.
825 void Writer::writeSections() {
826   // Record the section index that should be used when resolving a section
827   // relocation against an absolute symbol.
828   DefinedAbsolute::OutputSectionIndex = OutputSections.size() + 1;
829 
830   uint8_t *Buf = Buffer->getBufferStart();
831   for (OutputSection *Sec : OutputSections) {
832     uint8_t *SecBuf = Buf + Sec->getFileOff();
833     // Fill gaps between functions in .text with INT3 instructions
834     // instead of leaving as NUL bytes (which can be interpreted as
835     // ADD instructions).
836     if (Sec->getPermissions() & IMAGE_SCN_CNT_CODE)
837       memset(SecBuf, 0xCC, Sec->getRawSize());
838     for_each(parallel::par, Sec->getChunks().begin(), Sec->getChunks().end(),
839              [&](Chunk *C) { C->writeTo(SecBuf); });
840   }
841 }
842 
843 void Writer::writeBuildId() {
844   // If we're not writing a build id (e.g. because /debug is not specified),
845   // then just return;
846   if (!Config->Debug)
847     return;
848 
849   assert(BuildId && "BuildId is not set!");
850 
851   if (PreviousBuildId.hasValue()) {
852     *BuildId->BuildId = *PreviousBuildId;
853     BuildId->BuildId->PDB70.Age = BuildId->BuildId->PDB70.Age + 1;
854     return;
855   }
856 
857   BuildId->BuildId->Signature.CVSignature = OMF::Signature::PDB70;
858   BuildId->BuildId->PDB70.Age = 1;
859   llvm::getRandomBytes(BuildId->BuildId->PDB70.Signature, 16);
860 }
861 
862 // Sort .pdata section contents according to PE/COFF spec 5.5.
863 void Writer::sortExceptionTable() {
864   OutputSection *Sec = findSection(".pdata");
865   if (!Sec)
866     return;
867   // We assume .pdata contains function table entries only.
868   uint8_t *Begin = Buffer->getBufferStart() + Sec->getFileOff();
869   uint8_t *End = Begin + Sec->getVirtualSize();
870   if (Config->Machine == AMD64) {
871     struct Entry { ulittle32_t Begin, End, Unwind; };
872     sort(parallel::par, (Entry *)Begin, (Entry *)End,
873          [](const Entry &A, const Entry &B) { return A.Begin < B.Begin; });
874     return;
875   }
876   if (Config->Machine == ARMNT) {
877     struct Entry { ulittle32_t Begin, Unwind; };
878     sort(parallel::par, (Entry *)Begin, (Entry *)End,
879          [](const Entry &A, const Entry &B) { return A.Begin < B.Begin; });
880     return;
881   }
882   errs() << "warning: don't know how to handle .pdata.\n";
883 }
884 
885 OutputSection *Writer::findSection(StringRef Name) {
886   for (OutputSection *Sec : OutputSections)
887     if (Sec->getName() == Name)
888       return Sec;
889   return nullptr;
890 }
891 
892 uint32_t Writer::getSizeOfInitializedData() {
893   uint32_t Res = 0;
894   for (OutputSection *S : OutputSections)
895     if (S->getPermissions() & IMAGE_SCN_CNT_INITIALIZED_DATA)
896       Res += S->getRawSize();
897   return Res;
898 }
899 
900 // Returns an existing section or create a new one if not found.
901 OutputSection *Writer::createSection(StringRef Name) {
902   if (auto *Sec = findSection(Name))
903     return Sec;
904   const auto DATA = IMAGE_SCN_CNT_INITIALIZED_DATA;
905   const auto BSS = IMAGE_SCN_CNT_UNINITIALIZED_DATA;
906   const auto CODE = IMAGE_SCN_CNT_CODE;
907   const auto DISCARDABLE = IMAGE_SCN_MEM_DISCARDABLE;
908   const auto R = IMAGE_SCN_MEM_READ;
909   const auto W = IMAGE_SCN_MEM_WRITE;
910   const auto X = IMAGE_SCN_MEM_EXECUTE;
911   uint32_t Perms = StringSwitch<uint32_t>(Name)
912                        .Case(".bss", BSS | R | W)
913                        .Case(".data", DATA | R | W)
914                        .Cases(".didat", ".edata", ".idata", ".rdata", DATA | R)
915                        .Case(".reloc", DATA | DISCARDABLE | R)
916                        .Case(".text", CODE | R | X)
917                        .Default(0);
918   if (!Perms)
919     llvm_unreachable("unknown section name");
920   auto Sec = make<OutputSection>(Name);
921   Sec->addPermissions(Perms);
922   OutputSections.push_back(Sec);
923   return Sec;
924 }
925 
926 // Dest is .reloc section. Add contents to that section.
927 void Writer::addBaserels(OutputSection *Dest) {
928   std::vector<Baserel> V;
929   for (OutputSection *Sec : OutputSections) {
930     if (Sec == Dest)
931       continue;
932     // Collect all locations for base relocations.
933     for (Chunk *C : Sec->getChunks())
934       C->getBaserels(&V);
935     // Add the addresses to .reloc section.
936     if (!V.empty())
937       addBaserelBlocks(Dest, V);
938     V.clear();
939   }
940 }
941 
942 // Add addresses to .reloc section. Note that addresses are grouped by page.
943 void Writer::addBaserelBlocks(OutputSection *Dest, std::vector<Baserel> &V) {
944   const uint32_t Mask = ~uint32_t(PageSize - 1);
945   uint32_t Page = V[0].RVA & Mask;
946   size_t I = 0, J = 1;
947   for (size_t E = V.size(); J < E; ++J) {
948     uint32_t P = V[J].RVA & Mask;
949     if (P == Page)
950       continue;
951     Dest->addChunk(make<BaserelChunk>(Page, &V[I], &V[0] + J));
952     I = J;
953     Page = P;
954   }
955   if (I == J)
956     return;
957   Dest->addChunk(make<BaserelChunk>(Page, &V[I], &V[0] + J));
958 }
959