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