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