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