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,
35 unsigned Flags, SectionKind Kind);
39 ELFAsmParser() : SeenIdent(false) {
40 BracketExpressionsSupported = true;
43 virtual void Initialize(MCAsmParser &Parser) {
44 // Call the base implementation.
45 this->MCAsmParserExtension::Initialize(Parser);
47 addDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveData>(".data");
48 addDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveText>(".text");
49 addDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveBSS>(".bss");
50 addDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveRoData>(".rodata");
51 addDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveTData>(".tdata");
52 addDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveTBSS>(".tbss");
54 &ELFAsmParser::ParseSectionDirectiveDataRel>(".data.rel");
56 &ELFAsmParser::ParseSectionDirectiveDataRelRo>(".data.rel.ro");
58 &ELFAsmParser::ParseSectionDirectiveDataRelRoLocal>(".data.rel.ro.local");
60 &ELFAsmParser::ParseSectionDirectiveEhFrame>(".eh_frame");
61 addDirectiveHandler<&ELFAsmParser::ParseDirectiveSection>(".section");
63 &ELFAsmParser::ParseDirectivePushSection>(".pushsection");
64 addDirectiveHandler<&ELFAsmParser::ParseDirectivePopSection>(".popsection");
65 addDirectiveHandler<&ELFAsmParser::ParseDirectiveSize>(".size");
66 addDirectiveHandler<&ELFAsmParser::ParseDirectivePrevious>(".previous");
67 addDirectiveHandler<&ELFAsmParser::ParseDirectiveType>(".type");
68 addDirectiveHandler<&ELFAsmParser::ParseDirectiveIdent>(".ident");
69 addDirectiveHandler<&ELFAsmParser::ParseDirectiveSymver>(".symver");
70 addDirectiveHandler<&ELFAsmParser::ParseDirectiveVersion>(".version");
71 addDirectiveHandler<&ELFAsmParser::ParseDirectiveWeakref>(".weakref");
72 addDirectiveHandler<&ELFAsmParser::ParseDirectiveSymbolAttribute>(".weak");
73 addDirectiveHandler<&ELFAsmParser::ParseDirectiveSymbolAttribute>(".local");
75 &ELFAsmParser::ParseDirectiveSymbolAttribute>(".protected");
77 &ELFAsmParser::ParseDirectiveSymbolAttribute>(".internal");
79 &ELFAsmParser::ParseDirectiveSymbolAttribute>(".hidden");
80 addDirectiveHandler<&ELFAsmParser::ParseDirectiveSubsection>(".subsection");
83 // FIXME: Part of this logic is duplicated in the MCELFStreamer. What is
84 // the best way for us to get access to it?
85 bool ParseSectionDirectiveData(StringRef, SMLoc) {
86 return ParseSectionSwitch(".data", ELF::SHT_PROGBITS,
87 ELF::SHF_WRITE |ELF::SHF_ALLOC,
88 SectionKind::getDataRel());
90 bool ParseSectionDirectiveText(StringRef, SMLoc) {
91 return ParseSectionSwitch(".text", ELF::SHT_PROGBITS,
93 ELF::SHF_ALLOC, SectionKind::getText());
95 bool ParseSectionDirectiveBSS(StringRef, SMLoc) {
96 return ParseSectionSwitch(".bss", ELF::SHT_NOBITS,
98 ELF::SHF_ALLOC, SectionKind::getBSS());
100 bool ParseSectionDirectiveRoData(StringRef, SMLoc) {
101 return ParseSectionSwitch(".rodata", ELF::SHT_PROGBITS,
103 SectionKind::getReadOnly());
105 bool ParseSectionDirectiveTData(StringRef, SMLoc) {
106 return ParseSectionSwitch(".tdata", ELF::SHT_PROGBITS,
108 ELF::SHF_TLS | ELF::SHF_WRITE,
109 SectionKind::getThreadData());
111 bool ParseSectionDirectiveTBSS(StringRef, SMLoc) {
112 return ParseSectionSwitch(".tbss", ELF::SHT_NOBITS,
114 ELF::SHF_TLS | ELF::SHF_WRITE,
115 SectionKind::getThreadBSS());
117 bool ParseSectionDirectiveDataRel(StringRef, SMLoc) {
118 return ParseSectionSwitch(".data.rel", ELF::SHT_PROGBITS,
121 SectionKind::getDataRel());
123 bool ParseSectionDirectiveDataRelRo(StringRef, SMLoc) {
124 return ParseSectionSwitch(".data.rel.ro", ELF::SHT_PROGBITS,
127 SectionKind::getReadOnlyWithRel());
129 bool ParseSectionDirectiveDataRelRoLocal(StringRef, SMLoc) {
130 return ParseSectionSwitch(".data.rel.ro.local", ELF::SHT_PROGBITS,
133 SectionKind::getReadOnlyWithRelLocal());
135 bool ParseSectionDirectiveEhFrame(StringRef, SMLoc) {
136 return ParseSectionSwitch(".eh_frame", ELF::SHT_PROGBITS,
139 SectionKind::getDataRel());
141 bool ParseDirectivePushSection(StringRef, SMLoc);
142 bool ParseDirectivePopSection(StringRef, SMLoc);
143 bool ParseDirectiveSection(StringRef, SMLoc);
144 bool ParseDirectiveSize(StringRef, SMLoc);
145 bool ParseDirectivePrevious(StringRef, SMLoc);
146 bool ParseDirectiveType(StringRef, SMLoc);
147 bool ParseDirectiveIdent(StringRef, SMLoc);
148 bool ParseDirectiveSymver(StringRef, SMLoc);
149 bool ParseDirectiveVersion(StringRef, SMLoc);
150 bool ParseDirectiveWeakref(StringRef, SMLoc);
151 bool ParseDirectiveSymbolAttribute(StringRef, SMLoc);
152 bool ParseDirectiveSubsection(StringRef, SMLoc);
155 bool ParseSectionName(StringRef &SectionName);
156 bool ParseSectionArguments(bool IsPush);
161 /// ParseDirectiveSymbolAttribute
162 /// ::= { ".local", ".weak", ... } [ identifier ( , identifier )* ]
163 bool ELFAsmParser::ParseDirectiveSymbolAttribute(StringRef Directive, SMLoc) {
164 MCSymbolAttr Attr = StringSwitch<MCSymbolAttr>(Directive)
165 .Case(".weak", MCSA_Weak)
166 .Case(".local", MCSA_Local)
167 .Case(".hidden", MCSA_Hidden)
168 .Case(".internal", MCSA_Internal)
169 .Case(".protected", MCSA_Protected)
170 .Default(MCSA_Invalid);
171 assert(Attr != MCSA_Invalid && "unexpected symbol attribute directive!");
172 if (getLexer().isNot(AsmToken::EndOfStatement)) {
176 if (getParser().parseIdentifier(Name))
177 return TokError("expected identifier in directive");
179 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
181 getStreamer().EmitSymbolAttribute(Sym, Attr);
183 if (getLexer().is(AsmToken::EndOfStatement))
186 if (getLexer().isNot(AsmToken::Comma))
187 return TokError("unexpected token in directive");
196 bool ELFAsmParser::ParseSectionSwitch(StringRef Section, unsigned Type,
197 unsigned Flags, SectionKind Kind) {
198 const MCExpr *Subsection = 0;
199 if (getLexer().isNot(AsmToken::EndOfStatement)) {
200 if (getParser().parseExpression(Subsection))
204 getStreamer().SwitchSection(getContext().getELFSection(
205 Section, Type, Flags, Kind),
211 bool ELFAsmParser::ParseDirectiveSize(StringRef, SMLoc) {
213 if (getParser().parseIdentifier(Name))
214 return TokError("expected identifier in directive");
215 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
217 if (getLexer().isNot(AsmToken::Comma))
218 return TokError("unexpected token in directive");
222 if (getParser().parseExpression(Expr))
225 if (getLexer().isNot(AsmToken::EndOfStatement))
226 return TokError("unexpected token in directive");
228 getStreamer().EmitELFSize(Sym, Expr);
232 bool ELFAsmParser::ParseSectionName(StringRef &SectionName) {
233 // A section name can contain -, so we cannot just use
235 SMLoc FirstLoc = getLexer().getLoc();
238 if (getLexer().is(AsmToken::String)) {
239 SectionName = getTok().getIdentifier();
247 SMLoc PrevLoc = getLexer().getLoc();
248 if (getLexer().is(AsmToken::Minus)) {
250 Lex(); // Consume the "-".
251 } else if (getLexer().is(AsmToken::String)) {
252 CurSize = getTok().getIdentifier().size() + 2;
254 } else if (getLexer().is(AsmToken::Identifier)) {
255 CurSize = getTok().getIdentifier().size();
262 SectionName = StringRef(FirstLoc.getPointer(), Size);
264 // Make sure the following token is adjacent.
265 if (PrevLoc.getPointer() + CurSize != getTok().getLoc().getPointer())
274 static SectionKind computeSectionKind(unsigned Flags) {
275 if (Flags & ELF::SHF_EXECINSTR)
276 return SectionKind::getText();
277 if (Flags & ELF::SHF_TLS)
278 return SectionKind::getThreadData();
279 return SectionKind::getDataRel();
282 static unsigned parseSectionFlags(StringRef flagsStr, bool *UseLastGroup) {
285 for (unsigned i = 0; i < flagsStr.size(); i++) {
286 switch (flagsStr[i]) {
288 flags |= ELF::SHF_ALLOC;
291 flags |= ELF::SHF_EXCLUDE;
294 flags |= ELF::SHF_EXECINSTR;
297 flags |= ELF::SHF_WRITE;
300 flags |= ELF::SHF_MERGE;
303 flags |= ELF::SHF_STRINGS;
306 flags |= ELF::SHF_TLS;
309 flags |= ELF::XCORE_SHF_CP_SECTION;
312 flags |= ELF::XCORE_SHF_DP_SECTION;
315 flags |= ELF::SHF_GROUP;
318 *UseLastGroup = true;
328 bool ELFAsmParser::ParseDirectivePushSection(StringRef s, SMLoc loc) {
329 getStreamer().PushSection();
331 if (ParseSectionArguments(/*IsPush=*/true)) {
332 getStreamer().PopSection();
339 bool ELFAsmParser::ParseDirectivePopSection(StringRef, SMLoc) {
340 if (!getStreamer().PopSection())
341 return TokError(".popsection without corresponding .pushsection");
345 // FIXME: This is a work in progress.
346 bool ELFAsmParser::ParseDirectiveSection(StringRef, SMLoc) {
347 return ParseSectionArguments(/*IsPush=*/false);
350 bool ELFAsmParser::ParseSectionArguments(bool IsPush) {
351 StringRef SectionName;
353 if (ParseSectionName(SectionName))
354 return TokError("expected identifier in directive");
360 const MCExpr *Subsection = 0;
361 bool UseLastGroup = false;
363 // Set the defaults first.
364 if (SectionName == ".fini" || SectionName == ".init" ||
365 SectionName == ".rodata")
366 Flags |= ELF::SHF_ALLOC;
367 if (SectionName == ".fini" || SectionName == ".init")
368 Flags |= ELF::SHF_EXECINSTR;
370 if (getLexer().is(AsmToken::Comma)) {
373 if (IsPush && getLexer().isNot(AsmToken::String)) {
374 if (getParser().parseExpression(Subsection))
376 if (getLexer().isNot(AsmToken::Comma))
381 if (getLexer().isNot(AsmToken::String))
382 return TokError("expected string in directive");
384 StringRef FlagsStr = getTok().getStringContents();
387 unsigned extraFlags = parseSectionFlags(FlagsStr, &UseLastGroup);
388 if (extraFlags == -1U)
389 return TokError("unknown flag");
392 bool Mergeable = Flags & ELF::SHF_MERGE;
393 bool Group = Flags & ELF::SHF_GROUP;
394 if (Group && UseLastGroup)
395 return TokError("Section cannot specifiy a group name while also acting "
396 "as a member of the last group");
398 if (getLexer().isNot(AsmToken::Comma)) {
400 return TokError("Mergeable section must specify the type");
402 return TokError("Group section must specify the type");
405 if (getLexer().isNot(AsmToken::Percent) && getLexer().isNot(AsmToken::At))
406 return TokError("expected '@' or '%' before 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 , @attribute
503 bool ELFAsmParser::ParseDirectiveType(StringRef, SMLoc) {
505 if (getParser().parseIdentifier(Name))
506 return TokError("expected identifier in directive");
508 // Handle the identifier as the key symbol.
509 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
511 if (getLexer().isNot(AsmToken::Comma))
512 return TokError("unexpected token in '.type' directive");
515 if (getLexer().isNot(AsmToken::Percent) && getLexer().isNot(AsmToken::At))
516 return TokError("expected '@' or '%' before type");
522 TypeLoc = getLexer().getLoc();
523 if (getParser().parseIdentifier(Type))
524 return TokError("expected symbol type in directive");
526 MCSymbolAttr Attr = StringSwitch<MCSymbolAttr>(Type)
527 .Case("function", MCSA_ELF_TypeFunction)
528 .Case("object", MCSA_ELF_TypeObject)
529 .Case("tls_object", MCSA_ELF_TypeTLS)
530 .Case("common", MCSA_ELF_TypeCommon)
531 .Case("notype", MCSA_ELF_TypeNoType)
532 .Case("gnu_unique_object", MCSA_ELF_TypeGnuUniqueObject)
533 .Case("gnu_indirect_function", MCSA_ELF_TypeIndFunction)
534 .Default(MCSA_Invalid);
536 if (Attr == MCSA_Invalid)
537 return Error(TypeLoc, "unsupported attribute in '.type' directive");
539 if (getLexer().isNot(AsmToken::EndOfStatement))
540 return TokError("unexpected token in '.type' directive");
544 getStreamer().EmitSymbolAttribute(Sym, Attr);
549 /// ParseDirectiveIdent
550 /// ::= .ident string
551 bool ELFAsmParser::ParseDirectiveIdent(StringRef, SMLoc) {
552 if (getLexer().isNot(AsmToken::String))
553 return TokError("unexpected token in '.ident' directive");
555 StringRef Data = getTok().getIdentifier();
559 const MCSection *Comment =
560 getContext().getELFSection(".comment", ELF::SHT_PROGBITS,
563 SectionKind::getReadOnly(),
566 getStreamer().PushSection();
567 getStreamer().SwitchSection(Comment);
569 getStreamer().EmitIntValue(0, 1);
572 getStreamer().EmitBytes(Data);
573 getStreamer().EmitIntValue(0, 1);
574 getStreamer().PopSection();
578 /// ParseDirectiveSymver
579 /// ::= .symver foo, bar2@zed
580 bool ELFAsmParser::ParseDirectiveSymver(StringRef, SMLoc) {
582 if (getParser().parseIdentifier(Name))
583 return TokError("expected identifier in directive");
585 if (getLexer().isNot(AsmToken::Comma))
586 return TokError("expected a comma");
591 if (getParser().parseIdentifier(AliasName))
592 return TokError("expected identifier in directive");
594 if (AliasName.find('@') == StringRef::npos)
595 return TokError("expected a '@' in the name");
597 MCSymbol *Alias = getContext().GetOrCreateSymbol(AliasName);
598 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
599 const MCExpr *Value = MCSymbolRefExpr::Create(Sym, getContext());
601 getStreamer().EmitAssignment(Alias, Value);
605 /// ParseDirectiveVersion
606 /// ::= .version string
607 bool ELFAsmParser::ParseDirectiveVersion(StringRef, SMLoc) {
608 if (getLexer().isNot(AsmToken::String))
609 return TokError("unexpected token in '.version' directive");
611 StringRef Data = getTok().getIdentifier();
615 const MCSection *Note =
616 getContext().getELFSection(".note", ELF::SHT_NOTE, 0,
617 SectionKind::getReadOnly());
619 getStreamer().PushSection();
620 getStreamer().SwitchSection(Note);
621 getStreamer().EmitIntValue(Data.size()+1, 4); // namesz.
622 getStreamer().EmitIntValue(0, 4); // descsz = 0 (no description).
623 getStreamer().EmitIntValue(1, 4); // type = NT_VERSION.
624 getStreamer().EmitBytes(Data); // name.
625 getStreamer().EmitIntValue(0, 1); // terminate the string.
626 getStreamer().EmitValueToAlignment(4); // ensure 4 byte alignment.
627 getStreamer().PopSection();
631 /// ParseDirectiveWeakref
632 /// ::= .weakref foo, bar
633 bool ELFAsmParser::ParseDirectiveWeakref(StringRef, SMLoc) {
634 // FIXME: Share code with the other alias building directives.
637 if (getParser().parseIdentifier(AliasName))
638 return TokError("expected identifier in directive");
640 if (getLexer().isNot(AsmToken::Comma))
641 return TokError("expected a comma");
646 if (getParser().parseIdentifier(Name))
647 return TokError("expected identifier in directive");
649 MCSymbol *Alias = getContext().GetOrCreateSymbol(AliasName);
651 MCSymbol *Sym = getContext().GetOrCreateSymbol(Name);
653 getStreamer().EmitWeakReference(Alias, Sym);
657 bool ELFAsmParser::ParseDirectiveSubsection(StringRef, SMLoc) {
658 const MCExpr *Subsection = 0;
659 if (getLexer().isNot(AsmToken::EndOfStatement)) {
660 if (getParser().parseExpression(Subsection))
664 if (getLexer().isNot(AsmToken::EndOfStatement))
665 return TokError("unexpected token in directive");
667 getStreamer().SubSection(Subsection);
673 MCAsmParserExtension *createELFAsmParser() {
674 return new ELFAsmParser;