Handle strings in section names the same way as gas:
[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   if (getLexer().is(AsmToken::String)) {
172     SectionName = getTok().getIdentifier();
173     Lex();
174     return false;
175   }
176
177   for (;;) {
178     StringRef Tmp;
179     unsigned CurSize;
180
181     SMLoc PrevLoc = getLexer().getLoc();
182     if (getLexer().is(AsmToken::Minus)) {
183       CurSize = 1;
184       Lex(); // Consume the "-".
185     } else if (getLexer().is(AsmToken::String)) {
186       CurSize = getTok().getIdentifier().size() + 2;
187       Lex();
188     } else if (getLexer().is(AsmToken::Identifier)) {
189       CurSize = getTok().getIdentifier().size();
190       Lex();
191     } else {
192       break;
193     }
194
195     Size += CurSize;
196     SectionName = StringRef(FirstLoc.getPointer(), Size);
197
198     // Make sure the following token is adjacent.
199     if (PrevLoc.getPointer() + CurSize != getTok().getLoc().getPointer())
200       break;
201   }
202   if (Size == 0)
203     return true;
204
205   return false;
206 }
207
208 static SectionKind computeSectionKind(unsigned Flags) {
209   if (Flags & ELF::SHF_EXECINSTR)
210     return SectionKind::getText();
211   if (Flags & ELF::SHF_TLS)
212     return SectionKind::getThreadData();
213   return SectionKind::getDataRel();
214 }
215
216 static int parseSectionFlags(StringRef flagsStr) {
217   int flags = 0;
218
219   for (unsigned i = 0; i < flagsStr.size(); i++) {
220     switch (flagsStr[i]) {
221     case 'a':
222       flags |= ELF::SHF_ALLOC;
223       break;
224     case 'x':
225       flags |= ELF::SHF_EXECINSTR;
226       break;
227     case 'w':
228       flags |= ELF::SHF_WRITE;
229       break;
230     case 'M':
231       flags |= ELF::SHF_MERGE;
232       break;
233     case 'S':
234       flags |= ELF::SHF_STRINGS;
235       break;
236     case 'T':
237       flags |= ELF::SHF_TLS;
238       break;
239     case 'c':
240       flags |= ELF::XCORE_SHF_CP_SECTION;
241       break;
242     case 'd':
243       flags |= ELF::XCORE_SHF_DP_SECTION;
244       break;
245     case 'G':
246       flags |= ELF::SHF_GROUP;
247       break;
248     default:
249       return -1;
250     }
251   }
252
253   return flags;
254 }
255
256 // FIXME: This is a work in progress.
257 bool ELFAsmParser::ParseDirectiveSection(StringRef, SMLoc) {
258   StringRef SectionName;
259
260   if (ParseSectionName(SectionName))
261     return TokError("expected identifier in directive");
262
263   StringRef TypeName;
264   int64_t Size = 0;
265   StringRef GroupName;
266   unsigned Flags = 0;
267
268   // Set the defaults first.
269   if (SectionName == ".fini" || SectionName == ".init" ||
270       SectionName == ".rodata")
271     Flags |= ELF::SHF_ALLOC;
272   if (SectionName == ".fini" || SectionName == ".init")
273     Flags |= ELF::SHF_EXECINSTR;
274
275   if (getLexer().is(AsmToken::Comma)) {
276     Lex();
277
278     if (getLexer().isNot(AsmToken::String))
279       return TokError("expected string in directive");
280
281     StringRef FlagsStr = getTok().getStringContents();
282     Lex();
283
284     int extraFlags = parseSectionFlags(FlagsStr);
285     if (extraFlags < 0)
286       return TokError("unknown flag");
287     Flags |= extraFlags;
288
289     bool Mergeable = Flags & ELF::SHF_MERGE;
290     bool Group = Flags & ELF::SHF_GROUP;
291
292     if (getLexer().isNot(AsmToken::Comma)) {
293       if (Mergeable)
294         return TokError("Mergeable section must specify the type");
295       if (Group)
296         return TokError("Group section must specify the type");
297     } else {
298       Lex();
299       if (getLexer().isNot(AsmToken::Percent) && getLexer().isNot(AsmToken::At))
300         return TokError("expected '@' or '%' before type");
301
302       Lex();
303       if (getParser().ParseIdentifier(TypeName))
304         return TokError("expected identifier in directive");
305
306       if (Mergeable) {
307         if (getLexer().isNot(AsmToken::Comma))
308           return TokError("expected the entry size");
309         Lex();
310         if (getParser().ParseAbsoluteExpression(Size))
311           return true;
312         if (Size <= 0)
313           return TokError("entry size must be positive");
314       }
315
316       if (Group) {
317         if (getLexer().isNot(AsmToken::Comma))
318           return TokError("expected group name");
319         Lex();
320         if (getParser().ParseIdentifier(GroupName))
321           return true;
322         if (getLexer().is(AsmToken::Comma)) {
323           Lex();
324           StringRef Linkage;
325           if (getParser().ParseIdentifier(Linkage))
326             return true;
327           if (Linkage != "comdat")
328             return TokError("Linkage must be 'comdat'");
329         }
330       }
331     }
332   }
333
334   if (getLexer().isNot(AsmToken::EndOfStatement))
335     return TokError("unexpected token in directive");
336
337   unsigned Type = ELF::SHT_PROGBITS;
338
339   if (!TypeName.empty()) {
340     if (TypeName == "init_array")
341       Type = ELF::SHT_INIT_ARRAY;
342     else if (TypeName == "fini_array")
343       Type = ELF::SHT_FINI_ARRAY;
344     else if (TypeName == "preinit_array")
345       Type = ELF::SHT_PREINIT_ARRAY;
346     else if (TypeName == "nobits")
347       Type = ELF::SHT_NOBITS;
348     else if (TypeName == "progbits")
349       Type = ELF::SHT_PROGBITS;
350     else if (TypeName == "note")
351       Type = ELF::SHT_NOTE;
352     else if (TypeName == "unwind")
353       Type = ELF::SHT_X86_64_UNWIND;
354     else
355       return TokError("unknown section type");
356   }
357
358   SectionKind Kind = computeSectionKind(Flags);
359   getStreamer().SwitchSection(getContext().getELFSection(SectionName, Type,
360                                                          Flags, Kind, Size,
361                                                          GroupName));
362   return false;
363 }
364
365 bool ELFAsmParser::ParseDirectivePrevious(StringRef DirName, SMLoc) {
366   const MCSection *PreviousSection = getStreamer().getPreviousSection();
367   if (PreviousSection != NULL)
368     getStreamer().SwitchSection(PreviousSection);
369
370   return false;
371 }
372
373 /// ParseDirectiveELFType
374 ///  ::= .type identifier , @attribute
375 bool ELFAsmParser::ParseDirectiveType(StringRef, SMLoc) {
376   StringRef Name;
377   if (getParser().ParseIdentifier(Name))
378     return TokError("expected identifier in directive");
379
380   // Handle the identifier as the key symbol.
381   MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
382
383   if (getLexer().isNot(AsmToken::Comma))
384     return TokError("unexpected token in '.type' directive");
385   Lex();
386
387   if (getLexer().isNot(AsmToken::Percent) && getLexer().isNot(AsmToken::At))
388     return TokError("expected '@' or '%' before type");
389   Lex();
390
391   StringRef Type;
392   SMLoc TypeLoc;
393
394   TypeLoc = getLexer().getLoc();
395   if (getParser().ParseIdentifier(Type))
396     return TokError("expected symbol type in directive");
397
398   MCSymbolAttr Attr = StringSwitch<MCSymbolAttr>(Type)
399     .Case("function", MCSA_ELF_TypeFunction)
400     .Case("object", MCSA_ELF_TypeObject)
401     .Case("tls_object", MCSA_ELF_TypeTLS)
402     .Case("common", MCSA_ELF_TypeCommon)
403     .Case("notype", MCSA_ELF_TypeNoType)
404     .Case("gnu_unique_object", MCSA_ELF_TypeGnuUniqueObject)
405     .Default(MCSA_Invalid);
406
407   if (Attr == MCSA_Invalid)
408     return Error(TypeLoc, "unsupported attribute in '.type' directive");
409
410   if (getLexer().isNot(AsmToken::EndOfStatement))
411     return TokError("unexpected token in '.type' directive");
412
413   Lex();
414
415   getStreamer().EmitSymbolAttribute(Sym, Attr);
416
417   return false;
418 }
419
420 /// ParseDirectiveIdent
421 ///  ::= .ident string
422 bool ELFAsmParser::ParseDirectiveIdent(StringRef, SMLoc) {
423   if (getLexer().isNot(AsmToken::String))
424     return TokError("unexpected token in '.ident' directive");
425
426   StringRef Data = getTok().getIdentifier();
427
428   Lex();
429
430   const MCSection *OldSection = getStreamer().getCurrentSection();
431   const MCSection *Comment =
432     getContext().getELFSection(".comment", ELF::SHT_PROGBITS,
433                                ELF::SHF_MERGE |
434                                ELF::SHF_STRINGS,
435                                SectionKind::getReadOnly(),
436                                1, "");
437
438   static bool First = true;
439
440   getStreamer().SwitchSection(Comment);
441   if (First)
442     getStreamer().EmitIntValue(0, 1);
443   First = false;
444   getStreamer().EmitBytes(Data, 0);
445   getStreamer().EmitIntValue(0, 1);
446   getStreamer().SwitchSection(OldSection);
447   return false;
448 }
449
450 /// ParseDirectiveSymver
451 ///  ::= .symver foo, bar2@zed
452 bool ELFAsmParser::ParseDirectiveSymver(StringRef, SMLoc) {
453   StringRef Name;
454   if (getParser().ParseIdentifier(Name))
455     return TokError("expected identifier in directive");
456
457   if (getLexer().isNot(AsmToken::Comma))
458     return TokError("expected a comma");
459
460   Lex();
461
462   StringRef AliasName;
463   if (getParser().ParseIdentifier(AliasName))
464     return TokError("expected identifier in directive");
465
466   if (AliasName.find('@') == StringRef::npos)
467     return TokError("expected a '@' in the name");
468
469   MCSymbol *Alias = getContext().GetOrCreateSymbol(AliasName);
470   MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
471   const MCExpr *Value = MCSymbolRefExpr::Create(Sym, getContext());
472
473   getStreamer().EmitAssignment(Alias, Value);
474   return false;
475 }
476
477 /// ParseDirectiveWeakref
478 ///  ::= .weakref foo, bar
479 bool ELFAsmParser::ParseDirectiveWeakref(StringRef, SMLoc) {
480   // FIXME: Share code with the other alias building directives.
481
482   StringRef AliasName;
483   if (getParser().ParseIdentifier(AliasName))
484     return TokError("expected identifier in directive");
485
486   if (getLexer().isNot(AsmToken::Comma))
487     return TokError("expected a comma");
488
489   Lex();
490
491   StringRef Name;
492   if (getParser().ParseIdentifier(Name))
493     return TokError("expected identifier in directive");
494
495   MCSymbol *Alias = getContext().GetOrCreateSymbol(AliasName);
496
497   MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
498
499   getStreamer().EmitWeakReference(Alias, Sym);
500   return false;
501 }
502
503 namespace llvm {
504
505 MCAsmParserExtension *createELFAsmParser() {
506   return new ELFAsmParser;
507 }
508
509 }