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