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/MC/MCSymbolELF.h"
20 #include "llvm/Support/ELF.h"
21 using namespace llvm;
22 
23 namespace {
24 
25 class ELFAsmParser : public MCAsmParserExtension {
26   template<bool (ELFAsmParser::*HandlerMethod)(StringRef, SMLoc)>
addDirectiveHandler(StringRef Directive)27   void addDirectiveHandler(StringRef Directive) {
28     MCAsmParser::ExtensionDirectiveHandler Handler = std::make_pair(
29         this, HandleDirective<ELFAsmParser, HandlerMethod>);
30 
31     getParser().addDirectiveHandler(Directive, Handler);
32   }
33 
34   bool ParseSectionSwitch(StringRef Section, unsigned Type, unsigned Flags,
35                           SectionKind Kind);
36 
37 public:
ELFAsmParser()38   ELFAsmParser() { BracketExpressionsSupported = true; }
39 
Initialize(MCAsmParser & Parser)40   void Initialize(MCAsmParser &Parser) override {
41     // Call the base implementation.
42     this->MCAsmParserExtension::Initialize(Parser);
43 
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");
50     addDirectiveHandler<
51       &ELFAsmParser::ParseSectionDirectiveDataRel>(".data.rel");
52     addDirectiveHandler<
53       &ELFAsmParser::ParseSectionDirectiveDataRelRo>(".data.rel.ro");
54     addDirectiveHandler<
55       &ELFAsmParser::ParseSectionDirectiveEhFrame>(".eh_frame");
56     addDirectiveHandler<&ELFAsmParser::ParseDirectiveSection>(".section");
57     addDirectiveHandler<
58       &ELFAsmParser::ParseDirectivePushSection>(".pushsection");
59     addDirectiveHandler<&ELFAsmParser::ParseDirectivePopSection>(".popsection");
60     addDirectiveHandler<&ELFAsmParser::ParseDirectiveSize>(".size");
61     addDirectiveHandler<&ELFAsmParser::ParseDirectivePrevious>(".previous");
62     addDirectiveHandler<&ELFAsmParser::ParseDirectiveType>(".type");
63     addDirectiveHandler<&ELFAsmParser::ParseDirectiveIdent>(".ident");
64     addDirectiveHandler<&ELFAsmParser::ParseDirectiveSymver>(".symver");
65     addDirectiveHandler<&ELFAsmParser::ParseDirectiveVersion>(".version");
66     addDirectiveHandler<&ELFAsmParser::ParseDirectiveWeakref>(".weakref");
67     addDirectiveHandler<&ELFAsmParser::ParseDirectiveSymbolAttribute>(".weak");
68     addDirectiveHandler<&ELFAsmParser::ParseDirectiveSymbolAttribute>(".local");
69     addDirectiveHandler<
70       &ELFAsmParser::ParseDirectiveSymbolAttribute>(".protected");
71     addDirectiveHandler<
72       &ELFAsmParser::ParseDirectiveSymbolAttribute>(".internal");
73     addDirectiveHandler<
74       &ELFAsmParser::ParseDirectiveSymbolAttribute>(".hidden");
75     addDirectiveHandler<&ELFAsmParser::ParseDirectiveSubsection>(".subsection");
76   }
77 
78   // FIXME: Part of this logic is duplicated in the MCELFStreamer. What is
79   // the best way for us to get access to it?
ParseSectionDirectiveData(StringRef,SMLoc)80   bool ParseSectionDirectiveData(StringRef, SMLoc) {
81     return ParseSectionSwitch(".data", ELF::SHT_PROGBITS,
82                               ELF::SHF_WRITE | ELF::SHF_ALLOC,
83                               SectionKind::getData());
84   }
ParseSectionDirectiveText(StringRef,SMLoc)85   bool ParseSectionDirectiveText(StringRef, SMLoc) {
86     return ParseSectionSwitch(".text", ELF::SHT_PROGBITS,
87                               ELF::SHF_EXECINSTR |
88                               ELF::SHF_ALLOC, SectionKind::getText());
89   }
ParseSectionDirectiveBSS(StringRef,SMLoc)90   bool ParseSectionDirectiveBSS(StringRef, SMLoc) {
91     return ParseSectionSwitch(".bss", ELF::SHT_NOBITS,
92                               ELF::SHF_WRITE |
93                               ELF::SHF_ALLOC, SectionKind::getBSS());
94   }
ParseSectionDirectiveRoData(StringRef,SMLoc)95   bool ParseSectionDirectiveRoData(StringRef, SMLoc) {
96     return ParseSectionSwitch(".rodata", ELF::SHT_PROGBITS,
97                               ELF::SHF_ALLOC,
98                               SectionKind::getReadOnly());
99   }
ParseSectionDirectiveTData(StringRef,SMLoc)100   bool ParseSectionDirectiveTData(StringRef, SMLoc) {
101     return ParseSectionSwitch(".tdata", ELF::SHT_PROGBITS,
102                               ELF::SHF_ALLOC |
103                               ELF::SHF_TLS | ELF::SHF_WRITE,
104                               SectionKind::getThreadData());
105   }
ParseSectionDirectiveTBSS(StringRef,SMLoc)106   bool ParseSectionDirectiveTBSS(StringRef, SMLoc) {
107     return ParseSectionSwitch(".tbss", ELF::SHT_NOBITS,
108                               ELF::SHF_ALLOC |
109                               ELF::SHF_TLS | ELF::SHF_WRITE,
110                               SectionKind::getThreadBSS());
111   }
ParseSectionDirectiveDataRel(StringRef,SMLoc)112   bool ParseSectionDirectiveDataRel(StringRef, SMLoc) {
113     return ParseSectionSwitch(".data.rel", ELF::SHT_PROGBITS,
114                               ELF::SHF_ALLOC | ELF::SHF_WRITE,
115                               SectionKind::getData());
116   }
ParseSectionDirectiveDataRelRo(StringRef,SMLoc)117   bool ParseSectionDirectiveDataRelRo(StringRef, SMLoc) {
118     return ParseSectionSwitch(".data.rel.ro", ELF::SHT_PROGBITS,
119                               ELF::SHF_ALLOC |
120                               ELF::SHF_WRITE,
121                               SectionKind::getReadOnlyWithRel());
122   }
ParseSectionDirectiveEhFrame(StringRef,SMLoc)123   bool ParseSectionDirectiveEhFrame(StringRef, SMLoc) {
124     return ParseSectionSwitch(".eh_frame", ELF::SHT_PROGBITS,
125                               ELF::SHF_ALLOC | ELF::SHF_WRITE,
126                               SectionKind::getData());
127   }
128   bool ParseDirectivePushSection(StringRef, SMLoc);
129   bool ParseDirectivePopSection(StringRef, SMLoc);
130   bool ParseDirectiveSection(StringRef, SMLoc);
131   bool ParseDirectiveSize(StringRef, SMLoc);
132   bool ParseDirectivePrevious(StringRef, SMLoc);
133   bool ParseDirectiveType(StringRef, SMLoc);
134   bool ParseDirectiveIdent(StringRef, SMLoc);
135   bool ParseDirectiveSymver(StringRef, SMLoc);
136   bool ParseDirectiveVersion(StringRef, SMLoc);
137   bool ParseDirectiveWeakref(StringRef, SMLoc);
138   bool ParseDirectiveSymbolAttribute(StringRef, SMLoc);
139   bool ParseDirectiveSubsection(StringRef, SMLoc);
140 
141 private:
142   bool ParseSectionName(StringRef &SectionName);
143   bool ParseSectionArguments(bool IsPush, SMLoc loc);
144   unsigned parseSunStyleSectionFlags();
145 };
146 
147 }
148 
149 /// ParseDirectiveSymbolAttribute
150 ///  ::= { ".local", ".weak", ... } [ identifier ( , identifier )* ]
ParseDirectiveSymbolAttribute(StringRef Directive,SMLoc)151 bool ELFAsmParser::ParseDirectiveSymbolAttribute(StringRef Directive, SMLoc) {
152   MCSymbolAttr Attr = StringSwitch<MCSymbolAttr>(Directive)
153     .Case(".weak", MCSA_Weak)
154     .Case(".local", MCSA_Local)
155     .Case(".hidden", MCSA_Hidden)
156     .Case(".internal", MCSA_Internal)
157     .Case(".protected", MCSA_Protected)
158     .Default(MCSA_Invalid);
159   assert(Attr != MCSA_Invalid && "unexpected symbol attribute directive!");
160   if (getLexer().isNot(AsmToken::EndOfStatement)) {
161     for (;;) {
162       StringRef Name;
163 
164       if (getParser().parseIdentifier(Name))
165         return TokError("expected identifier in directive");
166 
167       MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
168 
169       getStreamer().EmitSymbolAttribute(Sym, Attr);
170 
171       if (getLexer().is(AsmToken::EndOfStatement))
172         break;
173 
174       if (getLexer().isNot(AsmToken::Comma))
175         return TokError("unexpected token in directive");
176       Lex();
177     }
178   }
179 
180   Lex();
181   return false;
182 }
183 
ParseSectionSwitch(StringRef Section,unsigned Type,unsigned Flags,SectionKind Kind)184 bool ELFAsmParser::ParseSectionSwitch(StringRef Section, unsigned Type,
185                                       unsigned Flags, SectionKind Kind) {
186   const MCExpr *Subsection = nullptr;
187   if (getLexer().isNot(AsmToken::EndOfStatement)) {
188     if (getParser().parseExpression(Subsection))
189       return true;
190   }
191 
192   getStreamer().SwitchSection(getContext().getELFSection(Section, Type, Flags),
193                               Subsection);
194 
195   return false;
196 }
197 
ParseDirectiveSize(StringRef,SMLoc)198 bool ELFAsmParser::ParseDirectiveSize(StringRef, SMLoc) {
199   StringRef Name;
200   if (getParser().parseIdentifier(Name))
201     return TokError("expected identifier in directive");
202   MCSymbolELF *Sym = cast<MCSymbolELF>(getContext().getOrCreateSymbol(Name));
203 
204   if (getLexer().isNot(AsmToken::Comma))
205     return TokError("unexpected token in directive");
206   Lex();
207 
208   const MCExpr *Expr;
209   if (getParser().parseExpression(Expr))
210     return true;
211 
212   if (getLexer().isNot(AsmToken::EndOfStatement))
213     return TokError("unexpected token in directive");
214 
215   getStreamer().emitELFSize(Sym, Expr);
216   return false;
217 }
218 
ParseSectionName(StringRef & SectionName)219 bool ELFAsmParser::ParseSectionName(StringRef &SectionName) {
220   // A section name can contain -, so we cannot just use
221   // parseIdentifier.
222   SMLoc FirstLoc = getLexer().getLoc();
223   unsigned Size = 0;
224 
225   if (getLexer().is(AsmToken::String)) {
226     SectionName = getTok().getIdentifier();
227     Lex();
228     return false;
229   }
230 
231   for (;;) {
232     unsigned CurSize;
233 
234     SMLoc PrevLoc = getLexer().getLoc();
235     if (getLexer().is(AsmToken::Minus)) {
236       CurSize = 1;
237       Lex(); // Consume the "-".
238     } else if (getLexer().is(AsmToken::String)) {
239       CurSize = getTok().getIdentifier().size() + 2;
240       Lex();
241     } else if (getLexer().is(AsmToken::Identifier)) {
242       CurSize = getTok().getIdentifier().size();
243       Lex();
244     } else {
245       break;
246     }
247 
248     Size += CurSize;
249     SectionName = StringRef(FirstLoc.getPointer(), Size);
250 
251     // Make sure the following token is adjacent.
252     if (PrevLoc.getPointer() + CurSize != getTok().getLoc().getPointer())
253       break;
254   }
255   if (Size == 0)
256     return true;
257 
258   return false;
259 }
260 
parseSectionFlags(StringRef flagsStr,bool * UseLastGroup)261 static unsigned parseSectionFlags(StringRef flagsStr, bool *UseLastGroup) {
262   unsigned flags = 0;
263 
264   for (unsigned i = 0; i < flagsStr.size(); i++) {
265     switch (flagsStr[i]) {
266     case 'a':
267       flags |= ELF::SHF_ALLOC;
268       break;
269     case 'e':
270       flags |= ELF::SHF_EXCLUDE;
271       break;
272     case 'x':
273       flags |= ELF::SHF_EXECINSTR;
274       break;
275     case 'w':
276       flags |= ELF::SHF_WRITE;
277       break;
278     case 'M':
279       flags |= ELF::SHF_MERGE;
280       break;
281     case 'S':
282       flags |= ELF::SHF_STRINGS;
283       break;
284     case 'T':
285       flags |= ELF::SHF_TLS;
286       break;
287     case 'c':
288       flags |= ELF::XCORE_SHF_CP_SECTION;
289       break;
290     case 'd':
291       flags |= ELF::XCORE_SHF_DP_SECTION;
292       break;
293     case 'G':
294       flags |= ELF::SHF_GROUP;
295       break;
296     case '?':
297       *UseLastGroup = true;
298       break;
299     default:
300       return -1U;
301     }
302   }
303 
304   return flags;
305 }
306 
parseSunStyleSectionFlags()307 unsigned ELFAsmParser::parseSunStyleSectionFlags() {
308   unsigned flags = 0;
309   while (getLexer().is(AsmToken::Hash)) {
310     Lex(); // Eat the #.
311 
312     if (!getLexer().is(AsmToken::Identifier))
313       return -1U;
314 
315     StringRef flagId = getTok().getIdentifier();
316     if (flagId == "alloc")
317       flags |= ELF::SHF_ALLOC;
318     else if (flagId == "execinstr")
319       flags |= ELF::SHF_EXECINSTR;
320     else if (flagId == "write")
321       flags |= ELF::SHF_WRITE;
322     else if (flagId == "tls")
323       flags |= ELF::SHF_TLS;
324     else
325       return -1U;
326 
327     Lex(); // Eat the flag.
328 
329     if (!getLexer().is(AsmToken::Comma))
330         break;
331     Lex(); // Eat the comma.
332   }
333   return flags;
334 }
335 
336 
ParseDirectivePushSection(StringRef s,SMLoc loc)337 bool ELFAsmParser::ParseDirectivePushSection(StringRef s, SMLoc loc) {
338   getStreamer().PushSection();
339 
340   if (ParseSectionArguments(/*IsPush=*/true, loc)) {
341     getStreamer().PopSection();
342     return true;
343   }
344 
345   return false;
346 }
347 
ParseDirectivePopSection(StringRef,SMLoc)348 bool ELFAsmParser::ParseDirectivePopSection(StringRef, SMLoc) {
349   if (!getStreamer().PopSection())
350     return TokError(".popsection without corresponding .pushsection");
351   return false;
352 }
353 
354 // FIXME: This is a work in progress.
ParseDirectiveSection(StringRef,SMLoc loc)355 bool ELFAsmParser::ParseDirectiveSection(StringRef, SMLoc loc) {
356   return ParseSectionArguments(/*IsPush=*/false, loc);
357 }
358 
ParseSectionArguments(bool IsPush,SMLoc loc)359 bool ELFAsmParser::ParseSectionArguments(bool IsPush, SMLoc loc)
360 {
361   StringRef SectionName;
362 
363   if (ParseSectionName(SectionName))
364     return TokError("expected identifier in directive");
365 
366   StringRef TypeName;
367   int64_t Size = 0;
368   StringRef GroupName;
369   unsigned Flags = 0;
370   const MCExpr *Subsection = nullptr;
371   bool UseLastGroup = false;
372   StringRef UniqueStr;
373   int64_t UniqueID = ~0;
374 
375   // Set the defaults first.
376   if (SectionName == ".fini" || SectionName == ".init" ||
377       SectionName == ".rodata")
378     Flags |= ELF::SHF_ALLOC;
379   if (SectionName == ".fini" || SectionName == ".init")
380     Flags |= ELF::SHF_EXECINSTR;
381 
382   if (getLexer().is(AsmToken::Comma)) {
383     Lex();
384 
385     if (IsPush && getLexer().isNot(AsmToken::String)) {
386       if (getParser().parseExpression(Subsection))
387         return true;
388       if (getLexer().isNot(AsmToken::Comma))
389         goto EndStmt;
390       Lex();
391     }
392 
393     unsigned extraFlags;
394 
395     if (getLexer().isNot(AsmToken::String)) {
396       if (!getContext().getAsmInfo()->usesSunStyleELFSectionSwitchSyntax()
397           || getLexer().isNot(AsmToken::Hash))
398         return TokError("expected string in directive");
399       extraFlags = parseSunStyleSectionFlags();
400     } else {
401       bool valid;
402       StringRef FlagsStr = getTok().getStringContents(valid);
403       if (!valid)
404           return true;
405       Lex();
406       extraFlags = parseSectionFlags(FlagsStr, &UseLastGroup);
407     }
408 
409     if (extraFlags == -1U)
410       return TokError("unknown flag");
411     Flags |= extraFlags;
412 
413     bool Mergeable = Flags & ELF::SHF_MERGE;
414     bool Group = Flags & ELF::SHF_GROUP;
415     if (Group && UseLastGroup)
416       return TokError("Section cannot specifiy a group name while also acting "
417                       "as a member of the last group");
418 
419     if (getLexer().isNot(AsmToken::Comma)) {
420       if (Mergeable)
421         return TokError("Mergeable section must specify the type");
422       if (Group)
423         return TokError("Group section must specify the type");
424     } else {
425       Lex();
426       if (getLexer().is(AsmToken::At) || getLexer().is(AsmToken::Percent) ||
427           getLexer().is(AsmToken::String)) {
428         if (!getLexer().is(AsmToken::String))
429           Lex();
430       } else
431         return TokError("expected '@<type>', '%<type>' or \"<type>\"");
432 
433       if (getParser().parseIdentifier(TypeName))
434         return TokError("expected identifier in directive");
435 
436       if (Mergeable) {
437         if (getLexer().isNot(AsmToken::Comma))
438           return TokError("expected the entry size");
439         Lex();
440         if (getParser().parseAbsoluteExpression(Size))
441           return true;
442         if (Size <= 0)
443           return TokError("entry size must be positive");
444       }
445 
446       if (Group) {
447         if (getLexer().isNot(AsmToken::Comma))
448           return TokError("expected group name");
449         Lex();
450         if (getParser().parseIdentifier(GroupName))
451           return true;
452         if (getLexer().is(AsmToken::Comma)) {
453           Lex();
454           StringRef Linkage;
455           if (getParser().parseIdentifier(Linkage))
456             return true;
457           if (Linkage != "comdat")
458             return TokError("Linkage must be 'comdat'");
459         }
460       }
461       if (getLexer().is(AsmToken::Comma)) {
462         Lex();
463         if (getParser().parseIdentifier(UniqueStr))
464           return TokError("expected identifier in directive");
465         if (UniqueStr != "unique")
466           return TokError("expected 'unique'");
467         if (getLexer().isNot(AsmToken::Comma))
468           return TokError("expected commma");
469         Lex();
470         if (getParser().parseAbsoluteExpression(UniqueID))
471           return true;
472         if (UniqueID < 0)
473           return TokError("unique id must be positive");
474         if (!isUInt<32>(UniqueID) || UniqueID == ~0U)
475           return TokError("unique id is too large");
476       }
477     }
478   }
479 
480 EndStmt:
481   if (getLexer().isNot(AsmToken::EndOfStatement))
482     return TokError("unexpected token in directive");
483 
484   unsigned Type = ELF::SHT_PROGBITS;
485 
486   if (TypeName.empty()) {
487     if (SectionName.startswith(".note"))
488       Type = ELF::SHT_NOTE;
489     else if (SectionName == ".init_array")
490       Type = ELF::SHT_INIT_ARRAY;
491     else if (SectionName == ".fini_array")
492       Type = ELF::SHT_FINI_ARRAY;
493     else if (SectionName == ".preinit_array")
494       Type = ELF::SHT_PREINIT_ARRAY;
495   } else {
496     if (TypeName == "init_array")
497       Type = ELF::SHT_INIT_ARRAY;
498     else if (TypeName == "fini_array")
499       Type = ELF::SHT_FINI_ARRAY;
500     else if (TypeName == "preinit_array")
501       Type = ELF::SHT_PREINIT_ARRAY;
502     else if (TypeName == "nobits")
503       Type = ELF::SHT_NOBITS;
504     else if (TypeName == "progbits")
505       Type = ELF::SHT_PROGBITS;
506     else if (TypeName == "note")
507       Type = ELF::SHT_NOTE;
508     else if (TypeName == "unwind")
509       Type = ELF::SHT_X86_64_UNWIND;
510     else
511       return TokError("unknown section type");
512   }
513 
514   if (UseLastGroup) {
515     MCSectionSubPair CurrentSection = getStreamer().getCurrentSection();
516     if (const MCSectionELF *Section =
517             cast_or_null<MCSectionELF>(CurrentSection.first))
518       if (const MCSymbol *Group = Section->getGroup()) {
519         GroupName = Group->getName();
520         Flags |= ELF::SHF_GROUP;
521       }
522   }
523 
524   MCSection *ELFSection = getContext().getELFSection(SectionName, Type, Flags,
525                                                      Size, GroupName, UniqueID);
526   getStreamer().SwitchSection(ELFSection, Subsection);
527 
528   if (getContext().getGenDwarfForAssembly()) {
529     bool InsertResult = getContext().addGenDwarfSection(ELFSection);
530     if (InsertResult) {
531       if (getContext().getDwarfVersion() <= 2)
532         Warning(loc, "DWARF2 only supports one section per compilation unit");
533 
534       if (!ELFSection->getBeginSymbol()) {
535         MCSymbol *SectionStartSymbol = getContext().createTempSymbol();
536         getStreamer().EmitLabel(SectionStartSymbol);
537         ELFSection->setBeginSymbol(SectionStartSymbol);
538       }
539     }
540   }
541 
542   return false;
543 }
544 
ParseDirectivePrevious(StringRef DirName,SMLoc)545 bool ELFAsmParser::ParseDirectivePrevious(StringRef DirName, SMLoc) {
546   MCSectionSubPair PreviousSection = getStreamer().getPreviousSection();
547   if (PreviousSection.first == nullptr)
548       return TokError(".previous without corresponding .section");
549   getStreamer().SwitchSection(PreviousSection.first, PreviousSection.second);
550 
551   return false;
552 }
553 
MCAttrForString(StringRef Type)554 static MCSymbolAttr MCAttrForString(StringRef Type) {
555   return StringSwitch<MCSymbolAttr>(Type)
556           .Cases("STT_FUNC", "function", MCSA_ELF_TypeFunction)
557           .Cases("STT_OBJECT", "object", MCSA_ELF_TypeObject)
558           .Cases("STT_TLS", "tls_object", MCSA_ELF_TypeTLS)
559           .Cases("STT_COMMON", "common", MCSA_ELF_TypeCommon)
560           .Cases("STT_NOTYPE", "notype", MCSA_ELF_TypeNoType)
561           .Cases("STT_GNU_IFUNC", "gnu_indirect_function",
562                  MCSA_ELF_TypeIndFunction)
563           .Case("gnu_unique_object", MCSA_ELF_TypeGnuUniqueObject)
564           .Default(MCSA_Invalid);
565 }
566 
567 /// ParseDirectiveELFType
568 ///  ::= .type identifier , STT_<TYPE_IN_UPPER_CASE>
569 ///  ::= .type identifier , #attribute
570 ///  ::= .type identifier , @attribute
571 ///  ::= .type identifier , %attribute
572 ///  ::= .type identifier , "attribute"
ParseDirectiveType(StringRef,SMLoc)573 bool ELFAsmParser::ParseDirectiveType(StringRef, SMLoc) {
574   StringRef Name;
575   if (getParser().parseIdentifier(Name))
576     return TokError("expected identifier in directive");
577 
578   // Handle the identifier as the key symbol.
579   MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
580 
581   // NOTE the comma is optional in all cases.  It is only documented as being
582   // optional in the first case, however, GAS will silently treat the comma as
583   // optional in all cases.  Furthermore, although the documentation states that
584   // the first form only accepts STT_<TYPE_IN_UPPER_CASE>, in reality, GAS
585   // accepts both the upper case name as well as the lower case aliases.
586   if (getLexer().is(AsmToken::Comma))
587     Lex();
588 
589   if (getLexer().isNot(AsmToken::Identifier) &&
590       getLexer().isNot(AsmToken::Hash) &&
591       getLexer().isNot(AsmToken::Percent) &&
592       getLexer().isNot(AsmToken::String)) {
593     if (!getLexer().getAllowAtInIdentifier())
594       return TokError("expected STT_<TYPE_IN_UPPER_CASE>, '#<type>', "
595                       "'%<type>' or \"<type>\"");
596     else if (getLexer().isNot(AsmToken::At))
597       return TokError("expected STT_<TYPE_IN_UPPER_CASE>, '#<type>', '@<type>', "
598                       "'%<type>' or \"<type>\"");
599   }
600 
601   if (getLexer().isNot(AsmToken::String) &&
602       getLexer().isNot(AsmToken::Identifier))
603     Lex();
604 
605   SMLoc TypeLoc = getLexer().getLoc();
606 
607   StringRef Type;
608   if (getParser().parseIdentifier(Type))
609     return TokError("expected symbol type in directive");
610 
611   MCSymbolAttr Attr = MCAttrForString(Type);
612   if (Attr == MCSA_Invalid)
613     return Error(TypeLoc, "unsupported attribute in '.type' directive");
614 
615   if (getLexer().isNot(AsmToken::EndOfStatement))
616     return TokError("unexpected token in '.type' directive");
617   Lex();
618 
619   getStreamer().EmitSymbolAttribute(Sym, Attr);
620 
621   return false;
622 }
623 
624 /// ParseDirectiveIdent
625 ///  ::= .ident string
ParseDirectiveIdent(StringRef,SMLoc)626 bool ELFAsmParser::ParseDirectiveIdent(StringRef, SMLoc) {
627   if (getLexer().isNot(AsmToken::String))
628     return TokError("unexpected token in '.ident' directive");
629 
630   StringRef Data = getTok().getIdentifier();
631 
632   Lex();
633 
634   getStreamer().EmitIdent(Data);
635   return false;
636 }
637 
638 /// ParseDirectiveSymver
639 ///  ::= .symver foo, bar2@zed
ParseDirectiveSymver(StringRef,SMLoc)640 bool ELFAsmParser::ParseDirectiveSymver(StringRef, SMLoc) {
641   StringRef Name;
642   if (getParser().parseIdentifier(Name))
643     return TokError("expected identifier in directive");
644 
645   if (getLexer().isNot(AsmToken::Comma))
646     return TokError("expected a comma");
647 
648   // ARM assembly uses @ for a comment...
649   // except when parsing the second parameter of the .symver directive.
650   // Force the next symbol to allow @ in the identifier, which is
651   // required for this directive and then reset it to its initial state.
652   const bool AllowAtInIdentifier = getLexer().getAllowAtInIdentifier();
653   getLexer().setAllowAtInIdentifier(true);
654   Lex();
655   getLexer().setAllowAtInIdentifier(AllowAtInIdentifier);
656 
657   StringRef AliasName;
658   if (getParser().parseIdentifier(AliasName))
659     return TokError("expected identifier in directive");
660 
661   if (AliasName.find('@') == StringRef::npos)
662     return TokError("expected a '@' in the name");
663 
664   MCSymbol *Alias = getContext().getOrCreateSymbol(AliasName);
665   MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
666   const MCExpr *Value = MCSymbolRefExpr::create(Sym, getContext());
667 
668   getStreamer().EmitAssignment(Alias, Value);
669   return false;
670 }
671 
672 /// ParseDirectiveVersion
673 ///  ::= .version string
ParseDirectiveVersion(StringRef,SMLoc)674 bool ELFAsmParser::ParseDirectiveVersion(StringRef, SMLoc)
675 {
676   bool Error;
677   if (getLexer().isNot(AsmToken::String))
678     return TokError("unexpected token in '.version' directive");
679 
680   StringRef Data = getTok().getIdentifier();
681 
682   Lex();
683 
684   MCSection *Note = getContext().getELFSection(".note", ELF::SHT_NOTE, 0);
685 
686   getStreamer().PushSection();
687   getStreamer().SwitchSection(Note);
688   getStreamer().EmitIntValue(Data.size()+1, 4, Error); // namesz.
689   if (Error)
690       return true;
691   getStreamer().EmitIntValue(0, 4, Error);             // descsz = 0 (no description).
692   getStreamer().EmitIntValue(1, 4, Error);             // type = NT_VERSION.
693   getStreamer().EmitBytes(Data);                // name.
694   getStreamer().EmitIntValue(0, 1, Error);             // terminate the string.
695   getStreamer().EmitValueToAlignment(4);        // ensure 4 byte alignment.
696   getStreamer().PopSection();
697   return false;
698 }
699 
700 /// ParseDirectiveWeakref
701 ///  ::= .weakref foo, bar
ParseDirectiveWeakref(StringRef,SMLoc)702 bool ELFAsmParser::ParseDirectiveWeakref(StringRef, SMLoc) {
703   // FIXME: Share code with the other alias building directives.
704 
705   StringRef AliasName;
706   if (getParser().parseIdentifier(AliasName))
707     return TokError("expected identifier in directive");
708 
709   if (getLexer().isNot(AsmToken::Comma))
710     return TokError("expected a comma");
711 
712   Lex();
713 
714   StringRef Name;
715   if (getParser().parseIdentifier(Name))
716     return TokError("expected identifier in directive");
717 
718   MCSymbol *Alias = getContext().getOrCreateSymbol(AliasName);
719 
720   MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
721 
722   getStreamer().EmitWeakReference(Alias, Sym);
723   return false;
724 }
725 
ParseDirectiveSubsection(StringRef,SMLoc)726 bool ELFAsmParser::ParseDirectiveSubsection(StringRef, SMLoc) {
727   const MCExpr *Subsection = nullptr;
728   if (getLexer().isNot(AsmToken::EndOfStatement)) {
729     if (getParser().parseExpression(Subsection))
730      return true;
731   }
732 
733   if (getLexer().isNot(AsmToken::EndOfStatement))
734     return TokError("unexpected token in directive");
735 
736   getStreamer().SubSection(Subsection);
737   return false;
738 }
739 
740 namespace llvm {
741 
createELFAsmParser()742 MCAsmParserExtension *createELFAsmParser() {
743   return new ELFAsmParser;
744 }
745 
746 }
747