1 //===- ELFAsmParser.cpp - ELF Assembly Parser -----------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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/MC/MCSymbol.h"
20 #include "llvm/Support/ELF.h"
25 class ELFAsmParser : public MCAsmParserExtension {
26 template<bool (ELFAsmParser::*HandlerMethod)(StringRef, SMLoc)>
27 void addDirectiveHandler(StringRef Directive) {
28 MCAsmParser::ExtensionDirectiveHandler Handler = std::make_pair(
29 this, HandleDirective<ELFAsmParser, HandlerMethod>);
31 getParser().addDirectiveHandler(Directive, Handler);
34 bool ParseSectionSwitch(StringRef Section, unsigned Type, unsigned Flags,
38 ELFAsmParser() { BracketExpressionsSupported = true; }
40 virtual void Initialize(MCAsmParser &Parser) {
41 // Call the base implementation.
42 this->MCAsmParserExtension::Initialize(Parser);
44 addDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveData>(".data");
45 addDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveText>(".text");
46 addDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveBSS>(".bss");
47 addDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveRoData>(".rodata");
48 addDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveTData>(".tdata");
49 addDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveTBSS>(".tbss");
51 &ELFAsmParser::ParseSectionDirectiveDataRel>(".data.rel");
53 &ELFAsmParser::ParseSectionDirectiveDataRelRo>(".data.rel.ro");
55 &ELFAsmParser::ParseSectionDirectiveDataRelRoLocal>(".data.rel.ro.local");
57 &ELFAsmParser::ParseSectionDirectiveEhFrame>(".eh_frame");
58 addDirectiveHandler<&ELFAsmParser::ParseDirectiveSection>(".section");
60 &ELFAsmParser::ParseDirectivePushSection>(".pushsection");
61 addDirectiveHandler<&ELFAsmParser::ParseDirectivePopSection>(".popsection");
62 addDirectiveHandler<&ELFAsmParser::ParseDirectiveSize>(".size");
63 addDirectiveHandler<&ELFAsmParser::ParseDirectivePrevious>(".previous");
64 addDirectiveHandler<&ELFAsmParser::ParseDirectiveType>(".type");
65 addDirectiveHandler<&ELFAsmParser::ParseDirectiveIdent>(".ident");
66 addDirectiveHandler<&ELFAsmParser::ParseDirectiveSymver>(".symver");
67 addDirectiveHandler<&ELFAsmParser::ParseDirectiveVersion>(".version");
68 addDirectiveHandler<&ELFAsmParser::ParseDirectiveWeakref>(".weakref");
69 addDirectiveHandler<&ELFAsmParser::ParseDirectiveSymbolAttribute>(".weak");
70 addDirectiveHandler<&ELFAsmParser::ParseDirectiveSymbolAttribute>(".local");
72 &ELFAsmParser::ParseDirectiveSymbolAttribute>(".protected");
74 &ELFAsmParser::ParseDirectiveSymbolAttribute>(".internal");
76 &ELFAsmParser::ParseDirectiveSymbolAttribute>(".hidden");
77 addDirectiveHandler<&ELFAsmParser::ParseDirectiveSubsection>(".subsection");
80 // FIXME: Part of this logic is duplicated in the MCELFStreamer. What is
81 // the best way for us to get access to it?
82 bool ParseSectionDirectiveData(StringRef, SMLoc) {
83 return ParseSectionSwitch(".data", ELF::SHT_PROGBITS,
84 ELF::SHF_WRITE |ELF::SHF_ALLOC,
85 SectionKind::getDataRel());
87 bool ParseSectionDirectiveText(StringRef, SMLoc) {
88 return ParseSectionSwitch(".text", ELF::SHT_PROGBITS,
90 ELF::SHF_ALLOC, SectionKind::getText());
92 bool ParseSectionDirectiveBSS(StringRef, SMLoc) {
93 return ParseSectionSwitch(".bss", ELF::SHT_NOBITS,
95 ELF::SHF_ALLOC, SectionKind::getBSS());
97 bool ParseSectionDirectiveRoData(StringRef, SMLoc) {
98 return ParseSectionSwitch(".rodata", ELF::SHT_PROGBITS,
100 SectionKind::getReadOnly());
102 bool ParseSectionDirectiveTData(StringRef, SMLoc) {
103 return ParseSectionSwitch(".tdata", ELF::SHT_PROGBITS,
105 ELF::SHF_TLS | ELF::SHF_WRITE,
106 SectionKind::getThreadData());
108 bool ParseSectionDirectiveTBSS(StringRef, SMLoc) {
109 return ParseSectionSwitch(".tbss", ELF::SHT_NOBITS,
111 ELF::SHF_TLS | ELF::SHF_WRITE,
112 SectionKind::getThreadBSS());
114 bool ParseSectionDirectiveDataRel(StringRef, SMLoc) {
115 return ParseSectionSwitch(".data.rel", ELF::SHT_PROGBITS,
118 SectionKind::getDataRel());
120 bool ParseSectionDirectiveDataRelRo(StringRef, SMLoc) {
121 return ParseSectionSwitch(".data.rel.ro", ELF::SHT_PROGBITS,
124 SectionKind::getReadOnlyWithRel());
126 bool ParseSectionDirectiveDataRelRoLocal(StringRef, SMLoc) {
127 return ParseSectionSwitch(".data.rel.ro.local", ELF::SHT_PROGBITS,
130 SectionKind::getReadOnlyWithRelLocal());
132 bool ParseSectionDirectiveEhFrame(StringRef, SMLoc) {
133 return ParseSectionSwitch(".eh_frame", ELF::SHT_PROGBITS,
136 SectionKind::getDataRel());
138 bool ParseDirectivePushSection(StringRef, SMLoc);
139 bool ParseDirectivePopSection(StringRef, SMLoc);
140 bool ParseDirectiveSection(StringRef, SMLoc);
141 bool ParseDirectiveSize(StringRef, SMLoc);
142 bool ParseDirectivePrevious(StringRef, SMLoc);
143 bool ParseDirectiveType(StringRef, SMLoc);
144 bool ParseDirectiveIdent(StringRef, SMLoc);
145 bool ParseDirectiveSymver(StringRef, SMLoc);
146 bool ParseDirectiveVersion(StringRef, SMLoc);
147 bool ParseDirectiveWeakref(StringRef, SMLoc);
148 bool ParseDirectiveSymbolAttribute(StringRef, SMLoc);
149 bool ParseDirectiveSubsection(StringRef, SMLoc);
152 bool ParseSectionName(StringRef &SectionName);
153 bool ParseSectionArguments(bool IsPush);
158 /// ParseDirectiveSymbolAttribute
159 /// ::= { ".local", ".weak", ... } [ identifier ( , identifier )* ]
160 bool ELFAsmParser::ParseDirectiveSymbolAttribute(StringRef Directive, SMLoc) {
161 MCSymbolAttr Attr = StringSwitch<MCSymbolAttr>(Directive)
162 .Case(".weak", MCSA_Weak)
163 .Case(".local", MCSA_Local)
164 .Case(".hidden", MCSA_Hidden)
165 .Case(".internal", MCSA_Internal)
166 .Case(".protected", MCSA_Protected)
167 .Default(MCSA_Invalid);
168 assert(Attr != MCSA_Invalid && "unexpected symbol attribute directive!");
169 if (getLexer().isNot(AsmToken::EndOfStatement)) {
173 if (getParser().parseIdentifier(Name))
174 return TokError("expected identifier in directive");
176 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
178 getStreamer().EmitSymbolAttribute(Sym, Attr);
180 if (getLexer().is(AsmToken::EndOfStatement))
183 if (getLexer().isNot(AsmToken::Comma))
184 return TokError("unexpected token in directive");
193 bool ELFAsmParser::ParseSectionSwitch(StringRef Section, unsigned Type,
194 unsigned Flags, SectionKind Kind) {
195 const MCExpr *Subsection = 0;
196 if (getLexer().isNot(AsmToken::EndOfStatement)) {
197 if (getParser().parseExpression(Subsection))
201 getStreamer().SwitchSection(getContext().getELFSection(
202 Section, Type, Flags, Kind),
208 bool ELFAsmParser::ParseDirectiveSize(StringRef, SMLoc) {
210 if (getParser().parseIdentifier(Name))
211 return TokError("expected identifier in directive");
212 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
214 if (getLexer().isNot(AsmToken::Comma))
215 return TokError("unexpected token in directive");
219 if (getParser().parseExpression(Expr))
222 if (getLexer().isNot(AsmToken::EndOfStatement))
223 return TokError("unexpected token in directive");
225 getStreamer().EmitELFSize(Sym, Expr);
229 bool ELFAsmParser::ParseSectionName(StringRef &SectionName) {
230 // A section name can contain -, so we cannot just use
232 SMLoc FirstLoc = getLexer().getLoc();
235 if (getLexer().is(AsmToken::String)) {
236 SectionName = getTok().getIdentifier();
244 SMLoc PrevLoc = getLexer().getLoc();
245 if (getLexer().is(AsmToken::Minus)) {
247 Lex(); // Consume the "-".
248 } else if (getLexer().is(AsmToken::String)) {
249 CurSize = getTok().getIdentifier().size() + 2;
251 } else if (getLexer().is(AsmToken::Identifier)) {
252 CurSize = getTok().getIdentifier().size();
259 SectionName = StringRef(FirstLoc.getPointer(), Size);
261 // Make sure the following token is adjacent.
262 if (PrevLoc.getPointer() + CurSize != getTok().getLoc().getPointer())
271 static SectionKind computeSectionKind(unsigned Flags) {
272 if (Flags & ELF::SHF_EXECINSTR)
273 return SectionKind::getText();
274 if (Flags & ELF::SHF_TLS)
275 return SectionKind::getThreadData();
276 return SectionKind::getDataRel();
279 static unsigned parseSectionFlags(StringRef flagsStr, bool *UseLastGroup) {
282 for (unsigned i = 0; i < flagsStr.size(); i++) {
283 switch (flagsStr[i]) {
285 flags |= ELF::SHF_ALLOC;
288 flags |= ELF::SHF_EXCLUDE;
291 flags |= ELF::SHF_EXECINSTR;
294 flags |= ELF::SHF_WRITE;
297 flags |= ELF::SHF_MERGE;
300 flags |= ELF::SHF_STRINGS;
303 flags |= ELF::SHF_TLS;
306 flags |= ELF::XCORE_SHF_CP_SECTION;
309 flags |= ELF::XCORE_SHF_DP_SECTION;
312 flags |= ELF::SHF_GROUP;
315 *UseLastGroup = true;
325 bool ELFAsmParser::ParseDirectivePushSection(StringRef s, SMLoc loc) {
326 getStreamer().PushSection();
328 if (ParseSectionArguments(/*IsPush=*/true)) {
329 getStreamer().PopSection();
336 bool ELFAsmParser::ParseDirectivePopSection(StringRef, SMLoc) {
337 if (!getStreamer().PopSection())
338 return TokError(".popsection without corresponding .pushsection");
342 // FIXME: This is a work in progress.
343 bool ELFAsmParser::ParseDirectiveSection(StringRef, SMLoc) {
344 return ParseSectionArguments(/*IsPush=*/false);
347 bool ELFAsmParser::ParseSectionArguments(bool IsPush) {
348 StringRef SectionName;
350 if (ParseSectionName(SectionName))
351 return TokError("expected identifier in directive");
357 const MCExpr *Subsection = 0;
358 bool UseLastGroup = false;
360 // Set the defaults first.
361 if (SectionName == ".fini" || SectionName == ".init" ||
362 SectionName == ".rodata")
363 Flags |= ELF::SHF_ALLOC;
364 if (SectionName == ".fini" || SectionName == ".init")
365 Flags |= ELF::SHF_EXECINSTR;
367 if (getLexer().is(AsmToken::Comma)) {
370 if (IsPush && getLexer().isNot(AsmToken::String)) {
371 if (getParser().parseExpression(Subsection))
373 if (getLexer().isNot(AsmToken::Comma))
378 if (getLexer().isNot(AsmToken::String))
379 return TokError("expected string in directive");
381 StringRef FlagsStr = getTok().getStringContents();
384 unsigned extraFlags = parseSectionFlags(FlagsStr, &UseLastGroup);
385 if (extraFlags == -1U)
386 return TokError("unknown flag");
389 bool Mergeable = Flags & ELF::SHF_MERGE;
390 bool Group = Flags & ELF::SHF_GROUP;
391 if (Group && UseLastGroup)
392 return TokError("Section cannot specifiy a group name while also acting "
393 "as a member of the last group");
395 if (getLexer().isNot(AsmToken::Comma)) {
397 return TokError("Mergeable section must specify the type");
399 return TokError("Group section must specify the type");
402 if (getLexer().is(AsmToken::At) || getLexer().is(AsmToken::Percent) ||
403 getLexer().is(AsmToken::String)) {
404 if (!getLexer().is(AsmToken::String))
407 return TokError("expected '@<type>', '%<type>' or \"<type>\"");
409 if (getParser().parseIdentifier(TypeName))
410 return TokError("expected identifier in directive");
413 if (getLexer().isNot(AsmToken::Comma))
414 return TokError("expected the entry size");
416 if (getParser().parseAbsoluteExpression(Size))
419 return TokError("entry size must be positive");
423 if (getLexer().isNot(AsmToken::Comma))
424 return TokError("expected group name");
426 if (getParser().parseIdentifier(GroupName))
428 if (getLexer().is(AsmToken::Comma)) {
431 if (getParser().parseIdentifier(Linkage))
433 if (Linkage != "comdat")
434 return TokError("Linkage must be 'comdat'");
441 if (getLexer().isNot(AsmToken::EndOfStatement))
442 return TokError("unexpected token in directive");
444 unsigned Type = ELF::SHT_PROGBITS;
446 if (TypeName.empty()) {
447 if (SectionName.startswith(".note"))
448 Type = ELF::SHT_NOTE;
449 else if (SectionName == ".init_array")
450 Type = ELF::SHT_INIT_ARRAY;
451 else if (SectionName == ".fini_array")
452 Type = ELF::SHT_FINI_ARRAY;
453 else if (SectionName == ".preinit_array")
454 Type = ELF::SHT_PREINIT_ARRAY;
456 if (TypeName == "init_array")
457 Type = ELF::SHT_INIT_ARRAY;
458 else if (TypeName == "fini_array")
459 Type = ELF::SHT_FINI_ARRAY;
460 else if (TypeName == "preinit_array")
461 Type = ELF::SHT_PREINIT_ARRAY;
462 else if (TypeName == "nobits")
463 Type = ELF::SHT_NOBITS;
464 else if (TypeName == "progbits")
465 Type = ELF::SHT_PROGBITS;
466 else if (TypeName == "note")
467 Type = ELF::SHT_NOTE;
468 else if (TypeName == "unwind")
469 Type = ELF::SHT_X86_64_UNWIND;
471 return TokError("unknown section type");
475 MCSectionSubPair CurrentSection = getStreamer().getCurrentSection();
476 if (const MCSectionELF *Section =
477 cast_or_null<MCSectionELF>(CurrentSection.first))
478 if (const MCSymbol *Group = Section->getGroup()) {
479 GroupName = Group->getName();
480 Flags |= ELF::SHF_GROUP;
484 SectionKind Kind = computeSectionKind(Flags);
485 getStreamer().SwitchSection(getContext().getELFSection(SectionName, Type,
492 bool ELFAsmParser::ParseDirectivePrevious(StringRef DirName, SMLoc) {
493 MCSectionSubPair PreviousSection = getStreamer().getPreviousSection();
494 if (PreviousSection.first == NULL)
495 return TokError(".previous without corresponding .section");
496 getStreamer().SwitchSection(PreviousSection.first, PreviousSection.second);
501 /// ParseDirectiveELFType
502 /// ::= .type identifier , STT_<TYPE_IN_UPPER_CASE>
503 /// ::= .type identifier , #attribute
504 /// ::= .type identifier , @attribute
505 /// ::= .type identifier , %attribute
506 /// ::= .type identifier , "attribute"
507 bool ELFAsmParser::ParseDirectiveType(StringRef, SMLoc) {
509 if (getParser().parseIdentifier(Name))
510 return TokError("expected identifier in directive");
512 // Handle the identifier as the key symbol.
513 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
515 if (getLexer().isNot(AsmToken::Comma))
516 return TokError("unexpected token in '.type' directive");
522 if (getLexer().is(AsmToken::Identifier)) {
523 TypeLoc = getLexer().getLoc();
524 if (getParser().parseIdentifier(Type))
525 return TokError("expected symbol type in directive");
526 Attr = StringSwitch<MCSymbolAttr>(Type)
527 .Case("STT_FUNC", MCSA_ELF_TypeFunction)
528 .Case("STT_OBJECT", MCSA_ELF_TypeObject)
529 .Case("STT_TLS", MCSA_ELF_TypeTLS)
530 .Case("STT_COMMON", MCSA_ELF_TypeCommon)
531 .Case("STT_NOTYPE", MCSA_ELF_TypeNoType)
532 .Case("STT_GNU_IFUNC", MCSA_ELF_TypeIndFunction)
533 .Default(MCSA_Invalid);
534 } else if (getLexer().is(AsmToken::Hash) || getLexer().is(AsmToken::At) ||
535 getLexer().is(AsmToken::Percent) ||
536 getLexer().is(AsmToken::String)) {
537 if (!getLexer().is(AsmToken::String))
540 TypeLoc = getLexer().getLoc();
541 if (getParser().parseIdentifier(Type))
542 return TokError("expected symbol type in directive");
543 Attr = StringSwitch<MCSymbolAttr>(Type)
544 .Case("function", MCSA_ELF_TypeFunction)
545 .Case("object", MCSA_ELF_TypeObject)
546 .Case("tls_object", MCSA_ELF_TypeTLS)
547 .Case("common", MCSA_ELF_TypeCommon)
548 .Case("notype", MCSA_ELF_TypeNoType)
549 .Case("gnu_unique_object", MCSA_ELF_TypeGnuUniqueObject)
550 .Case("gnu_indirect_function", MCSA_ELF_TypeIndFunction)
551 .Default(MCSA_Invalid);
553 return TokError("expected STT_<TYPE_IN_UPPER_CASE>, '#<type>', '@<type>', "
554 "'%<type>' or \"<type>\"");
556 if (Attr == MCSA_Invalid)
557 return Error(TypeLoc, "unsupported attribute in '.type' directive");
559 if (getLexer().isNot(AsmToken::EndOfStatement))
560 return TokError("unexpected token in '.type' directive");
564 getStreamer().EmitSymbolAttribute(Sym, Attr);
569 /// ParseDirectiveIdent
570 /// ::= .ident string
571 bool ELFAsmParser::ParseDirectiveIdent(StringRef, SMLoc) {
572 if (getLexer().isNot(AsmToken::String))
573 return TokError("unexpected token in '.ident' directive");
575 StringRef Data = getTok().getIdentifier();
579 getStreamer().EmitIdent(Data);
583 /// ParseDirectiveSymver
584 /// ::= .symver foo, bar2@zed
585 bool ELFAsmParser::ParseDirectiveSymver(StringRef, SMLoc) {
587 if (getParser().parseIdentifier(Name))
588 return TokError("expected identifier in directive");
590 if (getLexer().isNot(AsmToken::Comma))
591 return TokError("expected a comma");
593 // ARM assembly uses @ for a comment...
594 // except when parsing the second parameter of the .symver directive.
595 // Force the next symbol to allow @ in the identifier, which is
596 // required for this directive and then reset it to its initial state.
597 const bool AllowAtInIdentifier = getLexer().getAllowAtInIdentifier();
598 getLexer().setAllowAtInIdentifier(true);
600 getLexer().setAllowAtInIdentifier(AllowAtInIdentifier);
603 if (getParser().parseIdentifier(AliasName))
604 return TokError("expected identifier in directive");
606 if (AliasName.find('@') == StringRef::npos)
607 return TokError("expected a '@' in the name");
609 MCSymbol *Alias = getContext().GetOrCreateSymbol(AliasName);
610 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
611 const MCExpr *Value = MCSymbolRefExpr::Create(Sym, getContext());
613 getStreamer().EmitAssignment(Alias, Value);
617 /// ParseDirectiveVersion
618 /// ::= .version string
619 bool ELFAsmParser::ParseDirectiveVersion(StringRef, SMLoc) {
620 if (getLexer().isNot(AsmToken::String))
621 return TokError("unexpected token in '.version' directive");
623 StringRef Data = getTok().getIdentifier();
627 const MCSection *Note =
628 getContext().getELFSection(".note", ELF::SHT_NOTE, 0,
629 SectionKind::getReadOnly());
631 getStreamer().PushSection();
632 getStreamer().SwitchSection(Note);
633 getStreamer().EmitIntValue(Data.size()+1, 4); // namesz.
634 getStreamer().EmitIntValue(0, 4); // descsz = 0 (no description).
635 getStreamer().EmitIntValue(1, 4); // type = NT_VERSION.
636 getStreamer().EmitBytes(Data); // name.
637 getStreamer().EmitIntValue(0, 1); // terminate the string.
638 getStreamer().EmitValueToAlignment(4); // ensure 4 byte alignment.
639 getStreamer().PopSection();
643 /// ParseDirectiveWeakref
644 /// ::= .weakref foo, bar
645 bool ELFAsmParser::ParseDirectiveWeakref(StringRef, SMLoc) {
646 // FIXME: Share code with the other alias building directives.
649 if (getParser().parseIdentifier(AliasName))
650 return TokError("expected identifier in directive");
652 if (getLexer().isNot(AsmToken::Comma))
653 return TokError("expected a comma");
658 if (getParser().parseIdentifier(Name))
659 return TokError("expected identifier in directive");
661 MCSymbol *Alias = getContext().GetOrCreateSymbol(AliasName);
663 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
665 getStreamer().EmitWeakReference(Alias, Sym);
669 bool ELFAsmParser::ParseDirectiveSubsection(StringRef, SMLoc) {
670 const MCExpr *Subsection = 0;
671 if (getLexer().isNot(AsmToken::EndOfStatement)) {
672 if (getParser().parseExpression(Subsection))
676 if (getLexer().isNot(AsmToken::EndOfStatement))
677 return TokError("unexpected token in directive");
679 getStreamer().SubSection(Subsection);
685 MCAsmParserExtension *createELFAsmParser() {
686 return new ELFAsmParser;