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/StringMap.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/ADT/Twine.h"
21 #include "llvm/MC/MCAsmLayout.h"
22 #include "llvm/MC/MCAssembler.h"
23 #include "llvm/MC/MCContext.h"
24 #include "llvm/MC/MCExpr.h"
25 #include "llvm/MC/MCObjectWriter.h"
26 #include "llvm/MC/MCSection.h"
27 #include "llvm/MC/MCSectionCOFF.h"
28 #include "llvm/MC/MCSymbol.h"
29 #include "llvm/MC/MCValue.h"
30 #include "llvm/Support/COFF.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/TimeValue.h"
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 std::unique_ptr<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 virtual ~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, MCAssembler &Assembler,
151 const MCAsmLayout &Layout);
153 void MakeSymbolReal(COFFSymbol &S, size_t Index);
154 void MakeSectionReal(COFFSection &S, size_t Number);
156 bool ExportSymbol(MCSymbolData const &SymbolData, MCAssembler &Asm);
158 bool IsPhysicalSection(COFFSection *S);
160 // Entity writing methods.
162 void WriteFileHeader(const COFF::header &Header);
163 void WriteSymbol(const COFFSymbol *S);
164 void WriteAuxiliarySymbols(const COFFSymbol::AuxiliarySymbols &S);
165 void WriteSectionHeader(const COFF::section &S);
166 void WriteRelocation(const COFF::relocation &R);
168 // MCObjectWriter interface implementation.
170 void ExecutePostLayoutBinding(MCAssembler &Asm,
171 const MCAsmLayout &Layout) override;
173 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
174 const MCFragment *Fragment, const MCFixup &Fixup,
175 MCValue Target, uint64_t &FixedValue) override;
177 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
181 static inline void write_uint32_le(void *Data, uint32_t const &Value) {
182 uint8_t *Ptr = reinterpret_cast<uint8_t *>(Data);
183 Ptr[0] = (Value & 0x000000FF) >> 0;
184 Ptr[1] = (Value & 0x0000FF00) >> 8;
185 Ptr[2] = (Value & 0x00FF0000) >> 16;
186 Ptr[3] = (Value & 0xFF000000) >> 24;
189 //------------------------------------------------------------------------------
190 // Symbol class implementation
192 COFFSymbol::COFFSymbol(StringRef name)
193 : Name(name.begin(), name.end())
198 memset(&Data, 0, sizeof(Data));
201 size_t COFFSymbol::size() const {
202 return COFF::SymbolSize + (Data.NumberOfAuxSymbols * COFF::SymbolSize);
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);
213 /// logic to decide if the symbol should be reported in the symbol table
214 bool COFFSymbol::should_keep() const {
215 // no section means its external, keep it
219 // if it has relocations pointing at it, keep it
220 if (Relocations > 0) {
221 assert(Section->Number != -1 && "Sections with relocations must be real!");
225 // if the section its in is being droped, drop it
226 if (Section->Number == -1)
229 // if it is the section symbol, keep it
230 if (Section->Symbol == this)
233 // if its temporary, drop it
234 if (MCData && MCData->getSymbol().isTemporary())
237 // otherwise, keep it
241 //------------------------------------------------------------------------------
242 // Section class implementation
244 COFFSection::COFFSection(StringRef name)
248 memset(&Header, 0, sizeof(Header));
251 size_t COFFSection::size() {
252 return COFF::SectionSize;
255 //------------------------------------------------------------------------------
256 // StringTable class implementation
258 /// Write the length of the string table into Data.
259 /// The length of the string table includes uint32 length header.
260 void StringTable::update_length() {
261 write_uint32_le(&Data.front(), Data.size());
264 StringTable::StringTable() {
265 // The string table data begins with the length of the entire string table
266 // including the length header. Allocate space for this header.
271 size_t StringTable::size() const {
275 /// Add String to the table iff it is not already there.
276 /// @returns the index into the string table where the string is now located.
277 size_t StringTable::insert(StringRef String) {
278 map::iterator i = Map.find(String);
283 size_t Offset = Data.size();
285 // Insert string data into string table.
286 Data.insert(Data.end(), String.begin(), String.end());
287 Data.push_back('\0');
289 // Put a reference to it in the map.
290 Map[String] = Offset;
292 // Update the internal length field.
298 //------------------------------------------------------------------------------
299 // WinCOFFObjectWriter class implementation
301 WinCOFFObjectWriter::WinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW,
303 : MCObjectWriter(OS, true)
304 , TargetObjectWriter(MOTW) {
305 memset(&Header, 0, sizeof(Header));
307 Header.Machine = TargetObjectWriter->getMachine();
310 WinCOFFObjectWriter::~WinCOFFObjectWriter() {
311 for (symbols::iterator I = Symbols.begin(), E = Symbols.end(); I != E; ++I)
313 for (sections::iterator I = Sections.begin(), E = Sections.end(); I != E; ++I)
317 COFFSymbol *WinCOFFObjectWriter::createSymbol(StringRef Name) {
318 return createCOFFEntity<COFFSymbol>(Name, Symbols);
321 COFFSymbol *WinCOFFObjectWriter::GetOrCreateCOFFSymbol(const MCSymbol * Symbol){
322 symbol_map::iterator i = SymbolMap.find(Symbol);
323 if (i != SymbolMap.end())
325 COFFSymbol *RetSymbol
326 = createCOFFEntity<COFFSymbol>(Symbol->getName(), Symbols);
327 SymbolMap[Symbol] = RetSymbol;
331 COFFSection *WinCOFFObjectWriter::createSection(StringRef Name) {
332 return createCOFFEntity<COFFSection>(Name, Sections);
335 /// A template used to lookup or create a symbol/section, and initialize it if
337 template <typename object_t, typename list_t>
338 object_t *WinCOFFObjectWriter::createCOFFEntity(StringRef Name,
340 object_t *Object = new object_t(Name);
342 List.push_back(Object);
347 /// This function takes a section data object from the assembler
348 /// and creates the associated COFF section staging object.
349 void WinCOFFObjectWriter::DefineSection(MCSectionData const &SectionData) {
350 assert(SectionData.getSection().getVariant() == MCSection::SV_COFF
351 && "Got non-COFF section in the COFF backend!");
352 // FIXME: Not sure how to verify this (at least in a debug build).
353 MCSectionCOFF const &Sec =
354 static_cast<MCSectionCOFF const &>(SectionData.getSection());
356 COFFSection *coff_section = createSection(Sec.getSectionName());
357 COFFSymbol *coff_symbol = createSymbol(Sec.getSectionName());
359 coff_section->Symbol = coff_symbol;
360 coff_symbol->Section = coff_section;
361 coff_symbol->Data.StorageClass = COFF::IMAGE_SYM_CLASS_STATIC;
363 // In this case the auxiliary symbol is a Section Definition.
364 coff_symbol->Aux.resize(1);
365 memset(&coff_symbol->Aux[0], 0, sizeof(coff_symbol->Aux[0]));
366 coff_symbol->Aux[0].AuxType = ATSectionDefinition;
367 coff_symbol->Aux[0].Aux.SectionDefinition.Selection = Sec.getSelection();
369 coff_section->Header.Characteristics = Sec.getCharacteristics();
371 uint32_t &Characteristics = coff_section->Header.Characteristics;
372 switch (SectionData.getAlignment()) {
373 case 1: Characteristics |= COFF::IMAGE_SCN_ALIGN_1BYTES; break;
374 case 2: Characteristics |= COFF::IMAGE_SCN_ALIGN_2BYTES; break;
375 case 4: Characteristics |= COFF::IMAGE_SCN_ALIGN_4BYTES; break;
376 case 8: Characteristics |= COFF::IMAGE_SCN_ALIGN_8BYTES; break;
377 case 16: Characteristics |= COFF::IMAGE_SCN_ALIGN_16BYTES; break;
378 case 32: Characteristics |= COFF::IMAGE_SCN_ALIGN_32BYTES; break;
379 case 64: Characteristics |= COFF::IMAGE_SCN_ALIGN_64BYTES; break;
380 case 128: Characteristics |= COFF::IMAGE_SCN_ALIGN_128BYTES; break;
381 case 256: Characteristics |= COFF::IMAGE_SCN_ALIGN_256BYTES; break;
382 case 512: Characteristics |= COFF::IMAGE_SCN_ALIGN_512BYTES; break;
383 case 1024: Characteristics |= COFF::IMAGE_SCN_ALIGN_1024BYTES; break;
384 case 2048: Characteristics |= COFF::IMAGE_SCN_ALIGN_2048BYTES; break;
385 case 4096: Characteristics |= COFF::IMAGE_SCN_ALIGN_4096BYTES; break;
386 case 8192: Characteristics |= COFF::IMAGE_SCN_ALIGN_8192BYTES; break;
388 llvm_unreachable("unsupported section alignment");
391 // Bind internal COFF section to MC section.
392 coff_section->MCData = &SectionData;
393 SectionMap[&SectionData.getSection()] = coff_section;
396 /// This function takes a section data object from the assembler
397 /// and creates the associated COFF symbol staging object.
398 void WinCOFFObjectWriter::DefineSymbol(MCSymbolData const &SymbolData,
399 MCAssembler &Assembler,
400 const MCAsmLayout &Layout) {
401 MCSymbol const &Symbol = SymbolData.getSymbol();
402 COFFSymbol *coff_symbol = GetOrCreateCOFFSymbol(&Symbol);
403 SymbolMap[&Symbol] = coff_symbol;
405 if (SymbolData.getFlags() & COFF::SF_WeakExternal) {
406 coff_symbol->Data.StorageClass = COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL;
408 if (Symbol.isVariable()) {
409 const MCSymbolRefExpr *SymRef =
410 dyn_cast<MCSymbolRefExpr>(Symbol.getVariableValue());
413 report_fatal_error("Weak externals may only alias symbols");
415 coff_symbol->Other = GetOrCreateCOFFSymbol(&SymRef->getSymbol());
417 std::string WeakName = std::string(".weak.")
418 + Symbol.getName().str()
420 COFFSymbol *WeakDefault = createSymbol(WeakName);
421 WeakDefault->Data.SectionNumber = COFF::IMAGE_SYM_ABSOLUTE;
422 WeakDefault->Data.StorageClass = COFF::IMAGE_SYM_CLASS_EXTERNAL;
423 WeakDefault->Data.Type = 0;
424 WeakDefault->Data.Value = 0;
425 coff_symbol->Other = WeakDefault;
428 // Setup the Weak External auxiliary symbol.
429 coff_symbol->Aux.resize(1);
430 memset(&coff_symbol->Aux[0], 0, sizeof(coff_symbol->Aux[0]));
431 coff_symbol->Aux[0].AuxType = ATWeakExternal;
432 coff_symbol->Aux[0].Aux.WeakExternal.TagIndex = 0;
433 coff_symbol->Aux[0].Aux.WeakExternal.Characteristics =
434 COFF::IMAGE_WEAK_EXTERN_SEARCH_LIBRARY;
436 coff_symbol->MCData = &SymbolData;
438 const MCSymbolData &ResSymData =
439 Assembler.getSymbolData(Symbol.AliasedSymbol());
441 if (Symbol.isVariable()) {
443 if (Symbol.getVariableValue()->EvaluateAsAbsolute(Addr, Layout))
444 coff_symbol->Data.Value = Addr;
447 coff_symbol->Data.Type = (ResSymData.getFlags() & 0x0000FFFF) >> 0;
448 coff_symbol->Data.StorageClass = (ResSymData.getFlags() & 0x00FF0000) >> 16;
450 // If no storage class was specified in the streamer, define it here.
451 if (coff_symbol->Data.StorageClass == 0) {
452 bool external = ResSymData.isExternal() || (ResSymData.Fragment == NULL);
454 coff_symbol->Data.StorageClass =
455 external ? COFF::IMAGE_SYM_CLASS_EXTERNAL : COFF::IMAGE_SYM_CLASS_STATIC;
458 if (Symbol.isAbsolute() || Symbol.AliasedSymbol().isVariable())
459 coff_symbol->Data.SectionNumber = COFF::IMAGE_SYM_ABSOLUTE;
460 else if (ResSymData.Fragment != NULL)
461 coff_symbol->Section =
462 SectionMap[&ResSymData.Fragment->getParent()->getSection()];
464 coff_symbol->MCData = &ResSymData;
468 // Maximum offsets for different string table entry encodings.
469 static const unsigned Max6DecimalOffset = 999999;
470 static const unsigned Max7DecimalOffset = 9999999;
471 static const uint64_t MaxBase64Offset = 0xFFFFFFFFFULL; // 64^6, including 0
473 // Encode a string table entry offset in base 64, padded to 6 chars, and
474 // prefixed with a double slash: '//AAAAAA', '//AAAAAB', ...
475 // Buffer must be at least 8 bytes large. No terminating null appended.
476 static void encodeBase64StringEntry(char* Buffer, uint64_t Value) {
477 assert(Value > Max7DecimalOffset && Value <= MaxBase64Offset &&
478 "Illegal section name encoding for value");
480 static const char Alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
481 "abcdefghijklmnopqrstuvwxyz"
487 char* Ptr = Buffer + 7;
488 for (unsigned i = 0; i < 6; ++i) {
489 unsigned Rem = Value % 64;
491 *(Ptr--) = Alphabet[Rem];
495 /// making a section real involves assigned it a number and putting
496 /// name into the string table if needed
497 void WinCOFFObjectWriter::MakeSectionReal(COFFSection &S, size_t Number) {
498 if (S.Name.size() > COFF::NameSize) {
499 uint64_t StringTableEntry = Strings.insert(S.Name.c_str());
501 if (StringTableEntry <= Max6DecimalOffset) {
502 std::sprintf(S.Header.Name, "/%d", unsigned(StringTableEntry));
503 } else if (StringTableEntry <= Max7DecimalOffset) {
504 // With seven digits, we have to skip the terminating null. Because
505 // sprintf always appends it, we use a larger temporary buffer.
506 char buffer[9] = { };
507 std::sprintf(buffer, "/%d", unsigned(StringTableEntry));
508 std::memcpy(S.Header.Name, buffer, 8);
509 } else if (StringTableEntry <= MaxBase64Offset) {
510 // Starting with 10,000,000, offsets are encoded as base64.
511 encodeBase64StringEntry(S.Header.Name, StringTableEntry);
513 report_fatal_error("COFF string table is greater than 64 GB.");
516 std::memcpy(S.Header.Name, S.Name.c_str(), S.Name.size());
519 S.Symbol->Data.SectionNumber = S.Number;
520 S.Symbol->Aux[0].Aux.SectionDefinition.Number = S.Number;
523 void WinCOFFObjectWriter::MakeSymbolReal(COFFSymbol &S, size_t Index) {
524 if (S.Name.size() > COFF::NameSize) {
525 size_t StringTableEntry = Strings.insert(S.Name.c_str());
527 S.set_name_offset(StringTableEntry);
529 std::memcpy(S.Data.Name, S.Name.c_str(), S.Name.size());
533 bool WinCOFFObjectWriter::ExportSymbol(MCSymbolData const &SymbolData,
535 // This doesn't seem to be right. Strings referred to from the .data section
536 // need symbols so they can be linked to code in the .text section right?
538 // return Asm.isSymbolLinkerVisible (&SymbolData);
540 // For now, all non-variable symbols are exported,
541 // the linker will sort the rest out for us.
542 return SymbolData.isExternal() || !SymbolData.getSymbol().isVariable();
545 bool WinCOFFObjectWriter::IsPhysicalSection(COFFSection *S) {
546 return (S->Header.Characteristics
547 & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) == 0;
550 //------------------------------------------------------------------------------
551 // entity writing methods
553 void WinCOFFObjectWriter::WriteFileHeader(const COFF::header &Header) {
554 WriteLE16(Header.Machine);
555 WriteLE16(Header.NumberOfSections);
556 WriteLE32(Header.TimeDateStamp);
557 WriteLE32(Header.PointerToSymbolTable);
558 WriteLE32(Header.NumberOfSymbols);
559 WriteLE16(Header.SizeOfOptionalHeader);
560 WriteLE16(Header.Characteristics);
563 void WinCOFFObjectWriter::WriteSymbol(const COFFSymbol *S) {
564 WriteBytes(StringRef(S->Data.Name, COFF::NameSize));
565 WriteLE32(S->Data.Value);
566 WriteLE16(S->Data.SectionNumber);
567 WriteLE16(S->Data.Type);
568 Write8(S->Data.StorageClass);
569 Write8(S->Data.NumberOfAuxSymbols);
570 WriteAuxiliarySymbols(S->Aux);
573 void WinCOFFObjectWriter::WriteAuxiliarySymbols(
574 const COFFSymbol::AuxiliarySymbols &S) {
575 for(COFFSymbol::AuxiliarySymbols::const_iterator i = S.begin(), e = S.end();
578 case ATFunctionDefinition:
579 WriteLE32(i->Aux.FunctionDefinition.TagIndex);
580 WriteLE32(i->Aux.FunctionDefinition.TotalSize);
581 WriteLE32(i->Aux.FunctionDefinition.PointerToLinenumber);
582 WriteLE32(i->Aux.FunctionDefinition.PointerToNextFunction);
583 WriteZeros(sizeof(i->Aux.FunctionDefinition.unused));
585 case ATbfAndefSymbol:
586 WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused1));
587 WriteLE16(i->Aux.bfAndefSymbol.Linenumber);
588 WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused2));
589 WriteLE32(i->Aux.bfAndefSymbol.PointerToNextFunction);
590 WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused3));
593 WriteLE32(i->Aux.WeakExternal.TagIndex);
594 WriteLE32(i->Aux.WeakExternal.Characteristics);
595 WriteZeros(sizeof(i->Aux.WeakExternal.unused));
598 WriteBytes(StringRef(reinterpret_cast<const char *>(i->Aux.File.FileName),
599 sizeof(i->Aux.File.FileName)));
601 case ATSectionDefinition:
602 WriteLE32(i->Aux.SectionDefinition.Length);
603 WriteLE16(i->Aux.SectionDefinition.NumberOfRelocations);
604 WriteLE16(i->Aux.SectionDefinition.NumberOfLinenumbers);
605 WriteLE32(i->Aux.SectionDefinition.CheckSum);
606 WriteLE16(i->Aux.SectionDefinition.Number);
607 Write8(i->Aux.SectionDefinition.Selection);
608 WriteZeros(sizeof(i->Aux.SectionDefinition.unused));
614 void WinCOFFObjectWriter::WriteSectionHeader(const COFF::section &S) {
615 WriteBytes(StringRef(S.Name, COFF::NameSize));
617 WriteLE32(S.VirtualSize);
618 WriteLE32(S.VirtualAddress);
619 WriteLE32(S.SizeOfRawData);
620 WriteLE32(S.PointerToRawData);
621 WriteLE32(S.PointerToRelocations);
622 WriteLE32(S.PointerToLineNumbers);
623 WriteLE16(S.NumberOfRelocations);
624 WriteLE16(S.NumberOfLineNumbers);
625 WriteLE32(S.Characteristics);
628 void WinCOFFObjectWriter::WriteRelocation(const COFF::relocation &R) {
629 WriteLE32(R.VirtualAddress);
630 WriteLE32(R.SymbolTableIndex);
634 ////////////////////////////////////////////////////////////////////////////////
635 // MCObjectWriter interface implementations
637 void WinCOFFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
638 const MCAsmLayout &Layout) {
639 // "Define" each section & symbol. This creates section & symbol
640 // entries in the staging area.
642 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e; i++)
645 for (MCAssembler::const_symbol_iterator i = Asm.symbol_begin(),
646 e = Asm.symbol_end();
648 if (ExportSymbol(*i, Asm)) {
649 DefineSymbol(*i, Asm, Layout);
654 void WinCOFFObjectWriter::RecordRelocation(const MCAssembler &Asm,
655 const MCAsmLayout &Layout,
656 const MCFragment *Fragment,
657 const MCFixup &Fixup,
659 uint64_t &FixedValue) {
660 assert(Target.getSymA() != NULL && "Relocation must reference a symbol!");
662 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
663 const MCSymbol &A = Symbol.AliasedSymbol();
664 if (!Asm.hasSymbolData(A))
665 Asm.getContext().FatalError(
667 Twine("symbol '") + A.getName() + "' can not be undefined");
669 MCSymbolData &A_SD = Asm.getSymbolData(A);
671 MCSectionData const *SectionData = Fragment->getParent();
673 // Mark this symbol as requiring an entry in the symbol table.
674 assert(SectionMap.find(&SectionData->getSection()) != SectionMap.end() &&
675 "Section must already have been defined in ExecutePostLayoutBinding!");
676 assert(SymbolMap.find(&A_SD.getSymbol()) != SymbolMap.end() &&
677 "Symbol must already have been defined in ExecutePostLayoutBinding!");
679 COFFSection *coff_section = SectionMap[&SectionData->getSection()];
680 COFFSymbol *coff_symbol = SymbolMap[&A_SD.getSymbol()];
681 const MCSymbolRefExpr *SymB = Target.getSymB();
682 bool CrossSection = false;
685 const MCSymbol *B = &SymB->getSymbol();
686 MCSymbolData &B_SD = Asm.getSymbolData(*B);
687 if (!B_SD.getFragment())
688 Asm.getContext().FatalError(
690 Twine("symbol '") + B->getName() +
691 "' can not be undefined in a subtraction expression");
693 if (!A_SD.getFragment())
694 Asm.getContext().FatalError(
696 Twine("symbol '") + Symbol.getName() +
697 "' can not be undefined in a subtraction expression");
699 CrossSection = &Symbol.getSection() != &B->getSection();
701 // Offset of the symbol in the section
702 int64_t a = Layout.getSymbolOffset(&B_SD);
704 // Ofeset of the relocation in the section
705 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
708 // In the case where we have SymbA and SymB, we just need to store the delta
709 // between the two symbols. Update FixedValue to account for the delta, and
710 // skip recording the relocation.
714 FixedValue = Target.getConstant();
717 COFFRelocation Reloc;
719 Reloc.Data.SymbolTableIndex = 0;
720 Reloc.Data.VirtualAddress = Layout.getFragmentOffset(Fragment);
722 // Turn relocations for temporary symbols into section relocations.
723 if (coff_symbol->MCData->getSymbol().isTemporary() || CrossSection) {
724 Reloc.Symb = coff_symbol->Section->Symbol;
725 FixedValue += Layout.getFragmentOffset(coff_symbol->MCData->Fragment)
726 + coff_symbol->MCData->getOffset();
728 Reloc.Symb = coff_symbol;
730 ++Reloc.Symb->Relocations;
732 Reloc.Data.VirtualAddress += Fixup.getOffset();
733 Reloc.Data.Type = TargetObjectWriter->getRelocType(Target, Fixup,
736 // FIXME: Can anyone explain what this does other than adjust for the size
738 if (Reloc.Data.Type == COFF::IMAGE_REL_AMD64_REL32 ||
739 Reloc.Data.Type == COFF::IMAGE_REL_I386_REL32)
742 coff_section->Relocations.push_back(Reloc);
745 void WinCOFFObjectWriter::WriteObject(MCAssembler &Asm,
746 const MCAsmLayout &Layout) {
747 // Assign symbol and section indexes and offsets.
748 Header.NumberOfSections = 0;
750 DenseMap<COFFSection *, uint16_t> SectionIndices;
751 for (sections::iterator i = Sections.begin(),
752 e = Sections.end(); i != e; i++) {
753 if (Layout.getSectionAddressSize((*i)->MCData) > 0) {
754 size_t Number = ++Header.NumberOfSections;
755 SectionIndices[*i] = Number;
756 MakeSectionReal(**i, Number);
762 Header.NumberOfSymbols = 0;
764 for (symbols::iterator i = Symbols.begin(), e = Symbols.end(); i != e; i++) {
765 COFFSymbol *coff_symbol = *i;
766 MCSymbolData const *SymbolData = coff_symbol->MCData;
768 // Update section number & offset for symbols that have them.
769 if ((SymbolData != NULL) && (SymbolData->Fragment != NULL)) {
770 assert(coff_symbol->Section != NULL);
772 coff_symbol->Data.SectionNumber = coff_symbol->Section->Number;
773 coff_symbol->Data.Value = Layout.getFragmentOffset(SymbolData->Fragment)
774 + SymbolData->Offset;
777 if (coff_symbol->should_keep()) {
778 MakeSymbolReal(*coff_symbol, Header.NumberOfSymbols++);
780 // Update auxiliary symbol info.
781 coff_symbol->Data.NumberOfAuxSymbols = coff_symbol->Aux.size();
782 Header.NumberOfSymbols += coff_symbol->Data.NumberOfAuxSymbols;
784 coff_symbol->Index = -1;
787 // Fixup weak external references.
788 for (symbols::iterator i = Symbols.begin(), e = Symbols.end(); i != e; i++) {
789 COFFSymbol *coff_symbol = *i;
790 if (coff_symbol->Other != NULL) {
791 assert(coff_symbol->Index != -1);
792 assert(coff_symbol->Aux.size() == 1 &&
793 "Symbol must contain one aux symbol!");
794 assert(coff_symbol->Aux[0].AuxType == ATWeakExternal &&
795 "Symbol's aux symbol must be a Weak External!");
796 coff_symbol->Aux[0].Aux.WeakExternal.TagIndex = coff_symbol->Other->Index;
800 // Fixup associative COMDAT sections.
801 for (sections::iterator i = Sections.begin(),
802 e = Sections.end(); i != e; i++) {
803 if ((*i)->Symbol->Aux[0].Aux.SectionDefinition.Selection !=
804 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
807 const MCSectionCOFF &MCSec = static_cast<const MCSectionCOFF &>(
808 (*i)->MCData->getSection());
810 COFFSection *Assoc = SectionMap.lookup(MCSec.getAssocSection());
812 report_fatal_error(Twine("Missing associated COMDAT section ") +
813 MCSec.getAssocSection()->getSectionName() +
814 " for section " + MCSec.getSectionName());
817 // Skip this section if the associated section is unused.
818 if (Assoc->Number == -1)
821 (*i)->Symbol->Aux[0].Aux.SectionDefinition.Number = SectionIndices[Assoc];
825 // Assign file offsets to COFF object file structures.
829 offset += COFF::HeaderSize;
830 offset += COFF::SectionSize * Header.NumberOfSections;
832 for (MCAssembler::const_iterator i = Asm.begin(),
835 COFFSection *Sec = SectionMap[&i->getSection()];
837 if (Sec->Number == -1)
840 Sec->Header.SizeOfRawData = Layout.getSectionAddressSize(i);
842 if (IsPhysicalSection(Sec)) {
843 Sec->Header.PointerToRawData = offset;
845 offset += Sec->Header.SizeOfRawData;
848 if (Sec->Relocations.size() > 0) {
849 bool RelocationsOverflow = Sec->Relocations.size() >= 0xffff;
851 if (RelocationsOverflow) {
852 // Signal overflow by setting NumberOfSections to max value. Actual
853 // size is found in reloc #0. Microsoft tools understand this.
854 Sec->Header.NumberOfRelocations = 0xffff;
856 Sec->Header.NumberOfRelocations = Sec->Relocations.size();
858 Sec->Header.PointerToRelocations = offset;
860 if (RelocationsOverflow) {
861 // Reloc #0 will contain actual count, so make room for it.
862 offset += COFF::RelocationSize;
865 offset += COFF::RelocationSize * Sec->Relocations.size();
867 for (relocations::iterator cr = Sec->Relocations.begin(),
868 er = Sec->Relocations.end();
870 assert((*cr).Symb->Index != -1);
871 (*cr).Data.SymbolTableIndex = (*cr).Symb->Index;
875 assert(Sec->Symbol->Aux.size() == 1
876 && "Section's symbol must have one aux!");
877 AuxSymbol &Aux = Sec->Symbol->Aux[0];
878 assert(Aux.AuxType == ATSectionDefinition &&
879 "Section's symbol's aux symbol must be a Section Definition!");
880 Aux.Aux.SectionDefinition.Length = Sec->Header.SizeOfRawData;
881 Aux.Aux.SectionDefinition.NumberOfRelocations =
882 Sec->Header.NumberOfRelocations;
883 Aux.Aux.SectionDefinition.NumberOfLinenumbers =
884 Sec->Header.NumberOfLineNumbers;
887 Header.PointerToSymbolTable = offset;
889 // We want a deterministic output. It looks like GNU as also writes 0 in here.
890 Header.TimeDateStamp = 0;
892 // Write it all to disk...
893 WriteFileHeader(Header);
896 sections::iterator i, ie;
897 MCAssembler::const_iterator j, je;
899 for (i = Sections.begin(), ie = Sections.end(); i != ie; i++)
900 if ((*i)->Number != -1) {
901 if ((*i)->Relocations.size() >= 0xffff) {
902 (*i)->Header.Characteristics |= COFF::IMAGE_SCN_LNK_NRELOC_OVFL;
904 WriteSectionHeader((*i)->Header);
907 for (i = Sections.begin(), ie = Sections.end(),
908 j = Asm.begin(), je = Asm.end();
909 (i != ie) && (j != je); ++i, ++j) {
911 if ((*i)->Number == -1)
914 if ((*i)->Header.PointerToRawData != 0) {
915 assert(OS.tell() == (*i)->Header.PointerToRawData &&
916 "Section::PointerToRawData is insane!");
918 Asm.writeSectionData(j, Layout);
921 if ((*i)->Relocations.size() > 0) {
922 assert(OS.tell() == (*i)->Header.PointerToRelocations &&
923 "Section::PointerToRelocations is insane!");
925 if ((*i)->Relocations.size() >= 0xffff) {
926 // In case of overflow, write actual relocation count as first
927 // relocation. Including the synthetic reloc itself (+ 1).
929 r.VirtualAddress = (*i)->Relocations.size() + 1;
930 r.SymbolTableIndex = 0;
935 for (relocations::const_iterator k = (*i)->Relocations.begin(),
936 ke = (*i)->Relocations.end();
938 WriteRelocation(k->Data);
941 assert((*i)->Header.PointerToRelocations == 0 &&
942 "Section::PointerToRelocations is insane!");
946 assert(OS.tell() == Header.PointerToSymbolTable &&
947 "Header::PointerToSymbolTable is insane!");
949 for (symbols::iterator i = Symbols.begin(), e = Symbols.end(); i != e; i++)
950 if ((*i)->Index != -1)
953 OS.write((char const *)&Strings.Data.front(), Strings.Data.size());
956 MCWinCOFFObjectTargetWriter::MCWinCOFFObjectTargetWriter(unsigned Machine_) :
960 // Pin the vtable to this file.
961 void MCWinCOFFObjectTargetWriter::anchor() {}
963 //------------------------------------------------------------------------------
964 // WinCOFFObjectWriter factory function
967 MCObjectWriter *createWinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW,
969 return new WinCOFFObjectWriter(MOTW, OS);