1 //===-- llvm/MC/WinCOFFObjectWriter.cpp -------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains an implementation of a Win32 COFF object file writer.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "WinCOFFObjectWriter"
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"
39 typedef SmallString<COFF::NameSize> name;
50 AuxiliaryType AuxType;
61 typedef SmallVector<AuxSymbol, 1> AuxiliarySymbols;
70 MCSymbolData const *MCData;
72 COFFSymbol(StringRef name);
74 void set_name_offset(uint32_t Offset);
76 bool should_keep() const;
79 // This class contains staging data for a COFF relocation entry.
80 struct COFFRelocation {
81 COFF::relocation Data;
84 COFFRelocation() : Symb(NULL) {}
85 static size_t size() { return COFF::RelocationSize; }
88 typedef std::vector<COFFRelocation> relocations;
96 MCSectionData const *MCData;
98 relocations Relocations;
100 COFFSection(StringRef name);
101 static size_t size();
104 // This class holds the COFF string table.
106 typedef StringMap<size_t> map;
109 void update_length();
111 std::vector<char> Data;
115 size_t insert(StringRef String);
118 class WinCOFFObjectWriter : public MCObjectWriter {
121 typedef std::vector<COFFSymbol*> symbols;
122 typedef std::vector<COFFSection*> sections;
124 typedef DenseMap<MCSymbol const *, COFFSymbol *> symbol_map;
125 typedef DenseMap<MCSection const *, COFFSection *> section_map;
127 llvm::OwningPtr<MCWinCOFFObjectTargetWriter> TargetObjectWriter;
129 // Root level file contents.
135 // Maps used during object file creation.
136 section_map SectionMap;
137 symbol_map SymbolMap;
139 WinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW, raw_ostream &OS);
140 ~WinCOFFObjectWriter();
142 COFFSymbol *createSymbol(StringRef Name);
143 COFFSymbol *GetOrCreateCOFFSymbol(const MCSymbol * Symbol);
144 COFFSection *createSection(StringRef Name);
146 template <typename object_t, typename list_t>
147 object_t *createCOFFEntity(StringRef Name, list_t &List);
149 void DefineSection(MCSectionData const &SectionData);
150 void DefineSymbol(MCSymbolData const &SymbolData,
151 MCAssembler &Assembler);
153 void MakeSymbolReal(COFFSymbol &S, size_t Index);
154 void MakeSectionReal(COFFSection &S, size_t Number);
156 bool ExportSection(COFFSection const *S);
157 bool ExportSymbol(MCSymbolData const &SymbolData, MCAssembler &Asm);
159 bool IsPhysicalSection(COFFSection *S);
161 // Entity writing methods.
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);
169 // MCObjectWriter interface implementation.
171 void ExecutePostLayoutBinding(MCAssembler &Asm, const MCAsmLayout &Layout);
173 void RecordRelocation(const MCAssembler &Asm,
174 const MCAsmLayout &Layout,
175 const MCFragment *Fragment,
176 const MCFixup &Fixup,
178 uint64_t &FixedValue);
180 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
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;
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;
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;
203 //------------------------------------------------------------------------------
204 // Symbol class implementation
206 COFFSymbol::COFFSymbol(StringRef name)
207 : Name(name.begin(), name.end())
212 memset(&Data, 0, sizeof(Data));
215 size_t COFFSymbol::size() const {
216 return COFF::SymbolSize + (Data.NumberOfAuxSymbols * COFF::SymbolSize);
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);
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
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!");
239 // if the section its in is being droped, drop it
240 if (Section->Number == -1)
243 // if it is the section symbol, keep it
244 if (Section->Symbol == this)
247 // if its temporary, drop it
248 if (MCData && MCData->getSymbol().isTemporary())
251 // otherwise, keep it
255 //------------------------------------------------------------------------------
256 // Section class implementation
258 COFFSection::COFFSection(StringRef name)
262 memset(&Header, 0, sizeof(Header));
265 size_t COFFSection::size() {
266 return COFF::SectionSize;
269 //------------------------------------------------------------------------------
270 // StringTable class implementation
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());
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.
285 size_t StringTable::size() const {
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);
297 size_t Offset = Data.size();
299 // Insert string data into string table.
300 Data.insert(Data.end(), String.begin(), String.end());
301 Data.push_back('\0');
303 // Put a reference to it in the map.
304 Map[String] = Offset;
306 // Update the internal length field.
312 //------------------------------------------------------------------------------
313 // WinCOFFObjectWriter class implementation
315 WinCOFFObjectWriter::WinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW,
317 : MCObjectWriter(OS, true)
318 , TargetObjectWriter(MOTW) {
319 memset(&Header, 0, sizeof(Header));
321 Header.Machine = TargetObjectWriter->getMachine();
324 WinCOFFObjectWriter::~WinCOFFObjectWriter() {
325 for (symbols::iterator I = Symbols.begin(), E = Symbols.end(); I != E; ++I)
327 for (sections::iterator I = Sections.begin(), E = Sections.end(); I != E; ++I)
331 COFFSymbol *WinCOFFObjectWriter::createSymbol(StringRef Name) {
332 return createCOFFEntity<COFFSymbol>(Name, Symbols);
335 COFFSymbol *WinCOFFObjectWriter::GetOrCreateCOFFSymbol(const MCSymbol * Symbol){
336 symbol_map::iterator i = SymbolMap.find(Symbol);
337 if (i != SymbolMap.end())
339 COFFSymbol *RetSymbol
340 = createCOFFEntity<COFFSymbol>(Symbol->getName(), Symbols);
341 SymbolMap[Symbol] = RetSymbol;
345 COFFSection *WinCOFFObjectWriter::createSection(StringRef Name) {
346 return createCOFFEntity<COFFSection>(Name, Sections);
349 /// A template used to lookup or create a symbol/section, and initialize it if
351 template <typename object_t, typename list_t>
352 object_t *WinCOFFObjectWriter::createCOFFEntity(StringRef Name,
354 object_t *Object = new object_t(Name);
356 List.push_back(Object);
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());
370 COFFSection *coff_section = createSection(Sec.getSectionName());
371 COFFSymbol *coff_symbol = createSymbol(Sec.getSectionName());
373 coff_section->Symbol = coff_symbol;
374 coff_symbol->Section = coff_section;
375 coff_symbol->Data.StorageClass = COFF::IMAGE_SYM_CLASS_STATIC;
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();
383 coff_section->Header.Characteristics = Sec.getCharacteristics();
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;
402 llvm_unreachable("unsupported section alignment");
405 // Bind internal COFF section to MC section.
406 coff_section->MCData = &SectionData;
407 SectionMap[&SectionData.getSection()] = coff_section;
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;
418 if (SymbolData.getFlags() & COFF::SF_WeakExternal) {
419 coff_symbol->Data.StorageClass = COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL;
421 if (Symbol.isVariable()) {
422 const MCSymbolRefExpr *SymRef =
423 dyn_cast<MCSymbolRefExpr>(Symbol.getVariableValue());
426 report_fatal_error("Weak externals may only alias symbols");
428 coff_symbol->Other = GetOrCreateCOFFSymbol(&SymRef->getSymbol());
430 std::string WeakName = std::string(".weak.")
431 + Symbol.getName().str()
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;
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;
449 coff_symbol->MCData = &SymbolData;
451 const MCSymbolData &ResSymData =
452 Assembler.getSymbolData(Symbol.AliasedSymbol());
454 coff_symbol->Data.Type = (ResSymData.getFlags() & 0x0000FFFF) >> 0;
455 coff_symbol->Data.StorageClass = (ResSymData.getFlags() & 0x00FF0000) >> 16;
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);
461 coff_symbol->Data.StorageClass =
462 external ? COFF::IMAGE_SYM_CLASS_EXTERNAL : COFF::IMAGE_SYM_CLASS_STATIC;
465 if (ResSymData.Fragment != NULL)
466 coff_symbol->Section =
467 SectionMap[&ResSymData.Fragment->getParent()->getSection()];
469 coff_symbol->MCData = &ResSymData;
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());
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.");
488 std::sprintf(S.Header.Name, "/%d", unsigned(StringTableEntry));
490 std::memcpy(S.Header.Name, S.Name.c_str(), S.Name.size());
493 S.Symbol->Data.SectionNumber = S.Number;
494 S.Symbol->Aux[0].Aux.SectionDefinition.Number = S.Number;
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());
501 S.set_name_offset(StringTableEntry);
503 std::memcpy(S.Data.Name, S.Name.c_str(), S.Name.size());
507 bool WinCOFFObjectWriter::ExportSection(COFFSection const *S) {
508 return !S->MCData->getFragmentList().empty();
511 bool WinCOFFObjectWriter::ExportSymbol(MCSymbolData const &SymbolData,
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?
516 // return Asm.isSymbolLinkerVisible (&SymbolData);
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();
523 bool WinCOFFObjectWriter::IsPhysicalSection(COFFSection *S) {
524 return (S->Header.Characteristics
525 & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) == 0;
528 //------------------------------------------------------------------------------
529 // entity writing methods
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);
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);
551 void WinCOFFObjectWriter::WriteAuxiliarySymbols(
552 const COFFSymbol::AuxiliarySymbols &S) {
553 for(COFFSymbol::AuxiliarySymbols::const_iterator i = S.begin(), e = S.end();
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));
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));
571 WriteLE32(i->Aux.WeakExternal.TagIndex);
572 WriteLE32(i->Aux.WeakExternal.Characteristics);
573 WriteZeros(sizeof(i->Aux.WeakExternal.unused));
576 WriteBytes(StringRef(reinterpret_cast<const char *>(i->Aux.File.FileName),
577 sizeof(i->Aux.File.FileName)));
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));
592 void WinCOFFObjectWriter::WriteSectionHeader(const COFF::section &S) {
593 WriteBytes(StringRef(S.Name, COFF::NameSize));
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);
606 void WinCOFFObjectWriter::WriteRelocation(const COFF::relocation &R) {
607 WriteLE32(R.VirtualAddress);
608 WriteLE32(R.SymbolTableIndex);
612 ////////////////////////////////////////////////////////////////////////////////
613 // MCObjectWriter interface implementations
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.
620 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e; i++)
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);
631 void WinCOFFObjectWriter::RecordRelocation(const MCAssembler &Asm,
632 const MCAsmLayout &Layout,
633 const MCFragment *Fragment,
634 const MCFixup &Fixup,
636 uint64_t &FixedValue) {
637 assert(Target.getSymA() != NULL && "Relocation must reference a symbol!");
639 const MCSymbol *A = &Target.getSymA()->getSymbol();
640 MCSymbolData &A_SD = Asm.getSymbolData(*A);
642 MCSectionData const *SectionData = Fragment->getParent();
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!");
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();
657 if (Target.getSymB()) {
658 const MCSymbol *B = &Target.getSymB()->getSymbol();
659 MCSymbolData &B_SD = Asm.getSymbolData(*B);
661 // Offset of the symbol in the section
662 int64_t a = Layout.getSymbolOffset(&B_SD);
664 // Ofeset of the relocation in the section
665 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
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.
674 FixedValue = Target.getConstant();
677 COFFRelocation Reloc;
679 Reloc.Data.SymbolTableIndex = 0;
680 Reloc.Data.VirtualAddress = Layout.getFragmentOffset(Fragment);
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();
688 Reloc.Symb = coff_symbol;
690 ++Reloc.Symb->Relocations;
692 Reloc.Data.VirtualAddress += Fixup.getOffset();
693 Reloc.Data.Type = TargetObjectWriter->getRelocType(Target, Fixup,
696 // FIXME: Can anyone explain what this does other than adjust for the size
698 if (Reloc.Data.Type == COFF::IMAGE_REL_AMD64_REL32 ||
699 Reloc.Data.Type == COFF::IMAGE_REL_I386_REL32)
702 coff_section->Relocations.push_back(Reloc);
705 void WinCOFFObjectWriter::WriteObject(MCAssembler &Asm,
706 const MCAsmLayout &Layout) {
707 // Assign symbol and section indexes and offsets.
708 Header.NumberOfSections = 0;
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);
719 Header.NumberOfSymbols = 0;
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;
725 // Update section number & offset for symbols that have them.
726 if ((SymbolData != NULL) && (SymbolData->Fragment != NULL)) {
727 assert(coff_symbol->Section != NULL);
729 coff_symbol->Data.SectionNumber = coff_symbol->Section->Number;
730 coff_symbol->Data.Value = Layout.getFragmentOffset(SymbolData->Fragment)
731 + SymbolData->Offset;
734 if (coff_symbol->should_keep()) {
735 MakeSymbolReal(*coff_symbol, Header.NumberOfSymbols++);
737 // Update auxiliary symbol info.
738 coff_symbol->Data.NumberOfAuxSymbols = coff_symbol->Aux.size();
739 Header.NumberOfSymbols += coff_symbol->Data.NumberOfAuxSymbols;
741 coff_symbol->Index = -1;
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;
757 // Assign file offsets to COFF object file structures.
761 offset += COFF::HeaderSize;
762 offset += COFF::SectionSize * Header.NumberOfSections;
764 for (MCAssembler::const_iterator i = Asm.begin(),
767 COFFSection *Sec = SectionMap[&i->getSection()];
769 if (Sec->Number == -1)
772 Sec->Header.SizeOfRawData = Layout.getSectionAddressSize(i);
774 if (IsPhysicalSection(Sec)) {
775 Sec->Header.PointerToRawData = offset;
777 offset += Sec->Header.SizeOfRawData;
780 if (Sec->Relocations.size() > 0) {
781 bool RelocationsOverflow = Sec->Relocations.size() >= 0xffff;
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;
788 Sec->Header.NumberOfRelocations = Sec->Relocations.size();
790 Sec->Header.PointerToRelocations = offset;
792 if (RelocationsOverflow) {
793 // Reloc #0 will contain actual count, so make room for it.
794 offset += COFF::RelocationSize;
797 offset += COFF::RelocationSize * Sec->Relocations.size();
799 for (relocations::iterator cr = Sec->Relocations.begin(),
800 er = Sec->Relocations.end();
802 assert((*cr).Symb->Index != -1);
803 (*cr).Data.SymbolTableIndex = (*cr).Symb->Index;
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;
819 Header.PointerToSymbolTable = offset;
821 Header.TimeDateStamp = sys::TimeValue::now().toEpochTime();
823 // Write it all to disk...
824 WriteFileHeader(Header);
827 sections::iterator i, ie;
828 MCAssembler::const_iterator j, je;
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;
835 WriteSectionHeader((*i)->Header);
838 for (i = Sections.begin(), ie = Sections.end(),
839 j = Asm.begin(), je = Asm.end();
840 (i != ie) && (j != je); ++i, ++j) {
842 if ((*i)->Number == -1)
845 if ((*i)->Header.PointerToRawData != 0) {
846 assert(OS.tell() == (*i)->Header.PointerToRawData &&
847 "Section::PointerToRawData is insane!");
849 Asm.writeSectionData(j, Layout);
852 if ((*i)->Relocations.size() > 0) {
853 assert(OS.tell() == (*i)->Header.PointerToRelocations &&
854 "Section::PointerToRelocations is insane!");
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).
860 r.VirtualAddress = (*i)->Relocations.size() + 1;
861 r.SymbolTableIndex = 0;
866 for (relocations::const_iterator k = (*i)->Relocations.begin(),
867 ke = (*i)->Relocations.end();
869 WriteRelocation(k->Data);
872 assert((*i)->Header.PointerToRelocations == 0 &&
873 "Section::PointerToRelocations is insane!");
877 assert(OS.tell() == Header.PointerToSymbolTable &&
878 "Header::PointerToSymbolTable is insane!");
880 for (symbols::iterator i = Symbols.begin(), e = Symbols.end(); i != e; i++)
881 if ((*i)->Index != -1)
884 OS.write((char const *)&Strings.Data.front(), Strings.Data.size());
887 MCWinCOFFObjectTargetWriter::MCWinCOFFObjectTargetWriter(unsigned Machine_) :
891 //------------------------------------------------------------------------------
892 // WinCOFFObjectWriter factory function
895 MCObjectWriter *createWinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW,
897 return new WinCOFFObjectWriter(MOTW, OS);