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