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