Home | History | Annotate | Download | only in MC
      1 //===- lib/MC/MCELFStreamer.cpp - ELF Object Output ------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This file assembles .s files and emits ELF .o object files.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #include "MCELF.h"
     15 #include "llvm/ADT/SmallPtrSet.h"
     16 #include "llvm/MC/MCAssembler.h"
     17 #include "llvm/MC/MCCodeEmitter.h"
     18 #include "llvm/MC/MCContext.h"
     19 #include "llvm/MC/MCSectionELF.h"
     20 #include "llvm/MC/MCStreamer.h"
     21 #include "llvm/MC/MCELFSymbolFlags.h"
     22 #include "llvm/MC/MCExpr.h"
     23 #include "llvm/MC/MCInst.h"
     24 #include "llvm/MC/MCObjectStreamer.h"
     25 #include "llvm/MC/MCSection.h"
     26 #include "llvm/MC/MCSymbol.h"
     27 #include "llvm/MC/MCValue.h"
     28 #include "llvm/MC/MCAsmBackend.h"
     29 #include "llvm/Support/Debug.h"
     30 #include "llvm/Support/ELF.h"
     31 #include "llvm/Support/ErrorHandling.h"
     32 #include "llvm/Support/raw_ostream.h"
     33 
     34 using namespace llvm;
     35 
     36 namespace {
     37 class MCELFStreamer : public MCObjectStreamer {
     38 public:
     39   MCELFStreamer(MCContext &Context, MCAsmBackend &TAB,
     40                   raw_ostream &OS, MCCodeEmitter *Emitter)
     41     : MCObjectStreamer(Context, TAB, OS, Emitter) {}
     42 
     43   MCELFStreamer(MCContext &Context, MCAsmBackend &TAB,
     44                 raw_ostream &OS, MCCodeEmitter *Emitter,
     45                 MCAssembler *Assembler)
     46     : MCObjectStreamer(Context, TAB, OS, Emitter, Assembler) {}
     47 
     48 
     49   ~MCELFStreamer() {}
     50 
     51   /// @name MCStreamer Interface
     52   /// @{
     53 
     54   virtual void InitSections();
     55   virtual void ChangeSection(const MCSection *Section);
     56   virtual void EmitLabel(MCSymbol *Symbol);
     57   virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
     58   virtual void EmitThumbFunc(MCSymbol *Func);
     59   virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
     60   virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol);
     61   virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
     62   virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
     63     llvm_unreachable("ELF doesn't support this directive");
     64   }
     65   virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
     66                                 unsigned ByteAlignment);
     67   virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol) {
     68     llvm_unreachable("ELF doesn't support this directive");
     69   }
     70 
     71   virtual void EmitCOFFSymbolStorageClass(int StorageClass) {
     72     llvm_unreachable("ELF doesn't support this directive");
     73   }
     74 
     75   virtual void EmitCOFFSymbolType(int Type) {
     76     llvm_unreachable("ELF doesn't support this directive");
     77   }
     78 
     79   virtual void EndCOFFSymbolDef() {
     80     llvm_unreachable("ELF doesn't support this directive");
     81   }
     82 
     83   virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
     84      MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
     85      SD.setSize(Value);
     86   }
     87 
     88   virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
     89                                      unsigned ByteAlignment);
     90 
     91   virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
     92                             unsigned Size = 0, unsigned ByteAlignment = 0) {
     93     llvm_unreachable("ELF doesn't support this directive");
     94   }
     95   virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
     96                               uint64_t Size, unsigned ByteAlignment = 0) {
     97     llvm_unreachable("ELF doesn't support this directive");
     98   }
     99   virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
    100   virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
    101                                     unsigned ValueSize = 1,
    102                                     unsigned MaxBytesToEmit = 0);
    103   virtual void EmitCodeAlignment(unsigned ByteAlignment,
    104                                  unsigned MaxBytesToEmit = 0);
    105   virtual void EmitValueImpl(const MCExpr *Value, unsigned Size,
    106                              unsigned AddrSpace);
    107 
    108   virtual void EmitFileDirective(StringRef Filename);
    109 
    110   virtual void FinishImpl();
    111 
    112 private:
    113   virtual void EmitInstToFragment(const MCInst &Inst);
    114   virtual void EmitInstToData(const MCInst &Inst);
    115 
    116   void fixSymbolsInTLSFixups(const MCExpr *expr);
    117 
    118   struct LocalCommon {
    119     MCSymbolData *SD;
    120     uint64_t Size;
    121     unsigned ByteAlignment;
    122   };
    123   std::vector<LocalCommon> LocalCommons;
    124 
    125   SmallPtrSet<MCSymbol *, 16> BindingExplicitlySet;
    126   /// @}
    127   void SetSection(StringRef Section, unsigned Type, unsigned Flags,
    128                   SectionKind Kind) {
    129     SwitchSection(getContext().getELFSection(Section, Type, Flags, Kind));
    130   }
    131 
    132   void SetSectionData() {
    133     SetSection(".data", ELF::SHT_PROGBITS,
    134                ELF::SHF_WRITE |ELF::SHF_ALLOC,
    135                SectionKind::getDataRel());
    136     EmitCodeAlignment(4, 0);
    137   }
    138   void SetSectionText() {
    139     SetSection(".text", ELF::SHT_PROGBITS,
    140                ELF::SHF_EXECINSTR |
    141                ELF::SHF_ALLOC, SectionKind::getText());
    142     EmitCodeAlignment(4, 0);
    143   }
    144   void SetSectionBss() {
    145     SetSection(".bss", ELF::SHT_NOBITS,
    146                ELF::SHF_WRITE |
    147                ELF::SHF_ALLOC, SectionKind::getBSS());
    148     EmitCodeAlignment(4, 0);
    149   }
    150 };
    151 }
    152 
    153 void MCELFStreamer::InitSections() {
    154   // This emulates the same behavior of GNU as. This makes it easier
    155   // to compare the output as the major sections are in the same order.
    156   SetSectionText();
    157   SetSectionData();
    158   SetSectionBss();
    159   SetSectionText();
    160 }
    161 
    162 void MCELFStreamer::EmitLabel(MCSymbol *Symbol) {
    163   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
    164 
    165   MCObjectStreamer::EmitLabel(Symbol);
    166 
    167   const MCSectionELF &Section =
    168     static_cast<const MCSectionELF&>(Symbol->getSection());
    169   MCSymbolData &SD = getAssembler().getSymbolData(*Symbol);
    170   if (Section.getFlags() & ELF::SHF_TLS)
    171     MCELF::SetType(SD, ELF::STT_TLS);
    172 }
    173 
    174 void MCELFStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
    175   switch (Flag) {
    176   case MCAF_SyntaxUnified: return; // no-op here.
    177   case MCAF_Code16: return; // Change parsing mode; no-op here.
    178   case MCAF_Code32: return; // Change parsing mode; no-op here.
    179   case MCAF_Code64: return; // Change parsing mode; no-op here.
    180   case MCAF_SubsectionsViaSymbols:
    181     getAssembler().setSubsectionsViaSymbols(true);
    182     return;
    183   }
    184 
    185   llvm_unreachable("invalid assembler flag!");
    186 }
    187 
    188 void MCELFStreamer::EmitThumbFunc(MCSymbol *Func) {
    189   // FIXME: Anything needed here to flag the function as thumb?
    190 
    191   getAssembler().setIsThumbFunc(Func);
    192 
    193   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Func);
    194   SD.setFlags(SD.getFlags() | ELF_Other_ThumbFunc);
    195 }
    196 
    197 void MCELFStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
    198   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
    199   // MCObjectStreamer.
    200   // FIXME: Lift context changes into super class.
    201   getAssembler().getOrCreateSymbolData(*Symbol);
    202   Symbol->setVariableValue(AddValueSymbols(Value));
    203 }
    204 
    205 void MCELFStreamer::ChangeSection(const MCSection *Section) {
    206   const MCSymbol *Grp = static_cast<const MCSectionELF *>(Section)->getGroup();
    207   if (Grp)
    208     getAssembler().getOrCreateSymbolData(*Grp);
    209   this->MCObjectStreamer::ChangeSection(Section);
    210 }
    211 
    212 void MCELFStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
    213   getAssembler().getOrCreateSymbolData(*Symbol);
    214   MCSymbolData &AliasSD = getAssembler().getOrCreateSymbolData(*Alias);
    215   AliasSD.setFlags(AliasSD.getFlags() | ELF_Other_Weakref);
    216   const MCExpr *Value = MCSymbolRefExpr::Create(Symbol, getContext());
    217   Alias->setVariableValue(Value);
    218 }
    219 
    220 void MCELFStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
    221                                           MCSymbolAttr Attribute) {
    222   // Indirect symbols are handled differently, to match how 'as' handles
    223   // them. This makes writing matching .o files easier.
    224   if (Attribute == MCSA_IndirectSymbol) {
    225     // Note that we intentionally cannot use the symbol data here; this is
    226     // important for matching the string table that 'as' generates.
    227     IndirectSymbolData ISD;
    228     ISD.Symbol = Symbol;
    229     ISD.SectionData = getCurrentSectionData();
    230     getAssembler().getIndirectSymbols().push_back(ISD);
    231     return;
    232   }
    233 
    234   // Adding a symbol attribute always introduces the symbol, note that an
    235   // important side effect of calling getOrCreateSymbolData here is to register
    236   // the symbol with the assembler.
    237   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
    238 
    239   // The implementation of symbol attributes is designed to match 'as', but it
    240   // leaves much to desired. It doesn't really make sense to arbitrarily add and
    241   // remove flags, but 'as' allows this (in particular, see .desc).
    242   //
    243   // In the future it might be worth trying to make these operations more well
    244   // defined.
    245   switch (Attribute) {
    246   case MCSA_LazyReference:
    247   case MCSA_Reference:
    248   case MCSA_NoDeadStrip:
    249   case MCSA_SymbolResolver:
    250   case MCSA_PrivateExtern:
    251   case MCSA_WeakDefinition:
    252   case MCSA_WeakDefAutoPrivate:
    253   case MCSA_Invalid:
    254   case MCSA_IndirectSymbol:
    255     llvm_unreachable("Invalid symbol attribute for ELF!");
    256 
    257   case MCSA_ELF_TypeGnuUniqueObject:
    258     // Ignore for now.
    259     break;
    260 
    261   case MCSA_Global:
    262     MCELF::SetBinding(SD, ELF::STB_GLOBAL);
    263     SD.setExternal(true);
    264     BindingExplicitlySet.insert(Symbol);
    265     break;
    266 
    267   case MCSA_WeakReference:
    268   case MCSA_Weak:
    269     MCELF::SetBinding(SD, ELF::STB_WEAK);
    270     SD.setExternal(true);
    271     BindingExplicitlySet.insert(Symbol);
    272     break;
    273 
    274   case MCSA_Local:
    275     MCELF::SetBinding(SD, ELF::STB_LOCAL);
    276     SD.setExternal(false);
    277     BindingExplicitlySet.insert(Symbol);
    278     break;
    279 
    280   case MCSA_ELF_TypeFunction:
    281     MCELF::SetType(SD, ELF::STT_FUNC);
    282     break;
    283 
    284   case MCSA_ELF_TypeIndFunction:
    285     MCELF::SetType(SD, ELF::STT_GNU_IFUNC);
    286     break;
    287 
    288   case MCSA_ELF_TypeObject:
    289     MCELF::SetType(SD, ELF::STT_OBJECT);
    290     break;
    291 
    292   case MCSA_ELF_TypeTLS:
    293     MCELF::SetType(SD, ELF::STT_TLS);
    294     break;
    295 
    296   case MCSA_ELF_TypeCommon:
    297     MCELF::SetType(SD, ELF::STT_COMMON);
    298     break;
    299 
    300   case MCSA_ELF_TypeNoType:
    301     MCELF::SetType(SD, ELF::STT_NOTYPE);
    302     break;
    303 
    304   case MCSA_Protected:
    305     MCELF::SetVisibility(SD, ELF::STV_PROTECTED);
    306     break;
    307 
    308   case MCSA_Hidden:
    309     MCELF::SetVisibility(SD, ELF::STV_HIDDEN);
    310     break;
    311 
    312   case MCSA_Internal:
    313     MCELF::SetVisibility(SD, ELF::STV_INTERNAL);
    314     break;
    315   }
    316 }
    317 
    318 void MCELFStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
    319                                        unsigned ByteAlignment) {
    320   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
    321 
    322   if (!BindingExplicitlySet.count(Symbol)) {
    323     MCELF::SetBinding(SD, ELF::STB_GLOBAL);
    324     SD.setExternal(true);
    325   }
    326 
    327   MCELF::SetType(SD, ELF::STT_OBJECT);
    328 
    329   if (MCELF::GetBinding(SD) == ELF_STB_Local) {
    330     const MCSection *Section = getAssembler().getContext().getELFSection(".bss",
    331                                                          ELF::SHT_NOBITS,
    332                                                          ELF::SHF_WRITE |
    333                                                          ELF::SHF_ALLOC,
    334                                                          SectionKind::getBSS());
    335     Symbol->setSection(*Section);
    336 
    337     struct LocalCommon L = {&SD, Size, ByteAlignment};
    338     LocalCommons.push_back(L);
    339   } else {
    340     SD.setCommon(Size, ByteAlignment);
    341   }
    342 
    343   SD.setSize(MCConstantExpr::Create(Size, getContext()));
    344 }
    345 
    346 void MCELFStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
    347                                           unsigned ByteAlignment) {
    348   // FIXME: Should this be caught and done earlier?
    349   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
    350   MCELF::SetBinding(SD, ELF::STB_LOCAL);
    351   SD.setExternal(false);
    352   BindingExplicitlySet.insert(Symbol);
    353   EmitCommonSymbol(Symbol, Size, ByteAlignment);
    354 }
    355 
    356 void MCELFStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
    357   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
    358   // MCObjectStreamer.
    359   getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
    360 }
    361 
    362 void MCELFStreamer::EmitValueToAlignment(unsigned ByteAlignment,
    363                                            int64_t Value, unsigned ValueSize,
    364                                            unsigned MaxBytesToEmit) {
    365   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
    366   // MCObjectStreamer.
    367   if (MaxBytesToEmit == 0)
    368     MaxBytesToEmit = ByteAlignment;
    369   new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit,
    370                       getCurrentSectionData());
    371 
    372   // Update the maximum alignment on the current section if necessary.
    373   if (ByteAlignment > getCurrentSectionData()->getAlignment())
    374     getCurrentSectionData()->setAlignment(ByteAlignment);
    375 }
    376 
    377 void MCELFStreamer::EmitCodeAlignment(unsigned ByteAlignment,
    378                                         unsigned MaxBytesToEmit) {
    379   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
    380   // MCObjectStreamer.
    381   if (MaxBytesToEmit == 0)
    382     MaxBytesToEmit = ByteAlignment;
    383   MCAlignFragment *F = new MCAlignFragment(ByteAlignment, 0, 1, MaxBytesToEmit,
    384                                            getCurrentSectionData());
    385   F->setEmitNops(true);
    386 
    387   // Update the maximum alignment on the current section if necessary.
    388   if (ByteAlignment > getCurrentSectionData()->getAlignment())
    389     getCurrentSectionData()->setAlignment(ByteAlignment);
    390 }
    391 
    392 void MCELFStreamer::EmitValueImpl(const MCExpr *Value, unsigned Size,
    393                                   unsigned AddrSpace) {
    394   fixSymbolsInTLSFixups(Value);
    395   MCObjectStreamer::EmitValueImpl(Value, Size, AddrSpace);
    396 }
    397 
    398 
    399 // Add a symbol for the file name of this module. This is the second
    400 // entry in the module's symbol table (the first being the null symbol).
    401 void MCELFStreamer::EmitFileDirective(StringRef Filename) {
    402   MCSymbol *Symbol = getAssembler().getContext().GetOrCreateSymbol(Filename);
    403   Symbol->setSection(*getCurrentSection());
    404   Symbol->setAbsolute();
    405 
    406   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
    407 
    408   SD.setFlags(ELF_STT_File | ELF_STB_Local | ELF_STV_Default);
    409 }
    410 
    411 void  MCELFStreamer::fixSymbolsInTLSFixups(const MCExpr *expr) {
    412   switch (expr->getKind()) {
    413   case MCExpr::Target: llvm_unreachable("Can't handle target exprs yet!");
    414   case MCExpr::Constant:
    415     break;
    416 
    417   case MCExpr::Binary: {
    418     const MCBinaryExpr *be = cast<MCBinaryExpr>(expr);
    419     fixSymbolsInTLSFixups(be->getLHS());
    420     fixSymbolsInTLSFixups(be->getRHS());
    421     break;
    422   }
    423 
    424   case MCExpr::SymbolRef: {
    425     const MCSymbolRefExpr &symRef = *cast<MCSymbolRefExpr>(expr);
    426     switch (symRef.getKind()) {
    427     default:
    428       return;
    429     case MCSymbolRefExpr::VK_GOTTPOFF:
    430     case MCSymbolRefExpr::VK_INDNTPOFF:
    431     case MCSymbolRefExpr::VK_NTPOFF:
    432     case MCSymbolRefExpr::VK_GOTNTPOFF:
    433     case MCSymbolRefExpr::VK_TLSGD:
    434     case MCSymbolRefExpr::VK_TLSLD:
    435     case MCSymbolRefExpr::VK_TLSLDM:
    436     case MCSymbolRefExpr::VK_TPOFF:
    437     case MCSymbolRefExpr::VK_DTPOFF:
    438     case MCSymbolRefExpr::VK_ARM_TLSGD:
    439     case MCSymbolRefExpr::VK_ARM_TPOFF:
    440     case MCSymbolRefExpr::VK_ARM_GOTTPOFF:
    441     case MCSymbolRefExpr::VK_Mips_TLSGD:
    442     case MCSymbolRefExpr::VK_Mips_GOTTPREL:
    443     case MCSymbolRefExpr::VK_Mips_TPREL_HI:
    444     case MCSymbolRefExpr::VK_Mips_TPREL_LO:
    445       break;
    446     }
    447     MCSymbolData &SD = getAssembler().getOrCreateSymbolData(symRef.getSymbol());
    448     MCELF::SetType(SD, ELF::STT_TLS);
    449     break;
    450   }
    451 
    452   case MCExpr::Unary:
    453     fixSymbolsInTLSFixups(cast<MCUnaryExpr>(expr)->getSubExpr());
    454     break;
    455   }
    456 }
    457 
    458 void MCELFStreamer::EmitInstToFragment(const MCInst &Inst) {
    459   this->MCObjectStreamer::EmitInstToFragment(Inst);
    460   MCInstFragment &F = *cast<MCInstFragment>(getCurrentFragment());
    461 
    462   for (unsigned i = 0, e = F.getFixups().size(); i != e; ++i)
    463     fixSymbolsInTLSFixups(F.getFixups()[i].getValue());
    464 }
    465 
    466 void MCELFStreamer::EmitInstToData(const MCInst &Inst) {
    467   MCDataFragment *DF = getOrCreateDataFragment();
    468 
    469   SmallVector<MCFixup, 4> Fixups;
    470   SmallString<256> Code;
    471   raw_svector_ostream VecOS(Code);
    472   getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
    473   VecOS.flush();
    474 
    475   for (unsigned i = 0, e = Fixups.size(); i != e; ++i)
    476     fixSymbolsInTLSFixups(Fixups[i].getValue());
    477 
    478   // Add the fixups and data.
    479   for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
    480     Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
    481     DF->addFixup(Fixups[i]);
    482   }
    483   DF->getContents().append(Code.begin(), Code.end());
    484 }
    485 
    486 void MCELFStreamer::FinishImpl() {
    487   EmitFrames(true);
    488 
    489   for (std::vector<LocalCommon>::const_iterator i = LocalCommons.begin(),
    490                                                 e = LocalCommons.end();
    491        i != e; ++i) {
    492     MCSymbolData *SD = i->SD;
    493     uint64_t Size = i->Size;
    494     unsigned ByteAlignment = i->ByteAlignment;
    495     const MCSymbol &Symbol = SD->getSymbol();
    496     const MCSection &Section = Symbol.getSection();
    497 
    498     MCSectionData &SectData = getAssembler().getOrCreateSectionData(Section);
    499     new MCAlignFragment(ByteAlignment, 0, 1, ByteAlignment, &SectData);
    500 
    501     MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
    502     SD->setFragment(F);
    503 
    504     // Update the maximum alignment of the section if necessary.
    505     if (ByteAlignment > SectData.getAlignment())
    506       SectData.setAlignment(ByteAlignment);
    507   }
    508 
    509   this->MCObjectStreamer::FinishImpl();
    510 }
    511 
    512 MCStreamer *llvm::createELFStreamer(MCContext &Context, MCAsmBackend &MAB,
    513                                     raw_ostream &OS, MCCodeEmitter *CE,
    514                                     bool RelaxAll, bool NoExecStack) {
    515   MCELFStreamer *S = new MCELFStreamer(Context, MAB, OS, CE);
    516   if (RelaxAll)
    517     S->getAssembler().setRelaxAll(true);
    518   if (NoExecStack)
    519     S->getAssembler().setNoExecStack(true);
    520   return S;
    521 }
    522