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