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