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/Config/config.h"
21 #include "llvm/MC/MCAsmLayout.h"
22 #include "llvm/MC/MCAssembler.h"
23 #include "llvm/MC/MCContext.h"
24 #include "llvm/MC/MCExpr.h"
25 #include "llvm/MC/MCObjectFileInfo.h"
26 #include "llvm/MC/MCObjectWriter.h"
27 #include "llvm/MC/MCSection.h"
28 #include "llvm/MC/MCSectionCOFF.h"
29 #include "llvm/MC/MCSymbolCOFF.h"
30 #include "llvm/MC/MCValue.h"
31 #include "llvm/MC/StringTableBuilder.h"
32 #include "llvm/Support/COFF.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/Endian.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/JamCRC.h"
37 #include "llvm/Support/TimeValue.h"
38 #include <cstdio>
39 #include <ctime>
40 
41 using namespace llvm;
42 
43 #define DEBUG_TYPE "WinCOFFObjectWriter"
44 
45 namespace {
46 typedef SmallString<COFF::NameSize> name;
47 
48 enum AuxiliaryType {
49   ATFunctionDefinition,
50   ATbfAndefSymbol,
51   ATWeakExternal,
52   ATFile,
53   ATSectionDefinition
54 };
55 
56 struct AuxSymbol {
57   AuxiliaryType AuxType;
58   COFF::Auxiliary Aux;
59 };
60 
61 class COFFSymbol;
62 class COFFSection;
63 
64 class COFFSymbol {
65 public:
66   COFF::symbol Data;
67 
68   typedef SmallVector<AuxSymbol, 1> AuxiliarySymbols;
69 
70   name Name;
71   int Index;
72   AuxiliarySymbols Aux;
73   COFFSymbol *Other;
74   COFFSection *Section;
75   int Relocations;
76 
77   const MCSymbol *MC;
78 
79   COFFSymbol(StringRef name);
80   void set_name_offset(uint32_t Offset);
81 
82   int64_t getIndex() const { return Index; }
83   void setIndex(int Value) {
84     Index = Value;
85     if (MC)
86       MC->setIndex(static_cast<uint32_t>(Value));
87   }
88 };
89 
90 // This class contains staging data for a COFF relocation entry.
91 struct COFFRelocation {
92   COFF::relocation Data;
93   COFFSymbol *Symb;
94 
95   COFFRelocation() : Symb(nullptr) {}
96   static size_t size() { return COFF::RelocationSize; }
97 };
98 
99 typedef std::vector<COFFRelocation> relocations;
100 
101 class COFFSection {
102 public:
103   COFF::section Header;
104 
105   std::string Name;
106   int Number;
107   MCSectionCOFF const *MCSection;
108   COFFSymbol *Symbol;
109   relocations Relocations;
110 
111   COFFSection(StringRef name);
112   static size_t size();
113 };
114 
115 class WinCOFFObjectWriter : public MCObjectWriter {
116 public:
117   typedef std::vector<std::unique_ptr<COFFSymbol>> symbols;
118   typedef std::vector<std::unique_ptr<COFFSection>> sections;
119 
120   typedef DenseMap<MCSymbol const *, COFFSymbol *> symbol_map;
121   typedef DenseMap<MCSection const *, COFFSection *> section_map;
122 
123   std::unique_ptr<MCWinCOFFObjectTargetWriter> TargetObjectWriter;
124 
125   // Root level file contents.
126   COFF::header Header;
127   sections Sections;
128   symbols Symbols;
129   StringTableBuilder Strings{StringTableBuilder::WinCOFF};
130 
131   // Maps used during object file creation.
132   section_map SectionMap;
133   symbol_map SymbolMap;
134 
135   bool UseBigObj;
136 
137   WinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW, raw_pwrite_stream &OS);
138 
139   void reset() override {
140     memset(&Header, 0, sizeof(Header));
141     Header.Machine = TargetObjectWriter->getMachine();
142     Sections.clear();
143     Symbols.clear();
144     Strings.clear();
145     SectionMap.clear();
146     SymbolMap.clear();
147     MCObjectWriter::reset();
148   }
149 
150   COFFSymbol *createSymbol(StringRef Name);
151   COFFSymbol *GetOrCreateCOFFSymbol(const MCSymbol *Symbol);
152   COFFSection *createSection(StringRef Name);
153 
154   template <typename object_t, typename list_t>
155   object_t *createCOFFEntity(StringRef Name, list_t &List);
156 
157   void defineSection(MCSectionCOFF const &Sec);
158   void DefineSymbol(const MCSymbol &Symbol, MCAssembler &Assembler,
159                     const MCAsmLayout &Layout);
160 
161   void SetSymbolName(COFFSymbol &S);
162   void SetSectionName(COFFSection &S);
163 
164   bool IsPhysicalSection(COFFSection *S);
165 
166   // Entity writing methods.
167 
168   void WriteFileHeader(const COFF::header &Header);
169   void WriteSymbol(const COFFSymbol &S);
170   void WriteAuxiliarySymbols(const COFFSymbol::AuxiliarySymbols &S);
171   void writeSectionHeader(const COFF::section &S);
172   void WriteRelocation(const COFF::relocation &R);
173 
174   // MCObjectWriter interface implementation.
175 
176   void executePostLayoutBinding(MCAssembler &Asm,
177                                 const MCAsmLayout &Layout) override;
178 
179   bool isSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
180                                               const MCSymbol &SymA,
181                                               const MCFragment &FB, bool InSet,
182                                               bool IsPCRel) const override;
183 
184   bool isWeak(const MCSymbol &Sym) const override;
185 
186   void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
187                         const MCFragment *Fragment, const MCFixup &Fixup,
188                         MCValue Target, bool &IsPCRel,
189                         uint64_t &FixedValue) override;
190 
191   void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
192 };
193 }
194 
195 static inline void write_uint32_le(void *Data, uint32_t Value) {
196   support::endian::write<uint32_t, support::little, support::unaligned>(Data,
197                                                                         Value);
198 }
199 
200 //------------------------------------------------------------------------------
201 // Symbol class implementation
202 
203 COFFSymbol::COFFSymbol(StringRef name)
204     : Name(name.begin(), name.end()), Other(nullptr), Section(nullptr),
205       Relocations(0), MC(nullptr) {
206   memset(&Data, 0, sizeof(Data));
207 }
208 
209 // In the case that the name does not fit within 8 bytes, the offset
210 // into the string table is stored in the last 4 bytes instead, leaving
211 // the first 4 bytes as 0.
212 void COFFSymbol::set_name_offset(uint32_t Offset) {
213   write_uint32_le(Data.Name + 0, 0);
214   write_uint32_le(Data.Name + 4, Offset);
215 }
216 
217 //------------------------------------------------------------------------------
218 // Section class implementation
219 
220 COFFSection::COFFSection(StringRef name)
221     : Name(name), MCSection(nullptr), Symbol(nullptr) {
222   memset(&Header, 0, sizeof(Header));
223 }
224 
225 size_t COFFSection::size() { return COFF::SectionSize; }
226 
227 //------------------------------------------------------------------------------
228 // WinCOFFObjectWriter class implementation
229 
230 WinCOFFObjectWriter::WinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW,
231                                          raw_pwrite_stream &OS)
232     : MCObjectWriter(OS, true), TargetObjectWriter(MOTW) {
233   memset(&Header, 0, sizeof(Header));
234 
235   Header.Machine = TargetObjectWriter->getMachine();
236 }
237 
238 COFFSymbol *WinCOFFObjectWriter::createSymbol(StringRef Name) {
239   return createCOFFEntity<COFFSymbol>(Name, Symbols);
240 }
241 
242 COFFSymbol *WinCOFFObjectWriter::GetOrCreateCOFFSymbol(const MCSymbol *Symbol) {
243   symbol_map::iterator i = SymbolMap.find(Symbol);
244   if (i != SymbolMap.end())
245     return i->second;
246   COFFSymbol *RetSymbol =
247       createCOFFEntity<COFFSymbol>(Symbol->getName(), Symbols);
248   SymbolMap[Symbol] = RetSymbol;
249   return RetSymbol;
250 }
251 
252 COFFSection *WinCOFFObjectWriter::createSection(StringRef Name) {
253   return createCOFFEntity<COFFSection>(Name, Sections);
254 }
255 
256 /// A template used to lookup or create a symbol/section, and initialize it if
257 /// needed.
258 template <typename object_t, typename list_t>
259 object_t *WinCOFFObjectWriter::createCOFFEntity(StringRef Name, list_t &List) {
260   List.push_back(make_unique<object_t>(Name));
261 
262   return List.back().get();
263 }
264 
265 /// This function takes a section data object from the assembler
266 /// and creates the associated COFF section staging object.
267 void WinCOFFObjectWriter::defineSection(MCSectionCOFF const &Sec) {
268   COFFSection *coff_section = createSection(Sec.getSectionName());
269   COFFSymbol *coff_symbol = createSymbol(Sec.getSectionName());
270   if (Sec.getSelection() != COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) {
271     if (const MCSymbol *S = Sec.getCOMDATSymbol()) {
272       COFFSymbol *COMDATSymbol = GetOrCreateCOFFSymbol(S);
273       if (COMDATSymbol->Section)
274         report_fatal_error("two sections have the same comdat");
275       COMDATSymbol->Section = coff_section;
276     }
277   }
278 
279   coff_section->Symbol = coff_symbol;
280   coff_symbol->Section = coff_section;
281   coff_symbol->Data.StorageClass = COFF::IMAGE_SYM_CLASS_STATIC;
282 
283   // In this case the auxiliary symbol is a Section Definition.
284   coff_symbol->Aux.resize(1);
285   memset(&coff_symbol->Aux[0], 0, sizeof(coff_symbol->Aux[0]));
286   coff_symbol->Aux[0].AuxType = ATSectionDefinition;
287   coff_symbol->Aux[0].Aux.SectionDefinition.Selection = Sec.getSelection();
288 
289   coff_section->Header.Characteristics = Sec.getCharacteristics();
290 
291   uint32_t &Characteristics = coff_section->Header.Characteristics;
292   switch (Sec.getAlignment()) {
293   case 1:
294     Characteristics |= COFF::IMAGE_SCN_ALIGN_1BYTES;
295     break;
296   case 2:
297     Characteristics |= COFF::IMAGE_SCN_ALIGN_2BYTES;
298     break;
299   case 4:
300     Characteristics |= COFF::IMAGE_SCN_ALIGN_4BYTES;
301     break;
302   case 8:
303     Characteristics |= COFF::IMAGE_SCN_ALIGN_8BYTES;
304     break;
305   case 16:
306     Characteristics |= COFF::IMAGE_SCN_ALIGN_16BYTES;
307     break;
308   case 32:
309     Characteristics |= COFF::IMAGE_SCN_ALIGN_32BYTES;
310     break;
311   case 64:
312     Characteristics |= COFF::IMAGE_SCN_ALIGN_64BYTES;
313     break;
314   case 128:
315     Characteristics |= COFF::IMAGE_SCN_ALIGN_128BYTES;
316     break;
317   case 256:
318     Characteristics |= COFF::IMAGE_SCN_ALIGN_256BYTES;
319     break;
320   case 512:
321     Characteristics |= COFF::IMAGE_SCN_ALIGN_512BYTES;
322     break;
323   case 1024:
324     Characteristics |= COFF::IMAGE_SCN_ALIGN_1024BYTES;
325     break;
326   case 2048:
327     Characteristics |= COFF::IMAGE_SCN_ALIGN_2048BYTES;
328     break;
329   case 4096:
330     Characteristics |= COFF::IMAGE_SCN_ALIGN_4096BYTES;
331     break;
332   case 8192:
333     Characteristics |= COFF::IMAGE_SCN_ALIGN_8192BYTES;
334     break;
335   default:
336     llvm_unreachable("unsupported section alignment");
337   }
338 
339   // Bind internal COFF section to MC section.
340   coff_section->MCSection = &Sec;
341   SectionMap[&Sec] = coff_section;
342 }
343 
344 static uint64_t getSymbolValue(const MCSymbol &Symbol,
345                                const MCAsmLayout &Layout) {
346   if (Symbol.isCommon() && Symbol.isExternal())
347     return Symbol.getCommonSize();
348 
349   uint64_t Res;
350   if (!Layout.getSymbolOffset(Symbol, Res))
351     return 0;
352 
353   return Res;
354 }
355 
356 /// This function takes a symbol data object from the assembler
357 /// and creates the associated COFF symbol staging object.
358 void WinCOFFObjectWriter::DefineSymbol(const MCSymbol &Symbol,
359                                        MCAssembler &Assembler,
360                                        const MCAsmLayout &Layout) {
361   COFFSymbol *coff_symbol = GetOrCreateCOFFSymbol(&Symbol);
362 
363   if (cast<MCSymbolCOFF>(Symbol).isWeakExternal()) {
364     coff_symbol->Data.StorageClass = COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL;
365 
366     if (Symbol.isVariable()) {
367       const MCSymbolRefExpr *SymRef =
368           dyn_cast<MCSymbolRefExpr>(Symbol.getVariableValue());
369 
370       if (!SymRef)
371         report_fatal_error("Weak externals may only alias symbols");
372 
373       coff_symbol->Other = GetOrCreateCOFFSymbol(&SymRef->getSymbol());
374     } else {
375       std::string WeakName = (".weak." + Symbol.getName() + ".default").str();
376       COFFSymbol *WeakDefault = createSymbol(WeakName);
377       WeakDefault->Data.SectionNumber = COFF::IMAGE_SYM_ABSOLUTE;
378       WeakDefault->Data.StorageClass = COFF::IMAGE_SYM_CLASS_EXTERNAL;
379       WeakDefault->Data.Type = 0;
380       WeakDefault->Data.Value = 0;
381       coff_symbol->Other = WeakDefault;
382     }
383 
384     // Setup the Weak External auxiliary symbol.
385     coff_symbol->Aux.resize(1);
386     memset(&coff_symbol->Aux[0], 0, sizeof(coff_symbol->Aux[0]));
387     coff_symbol->Aux[0].AuxType = ATWeakExternal;
388     coff_symbol->Aux[0].Aux.WeakExternal.TagIndex = 0;
389     coff_symbol->Aux[0].Aux.WeakExternal.Characteristics =
390         COFF::IMAGE_WEAK_EXTERN_SEARCH_LIBRARY;
391 
392     coff_symbol->MC = &Symbol;
393   } else {
394     const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
395     coff_symbol->Data.Value = getSymbolValue(Symbol, Layout);
396 
397     const MCSymbolCOFF &SymbolCOFF = cast<MCSymbolCOFF>(Symbol);
398     coff_symbol->Data.Type = SymbolCOFF.getType();
399     coff_symbol->Data.StorageClass = SymbolCOFF.getClass();
400 
401     // If no storage class was specified in the streamer, define it here.
402     if (coff_symbol->Data.StorageClass == COFF::IMAGE_SYM_CLASS_NULL) {
403       bool IsExternal = Symbol.isExternal() ||
404                         (!Symbol.getFragment() && !Symbol.isVariable());
405 
406       coff_symbol->Data.StorageClass = IsExternal
407                                            ? COFF::IMAGE_SYM_CLASS_EXTERNAL
408                                            : COFF::IMAGE_SYM_CLASS_STATIC;
409     }
410 
411     if (!Base) {
412       coff_symbol->Data.SectionNumber = COFF::IMAGE_SYM_ABSOLUTE;
413     } else {
414       if (Base->getFragment()) {
415         COFFSection *Sec = SectionMap[Base->getFragment()->getParent()];
416 
417         if (coff_symbol->Section && coff_symbol->Section != Sec)
418           report_fatal_error("conflicting sections for symbol");
419 
420         coff_symbol->Section = Sec;
421       }
422     }
423 
424     coff_symbol->MC = &Symbol;
425   }
426 }
427 
428 // Maximum offsets for different string table entry encodings.
429 enum : unsigned { Max7DecimalOffset = 9999999U };
430 enum : 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 <= Max7DecimalOffset) {
459       SmallVector<char, COFF::NameSize> Buffer;
460       Twine('/').concat(Twine(StringTableEntry)).toVector(Buffer);
461       assert(Buffer.size() <= COFF::NameSize && Buffer.size() >= 2);
462 
463       std::memcpy(S.Header.Name, Buffer.data(), Buffer.size());
464     } else if (StringTableEntry <= MaxBase64Offset) {
465       // Starting with 10,000,000, offsets are encoded as base64.
466       encodeBase64StringEntry(S.Header.Name, StringTableEntry);
467     } else {
468       report_fatal_error("COFF string table is greater than 64 GB.");
469     }
470   } else {
471     std::memcpy(S.Header.Name, S.Name.c_str(), S.Name.size());
472   }
473 }
474 
475 void WinCOFFObjectWriter::SetSymbolName(COFFSymbol &S) {
476   if (S.Name.size() > COFF::NameSize)
477     S.set_name_offset(Strings.getOffset(S.Name));
478   else
479     std::memcpy(S.Data.Name, S.Name.c_str(), S.Name.size());
480 }
481 
482 bool WinCOFFObjectWriter::IsPhysicalSection(COFFSection *S) {
483   return (S->Header.Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) ==
484          0;
485 }
486 
487 //------------------------------------------------------------------------------
488 // entity writing methods
489 
490 void WinCOFFObjectWriter::WriteFileHeader(const COFF::header &Header) {
491   if (UseBigObj) {
492     writeLE16(COFF::IMAGE_FILE_MACHINE_UNKNOWN);
493     writeLE16(0xFFFF);
494     writeLE16(COFF::BigObjHeader::MinBigObjectVersion);
495     writeLE16(Header.Machine);
496     writeLE32(Header.TimeDateStamp);
497     writeBytes(StringRef(COFF::BigObjMagic, sizeof(COFF::BigObjMagic)));
498     writeLE32(0);
499     writeLE32(0);
500     writeLE32(0);
501     writeLE32(0);
502     writeLE32(Header.NumberOfSections);
503     writeLE32(Header.PointerToSymbolTable);
504     writeLE32(Header.NumberOfSymbols);
505   } else {
506     writeLE16(Header.Machine);
507     writeLE16(static_cast<int16_t>(Header.NumberOfSections));
508     writeLE32(Header.TimeDateStamp);
509     writeLE32(Header.PointerToSymbolTable);
510     writeLE32(Header.NumberOfSymbols);
511     writeLE16(Header.SizeOfOptionalHeader);
512     writeLE16(Header.Characteristics);
513   }
514 }
515 
516 void WinCOFFObjectWriter::WriteSymbol(const COFFSymbol &S) {
517   writeBytes(StringRef(S.Data.Name, COFF::NameSize));
518   writeLE32(S.Data.Value);
519   if (UseBigObj)
520     writeLE32(S.Data.SectionNumber);
521   else
522     writeLE16(static_cast<int16_t>(S.Data.SectionNumber));
523   writeLE16(S.Data.Type);
524   write8(S.Data.StorageClass);
525   write8(S.Data.NumberOfAuxSymbols);
526   WriteAuxiliarySymbols(S.Aux);
527 }
528 
529 void WinCOFFObjectWriter::WriteAuxiliarySymbols(
530     const COFFSymbol::AuxiliarySymbols &S) {
531   for (COFFSymbol::AuxiliarySymbols::const_iterator i = S.begin(), e = S.end();
532        i != e; ++i) {
533     switch (i->AuxType) {
534     case ATFunctionDefinition:
535       writeLE32(i->Aux.FunctionDefinition.TagIndex);
536       writeLE32(i->Aux.FunctionDefinition.TotalSize);
537       writeLE32(i->Aux.FunctionDefinition.PointerToLinenumber);
538       writeLE32(i->Aux.FunctionDefinition.PointerToNextFunction);
539       WriteZeros(sizeof(i->Aux.FunctionDefinition.unused));
540       if (UseBigObj)
541         WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
542       break;
543     case ATbfAndefSymbol:
544       WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused1));
545       writeLE16(i->Aux.bfAndefSymbol.Linenumber);
546       WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused2));
547       writeLE32(i->Aux.bfAndefSymbol.PointerToNextFunction);
548       WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused3));
549       if (UseBigObj)
550         WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
551       break;
552     case ATWeakExternal:
553       writeLE32(i->Aux.WeakExternal.TagIndex);
554       writeLE32(i->Aux.WeakExternal.Characteristics);
555       WriteZeros(sizeof(i->Aux.WeakExternal.unused));
556       if (UseBigObj)
557         WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
558       break;
559     case ATFile:
560       writeBytes(
561           StringRef(reinterpret_cast<const char *>(&i->Aux),
562                     UseBigObj ? COFF::Symbol32Size : COFF::Symbol16Size));
563       break;
564     case ATSectionDefinition:
565       writeLE32(i->Aux.SectionDefinition.Length);
566       writeLE16(i->Aux.SectionDefinition.NumberOfRelocations);
567       writeLE16(i->Aux.SectionDefinition.NumberOfLinenumbers);
568       writeLE32(i->Aux.SectionDefinition.CheckSum);
569       writeLE16(static_cast<int16_t>(i->Aux.SectionDefinition.Number));
570       write8(i->Aux.SectionDefinition.Selection);
571       WriteZeros(sizeof(i->Aux.SectionDefinition.unused));
572       writeLE16(static_cast<int16_t>(i->Aux.SectionDefinition.Number >> 16));
573       if (UseBigObj)
574         WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
575       break;
576     }
577   }
578 }
579 
580 void WinCOFFObjectWriter::writeSectionHeader(const COFF::section &S) {
581   writeBytes(StringRef(S.Name, COFF::NameSize));
582 
583   writeLE32(S.VirtualSize);
584   writeLE32(S.VirtualAddress);
585   writeLE32(S.SizeOfRawData);
586   writeLE32(S.PointerToRawData);
587   writeLE32(S.PointerToRelocations);
588   writeLE32(S.PointerToLineNumbers);
589   writeLE16(S.NumberOfRelocations);
590   writeLE16(S.NumberOfLineNumbers);
591   writeLE32(S.Characteristics);
592 }
593 
594 void WinCOFFObjectWriter::WriteRelocation(const COFF::relocation &R) {
595   writeLE32(R.VirtualAddress);
596   writeLE32(R.SymbolTableIndex);
597   writeLE16(R.Type);
598 }
599 
600 ////////////////////////////////////////////////////////////////////////////////
601 // MCObjectWriter interface implementations
602 
603 void WinCOFFObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
604                                                    const MCAsmLayout &Layout) {
605   // "Define" each section & symbol. This creates section & symbol
606   // entries in the staging area.
607   for (const auto &Section : Asm)
608     defineSection(static_cast<const MCSectionCOFF &>(Section));
609 
610   for (const MCSymbol &Symbol : Asm.symbols())
611     if (!Symbol.isTemporary())
612       DefineSymbol(Symbol, Asm, Layout);
613 }
614 
615 bool WinCOFFObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(
616     const MCAssembler &Asm, const MCSymbol &SymA, const MCFragment &FB,
617     bool InSet, bool IsPCRel) const {
618   // MS LINK expects to be able to replace all references to a function with a
619   // thunk to implement their /INCREMENTAL feature.  Make sure we don't optimize
620   // away any relocations to functions.
621   uint16_t Type = cast<MCSymbolCOFF>(SymA).getType();
622   if (Asm.isIncrementalLinkerCompatible() &&
623       (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 = alignTo(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   // MS LINK expects to be able to use this timestamp to implement their
971   // /INCREMENTAL feature.
972   if (Asm.isIncrementalLinkerCompatible()) {
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     // Have deterministic output if /INCREMENTAL isn't needed. Also matches GNU.
979     Header.TimeDateStamp = 0;
980   }
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 }
1091