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 "MCELFStreamer.h"
     15 #include "MCELF.h"
     16 #include "llvm/MC/MCStreamer.h"
     17 #include "llvm/MC/MCCodeEmitter.h"
     18 #include "llvm/MC/MCELFSymbolFlags.h"
     19 #include "llvm/MC/MCExpr.h"
     20 #include "llvm/MC/MCInst.h"
     21 #include "llvm/MC/MCSection.h"
     22 #include "llvm/MC/MCSymbol.h"
     23 #include "llvm/MC/MCValue.h"
     24 #include "llvm/MC/MCAsmBackend.h"
     25 #include "llvm/Support/Debug.h"
     26 #include "llvm/Support/ELF.h"
     27 #include "llvm/Support/ErrorHandling.h"
     28 #include "llvm/Support/raw_ostream.h"
     29 
     30 using namespace llvm;
     31 
     32 void MCELFStreamer::InitSections() {
     33   // This emulates the same behavior of GNU as. This makes it easier
     34   // to compare the output as the major sections are in the same order.
     35   SetSectionText();
     36   SetSectionData();
     37   SetSectionBss();
     38   SetSectionText();
     39 }
     40 
     41 void MCELFStreamer::EmitLabel(MCSymbol *Symbol) {
     42   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
     43 
     44   MCObjectStreamer::EmitLabel(Symbol);
     45 
     46   const MCSectionELF &Section =
     47     static_cast<const MCSectionELF&>(Symbol->getSection());
     48   MCSymbolData &SD = getAssembler().getSymbolData(*Symbol);
     49   if (Section.getFlags() & ELF::SHF_TLS)
     50     MCELF::SetType(SD, ELF::STT_TLS);
     51 }
     52 
     53 void MCELFStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
     54   switch (Flag) {
     55   case MCAF_SyntaxUnified: return; // no-op here.
     56   case MCAF_Code16: return; // Change parsing mode; no-op here.
     57   case MCAF_Code32: return; // Change parsing mode; no-op here.
     58   case MCAF_Code64: return; // Change parsing mode; no-op here.
     59   case MCAF_SubsectionsViaSymbols:
     60     getAssembler().setSubsectionsViaSymbols(true);
     61     return;
     62   }
     63 
     64   assert(0 && "invalid assembler flag!");
     65 }
     66 
     67 void MCELFStreamer::EmitThumbFunc(MCSymbol *Func) {
     68   // FIXME: Anything needed here to flag the function as thumb?
     69 
     70   getAssembler().setIsThumbFunc(Func);
     71 
     72   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Func);
     73   SD.setFlags(SD.getFlags() | ELF_Other_ThumbFunc);
     74 }
     75 
     76 void MCELFStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
     77   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
     78   // MCObjectStreamer.
     79   // FIXME: Lift context changes into super class.
     80   getAssembler().getOrCreateSymbolData(*Symbol);
     81   Symbol->setVariableValue(AddValueSymbols(Value));
     82 }
     83 
     84 void MCELFStreamer::ChangeSection(const MCSection *Section) {
     85   const MCSymbol *Grp = static_cast<const MCSectionELF *>(Section)->getGroup();
     86   if (Grp)
     87     getAssembler().getOrCreateSymbolData(*Grp);
     88   this->MCObjectStreamer::ChangeSection(Section);
     89 }
     90 
     91 void MCELFStreamer::EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) {
     92   getAssembler().getOrCreateSymbolData(*Symbol);
     93   MCSymbolData &AliasSD = getAssembler().getOrCreateSymbolData(*Alias);
     94   AliasSD.setFlags(AliasSD.getFlags() | ELF_Other_Weakref);
     95   const MCExpr *Value = MCSymbolRefExpr::Create(Symbol, getContext());
     96   Alias->setVariableValue(Value);
     97 }
     98 
     99 void MCELFStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
    100                                           MCSymbolAttr Attribute) {
    101   // Indirect symbols are handled differently, to match how 'as' handles
    102   // them. This makes writing matching .o files easier.
    103   if (Attribute == MCSA_IndirectSymbol) {
    104     // Note that we intentionally cannot use the symbol data here; this is
    105     // important for matching the string table that 'as' generates.
    106     IndirectSymbolData ISD;
    107     ISD.Symbol = Symbol;
    108     ISD.SectionData = getCurrentSectionData();
    109     getAssembler().getIndirectSymbols().push_back(ISD);
    110     return;
    111   }
    112 
    113   // Adding a symbol attribute always introduces the symbol, note that an
    114   // important side effect of calling getOrCreateSymbolData here is to register
    115   // the symbol with the assembler.
    116   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
    117 
    118   // The implementation of symbol attributes is designed to match 'as', but it
    119   // leaves much to desired. It doesn't really make sense to arbitrarily add and
    120   // remove flags, but 'as' allows this (in particular, see .desc).
    121   //
    122   // In the future it might be worth trying to make these operations more well
    123   // defined.
    124   switch (Attribute) {
    125   case MCSA_LazyReference:
    126   case MCSA_Reference:
    127   case MCSA_NoDeadStrip:
    128   case MCSA_SymbolResolver:
    129   case MCSA_PrivateExtern:
    130   case MCSA_WeakDefinition:
    131   case MCSA_WeakDefAutoPrivate:
    132   case MCSA_Invalid:
    133   case MCSA_ELF_TypeIndFunction:
    134   case MCSA_IndirectSymbol:
    135     assert(0 && "Invalid symbol attribute for ELF!");
    136     break;
    137 
    138   case MCSA_ELF_TypeGnuUniqueObject:
    139     // Ignore for now.
    140     break;
    141 
    142   case MCSA_Global:
    143     MCELF::SetBinding(SD, ELF::STB_GLOBAL);
    144     SD.setExternal(true);
    145     BindingExplicitlySet.insert(Symbol);
    146     break;
    147 
    148   case MCSA_WeakReference:
    149   case MCSA_Weak:
    150     MCELF::SetBinding(SD, ELF::STB_WEAK);
    151     SD.setExternal(true);
    152     BindingExplicitlySet.insert(Symbol);
    153     break;
    154 
    155   case MCSA_Local:
    156     MCELF::SetBinding(SD, ELF::STB_LOCAL);
    157     SD.setExternal(false);
    158     BindingExplicitlySet.insert(Symbol);
    159     break;
    160 
    161   case MCSA_ELF_TypeFunction:
    162     MCELF::SetType(SD, ELF::STT_FUNC);
    163     break;
    164 
    165   case MCSA_ELF_TypeObject:
    166     MCELF::SetType(SD, ELF::STT_OBJECT);
    167     break;
    168 
    169   case MCSA_ELF_TypeTLS:
    170     MCELF::SetType(SD, ELF::STT_TLS);
    171     break;
    172 
    173   case MCSA_ELF_TypeCommon:
    174     MCELF::SetType(SD, ELF::STT_COMMON);
    175     break;
    176 
    177   case MCSA_ELF_TypeNoType:
    178     MCELF::SetType(SD, ELF::STT_NOTYPE);
    179     break;
    180 
    181   case MCSA_Protected:
    182     MCELF::SetVisibility(SD, ELF::STV_PROTECTED);
    183     break;
    184 
    185   case MCSA_Hidden:
    186     MCELF::SetVisibility(SD, ELF::STV_HIDDEN);
    187     break;
    188 
    189   case MCSA_Internal:
    190     MCELF::SetVisibility(SD, ELF::STV_INTERNAL);
    191     break;
    192   }
    193 }
    194 
    195 void MCELFStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
    196                                        unsigned ByteAlignment) {
    197   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
    198 
    199   if (!BindingExplicitlySet.count(Symbol)) {
    200     MCELF::SetBinding(SD, ELF::STB_GLOBAL);
    201     SD.setExternal(true);
    202   }
    203 
    204   MCELF::SetType(SD, ELF::STT_OBJECT);
    205 
    206   if (MCELF::GetBinding(SD) == ELF_STB_Local) {
    207     const MCSection *Section = getAssembler().getContext().getELFSection(".bss",
    208                                                                     ELF::SHT_NOBITS,
    209                                                                     ELF::SHF_WRITE |
    210                                                                     ELF::SHF_ALLOC,
    211                                                                     SectionKind::getBSS());
    212     Symbol->setSection(*Section);
    213 
    214     struct LocalCommon L = {&SD, Size, ByteAlignment};
    215     LocalCommons.push_back(L);
    216   } else {
    217     SD.setCommon(Size, ByteAlignment);
    218   }
    219 
    220   SD.setSize(MCConstantExpr::Create(Size, getContext()));
    221 }
    222 
    223 void MCELFStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
    224                                           unsigned ByteAlignment) {
    225   // FIXME: Should this be caught and done earlier?
    226   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
    227   MCELF::SetBinding(SD, ELF::STB_LOCAL);
    228   SD.setExternal(false);
    229   BindingExplicitlySet.insert(Symbol);
    230   EmitCommonSymbol(Symbol, Size, ByteAlignment);
    231 }
    232 
    233 void MCELFStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
    234   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
    235   // MCObjectStreamer.
    236   getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
    237 }
    238 
    239 void MCELFStreamer::EmitValueToAlignment(unsigned ByteAlignment,
    240                                            int64_t Value, unsigned ValueSize,
    241                                            unsigned MaxBytesToEmit) {
    242   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
    243   // MCObjectStreamer.
    244   if (MaxBytesToEmit == 0)
    245     MaxBytesToEmit = ByteAlignment;
    246   new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit,
    247                       getCurrentSectionData());
    248 
    249   // Update the maximum alignment on the current section if necessary.
    250   if (ByteAlignment > getCurrentSectionData()->getAlignment())
    251     getCurrentSectionData()->setAlignment(ByteAlignment);
    252 }
    253 
    254 void MCELFStreamer::EmitCodeAlignment(unsigned ByteAlignment,
    255                                         unsigned MaxBytesToEmit) {
    256   // TODO: This is exactly the same as WinCOFFStreamer. Consider merging into
    257   // MCObjectStreamer.
    258   if (MaxBytesToEmit == 0)
    259     MaxBytesToEmit = ByteAlignment;
    260   MCAlignFragment *F = new MCAlignFragment(ByteAlignment, 0, 1, MaxBytesToEmit,
    261                                            getCurrentSectionData());
    262   F->setEmitNops(true);
    263 
    264   // Update the maximum alignment on the current section if necessary.
    265   if (ByteAlignment > getCurrentSectionData()->getAlignment())
    266     getCurrentSectionData()->setAlignment(ByteAlignment);
    267 }
    268 
    269 // Add a symbol for the file name of this module. This is the second
    270 // entry in the module's symbol table (the first being the null symbol).
    271 void MCELFStreamer::EmitFileDirective(StringRef Filename) {
    272   MCSymbol *Symbol = getAssembler().getContext().GetOrCreateSymbol(Filename);
    273   Symbol->setSection(*getCurrentSection());
    274   Symbol->setAbsolute();
    275 
    276   MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
    277 
    278   SD.setFlags(ELF_STT_File | ELF_STB_Local | ELF_STV_Default);
    279 }
    280 
    281 void  MCELFStreamer::fixSymbolsInTLSFixups(const MCExpr *expr) {
    282   switch (expr->getKind()) {
    283   case MCExpr::Target: llvm_unreachable("Can't handle target exprs yet!");
    284   case MCExpr::Constant:
    285     break;
    286 
    287   case MCExpr::Binary: {
    288     const MCBinaryExpr *be = cast<MCBinaryExpr>(expr);
    289     fixSymbolsInTLSFixups(be->getLHS());
    290     fixSymbolsInTLSFixups(be->getRHS());
    291     break;
    292   }
    293 
    294   case MCExpr::SymbolRef: {
    295     const MCSymbolRefExpr &symRef = *cast<MCSymbolRefExpr>(expr);
    296     switch (symRef.getKind()) {
    297     default:
    298       return;
    299     case MCSymbolRefExpr::VK_GOTTPOFF:
    300     case MCSymbolRefExpr::VK_INDNTPOFF:
    301     case MCSymbolRefExpr::VK_NTPOFF:
    302     case MCSymbolRefExpr::VK_GOTNTPOFF:
    303     case MCSymbolRefExpr::VK_TLSGD:
    304     case MCSymbolRefExpr::VK_TLSLD:
    305     case MCSymbolRefExpr::VK_TLSLDM:
    306     case MCSymbolRefExpr::VK_TPOFF:
    307     case MCSymbolRefExpr::VK_DTPOFF:
    308     case MCSymbolRefExpr::VK_ARM_TLSGD:
    309     case MCSymbolRefExpr::VK_ARM_TPOFF:
    310     case MCSymbolRefExpr::VK_ARM_GOTTPOFF:
    311       break;
    312     }
    313     MCSymbolData &SD = getAssembler().getOrCreateSymbolData(symRef.getSymbol());
    314     MCELF::SetType(SD, ELF::STT_TLS);
    315     break;
    316   }
    317 
    318   case MCExpr::Unary:
    319     fixSymbolsInTLSFixups(cast<MCUnaryExpr>(expr)->getSubExpr());
    320     break;
    321   }
    322 }
    323 
    324 void MCELFStreamer::EmitInstToFragment(const MCInst &Inst) {
    325   this->MCObjectStreamer::EmitInstToFragment(Inst);
    326   MCInstFragment &F = *cast<MCInstFragment>(getCurrentFragment());
    327 
    328   for (unsigned i = 0, e = F.getFixups().size(); i != e; ++i)
    329     fixSymbolsInTLSFixups(F.getFixups()[i].getValue());
    330 }
    331 
    332 void MCELFStreamer::EmitInstToData(const MCInst &Inst) {
    333   MCDataFragment *DF = getOrCreateDataFragment();
    334 
    335   SmallVector<MCFixup, 4> Fixups;
    336   SmallString<256> Code;
    337   raw_svector_ostream VecOS(Code);
    338   getAssembler().getEmitter().EncodeInstruction(Inst, VecOS, Fixups);
    339   VecOS.flush();
    340 
    341   for (unsigned i = 0, e = Fixups.size(); i != e; ++i)
    342     fixSymbolsInTLSFixups(Fixups[i].getValue());
    343 
    344   // Add the fixups and data.
    345   for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
    346     Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
    347     DF->addFixup(Fixups[i]);
    348   }
    349   DF->getContents().append(Code.begin(), Code.end());
    350 }
    351 
    352 void MCELFStreamer::Finish() {
    353   EmitFrames(true);
    354 
    355   for (std::vector<LocalCommon>::const_iterator i = LocalCommons.begin(),
    356                                                 e = LocalCommons.end();
    357        i != e; ++i) {
    358     MCSymbolData *SD = i->SD;
    359     uint64_t Size = i->Size;
    360     unsigned ByteAlignment = i->ByteAlignment;
    361     const MCSymbol &Symbol = SD->getSymbol();
    362     const MCSection &Section = Symbol.getSection();
    363 
    364     MCSectionData &SectData = getAssembler().getOrCreateSectionData(Section);
    365     new MCAlignFragment(ByteAlignment, 0, 1, ByteAlignment, &SectData);
    366 
    367     MCFragment *F = new MCFillFragment(0, 0, Size, &SectData);
    368     SD->setFragment(F);
    369 
    370     // Update the maximum alignment of the section if necessary.
    371     if (ByteAlignment > SectData.getAlignment())
    372       SectData.setAlignment(ByteAlignment);
    373   }
    374 
    375   this->MCObjectStreamer::Finish();
    376 }
    377 
    378 MCStreamer *llvm::createELFStreamer(MCContext &Context, MCAsmBackend &MAB,
    379                                     raw_ostream &OS, MCCodeEmitter *CE,
    380                                     bool RelaxAll, bool NoExecStack) {
    381   MCELFStreamer *S = new MCELFStreamer(Context, MAB, OS, CE);
    382   if (RelaxAll)
    383     S->getAssembler().setRelaxAll(true);
    384   if (NoExecStack)
    385     S->getAssembler().setNoExecStack(true);
    386   return S;
    387 }
    388