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