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