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