]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/MC/WinCOFFObjectWriter.cpp
Merge compiler-rt trunk r300890, and update build glue.
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / MC / WinCOFFObjectWriter.cpp
1 //===- llvm/MC/WinCOFFObjectWriter.cpp ------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains an implementation of a Win32 COFF object file writer.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/ADT/DenseMap.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/Twine.h"
20 #include "llvm/MC/MCAsmLayout.h"
21 #include "llvm/MC/MCAssembler.h"
22 #include "llvm/MC/MCContext.h"
23 #include "llvm/MC/MCExpr.h"
24 #include "llvm/MC/MCFixup.h"
25 #include "llvm/MC/MCFragment.h"
26 #include "llvm/MC/MCObjectWriter.h"
27 #include "llvm/MC/MCSection.h"
28 #include "llvm/MC/MCSectionCOFF.h"
29 #include "llvm/MC/MCSymbol.h"
30 #include "llvm/MC/MCSymbolCOFF.h"
31 #include "llvm/MC/MCValue.h"
32 #include "llvm/MC/MCWinCOFFObjectWriter.h"
33 #include "llvm/MC/StringTableBuilder.h"
34 #include "llvm/Support/Casting.h"
35 #include "llvm/Support/COFF.h"
36 #include "llvm/Support/Endian.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/JamCRC.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include <cassert>
42 #include <cstddef>
43 #include <cstdint>
44 #include <cstring>
45 #include <ctime>
46 #include <memory>
47 #include <string>
48 #include <vector>
49
50 using namespace llvm;
51 using llvm::support::endian::write32le;
52
53 #define DEBUG_TYPE "WinCOFFObjectWriter"
54
55 namespace {
56
57 typedef SmallString<COFF::NameSize> name;
58
59 enum AuxiliaryType {
60   ATFunctionDefinition,
61   ATbfAndefSymbol,
62   ATWeakExternal,
63   ATFile,
64   ATSectionDefinition
65 };
66
67 struct AuxSymbol {
68   AuxiliaryType AuxType;
69   COFF::Auxiliary Aux;
70 };
71
72 class COFFSection;
73
74 class COFFSymbol {
75 public:
76   COFF::symbol Data = {};
77
78   typedef SmallVector<AuxSymbol, 1> AuxiliarySymbols;
79
80   name Name;
81   int Index;
82   AuxiliarySymbols Aux;
83   COFFSymbol *Other = nullptr;
84   COFFSection *Section = nullptr;
85   int Relocations = 0;
86   const MCSymbol *MC = nullptr;
87
88   COFFSymbol(StringRef Name) : Name(Name) {}
89
90   void set_name_offset(uint32_t Offset);
91
92   int64_t getIndex() const { return Index; }
93   void setIndex(int Value) {
94     Index = Value;
95     if (MC)
96       MC->setIndex(static_cast<uint32_t>(Value));
97   }
98 };
99
100 // This class contains staging data for a COFF relocation entry.
101 struct COFFRelocation {
102   COFF::relocation Data;
103   COFFSymbol *Symb = nullptr;
104
105   COFFRelocation() = default;
106
107   static size_t size() { return COFF::RelocationSize; }
108 };
109
110 typedef std::vector<COFFRelocation> relocations;
111
112 class COFFSection {
113 public:
114   COFF::section Header = {};
115
116   std::string Name;
117   int Number;
118   MCSectionCOFF const *MCSection = nullptr;
119   COFFSymbol *Symbol = nullptr;
120   relocations Relocations;
121
122   COFFSection(StringRef Name) : Name(Name) {}
123 };
124
125 class WinCOFFObjectWriter : public MCObjectWriter {
126 public:
127   typedef std::vector<std::unique_ptr<COFFSymbol>> symbols;
128   typedef std::vector<std::unique_ptr<COFFSection>> sections;
129
130   typedef DenseMap<MCSymbol const *, COFFSymbol *> symbol_map;
131   typedef DenseMap<MCSection const *, COFFSection *> section_map;
132
133   std::unique_ptr<MCWinCOFFObjectTargetWriter> TargetObjectWriter;
134
135   // Root level file contents.
136   COFF::header Header = {};
137   sections Sections;
138   symbols Symbols;
139   StringTableBuilder Strings{StringTableBuilder::WinCOFF};
140
141   // Maps used during object file creation.
142   section_map SectionMap;
143   symbol_map SymbolMap;
144
145   bool UseBigObj;
146
147   WinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW, raw_pwrite_stream &OS);
148
149   void reset() override {
150     memset(&Header, 0, sizeof(Header));
151     Header.Machine = TargetObjectWriter->getMachine();
152     Sections.clear();
153     Symbols.clear();
154     Strings.clear();
155     SectionMap.clear();
156     SymbolMap.clear();
157     MCObjectWriter::reset();
158   }
159
160   COFFSymbol *createSymbol(StringRef Name);
161   COFFSymbol *GetOrCreateCOFFSymbol(const MCSymbol *Symbol);
162   COFFSection *createSection(StringRef Name);
163
164   void defineSection(MCSectionCOFF const &Sec);
165
166   COFFSymbol *getLinkedSymbol(const MCSymbol &Symbol);
167   void DefineSymbol(const MCSymbol &Symbol, MCAssembler &Assembler,
168                     const MCAsmLayout &Layout);
169
170   void SetSymbolName(COFFSymbol &S);
171   void SetSectionName(COFFSection &S);
172
173   bool IsPhysicalSection(COFFSection *S);
174
175   // Entity writing methods.
176
177   void WriteFileHeader(const COFF::header &Header);
178   void WriteSymbol(const COFFSymbol &S);
179   void WriteAuxiliarySymbols(const COFFSymbol::AuxiliarySymbols &S);
180   void writeSectionHeaders();
181   void WriteRelocation(const COFF::relocation &R);
182   uint32_t writeSectionContents(MCAssembler &Asm, const MCAsmLayout &Layout,
183                                 const MCSection &MCSec);
184   void writeSection(MCAssembler &Asm, const MCAsmLayout &Layout,
185                     const COFFSection &Sec, const MCSection &MCSec);
186
187   // MCObjectWriter interface implementation.
188
189   void executePostLayoutBinding(MCAssembler &Asm,
190                                 const MCAsmLayout &Layout) override;
191
192   bool isSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
193                                               const MCSymbol &SymA,
194                                               const MCFragment &FB, bool InSet,
195                                               bool IsPCRel) const override;
196
197   void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
198                         const MCFragment *Fragment, const MCFixup &Fixup,
199                         MCValue Target, bool &IsPCRel,
200                         uint64_t &FixedValue) override;
201
202   void createFileSymbols(MCAssembler &Asm);
203   void assignSectionNumbers();
204   void assignFileOffsets(MCAssembler &Asm, const MCAsmLayout &Layout);
205
206   void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
207 };
208
209 } // end anonymous namespace
210
211 //------------------------------------------------------------------------------
212 // Symbol class implementation
213
214 // In the case that the name does not fit within 8 bytes, the offset
215 // into the string table is stored in the last 4 bytes instead, leaving
216 // the first 4 bytes as 0.
217 void COFFSymbol::set_name_offset(uint32_t Offset) {
218   write32le(Data.Name + 0, 0);
219   write32le(Data.Name + 4, Offset);
220 }
221
222 //------------------------------------------------------------------------------
223 // WinCOFFObjectWriter class implementation
224
225 WinCOFFObjectWriter::WinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW,
226                                          raw_pwrite_stream &OS)
227     : MCObjectWriter(OS, true), TargetObjectWriter(MOTW) {
228   Header.Machine = TargetObjectWriter->getMachine();
229 }
230
231 COFFSymbol *WinCOFFObjectWriter::createSymbol(StringRef Name) {
232   Symbols.push_back(make_unique<COFFSymbol>(Name));
233   return Symbols.back().get();
234 }
235
236 COFFSymbol *WinCOFFObjectWriter::GetOrCreateCOFFSymbol(const MCSymbol *Symbol) {
237   COFFSymbol *&Ret = SymbolMap[Symbol];
238   if (!Ret)
239     Ret = createSymbol(Symbol->getName());
240   return Ret;
241 }
242
243 COFFSection *WinCOFFObjectWriter::createSection(StringRef Name) {
244   Sections.emplace_back(make_unique<COFFSection>(Name));
245   return Sections.back().get();
246 }
247
248 static uint32_t getAlignment(const MCSectionCOFF &Sec) {
249   switch (Sec.getAlignment()) {
250   case 1:
251     return COFF::IMAGE_SCN_ALIGN_1BYTES;
252   case 2:
253     return COFF::IMAGE_SCN_ALIGN_2BYTES;
254   case 4:
255     return COFF::IMAGE_SCN_ALIGN_4BYTES;
256   case 8:
257     return COFF::IMAGE_SCN_ALIGN_8BYTES;
258   case 16:
259     return COFF::IMAGE_SCN_ALIGN_16BYTES;
260   case 32:
261     return COFF::IMAGE_SCN_ALIGN_32BYTES;
262   case 64:
263     return COFF::IMAGE_SCN_ALIGN_64BYTES;
264   case 128:
265     return COFF::IMAGE_SCN_ALIGN_128BYTES;
266   case 256:
267     return COFF::IMAGE_SCN_ALIGN_256BYTES;
268   case 512:
269     return COFF::IMAGE_SCN_ALIGN_512BYTES;
270   case 1024:
271     return COFF::IMAGE_SCN_ALIGN_1024BYTES;
272   case 2048:
273     return COFF::IMAGE_SCN_ALIGN_2048BYTES;
274   case 4096:
275     return COFF::IMAGE_SCN_ALIGN_4096BYTES;
276   case 8192:
277     return COFF::IMAGE_SCN_ALIGN_8192BYTES;
278   }
279   llvm_unreachable("unsupported section alignment");
280 }
281
282 /// This function takes a section data object from the assembler
283 /// and creates the associated COFF section staging object.
284 void WinCOFFObjectWriter::defineSection(const MCSectionCOFF &MCSec) {
285   COFFSection *Section = createSection(MCSec.getSectionName());
286   COFFSymbol *Symbol = createSymbol(MCSec.getSectionName());
287   Section->Symbol = Symbol;
288   Symbol->Section = Section;
289   Symbol->Data.StorageClass = COFF::IMAGE_SYM_CLASS_STATIC;
290
291   // Create a COMDAT symbol if needed.
292   if (MCSec.getSelection() != COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) {
293     if (const MCSymbol *S = MCSec.getCOMDATSymbol()) {
294       COFFSymbol *COMDATSymbol = GetOrCreateCOFFSymbol(S);
295       if (COMDATSymbol->Section)
296         report_fatal_error("two sections have the same comdat");
297       COMDATSymbol->Section = Section;
298     }
299   }
300
301   // In this case the auxiliary symbol is a Section Definition.
302   Symbol->Aux.resize(1);
303   Symbol->Aux[0] = {};
304   Symbol->Aux[0].AuxType = ATSectionDefinition;
305   Symbol->Aux[0].Aux.SectionDefinition.Selection = MCSec.getSelection();
306
307   // Set section alignment.
308   Section->Header.Characteristics = MCSec.getCharacteristics();
309   Section->Header.Characteristics |= getAlignment(MCSec);
310
311   // Bind internal COFF section to MC section.
312   Section->MCSection = &MCSec;
313   SectionMap[&MCSec] = Section;
314 }
315
316 static uint64_t getSymbolValue(const MCSymbol &Symbol,
317                                const MCAsmLayout &Layout) {
318   if (Symbol.isCommon() && Symbol.isExternal())
319     return Symbol.getCommonSize();
320
321   uint64_t Res;
322   if (!Layout.getSymbolOffset(Symbol, Res))
323     return 0;
324
325   return Res;
326 }
327
328 COFFSymbol *WinCOFFObjectWriter::getLinkedSymbol(const MCSymbol &Symbol) {
329   if (!Symbol.isVariable())
330     return nullptr;
331
332   const MCSymbolRefExpr *SymRef =
333       dyn_cast<MCSymbolRefExpr>(Symbol.getVariableValue());
334   if (!SymRef)
335     return nullptr;
336
337   const MCSymbol &Aliasee = SymRef->getSymbol();
338   if (!Aliasee.isUndefined())
339     return nullptr;
340   return GetOrCreateCOFFSymbol(&Aliasee);
341 }
342
343 /// This function takes a symbol data object from the assembler
344 /// and creates the associated COFF symbol staging object.
345 void WinCOFFObjectWriter::DefineSymbol(const MCSymbol &MCSym,
346                                        MCAssembler &Assembler,
347                                        const MCAsmLayout &Layout) {
348   COFFSymbol *Sym = GetOrCreateCOFFSymbol(&MCSym);
349   const MCSymbol *Base = Layout.getBaseSymbol(MCSym);
350   COFFSection *Sec = nullptr;
351   if (Base && Base->getFragment()) {
352     Sec = SectionMap[Base->getFragment()->getParent()];
353     if (Sym->Section && Sym->Section != Sec)
354       report_fatal_error("conflicting sections for symbol");
355   }
356
357   COFFSymbol *Local = nullptr;
358   if (cast<MCSymbolCOFF>(MCSym).isWeakExternal()) {
359     Sym->Data.StorageClass = COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL;
360
361     COFFSymbol *WeakDefault = getLinkedSymbol(MCSym);
362     if (!WeakDefault) {
363       std::string WeakName = (".weak." + MCSym.getName() + ".default").str();
364       WeakDefault = createSymbol(WeakName);
365       if (!Sec)
366         WeakDefault->Data.SectionNumber = COFF::IMAGE_SYM_ABSOLUTE;
367       else
368         WeakDefault->Section = Sec;
369       Local = WeakDefault;
370     }
371
372     Sym->Other = WeakDefault;
373
374     // Setup the Weak External auxiliary symbol.
375     Sym->Aux.resize(1);
376     memset(&Sym->Aux[0], 0, sizeof(Sym->Aux[0]));
377     Sym->Aux[0].AuxType = ATWeakExternal;
378     Sym->Aux[0].Aux.WeakExternal.TagIndex = 0;
379     Sym->Aux[0].Aux.WeakExternal.Characteristics =
380         COFF::IMAGE_WEAK_EXTERN_SEARCH_LIBRARY;
381   } else {
382     if (!Base)
383       Sym->Data.SectionNumber = COFF::IMAGE_SYM_ABSOLUTE;
384     else
385       Sym->Section = Sec;
386     Local = Sym;
387   }
388
389   if (Local) {
390     Local->Data.Value = getSymbolValue(MCSym, Layout);
391
392     const MCSymbolCOFF &SymbolCOFF = cast<MCSymbolCOFF>(MCSym);
393     Local->Data.Type = SymbolCOFF.getType();
394     Local->Data.StorageClass = SymbolCOFF.getClass();
395
396     // If no storage class was specified in the streamer, define it here.
397     if (Local->Data.StorageClass == COFF::IMAGE_SYM_CLASS_NULL) {
398       bool IsExternal = MCSym.isExternal() ||
399                         (!MCSym.getFragment() && !MCSym.isVariable());
400
401       Local->Data.StorageClass = IsExternal ? COFF::IMAGE_SYM_CLASS_EXTERNAL
402                                             : COFF::IMAGE_SYM_CLASS_STATIC;
403     }
404   }
405
406   Sym->MC = &MCSym;
407 }
408
409 // Maximum offsets for different string table entry encodings.
410 enum : unsigned { Max7DecimalOffset = 9999999U };
411 enum : uint64_t { MaxBase64Offset = 0xFFFFFFFFFULL }; // 64^6, including 0
412
413 // Encode a string table entry offset in base 64, padded to 6 chars, and
414 // prefixed with a double slash: '//AAAAAA', '//AAAAAB', ...
415 // Buffer must be at least 8 bytes large. No terminating null appended.
416 static void encodeBase64StringEntry(char *Buffer, uint64_t Value) {
417   assert(Value > Max7DecimalOffset && Value <= MaxBase64Offset &&
418          "Illegal section name encoding for value");
419
420   static const char Alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
421                                  "abcdefghijklmnopqrstuvwxyz"
422                                  "0123456789+/";
423
424   Buffer[0] = '/';
425   Buffer[1] = '/';
426
427   char *Ptr = Buffer + 7;
428   for (unsigned i = 0; i < 6; ++i) {
429     unsigned Rem = Value % 64;
430     Value /= 64;
431     *(Ptr--) = Alphabet[Rem];
432   }
433 }
434
435 void WinCOFFObjectWriter::SetSectionName(COFFSection &S) {
436   if (S.Name.size() <= COFF::NameSize) {
437     std::memcpy(S.Header.Name, S.Name.c_str(), S.Name.size());
438     return;
439   }
440
441   uint64_t StringTableEntry = Strings.getOffset(S.Name);
442   if (StringTableEntry <= Max7DecimalOffset) {
443     SmallVector<char, COFF::NameSize> Buffer;
444     Twine('/').concat(Twine(StringTableEntry)).toVector(Buffer);
445     assert(Buffer.size() <= COFF::NameSize && Buffer.size() >= 2);
446     std::memcpy(S.Header.Name, Buffer.data(), Buffer.size());
447     return;
448   }
449   if (StringTableEntry <= MaxBase64Offset) {
450     // Starting with 10,000,000, offsets are encoded as base64.
451     encodeBase64StringEntry(S.Header.Name, StringTableEntry);
452     return;
453   }
454   report_fatal_error("COFF string table is greater than 64 GB.");
455 }
456
457 void WinCOFFObjectWriter::SetSymbolName(COFFSymbol &S) {
458   if (S.Name.size() > COFF::NameSize)
459     S.set_name_offset(Strings.getOffset(S.Name));
460   else
461     std::memcpy(S.Data.Name, S.Name.c_str(), S.Name.size());
462 }
463
464 bool WinCOFFObjectWriter::IsPhysicalSection(COFFSection *S) {
465   return (S->Header.Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) ==
466          0;
467 }
468
469 //------------------------------------------------------------------------------
470 // entity writing methods
471
472 void WinCOFFObjectWriter::WriteFileHeader(const COFF::header &Header) {
473   if (UseBigObj) {
474     writeLE16(COFF::IMAGE_FILE_MACHINE_UNKNOWN);
475     writeLE16(0xFFFF);
476     writeLE16(COFF::BigObjHeader::MinBigObjectVersion);
477     writeLE16(Header.Machine);
478     writeLE32(Header.TimeDateStamp);
479     writeBytes(StringRef(COFF::BigObjMagic, sizeof(COFF::BigObjMagic)));
480     writeLE32(0);
481     writeLE32(0);
482     writeLE32(0);
483     writeLE32(0);
484     writeLE32(Header.NumberOfSections);
485     writeLE32(Header.PointerToSymbolTable);
486     writeLE32(Header.NumberOfSymbols);
487   } else {
488     writeLE16(Header.Machine);
489     writeLE16(static_cast<int16_t>(Header.NumberOfSections));
490     writeLE32(Header.TimeDateStamp);
491     writeLE32(Header.PointerToSymbolTable);
492     writeLE32(Header.NumberOfSymbols);
493     writeLE16(Header.SizeOfOptionalHeader);
494     writeLE16(Header.Characteristics);
495   }
496 }
497
498 void WinCOFFObjectWriter::WriteSymbol(const COFFSymbol &S) {
499   writeBytes(StringRef(S.Data.Name, COFF::NameSize));
500   writeLE32(S.Data.Value);
501   if (UseBigObj)
502     writeLE32(S.Data.SectionNumber);
503   else
504     writeLE16(static_cast<int16_t>(S.Data.SectionNumber));
505   writeLE16(S.Data.Type);
506   write8(S.Data.StorageClass);
507   write8(S.Data.NumberOfAuxSymbols);
508   WriteAuxiliarySymbols(S.Aux);
509 }
510
511 void WinCOFFObjectWriter::WriteAuxiliarySymbols(
512     const COFFSymbol::AuxiliarySymbols &S) {
513   for (const AuxSymbol &i : S) {
514     switch (i.AuxType) {
515     case ATFunctionDefinition:
516       writeLE32(i.Aux.FunctionDefinition.TagIndex);
517       writeLE32(i.Aux.FunctionDefinition.TotalSize);
518       writeLE32(i.Aux.FunctionDefinition.PointerToLinenumber);
519       writeLE32(i.Aux.FunctionDefinition.PointerToNextFunction);
520       WriteZeros(sizeof(i.Aux.FunctionDefinition.unused));
521       if (UseBigObj)
522         WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
523       break;
524     case ATbfAndefSymbol:
525       WriteZeros(sizeof(i.Aux.bfAndefSymbol.unused1));
526       writeLE16(i.Aux.bfAndefSymbol.Linenumber);
527       WriteZeros(sizeof(i.Aux.bfAndefSymbol.unused2));
528       writeLE32(i.Aux.bfAndefSymbol.PointerToNextFunction);
529       WriteZeros(sizeof(i.Aux.bfAndefSymbol.unused3));
530       if (UseBigObj)
531         WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
532       break;
533     case ATWeakExternal:
534       writeLE32(i.Aux.WeakExternal.TagIndex);
535       writeLE32(i.Aux.WeakExternal.Characteristics);
536       WriteZeros(sizeof(i.Aux.WeakExternal.unused));
537       if (UseBigObj)
538         WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
539       break;
540     case ATFile:
541       writeBytes(
542           StringRef(reinterpret_cast<const char *>(&i.Aux),
543                     UseBigObj ? COFF::Symbol32Size : COFF::Symbol16Size));
544       break;
545     case ATSectionDefinition:
546       writeLE32(i.Aux.SectionDefinition.Length);
547       writeLE16(i.Aux.SectionDefinition.NumberOfRelocations);
548       writeLE16(i.Aux.SectionDefinition.NumberOfLinenumbers);
549       writeLE32(i.Aux.SectionDefinition.CheckSum);
550       writeLE16(static_cast<int16_t>(i.Aux.SectionDefinition.Number));
551       write8(i.Aux.SectionDefinition.Selection);
552       WriteZeros(sizeof(i.Aux.SectionDefinition.unused));
553       writeLE16(static_cast<int16_t>(i.Aux.SectionDefinition.Number >> 16));
554       if (UseBigObj)
555         WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
556       break;
557     }
558   }
559 }
560
561 // Write the section header.
562 void WinCOFFObjectWriter::writeSectionHeaders() {
563   // Section numbers must be monotonically increasing in the section
564   // header, but our Sections array is not sorted by section number,
565   // so make a copy of Sections and sort it.
566   std::vector<COFFSection *> Arr;
567   for (auto &Section : Sections)
568     Arr.push_back(Section.get());
569   std::sort(Arr.begin(), Arr.end(),
570             [](const COFFSection *A, const COFFSection *B) {
571               return A->Number < B->Number;
572             });
573
574   for (auto &Section : Arr) {
575     if (Section->Number == -1)
576       continue;
577
578     COFF::section &S = Section->Header;
579     if (Section->Relocations.size() >= 0xffff)
580       S.Characteristics |= COFF::IMAGE_SCN_LNK_NRELOC_OVFL;
581     writeBytes(StringRef(S.Name, COFF::NameSize));
582     writeLE32(S.VirtualSize);
583     writeLE32(S.VirtualAddress);
584     writeLE32(S.SizeOfRawData);
585     writeLE32(S.PointerToRawData);
586     writeLE32(S.PointerToRelocations);
587     writeLE32(S.PointerToLineNumbers);
588     writeLE16(S.NumberOfRelocations);
589     writeLE16(S.NumberOfLineNumbers);
590     writeLE32(S.Characteristics);
591   }
592 }
593
594 void WinCOFFObjectWriter::WriteRelocation(const COFF::relocation &R) {
595   writeLE32(R.VirtualAddress);
596   writeLE32(R.SymbolTableIndex);
597   writeLE16(R.Type);
598 }
599
600 // Write MCSec's contents. What this function does is essentially
601 // "Asm.writeSectionData(&MCSec, Layout)", but it's a bit complicated
602 // because it needs to compute a CRC.
603 uint32_t WinCOFFObjectWriter::writeSectionContents(MCAssembler &Asm,
604                                                    const MCAsmLayout &Layout,
605                                                    const MCSection &MCSec) {
606   // Save the contents of the section to a temporary buffer, we need this
607   // to CRC the data before we dump it into the object file.
608   SmallVector<char, 128> Buf;
609   raw_svector_ostream VecOS(Buf);
610   raw_pwrite_stream &OldStream = getStream();
611
612   // Redirect the output stream to our buffer and fill our buffer with
613   // the section data.
614   setStream(VecOS);
615   Asm.writeSectionData(&MCSec, Layout);
616
617   // Reset the stream back to what it was before.
618   setStream(OldStream);
619
620   // Write the section contents to the object file.
621   getStream() << Buf;
622
623   // Calculate our CRC with an initial value of '0', this is not how
624   // JamCRC is specified but it aligns with the expected output.
625   JamCRC JC(/*Init=*/0);
626   JC.update(Buf);
627   return JC.getCRC();
628 }
629
630 void WinCOFFObjectWriter::writeSection(MCAssembler &Asm,
631                                        const MCAsmLayout &Layout,
632                                        const COFFSection &Sec,
633                                        const MCSection &MCSec) {
634   if (Sec.Number == -1)
635     return;
636
637   // Write the section contents.
638   if (Sec.Header.PointerToRawData != 0) {
639     assert(getStream().tell() <= Sec.Header.PointerToRawData &&
640            "Section::PointerToRawData is insane!");
641
642     unsigned PaddingSize = Sec.Header.PointerToRawData - getStream().tell();
643     assert(PaddingSize < 4 &&
644            "Should only need at most three bytes of padding!");
645     WriteZeros(PaddingSize);
646
647     uint32_t CRC = writeSectionContents(Asm, Layout, MCSec);
648
649     // Update the section definition auxiliary symbol to record the CRC.
650     COFFSection *Sec = SectionMap[&MCSec];
651     COFFSymbol::AuxiliarySymbols &AuxSyms = Sec->Symbol->Aux;
652     assert(AuxSyms.size() == 1 && AuxSyms[0].AuxType == ATSectionDefinition);
653     AuxSymbol &SecDef = AuxSyms[0];
654     SecDef.Aux.SectionDefinition.CheckSum = CRC;
655   }
656
657   // Write relocations for this section.
658   if (Sec.Relocations.empty()) {
659     assert(Sec.Header.PointerToRelocations == 0 &&
660            "Section::PointerToRelocations is insane!");
661     return;
662   }
663
664   assert(getStream().tell() == Sec.Header.PointerToRelocations &&
665          "Section::PointerToRelocations is insane!");
666
667   if (Sec.Relocations.size() >= 0xffff) {
668     // In case of overflow, write actual relocation count as first
669     // relocation. Including the synthetic reloc itself (+ 1).
670     COFF::relocation R;
671     R.VirtualAddress = Sec.Relocations.size() + 1;
672     R.SymbolTableIndex = 0;
673     R.Type = 0;
674     WriteRelocation(R);
675   }
676
677   for (const auto &Relocation : Sec.Relocations)
678     WriteRelocation(Relocation.Data);
679 }
680
681 ////////////////////////////////////////////////////////////////////////////////
682 // MCObjectWriter interface implementations
683
684 void WinCOFFObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
685                                                    const MCAsmLayout &Layout) {
686   // "Define" each section & symbol. This creates section & symbol
687   // entries in the staging area.
688   for (const auto &Section : Asm)
689     defineSection(static_cast<const MCSectionCOFF &>(Section));
690
691   for (const MCSymbol &Symbol : Asm.symbols())
692     if (!Symbol.isTemporary())
693       DefineSymbol(Symbol, Asm, Layout);
694 }
695
696 bool WinCOFFObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(
697     const MCAssembler &Asm, const MCSymbol &SymA, const MCFragment &FB,
698     bool InSet, bool IsPCRel) const {
699   // MS LINK expects to be able to replace all references to a function with a
700   // thunk to implement their /INCREMENTAL feature.  Make sure we don't optimize
701   // away any relocations to functions.
702   uint16_t Type = cast<MCSymbolCOFF>(SymA).getType();
703   if (Asm.isIncrementalLinkerCompatible() &&
704       (Type >> COFF::SCT_COMPLEX_TYPE_SHIFT) == COFF::IMAGE_SYM_DTYPE_FUNCTION)
705     return false;
706   return MCObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(Asm, SymA, FB,
707                                                                 InSet, IsPCRel);
708 }
709
710 void WinCOFFObjectWriter::recordRelocation(
711     MCAssembler &Asm, const MCAsmLayout &Layout, const MCFragment *Fragment,
712     const MCFixup &Fixup, MCValue Target, bool &IsPCRel, uint64_t &FixedValue) {
713   assert(Target.getSymA() && "Relocation must reference a symbol!");
714
715   const MCSymbol &A = Target.getSymA()->getSymbol();
716   if (!A.isRegistered()) {
717     Asm.getContext().reportError(Fixup.getLoc(),
718                                       Twine("symbol '") + A.getName() +
719                                           "' can not be undefined");
720     return;
721   }
722   if (A.isTemporary() && A.isUndefined()) {
723     Asm.getContext().reportError(Fixup.getLoc(),
724                                       Twine("assembler label '") + A.getName() +
725                                           "' can not be undefined");
726     return;
727   }
728
729   MCSection *MCSec = Fragment->getParent();
730
731   // Mark this symbol as requiring an entry in the symbol table.
732   assert(SectionMap.find(MCSec) != SectionMap.end() &&
733          "Section must already have been defined in executePostLayoutBinding!");
734
735   COFFSection *Sec = SectionMap[MCSec];
736   const MCSymbolRefExpr *SymB = Target.getSymB();
737   bool CrossSection = false;
738
739   if (SymB) {
740     const MCSymbol *B = &SymB->getSymbol();
741     if (!B->getFragment()) {
742       Asm.getContext().reportError(
743           Fixup.getLoc(),
744           Twine("symbol '") + B->getName() +
745               "' can not be undefined in a subtraction expression");
746       return;
747     }
748
749     if (!A.getFragment()) {
750       Asm.getContext().reportError(
751           Fixup.getLoc(),
752           Twine("symbol '") + A.getName() +
753               "' can not be undefined in a subtraction expression");
754       return;
755     }
756
757     CrossSection = &A.getSection() != &B->getSection();
758
759     // Offset of the symbol in the section
760     int64_t OffsetOfB = Layout.getSymbolOffset(*B);
761
762     // In the case where we have SymbA and SymB, we just need to store the delta
763     // between the two symbols.  Update FixedValue to account for the delta, and
764     // skip recording the relocation.
765     if (!CrossSection) {
766       int64_t OffsetOfA = Layout.getSymbolOffset(A);
767       FixedValue = (OffsetOfA - OffsetOfB) + Target.getConstant();
768       return;
769     }
770
771     // Offset of the relocation in the section
772     int64_t OffsetOfRelocation =
773         Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
774
775     FixedValue = (OffsetOfRelocation - OffsetOfB) + Target.getConstant();
776   } else {
777     FixedValue = Target.getConstant();
778   }
779
780   COFFRelocation Reloc;
781
782   Reloc.Data.SymbolTableIndex = 0;
783   Reloc.Data.VirtualAddress = Layout.getFragmentOffset(Fragment);
784
785   // Turn relocations for temporary symbols into section relocations.
786   if (A.isTemporary() || CrossSection) {
787     MCSection *TargetSection = &A.getSection();
788     assert(
789         SectionMap.find(TargetSection) != SectionMap.end() &&
790         "Section must already have been defined in executePostLayoutBinding!");
791     Reloc.Symb = SectionMap[TargetSection]->Symbol;
792     FixedValue += Layout.getSymbolOffset(A);
793   } else {
794     assert(
795         SymbolMap.find(&A) != SymbolMap.end() &&
796         "Symbol must already have been defined in executePostLayoutBinding!");
797     Reloc.Symb = SymbolMap[&A];
798   }
799
800   ++Reloc.Symb->Relocations;
801
802   Reloc.Data.VirtualAddress += Fixup.getOffset();
803   Reloc.Data.Type = TargetObjectWriter->getRelocType(
804       Target, Fixup, CrossSection, Asm.getBackend());
805
806   // FIXME: Can anyone explain what this does other than adjust for the size
807   // of the offset?
808   if ((Header.Machine == COFF::IMAGE_FILE_MACHINE_AMD64 &&
809        Reloc.Data.Type == COFF::IMAGE_REL_AMD64_REL32) ||
810       (Header.Machine == COFF::IMAGE_FILE_MACHINE_I386 &&
811        Reloc.Data.Type == COFF::IMAGE_REL_I386_REL32))
812     FixedValue += 4;
813
814   if (Header.Machine == COFF::IMAGE_FILE_MACHINE_ARMNT) {
815     switch (Reloc.Data.Type) {
816     case COFF::IMAGE_REL_ARM_ABSOLUTE:
817     case COFF::IMAGE_REL_ARM_ADDR32:
818     case COFF::IMAGE_REL_ARM_ADDR32NB:
819     case COFF::IMAGE_REL_ARM_TOKEN:
820     case COFF::IMAGE_REL_ARM_SECTION:
821     case COFF::IMAGE_REL_ARM_SECREL:
822       break;
823     case COFF::IMAGE_REL_ARM_BRANCH11:
824     case COFF::IMAGE_REL_ARM_BLX11:
825     // IMAGE_REL_ARM_BRANCH11 and IMAGE_REL_ARM_BLX11 are only used for
826     // pre-ARMv7, which implicitly rules it out of ARMNT (it would be valid
827     // for Windows CE).
828     case COFF::IMAGE_REL_ARM_BRANCH24:
829     case COFF::IMAGE_REL_ARM_BLX24:
830     case COFF::IMAGE_REL_ARM_MOV32A:
831       // IMAGE_REL_ARM_BRANCH24, IMAGE_REL_ARM_BLX24, IMAGE_REL_ARM_MOV32A are
832       // only used for ARM mode code, which is documented as being unsupported
833       // by Windows on ARM.  Empirical proof indicates that masm is able to
834       // generate the relocations however the rest of the MSVC toolchain is
835       // unable to handle it.
836       llvm_unreachable("unsupported relocation");
837       break;
838     case COFF::IMAGE_REL_ARM_MOV32T:
839       break;
840     case COFF::IMAGE_REL_ARM_BRANCH20T:
841     case COFF::IMAGE_REL_ARM_BRANCH24T:
842     case COFF::IMAGE_REL_ARM_BLX23T:
843       // IMAGE_REL_BRANCH20T, IMAGE_REL_ARM_BRANCH24T, IMAGE_REL_ARM_BLX23T all
844       // perform a 4 byte adjustment to the relocation.  Relative branches are
845       // offset by 4 on ARM, however, because there is no RELA relocations, all
846       // branches are offset by 4.
847       FixedValue = FixedValue + 4;
848       break;
849     }
850   }
851
852   // The fixed value never makes sense for section indices, ignore it.
853   if (Fixup.getKind() == FK_SecRel_2)
854     FixedValue = 0;
855
856   if (TargetObjectWriter->recordRelocation(Fixup))
857     Sec->Relocations.push_back(Reloc);
858 }
859
860 static std::time_t getTime() {
861   std::time_t Now = time(nullptr);
862   if (Now < 0 || !isUInt<32>(Now))
863     return UINT32_MAX;
864   return Now;
865 }
866
867 // Create .file symbols.
868 void WinCOFFObjectWriter::createFileSymbols(MCAssembler &Asm) {
869   for (const std::string &Name : Asm.getFileNames()) {
870     // round up to calculate the number of auxiliary symbols required
871     unsigned SymbolSize = UseBigObj ? COFF::Symbol32Size : COFF::Symbol16Size;
872     unsigned Count = (Name.size() + SymbolSize - 1) / SymbolSize;
873
874     COFFSymbol *File = createSymbol(".file");
875     File->Data.SectionNumber = COFF::IMAGE_SYM_DEBUG;
876     File->Data.StorageClass = COFF::IMAGE_SYM_CLASS_FILE;
877     File->Aux.resize(Count);
878
879     unsigned Offset = 0;
880     unsigned Length = Name.size();
881     for (auto &Aux : File->Aux) {
882       Aux.AuxType = ATFile;
883
884       if (Length > SymbolSize) {
885         memcpy(&Aux.Aux, Name.c_str() + Offset, SymbolSize);
886         Length = Length - SymbolSize;
887       } else {
888         memcpy(&Aux.Aux, Name.c_str() + Offset, Length);
889         memset((char *)&Aux.Aux + Length, 0, SymbolSize - Length);
890         break;
891       }
892
893       Offset += SymbolSize;
894     }
895   }
896 }
897
898 static bool isAssociative(const COFFSection &Section) {
899   return Section.Symbol->Aux[0].Aux.SectionDefinition.Selection ==
900          COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
901 }
902
903 void WinCOFFObjectWriter::assignSectionNumbers() {
904   size_t I = 1;
905   auto Assign = [&](COFFSection &Section) {
906     Section.Number = I;
907     Section.Symbol->Data.SectionNumber = I;
908     Section.Symbol->Aux[0].Aux.SectionDefinition.Number = I;
909     ++I;
910   };
911
912   // Although it is not explicitly requested by the Microsoft COFF spec,
913   // we should avoid emitting forward associative section references,
914   // because MSVC link.exe as of 2017 cannot handle that.
915   for (const std::unique_ptr<COFFSection> &Section : Sections)
916     if (!isAssociative(*Section))
917       Assign(*Section);
918   for (const std::unique_ptr<COFFSection> &Section : Sections)
919     if (isAssociative(*Section))
920       Assign(*Section);
921 }
922
923 // Assign file offsets to COFF object file structures.
924 void WinCOFFObjectWriter::assignFileOffsets(MCAssembler &Asm,
925                                             const MCAsmLayout &Layout) {
926   unsigned Offset = getInitialOffset();
927
928   Offset += UseBigObj ? COFF::Header32Size : COFF::Header16Size;
929   Offset += COFF::SectionSize * Header.NumberOfSections;
930
931   for (const auto &Section : Asm) {
932     COFFSection *Sec = SectionMap[&Section];
933
934     if (Sec->Number == -1)
935       continue;
936
937     Sec->Header.SizeOfRawData = Layout.getSectionAddressSize(&Section);
938
939     if (IsPhysicalSection(Sec)) {
940       // Align the section data to a four byte boundary.
941       Offset = alignTo(Offset, 4);
942       Sec->Header.PointerToRawData = Offset;
943
944       Offset += Sec->Header.SizeOfRawData;
945     }
946
947     if (!Sec->Relocations.empty()) {
948       bool RelocationsOverflow = Sec->Relocations.size() >= 0xffff;
949
950       if (RelocationsOverflow) {
951         // Signal overflow by setting NumberOfRelocations to max value. Actual
952         // size is found in reloc #0. Microsoft tools understand this.
953         Sec->Header.NumberOfRelocations = 0xffff;
954       } else {
955         Sec->Header.NumberOfRelocations = Sec->Relocations.size();
956       }
957       Sec->Header.PointerToRelocations = Offset;
958
959       if (RelocationsOverflow) {
960         // Reloc #0 will contain actual count, so make room for it.
961         Offset += COFF::RelocationSize;
962       }
963
964       Offset += COFF::RelocationSize * Sec->Relocations.size();
965
966       for (auto &Relocation : Sec->Relocations) {
967         assert(Relocation.Symb->getIndex() != -1);
968         Relocation.Data.SymbolTableIndex = Relocation.Symb->getIndex();
969       }
970     }
971
972     assert(Sec->Symbol->Aux.size() == 1 &&
973            "Section's symbol must have one aux!");
974     AuxSymbol &Aux = Sec->Symbol->Aux[0];
975     assert(Aux.AuxType == ATSectionDefinition &&
976            "Section's symbol's aux symbol must be a Section Definition!");
977     Aux.Aux.SectionDefinition.Length = Sec->Header.SizeOfRawData;
978     Aux.Aux.SectionDefinition.NumberOfRelocations =
979         Sec->Header.NumberOfRelocations;
980     Aux.Aux.SectionDefinition.NumberOfLinenumbers =
981         Sec->Header.NumberOfLineNumbers;
982   }
983
984   Header.PointerToSymbolTable = Offset;
985 }
986
987 void WinCOFFObjectWriter::writeObject(MCAssembler &Asm,
988                                       const MCAsmLayout &Layout) {
989   if (Sections.size() > INT32_MAX)
990     report_fatal_error(
991         "PE COFF object files can't have more than 2147483647 sections");
992
993   UseBigObj = Sections.size() > COFF::MaxNumberOfSections16;
994   Header.NumberOfSections = Sections.size();
995   Header.NumberOfSymbols = 0;
996
997   assignSectionNumbers();
998   createFileSymbols(Asm);
999
1000   for (auto &Symbol : Symbols) {
1001     // Update section number & offset for symbols that have them.
1002     if (Symbol->Section)
1003       Symbol->Data.SectionNumber = Symbol->Section->Number;
1004     Symbol->setIndex(Header.NumberOfSymbols++);
1005     // Update auxiliary symbol info.
1006     Symbol->Data.NumberOfAuxSymbols = Symbol->Aux.size();
1007     Header.NumberOfSymbols += Symbol->Data.NumberOfAuxSymbols;
1008   }
1009
1010   // Build string table.
1011   for (const auto &S : Sections)
1012     if (S->Name.size() > COFF::NameSize)
1013       Strings.add(S->Name);
1014   for (const auto &S : Symbols)
1015     if (S->Name.size() > COFF::NameSize)
1016       Strings.add(S->Name);
1017   Strings.finalize();
1018
1019   // Set names.
1020   for (const auto &S : Sections)
1021     SetSectionName(*S);
1022   for (auto &S : Symbols)
1023     SetSymbolName(*S);
1024
1025   // Fixup weak external references.
1026   for (auto &Symbol : Symbols) {
1027     if (Symbol->Other) {
1028       assert(Symbol->getIndex() != -1);
1029       assert(Symbol->Aux.size() == 1 && "Symbol must contain one aux symbol!");
1030       assert(Symbol->Aux[0].AuxType == ATWeakExternal &&
1031              "Symbol's aux symbol must be a Weak External!");
1032       Symbol->Aux[0].Aux.WeakExternal.TagIndex = Symbol->Other->getIndex();
1033     }
1034   }
1035
1036   // Fixup associative COMDAT sections.
1037   for (auto &Section : Sections) {
1038     if (Section->Symbol->Aux[0].Aux.SectionDefinition.Selection !=
1039         COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
1040       continue;
1041
1042     const MCSectionCOFF &MCSec = *Section->MCSection;
1043
1044     const MCSymbol *COMDAT = MCSec.getCOMDATSymbol();
1045     assert(COMDAT);
1046     COFFSymbol *COMDATSymbol = GetOrCreateCOFFSymbol(COMDAT);
1047     assert(COMDATSymbol);
1048     COFFSection *Assoc = COMDATSymbol->Section;
1049     if (!Assoc)
1050       report_fatal_error(
1051           Twine("Missing associated COMDAT section for section ") +
1052           MCSec.getSectionName());
1053
1054     // Skip this section if the associated section is unused.
1055     if (Assoc->Number == -1)
1056       continue;
1057
1058     Section->Symbol->Aux[0].Aux.SectionDefinition.Number = Assoc->Number;
1059   }
1060
1061   assignFileOffsets(Asm, Layout);
1062
1063   // MS LINK expects to be able to use this timestamp to implement their
1064   // /INCREMENTAL feature.
1065   if (Asm.isIncrementalLinkerCompatible()) {
1066     Header.TimeDateStamp = getTime();
1067   } else {
1068     // Have deterministic output if /INCREMENTAL isn't needed. Also matches GNU.
1069     Header.TimeDateStamp = 0;
1070   }
1071
1072   // Write it all to disk...
1073   WriteFileHeader(Header);
1074   writeSectionHeaders();
1075
1076   // Write section contents.
1077   sections::iterator I = Sections.begin();
1078   sections::iterator IE = Sections.end();
1079   MCAssembler::iterator J = Asm.begin();
1080   MCAssembler::iterator JE = Asm.end();
1081   for (; I != IE && J != JE; ++I, ++J)
1082     writeSection(Asm, Layout, **I, *J);
1083
1084   assert(getStream().tell() == Header.PointerToSymbolTable &&
1085          "Header::PointerToSymbolTable is insane!");
1086
1087   // Write a symbol table.
1088   for (auto &Symbol : Symbols)
1089     if (Symbol->getIndex() != -1)
1090       WriteSymbol(*Symbol);
1091
1092   // Write a string table, which completes the entire COFF file.
1093   Strings.write(getStream());
1094 }
1095
1096 MCWinCOFFObjectTargetWriter::MCWinCOFFObjectTargetWriter(unsigned Machine_)
1097     : Machine(Machine_) {}
1098
1099 // Pin the vtable to this file.
1100 void MCWinCOFFObjectTargetWriter::anchor() {}
1101
1102 //------------------------------------------------------------------------------
1103 // WinCOFFObjectWriter factory function
1104
1105 MCObjectWriter *
1106 llvm::createWinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW,
1107                                 raw_pwrite_stream &OS) {
1108   return new WinCOFFObjectWriter(MOTW, OS);
1109 }