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