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