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