MC: Add WinCOFFObjectWriter implementation.
[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/MCObjectWriter.h"
17 #include "llvm/MC/MCSection.h"
18 #include "llvm/MC/MCContext.h"
19 #include "llvm/MC/MCSymbol.h"
20 #include "llvm/MC/MCExpr.h"
21 #include "llvm/MC/MCValue.h"
22 #include "llvm/MC/MCAssembler.h"
23 #include "llvm/MC/MCAsmLayout.h"
24 #include "llvm/MC/MCSectionCOFF.h"
25
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/StringMap.h"
28 #include "llvm/ADT/StringRef.h"
29
30 #include "llvm/Support/COFF.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33
34 #include <cstdio>
35
36 using namespace llvm;
37
38 namespace {
39 typedef llvm::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 public:
56   COFF::symbol Data;
57
58   typedef llvm::SmallVector<AuxSymbol, 1> AuxiliarySymbols;
59
60   name             Name;
61   size_t           Index;
62   AuxiliarySymbols Aux;
63   COFFSymbol      *Other;
64
65   MCSymbolData const *MCData;
66
67   COFFSymbol(llvm::StringRef name, size_t index);
68   size_t size() const;
69   void set_name_offset(uint32_t Offset);
70 };
71
72 // This class contains staging data for a COFF relocation entry.
73 struct COFFRelocation {
74   COFF::relocation Data;
75   COFFSymbol          *Symb;
76
77   COFFRelocation() : Symb(NULL) {}
78   static size_t size() { return COFF::RelocationSize; }
79 };
80
81 typedef std::vector<COFFRelocation> relocations;
82
83 class COFFSection {
84 public:
85   COFF::section Header;
86
87   std::string          Name;
88   size_t               Number;
89   MCSectionData const *MCData;
90   COFFSymbol              *Symb;
91   relocations          Relocations;
92
93   COFFSection(llvm::StringRef name, size_t Index);
94   static size_t size();
95 };
96
97 // This class holds the COFF string table.
98 class StringTable {
99   typedef llvm::StringMap<size_t> map;
100   map Map;
101
102   void update_length();
103 public:
104   std::vector<char> Data;
105
106   StringTable();
107   size_t size() const;
108   size_t insert(llvm::StringRef String);
109 };
110
111 class WinCOFFObjectWriter : public MCObjectWriter {
112 public:
113
114   typedef std::vector<COFFSymbol*>  symbols;
115   typedef std::vector<COFFSection*> sections;
116
117   typedef StringMap<COFFSymbol *>  name_symbol_map;
118   typedef StringMap<COFFSection *> name_section_map;
119
120   typedef DenseMap<MCSymbolData const *, COFFSymbol *>   symbol_map;
121   typedef DenseMap<MCSectionData const *, COFFSection *> section_map;
122
123   // Root level file contents.
124   COFF::header Header;
125   sections     Sections;
126   symbols      Symbols;
127   StringTable  Strings;
128
129   // Maps used during object file creation.
130   section_map SectionMap;
131   symbol_map  SymbolMap;
132
133   WinCOFFObjectWriter(raw_ostream &OS);
134
135   COFFSymbol *createSymbol(llvm::StringRef Name);
136   COFFSection *createSection(llvm::StringRef Name);
137
138   void InitCOFFEntity(COFFSymbol &Symbol);
139   void InitCOFFEntity(COFFSection &Section);
140
141   template <typename object_t, typename list_t>
142   object_t *createCOFFEntity(llvm::StringRef Name, list_t &List);
143
144   void DefineSection(MCSectionData const &SectionData);
145   void DefineSymbol(MCSymbolData const &SymbolData, MCAssembler &Assembler);
146
147   bool ExportSection(COFFSection *S);
148   bool ExportSymbol(MCSymbolData const &SymbolData, MCAssembler &Asm);
149
150   // Entity writing methods.
151
152   void WriteFileHeader(const COFF::header &Header);
153   void WriteSymbol(const COFFSymbol *S);
154   void WriteAuxiliarySymbols(const COFFSymbol::AuxiliarySymbols &S);
155   void WriteSectionHeader(const COFF::section &S);
156   void WriteRelocation(const COFF::relocation &R);
157
158   // MCObjectWriter interface implementation.
159
160   void ExecutePostLayoutBinding(MCAssembler &Asm);
161
162   void RecordRelocation(const MCAssembler &Asm,
163                         const MCAsmLayout &Layout,
164                         const MCFragment *Fragment,
165                         const MCFixup &Fixup,
166                         MCValue Target,
167                         uint64_t &FixedValue);
168
169   void WriteObject(const MCAssembler &Asm, const MCAsmLayout &Layout);
170 };
171 }
172
173 static inline void write_uint32_le(void *Data, uint32_t const &Value) {
174   uint8_t *Ptr = reinterpret_cast<uint8_t *>(Data);
175   Ptr[0] = (Value & 0x000000FF) >>  0;
176   Ptr[1] = (Value & 0x0000FF00) >>  8;
177   Ptr[2] = (Value & 0x00FF0000) >> 16;
178   Ptr[3] = (Value & 0xFF000000) >> 24;
179 }
180
181 static inline void write_uint16_le(void *Data, uint16_t const &Value) {
182   uint8_t *Ptr = reinterpret_cast<uint8_t *>(Data);
183   Ptr[0] = (Value & 0x00FF) >> 0;
184   Ptr[1] = (Value & 0xFF00) >> 8;
185 }
186
187 static inline void write_uint8_le(void *Data, uint8_t const &Value) {
188   uint8_t *Ptr = reinterpret_cast<uint8_t *>(Data);
189   Ptr[0] = (Value & 0xFF) >> 0;
190 }
191
192 //------------------------------------------------------------------------------
193 // Symbol class implementation
194
195 COFFSymbol::COFFSymbol(llvm::StringRef name, size_t index)
196       : Name(name.begin(), name.end()), Index(-1)
197       , Other(NULL), 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 //------------------------------------------------------------------------------
214 // Section class implementation
215
216 COFFSection::COFFSection(llvm::StringRef name, size_t Index)
217        : Name(name), Number(Index + 1)
218        , MCData(NULL), Symb(NULL) {
219   memset(&Header, 0, sizeof(Header));
220 }
221
222 size_t COFFSection::size() {
223   return COFF::SectionSize;
224 }
225
226 //------------------------------------------------------------------------------
227 // StringTable class implementation
228
229 /// Write the length of the string table into Data.
230 /// The length of the string table includes uint32 length header.
231 void StringTable::update_length() {
232   write_uint32_le(&Data.front(), Data.size());
233 }
234
235 StringTable::StringTable() {
236   // The string table data begins with the length of the entire string table
237   // including the length header. Allocate space for this header.
238   Data.resize(4);
239 }
240
241 size_t StringTable::size() const {
242   return Data.size();
243 }
244
245 /// Add String to the table iff it is not already there.
246 /// @returns the index into the string table where the string is now located.
247 size_t StringTable::insert(llvm::StringRef String) {
248   map::iterator i = Map.find(String);
249
250   if (i != Map.end())
251     return i->second;
252
253   size_t Offset = Data.size();
254
255   // Insert string data into string table.
256   Data.insert(Data.end(), String.begin(), String.end());
257   Data.push_back('\0');
258
259   // Put a reference to it in the map.
260   Map[String] = Offset;
261
262   // Update the internal length field.
263   update_length();
264
265   return Offset;
266 }
267
268 //------------------------------------------------------------------------------
269 // WinCOFFObjectWriter class implementation
270
271 WinCOFFObjectWriter::WinCOFFObjectWriter(raw_ostream &OS)
272                                 : MCObjectWriter(OS, true) {
273   memset(&Header, 0, sizeof(Header));
274   // TODO: Move magic constant out to COFF.h
275   Header.Machine = 0x14C; // x86
276 }
277
278 COFFSymbol *WinCOFFObjectWriter::createSymbol(llvm::StringRef Name) {
279   return createCOFFEntity<COFFSymbol>(Name, Symbols);
280 }
281
282 COFFSection *WinCOFFObjectWriter::createSection(llvm::StringRef Name) {
283   return createCOFFEntity<COFFSection>(Name, Sections);
284 }
285
286 /// This function initializes a symbol by entering its name into the string
287 /// table if it is too long to fit in the symbol table header.
288 void WinCOFFObjectWriter::InitCOFFEntity(COFFSymbol &S) {
289   if (S.Name.size() > COFF::NameSize) {
290     size_t StringTableEntry = Strings.insert(S.Name.c_str());
291
292     S.set_name_offset(StringTableEntry);
293   } else
294     memcpy(S.Data.Name, S.Name.c_str(), S.Name.size());
295 }
296
297 /// This function initializes a section by entering its name into the string
298 /// table if it is too long to fit in the section table header.
299 void WinCOFFObjectWriter::InitCOFFEntity(COFFSection &S) {
300   if (S.Name.size() > COFF::NameSize) {
301     size_t StringTableEntry = Strings.insert(S.Name.c_str());
302
303     // FIXME: Why is this number 999999? This number is never mentioned in the
304     // spec. I'm assuming this is due to the printed value needing to fit into
305     // the S.Header.Name field. In which case why not 9999999 (7 9's instead of
306     // 6)? The spec does not state if this entry should be null terminated in
307     // this case, and thus this seems to be the best way to do it. I think I
308     // just solved my own FIXME...
309     if (StringTableEntry > 999999)
310       report_fatal_error("COFF string table is greater than 999999 bytes.");
311
312     sprintf(S.Header.Name, "/%d", StringTableEntry);
313   } else
314     memcpy(S.Header.Name, S.Name.c_str(), S.Name.size());
315 }
316
317 /// A template used to lookup or create a symbol/section, and initialize it if
318 /// needed.
319 template <typename object_t, typename list_t>
320 object_t *WinCOFFObjectWriter::createCOFFEntity(llvm::StringRef Name,
321                                                 list_t &List) {
322   object_t *Object = new object_t(Name, List.size());
323
324   InitCOFFEntity(*Object);
325
326   List.push_back(Object);
327
328   return Object;
329 }
330
331 /// This function takes a section data object from the assembler
332 /// and creates the associated COFF section staging object.
333 void WinCOFFObjectWriter::DefineSection(MCSectionData const &SectionData) {
334   // FIXME: Not sure how to verify this (at least in a debug build).
335   MCSectionCOFF const &Sec =
336     static_cast<MCSectionCOFF const &>(SectionData.getSection());
337
338   COFFSection *coff_section = createSection(Sec.getSectionName());
339   COFFSymbol  *coff_symbol = createSymbol(Sec.getSectionName());
340
341   coff_section->Symb = coff_symbol;
342   coff_symbol->Data.StorageClass = COFF::IMAGE_SYM_CLASS_STATIC;
343   coff_symbol->Data.SectionNumber = coff_section->Number;
344
345   // In this case the auxiliary symbol is a Section Definition.
346   coff_symbol->Aux.resize(1);
347   memset(&coff_symbol->Aux[0], 0, sizeof(coff_symbol->Aux[0]));
348   coff_symbol->Aux[0].AuxType = ATSectionDefinition;
349   coff_symbol->Aux[0].Aux.SectionDefinition.Number = coff_section->Number;
350   coff_symbol->Aux[0].Aux.SectionDefinition.Selection = Sec.getSelection();
351
352   coff_section->Header.Characteristics = Sec.getCharacteristics();
353
354   uint32_t &Characteristics = coff_section->Header.Characteristics;
355   switch (SectionData.getAlignment()) {
356   case 1:    Characteristics |= COFF::IMAGE_SCN_ALIGN_1BYTES;    break;
357   case 2:    Characteristics |= COFF::IMAGE_SCN_ALIGN_2BYTES;    break;
358   case 4:    Characteristics |= COFF::IMAGE_SCN_ALIGN_4BYTES;    break;
359   case 8:    Characteristics |= COFF::IMAGE_SCN_ALIGN_8BYTES;    break;
360   case 16:   Characteristics |= COFF::IMAGE_SCN_ALIGN_16BYTES;   break;
361   case 32:   Characteristics |= COFF::IMAGE_SCN_ALIGN_32BYTES;   break;
362   case 64:   Characteristics |= COFF::IMAGE_SCN_ALIGN_64BYTES;   break;
363   case 128:  Characteristics |= COFF::IMAGE_SCN_ALIGN_128BYTES;  break;
364   case 256:  Characteristics |= COFF::IMAGE_SCN_ALIGN_256BYTES;  break;
365   case 512:  Characteristics |= COFF::IMAGE_SCN_ALIGN_512BYTES;  break;
366   case 1024: Characteristics |= COFF::IMAGE_SCN_ALIGN_1024BYTES; break;
367   case 2048: Characteristics |= COFF::IMAGE_SCN_ALIGN_2048BYTES; break;
368   case 4096: Characteristics |= COFF::IMAGE_SCN_ALIGN_4096BYTES; break;
369   case 8192: Characteristics |= COFF::IMAGE_SCN_ALIGN_8192BYTES; break;
370   default:
371     llvm_unreachable("unsupported section alignment");
372   }
373
374   // Bind internal COFF section to MC section.
375   coff_section->MCData = &SectionData;
376   SectionMap[&SectionData] = coff_section;
377 }
378
379 /// This function takes a section data object from the assembler
380 /// and creates the associated COFF symbol staging object.
381 void WinCOFFObjectWriter::DefineSymbol(MCSymbolData const &SymbolData,
382                                         MCAssembler &Assembler) {
383   COFFSymbol *coff_symbol = createSymbol(SymbolData.getSymbol().getName());
384
385   coff_symbol->Data.Type         = (SymbolData.getFlags() & 0x0000FFFF) >>  0;
386   coff_symbol->Data.StorageClass = (SymbolData.getFlags() & 0x00FF0000) >> 16;
387
388   // If no storage class was specified in the streamer, define it here.
389   if (coff_symbol->Data.StorageClass == 0) {
390     bool external = SymbolData.isExternal() || (SymbolData.Fragment == NULL);
391
392     coff_symbol->Data.StorageClass =
393       external ? COFF::IMAGE_SYM_CLASS_EXTERNAL : COFF::IMAGE_SYM_CLASS_STATIC;
394   }
395
396   if (SymbolData.getFlags() & COFF::SF_WeakReference) {
397     coff_symbol->Data.StorageClass = COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL;
398
399     const MCExpr *Value = SymbolData.getSymbol().getVariableValue();
400
401     // FIXME: This assert message isn't very good.
402     assert(Value->getKind() == MCExpr::SymbolRef &&
403            "Value must be a SymbolRef!");
404
405     const MCSymbolRefExpr *SymbolRef =
406       static_cast<const MCSymbolRefExpr *>(Value);
407
408     const MCSymbolData &OtherSymbolData =
409       Assembler.getSymbolData(SymbolRef->getSymbol());
410
411     // FIXME: This assert message isn't very good.
412     assert(SymbolMap.find(&OtherSymbolData) != SymbolMap.end() &&
413            "OtherSymbolData must be in the symbol map!");
414
415     coff_symbol->Other = SymbolMap[&OtherSymbolData];
416
417     // Setup the Weak External auxiliary symbol.
418     coff_symbol->Aux.resize(1);
419     memset(&coff_symbol->Aux[0], 0, sizeof(coff_symbol->Aux[0]));
420     coff_symbol->Aux[0].AuxType = ATWeakExternal;
421     coff_symbol->Aux[0].Aux.WeakExternal.TagIndex = 0;
422     coff_symbol->Aux[0].Aux.WeakExternal.Characteristics =
423                                         COFF::IMAGE_WEAK_EXTERN_SEARCH_LIBRARY;
424   }
425
426   // Bind internal COFF symbol to MC symbol.
427   coff_symbol->MCData = &SymbolData;
428   SymbolMap[&SymbolData] = coff_symbol;
429 }
430
431 bool WinCOFFObjectWriter::ExportSection(COFFSection *S) {
432   return (S->Header.Characteristics
433          & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) == 0;
434 }
435
436 bool WinCOFFObjectWriter::ExportSymbol(MCSymbolData const &SymbolData,
437                                        MCAssembler &Asm) {
438   // This doesn't seem to be right. Strings referred to from the .data section
439   // need symbols so they can be linked to code in the .text section right?
440
441   // return Asm.isSymbolLinkerVisible (&SymbolData);
442
443   // For now, all symbols are exported, the linker will sort it out for us.
444   return true;
445 }
446
447 //------------------------------------------------------------------------------
448 // entity writing methods
449
450 void WinCOFFObjectWriter::WriteFileHeader(const COFF::header &Header) {
451   WriteLE16(Header.Machine);
452   WriteLE16(Header.NumberOfSections);
453   WriteLE32(Header.TimeDateStamp);
454   WriteLE32(Header.PointerToSymbolTable);
455   WriteLE32(Header.NumberOfSymbols);
456   WriteLE16(Header.SizeOfOptionalHeader);
457   WriteLE16(Header.Characteristics);
458 }
459
460 void WinCOFFObjectWriter::WriteSymbol(const COFFSymbol *S) {
461   WriteBytes(StringRef(S->Data.Name, COFF::NameSize));
462   WriteLE32(S->Data.Value);
463   WriteLE16(S->Data.SectionNumber);
464   WriteLE16(S->Data.Type);
465   Write8(S->Data.StorageClass);
466   Write8(S->Data.NumberOfAuxSymbols);
467   WriteAuxiliarySymbols(S->Aux);
468 }
469
470 void WinCOFFObjectWriter::WriteAuxiliarySymbols(
471                                         const COFFSymbol::AuxiliarySymbols &S) {
472   for(COFFSymbol::AuxiliarySymbols::const_iterator i = S.begin(), e = S.end();
473       i != e; ++i) {
474     switch(i->AuxType) {
475     case ATFunctionDefinition:
476       WriteLE32(i->Aux.FunctionDefinition.TagIndex);
477       WriteLE32(i->Aux.FunctionDefinition.TotalSize);
478       WriteLE32(i->Aux.FunctionDefinition.PointerToLinenumber);
479       WriteLE32(i->Aux.FunctionDefinition.PointerToNextFunction);
480       WriteZeros(sizeof(i->Aux.FunctionDefinition.unused));
481       break;
482     case ATbfAndefSymbol:
483       WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused1));
484       WriteLE16(i->Aux.bfAndefSymbol.Linenumber);
485       WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused2));
486       WriteLE32(i->Aux.bfAndefSymbol.PointerToNextFunction);
487       WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused3));
488       break;
489     case ATWeakExternal:
490       WriteLE32(i->Aux.WeakExternal.TagIndex);
491       WriteLE32(i->Aux.WeakExternal.Characteristics);
492       WriteZeros(sizeof(i->Aux.WeakExternal.unused));
493       break;
494     case ATFile:
495       WriteBytes(StringRef(reinterpret_cast<const char *>(i->Aux.File.FileName),
496                  sizeof(i->Aux.File.FileName)));
497       break;
498     case ATSectionDefinition:
499       WriteLE32(i->Aux.SectionDefinition.Length);
500       WriteLE16(i->Aux.SectionDefinition.NumberOfRelocations);
501       WriteLE16(i->Aux.SectionDefinition.NumberOfLinenumbers);
502       WriteLE32(i->Aux.SectionDefinition.CheckSum);
503       WriteLE16(i->Aux.SectionDefinition.Number);
504       Write8(i->Aux.SectionDefinition.Selection);
505       WriteZeros(sizeof(i->Aux.SectionDefinition.unused));
506       break;
507     }
508   }
509 }
510
511 void WinCOFFObjectWriter::WriteSectionHeader(const COFF::section &S) {
512   WriteBytes(StringRef(S.Name, COFF::NameSize));
513
514   WriteLE32(S.VirtualSize);
515   WriteLE32(S.VirtualAddress);
516   WriteLE32(S.SizeOfRawData);
517   WriteLE32(S.PointerToRawData);
518   WriteLE32(S.PointerToRelocations);
519   WriteLE32(S.PointerToLineNumbers);
520   WriteLE16(S.NumberOfRelocations);
521   WriteLE16(S.NumberOfLineNumbers);
522   WriteLE32(S.Characteristics);
523 }
524
525 void WinCOFFObjectWriter::WriteRelocation(const COFF::relocation &R) {
526   WriteLE32(R.VirtualAddress);
527   WriteLE32(R.SymbolTableIndex);
528   WriteLE16(R.Type);
529 }
530
531 ////////////////////////////////////////////////////////////////////////////////
532 // MCObjectWriter interface implementations
533
534 void WinCOFFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
535   // "Define" each section & symbol. This creates section & symbol
536   // entries in the staging area and gives them their final indexes.
537
538   for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e; i++)
539     DefineSection(*i);
540
541   for (MCAssembler::const_symbol_iterator i = Asm.symbol_begin(),
542                                           e = Asm.symbol_end(); i != e; i++) {
543     if (ExportSymbol(*i, Asm))
544       DefineSymbol(*i, Asm);
545   }
546 }
547
548 void WinCOFFObjectWriter::RecordRelocation(const MCAssembler &Asm,
549                                            const MCAsmLayout &Layout,
550                                            const MCFragment *Fragment,
551                                            const MCFixup &Fixup,
552                                            MCValue Target,
553                                            uint64_t &FixedValue) {
554   assert(Target.getSymA() != NULL && "Relocation must reference a symbol!");
555   assert(Target.getSymB() == NULL &&
556          "Relocation must reference only one symbol!");
557
558   MCSectionData const *SectionData = Fragment->getParent();
559   MCSymbolData const *SymbolData =
560                               &Asm.getSymbolData(Target.getSymA()->getSymbol());
561
562   assert(SectionMap.find(SectionData) != SectionMap.end() &&
563          "Section must already have been defined in ExecutePostLayoutBinding!");
564   assert(SymbolMap.find(SymbolData) != SymbolMap.end() &&
565          "Symbol must already have been defined in ExecutePostLayoutBinding!");
566
567   COFFSection *coff_section = SectionMap[SectionData];
568   COFFSymbol *coff_symbol = SymbolMap[SymbolData];
569
570   FixedValue = Target.getConstant();
571
572   COFFRelocation Reloc;
573
574   Reloc.Data.VirtualAddress = Layout.getFragmentOffset(Fragment);
575   Reloc.Symb = coff_symbol;
576
577   Reloc.Data.VirtualAddress += Fixup.getOffset();
578
579   switch (Fixup.getKind()) {
580   case FirstTargetFixupKind: // reloc_pcrel_4byte
581     Reloc.Data.Type = COFF::IMAGE_REL_I386_REL32;
582     FixedValue += 4;
583     break;
584   case FK_Data_4:
585     Reloc.Data.Type = COFF::IMAGE_REL_I386_DIR32;
586     break;
587   default:
588     llvm_unreachable("unsupported relocation type");
589   }
590
591   coff_section->Relocations.push_back(Reloc);
592 }
593
594 void WinCOFFObjectWriter::WriteObject(const MCAssembler &Asm,
595                                       const MCAsmLayout &Layout) {
596   // Assign symbol and section indexes and offsets.
597
598   Header.NumberOfSymbols = 0;
599
600   for (symbols::iterator i = Symbols.begin(), e = Symbols.end(); i != e; i++) {
601     COFFSymbol *coff_symbol = *i;
602     MCSymbolData const *SymbolData = coff_symbol->MCData;
603
604     coff_symbol->Index = Header.NumberOfSymbols++;
605
606     // Update section number & offset for symbols that have them.
607     if ((SymbolData != NULL) && (SymbolData->Fragment != NULL)) {
608       COFFSection *coff_section = SectionMap[SymbolData->Fragment->getParent()];
609
610       coff_symbol->Data.SectionNumber = coff_section->Number;
611       coff_symbol->Data.Value = Layout.getFragmentOffset(SymbolData->Fragment);
612     }
613
614     // Update auxiliary symbol info.
615     coff_symbol->Data.NumberOfAuxSymbols = coff_symbol->Aux.size();
616     Header.NumberOfSymbols += coff_symbol->Data.NumberOfAuxSymbols;
617   }
618
619   // Fixup weak external references.
620   for (symbols::iterator i = Symbols.begin(), e = Symbols.end(); i != e; i++) {
621     COFFSymbol *symb = *i;
622
623     if (symb->Other != NULL) {
624       assert(symb->Aux.size() == 1 &&
625              "Symbol must contain one aux symbol!");
626       assert(symb->Aux[0].AuxType == ATWeakExternal &&
627              "Symbol's aux symbol must be a Weak External!");
628       symb->Aux[0].Aux.WeakExternal.TagIndex = symb->Other->Index;
629     }
630   }
631
632   // Assign file offsets to COFF object file structures.
633
634   unsigned offset = 0;
635
636   offset += COFF::HeaderSize;
637   offset += COFF::SectionSize * Asm.size();
638
639   Header.NumberOfSections = Sections.size();
640
641   for (MCAssembler::const_iterator i = Asm.begin(),
642                                    e = Asm.end();
643                                    i != e; i++) {
644     COFFSection *Sec = SectionMap[i];
645
646     Sec->Header.SizeOfRawData = Layout.getSectionFileSize(i);
647
648     if (ExportSection(Sec)) {
649       Sec->Header.PointerToRawData = offset;
650
651       offset += Sec->Header.SizeOfRawData;
652     }
653
654     if (Sec->Relocations.size() > 0) {
655       Sec->Header.NumberOfRelocations = Sec->Relocations.size();
656       Sec->Header.PointerToRelocations = offset;
657
658       offset += COFF::RelocationSize * Sec->Relocations.size();
659
660       for (relocations::iterator cr = Sec->Relocations.begin(),
661                                  er = Sec->Relocations.end();
662                                  cr != er; cr++) {
663         (*cr).Data.SymbolTableIndex = (*cr).Symb->Index;
664       }
665     }
666
667     assert(Sec->Symb->Aux.size() == 1 && "Section's symbol must have one aux!");
668     AuxSymbol &Aux = Sec->Symb->Aux[0];
669     assert(Aux.AuxType == ATSectionDefinition &&
670            "Section's symbol's aux symbol must be a Section Definition!");
671     Aux.Aux.SectionDefinition.Length = Sec->Header.SizeOfRawData;
672     Aux.Aux.SectionDefinition.NumberOfRelocations =
673                                                 Sec->Header.NumberOfRelocations;
674     Aux.Aux.SectionDefinition.NumberOfLinenumbers =
675                                                 Sec->Header.NumberOfLineNumbers;
676   }
677
678   Header.PointerToSymbolTable = offset;
679
680   // Write it all to disk...
681   WriteFileHeader(Header);
682
683   {
684     sections::iterator i, ie;
685     MCAssembler::const_iterator j, je;
686
687     for (i = Sections.begin(), ie = Sections.end(); i != ie; i++)
688       WriteSectionHeader((*i)->Header);
689
690     for (i = Sections.begin(), ie = Sections.end(),
691          j = Asm.begin(), je = Asm.end();
692          (i != ie) && (j != je); i++, j++) {
693       if ((*i)->Header.PointerToRawData != 0) {
694         assert(OS.tell() == (*i)->Header.PointerToRawData &&
695                "Section::PointerToRawData is insane!");
696
697         Asm.WriteSectionData(j, Layout, this);
698       }
699
700       if ((*i)->Relocations.size() > 0) {
701         assert(OS.tell() == (*i)->Header.PointerToRelocations &&
702                "Section::PointerToRelocations is insane!");
703
704         for (relocations::const_iterator k = (*i)->Relocations.begin(),
705                                                ke = (*i)->Relocations.end();
706                                                k != ke; k++) {
707           WriteRelocation(k->Data);
708         }
709       } else
710         assert((*i)->Header.PointerToRelocations == 0 &&
711                "Section::PointerToRelocations is insane!");
712     }
713   }
714
715   assert(OS.tell() == Header.PointerToSymbolTable &&
716          "Header::PointerToSymbolTable is insane!");
717
718   for (symbols::iterator i = Symbols.begin(), e = Symbols.end(); i != e; i++)
719     WriteSymbol(*i);
720
721   OS.write((char const *)&Strings.Data.front(), Strings.Data.size());
722 }
723
724 //------------------------------------------------------------------------------
725 // WinCOFFObjectWriter factory function
726
727 namespace llvm {
728   MCObjectWriter *createWinCOFFObjectWriter(raw_ostream &OS) {
729     return new WinCOFFObjectWriter(OS);
730   }
731 }