LLVM API Documentation

WinCOFFObjectWriter.cpp
Go to the documentation of this file.
00001 //===-- llvm/MC/WinCOFFObjectWriter.cpp -------------------------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file contains an implementation of a Win32 COFF object file writer.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/MC/MCWinCOFFObjectWriter.h"
00015 #include "llvm/ADT/DenseMap.h"
00016 #include "llvm/ADT/StringMap.h"
00017 #include "llvm/ADT/StringRef.h"
00018 #include "llvm/ADT/STLExtras.h"
00019 #include "llvm/ADT/Twine.h"
00020 #include "llvm/MC/MCAsmLayout.h"
00021 #include "llvm/MC/MCAssembler.h"
00022 #include "llvm/MC/MCContext.h"
00023 #include "llvm/MC/MCExpr.h"
00024 #include "llvm/MC/MCObjectWriter.h"
00025 #include "llvm/MC/MCSection.h"
00026 #include "llvm/MC/MCSectionCOFF.h"
00027 #include "llvm/MC/MCSymbol.h"
00028 #include "llvm/MC/MCValue.h"
00029 #include "llvm/Support/COFF.h"
00030 #include "llvm/Support/Debug.h"
00031 #include "llvm/Support/ErrorHandling.h"
00032 #include "llvm/Support/TimeValue.h"
00033 #include <cstdio>
00034 
00035 using namespace llvm;
00036 
00037 #define DEBUG_TYPE "WinCOFFObjectWriter"
00038 
00039 namespace {
00040 typedef SmallString<COFF::NameSize> name;
00041 
00042 enum AuxiliaryType {
00043   ATFunctionDefinition,
00044   ATbfAndefSymbol,
00045   ATWeakExternal,
00046   ATFile,
00047   ATSectionDefinition
00048 };
00049 
00050 struct AuxSymbol {
00051   AuxiliaryType   AuxType;
00052   COFF::Auxiliary Aux;
00053 };
00054 
00055 class COFFSymbol;
00056 class COFFSection;
00057 
00058 class COFFSymbol {
00059 public:
00060   COFF::symbol Data;
00061 
00062   typedef SmallVector<AuxSymbol, 1> AuxiliarySymbols;
00063 
00064   name             Name;
00065   int              Index;
00066   AuxiliarySymbols Aux;
00067   COFFSymbol      *Other;
00068   COFFSection     *Section;
00069   int              Relocations;
00070 
00071   MCSymbolData const *MCData;
00072 
00073   COFFSymbol(StringRef name);
00074   void set_name_offset(uint32_t Offset);
00075 
00076   bool should_keep() const;
00077 };
00078 
00079 // This class contains staging data for a COFF relocation entry.
00080 struct COFFRelocation {
00081   COFF::relocation Data;
00082   COFFSymbol          *Symb;
00083 
00084   COFFRelocation() : Symb(nullptr) {}
00085   static size_t size() { return COFF::RelocationSize; }
00086 };
00087 
00088 typedef std::vector<COFFRelocation> relocations;
00089 
00090 class COFFSection {
00091 public:
00092   COFF::section Header;
00093 
00094   std::string          Name;
00095   int                  Number;
00096   MCSectionData const *MCData;
00097   COFFSymbol          *Symbol;
00098   relocations          Relocations;
00099 
00100   COFFSection(StringRef name);
00101   static size_t size();
00102 };
00103 
00104 // This class holds the COFF string table.
00105 class StringTable {
00106   typedef StringMap<size_t> map;
00107   map Map;
00108 
00109   void update_length();
00110 public:
00111   std::vector<char> Data;
00112 
00113   StringTable();
00114   size_t size() const;
00115   size_t insert(StringRef String);
00116   void clear() {
00117     Map.clear();
00118     Data.resize(4);
00119     update_length();
00120   }  
00121 };
00122 
00123 class WinCOFFObjectWriter : public MCObjectWriter {
00124 public:
00125 
00126   typedef std::vector<std::unique_ptr<COFFSymbol>>  symbols;
00127   typedef std::vector<std::unique_ptr<COFFSection>> sections;
00128 
00129   typedef DenseMap<MCSymbol  const *, COFFSymbol *>   symbol_map;
00130   typedef DenseMap<MCSection const *, COFFSection *> section_map;
00131 
00132   std::unique_ptr<MCWinCOFFObjectTargetWriter> TargetObjectWriter;
00133 
00134   // Root level file contents.
00135   COFF::header Header;
00136   sections     Sections;
00137   symbols      Symbols;
00138   StringTable  Strings;
00139 
00140   // Maps used during object file creation.
00141   section_map SectionMap;
00142   symbol_map  SymbolMap;
00143 
00144   bool UseBigObj;
00145 
00146   WinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW, raw_ostream &OS);
00147   
00148   void reset() override {
00149     memset(&Header, 0, sizeof(Header));
00150     Header.Machine = TargetObjectWriter->getMachine();
00151     Sections.clear();
00152     Symbols.clear();
00153     Strings.clear();
00154     SectionMap.clear();
00155     SymbolMap.clear();
00156     MCObjectWriter::reset();
00157   }
00158 
00159   COFFSymbol *createSymbol(StringRef Name);
00160   COFFSymbol *GetOrCreateCOFFSymbol(const MCSymbol * Symbol);
00161   COFFSection *createSection(StringRef Name);
00162 
00163   template <typename object_t, typename list_t>
00164   object_t *createCOFFEntity(StringRef Name, list_t &List);
00165 
00166   void DefineSection(MCSectionData const &SectionData);
00167   void DefineSymbol(MCSymbolData const &SymbolData, MCAssembler &Assembler,
00168                     const MCAsmLayout &Layout);
00169 
00170   void MakeSymbolReal(COFFSymbol &S, size_t Index);
00171   void MakeSectionReal(COFFSection &S, size_t Number);
00172 
00173   bool ExportSymbol(const MCSymbol &Symbol, MCAssembler &Asm);
00174 
00175   bool IsPhysicalSection(COFFSection *S);
00176 
00177   // Entity writing methods.
00178 
00179   void WriteFileHeader(const COFF::header &Header);
00180   void WriteSymbol(const COFFSymbol &S);
00181   void WriteAuxiliarySymbols(const COFFSymbol::AuxiliarySymbols &S);
00182   void WriteSectionHeader(const COFF::section &S);
00183   void WriteRelocation(const COFF::relocation &R);
00184 
00185   // MCObjectWriter interface implementation.
00186 
00187   void ExecutePostLayoutBinding(MCAssembler &Asm,
00188                                 const MCAsmLayout &Layout) override;
00189 
00190   void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
00191                         const MCFragment *Fragment, const MCFixup &Fixup,
00192                         MCValue Target, bool &IsPCRel,
00193                         uint64_t &FixedValue) override;
00194 
00195   void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
00196 };
00197 }
00198 
00199 static inline void write_uint32_le(void *Data, uint32_t const &Value) {
00200   uint8_t *Ptr = reinterpret_cast<uint8_t *>(Data);
00201   Ptr[0] = (Value & 0x000000FF) >>  0;
00202   Ptr[1] = (Value & 0x0000FF00) >>  8;
00203   Ptr[2] = (Value & 0x00FF0000) >> 16;
00204   Ptr[3] = (Value & 0xFF000000) >> 24;
00205 }
00206 
00207 //------------------------------------------------------------------------------
00208 // Symbol class implementation
00209 
00210 COFFSymbol::COFFSymbol(StringRef name)
00211   : Name(name.begin(), name.end())
00212   , Other(nullptr)
00213   , Section(nullptr)
00214   , Relocations(0)
00215   , MCData(nullptr) {
00216   memset(&Data, 0, sizeof(Data));
00217 }
00218 
00219 // In the case that the name does not fit within 8 bytes, the offset
00220 // into the string table is stored in the last 4 bytes instead, leaving
00221 // the first 4 bytes as 0.
00222 void COFFSymbol::set_name_offset(uint32_t Offset) {
00223   write_uint32_le(Data.Name + 0, 0);
00224   write_uint32_le(Data.Name + 4, Offset);
00225 }
00226 
00227 /// logic to decide if the symbol should be reported in the symbol table
00228 bool COFFSymbol::should_keep() const {
00229   // no section means its external, keep it
00230   if (!Section)
00231     return true;
00232 
00233   // if it has relocations pointing at it, keep it
00234   if (Relocations > 0)   {
00235     assert(Section->Number != -1 && "Sections with relocations must be real!");
00236     return true;
00237   }
00238 
00239   // if the section its in is being droped, drop it
00240   if (Section->Number == -1)
00241       return false;
00242 
00243   // if it is the section symbol, keep it
00244   if (Section->Symbol == this)
00245     return true;
00246 
00247   // if its temporary, drop it
00248   if (MCData && MCData->getSymbol().isTemporary())
00249       return false;
00250 
00251   // otherwise, keep it
00252   return true;
00253 }
00254 
00255 //------------------------------------------------------------------------------
00256 // Section class implementation
00257 
00258 COFFSection::COFFSection(StringRef name)
00259   : Name(name)
00260   , MCData(nullptr)
00261   , Symbol(nullptr) {
00262   memset(&Header, 0, sizeof(Header));
00263 }
00264 
00265 size_t COFFSection::size() {
00266   return COFF::SectionSize;
00267 }
00268 
00269 //------------------------------------------------------------------------------
00270 // StringTable class implementation
00271 
00272 /// Write the length of the string table into Data.
00273 /// The length of the string table includes uint32 length header.
00274 void StringTable::update_length() {
00275   write_uint32_le(&Data.front(), Data.size());
00276 }
00277 
00278 StringTable::StringTable() {
00279   // The string table data begins with the length of the entire string table
00280   // including the length header. Allocate space for this header.
00281   Data.resize(4);
00282   update_length();
00283 }
00284 
00285 size_t StringTable::size() const {
00286   return Data.size();
00287 }
00288 
00289 /// Add String to the table iff it is not already there.
00290 /// @returns the index into the string table where the string is now located.
00291 size_t StringTable::insert(StringRef String) {
00292   map::iterator i = Map.find(String);
00293 
00294   if (i != Map.end())
00295     return i->second;
00296 
00297   size_t Offset = Data.size();
00298 
00299   // Insert string data into string table.
00300   Data.insert(Data.end(), String.begin(), String.end());
00301   Data.push_back('\0');
00302 
00303   // Put a reference to it in the map.
00304   Map[String] = Offset;
00305 
00306   // Update the internal length field.
00307   update_length();
00308 
00309   return Offset;
00310 }
00311 
00312 //------------------------------------------------------------------------------
00313 // WinCOFFObjectWriter class implementation
00314 
00315 WinCOFFObjectWriter::WinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW,
00316                                          raw_ostream &OS)
00317     : MCObjectWriter(OS, true), TargetObjectWriter(MOTW) {
00318   memset(&Header, 0, sizeof(Header));
00319 
00320   Header.Machine = TargetObjectWriter->getMachine();
00321 }
00322 
00323 COFFSymbol *WinCOFFObjectWriter::createSymbol(StringRef Name) {
00324   return createCOFFEntity<COFFSymbol>(Name, Symbols);
00325 }
00326 
00327 COFFSymbol *WinCOFFObjectWriter::GetOrCreateCOFFSymbol(const MCSymbol * Symbol){
00328   symbol_map::iterator i = SymbolMap.find(Symbol);
00329   if (i != SymbolMap.end())
00330     return i->second;
00331   COFFSymbol *RetSymbol
00332     = createCOFFEntity<COFFSymbol>(Symbol->getName(), Symbols);
00333   SymbolMap[Symbol] = RetSymbol;
00334   return RetSymbol;
00335 }
00336 
00337 COFFSection *WinCOFFObjectWriter::createSection(StringRef Name) {
00338   return createCOFFEntity<COFFSection>(Name, Sections);
00339 }
00340 
00341 /// A template used to lookup or create a symbol/section, and initialize it if
00342 /// needed.
00343 template <typename object_t, typename list_t>
00344 object_t *WinCOFFObjectWriter::createCOFFEntity(StringRef Name,
00345                                                 list_t &List) {
00346   List.push_back(make_unique<object_t>(Name));
00347 
00348   return List.back().get();
00349 }
00350 
00351 /// This function takes a section data object from the assembler
00352 /// and creates the associated COFF section staging object.
00353 void WinCOFFObjectWriter::DefineSection(MCSectionData const &SectionData) {
00354   assert(SectionData.getSection().getVariant() == MCSection::SV_COFF
00355     && "Got non-COFF section in the COFF backend!");
00356   // FIXME: Not sure how to verify this (at least in a debug build).
00357   MCSectionCOFF const &Sec =
00358     static_cast<MCSectionCOFF const &>(SectionData.getSection());
00359 
00360   COFFSection *coff_section = createSection(Sec.getSectionName());
00361   COFFSymbol  *coff_symbol = createSymbol(Sec.getSectionName());
00362   if (Sec.getSelection() != COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) {
00363     if (const MCSymbol *S = Sec.getCOMDATSymbol()) {
00364       COFFSymbol *COMDATSymbol = GetOrCreateCOFFSymbol(S);
00365       if (COMDATSymbol->Section)
00366         report_fatal_error("two sections have the same comdat");
00367       COMDATSymbol->Section = coff_section;
00368     }
00369   }
00370 
00371   coff_section->Symbol = coff_symbol;
00372   coff_symbol->Section = coff_section;
00373   coff_symbol->Data.StorageClass = COFF::IMAGE_SYM_CLASS_STATIC;
00374 
00375   // In this case the auxiliary symbol is a Section Definition.
00376   coff_symbol->Aux.resize(1);
00377   memset(&coff_symbol->Aux[0], 0, sizeof(coff_symbol->Aux[0]));
00378   coff_symbol->Aux[0].AuxType = ATSectionDefinition;
00379   coff_symbol->Aux[0].Aux.SectionDefinition.Selection = Sec.getSelection();
00380 
00381   coff_section->Header.Characteristics = Sec.getCharacteristics();
00382 
00383   uint32_t &Characteristics = coff_section->Header.Characteristics;
00384   switch (SectionData.getAlignment()) {
00385   case 1:    Characteristics |= COFF::IMAGE_SCN_ALIGN_1BYTES;    break;
00386   case 2:    Characteristics |= COFF::IMAGE_SCN_ALIGN_2BYTES;    break;
00387   case 4:    Characteristics |= COFF::IMAGE_SCN_ALIGN_4BYTES;    break;
00388   case 8:    Characteristics |= COFF::IMAGE_SCN_ALIGN_8BYTES;    break;
00389   case 16:   Characteristics |= COFF::IMAGE_SCN_ALIGN_16BYTES;   break;
00390   case 32:   Characteristics |= COFF::IMAGE_SCN_ALIGN_32BYTES;   break;
00391   case 64:   Characteristics |= COFF::IMAGE_SCN_ALIGN_64BYTES;   break;
00392   case 128:  Characteristics |= COFF::IMAGE_SCN_ALIGN_128BYTES;  break;
00393   case 256:  Characteristics |= COFF::IMAGE_SCN_ALIGN_256BYTES;  break;
00394   case 512:  Characteristics |= COFF::IMAGE_SCN_ALIGN_512BYTES;  break;
00395   case 1024: Characteristics |= COFF::IMAGE_SCN_ALIGN_1024BYTES; break;
00396   case 2048: Characteristics |= COFF::IMAGE_SCN_ALIGN_2048BYTES; break;
00397   case 4096: Characteristics |= COFF::IMAGE_SCN_ALIGN_4096BYTES; break;
00398   case 8192: Characteristics |= COFF::IMAGE_SCN_ALIGN_8192BYTES; break;
00399   default:
00400     llvm_unreachable("unsupported section alignment");
00401   }
00402 
00403   // Bind internal COFF section to MC section.
00404   coff_section->MCData = &SectionData;
00405   SectionMap[&SectionData.getSection()] = coff_section;
00406 }
00407 
00408 static uint64_t getSymbolValue(const MCSymbolData &Data,
00409                                const MCAsmLayout &Layout) {
00410   if (Data.isCommon() && Data.isExternal())
00411     return Data.getCommonSize();
00412 
00413   uint64_t Res;
00414   if (!Layout.getSymbolOffset(&Data, Res))
00415     return 0;
00416 
00417   return Res;
00418 }
00419 
00420 /// This function takes a symbol data object from the assembler
00421 /// and creates the associated COFF symbol staging object.
00422 void WinCOFFObjectWriter::DefineSymbol(MCSymbolData const &SymbolData,
00423                                        MCAssembler &Assembler,
00424                                        const MCAsmLayout &Layout) {
00425   MCSymbol const &Symbol = SymbolData.getSymbol();
00426   COFFSymbol *coff_symbol = GetOrCreateCOFFSymbol(&Symbol);
00427   SymbolMap[&Symbol] = coff_symbol;
00428 
00429   if (SymbolData.getFlags() & COFF::SF_WeakExternal) {
00430     coff_symbol->Data.StorageClass = COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL;
00431 
00432     if (Symbol.isVariable()) {
00433       const MCSymbolRefExpr *SymRef =
00434         dyn_cast<MCSymbolRefExpr>(Symbol.getVariableValue());
00435 
00436       if (!SymRef)
00437         report_fatal_error("Weak externals may only alias symbols");
00438 
00439       coff_symbol->Other = GetOrCreateCOFFSymbol(&SymRef->getSymbol());
00440     } else {
00441       std::string WeakName = std::string(".weak.")
00442                            +  Symbol.getName().str()
00443                            + ".default";
00444       COFFSymbol *WeakDefault = createSymbol(WeakName);
00445       WeakDefault->Data.SectionNumber = COFF::IMAGE_SYM_ABSOLUTE;
00446       WeakDefault->Data.StorageClass  = COFF::IMAGE_SYM_CLASS_EXTERNAL;
00447       WeakDefault->Data.Type          = 0;
00448       WeakDefault->Data.Value         = 0;
00449       coff_symbol->Other = WeakDefault;
00450     }
00451 
00452     // Setup the Weak External auxiliary symbol.
00453     coff_symbol->Aux.resize(1);
00454     memset(&coff_symbol->Aux[0], 0, sizeof(coff_symbol->Aux[0]));
00455     coff_symbol->Aux[0].AuxType = ATWeakExternal;
00456     coff_symbol->Aux[0].Aux.WeakExternal.TagIndex = 0;
00457     coff_symbol->Aux[0].Aux.WeakExternal.Characteristics =
00458       COFF::IMAGE_WEAK_EXTERN_SEARCH_LIBRARY;
00459 
00460     coff_symbol->MCData = &SymbolData;
00461   } else {
00462     const MCSymbolData &ResSymData = Assembler.getSymbolData(Symbol);
00463     const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
00464     coff_symbol->Data.Value = getSymbolValue(ResSymData, Layout);
00465 
00466     coff_symbol->Data.Type         = (ResSymData.getFlags() & 0x0000FFFF) >>  0;
00467     coff_symbol->Data.StorageClass = (ResSymData.getFlags() & 0x00FF0000) >> 16;
00468 
00469     // If no storage class was specified in the streamer, define it here.
00470     if (coff_symbol->Data.StorageClass == 0) {
00471       bool IsExternal =
00472           ResSymData.isExternal() ||
00473           (!ResSymData.getFragment() && !ResSymData.getSymbol().isVariable());
00474 
00475       coff_symbol->Data.StorageClass = IsExternal
00476                                            ? COFF::IMAGE_SYM_CLASS_EXTERNAL
00477                                            : COFF::IMAGE_SYM_CLASS_STATIC;
00478     }
00479 
00480     if (!Base) {
00481       coff_symbol->Data.SectionNumber = COFF::IMAGE_SYM_ABSOLUTE;
00482     } else {
00483       const MCSymbolData &BaseData = Assembler.getSymbolData(*Base);
00484       if (BaseData.Fragment) {
00485         COFFSection *Sec =
00486             SectionMap[&BaseData.Fragment->getParent()->getSection()];
00487 
00488         if (coff_symbol->Section && coff_symbol->Section != Sec)
00489           report_fatal_error("conflicting sections for symbol");
00490 
00491         coff_symbol->Section = Sec;
00492       }
00493     }
00494 
00495     coff_symbol->MCData = &ResSymData;
00496   }
00497 }
00498 
00499 // Maximum offsets for different string table entry encodings.
00500 static const unsigned Max6DecimalOffset = 999999;
00501 static const unsigned Max7DecimalOffset = 9999999;
00502 static const uint64_t MaxBase64Offset = 0xFFFFFFFFFULL; // 64^6, including 0
00503 
00504 // Encode a string table entry offset in base 64, padded to 6 chars, and
00505 // prefixed with a double slash: '//AAAAAA', '//AAAAAB', ...
00506 // Buffer must be at least 8 bytes large. No terminating null appended.
00507 static void encodeBase64StringEntry(char* Buffer, uint64_t Value) {
00508   assert(Value > Max7DecimalOffset && Value <= MaxBase64Offset &&
00509          "Illegal section name encoding for value");
00510 
00511   static const char Alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
00512                                  "abcdefghijklmnopqrstuvwxyz"
00513                                  "0123456789+/";
00514 
00515   Buffer[0] = '/';
00516   Buffer[1] = '/';
00517 
00518   char* Ptr = Buffer + 7;
00519   for (unsigned i = 0; i < 6; ++i) {
00520     unsigned Rem = Value % 64;
00521     Value /= 64;
00522     *(Ptr--) = Alphabet[Rem];
00523   }
00524 }
00525 
00526 /// making a section real involves assigned it a number and putting
00527 /// name into the string table if needed
00528 void WinCOFFObjectWriter::MakeSectionReal(COFFSection &S, size_t Number) {
00529   if (S.Name.size() > COFF::NameSize) {
00530     uint64_t StringTableEntry = Strings.insert(S.Name.c_str());
00531 
00532     if (StringTableEntry <= Max6DecimalOffset) {
00533       std::sprintf(S.Header.Name, "/%d", unsigned(StringTableEntry));
00534     } else if (StringTableEntry <= Max7DecimalOffset) {
00535       // With seven digits, we have to skip the terminating null. Because
00536       // sprintf always appends it, we use a larger temporary buffer.
00537       char buffer[9] = { };
00538       std::sprintf(buffer, "/%d", unsigned(StringTableEntry));
00539       std::memcpy(S.Header.Name, buffer, 8);
00540     } else if (StringTableEntry <= MaxBase64Offset) {
00541       // Starting with 10,000,000, offsets are encoded as base64.
00542       encodeBase64StringEntry(S.Header.Name, StringTableEntry);
00543     } else {
00544       report_fatal_error("COFF string table is greater than 64 GB.");
00545     }
00546   } else
00547     std::memcpy(S.Header.Name, S.Name.c_str(), S.Name.size());
00548 
00549   S.Number = Number;
00550   S.Symbol->Data.SectionNumber = S.Number;
00551   S.Symbol->Aux[0].Aux.SectionDefinition.Number = S.Number;
00552 }
00553 
00554 void WinCOFFObjectWriter::MakeSymbolReal(COFFSymbol &S, size_t Index) {
00555   if (S.Name.size() > COFF::NameSize) {
00556     size_t StringTableEntry = Strings.insert(S.Name.c_str());
00557 
00558     S.set_name_offset(StringTableEntry);
00559   } else
00560     std::memcpy(S.Data.Name, S.Name.c_str(), S.Name.size());
00561   S.Index = Index;
00562 }
00563 
00564 bool WinCOFFObjectWriter::ExportSymbol(const MCSymbol &Symbol,
00565                                        MCAssembler &Asm) {
00566   // This doesn't seem to be right. Strings referred to from the .data section
00567   // need symbols so they can be linked to code in the .text section right?
00568 
00569   // return Asm.isSymbolLinkerVisible(Symbol);
00570 
00571   // Non-temporary labels should always be visible to the linker.
00572   if (!Symbol.isTemporary())
00573     return true;
00574 
00575   // Absolute temporary labels are never visible.
00576   if (!Symbol.isInSection())
00577     return false;
00578 
00579   // For now, all non-variable symbols are exported,
00580   // the linker will sort the rest out for us.
00581   return !Symbol.isVariable();
00582 }
00583 
00584 bool WinCOFFObjectWriter::IsPhysicalSection(COFFSection *S) {
00585   return (S->Header.Characteristics
00586          & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) == 0;
00587 }
00588 
00589 //------------------------------------------------------------------------------
00590 // entity writing methods
00591 
00592 void WinCOFFObjectWriter::WriteFileHeader(const COFF::header &Header) {
00593   if (UseBigObj) {
00594     WriteLE16(COFF::IMAGE_FILE_MACHINE_UNKNOWN);
00595     WriteLE16(0xFFFF);
00596     WriteLE16(COFF::BigObjHeader::MinBigObjectVersion);
00597     WriteLE16(Header.Machine);
00598     WriteLE32(Header.TimeDateStamp);
00599     for (uint8_t MagicChar : COFF::BigObjMagic)
00600       Write8(MagicChar);
00601     WriteLE32(0);
00602     WriteLE32(0);
00603     WriteLE32(0);
00604     WriteLE32(0);
00605     WriteLE32(Header.NumberOfSections);
00606     WriteLE32(Header.PointerToSymbolTable);
00607     WriteLE32(Header.NumberOfSymbols);
00608   } else {
00609     WriteLE16(Header.Machine);
00610     WriteLE16(static_cast<int16_t>(Header.NumberOfSections));
00611     WriteLE32(Header.TimeDateStamp);
00612     WriteLE32(Header.PointerToSymbolTable);
00613     WriteLE32(Header.NumberOfSymbols);
00614     WriteLE16(Header.SizeOfOptionalHeader);
00615     WriteLE16(Header.Characteristics);
00616   }
00617 }
00618 
00619 void WinCOFFObjectWriter::WriteSymbol(const COFFSymbol &S) {
00620   WriteBytes(StringRef(S.Data.Name, COFF::NameSize));
00621   WriteLE32(S.Data.Value);
00622   if (UseBigObj)
00623     WriteLE32(S.Data.SectionNumber);
00624   else
00625     WriteLE16(static_cast<int16_t>(S.Data.SectionNumber));
00626   WriteLE16(S.Data.Type);
00627   Write8(S.Data.StorageClass);
00628   Write8(S.Data.NumberOfAuxSymbols);
00629   WriteAuxiliarySymbols(S.Aux);
00630 }
00631 
00632 void WinCOFFObjectWriter::WriteAuxiliarySymbols(
00633                                         const COFFSymbol::AuxiliarySymbols &S) {
00634   for(COFFSymbol::AuxiliarySymbols::const_iterator i = S.begin(), e = S.end();
00635       i != e; ++i) {
00636     switch(i->AuxType) {
00637     case ATFunctionDefinition:
00638       WriteLE32(i->Aux.FunctionDefinition.TagIndex);
00639       WriteLE32(i->Aux.FunctionDefinition.TotalSize);
00640       WriteLE32(i->Aux.FunctionDefinition.PointerToLinenumber);
00641       WriteLE32(i->Aux.FunctionDefinition.PointerToNextFunction);
00642       WriteZeros(sizeof(i->Aux.FunctionDefinition.unused));
00643       if (UseBigObj)
00644         WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
00645       break;
00646     case ATbfAndefSymbol:
00647       WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused1));
00648       WriteLE16(i->Aux.bfAndefSymbol.Linenumber);
00649       WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused2));
00650       WriteLE32(i->Aux.bfAndefSymbol.PointerToNextFunction);
00651       WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused3));
00652       if (UseBigObj)
00653         WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
00654       break;
00655     case ATWeakExternal:
00656       WriteLE32(i->Aux.WeakExternal.TagIndex);
00657       WriteLE32(i->Aux.WeakExternal.Characteristics);
00658       WriteZeros(sizeof(i->Aux.WeakExternal.unused));
00659       if (UseBigObj)
00660         WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
00661       break;
00662     case ATFile:
00663       WriteBytes(
00664           StringRef(reinterpret_cast<const char *>(&i->Aux),
00665                     UseBigObj ? COFF::Symbol32Size : COFF::Symbol16Size));
00666       break;
00667     case ATSectionDefinition:
00668       WriteLE32(i->Aux.SectionDefinition.Length);
00669       WriteLE16(i->Aux.SectionDefinition.NumberOfRelocations);
00670       WriteLE16(i->Aux.SectionDefinition.NumberOfLinenumbers);
00671       WriteLE32(i->Aux.SectionDefinition.CheckSum);
00672       WriteLE16(static_cast<int16_t>(i->Aux.SectionDefinition.Number));
00673       Write8(i->Aux.SectionDefinition.Selection);
00674       WriteZeros(sizeof(i->Aux.SectionDefinition.unused));
00675       WriteLE16(static_cast<int16_t>(i->Aux.SectionDefinition.Number >> 16));
00676       if (UseBigObj)
00677         WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
00678       break;
00679     }
00680   }
00681 }
00682 
00683 void WinCOFFObjectWriter::WriteSectionHeader(const COFF::section &S) {
00684   WriteBytes(StringRef(S.Name, COFF::NameSize));
00685 
00686   WriteLE32(S.VirtualSize);
00687   WriteLE32(S.VirtualAddress);
00688   WriteLE32(S.SizeOfRawData);
00689   WriteLE32(S.PointerToRawData);
00690   WriteLE32(S.PointerToRelocations);
00691   WriteLE32(S.PointerToLineNumbers);
00692   WriteLE16(S.NumberOfRelocations);
00693   WriteLE16(S.NumberOfLineNumbers);
00694   WriteLE32(S.Characteristics);
00695 }
00696 
00697 void WinCOFFObjectWriter::WriteRelocation(const COFF::relocation &R) {
00698   WriteLE32(R.VirtualAddress);
00699   WriteLE32(R.SymbolTableIndex);
00700   WriteLE16(R.Type);
00701 }
00702 
00703 ////////////////////////////////////////////////////////////////////////////////
00704 // MCObjectWriter interface implementations
00705 
00706 void WinCOFFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
00707                                                    const MCAsmLayout &Layout) {
00708   // "Define" each section & symbol. This creates section & symbol
00709   // entries in the staging area.
00710   for (const auto & Section : Asm)
00711     DefineSection(Section);
00712 
00713   for (MCSymbolData &SD : Asm.symbols())
00714     if (ExportSymbol(SD.getSymbol(), Asm))
00715       DefineSymbol(SD, Asm, Layout);
00716 }
00717 
00718 void WinCOFFObjectWriter::RecordRelocation(const MCAssembler &Asm,
00719                                            const MCAsmLayout &Layout,
00720                                            const MCFragment *Fragment,
00721                                            const MCFixup &Fixup,
00722                                            MCValue Target,
00723                                            bool &IsPCRel,
00724                                            uint64_t &FixedValue) {
00725   assert(Target.getSymA() && "Relocation must reference a symbol!");
00726 
00727   const MCSymbol &Symbol = Target.getSymA()->getSymbol();
00728   const MCSymbol &A = Symbol.AliasedSymbol();
00729   if (!Asm.hasSymbolData(A))
00730     Asm.getContext().FatalError(
00731         Fixup.getLoc(),
00732         Twine("symbol '") + A.getName() + "' can not be undefined");
00733 
00734   const MCSymbolData &A_SD = Asm.getSymbolData(A);
00735 
00736   MCSectionData const *SectionData = Fragment->getParent();
00737 
00738   // Mark this symbol as requiring an entry in the symbol table.
00739   assert(SectionMap.find(&SectionData->getSection()) != SectionMap.end() &&
00740          "Section must already have been defined in ExecutePostLayoutBinding!");
00741   assert(SymbolMap.find(&A_SD.getSymbol()) != SymbolMap.end() &&
00742          "Symbol must already have been defined in ExecutePostLayoutBinding!");
00743 
00744   COFFSection *coff_section = SectionMap[&SectionData->getSection()];
00745   COFFSymbol *coff_symbol = SymbolMap[&A_SD.getSymbol()];
00746   const MCSymbolRefExpr *SymB = Target.getSymB();
00747   bool CrossSection = false;
00748 
00749   if (SymB) {
00750     const MCSymbol *B = &SymB->getSymbol();
00751     const MCSymbolData &B_SD = Asm.getSymbolData(*B);
00752     if (!B_SD.getFragment())
00753       Asm.getContext().FatalError(
00754           Fixup.getLoc(),
00755           Twine("symbol '") + B->getName() +
00756               "' can not be undefined in a subtraction expression");
00757 
00758     if (!A_SD.getFragment())
00759       Asm.getContext().FatalError(
00760           Fixup.getLoc(),
00761           Twine("symbol '") + Symbol.getName() +
00762               "' can not be undefined in a subtraction expression");
00763 
00764     CrossSection = &Symbol.getSection() != &B->getSection();
00765 
00766     // Offset of the symbol in the section
00767     int64_t a = Layout.getSymbolOffset(&B_SD);
00768 
00769     // Ofeset of the relocation in the section
00770     int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
00771 
00772     FixedValue = b - a;
00773     // In the case where we have SymbA and SymB, we just need to store the delta
00774     // between the two symbols.  Update FixedValue to account for the delta, and
00775     // skip recording the relocation.
00776     if (!CrossSection)
00777       return;
00778   } else {
00779     FixedValue = Target.getConstant();
00780   }
00781 
00782   COFFRelocation Reloc;
00783 
00784   Reloc.Data.SymbolTableIndex = 0;
00785   Reloc.Data.VirtualAddress = Layout.getFragmentOffset(Fragment);
00786 
00787   // Turn relocations for temporary symbols into section relocations.
00788   if (coff_symbol->MCData->getSymbol().isTemporary() || CrossSection) {
00789     Reloc.Symb = coff_symbol->Section->Symbol;
00790     FixedValue += Layout.getFragmentOffset(coff_symbol->MCData->Fragment)
00791                 + coff_symbol->MCData->getOffset();
00792   } else
00793     Reloc.Symb = coff_symbol;
00794 
00795   ++Reloc.Symb->Relocations;
00796 
00797   Reloc.Data.VirtualAddress += Fixup.getOffset();
00798   Reloc.Data.Type = TargetObjectWriter->getRelocType(Target, Fixup,
00799                                                      CrossSection);
00800 
00801   // FIXME: Can anyone explain what this does other than adjust for the size
00802   // of the offset?
00803   if ((Header.Machine == COFF::IMAGE_FILE_MACHINE_AMD64 &&
00804        Reloc.Data.Type == COFF::IMAGE_REL_AMD64_REL32) ||
00805       (Header.Machine == COFF::IMAGE_FILE_MACHINE_I386 &&
00806        Reloc.Data.Type == COFF::IMAGE_REL_I386_REL32))
00807     FixedValue += 4;
00808 
00809   if (Header.Machine == COFF::IMAGE_FILE_MACHINE_ARMNT) {
00810     switch (Reloc.Data.Type) {
00811     case COFF::IMAGE_REL_ARM_ABSOLUTE:
00812     case COFF::IMAGE_REL_ARM_ADDR32:
00813     case COFF::IMAGE_REL_ARM_ADDR32NB:
00814     case COFF::IMAGE_REL_ARM_TOKEN:
00815     case COFF::IMAGE_REL_ARM_SECTION:
00816     case COFF::IMAGE_REL_ARM_SECREL:
00817       break;
00818     case COFF::IMAGE_REL_ARM_BRANCH11:
00819     case COFF::IMAGE_REL_ARM_BLX11:
00820       // IMAGE_REL_ARM_BRANCH11 and IMAGE_REL_ARM_BLX11 are only used for
00821       // pre-ARMv7, which implicitly rules it out of ARMNT (it would be valid
00822       // for Windows CE).
00823     case COFF::IMAGE_REL_ARM_BRANCH24:
00824     case COFF::IMAGE_REL_ARM_BLX24:
00825     case COFF::IMAGE_REL_ARM_MOV32A:
00826       // IMAGE_REL_ARM_BRANCH24, IMAGE_REL_ARM_BLX24, IMAGE_REL_ARM_MOV32A are
00827       // only used for ARM mode code, which is documented as being unsupported
00828       // by Windows on ARM.  Empirical proof indicates that masm is able to
00829       // generate the relocations however the rest of the MSVC toolchain is
00830       // unable to handle it.
00831       llvm_unreachable("unsupported relocation");
00832       break;
00833     case COFF::IMAGE_REL_ARM_MOV32T:
00834       break;
00835     case COFF::IMAGE_REL_ARM_BRANCH20T:
00836     case COFF::IMAGE_REL_ARM_BRANCH24T:
00837     case COFF::IMAGE_REL_ARM_BLX23T:
00838       // IMAGE_REL_BRANCH20T, IMAGE_REL_ARM_BRANCH24T, IMAGE_REL_ARM_BLX23T all
00839       // perform a 4 byte adjustment to the relocation.  Relative branches are
00840       // offset by 4 on ARM, however, because there is no RELA relocations, all
00841       // branches are offset by 4.
00842       FixedValue = FixedValue + 4;
00843       break;
00844     }
00845   }
00846 
00847   if (TargetObjectWriter->recordRelocation(Fixup))
00848     coff_section->Relocations.push_back(Reloc);
00849 }
00850 
00851 void WinCOFFObjectWriter::WriteObject(MCAssembler &Asm,
00852                                       const MCAsmLayout &Layout) {
00853   size_t SectionsSize = Sections.size();
00854   if (SectionsSize > static_cast<size_t>(INT32_MAX))
00855     report_fatal_error(
00856         "PE COFF object files can't have more than 2147483647 sections");
00857 
00858   // Assign symbol and section indexes and offsets.
00859   int32_t NumberOfSections = static_cast<int32_t>(SectionsSize);
00860 
00861   UseBigObj = NumberOfSections > COFF::MaxNumberOfSections16;
00862 
00863   DenseMap<COFFSection *, int32_t> SectionIndices(
00864       NextPowerOf2(NumberOfSections));
00865   size_t Number = 1;
00866   for (const auto &Section : Sections) {
00867     SectionIndices[Section.get()] = Number;
00868     MakeSectionReal(*Section, Number);
00869     ++Number;
00870   }
00871 
00872   Header.NumberOfSections = NumberOfSections;
00873   Header.NumberOfSymbols = 0;
00874 
00875   for (auto FI = Asm.file_names_begin(), FE = Asm.file_names_end();
00876        FI != FE; ++FI) {
00877     // round up to calculate the number of auxiliary symbols required
00878     unsigned SymbolSize = UseBigObj ? COFF::Symbol32Size : COFF::Symbol16Size;
00879     unsigned Count = (FI->size() + SymbolSize - 1) / SymbolSize;
00880 
00881     COFFSymbol *file = createSymbol(".file");
00882     file->Data.SectionNumber = COFF::IMAGE_SYM_DEBUG;
00883     file->Data.StorageClass = COFF::IMAGE_SYM_CLASS_FILE;
00884     file->Aux.resize(Count);
00885 
00886     unsigned Offset = 0;
00887     unsigned Length = FI->size();
00888     for (auto & Aux : file->Aux) {
00889       Aux.AuxType = ATFile;
00890 
00891       if (Length > SymbolSize) {
00892         memcpy(&Aux.Aux, FI->c_str() + Offset, SymbolSize);
00893         Length = Length - SymbolSize;
00894       } else {
00895         memcpy(&Aux.Aux, FI->c_str() + Offset, Length);
00896         memset((char *)&Aux.Aux + Length, 0, SymbolSize - Length);
00897         break;
00898       }
00899 
00900       Offset += SymbolSize;
00901     }
00902   }
00903 
00904   for (auto &Symbol : Symbols) {
00905     // Update section number & offset for symbols that have them.
00906     if (Symbol->Section)
00907       Symbol->Data.SectionNumber = Symbol->Section->Number;
00908 
00909     if (Symbol->should_keep()) {
00910       MakeSymbolReal(*Symbol, Header.NumberOfSymbols++);
00911 
00912       // Update auxiliary symbol info.
00913       Symbol->Data.NumberOfAuxSymbols = Symbol->Aux.size();
00914       Header.NumberOfSymbols += Symbol->Data.NumberOfAuxSymbols;
00915     } else
00916       Symbol->Index = -1;
00917   }
00918 
00919   // Fixup weak external references.
00920   for (auto & Symbol : Symbols) {
00921     if (Symbol->Other) {
00922       assert(Symbol->Index != -1);
00923       assert(Symbol->Aux.size() == 1 && "Symbol must contain one aux symbol!");
00924       assert(Symbol->Aux[0].AuxType == ATWeakExternal &&
00925              "Symbol's aux symbol must be a Weak External!");
00926       Symbol->Aux[0].Aux.WeakExternal.TagIndex = Symbol->Other->Index;
00927     }
00928   }
00929 
00930   // Fixup associative COMDAT sections.
00931   for (auto & Section : Sections) {
00932     if (Section->Symbol->Aux[0].Aux.SectionDefinition.Selection !=
00933         COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
00934       continue;
00935 
00936     const MCSectionCOFF &MCSec =
00937       static_cast<const MCSectionCOFF &>(Section->MCData->getSection());
00938 
00939     const MCSymbol *COMDAT = MCSec.getCOMDATSymbol();
00940     assert(COMDAT);
00941     COFFSymbol *COMDATSymbol = GetOrCreateCOFFSymbol(COMDAT);
00942     assert(COMDATSymbol);
00943     COFFSection *Assoc = COMDATSymbol->Section;
00944     if (!Assoc)
00945       report_fatal_error(
00946           Twine("Missing associated COMDAT section for section ") +
00947           MCSec.getSectionName());
00948 
00949     // Skip this section if the associated section is unused.
00950     if (Assoc->Number == -1)
00951       continue;
00952 
00953     Section->Symbol->Aux[0].Aux.SectionDefinition.Number = SectionIndices[Assoc];
00954   }
00955 
00956 
00957   // Assign file offsets to COFF object file structures.
00958 
00959   unsigned offset = 0;
00960 
00961   if (UseBigObj)
00962     offset += COFF::Header32Size;
00963   else
00964     offset += COFF::Header16Size;
00965   offset += COFF::SectionSize * Header.NumberOfSections;
00966 
00967   for (const auto & Section : Asm) {
00968     COFFSection *Sec = SectionMap[&Section.getSection()];
00969 
00970     if (Sec->Number == -1)
00971       continue;
00972 
00973     Sec->Header.SizeOfRawData = Layout.getSectionAddressSize(&Section);
00974 
00975     if (IsPhysicalSection(Sec)) {
00976       Sec->Header.PointerToRawData = offset;
00977 
00978       offset += Sec->Header.SizeOfRawData;
00979     }
00980 
00981     if (Sec->Relocations.size() > 0) {
00982       bool RelocationsOverflow = Sec->Relocations.size() >= 0xffff;
00983 
00984       if (RelocationsOverflow) {
00985         // Signal overflow by setting NumberOfRelocations to max value. Actual
00986         // size is found in reloc #0. Microsoft tools understand this.
00987         Sec->Header.NumberOfRelocations = 0xffff;
00988       } else {
00989         Sec->Header.NumberOfRelocations = Sec->Relocations.size();
00990       }
00991       Sec->Header.PointerToRelocations = offset;
00992 
00993       if (RelocationsOverflow) {
00994         // Reloc #0 will contain actual count, so make room for it.
00995         offset += COFF::RelocationSize;
00996       }
00997 
00998       offset += COFF::RelocationSize * Sec->Relocations.size();
00999 
01000       for (auto & Relocation : Sec->Relocations) {
01001         assert(Relocation.Symb->Index != -1);
01002         Relocation.Data.SymbolTableIndex = Relocation.Symb->Index;
01003       }
01004     }
01005 
01006     assert(Sec->Symbol->Aux.size() == 1 &&
01007            "Section's symbol must have one aux!");
01008     AuxSymbol &Aux = Sec->Symbol->Aux[0];
01009     assert(Aux.AuxType == ATSectionDefinition &&
01010            "Section's symbol's aux symbol must be a Section Definition!");
01011     Aux.Aux.SectionDefinition.Length = Sec->Header.SizeOfRawData;
01012     Aux.Aux.SectionDefinition.NumberOfRelocations =
01013                                                 Sec->Header.NumberOfRelocations;
01014     Aux.Aux.SectionDefinition.NumberOfLinenumbers =
01015                                                 Sec->Header.NumberOfLineNumbers;
01016   }
01017 
01018   Header.PointerToSymbolTable = offset;
01019 
01020   // We want a deterministic output. It looks like GNU as also writes 0 in here.
01021   Header.TimeDateStamp = 0;
01022 
01023   // Write it all to disk...
01024   WriteFileHeader(Header);
01025 
01026   {
01027     sections::iterator i, ie;
01028     MCAssembler::const_iterator j, je;
01029 
01030     for (auto & Section : Sections) {
01031       if (Section->Number != -1) {
01032         if (Section->Relocations.size() >= 0xffff)
01033           Section->Header.Characteristics |= COFF::IMAGE_SCN_LNK_NRELOC_OVFL;
01034         WriteSectionHeader(Section->Header);
01035       }
01036     }
01037 
01038     for (i = Sections.begin(), ie = Sections.end(),
01039          j = Asm.begin(), je = Asm.end();
01040          (i != ie) && (j != je); ++i, ++j) {
01041 
01042       if ((*i)->Number == -1)
01043         continue;
01044 
01045       if ((*i)->Header.PointerToRawData != 0) {
01046         assert(OS.tell() == (*i)->Header.PointerToRawData &&
01047                "Section::PointerToRawData is insane!");
01048 
01049         Asm.writeSectionData(j, Layout);
01050       }
01051 
01052       if ((*i)->Relocations.size() > 0) {
01053         assert(OS.tell() == (*i)->Header.PointerToRelocations &&
01054                "Section::PointerToRelocations is insane!");
01055 
01056         if ((*i)->Relocations.size() >= 0xffff) {
01057           // In case of overflow, write actual relocation count as first
01058           // relocation. Including the synthetic reloc itself (+ 1).
01059           COFF::relocation r;
01060           r.VirtualAddress = (*i)->Relocations.size() + 1;
01061           r.SymbolTableIndex = 0;
01062           r.Type = 0;
01063           WriteRelocation(r);
01064         }
01065 
01066         for (const auto & Relocation : (*i)->Relocations)
01067           WriteRelocation(Relocation.Data);
01068       } else
01069         assert((*i)->Header.PointerToRelocations == 0 &&
01070                "Section::PointerToRelocations is insane!");
01071     }
01072   }
01073 
01074   assert(OS.tell() == Header.PointerToSymbolTable &&
01075          "Header::PointerToSymbolTable is insane!");
01076 
01077   for (auto & Symbol : Symbols)
01078     if (Symbol->Index != -1)
01079       WriteSymbol(*Symbol);
01080 
01081   OS.write((char const *)&Strings.Data.front(), Strings.Data.size());
01082 }
01083 
01084 MCWinCOFFObjectTargetWriter::MCWinCOFFObjectTargetWriter(unsigned Machine_) :
01085   Machine(Machine_) {
01086 }
01087 
01088 // Pin the vtable to this file.
01089 void MCWinCOFFObjectTargetWriter::anchor() {}
01090 
01091 //------------------------------------------------------------------------------
01092 // WinCOFFObjectWriter factory function
01093 
01094 namespace llvm {
01095   MCObjectWriter *createWinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW,
01096                                             raw_ostream &OS) {
01097     return new WinCOFFObjectWriter(MOTW, OS);
01098   }
01099 }