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