Delay the creation of eh_frame so that the user can change the defaults.
[oota-llvm.git] / lib / MC / MCParser / ELFAsmParser.cpp
1 //===- ELFAsmParser.cpp - ELF Assembly Parser -----------------------------===//
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 #include "llvm/MC/MCParser/MCAsmParserExtension.h"
11 #include "llvm/ADT/StringSwitch.h"
12 #include "llvm/ADT/Twine.h"
13 #include "llvm/MC/MCAsmInfo.h"
14 #include "llvm/MC/MCContext.h"
15 #include "llvm/MC/MCExpr.h"
16 #include "llvm/MC/MCParser/MCAsmLexer.h"
17 #include "llvm/MC/MCSectionELF.h"
18 #include "llvm/MC/MCStreamer.h"
19 #include "llvm/Support/ELF.h"
20 using namespace llvm;
21
22 namespace {
23
24 class ELFAsmParser : public MCAsmParserExtension {
25   template<bool (ELFAsmParser::*Handler)(StringRef, SMLoc)>
26   void AddDirectiveHandler(StringRef Directive) {
27     getParser().AddDirectiveHandler(this, Directive,
28                                     HandleDirective<ELFAsmParser, Handler>);
29   }
30
31   bool ParseSectionSwitch(StringRef Section, unsigned Type,
32                           unsigned Flags, SectionKind Kind);
33
34 public:
35   ELFAsmParser() {}
36
37   virtual void Initialize(MCAsmParser &Parser) {
38     // Call the base implementation.
39     this->MCAsmParserExtension::Initialize(Parser);
40
41     AddDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveData>(".data");
42     AddDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveText>(".text");
43     AddDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveBSS>(".bss");
44     AddDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveRoData>(".rodata");
45     AddDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveTData>(".tdata");
46     AddDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveTBSS>(".tbss");
47     AddDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveDataRel>(".data.rel");
48     AddDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveDataRelRo>(".data.rel.ro");
49     AddDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveDataRelRoLocal>(".data.rel.ro.local");
50     AddDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveEhFrame>(".eh_frame");
51     AddDirectiveHandler<&ELFAsmParser::ParseDirectiveSection>(".section");
52     AddDirectiveHandler<&ELFAsmParser::ParseDirectiveSize>(".size");
53     AddDirectiveHandler<&ELFAsmParser::ParseDirectivePrevious>(".previous");
54     AddDirectiveHandler<&ELFAsmParser::ParseDirectiveType>(".type");
55     AddDirectiveHandler<&ELFAsmParser::ParseDirectiveIdent>(".ident");
56     AddDirectiveHandler<&ELFAsmParser::ParseDirectiveSymver>(".symver");
57     AddDirectiveHandler<&ELFAsmParser::ParseDirectiveWeakref>(".weakref");
58   }
59
60   // FIXME: Part of this logic is duplicated in the MCELFStreamer. What is
61   // the best way for us to get access to it?
62   bool ParseSectionDirectiveData(StringRef, SMLoc) {
63     return ParseSectionSwitch(".data", ELF::SHT_PROGBITS,
64                               ELF::SHF_WRITE |ELF::SHF_ALLOC,
65                               SectionKind::getDataRel());
66   }
67   bool ParseSectionDirectiveText(StringRef, SMLoc) {
68     return ParseSectionSwitch(".text", ELF::SHT_PROGBITS,
69                               ELF::SHF_EXECINSTR |
70                               ELF::SHF_ALLOC, SectionKind::getText());
71   }
72   bool ParseSectionDirectiveBSS(StringRef, SMLoc) {
73     return ParseSectionSwitch(".bss", ELF::SHT_NOBITS,
74                               ELF::SHF_WRITE |
75                               ELF::SHF_ALLOC, SectionKind::getBSS());
76   }
77   bool ParseSectionDirectiveRoData(StringRef, SMLoc) {
78     return ParseSectionSwitch(".rodata", ELF::SHT_PROGBITS,
79                               ELF::SHF_ALLOC,
80                               SectionKind::getReadOnly());
81   }
82   bool ParseSectionDirectiveTData(StringRef, SMLoc) {
83     return ParseSectionSwitch(".tdata", ELF::SHT_PROGBITS,
84                               ELF::SHF_ALLOC |
85                               ELF::SHF_TLS | ELF::SHF_WRITE,
86                               SectionKind::getThreadData());
87   }
88   bool ParseSectionDirectiveTBSS(StringRef, SMLoc) {
89     return ParseSectionSwitch(".tbss", ELF::SHT_NOBITS,
90                               ELF::SHF_ALLOC |
91                               ELF::SHF_TLS | ELF::SHF_WRITE,
92                               SectionKind::getThreadBSS());
93   }
94   bool ParseSectionDirectiveDataRel(StringRef, SMLoc) {
95     return ParseSectionSwitch(".data.rel", ELF::SHT_PROGBITS,
96                               ELF::SHF_ALLOC |
97                               ELF::SHF_WRITE,
98                               SectionKind::getDataRel());
99   }
100   bool ParseSectionDirectiveDataRelRo(StringRef, SMLoc) {
101     return ParseSectionSwitch(".data.rel.ro", ELF::SHT_PROGBITS,
102                               ELF::SHF_ALLOC |
103                               ELF::SHF_WRITE,
104                               SectionKind::getReadOnlyWithRel());
105   }
106   bool ParseSectionDirectiveDataRelRoLocal(StringRef, SMLoc) {
107     return ParseSectionSwitch(".data.rel.ro.local", ELF::SHT_PROGBITS,
108                               ELF::SHF_ALLOC |
109                               ELF::SHF_WRITE,
110                               SectionKind::getReadOnlyWithRelLocal());
111   }
112   bool ParseSectionDirectiveEhFrame(StringRef, SMLoc) {
113     return ParseSectionSwitch(".eh_frame", ELF::SHT_PROGBITS,
114                               ELF::SHF_ALLOC |
115                               ELF::SHF_WRITE,
116                               SectionKind::getDataRel());
117   }
118   bool ParseDirectiveSection(StringRef, SMLoc);
119   bool ParseDirectiveSize(StringRef, SMLoc);
120   bool ParseDirectivePrevious(StringRef, SMLoc);
121   bool ParseDirectiveType(StringRef, SMLoc);
122   bool ParseDirectiveIdent(StringRef, SMLoc);
123   bool ParseDirectiveSymver(StringRef, SMLoc);
124   bool ParseDirectiveWeakref(StringRef, SMLoc);
125
126 private:
127   bool ParseSectionName(StringRef &SectionName);
128 };
129
130 }
131
132 bool ELFAsmParser::ParseSectionSwitch(StringRef Section, unsigned Type,
133                                       unsigned Flags, SectionKind Kind) {
134   if (getLexer().isNot(AsmToken::EndOfStatement))
135     return TokError("unexpected token in section switching directive");
136   Lex();
137
138   getStreamer().SwitchSection(getContext().getELFSection(
139                                 Section, Type, Flags, Kind));
140
141   return false;
142 }
143
144 bool ELFAsmParser::ParseDirectiveSize(StringRef, SMLoc) {
145   StringRef Name;
146   if (getParser().ParseIdentifier(Name))
147     return TokError("expected identifier in directive");
148   MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);;
149
150   if (getLexer().isNot(AsmToken::Comma))
151     return TokError("unexpected token in directive");
152   Lex();
153
154   const MCExpr *Expr;
155   if (getParser().ParseExpression(Expr))
156     return true;
157
158   if (getLexer().isNot(AsmToken::EndOfStatement))
159     return TokError("unexpected token in directive");
160
161   getStreamer().EmitELFSize(Sym, Expr);
162   return false;
163 }
164
165 bool ELFAsmParser::ParseSectionName(StringRef &SectionName) {
166   // A section name can contain -, so we cannot just use
167   // ParseIdentifier.
168   SMLoc FirstLoc = getLexer().getLoc();
169   unsigned Size = 0;
170
171   for (;;) {
172     StringRef Tmp;
173     unsigned CurSize;
174
175     SMLoc PrevLoc = getLexer().getLoc();
176     if (getLexer().is(AsmToken::Minus)) {
177       CurSize = 1;
178       Lex(); // Consume the "-".
179     } else if (!getParser().ParseIdentifier(Tmp))
180       CurSize = Tmp.size();
181     else
182       break;
183
184     Size += CurSize;
185     SectionName = StringRef(FirstLoc.getPointer(), Size);
186
187     // Make sure the following token is adjacent.
188     if (PrevLoc.getPointer() + CurSize != getTok().getLoc().getPointer())
189       break;
190   }
191   if (Size == 0)
192     return true;
193
194   return false;
195 }
196
197 static SectionKind computeSectionKind(unsigned Flags) {
198   if (Flags & ELF::SHF_EXECINSTR)
199     return SectionKind::getText();
200   if (Flags & ELF::SHF_TLS)
201     return SectionKind::getThreadData();
202   return SectionKind::getDataRel();
203 }
204
205 static int parseSectionFlags(StringRef flagsStr) {
206   int flags = 0;
207
208   for (unsigned i = 0; i < flagsStr.size(); i++) {
209     switch (flagsStr[i]) {
210     case 'a':
211       flags |= ELF::SHF_ALLOC;
212       break;
213     case 'x':
214       flags |= ELF::SHF_EXECINSTR;
215       break;
216     case 'w':
217       flags |= ELF::SHF_WRITE;
218       break;
219     case 'M':
220       flags |= ELF::SHF_MERGE;
221       break;
222     case 'S':
223       flags |= ELF::SHF_STRINGS;
224       break;
225     case 'T':
226       flags |= ELF::SHF_TLS;
227       break;
228     case 'c':
229       flags |= ELF::XCORE_SHF_CP_SECTION;
230       break;
231     case 'd':
232       flags |= ELF::XCORE_SHF_DP_SECTION;
233       break;
234     case 'G':
235       flags |= ELF::SHF_GROUP;
236       break;
237     default:
238       return -1;
239     }
240   }
241
242   return flags;
243 }
244
245 // FIXME: This is a work in progress.
246 bool ELFAsmParser::ParseDirectiveSection(StringRef, SMLoc) {
247   StringRef SectionName;
248
249   if (ParseSectionName(SectionName))
250     return TokError("expected identifier in directive");
251
252   StringRef TypeName;
253   int64_t Size = 0;
254   StringRef GroupName;
255   unsigned Flags = 0;
256
257   // Set the defaults first.
258   if (SectionName == ".fini" || SectionName == ".init" ||
259       SectionName == ".rodata")
260     Flags |= ELF::SHF_ALLOC;
261   if (SectionName == ".fini" || SectionName == ".init")
262     Flags |= ELF::SHF_EXECINSTR;
263
264   if (getLexer().is(AsmToken::Comma)) {
265     Lex();
266
267     if (getLexer().isNot(AsmToken::String))
268       return TokError("expected string in directive");
269
270     StringRef FlagsStr = getTok().getStringContents();
271     Lex();
272
273     int extraFlags = parseSectionFlags(FlagsStr);
274     if (extraFlags < 0)
275       return TokError("unknown flag");
276     Flags |= extraFlags;
277
278     bool Mergeable = Flags & ELF::SHF_MERGE;
279     bool Group = Flags & ELF::SHF_GROUP;
280
281     if (getLexer().isNot(AsmToken::Comma)) {
282       if (Mergeable)
283         return TokError("Mergeable section must specify the type");
284       if (Group)
285         return TokError("Group section must specify the type");
286     } else {
287       Lex();
288       if (getLexer().isNot(AsmToken::Percent) && getLexer().isNot(AsmToken::At))
289         return TokError("expected '@' or '%' before type");
290
291       Lex();
292       if (getParser().ParseIdentifier(TypeName))
293         return TokError("expected identifier in directive");
294
295       if (Mergeable) {
296         if (getLexer().isNot(AsmToken::Comma))
297           return TokError("expected the entry size");
298         Lex();
299         if (getParser().ParseAbsoluteExpression(Size))
300           return true;
301         if (Size <= 0)
302           return TokError("entry size must be positive");
303       }
304
305       if (Group) {
306         if (getLexer().isNot(AsmToken::Comma))
307           return TokError("expected group name");
308         Lex();
309         if (getParser().ParseIdentifier(GroupName))
310           return true;
311         if (getLexer().is(AsmToken::Comma)) {
312           Lex();
313           StringRef Linkage;
314           if (getParser().ParseIdentifier(Linkage))
315             return true;
316           if (Linkage != "comdat")
317             return TokError("Linkage must be 'comdat'");
318         }
319       }
320     }
321   }
322
323   if (getLexer().isNot(AsmToken::EndOfStatement))
324     return TokError("unexpected token in directive");
325
326   unsigned Type = ELF::SHT_PROGBITS;
327
328   if (!TypeName.empty()) {
329     if (TypeName == "init_array")
330       Type = ELF::SHT_INIT_ARRAY;
331     else if (TypeName == "fini_array")
332       Type = ELF::SHT_FINI_ARRAY;
333     else if (TypeName == "preinit_array")
334       Type = ELF::SHT_PREINIT_ARRAY;
335     else if (TypeName == "nobits")
336       Type = ELF::SHT_NOBITS;
337     else if (TypeName == "progbits")
338       Type = ELF::SHT_PROGBITS;
339     else if (TypeName == "note")
340       Type = ELF::SHT_NOTE;
341     else if (TypeName == "unwind")
342       Type = ELF::SHT_X86_64_UNWIND;
343     else
344       return TokError("unknown section type");
345   }
346
347   SectionKind Kind = computeSectionKind(Flags);
348   getStreamer().SwitchSection(getContext().getELFSection(SectionName, Type,
349                                                          Flags, Kind, Size,
350                                                          GroupName));
351   return false;
352 }
353
354 bool ELFAsmParser::ParseDirectivePrevious(StringRef DirName, SMLoc) {
355   const MCSection *PreviousSection = getStreamer().getPreviousSection();
356   if (PreviousSection != NULL)
357     getStreamer().SwitchSection(PreviousSection);
358
359   return false;
360 }
361
362 /// ParseDirectiveELFType
363 ///  ::= .type identifier , @attribute
364 bool ELFAsmParser::ParseDirectiveType(StringRef, SMLoc) {
365   StringRef Name;
366   if (getParser().ParseIdentifier(Name))
367     return TokError("expected identifier in directive");
368
369   // Handle the identifier as the key symbol.
370   MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
371
372   if (getLexer().isNot(AsmToken::Comma))
373     return TokError("unexpected token in '.type' directive");
374   Lex();
375
376   if (getLexer().isNot(AsmToken::Percent) && getLexer().isNot(AsmToken::At))
377     return TokError("expected '@' or '%' before type");
378   Lex();
379
380   StringRef Type;
381   SMLoc TypeLoc;
382
383   TypeLoc = getLexer().getLoc();
384   if (getParser().ParseIdentifier(Type))
385     return TokError("expected symbol type in directive");
386
387   MCSymbolAttr Attr = StringSwitch<MCSymbolAttr>(Type)
388     .Case("function", MCSA_ELF_TypeFunction)
389     .Case("object", MCSA_ELF_TypeObject)
390     .Case("tls_object", MCSA_ELF_TypeTLS)
391     .Case("common", MCSA_ELF_TypeCommon)
392     .Case("notype", MCSA_ELF_TypeNoType)
393     .Case("gnu_unique_object", MCSA_ELF_TypeGnuUniqueObject)
394     .Default(MCSA_Invalid);
395
396   if (Attr == MCSA_Invalid)
397     return Error(TypeLoc, "unsupported attribute in '.type' directive");
398
399   if (getLexer().isNot(AsmToken::EndOfStatement))
400     return TokError("unexpected token in '.type' directive");
401
402   Lex();
403
404   getStreamer().EmitSymbolAttribute(Sym, Attr);
405
406   return false;
407 }
408
409 /// ParseDirectiveIdent
410 ///  ::= .ident string
411 bool ELFAsmParser::ParseDirectiveIdent(StringRef, SMLoc) {
412   if (getLexer().isNot(AsmToken::String))
413     return TokError("unexpected token in '.ident' directive");
414
415   StringRef Data = getTok().getIdentifier();
416
417   Lex();
418
419   const MCSection *OldSection = getStreamer().getCurrentSection();
420   const MCSection *Comment =
421     getContext().getELFSection(".comment", ELF::SHT_PROGBITS,
422                                ELF::SHF_MERGE |
423                                ELF::SHF_STRINGS,
424                                SectionKind::getReadOnly(),
425                                1, "");
426
427   static bool First = true;
428
429   getStreamer().SwitchSection(Comment);
430   if (First)
431     getStreamer().EmitIntValue(0, 1);
432   First = false;
433   getStreamer().EmitBytes(Data, 0);
434   getStreamer().EmitIntValue(0, 1);
435   getStreamer().SwitchSection(OldSection);
436   return false;
437 }
438
439 /// ParseDirectiveSymver
440 ///  ::= .symver foo, bar2@zed
441 bool ELFAsmParser::ParseDirectiveSymver(StringRef, SMLoc) {
442   StringRef Name;
443   if (getParser().ParseIdentifier(Name))
444     return TokError("expected identifier in directive");
445
446   if (getLexer().isNot(AsmToken::Comma))
447     return TokError("expected a comma");
448
449   Lex();
450
451   StringRef AliasName;
452   if (getParser().ParseIdentifier(AliasName))
453     return TokError("expected identifier in directive");
454
455   if (AliasName.find('@') == StringRef::npos)
456     return TokError("expected a '@' in the name");
457
458   MCSymbol *Alias = getContext().GetOrCreateSymbol(AliasName);
459   MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
460   const MCExpr *Value = MCSymbolRefExpr::Create(Sym, getContext());
461
462   getStreamer().EmitAssignment(Alias, Value);
463   return false;
464 }
465
466 /// ParseDirectiveWeakref
467 ///  ::= .weakref foo, bar
468 bool ELFAsmParser::ParseDirectiveWeakref(StringRef, SMLoc) {
469   // FIXME: Share code with the other alias building directives.
470
471   StringRef AliasName;
472   if (getParser().ParseIdentifier(AliasName))
473     return TokError("expected identifier in directive");
474
475   if (getLexer().isNot(AsmToken::Comma))
476     return TokError("expected a comma");
477
478   Lex();
479
480   StringRef Name;
481   if (getParser().ParseIdentifier(Name))
482     return TokError("expected identifier in directive");
483
484   MCSymbol *Alias = getContext().GetOrCreateSymbol(AliasName);
485
486   MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
487
488   getStreamer().EmitWeakReference(Alias, Sym);
489   return false;
490 }
491
492 namespace llvm {
493
494 MCAsmParserExtension *createELFAsmParser() {
495   return new ELFAsmParser;
496 }
497
498 }