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