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