xref: /llvm-project-15.0.7/lld/COFF/Writer.cpp (revision e00799ea)
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/Path.h"
30 #include "llvm/Support/RandomNumberGenerator.h"
31 #include "llvm/Support/xxhash.h"
32 #include <algorithm>
33 #include <cstdio>
34 #include <map>
35 #include <memory>
36 #include <utility>
37 
38 using namespace llvm;
39 using namespace llvm::COFF;
40 using namespace llvm::object;
41 using namespace llvm::support;
42 using namespace llvm::support::endian;
43 using namespace lld;
44 using namespace lld::coff;
45 
46 /* To re-generate DOSProgram:
47 $ cat > /tmp/DOSProgram.asm
48 org 0
49         ; Copy cs to ds.
50         push cs
51         pop ds
52         ; Point ds:dx at the $-terminated string.
53         mov dx, str
54         ; Int 21/AH=09h: Write string to standard output.
55         mov ah, 0x9
56         int 0x21
57         ; Int 21/AH=4Ch: Exit with return code (in AL).
58         mov ax, 0x4C01
59         int 0x21
60 str:
61         db 'This program cannot be run in DOS mode.$'
62 align 8, db 0
63 $ nasm -fbin /tmp/DOSProgram.asm -o /tmp/DOSProgram.bin
64 $ xxd -i /tmp/DOSProgram.bin
65 */
66 static unsigned char DOSProgram[] = {
67   0x0e, 0x1f, 0xba, 0x0e, 0x00, 0xb4, 0x09, 0xcd, 0x21, 0xb8, 0x01, 0x4c,
68   0xcd, 0x21, 0x54, 0x68, 0x69, 0x73, 0x20, 0x70, 0x72, 0x6f, 0x67, 0x72,
69   0x61, 0x6d, 0x20, 0x63, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x20, 0x62, 0x65,
70   0x20, 0x72, 0x75, 0x6e, 0x20, 0x69, 0x6e, 0x20, 0x44, 0x4f, 0x53, 0x20,
71   0x6d, 0x6f, 0x64, 0x65, 0x2e, 0x24, 0x00, 0x00
72 };
73 static_assert(sizeof(DOSProgram) % 8 == 0,
74               "DOSProgram size must be multiple of 8");
75 
76 static const int SectorSize = 512;
77 static const int DOSStubSize = sizeof(dos_header) + sizeof(DOSProgram);
78 static_assert(DOSStubSize % 8 == 0, "DOSStub size must be multiple of 8");
79 
80 static const int NumberfOfDataDirectory = 16;
81 
82 namespace {
83 
84 class DebugDirectoryChunk : public Chunk {
85 public:
86   DebugDirectoryChunk(const std::vector<Chunk *> &R) : Records(R) {}
87 
88   size_t getSize() const override {
89     return Records.size() * sizeof(debug_directory);
90   }
91 
92   void writeTo(uint8_t *B) const override {
93     auto *D = reinterpret_cast<debug_directory *>(B + OutputSectionOff);
94 
95     for (const Chunk *Record : Records) {
96       D->Characteristics = 0;
97       D->TimeDateStamp = 0;
98       D->MajorVersion = 0;
99       D->MinorVersion = 0;
100       D->Type = COFF::IMAGE_DEBUG_TYPE_CODEVIEW;
101       D->SizeOfData = Record->getSize();
102       D->AddressOfRawData = Record->getRVA();
103       OutputSection *OS = Record->getOutputSection();
104       uint64_t Offs = OS->getFileOff() + (Record->getRVA() - OS->getRVA());
105       D->PointerToRawData = Offs;
106 
107       TimeDateStamps.push_back(&D->TimeDateStamp);
108       ++D;
109     }
110   }
111 
112   void setTimeDateStamp(uint32_t TimeDateStamp) {
113     for (support::ulittle32_t *TDS : TimeDateStamps)
114       *TDS = TimeDateStamp;
115   }
116 
117 private:
118   mutable std::vector<support::ulittle32_t *> TimeDateStamps;
119   const std::vector<Chunk *> &Records;
120 };
121 
122 class CVDebugRecordChunk : public Chunk {
123 public:
124   CVDebugRecordChunk() {
125     PDBAbsPath = Config->PDBPath;
126     if (!PDBAbsPath.empty())
127       llvm::sys::fs::make_absolute(PDBAbsPath);
128   }
129 
130   size_t getSize() const override {
131     return sizeof(codeview::DebugInfo) + PDBAbsPath.size() + 1;
132   }
133 
134   void writeTo(uint8_t *B) const override {
135     // Save off the DebugInfo entry to backfill the file signature (build id)
136     // in Writer::writeBuildId
137     BuildId = reinterpret_cast<codeview::DebugInfo *>(B + OutputSectionOff);
138 
139     // variable sized field (PDB Path)
140     char *P = reinterpret_cast<char *>(B + OutputSectionOff + sizeof(*BuildId));
141     if (!PDBAbsPath.empty())
142       memcpy(P, PDBAbsPath.data(), PDBAbsPath.size());
143     P[PDBAbsPath.size()] = '\0';
144   }
145 
146   SmallString<128> PDBAbsPath;
147   mutable codeview::DebugInfo *BuildId = nullptr;
148 };
149 
150 // The writer writes a SymbolTable result to a file.
151 class Writer {
152 public:
153   Writer() : Buffer(errorHandler().OutputBuffer) {}
154   void run();
155 
156 private:
157   void createSections();
158   void createMiscChunks();
159   void createImportTables();
160   void createExportTable();
161   void assignAddresses();
162   void removeEmptySections();
163   void createSymbolAndStringTable();
164   void openFile(StringRef OutputPath);
165   template <typename PEHeaderTy> void writeHeader();
166   void createSEHTable(OutputSection *RData);
167   void createGuardCFTables(OutputSection *RData);
168   void createGLJmpTable(OutputSection *RData);
169   void markSymbolsForRVATable(ObjFile *File,
170                               ArrayRef<SectionChunk *> SymIdxChunks,
171                               SymbolRVASet &TableSymbols);
172   void maybeAddRVATable(OutputSection *RData, SymbolRVASet TableSymbols,
173                         StringRef TableSym, StringRef CountSym);
174   void setSectionPermissions();
175   void writeSections();
176   void writeBuildId();
177   void sortExceptionTable();
178 
179   llvm::Optional<coff_symbol16> createSymbol(Defined *D);
180   size_t addEntryToStringTable(StringRef Str);
181 
182   OutputSection *findSection(StringRef Name);
183   OutputSection *createSection(StringRef Name);
184   void addBaserels(OutputSection *Dest);
185   void addBaserelBlocks(OutputSection *Dest, std::vector<Baserel> &V);
186 
187   uint32_t getSizeOfInitializedData();
188   std::map<StringRef, std::vector<DefinedImportData *>> binImports();
189 
190   std::unique_ptr<FileOutputBuffer> &Buffer;
191   std::vector<OutputSection *> OutputSections;
192   std::vector<char> Strtab;
193   std::vector<llvm::object::coff_symbol16> OutputSymtab;
194   IdataContents Idata;
195   DelayLoadContents DelayIdata;
196   EdataContents Edata;
197   RVATableChunk *GuardFidsTable = nullptr;
198   RVATableChunk *SEHTable = nullptr;
199 
200   DebugDirectoryChunk *DebugDirectory = nullptr;
201   std::vector<Chunk *> DebugRecords;
202   CVDebugRecordChunk *BuildId = nullptr;
203   Optional<codeview::DebugInfo> PreviousBuildId;
204   ArrayRef<uint8_t> SectionTable;
205 
206   uint64_t FileSize;
207   uint32_t PointerToSymbolTable = 0;
208   uint64_t SizeOfImage;
209   uint64_t SizeOfHeaders;
210 };
211 } // anonymous namespace
212 
213 namespace lld {
214 namespace coff {
215 
216 static Timer CodeLayoutTimer("Code Layout", Timer::root());
217 static Timer DiskCommitTimer("Commit Output File", Timer::root());
218 
219 void writeResult() { Writer().run(); }
220 
221 void OutputSection::addChunk(Chunk *C) {
222   Chunks.push_back(C);
223   C->setOutputSection(this);
224 }
225 
226 void OutputSection::addPermissions(uint32_t C) {
227   Header.Characteristics |= C & PermMask;
228 }
229 
230 void OutputSection::setPermissions(uint32_t C) {
231   Header.Characteristics = C & PermMask;
232 }
233 
234 // Write the section header to a given buffer.
235 void OutputSection::writeHeaderTo(uint8_t *Buf) {
236   auto *Hdr = reinterpret_cast<coff_section *>(Buf);
237   *Hdr = Header;
238   if (StringTableOff) {
239     // If name is too long, write offset into the string table as a name.
240     sprintf(Hdr->Name, "/%d", StringTableOff);
241   } else {
242     assert(!Config->Debug || Name.size() <= COFF::NameSize ||
243            (Hdr->Characteristics & IMAGE_SCN_MEM_DISCARDABLE) == 0);
244     strncpy(Hdr->Name, Name.data(),
245             std::min(Name.size(), (size_t)COFF::NameSize));
246   }
247 }
248 
249 } // namespace coff
250 } // namespace lld
251 
252 // PDBs are matched against executables using a build id which consists of three
253 // components:
254 //   1. A 16-bit GUID
255 //   2. An age
256 //   3. A time stamp.
257 //
258 // Debuggers and symbol servers match executables against debug info by checking
259 // each of these components of the EXE/DLL against the corresponding value in
260 // the PDB and failing a match if any of the components differ.  In the case of
261 // symbol servers, symbols are cached in a folder that is a function of the
262 // GUID.  As a result, in order to avoid symbol cache pollution where every
263 // incremental build copies a new PDB to the symbol cache, we must try to re-use
264 // the existing GUID if one exists, but bump the age.  This way the match will
265 // fail, so the symbol cache knows to use the new PDB, but the GUID matches, so
266 // it overwrites the existing item in the symbol cache rather than making a new
267 // one.
268 static Optional<codeview::DebugInfo> loadExistingBuildId(StringRef Path) {
269   // We don't need to incrementally update a previous build id if we're not
270   // writing codeview debug info.
271   if (!Config->Debug)
272     return None;
273 
274   auto ExpectedBinary = llvm::object::createBinary(Path);
275   if (!ExpectedBinary) {
276     consumeError(ExpectedBinary.takeError());
277     return None;
278   }
279 
280   auto Binary = std::move(*ExpectedBinary);
281   if (!Binary.getBinary()->isCOFF())
282     return None;
283 
284   std::error_code EC;
285   COFFObjectFile File(Binary.getBinary()->getMemoryBufferRef(), EC);
286   if (EC)
287     return None;
288 
289   // If the machine of the binary we're outputting doesn't match the machine
290   // of the existing binary, don't try to re-use the build id.
291   if (File.is64() != Config->is64() || File.getMachine() != Config->Machine)
292     return None;
293 
294   for (const auto &DebugDir : File.debug_directories()) {
295     if (DebugDir.Type != IMAGE_DEBUG_TYPE_CODEVIEW)
296       continue;
297 
298     const codeview::DebugInfo *ExistingDI = nullptr;
299     StringRef PDBFileName;
300     if (auto EC = File.getDebugPDBInfo(ExistingDI, PDBFileName)) {
301       (void)EC;
302       return None;
303     }
304     // We only support writing PDBs in v70 format.  So if this is not a build
305     // id that we recognize / support, ignore it.
306     if (ExistingDI->Signature.CVSignature != OMF::Signature::PDB70)
307       return None;
308     return *ExistingDI;
309   }
310   return None;
311 }
312 
313 // The main function of the writer.
314 void Writer::run() {
315   ScopedTimer T1(CodeLayoutTimer);
316 
317   createSections();
318   createMiscChunks();
319   createImportTables();
320   createExportTable();
321   if (Config->Relocatable)
322     createSection(".reloc");
323   assignAddresses();
324   removeEmptySections();
325   setSectionPermissions();
326   createSymbolAndStringTable();
327 
328   if (FileSize > UINT32_MAX)
329     fatal("image size (" + Twine(FileSize) + ") " +
330         "exceeds maximum allowable size (" + Twine(UINT32_MAX) + ")");
331 
332   // We must do this before opening the output file, as it depends on being able
333   // to read the contents of the existing output file.
334   PreviousBuildId = loadExistingBuildId(Config->OutputFile);
335   openFile(Config->OutputFile);
336   if (Config->is64()) {
337     writeHeader<pe32plus_header>();
338   } else {
339     writeHeader<pe32_header>();
340   }
341   writeSections();
342   sortExceptionTable();
343   writeBuildId();
344 
345   T1.stop();
346 
347   if (!Config->PDBPath.empty() && Config->Debug) {
348     assert(BuildId);
349     createPDB(Symtab, OutputSections, SectionTable, *BuildId->BuildId);
350   }
351 
352   writeMapFile(OutputSections);
353 
354   ScopedTimer T2(DiskCommitTimer);
355   if (auto E = Buffer->commit())
356     fatal("failed to write the output file: " + toString(std::move(E)));
357 }
358 
359 static StringRef getOutputSection(StringRef Name) {
360   StringRef S = Name.split('$').first;
361 
362   // Treat a later period as a separator for MinGW, for sections like
363   // ".ctors.01234".
364   S = S.substr(0, S.find('.', 1));
365 
366   auto It = Config->Merge.find(S);
367   if (It == Config->Merge.end())
368     return S;
369   return It->second;
370 }
371 
372 // For /order.
373 static void sortBySectionOrder(std::vector<Chunk *> &Chunks) {
374   auto GetPriority = [](const Chunk *C) {
375     if (auto *Sec = dyn_cast<SectionChunk>(C))
376       if (Sec->Sym)
377         return Config->Order.lookup(Sec->Sym->getName());
378     return 0;
379   };
380 
381   std::stable_sort(Chunks.begin(), Chunks.end(),
382                    [=](const Chunk *A, const Chunk *B) {
383                      return GetPriority(A) < GetPriority(B);
384                    });
385 }
386 
387 // Create output section objects and add them to OutputSections.
388 void Writer::createSections() {
389   // First, bin chunks by name.
390   std::map<StringRef, std::vector<Chunk *>> Map;
391   for (Chunk *C : Symtab->getChunks()) {
392     auto *SC = dyn_cast<SectionChunk>(C);
393     if (SC && !SC->isLive()) {
394       if (Config->Verbose)
395         SC->printDiscardedMessage();
396       continue;
397     }
398     Map[C->getSectionName()].push_back(C);
399   }
400 
401   // Process an /order option.
402   if (!Config->Order.empty())
403     for (auto &Pair : Map)
404       sortBySectionOrder(Pair.second);
405 
406   // Then create an OutputSection for each section.
407   // '$' and all following characters in input section names are
408   // discarded when determining output section. So, .text$foo
409   // contributes to .text, for example. See PE/COFF spec 3.2.
410   SmallDenseMap<StringRef, OutputSection *> Sections;
411   for (auto Pair : Map) {
412     StringRef Name = getOutputSection(Pair.first);
413     OutputSection *&Sec = Sections[Name];
414     if (!Sec) {
415       Sec = make<OutputSection>(Name);
416       OutputSections.push_back(Sec);
417     }
418     std::vector<Chunk *> &Chunks = Pair.second;
419     for (Chunk *C : Chunks) {
420       Sec->addChunk(C);
421       Sec->addPermissions(C->getPermissions());
422     }
423   }
424 }
425 
426 void Writer::createMiscChunks() {
427   OutputSection *RData = createSection(".rdata");
428 
429   for (auto &P : MergeChunk::Instances)
430     RData->addChunk(P.second);
431 
432   // Create thunks for locally-dllimported symbols.
433   if (!Symtab->LocalImportChunks.empty()) {
434     for (Chunk *C : Symtab->LocalImportChunks)
435       RData->addChunk(C);
436   }
437 
438   // Create Debug Information Chunks
439   if (Config->Debug) {
440     DebugDirectory = make<DebugDirectoryChunk>(DebugRecords);
441 
442     // Make a CVDebugRecordChunk even when /DEBUG:CV is not specified.  We
443     // output a PDB no matter what, and this chunk provides the only means of
444     // allowing a debugger to match a PDB and an executable.  So we need it even
445     // if we're ultimately not going to write CodeView data to the PDB.
446     auto *CVChunk = make<CVDebugRecordChunk>();
447     BuildId = CVChunk;
448     DebugRecords.push_back(CVChunk);
449 
450     RData->addChunk(DebugDirectory);
451     for (Chunk *C : DebugRecords)
452       RData->addChunk(C);
453   }
454 
455   // Create SEH table. x86-only.
456   if (Config->Machine == I386)
457     createSEHTable(RData);
458 
459   // Create /guard:cf tables if requested.
460   if (Config->GuardCF != GuardCFLevel::Off)
461     createGuardCFTables(RData);
462 }
463 
464 // Create .idata section for the DLL-imported symbol table.
465 // The format of this section is inherently Windows-specific.
466 // IdataContents class abstracted away the details for us,
467 // so we just let it create chunks and add them to the section.
468 void Writer::createImportTables() {
469   if (ImportFile::Instances.empty())
470     return;
471 
472   // Initialize DLLOrder so that import entries are ordered in
473   // the same order as in the command line. (That affects DLL
474   // initialization order, and this ordering is MSVC-compatible.)
475   for (ImportFile *File : ImportFile::Instances) {
476     if (!File->Live)
477       continue;
478 
479     std::string DLL = StringRef(File->DLLName).lower();
480     if (Config->DLLOrder.count(DLL) == 0)
481       Config->DLLOrder[DLL] = Config->DLLOrder.size();
482   }
483 
484   OutputSection *Text = createSection(".text");
485   for (ImportFile *File : ImportFile::Instances) {
486     if (!File->Live)
487       continue;
488 
489     if (DefinedImportThunk *Thunk = File->ThunkSym)
490       Text->addChunk(Thunk->getChunk());
491 
492     if (Config->DelayLoads.count(StringRef(File->DLLName).lower())) {
493       if (!File->ThunkSym)
494         fatal("cannot delay-load " + toString(File) +
495               " due to import of data: " + toString(*File->ImpSym));
496       DelayIdata.add(File->ImpSym);
497     } else {
498       Idata.add(File->ImpSym);
499     }
500   }
501 
502   if (!Idata.empty()) {
503     OutputSection *Sec = createSection(".idata");
504     for (Chunk *C : Idata.getChunks())
505       Sec->addChunk(C);
506   }
507 
508   if (!DelayIdata.empty()) {
509     Defined *Helper = cast<Defined>(Config->DelayLoadHelper);
510     DelayIdata.create(Helper);
511     OutputSection *Sec = createSection(".didat");
512     for (Chunk *C : DelayIdata.getChunks())
513       Sec->addChunk(C);
514     Sec = createSection(".data");
515     for (Chunk *C : DelayIdata.getDataChunks())
516       Sec->addChunk(C);
517     Sec = createSection(".text");
518     for (Chunk *C : DelayIdata.getCodeChunks())
519       Sec->addChunk(C);
520   }
521 }
522 
523 void Writer::createExportTable() {
524   if (Config->Exports.empty())
525     return;
526   OutputSection *Sec = createSection(".edata");
527   for (Chunk *C : Edata.Chunks)
528     Sec->addChunk(C);
529 }
530 
531 // The Windows loader doesn't seem to like empty sections,
532 // so we remove them if any.
533 void Writer::removeEmptySections() {
534   auto IsEmpty = [](OutputSection *S) { return S->getVirtualSize() == 0; };
535   OutputSections.erase(
536       std::remove_if(OutputSections.begin(), OutputSections.end(), IsEmpty),
537       OutputSections.end());
538   uint32_t Idx = 1;
539   for (OutputSection *Sec : OutputSections)
540     Sec->SectionIndex = Idx++;
541 }
542 
543 size_t Writer::addEntryToStringTable(StringRef Str) {
544   assert(Str.size() > COFF::NameSize);
545   size_t OffsetOfEntry = Strtab.size() + 4; // +4 for the size field
546   Strtab.insert(Strtab.end(), Str.begin(), Str.end());
547   Strtab.push_back('\0');
548   return OffsetOfEntry;
549 }
550 
551 Optional<coff_symbol16> Writer::createSymbol(Defined *Def) {
552   // Relative symbols are unrepresentable in a COFF symbol table.
553   if (isa<DefinedSynthetic>(Def))
554     return None;
555 
556   // Don't write dead symbols or symbols in codeview sections to the symbol
557   // table.
558   if (!Def->isLive())
559     return None;
560   if (auto *D = dyn_cast<DefinedRegular>(Def))
561     if (D->getChunk()->isCodeView())
562       return None;
563 
564   coff_symbol16 Sym;
565   StringRef Name = Def->getName();
566   if (Name.size() > COFF::NameSize) {
567     Sym.Name.Offset.Zeroes = 0;
568     Sym.Name.Offset.Offset = addEntryToStringTable(Name);
569   } else {
570     memset(Sym.Name.ShortName, 0, COFF::NameSize);
571     memcpy(Sym.Name.ShortName, Name.data(), Name.size());
572   }
573 
574   if (auto *D = dyn_cast<DefinedCOFF>(Def)) {
575     COFFSymbolRef Ref = D->getCOFFSymbol();
576     Sym.Type = Ref.getType();
577     Sym.StorageClass = Ref.getStorageClass();
578   } else {
579     Sym.Type = IMAGE_SYM_TYPE_NULL;
580     Sym.StorageClass = IMAGE_SYM_CLASS_EXTERNAL;
581   }
582   Sym.NumberOfAuxSymbols = 0;
583 
584   switch (Def->kind()) {
585   case Symbol::DefinedAbsoluteKind:
586     Sym.Value = Def->getRVA();
587     Sym.SectionNumber = IMAGE_SYM_ABSOLUTE;
588     break;
589   default: {
590     uint64_t RVA = Def->getRVA();
591     OutputSection *Sec = nullptr;
592     for (OutputSection *S : OutputSections) {
593       if (S->getRVA() > RVA)
594         break;
595       Sec = S;
596     }
597     Sym.Value = RVA - Sec->getRVA();
598     Sym.SectionNumber = Sec->SectionIndex;
599     break;
600   }
601   }
602   return Sym;
603 }
604 
605 void Writer::createSymbolAndStringTable() {
606   // PE/COFF images are limited to 8 byte section names. Longer names can be
607   // supported by writing a non-standard string table, but this string table is
608   // not mapped at runtime and the long names will therefore be inaccessible.
609   // link.exe always truncates section names to 8 bytes, whereas binutils always
610   // preserves long section names via the string table. LLD adopts a hybrid
611   // solution where discardable sections have long names preserved and
612   // non-discardable sections have their names truncated, to ensure that any
613   // section which is mapped at runtime also has its name mapped at runtime.
614   for (OutputSection *Sec : OutputSections) {
615     if (Sec->Name.size() <= COFF::NameSize)
616       continue;
617     if ((Sec->getPermissions() & IMAGE_SCN_MEM_DISCARDABLE) == 0)
618       continue;
619     Sec->setStringTableOff(addEntryToStringTable(Sec->Name));
620   }
621 
622   if (Config->DebugDwarf) {
623     for (ObjFile *File : ObjFile::Instances) {
624       for (Symbol *B : File->getSymbols()) {
625         auto *D = dyn_cast_or_null<Defined>(B);
626         if (!D || D->WrittenToSymtab)
627           continue;
628         D->WrittenToSymtab = true;
629 
630         if (Optional<coff_symbol16> Sym = createSymbol(D))
631           OutputSymtab.push_back(*Sym);
632       }
633     }
634   }
635 
636   if (OutputSymtab.empty() && Strtab.empty())
637     return;
638 
639   // We position the symbol table to be adjacent to the end of the last section.
640   uint64_t FileOff = FileSize;
641   PointerToSymbolTable = FileOff;
642   FileOff += OutputSymtab.size() * sizeof(coff_symbol16);
643   FileOff += 4 + Strtab.size();
644   FileSize = alignTo(FileOff, SectorSize);
645 }
646 
647 static int sectionIndex(OutputSection *S) {
648   // Move DISCARDABLE (or non-memory-mapped) sections to the end of file because
649   // the loader cannot handle holes.
650   if (S->getPermissions() & IMAGE_SCN_MEM_DISCARDABLE)
651     return 101;
652 
653   // Try to match the section order used by link.exe. In particular, it's
654   // important that .reloc comes last since it refers to RVA's of data in
655   // the previous sections. .rsrc should come late because its size may
656   // change by the Win32 UpdateResources() function, causing subsequent
657   // sections to move (see https://crbug.com/827082).
658   return StringSwitch<int>(S->Name)
659       .Case(".text", 1)
660       .Case(".bss", 2)
661       .Case(".rdata", 3)
662       .Case(".data", 4)
663       .Case(".pdata", 5)
664       .Case(".idata", 6)
665       .Case(".rsrc", 99)
666       .Case(".reloc", 100)
667       .Default(50); // Default to somewhere in the middle.
668 }
669 
670 // Visits all sections to assign incremental, non-overlapping RVAs and
671 // file offsets.
672 void Writer::assignAddresses() {
673   SizeOfHeaders = DOSStubSize + sizeof(PEMagic) + sizeof(coff_file_header) +
674                   sizeof(data_directory) * NumberfOfDataDirectory +
675                   sizeof(coff_section) * OutputSections.size();
676   SizeOfHeaders +=
677       Config->is64() ? sizeof(pe32plus_header) : sizeof(pe32_header);
678   SizeOfHeaders = alignTo(SizeOfHeaders, SectorSize);
679   uint64_t RVA = PageSize; // The first page is kept unmapped.
680   FileSize = SizeOfHeaders;
681 
682   // Reorder the sections.
683   std::stable_sort(OutputSections.begin(), OutputSections.end(),
684                    [](OutputSection *S, OutputSection *T) {
685                      return sectionIndex(S) < sectionIndex(T);
686                    });
687 
688   for (OutputSection *Sec : OutputSections) {
689     if (Sec->Name == ".reloc")
690       addBaserels(Sec);
691     uint64_t RawSize = 0, VirtualSize = 0;
692     Sec->Header.VirtualAddress = RVA;
693     for (Chunk *C : Sec->getChunks()) {
694       VirtualSize = alignTo(VirtualSize, C->Alignment);
695       C->setRVA(RVA + VirtualSize);
696       C->OutputSectionOff = VirtualSize;
697       C->finalizeContents();
698       VirtualSize += C->getSize();
699       if (C->hasData())
700         RawSize = alignTo(VirtualSize, SectorSize);
701     }
702     if (VirtualSize > UINT32_MAX)
703       error("section larger than 4 GiB: " + Sec->Name);
704     Sec->Header.VirtualSize = VirtualSize;
705     Sec->Header.SizeOfRawData = RawSize;
706     if (RawSize != 0)
707       Sec->Header.PointerToRawData = FileSize;
708     RVA += alignTo(VirtualSize, PageSize);
709     FileSize += alignTo(RawSize, SectorSize);
710   }
711   SizeOfImage = alignTo(RVA, PageSize);
712 }
713 
714 template <typename PEHeaderTy> void Writer::writeHeader() {
715   // Write DOS header. For backwards compatibility, the first part of a PE/COFF
716   // executable consists of an MS-DOS MZ executable. If the executable is run
717   // under DOS, that program gets run (usually to just print an error message).
718   // When run under Windows, the loader looks at AddressOfNewExeHeader and uses
719   // the PE header instead.
720   uint8_t *Buf = Buffer->getBufferStart();
721   auto *DOS = reinterpret_cast<dos_header *>(Buf);
722   Buf += sizeof(dos_header);
723   DOS->Magic[0] = 'M';
724   DOS->Magic[1] = 'Z';
725   DOS->UsedBytesInTheLastPage = DOSStubSize % 512;
726   DOS->FileSizeInPages = divideCeil(DOSStubSize, 512);
727   DOS->HeaderSizeInParagraphs = sizeof(dos_header) / 16;
728 
729   DOS->AddressOfRelocationTable = sizeof(dos_header);
730   DOS->AddressOfNewExeHeader = DOSStubSize;
731 
732   // Write DOS program.
733   memcpy(Buf, DOSProgram, sizeof(DOSProgram));
734   Buf += sizeof(DOSProgram);
735 
736   // Write PE magic
737   memcpy(Buf, PEMagic, sizeof(PEMagic));
738   Buf += sizeof(PEMagic);
739 
740   // Write COFF header
741   auto *COFF = reinterpret_cast<coff_file_header *>(Buf);
742   Buf += sizeof(*COFF);
743   COFF->Machine = Config->Machine;
744   COFF->NumberOfSections = OutputSections.size();
745   COFF->Characteristics = IMAGE_FILE_EXECUTABLE_IMAGE;
746   if (Config->LargeAddressAware)
747     COFF->Characteristics |= IMAGE_FILE_LARGE_ADDRESS_AWARE;
748   if (!Config->is64())
749     COFF->Characteristics |= IMAGE_FILE_32BIT_MACHINE;
750   if (Config->DLL)
751     COFF->Characteristics |= IMAGE_FILE_DLL;
752   if (!Config->Relocatable)
753     COFF->Characteristics |= IMAGE_FILE_RELOCS_STRIPPED;
754   COFF->SizeOfOptionalHeader =
755       sizeof(PEHeaderTy) + sizeof(data_directory) * NumberfOfDataDirectory;
756 
757   // Write PE header
758   auto *PE = reinterpret_cast<PEHeaderTy *>(Buf);
759   Buf += sizeof(*PE);
760   PE->Magic = Config->is64() ? PE32Header::PE32_PLUS : PE32Header::PE32;
761 
762   // If {Major,Minor}LinkerVersion is left at 0.0, then for some
763   // reason signing the resulting PE file with Authenticode produces a
764   // signature that fails to validate on Windows 7 (but is OK on 10).
765   // Set it to 14.0, which is what VS2015 outputs, and which avoids
766   // that problem.
767   PE->MajorLinkerVersion = 14;
768   PE->MinorLinkerVersion = 0;
769 
770   PE->ImageBase = Config->ImageBase;
771   PE->SectionAlignment = PageSize;
772   PE->FileAlignment = SectorSize;
773   PE->MajorImageVersion = Config->MajorImageVersion;
774   PE->MinorImageVersion = Config->MinorImageVersion;
775   PE->MajorOperatingSystemVersion = Config->MajorOSVersion;
776   PE->MinorOperatingSystemVersion = Config->MinorOSVersion;
777   PE->MajorSubsystemVersion = Config->MajorOSVersion;
778   PE->MinorSubsystemVersion = Config->MinorOSVersion;
779   PE->Subsystem = Config->Subsystem;
780   PE->SizeOfImage = SizeOfImage;
781   PE->SizeOfHeaders = SizeOfHeaders;
782   if (!Config->NoEntry) {
783     Defined *Entry = cast<Defined>(Config->Entry);
784     PE->AddressOfEntryPoint = Entry->getRVA();
785     // Pointer to thumb code must have the LSB set, so adjust it.
786     if (Config->Machine == ARMNT)
787       PE->AddressOfEntryPoint |= 1;
788   }
789   PE->SizeOfStackReserve = Config->StackReserve;
790   PE->SizeOfStackCommit = Config->StackCommit;
791   PE->SizeOfHeapReserve = Config->HeapReserve;
792   PE->SizeOfHeapCommit = Config->HeapCommit;
793   if (Config->AppContainer)
794     PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_APPCONTAINER;
795   if (Config->DynamicBase)
796     PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE;
797   if (Config->HighEntropyVA)
798     PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA;
799   if (!Config->AllowBind)
800     PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_BIND;
801   if (Config->NxCompat)
802     PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NX_COMPAT;
803   if (!Config->AllowIsolation)
804     PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_ISOLATION;
805   if (Config->GuardCF != GuardCFLevel::Off)
806     PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_GUARD_CF;
807   if (Config->Machine == I386 && !SEHTable &&
808       !Symtab->findUnderscore("_load_config_used"))
809     PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_NO_SEH;
810   if (Config->TerminalServerAware)
811     PE->DLLCharacteristics |= IMAGE_DLL_CHARACTERISTICS_TERMINAL_SERVER_AWARE;
812   PE->NumberOfRvaAndSize = NumberfOfDataDirectory;
813   if (OutputSection *Text = findSection(".text")) {
814     PE->BaseOfCode = Text->getRVA();
815     PE->SizeOfCode = Text->getRawSize();
816   }
817   PE->SizeOfInitializedData = getSizeOfInitializedData();
818 
819   // Write data directory
820   auto *Dir = reinterpret_cast<data_directory *>(Buf);
821   Buf += sizeof(*Dir) * NumberfOfDataDirectory;
822   if (OutputSection *Sec = findSection(".edata")) {
823     Dir[EXPORT_TABLE].RelativeVirtualAddress = Sec->getRVA();
824     Dir[EXPORT_TABLE].Size = Sec->getVirtualSize();
825   }
826   if (!Idata.empty()) {
827     Dir[IMPORT_TABLE].RelativeVirtualAddress = Idata.getDirRVA();
828     Dir[IMPORT_TABLE].Size = Idata.getDirSize();
829     Dir[IAT].RelativeVirtualAddress = Idata.getIATRVA();
830     Dir[IAT].Size = Idata.getIATSize();
831   }
832   if (OutputSection *Sec = findSection(".rsrc")) {
833     Dir[RESOURCE_TABLE].RelativeVirtualAddress = Sec->getRVA();
834     Dir[RESOURCE_TABLE].Size = Sec->getVirtualSize();
835   }
836   if (OutputSection *Sec = findSection(".pdata")) {
837     Dir[EXCEPTION_TABLE].RelativeVirtualAddress = Sec->getRVA();
838     Dir[EXCEPTION_TABLE].Size = Sec->getVirtualSize();
839   }
840   if (OutputSection *Sec = findSection(".reloc")) {
841     Dir[BASE_RELOCATION_TABLE].RelativeVirtualAddress = Sec->getRVA();
842     Dir[BASE_RELOCATION_TABLE].Size = Sec->getVirtualSize();
843   }
844   if (Symbol *Sym = Symtab->findUnderscore("_tls_used")) {
845     if (Defined *B = dyn_cast<Defined>(Sym)) {
846       Dir[TLS_TABLE].RelativeVirtualAddress = B->getRVA();
847       Dir[TLS_TABLE].Size = Config->is64()
848                                 ? sizeof(object::coff_tls_directory64)
849                                 : sizeof(object::coff_tls_directory32);
850     }
851   }
852   if (Config->Debug) {
853     Dir[DEBUG_DIRECTORY].RelativeVirtualAddress = DebugDirectory->getRVA();
854     Dir[DEBUG_DIRECTORY].Size = DebugDirectory->getSize();
855   }
856   if (Symbol *Sym = Symtab->findUnderscore("_load_config_used")) {
857     if (auto *B = dyn_cast<DefinedRegular>(Sym)) {
858       SectionChunk *SC = B->getChunk();
859       assert(B->getRVA() >= SC->getRVA());
860       uint64_t OffsetInChunk = B->getRVA() - SC->getRVA();
861       if (!SC->hasData() || OffsetInChunk + 4 > SC->getSize())
862         fatal("_load_config_used is malformed");
863 
864       ArrayRef<uint8_t> SecContents = SC->getContents();
865       uint32_t LoadConfigSize =
866           *reinterpret_cast<const ulittle32_t *>(&SecContents[OffsetInChunk]);
867       if (OffsetInChunk + LoadConfigSize > SC->getSize())
868         fatal("_load_config_used is too large");
869       Dir[LOAD_CONFIG_TABLE].RelativeVirtualAddress = B->getRVA();
870       Dir[LOAD_CONFIG_TABLE].Size = LoadConfigSize;
871     }
872   }
873   if (!DelayIdata.empty()) {
874     Dir[DELAY_IMPORT_DESCRIPTOR].RelativeVirtualAddress =
875         DelayIdata.getDirRVA();
876     Dir[DELAY_IMPORT_DESCRIPTOR].Size = DelayIdata.getDirSize();
877   }
878 
879   // Write section table
880   for (OutputSection *Sec : OutputSections) {
881     Sec->writeHeaderTo(Buf);
882     Buf += sizeof(coff_section);
883   }
884   SectionTable = ArrayRef<uint8_t>(
885       Buf - OutputSections.size() * sizeof(coff_section), Buf);
886 
887   if (OutputSymtab.empty() && Strtab.empty())
888     return;
889 
890   COFF->PointerToSymbolTable = PointerToSymbolTable;
891   uint32_t NumberOfSymbols = OutputSymtab.size();
892   COFF->NumberOfSymbols = NumberOfSymbols;
893   auto *SymbolTable = reinterpret_cast<coff_symbol16 *>(
894       Buffer->getBufferStart() + COFF->PointerToSymbolTable);
895   for (size_t I = 0; I != NumberOfSymbols; ++I)
896     SymbolTable[I] = OutputSymtab[I];
897   // Create the string table, it follows immediately after the symbol table.
898   // The first 4 bytes is length including itself.
899   Buf = reinterpret_cast<uint8_t *>(&SymbolTable[NumberOfSymbols]);
900   write32le(Buf, Strtab.size() + 4);
901   if (!Strtab.empty())
902     memcpy(Buf + 4, Strtab.data(), Strtab.size());
903 }
904 
905 void Writer::openFile(StringRef Path) {
906   Buffer = CHECK(
907       FileOutputBuffer::create(Path, FileSize, FileOutputBuffer::F_executable),
908       "failed to open " + Path);
909 }
910 
911 void Writer::createSEHTable(OutputSection *RData) {
912   SymbolRVASet Handlers;
913   for (ObjFile *File : ObjFile::Instances) {
914     // FIXME: We should error here instead of earlier unless /safeseh:no was
915     // passed.
916     if (!File->hasSafeSEH())
917       return;
918 
919     markSymbolsForRVATable(File, File->getSXDataChunks(), Handlers);
920   }
921 
922   maybeAddRVATable(RData, std::move(Handlers), "__safe_se_handler_table",
923                    "__safe_se_handler_count");
924 }
925 
926 // Add a symbol to an RVA set. Two symbols may have the same RVA, but an RVA set
927 // cannot contain duplicates. Therefore, the set is uniqued by Chunk and the
928 // symbol's offset into that Chunk.
929 static void addSymbolToRVASet(SymbolRVASet &RVASet, Defined *S) {
930   Chunk *C = S->getChunk();
931   if (auto *SC = dyn_cast<SectionChunk>(C))
932     C = SC->Repl; // Look through ICF replacement.
933   uint32_t Off = S->getRVA() - (C ? C->getRVA() : 0);
934   RVASet.insert({C, Off});
935 }
936 
937 // Visit all relocations from all section contributions of this object file and
938 // mark the relocation target as address-taken.
939 static void markSymbolsWithRelocations(ObjFile *File,
940                                        SymbolRVASet &UsedSymbols) {
941   for (Chunk *C : File->getChunks()) {
942     // We only care about live section chunks. Common chunks and other chunks
943     // don't generally contain relocations.
944     SectionChunk *SC = dyn_cast<SectionChunk>(C);
945     if (!SC || !SC->isLive())
946       continue;
947 
948     // Look for relocations in this section against symbols in executable output
949     // sections.
950     for (Symbol *Ref : SC->symbols()) {
951       // FIXME: Do further testing to see if the relocation type matters,
952       // especially for 32-bit where taking the address of something usually
953       // uses an absolute relocation instead of a relative one.
954       if (auto *D = dyn_cast_or_null<Defined>(Ref)) {
955         Chunk *RefChunk = D->getChunk();
956         OutputSection *OS = RefChunk ? RefChunk->getOutputSection() : nullptr;
957         if (OS && OS->getPermissions() & IMAGE_SCN_MEM_EXECUTE)
958           addSymbolToRVASet(UsedSymbols, D);
959       }
960     }
961   }
962 }
963 
964 // Create the guard function id table. This is a table of RVAs of all
965 // address-taken functions. It is sorted and uniqued, just like the safe SEH
966 // table.
967 void Writer::createGuardCFTables(OutputSection *RData) {
968   SymbolRVASet AddressTakenSyms;
969   SymbolRVASet LongJmpTargets;
970   for (ObjFile *File : ObjFile::Instances) {
971     // If the object was compiled with /guard:cf, the address taken symbols
972     // are in .gfids$y sections, and the longjmp targets are in .gljmp$y
973     // sections. If the object was not compiled with /guard:cf, we assume there
974     // were no setjmp targets, and that all code symbols with relocations are
975     // possibly address-taken.
976     if (File->hasGuardCF()) {
977       markSymbolsForRVATable(File, File->getGuardFidChunks(), AddressTakenSyms);
978       markSymbolsForRVATable(File, File->getGuardLJmpChunks(), LongJmpTargets);
979     } else {
980       markSymbolsWithRelocations(File, AddressTakenSyms);
981     }
982   }
983 
984   // Mark the image entry as address-taken.
985   if (Config->Entry)
986     addSymbolToRVASet(AddressTakenSyms, cast<Defined>(Config->Entry));
987 
988   maybeAddRVATable(RData, std::move(AddressTakenSyms), "__guard_fids_table",
989                    "__guard_fids_count");
990 
991   // Add the longjmp target table unless the user told us not to.
992   if (Config->GuardCF == GuardCFLevel::Full)
993     maybeAddRVATable(RData, std::move(LongJmpTargets), "__guard_longjmp_table",
994                      "__guard_longjmp_count");
995 
996   // Set __guard_flags, which will be used in the load config to indicate that
997   // /guard:cf was enabled.
998   uint32_t GuardFlags = uint32_t(coff_guard_flags::CFInstrumented) |
999                         uint32_t(coff_guard_flags::HasFidTable);
1000   if (Config->GuardCF == GuardCFLevel::Full)
1001     GuardFlags |= uint32_t(coff_guard_flags::HasLongJmpTable);
1002   Symbol *FlagSym = Symtab->findUnderscore("__guard_flags");
1003   cast<DefinedAbsolute>(FlagSym)->setVA(GuardFlags);
1004 }
1005 
1006 // Take a list of input sections containing symbol table indices and add those
1007 // symbols to an RVA table. The challenge is that symbol RVAs are not known and
1008 // depend on the table size, so we can't directly build a set of integers.
1009 void Writer::markSymbolsForRVATable(ObjFile *File,
1010                                     ArrayRef<SectionChunk *> SymIdxChunks,
1011                                     SymbolRVASet &TableSymbols) {
1012   for (SectionChunk *C : SymIdxChunks) {
1013     // Skip sections discarded by linker GC. This comes up when a .gfids section
1014     // is associated with something like a vtable and the vtable is discarded.
1015     // In this case, the associated gfids section is discarded, and we don't
1016     // mark the virtual member functions as address-taken by the vtable.
1017     if (!C->isLive())
1018       continue;
1019 
1020     // Validate that the contents look like symbol table indices.
1021     ArrayRef<uint8_t> Data = C->getContents();
1022     if (Data.size() % 4 != 0) {
1023       warn("ignoring " + C->getSectionName() +
1024            " symbol table index section in object " + toString(File));
1025       continue;
1026     }
1027 
1028     // Read each symbol table index and check if that symbol was included in the
1029     // final link. If so, add it to the table symbol set.
1030     ArrayRef<ulittle32_t> SymIndices(
1031         reinterpret_cast<const ulittle32_t *>(Data.data()), Data.size() / 4);
1032     ArrayRef<Symbol *> ObjSymbols = File->getSymbols();
1033     for (uint32_t SymIndex : SymIndices) {
1034       if (SymIndex >= ObjSymbols.size()) {
1035         warn("ignoring invalid symbol table index in section " +
1036              C->getSectionName() + " in object " + toString(File));
1037         continue;
1038       }
1039       if (Symbol *S = ObjSymbols[SymIndex]) {
1040         if (S->isLive())
1041           addSymbolToRVASet(TableSymbols, cast<Defined>(S));
1042       }
1043     }
1044   }
1045 }
1046 
1047 // Replace the absolute table symbol with a synthetic symbol pointing to
1048 // TableChunk so that we can emit base relocations for it and resolve section
1049 // relative relocations.
1050 void Writer::maybeAddRVATable(OutputSection *RData,
1051                               SymbolRVASet TableSymbols,
1052                               StringRef TableSym, StringRef CountSym) {
1053   if (TableSymbols.empty())
1054     return;
1055 
1056   RVATableChunk *TableChunk = make<RVATableChunk>(std::move(TableSymbols));
1057   RData->addChunk(TableChunk);
1058 
1059   Symbol *T = Symtab->findUnderscore(TableSym);
1060   Symbol *C = Symtab->findUnderscore(CountSym);
1061   replaceSymbol<DefinedSynthetic>(T, T->getName(), TableChunk);
1062   cast<DefinedAbsolute>(C)->setVA(TableChunk->getSize() / 4);
1063 }
1064 
1065 // Handles /section options to allow users to overwrite
1066 // section attributes.
1067 void Writer::setSectionPermissions() {
1068   for (auto &P : Config->Section) {
1069     StringRef Name = P.first;
1070     uint32_t Perm = P.second;
1071     if (auto *Sec = findSection(Name))
1072       Sec->setPermissions(Perm);
1073   }
1074 }
1075 
1076 // Write section contents to a mmap'ed file.
1077 void Writer::writeSections() {
1078   // Record the number of sections to apply section index relocations
1079   // against absolute symbols. See applySecIdx in Chunks.cpp..
1080   DefinedAbsolute::NumOutputSections = OutputSections.size();
1081 
1082   uint8_t *Buf = Buffer->getBufferStart();
1083   for (OutputSection *Sec : OutputSections) {
1084     uint8_t *SecBuf = Buf + Sec->getFileOff();
1085     // Fill gaps between functions in .text with INT3 instructions
1086     // instead of leaving as NUL bytes (which can be interpreted as
1087     // ADD instructions).
1088     if (Sec->getPermissions() & IMAGE_SCN_CNT_CODE)
1089       memset(SecBuf, 0xCC, Sec->getRawSize());
1090     for_each(parallel::par, Sec->getChunks().begin(), Sec->getChunks().end(),
1091              [&](Chunk *C) { C->writeTo(SecBuf); });
1092   }
1093 }
1094 
1095 void Writer::writeBuildId() {
1096   // There are two important parts to the build ID.
1097   // 1) If building with debug info, the COFF debug directory contains a
1098   //    timestamp as well as a Guid and Age of the PDB.
1099   // 2) In all cases, the PE COFF file header also contains a timestamp.
1100   // For reproducibility, instead of a timestamp we want to use a hash of the
1101   // binary, however when building with debug info the hash needs to take into
1102   // account the debug info, since it's possible to add blank lines to a file
1103   // which causes the debug info to change but not the generated code.
1104   //
1105   // To handle this, we first set the Guid and Age in the debug directory (but
1106   // only if we're doing a debug build).  Then, we hash the binary (thus causing
1107   // the hash to change if only the debug info changes, since the Age will be
1108   // different).  Finally, we write that hash into the debug directory (if
1109   // present) as well as the COFF file header (always).
1110   if (Config->Debug) {
1111     assert(BuildId && "BuildId is not set!");
1112     if (PreviousBuildId.hasValue()) {
1113       *BuildId->BuildId = *PreviousBuildId;
1114       BuildId->BuildId->PDB70.Age = BuildId->BuildId->PDB70.Age + 1;
1115     } else {
1116       BuildId->BuildId->Signature.CVSignature = OMF::Signature::PDB70;
1117       BuildId->BuildId->PDB70.Age = 1;
1118       llvm::getRandomBytes(BuildId->BuildId->PDB70.Signature, 16);
1119     }
1120   }
1121 
1122   // At this point the only fields in the COFF file which remain unset are the
1123   // "timestamp" in the COFF file header, and the ones in the coff debug
1124   // directory.  Now we can hash the file and write that hash to the various
1125   // timestamp fields in the file.
1126   StringRef OutputFileData(
1127       reinterpret_cast<const char *>(Buffer->getBufferStart()),
1128       Buffer->getBufferSize());
1129 
1130   uint32_t Hash = static_cast<uint32_t>(xxHash64(OutputFileData));
1131 
1132   if (DebugDirectory)
1133     DebugDirectory->setTimeDateStamp(Hash);
1134 
1135   uint8_t *Buf = Buffer->getBufferStart();
1136   Buf += DOSStubSize + sizeof(PEMagic);
1137   object::coff_file_header *CoffHeader =
1138       reinterpret_cast<coff_file_header *>(Buf);
1139   CoffHeader->TimeDateStamp = Hash;
1140 }
1141 
1142 // Sort .pdata section contents according to PE/COFF spec 5.5.
1143 void Writer::sortExceptionTable() {
1144   OutputSection *Sec = findSection(".pdata");
1145   if (!Sec)
1146     return;
1147   // We assume .pdata contains function table entries only.
1148   uint8_t *Begin = Buffer->getBufferStart() + Sec->getFileOff();
1149   uint8_t *End = Begin + Sec->getVirtualSize();
1150   if (Config->Machine == AMD64) {
1151     struct Entry { ulittle32_t Begin, End, Unwind; };
1152     sort(parallel::par, (Entry *)Begin, (Entry *)End,
1153          [](const Entry &A, const Entry &B) { return A.Begin < B.Begin; });
1154     return;
1155   }
1156   if (Config->Machine == ARMNT || Config->Machine == ARM64) {
1157     struct Entry { ulittle32_t Begin, Unwind; };
1158     sort(parallel::par, (Entry *)Begin, (Entry *)End,
1159          [](const Entry &A, const Entry &B) { return A.Begin < B.Begin; });
1160     return;
1161   }
1162   errs() << "warning: don't know how to handle .pdata.\n";
1163 }
1164 
1165 OutputSection *Writer::findSection(StringRef Name) {
1166   for (OutputSection *Sec : OutputSections)
1167     if (Sec->Name == Name)
1168       return Sec;
1169   return nullptr;
1170 }
1171 
1172 uint32_t Writer::getSizeOfInitializedData() {
1173   uint32_t Res = 0;
1174   for (OutputSection *S : OutputSections)
1175     if (S->getPermissions() & IMAGE_SCN_CNT_INITIALIZED_DATA)
1176       Res += S->getRawSize();
1177   return Res;
1178 }
1179 
1180 // Returns an existing section or create a new one if not found.
1181 OutputSection *Writer::createSection(StringRef Name) {
1182   if (auto *Sec = findSection(Name))
1183     return Sec;
1184   const auto DATA = IMAGE_SCN_CNT_INITIALIZED_DATA;
1185   const auto BSS = IMAGE_SCN_CNT_UNINITIALIZED_DATA;
1186   const auto CODE = IMAGE_SCN_CNT_CODE;
1187   const auto DISCARDABLE = IMAGE_SCN_MEM_DISCARDABLE;
1188   const auto R = IMAGE_SCN_MEM_READ;
1189   const auto W = IMAGE_SCN_MEM_WRITE;
1190   const auto X = IMAGE_SCN_MEM_EXECUTE;
1191   uint32_t Perms = StringSwitch<uint32_t>(Name)
1192                        .Case(".bss", BSS | R | W)
1193                        .Case(".data", DATA | R | W)
1194                        .Cases(".didat", ".edata", ".idata", ".rdata", DATA | R)
1195                        .Case(".reloc", DATA | DISCARDABLE | R)
1196                        .Case(".text", CODE | R | X)
1197                        .Default(0);
1198   if (!Perms)
1199     llvm_unreachable("unknown section name");
1200   auto Sec = make<OutputSection>(Name);
1201   Sec->addPermissions(Perms);
1202   OutputSections.push_back(Sec);
1203   return Sec;
1204 }
1205 
1206 // Dest is .reloc section. Add contents to that section.
1207 void Writer::addBaserels(OutputSection *Dest) {
1208   std::vector<Baserel> V;
1209   for (OutputSection *Sec : OutputSections) {
1210     if (Sec == Dest)
1211       continue;
1212     // Collect all locations for base relocations.
1213     for (Chunk *C : Sec->getChunks())
1214       C->getBaserels(&V);
1215     // Add the addresses to .reloc section.
1216     if (!V.empty())
1217       addBaserelBlocks(Dest, V);
1218     V.clear();
1219   }
1220 }
1221 
1222 // Add addresses to .reloc section. Note that addresses are grouped by page.
1223 void Writer::addBaserelBlocks(OutputSection *Dest, std::vector<Baserel> &V) {
1224   const uint32_t Mask = ~uint32_t(PageSize - 1);
1225   uint32_t Page = V[0].RVA & Mask;
1226   size_t I = 0, J = 1;
1227   for (size_t E = V.size(); J < E; ++J) {
1228     uint32_t P = V[J].RVA & Mask;
1229     if (P == Page)
1230       continue;
1231     Dest->addChunk(make<BaserelChunk>(Page, &V[I], &V[0] + J));
1232     I = J;
1233     Page = P;
1234   }
1235   if (I == J)
1236     return;
1237   Dest->addChunk(make<BaserelChunk>(Page, &V[I], &V[0] + J));
1238 }
1239