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