]> CyberLeo.Net >> Repos - FreeBSD/releng/10.0.git/blob - contrib/llvm/lib/MC/WinCOFFObjectWriter.cpp
- Copy stable/10 (r259064) to releng/10.0 as part of the
[FreeBSD/releng/10.0.git] / contrib / llvm / 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/OwningPtr.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/ADT/StringRef.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   llvm::OwningPtr<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   ~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,
151                     MCAssembler &Assembler);
152
153   void MakeSymbolReal(COFFSymbol &S, size_t Index);
154   void MakeSectionReal(COFFSection &S, size_t Number);
155
156   bool ExportSection(COFFSection const *S);
157   bool ExportSymbol(MCSymbolData const &SymbolData, MCAssembler &Asm);
158
159   bool IsPhysicalSection(COFFSection *S);
160
161   // Entity writing methods.
162
163   void WriteFileHeader(const COFF::header &Header);
164   void WriteSymbol(const COFFSymbol *S);
165   void WriteAuxiliarySymbols(const COFFSymbol::AuxiliarySymbols &S);
166   void WriteSectionHeader(const COFF::section &S);
167   void WriteRelocation(const COFF::relocation &R);
168
169   // MCObjectWriter interface implementation.
170
171   void ExecutePostLayoutBinding(MCAssembler &Asm, const MCAsmLayout &Layout);
172
173   void RecordRelocation(const MCAssembler &Asm,
174                         const MCAsmLayout &Layout,
175                         const MCFragment *Fragment,
176                         const MCFixup &Fixup,
177                         MCValue Target,
178                         uint64_t &FixedValue);
179
180   void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
181 };
182 }
183
184 static inline void write_uint32_le(void *Data, uint32_t const &Value) {
185   uint8_t *Ptr = reinterpret_cast<uint8_t *>(Data);
186   Ptr[0] = (Value & 0x000000FF) >>  0;
187   Ptr[1] = (Value & 0x0000FF00) >>  8;
188   Ptr[2] = (Value & 0x00FF0000) >> 16;
189   Ptr[3] = (Value & 0xFF000000) >> 24;
190 }
191
192 static inline void write_uint16_le(void *Data, uint16_t const &Value) {
193   uint8_t *Ptr = reinterpret_cast<uint8_t *>(Data);
194   Ptr[0] = (Value & 0x00FF) >> 0;
195   Ptr[1] = (Value & 0xFF00) >> 8;
196 }
197
198 static inline void write_uint8_le(void *Data, uint8_t const &Value) {
199   uint8_t *Ptr = reinterpret_cast<uint8_t *>(Data);
200   Ptr[0] = (Value & 0xFF) >> 0;
201 }
202
203 //------------------------------------------------------------------------------
204 // Symbol class implementation
205
206 COFFSymbol::COFFSymbol(StringRef name)
207   : Name(name.begin(), name.end())
208   , Other(NULL)
209   , Section(NULL)
210   , Relocations(0)
211   , MCData(NULL) {
212   memset(&Data, 0, sizeof(Data));
213 }
214
215 size_t COFFSymbol::size() const {
216   return COFF::SymbolSize + (Data.NumberOfAuxSymbols * COFF::SymbolSize);
217 }
218
219 // In the case that the name does not fit within 8 bytes, the offset
220 // into the string table is stored in the last 4 bytes instead, leaving
221 // the first 4 bytes as 0.
222 void COFFSymbol::set_name_offset(uint32_t Offset) {
223   write_uint32_le(Data.Name + 0, 0);
224   write_uint32_le(Data.Name + 4, Offset);
225 }
226
227 /// logic to decide if the symbol should be reported in the symbol table
228 bool COFFSymbol::should_keep() const {
229   // no section means its external, keep it
230   if (Section == NULL)
231     return true;
232
233   // if it has relocations pointing at it, keep it
234   if (Relocations > 0)   {
235     assert(Section->Number != -1 && "Sections with relocations must be real!");
236     return true;
237   }
238
239   // if the section its in is being droped, drop it
240   if (Section->Number == -1)
241       return false;
242
243   // if it is the section symbol, keep it
244   if (Section->Symbol == this)
245     return true;
246
247   // if its temporary, drop it
248   if (MCData && MCData->getSymbol().isTemporary())
249       return false;
250
251   // otherwise, keep it
252   return true;
253 }
254
255 //------------------------------------------------------------------------------
256 // Section class implementation
257
258 COFFSection::COFFSection(StringRef name)
259   : Name(name)
260   , MCData(NULL)
261   , Symbol(NULL) {
262   memset(&Header, 0, sizeof(Header));
263 }
264
265 size_t COFFSection::size() {
266   return COFF::SectionSize;
267 }
268
269 //------------------------------------------------------------------------------
270 // StringTable class implementation
271
272 /// Write the length of the string table into Data.
273 /// The length of the string table includes uint32 length header.
274 void StringTable::update_length() {
275   write_uint32_le(&Data.front(), Data.size());
276 }
277
278 StringTable::StringTable() {
279   // The string table data begins with the length of the entire string table
280   // including the length header. Allocate space for this header.
281   Data.resize(4);
282   update_length();
283 }
284
285 size_t StringTable::size() const {
286   return Data.size();
287 }
288
289 /// Add String to the table iff it is not already there.
290 /// @returns the index into the string table where the string is now located.
291 size_t StringTable::insert(StringRef String) {
292   map::iterator i = Map.find(String);
293
294   if (i != Map.end())
295     return i->second;
296
297   size_t Offset = Data.size();
298
299   // Insert string data into string table.
300   Data.insert(Data.end(), String.begin(), String.end());
301   Data.push_back('\0');
302
303   // Put a reference to it in the map.
304   Map[String] = Offset;
305
306   // Update the internal length field.
307   update_length();
308
309   return Offset;
310 }
311
312 //------------------------------------------------------------------------------
313 // WinCOFFObjectWriter class implementation
314
315 WinCOFFObjectWriter::WinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW,
316                                          raw_ostream &OS)
317   : MCObjectWriter(OS, true)
318   , TargetObjectWriter(MOTW) {
319   memset(&Header, 0, sizeof(Header));
320
321   Header.Machine = TargetObjectWriter->getMachine();
322 }
323
324 WinCOFFObjectWriter::~WinCOFFObjectWriter() {
325   for (symbols::iterator I = Symbols.begin(), E = Symbols.end(); I != E; ++I)
326     delete *I;
327   for (sections::iterator I = Sections.begin(), E = Sections.end(); I != E; ++I)
328     delete *I;
329 }
330
331 COFFSymbol *WinCOFFObjectWriter::createSymbol(StringRef Name) {
332   return createCOFFEntity<COFFSymbol>(Name, Symbols);
333 }
334
335 COFFSymbol *WinCOFFObjectWriter::GetOrCreateCOFFSymbol(const MCSymbol * Symbol){
336   symbol_map::iterator i = SymbolMap.find(Symbol);
337   if (i != SymbolMap.end())
338     return i->second;
339   COFFSymbol *RetSymbol
340     = createCOFFEntity<COFFSymbol>(Symbol->getName(), Symbols);
341   SymbolMap[Symbol] = RetSymbol;
342   return RetSymbol;
343 }
344
345 COFFSection *WinCOFFObjectWriter::createSection(StringRef Name) {
346   return createCOFFEntity<COFFSection>(Name, Sections);
347 }
348
349 /// A template used to lookup or create a symbol/section, and initialize it if
350 /// needed.
351 template <typename object_t, typename list_t>
352 object_t *WinCOFFObjectWriter::createCOFFEntity(StringRef Name,
353                                                 list_t &List) {
354   object_t *Object = new object_t(Name);
355
356   List.push_back(Object);
357
358   return Object;
359 }
360
361 /// This function takes a section data object from the assembler
362 /// and creates the associated COFF section staging object.
363 void WinCOFFObjectWriter::DefineSection(MCSectionData const &SectionData) {
364   assert(SectionData.getSection().getVariant() == MCSection::SV_COFF
365     && "Got non COFF section in the COFF backend!");
366   // FIXME: Not sure how to verify this (at least in a debug build).
367   MCSectionCOFF const &Sec =
368     static_cast<MCSectionCOFF const &>(SectionData.getSection());
369
370   COFFSection *coff_section = createSection(Sec.getSectionName());
371   COFFSymbol  *coff_symbol = createSymbol(Sec.getSectionName());
372
373   coff_section->Symbol = coff_symbol;
374   coff_symbol->Section = coff_section;
375   coff_symbol->Data.StorageClass = COFF::IMAGE_SYM_CLASS_STATIC;
376
377   // In this case the auxiliary symbol is a Section Definition.
378   coff_symbol->Aux.resize(1);
379   memset(&coff_symbol->Aux[0], 0, sizeof(coff_symbol->Aux[0]));
380   coff_symbol->Aux[0].AuxType = ATSectionDefinition;
381   coff_symbol->Aux[0].Aux.SectionDefinition.Selection = Sec.getSelection();
382
383   coff_section->Header.Characteristics = Sec.getCharacteristics();
384
385   uint32_t &Characteristics = coff_section->Header.Characteristics;
386   switch (SectionData.getAlignment()) {
387   case 1:    Characteristics |= COFF::IMAGE_SCN_ALIGN_1BYTES;    break;
388   case 2:    Characteristics |= COFF::IMAGE_SCN_ALIGN_2BYTES;    break;
389   case 4:    Characteristics |= COFF::IMAGE_SCN_ALIGN_4BYTES;    break;
390   case 8:    Characteristics |= COFF::IMAGE_SCN_ALIGN_8BYTES;    break;
391   case 16:   Characteristics |= COFF::IMAGE_SCN_ALIGN_16BYTES;   break;
392   case 32:   Characteristics |= COFF::IMAGE_SCN_ALIGN_32BYTES;   break;
393   case 64:   Characteristics |= COFF::IMAGE_SCN_ALIGN_64BYTES;   break;
394   case 128:  Characteristics |= COFF::IMAGE_SCN_ALIGN_128BYTES;  break;
395   case 256:  Characteristics |= COFF::IMAGE_SCN_ALIGN_256BYTES;  break;
396   case 512:  Characteristics |= COFF::IMAGE_SCN_ALIGN_512BYTES;  break;
397   case 1024: Characteristics |= COFF::IMAGE_SCN_ALIGN_1024BYTES; break;
398   case 2048: Characteristics |= COFF::IMAGE_SCN_ALIGN_2048BYTES; break;
399   case 4096: Characteristics |= COFF::IMAGE_SCN_ALIGN_4096BYTES; break;
400   case 8192: Characteristics |= COFF::IMAGE_SCN_ALIGN_8192BYTES; break;
401   default:
402     llvm_unreachable("unsupported section alignment");
403   }
404
405   // Bind internal COFF section to MC section.
406   coff_section->MCData = &SectionData;
407   SectionMap[&SectionData.getSection()] = coff_section;
408 }
409
410 /// This function takes a section data object from the assembler
411 /// and creates the associated COFF symbol staging object.
412 void WinCOFFObjectWriter::DefineSymbol(MCSymbolData const &SymbolData,
413                                        MCAssembler &Assembler) {
414   MCSymbol const &Symbol = SymbolData.getSymbol();
415   COFFSymbol *coff_symbol = GetOrCreateCOFFSymbol(&Symbol);
416   SymbolMap[&Symbol] = coff_symbol;
417
418   if (SymbolData.getFlags() & COFF::SF_WeakExternal) {
419     coff_symbol->Data.StorageClass = COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL;
420
421     if (Symbol.isVariable()) {
422       const MCSymbolRefExpr *SymRef =
423         dyn_cast<MCSymbolRefExpr>(Symbol.getVariableValue());
424
425       if (!SymRef)
426         report_fatal_error("Weak externals may only alias symbols");
427
428       coff_symbol->Other = GetOrCreateCOFFSymbol(&SymRef->getSymbol());
429     } else {
430       std::string WeakName = std::string(".weak.")
431                            +  Symbol.getName().str()
432                            + ".default";
433       COFFSymbol *WeakDefault = createSymbol(WeakName);
434       WeakDefault->Data.SectionNumber = COFF::IMAGE_SYM_ABSOLUTE;
435       WeakDefault->Data.StorageClass  = COFF::IMAGE_SYM_CLASS_EXTERNAL;
436       WeakDefault->Data.Type          = 0;
437       WeakDefault->Data.Value         = 0;
438       coff_symbol->Other = WeakDefault;
439     }
440
441     // Setup the Weak External auxiliary symbol.
442     coff_symbol->Aux.resize(1);
443     memset(&coff_symbol->Aux[0], 0, sizeof(coff_symbol->Aux[0]));
444     coff_symbol->Aux[0].AuxType = ATWeakExternal;
445     coff_symbol->Aux[0].Aux.WeakExternal.TagIndex = 0;
446     coff_symbol->Aux[0].Aux.WeakExternal.Characteristics =
447       COFF::IMAGE_WEAK_EXTERN_SEARCH_LIBRARY;
448
449     coff_symbol->MCData = &SymbolData;
450   } else {
451     const MCSymbolData &ResSymData =
452       Assembler.getSymbolData(Symbol.AliasedSymbol());
453
454     coff_symbol->Data.Type         = (ResSymData.getFlags() & 0x0000FFFF) >>  0;
455     coff_symbol->Data.StorageClass = (ResSymData.getFlags() & 0x00FF0000) >> 16;
456
457     // If no storage class was specified in the streamer, define it here.
458     if (coff_symbol->Data.StorageClass == 0) {
459       bool external = ResSymData.isExternal() || (ResSymData.Fragment == NULL);
460
461       coff_symbol->Data.StorageClass =
462        external ? COFF::IMAGE_SYM_CLASS_EXTERNAL : COFF::IMAGE_SYM_CLASS_STATIC;
463     }
464
465     if (ResSymData.Fragment != NULL)
466       coff_symbol->Section =
467         SectionMap[&ResSymData.Fragment->getParent()->getSection()];
468
469     coff_symbol->MCData = &ResSymData;
470   }
471 }
472
473 /// making a section real involves assigned it a number and putting
474 /// name into the string table if needed
475 void WinCOFFObjectWriter::MakeSectionReal(COFFSection &S, size_t Number) {
476   if (S.Name.size() > COFF::NameSize) {
477     size_t StringTableEntry = Strings.insert(S.Name.c_str());
478
479     // FIXME: Why is this number 999999? This number is never mentioned in the
480     // spec. I'm assuming this is due to the printed value needing to fit into
481     // the S.Header.Name field. In which case why not 9999999 (7 9's instead of
482     // 6)? The spec does not state if this entry should be null terminated in
483     // this case, and thus this seems to be the best way to do it. I think I
484     // just solved my own FIXME...
485     if (StringTableEntry > 999999)
486       report_fatal_error("COFF string table is greater than 999999 bytes.");
487
488     std::sprintf(S.Header.Name, "/%d", unsigned(StringTableEntry));
489   } else
490     std::memcpy(S.Header.Name, S.Name.c_str(), S.Name.size());
491
492   S.Number = Number;
493   S.Symbol->Data.SectionNumber = S.Number;
494   S.Symbol->Aux[0].Aux.SectionDefinition.Number = S.Number;
495 }
496
497 void WinCOFFObjectWriter::MakeSymbolReal(COFFSymbol &S, size_t Index) {
498   if (S.Name.size() > COFF::NameSize) {
499     size_t StringTableEntry = Strings.insert(S.Name.c_str());
500
501     S.set_name_offset(StringTableEntry);
502   } else
503     std::memcpy(S.Data.Name, S.Name.c_str(), S.Name.size());
504   S.Index = Index;
505 }
506
507 bool WinCOFFObjectWriter::ExportSection(COFFSection const *S) {
508   return !S->MCData->getFragmentList().empty();
509 }
510
511 bool WinCOFFObjectWriter::ExportSymbol(MCSymbolData const &SymbolData,
512                                        MCAssembler &Asm) {
513   // This doesn't seem to be right. Strings referred to from the .data section
514   // need symbols so they can be linked to code in the .text section right?
515
516   // return Asm.isSymbolLinkerVisible (&SymbolData);
517
518   // For now, all non-variable symbols are exported,
519   // the linker will sort the rest out for us.
520   return SymbolData.isExternal() || !SymbolData.getSymbol().isVariable();
521 }
522
523 bool WinCOFFObjectWriter::IsPhysicalSection(COFFSection *S) {
524   return (S->Header.Characteristics
525          & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) == 0;
526 }
527
528 //------------------------------------------------------------------------------
529 // entity writing methods
530
531 void WinCOFFObjectWriter::WriteFileHeader(const COFF::header &Header) {
532   WriteLE16(Header.Machine);
533   WriteLE16(Header.NumberOfSections);
534   WriteLE32(Header.TimeDateStamp);
535   WriteLE32(Header.PointerToSymbolTable);
536   WriteLE32(Header.NumberOfSymbols);
537   WriteLE16(Header.SizeOfOptionalHeader);
538   WriteLE16(Header.Characteristics);
539 }
540
541 void WinCOFFObjectWriter::WriteSymbol(const COFFSymbol *S) {
542   WriteBytes(StringRef(S->Data.Name, COFF::NameSize));
543   WriteLE32(S->Data.Value);
544   WriteLE16(S->Data.SectionNumber);
545   WriteLE16(S->Data.Type);
546   Write8(S->Data.StorageClass);
547   Write8(S->Data.NumberOfAuxSymbols);
548   WriteAuxiliarySymbols(S->Aux);
549 }
550
551 void WinCOFFObjectWriter::WriteAuxiliarySymbols(
552                                         const COFFSymbol::AuxiliarySymbols &S) {
553   for(COFFSymbol::AuxiliarySymbols::const_iterator i = S.begin(), e = S.end();
554       i != e; ++i) {
555     switch(i->AuxType) {
556     case ATFunctionDefinition:
557       WriteLE32(i->Aux.FunctionDefinition.TagIndex);
558       WriteLE32(i->Aux.FunctionDefinition.TotalSize);
559       WriteLE32(i->Aux.FunctionDefinition.PointerToLinenumber);
560       WriteLE32(i->Aux.FunctionDefinition.PointerToNextFunction);
561       WriteZeros(sizeof(i->Aux.FunctionDefinition.unused));
562       break;
563     case ATbfAndefSymbol:
564       WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused1));
565       WriteLE16(i->Aux.bfAndefSymbol.Linenumber);
566       WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused2));
567       WriteLE32(i->Aux.bfAndefSymbol.PointerToNextFunction);
568       WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused3));
569       break;
570     case ATWeakExternal:
571       WriteLE32(i->Aux.WeakExternal.TagIndex);
572       WriteLE32(i->Aux.WeakExternal.Characteristics);
573       WriteZeros(sizeof(i->Aux.WeakExternal.unused));
574       break;
575     case ATFile:
576       WriteBytes(StringRef(reinterpret_cast<const char *>(i->Aux.File.FileName),
577                  sizeof(i->Aux.File.FileName)));
578       break;
579     case ATSectionDefinition:
580       WriteLE32(i->Aux.SectionDefinition.Length);
581       WriteLE16(i->Aux.SectionDefinition.NumberOfRelocations);
582       WriteLE16(i->Aux.SectionDefinition.NumberOfLinenumbers);
583       WriteLE32(i->Aux.SectionDefinition.CheckSum);
584       WriteLE16(i->Aux.SectionDefinition.Number);
585       Write8(i->Aux.SectionDefinition.Selection);
586       WriteZeros(sizeof(i->Aux.SectionDefinition.unused));
587       break;
588     }
589   }
590 }
591
592 void WinCOFFObjectWriter::WriteSectionHeader(const COFF::section &S) {
593   WriteBytes(StringRef(S.Name, COFF::NameSize));
594
595   WriteLE32(S.VirtualSize);
596   WriteLE32(S.VirtualAddress);
597   WriteLE32(S.SizeOfRawData);
598   WriteLE32(S.PointerToRawData);
599   WriteLE32(S.PointerToRelocations);
600   WriteLE32(S.PointerToLineNumbers);
601   WriteLE16(S.NumberOfRelocations);
602   WriteLE16(S.NumberOfLineNumbers);
603   WriteLE32(S.Characteristics);
604 }
605
606 void WinCOFFObjectWriter::WriteRelocation(const COFF::relocation &R) {
607   WriteLE32(R.VirtualAddress);
608   WriteLE32(R.SymbolTableIndex);
609   WriteLE16(R.Type);
610 }
611
612 ////////////////////////////////////////////////////////////////////////////////
613 // MCObjectWriter interface implementations
614
615 void WinCOFFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
616                                                    const MCAsmLayout &Layout) {
617   // "Define" each section & symbol. This creates section & symbol
618   // entries in the staging area.
619
620   for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e; i++)
621     DefineSection(*i);
622
623   for (MCAssembler::const_symbol_iterator i = Asm.symbol_begin(),
624                                           e = Asm.symbol_end(); i != e; i++) {
625     if (ExportSymbol(*i, Asm)) {
626       DefineSymbol(*i, Asm);
627     }
628   }
629 }
630
631 void WinCOFFObjectWriter::RecordRelocation(const MCAssembler &Asm,
632                                            const MCAsmLayout &Layout,
633                                            const MCFragment *Fragment,
634                                            const MCFixup &Fixup,
635                                            MCValue Target,
636                                            uint64_t &FixedValue) {
637   assert(Target.getSymA() != NULL && "Relocation must reference a symbol!");
638
639   const MCSymbol *A = &Target.getSymA()->getSymbol();
640   MCSymbolData &A_SD = Asm.getSymbolData(*A);
641
642   MCSectionData const *SectionData = Fragment->getParent();
643
644   // Mark this symbol as requiring an entry in the symbol table.
645   assert(SectionMap.find(&SectionData->getSection()) != SectionMap.end() &&
646          "Section must already have been defined in ExecutePostLayoutBinding!");
647   assert(SymbolMap.find(&A_SD.getSymbol()) != SymbolMap.end() &&
648          "Symbol must already have been defined in ExecutePostLayoutBinding!");
649
650   COFFSection *coff_section = SectionMap[&SectionData->getSection()];
651   COFFSymbol *coff_symbol = SymbolMap[&A_SD.getSymbol()];
652   const MCSymbolRefExpr *SymA = Target.getSymA();
653   const MCSymbolRefExpr *SymB = Target.getSymB();
654   const bool CrossSection = SymB &&
655     &SymA->getSymbol().getSection() != &SymB->getSymbol().getSection();
656
657   if (Target.getSymB()) {
658     const MCSymbol *B = &Target.getSymB()->getSymbol();
659     MCSymbolData &B_SD = Asm.getSymbolData(*B);
660
661     // Offset of the symbol in the section
662     int64_t a = Layout.getSymbolOffset(&B_SD);
663
664     // Ofeset of the relocation in the section
665     int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
666
667     FixedValue = b - a;
668     // In the case where we have SymbA and SymB, we just need to store the delta
669     // between the two symbols.  Update FixedValue to account for the delta, and
670     // skip recording the relocation.
671     if (!CrossSection)
672       return;
673   } else {
674     FixedValue = Target.getConstant();
675   }
676
677   COFFRelocation Reloc;
678
679   Reloc.Data.SymbolTableIndex = 0;
680   Reloc.Data.VirtualAddress = Layout.getFragmentOffset(Fragment);
681
682   // Turn relocations for temporary symbols into section relocations.
683   if (coff_symbol->MCData->getSymbol().isTemporary() || CrossSection) {
684     Reloc.Symb = coff_symbol->Section->Symbol;
685     FixedValue += Layout.getFragmentOffset(coff_symbol->MCData->Fragment)
686                 + coff_symbol->MCData->getOffset();
687   } else
688     Reloc.Symb = coff_symbol;
689
690   ++Reloc.Symb->Relocations;
691
692   Reloc.Data.VirtualAddress += Fixup.getOffset();
693   Reloc.Data.Type = TargetObjectWriter->getRelocType(Target, Fixup,
694                                                      CrossSection);
695
696   // FIXME: Can anyone explain what this does other than adjust for the size
697   // of the offset?
698   if (Reloc.Data.Type == COFF::IMAGE_REL_AMD64_REL32 ||
699       Reloc.Data.Type == COFF::IMAGE_REL_I386_REL32)
700     FixedValue += 4;
701
702   coff_section->Relocations.push_back(Reloc);
703 }
704
705 void WinCOFFObjectWriter::WriteObject(MCAssembler &Asm,
706                                       const MCAsmLayout &Layout) {
707   // Assign symbol and section indexes and offsets.
708   Header.NumberOfSections = 0;
709
710   for (sections::iterator i = Sections.begin(),
711                           e = Sections.end(); i != e; i++) {
712     if (Layout.getSectionAddressSize((*i)->MCData) > 0) {
713       MakeSectionReal(**i, ++Header.NumberOfSections);
714     } else {
715       (*i)->Number = -1;
716     }
717   }
718
719   Header.NumberOfSymbols = 0;
720
721   for (symbols::iterator i = Symbols.begin(), e = Symbols.end(); i != e; i++) {
722     COFFSymbol *coff_symbol = *i;
723     MCSymbolData const *SymbolData = coff_symbol->MCData;
724
725     // Update section number & offset for symbols that have them.
726     if ((SymbolData != NULL) && (SymbolData->Fragment != NULL)) {
727       assert(coff_symbol->Section != NULL);
728
729       coff_symbol->Data.SectionNumber = coff_symbol->Section->Number;
730       coff_symbol->Data.Value = Layout.getFragmentOffset(SymbolData->Fragment)
731                               + SymbolData->Offset;
732     }
733
734     if (coff_symbol->should_keep()) {
735       MakeSymbolReal(*coff_symbol, Header.NumberOfSymbols++);
736
737       // Update auxiliary symbol info.
738       coff_symbol->Data.NumberOfAuxSymbols = coff_symbol->Aux.size();
739       Header.NumberOfSymbols += coff_symbol->Data.NumberOfAuxSymbols;
740     } else
741       coff_symbol->Index = -1;
742   }
743
744   // Fixup weak external references.
745   for (symbols::iterator i = Symbols.begin(), e = Symbols.end(); i != e; i++) {
746     COFFSymbol *coff_symbol = *i;
747     if (coff_symbol->Other != NULL) {
748       assert(coff_symbol->Index != -1);
749       assert(coff_symbol->Aux.size() == 1 &&
750              "Symbol must contain one aux symbol!");
751       assert(coff_symbol->Aux[0].AuxType == ATWeakExternal &&
752              "Symbol's aux symbol must be a Weak External!");
753       coff_symbol->Aux[0].Aux.WeakExternal.TagIndex = coff_symbol->Other->Index;
754     }
755   }
756
757   // Assign file offsets to COFF object file structures.
758
759   unsigned offset = 0;
760
761   offset += COFF::HeaderSize;
762   offset += COFF::SectionSize * Header.NumberOfSections;
763
764   for (MCAssembler::const_iterator i = Asm.begin(),
765                                    e = Asm.end();
766                                    i != e; i++) {
767     COFFSection *Sec = SectionMap[&i->getSection()];
768
769     if (Sec->Number == -1)
770       continue;
771
772     Sec->Header.SizeOfRawData = Layout.getSectionAddressSize(i);
773
774     if (IsPhysicalSection(Sec)) {
775       Sec->Header.PointerToRawData = offset;
776
777       offset += Sec->Header.SizeOfRawData;
778     }
779
780     if (Sec->Relocations.size() > 0) {
781       bool RelocationsOverflow = Sec->Relocations.size() >= 0xffff;
782
783       if (RelocationsOverflow) {
784         // Signal overflow by setting NumberOfSections to max value. Actual
785         // size is found in reloc #0. Microsoft tools understand this.
786         Sec->Header.NumberOfRelocations = 0xffff;
787       } else {
788         Sec->Header.NumberOfRelocations = Sec->Relocations.size();
789       }
790       Sec->Header.PointerToRelocations = offset;
791
792       if (RelocationsOverflow) {
793         // Reloc #0 will contain actual count, so make room for it.
794         offset += COFF::RelocationSize;
795       }
796
797       offset += COFF::RelocationSize * Sec->Relocations.size();
798
799       for (relocations::iterator cr = Sec->Relocations.begin(),
800                                  er = Sec->Relocations.end();
801                                  cr != er; ++cr) {
802         assert((*cr).Symb->Index != -1);
803         (*cr).Data.SymbolTableIndex = (*cr).Symb->Index;
804       }
805     }
806
807     assert(Sec->Symbol->Aux.size() == 1
808       && "Section's symbol must have one aux!");
809     AuxSymbol &Aux = Sec->Symbol->Aux[0];
810     assert(Aux.AuxType == ATSectionDefinition &&
811            "Section's symbol's aux symbol must be a Section Definition!");
812     Aux.Aux.SectionDefinition.Length = Sec->Header.SizeOfRawData;
813     Aux.Aux.SectionDefinition.NumberOfRelocations =
814                                                 Sec->Header.NumberOfRelocations;
815     Aux.Aux.SectionDefinition.NumberOfLinenumbers =
816                                                 Sec->Header.NumberOfLineNumbers;
817   }
818
819   Header.PointerToSymbolTable = offset;
820
821   Header.TimeDateStamp = sys::TimeValue::now().toEpochTime();
822
823   // Write it all to disk...
824   WriteFileHeader(Header);
825
826   {
827     sections::iterator i, ie;
828     MCAssembler::const_iterator j, je;
829
830     for (i = Sections.begin(), ie = Sections.end(); i != ie; i++)
831       if ((*i)->Number != -1) {
832         if ((*i)->Relocations.size() >= 0xffff) {
833           (*i)->Header.Characteristics |= COFF::IMAGE_SCN_LNK_NRELOC_OVFL;
834         }
835         WriteSectionHeader((*i)->Header);
836       }
837
838     for (i = Sections.begin(), ie = Sections.end(),
839          j = Asm.begin(), je = Asm.end();
840          (i != ie) && (j != je); ++i, ++j) {
841
842       if ((*i)->Number == -1)
843         continue;
844
845       if ((*i)->Header.PointerToRawData != 0) {
846         assert(OS.tell() == (*i)->Header.PointerToRawData &&
847                "Section::PointerToRawData is insane!");
848
849         Asm.writeSectionData(j, Layout);
850       }
851
852       if ((*i)->Relocations.size() > 0) {
853         assert(OS.tell() == (*i)->Header.PointerToRelocations &&
854                "Section::PointerToRelocations is insane!");
855
856         if ((*i)->Relocations.size() >= 0xffff) {
857           // In case of overflow, write actual relocation count as first
858           // relocation. Including the synthetic reloc itself (+ 1).
859           COFF::relocation r;
860           r.VirtualAddress = (*i)->Relocations.size() + 1;
861           r.SymbolTableIndex = 0;
862           r.Type = 0;
863           WriteRelocation(r);
864         }
865
866         for (relocations::const_iterator k = (*i)->Relocations.begin(),
867                                                ke = (*i)->Relocations.end();
868                                                k != ke; k++) {
869           WriteRelocation(k->Data);
870         }
871       } else
872         assert((*i)->Header.PointerToRelocations == 0 &&
873                "Section::PointerToRelocations is insane!");
874     }
875   }
876
877   assert(OS.tell() == Header.PointerToSymbolTable &&
878          "Header::PointerToSymbolTable is insane!");
879
880   for (symbols::iterator i = Symbols.begin(), e = Symbols.end(); i != e; i++)
881     if ((*i)->Index != -1)
882       WriteSymbol(*i);
883
884   OS.write((char const *)&Strings.Data.front(), Strings.Data.size());
885 }
886
887 MCWinCOFFObjectTargetWriter::MCWinCOFFObjectTargetWriter(unsigned Machine_) :
888   Machine(Machine_) {
889 }
890
891 //------------------------------------------------------------------------------
892 // WinCOFFObjectWriter factory function
893
894 namespace llvm {
895   MCObjectWriter *createWinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW,
896                                             raw_ostream &OS) {
897     return new WinCOFFObjectWriter(MOTW, OS);
898   }
899 }