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