1 //===- ELFAsmParser.cpp - ELF Assembly Parser -----------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "llvm/ADT/StringRef.h"
10 #include "llvm/ADT/StringSwitch.h"
11 #include "llvm/BinaryFormat/ELF.h"
12 #include "llvm/MC/MCAsmInfo.h"
13 #include "llvm/MC/MCContext.h"
14 #include "llvm/MC/MCDirectives.h"
15 #include "llvm/MC/MCParser/MCAsmLexer.h"
16 #include "llvm/MC/MCParser/MCAsmParser.h"
17 #include "llvm/MC/MCParser/MCAsmParserExtension.h"
18 #include "llvm/MC/MCSectionELF.h"
19 #include "llvm/MC/MCStreamer.h"
20 #include "llvm/MC/MCSymbol.h"
21 #include "llvm/MC/MCSymbolELF.h"
22 #include "llvm/MC/SectionKind.h"
23 #include "llvm/Support/Casting.h"
24 #include "llvm/Support/MathExtras.h"
25 #include "llvm/Support/SMLoc.h"
26 #include <cassert>
27 #include <cstdint>
28 #include <utility>
29 
30 using namespace llvm;
31 
32 namespace {
33 
34 class ELFAsmParser : public MCAsmParserExtension {
35   template<bool (ELFAsmParser::*HandlerMethod)(StringRef, SMLoc)>
36   void addDirectiveHandler(StringRef Directive) {
37     MCAsmParser::ExtensionDirectiveHandler Handler = std::make_pair(
38         this, HandleDirective<ELFAsmParser, HandlerMethod>);
39 
40     getParser().addDirectiveHandler(Directive, Handler);
41   }
42 
43   bool ParseSectionSwitch(StringRef Section, unsigned Type, unsigned Flags,
44                           SectionKind Kind);
45 
46 public:
47   ELFAsmParser() { BracketExpressionsSupported = true; }
48 
49   void Initialize(MCAsmParser &Parser) override {
50     // Call the base implementation.
51     this->MCAsmParserExtension::Initialize(Parser);
52 
53     addDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveData>(".data");
54     addDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveText>(".text");
55     addDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveBSS>(".bss");
56     addDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveRoData>(".rodata");
57     addDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveTData>(".tdata");
58     addDirectiveHandler<&ELFAsmParser::ParseSectionDirectiveTBSS>(".tbss");
59     addDirectiveHandler<
60       &ELFAsmParser::ParseSectionDirectiveDataRel>(".data.rel");
61     addDirectiveHandler<
62       &ELFAsmParser::ParseSectionDirectiveDataRelRo>(".data.rel.ro");
63     addDirectiveHandler<
64       &ELFAsmParser::ParseSectionDirectiveEhFrame>(".eh_frame");
65     addDirectiveHandler<&ELFAsmParser::ParseDirectiveSection>(".section");
66     addDirectiveHandler<
67       &ELFAsmParser::ParseDirectivePushSection>(".pushsection");
68     addDirectiveHandler<&ELFAsmParser::ParseDirectivePopSection>(".popsection");
69     addDirectiveHandler<&ELFAsmParser::ParseDirectiveSize>(".size");
70     addDirectiveHandler<&ELFAsmParser::ParseDirectivePrevious>(".previous");
71     addDirectiveHandler<&ELFAsmParser::ParseDirectiveType>(".type");
72     addDirectiveHandler<&ELFAsmParser::ParseDirectiveIdent>(".ident");
73     addDirectiveHandler<&ELFAsmParser::ParseDirectiveSymver>(".symver");
74     addDirectiveHandler<&ELFAsmParser::ParseDirectiveVersion>(".version");
75     addDirectiveHandler<&ELFAsmParser::ParseDirectiveWeakref>(".weakref");
76     addDirectiveHandler<&ELFAsmParser::ParseDirectiveSymbolAttribute>(".weak");
77     addDirectiveHandler<&ELFAsmParser::ParseDirectiveSymbolAttribute>(".local");
78     addDirectiveHandler<
79       &ELFAsmParser::ParseDirectiveSymbolAttribute>(".protected");
80     addDirectiveHandler<
81       &ELFAsmParser::ParseDirectiveSymbolAttribute>(".internal");
82     addDirectiveHandler<
83       &ELFAsmParser::ParseDirectiveSymbolAttribute>(".hidden");
84     addDirectiveHandler<&ELFAsmParser::ParseDirectiveSubsection>(".subsection");
85     addDirectiveHandler<&ELFAsmParser::ParseDirectiveCGProfile>(".cg_profile");
86   }
87 
88   // FIXME: Part of this logic is duplicated in the MCELFStreamer. What is
89   // the best way for us to get access to it?
90   bool ParseSectionDirectiveData(StringRef, SMLoc) {
91     return ParseSectionSwitch(".data", ELF::SHT_PROGBITS,
92                               ELF::SHF_WRITE | ELF::SHF_ALLOC,
93                               SectionKind::getData());
94   }
95   bool ParseSectionDirectiveText(StringRef, SMLoc) {
96     return ParseSectionSwitch(".text", ELF::SHT_PROGBITS,
97                               ELF::SHF_EXECINSTR |
98                               ELF::SHF_ALLOC, SectionKind::getText());
99   }
100   bool ParseSectionDirectiveBSS(StringRef, SMLoc) {
101     return ParseSectionSwitch(".bss", ELF::SHT_NOBITS,
102                               ELF::SHF_WRITE |
103                               ELF::SHF_ALLOC, SectionKind::getBSS());
104   }
105   bool ParseSectionDirectiveRoData(StringRef, SMLoc) {
106     return ParseSectionSwitch(".rodata", ELF::SHT_PROGBITS,
107                               ELF::SHF_ALLOC,
108                               SectionKind::getReadOnly());
109   }
110   bool ParseSectionDirectiveTData(StringRef, SMLoc) {
111     return ParseSectionSwitch(".tdata", ELF::SHT_PROGBITS,
112                               ELF::SHF_ALLOC |
113                               ELF::SHF_TLS | ELF::SHF_WRITE,
114                               SectionKind::getThreadData());
115   }
116   bool ParseSectionDirectiveTBSS(StringRef, SMLoc) {
117     return ParseSectionSwitch(".tbss", ELF::SHT_NOBITS,
118                               ELF::SHF_ALLOC |
119                               ELF::SHF_TLS | ELF::SHF_WRITE,
120                               SectionKind::getThreadBSS());
121   }
122   bool ParseSectionDirectiveDataRel(StringRef, SMLoc) {
123     return ParseSectionSwitch(".data.rel", ELF::SHT_PROGBITS,
124                               ELF::SHF_ALLOC | ELF::SHF_WRITE,
125                               SectionKind::getData());
126   }
127   bool ParseSectionDirectiveDataRelRo(StringRef, SMLoc) {
128     return ParseSectionSwitch(".data.rel.ro", ELF::SHT_PROGBITS,
129                               ELF::SHF_ALLOC |
130                               ELF::SHF_WRITE,
131                               SectionKind::getReadOnlyWithRel());
132   }
133   bool ParseSectionDirectiveEhFrame(StringRef, SMLoc) {
134     return ParseSectionSwitch(".eh_frame", ELF::SHT_PROGBITS,
135                               ELF::SHF_ALLOC | ELF::SHF_WRITE,
136                               SectionKind::getData());
137   }
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);
150   bool ParseDirectiveCGProfile(StringRef, SMLoc);
151 
152 private:
153   bool ParseSectionName(StringRef &SectionName);
154   bool ParseSectionArguments(bool IsPush, SMLoc loc);
155   unsigned parseSunStyleSectionFlags();
156   bool maybeParseSectionType(StringRef &TypeName);
157   bool parseMergeSize(int64_t &Size);
158   bool parseGroup(StringRef &GroupName, bool &IsComdat);
159   bool parseLinkedToSym(MCSymbolELF *&LinkedToSym);
160   bool maybeParseUniqueID(int64_t &UniqueID);
161 };
162 
163 } // end anonymous namespace
164 
165 /// ParseDirectiveSymbolAttribute
166 ///  ::= { ".local", ".weak", ... } [ identifier ( , identifier )* ]
167 bool ELFAsmParser::ParseDirectiveSymbolAttribute(StringRef Directive, SMLoc) {
168   MCSymbolAttr Attr = StringSwitch<MCSymbolAttr>(Directive)
169     .Case(".weak", MCSA_Weak)
170     .Case(".local", MCSA_Local)
171     .Case(".hidden", MCSA_Hidden)
172     .Case(".internal", MCSA_Internal)
173     .Case(".protected", MCSA_Protected)
174     .Default(MCSA_Invalid);
175   assert(Attr != MCSA_Invalid && "unexpected symbol attribute directive!");
176   if (getLexer().isNot(AsmToken::EndOfStatement)) {
177     while (true) {
178       StringRef Name;
179 
180       if (getParser().parseIdentifier(Name))
181         return TokError("expected identifier in directive");
182 
183       if (getParser().discardLTOSymbol(Name)) {
184         if (getLexer().is(AsmToken::EndOfStatement))
185           break;
186         continue;
187       }
188 
189       MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
190 
191       getStreamer().emitSymbolAttribute(Sym, Attr);
192 
193       if (getLexer().is(AsmToken::EndOfStatement))
194         break;
195 
196       if (getLexer().isNot(AsmToken::Comma))
197         return TokError("unexpected token in directive");
198       Lex();
199     }
200   }
201 
202   Lex();
203   return false;
204 }
205 
206 bool ELFAsmParser::ParseSectionSwitch(StringRef Section, unsigned Type,
207                                       unsigned Flags, SectionKind Kind) {
208   const MCExpr *Subsection = nullptr;
209   if (getLexer().isNot(AsmToken::EndOfStatement)) {
210     if (getParser().parseExpression(Subsection))
211       return true;
212   }
213   Lex();
214 
215   getStreamer().SwitchSection(getContext().getELFSection(Section, Type, Flags),
216                               Subsection);
217 
218   return false;
219 }
220 
221 bool ELFAsmParser::ParseDirectiveSize(StringRef, SMLoc) {
222   StringRef Name;
223   if (getParser().parseIdentifier(Name))
224     return TokError("expected identifier in directive");
225   MCSymbolELF *Sym = cast<MCSymbolELF>(getContext().getOrCreateSymbol(Name));
226 
227   if (getLexer().isNot(AsmToken::Comma))
228     return TokError("unexpected token in directive");
229   Lex();
230 
231   const MCExpr *Expr;
232   if (getParser().parseExpression(Expr))
233     return true;
234 
235   if (getLexer().isNot(AsmToken::EndOfStatement))
236     return TokError("unexpected token in directive");
237   Lex();
238 
239   getStreamer().emitELFSize(Sym, Expr);
240   return false;
241 }
242 
243 bool ELFAsmParser::ParseSectionName(StringRef &SectionName) {
244   // A section name can contain -, so we cannot just use
245   // parseIdentifier.
246   SMLoc FirstLoc = getLexer().getLoc();
247   unsigned Size = 0;
248 
249   if (getLexer().is(AsmToken::String)) {
250     SectionName = getTok().getIdentifier();
251     Lex();
252     return false;
253   }
254 
255   while (!getParser().hasPendingError()) {
256     SMLoc PrevLoc = getLexer().getLoc();
257     if (getLexer().is(AsmToken::Comma) ||
258       getLexer().is(AsmToken::EndOfStatement))
259       break;
260 
261     unsigned CurSize;
262     if (getLexer().is(AsmToken::String)) {
263       CurSize = getTok().getIdentifier().size() + 2;
264       Lex();
265     } else if (getLexer().is(AsmToken::Identifier)) {
266       CurSize = getTok().getIdentifier().size();
267       Lex();
268     } else {
269       CurSize = getTok().getString().size();
270       Lex();
271     }
272     Size += CurSize;
273     SectionName = StringRef(FirstLoc.getPointer(), Size);
274 
275     // Make sure the following token is adjacent.
276     if (PrevLoc.getPointer() + CurSize != getTok().getLoc().getPointer())
277       break;
278   }
279   if (Size == 0)
280     return true;
281 
282   return false;
283 }
284 
285 static unsigned parseSectionFlags(StringRef flagsStr, bool *UseLastGroup) {
286   unsigned flags = 0;
287 
288   // If a valid numerical value is set for the section flag, use it verbatim
289   if (!flagsStr.getAsInteger(0, flags))
290     return flags;
291 
292   for (char i : flagsStr) {
293     switch (i) {
294     case 'a':
295       flags |= ELF::SHF_ALLOC;
296       break;
297     case 'e':
298       flags |= ELF::SHF_EXCLUDE;
299       break;
300     case 'x':
301       flags |= ELF::SHF_EXECINSTR;
302       break;
303     case 'w':
304       flags |= ELF::SHF_WRITE;
305       break;
306     case 'o':
307       flags |= ELF::SHF_LINK_ORDER;
308       break;
309     case 'M':
310       flags |= ELF::SHF_MERGE;
311       break;
312     case 'S':
313       flags |= ELF::SHF_STRINGS;
314       break;
315     case 'T':
316       flags |= ELF::SHF_TLS;
317       break;
318     case 'c':
319       flags |= ELF::XCORE_SHF_CP_SECTION;
320       break;
321     case 'd':
322       flags |= ELF::XCORE_SHF_DP_SECTION;
323       break;
324     case 'y':
325       flags |= ELF::SHF_ARM_PURECODE;
326       break;
327     case 's':
328       flags |= ELF::SHF_HEX_GPREL;
329       break;
330     case 'G':
331       flags |= ELF::SHF_GROUP;
332       break;
333     case 'R':
334       flags |= ELF::SHF_GNU_RETAIN;
335       break;
336     case '?':
337       *UseLastGroup = true;
338       break;
339     default:
340       return -1U;
341     }
342   }
343 
344   return flags;
345 }
346 
347 unsigned ELFAsmParser::parseSunStyleSectionFlags() {
348   unsigned flags = 0;
349   while (getLexer().is(AsmToken::Hash)) {
350     Lex(); // Eat the #.
351 
352     if (!getLexer().is(AsmToken::Identifier))
353       return -1U;
354 
355     StringRef flagId = getTok().getIdentifier();
356     if (flagId == "alloc")
357       flags |= ELF::SHF_ALLOC;
358     else if (flagId == "execinstr")
359       flags |= ELF::SHF_EXECINSTR;
360     else if (flagId == "write")
361       flags |= ELF::SHF_WRITE;
362     else if (flagId == "tls")
363       flags |= ELF::SHF_TLS;
364     else
365       return -1U;
366 
367     Lex(); // Eat the flag.
368 
369     if (!getLexer().is(AsmToken::Comma))
370         break;
371     Lex(); // Eat the comma.
372   }
373   return flags;
374 }
375 
376 
377 bool ELFAsmParser::ParseDirectivePushSection(StringRef s, SMLoc loc) {
378   getStreamer().PushSection();
379 
380   if (ParseSectionArguments(/*IsPush=*/true, loc)) {
381     getStreamer().PopSection();
382     return true;
383   }
384 
385   return false;
386 }
387 
388 bool ELFAsmParser::ParseDirectivePopSection(StringRef, SMLoc) {
389   if (!getStreamer().PopSection())
390     return TokError(".popsection without corresponding .pushsection");
391   return false;
392 }
393 
394 bool ELFAsmParser::ParseDirectiveSection(StringRef, SMLoc loc) {
395   return ParseSectionArguments(/*IsPush=*/false, loc);
396 }
397 
398 bool ELFAsmParser::maybeParseSectionType(StringRef &TypeName) {
399   MCAsmLexer &L = getLexer();
400   if (L.isNot(AsmToken::Comma))
401     return false;
402   Lex();
403   if (L.isNot(AsmToken::At) && L.isNot(AsmToken::Percent) &&
404       L.isNot(AsmToken::String)) {
405     if (L.getAllowAtInIdentifier())
406       return TokError("expected '@<type>', '%<type>' or \"<type>\"");
407     else
408       return TokError("expected '%<type>' or \"<type>\"");
409   }
410   if (!L.is(AsmToken::String))
411     Lex();
412   if (L.is(AsmToken::Integer)) {
413     TypeName = getTok().getString();
414     Lex();
415   } else if (getParser().parseIdentifier(TypeName))
416     return TokError("expected identifier in directive");
417   return false;
418 }
419 
420 bool ELFAsmParser::parseMergeSize(int64_t &Size) {
421   if (getLexer().isNot(AsmToken::Comma))
422     return TokError("expected the entry size");
423   Lex();
424   if (getParser().parseAbsoluteExpression(Size))
425     return true;
426   if (Size <= 0)
427     return TokError("entry size must be positive");
428   return false;
429 }
430 
431 bool ELFAsmParser::parseGroup(StringRef &GroupName, bool &IsComdat) {
432   MCAsmLexer &L = getLexer();
433   if (L.isNot(AsmToken::Comma))
434     return TokError("expected group name");
435   Lex();
436   if (L.is(AsmToken::Integer)) {
437     GroupName = getTok().getString();
438     Lex();
439   } else if (getParser().parseIdentifier(GroupName)) {
440     return TokError("invalid group name");
441   }
442   if (L.is(AsmToken::Comma)) {
443     Lex();
444     StringRef Linkage;
445     if (getParser().parseIdentifier(Linkage))
446       return TokError("invalid linkage");
447     if (Linkage != "comdat")
448       return TokError("Linkage must be 'comdat'");
449     IsComdat = true;
450   } else {
451     IsComdat = false;
452   }
453   return false;
454 }
455 
456 bool ELFAsmParser::parseLinkedToSym(MCSymbolELF *&LinkedToSym) {
457   MCAsmLexer &L = getLexer();
458   if (L.isNot(AsmToken::Comma))
459     return TokError("expected linked-to symbol");
460   Lex();
461   StringRef Name;
462   SMLoc StartLoc = L.getLoc();
463   if (getParser().parseIdentifier(Name)) {
464     if (getParser().getTok().getString() == "0") {
465       getParser().Lex();
466       LinkedToSym = nullptr;
467       return false;
468     }
469     return TokError("invalid linked-to symbol");
470   }
471   LinkedToSym = dyn_cast_or_null<MCSymbolELF>(getContext().lookupSymbol(Name));
472   if (!LinkedToSym || !LinkedToSym->isInSection())
473     return Error(StartLoc, "linked-to symbol is not in a section: " + Name);
474   return false;
475 }
476 
477 bool ELFAsmParser::maybeParseUniqueID(int64_t &UniqueID) {
478   MCAsmLexer &L = getLexer();
479   if (L.isNot(AsmToken::Comma))
480     return false;
481   Lex();
482   StringRef UniqueStr;
483   if (getParser().parseIdentifier(UniqueStr))
484     return TokError("expected identifier in directive");
485   if (UniqueStr != "unique")
486     return TokError("expected 'unique'");
487   if (L.isNot(AsmToken::Comma))
488     return TokError("expected commma");
489   Lex();
490   if (getParser().parseAbsoluteExpression(UniqueID))
491     return true;
492   if (UniqueID < 0)
493     return TokError("unique id must be positive");
494   if (!isUInt<32>(UniqueID) || UniqueID == ~0U)
495     return TokError("unique id is too large");
496   return false;
497 }
498 
499 static bool hasPrefix(StringRef SectionName, StringRef Prefix) {
500   return SectionName.consume_front(Prefix) &&
501          (SectionName.empty() || SectionName[0] == '.');
502 }
503 
504 static bool allowSectionTypeMismatch(const Triple &TT, StringRef SectionName,
505                                      unsigned Type) {
506   if (TT.getArch() == Triple::x86_64) {
507     // x86-64 psABI names SHT_X86_64_UNWIND as the canonical type for .eh_frame,
508     // but GNU as emits SHT_PROGBITS .eh_frame for .cfi_* directives. Don't
509     // error for SHT_PROGBITS .eh_frame
510     return SectionName == ".eh_frame" && Type == ELF::SHT_PROGBITS;
511   }
512   if (TT.isMIPS()) {
513     // MIPS .debug_* sections should have SHT_MIPS_DWARF section type to
514     // distinguish among sections contain DWARF and ECOFF debug formats,
515     // but in assembly files these sections have SHT_PROGBITS type.
516     return SectionName.startswith(".debug_") && Type == ELF::SHT_PROGBITS;
517   }
518   return false;
519 }
520 
521 bool ELFAsmParser::ParseSectionArguments(bool IsPush, SMLoc loc) {
522   StringRef SectionName;
523 
524   if (ParseSectionName(SectionName))
525     return TokError("expected identifier in directive");
526 
527   StringRef TypeName;
528   int64_t Size = 0;
529   StringRef GroupName;
530   bool IsComdat = false;
531   unsigned Flags = 0;
532   unsigned extraFlags = 0;
533   const MCExpr *Subsection = nullptr;
534   bool UseLastGroup = false;
535   MCSymbolELF *LinkedToSym = nullptr;
536   int64_t UniqueID = ~0;
537 
538   // Set the defaults first.
539   if (hasPrefix(SectionName, ".rodata") || SectionName == ".rodata1")
540     Flags |= ELF::SHF_ALLOC;
541   else if (SectionName == ".fini" || SectionName == ".init" ||
542            hasPrefix(SectionName, ".text"))
543     Flags |= ELF::SHF_ALLOC | ELF::SHF_EXECINSTR;
544   else if (hasPrefix(SectionName, ".data") || SectionName == ".data1" ||
545            hasPrefix(SectionName, ".bss") ||
546            hasPrefix(SectionName, ".init_array") ||
547            hasPrefix(SectionName, ".fini_array") ||
548            hasPrefix(SectionName, ".preinit_array"))
549     Flags |= ELF::SHF_ALLOC | ELF::SHF_WRITE;
550   else if (hasPrefix(SectionName, ".tdata") || hasPrefix(SectionName, ".tbss"))
551     Flags |= ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_TLS;
552 
553   if (getLexer().is(AsmToken::Comma)) {
554     Lex();
555 
556     if (IsPush && getLexer().isNot(AsmToken::String)) {
557       if (getParser().parseExpression(Subsection))
558         return true;
559       if (getLexer().isNot(AsmToken::Comma))
560         goto EndStmt;
561       Lex();
562     }
563 
564     if (getLexer().isNot(AsmToken::String)) {
565       if (!getContext().getAsmInfo()->usesSunStyleELFSectionSwitchSyntax()
566           || getLexer().isNot(AsmToken::Hash))
567         return TokError("expected string in directive");
568       extraFlags = parseSunStyleSectionFlags();
569     } else {
570       StringRef FlagsStr = getTok().getStringContents();
571       Lex();
572       extraFlags = parseSectionFlags(FlagsStr, &UseLastGroup);
573     }
574 
575     if (extraFlags == -1U)
576       return TokError("unknown flag");
577     Flags |= extraFlags;
578 
579     bool Mergeable = Flags & ELF::SHF_MERGE;
580     bool Group = Flags & ELF::SHF_GROUP;
581     if (Group && UseLastGroup)
582       return TokError("Section cannot specifiy a group name while also acting "
583                       "as a member of the last group");
584 
585     if (maybeParseSectionType(TypeName))
586       return true;
587 
588     MCAsmLexer &L = getLexer();
589     if (TypeName.empty()) {
590       if (Mergeable)
591         return TokError("Mergeable section must specify the type");
592       if (Group)
593         return TokError("Group section must specify the type");
594       if (L.isNot(AsmToken::EndOfStatement))
595         return TokError("unexpected token in directive");
596     }
597 
598     if (Mergeable)
599       if (parseMergeSize(Size))
600         return true;
601     if (Group)
602       if (parseGroup(GroupName, IsComdat))
603         return true;
604     if (Flags & ELF::SHF_LINK_ORDER)
605       if (parseLinkedToSym(LinkedToSym))
606         return true;
607     if (maybeParseUniqueID(UniqueID))
608       return true;
609   }
610 
611 EndStmt:
612   if (getLexer().isNot(AsmToken::EndOfStatement))
613     return TokError("unexpected token in directive");
614   Lex();
615 
616   unsigned Type = ELF::SHT_PROGBITS;
617 
618   if (TypeName.empty()) {
619     if (SectionName.startswith(".note"))
620       Type = ELF::SHT_NOTE;
621     else if (hasPrefix(SectionName, ".init_array"))
622       Type = ELF::SHT_INIT_ARRAY;
623     else if (hasPrefix(SectionName, ".bss"))
624       Type = ELF::SHT_NOBITS;
625     else if (hasPrefix(SectionName, ".tbss"))
626       Type = ELF::SHT_NOBITS;
627     else if (hasPrefix(SectionName, ".fini_array"))
628       Type = ELF::SHT_FINI_ARRAY;
629     else if (hasPrefix(SectionName, ".preinit_array"))
630       Type = ELF::SHT_PREINIT_ARRAY;
631   } else {
632     if (TypeName == "init_array")
633       Type = ELF::SHT_INIT_ARRAY;
634     else if (TypeName == "fini_array")
635       Type = ELF::SHT_FINI_ARRAY;
636     else if (TypeName == "preinit_array")
637       Type = ELF::SHT_PREINIT_ARRAY;
638     else if (TypeName == "nobits")
639       Type = ELF::SHT_NOBITS;
640     else if (TypeName == "progbits")
641       Type = ELF::SHT_PROGBITS;
642     else if (TypeName == "note")
643       Type = ELF::SHT_NOTE;
644     else if (TypeName == "unwind")
645       Type = ELF::SHT_X86_64_UNWIND;
646     else if (TypeName == "llvm_odrtab")
647       Type = ELF::SHT_LLVM_ODRTAB;
648     else if (TypeName == "llvm_linker_options")
649       Type = ELF::SHT_LLVM_LINKER_OPTIONS;
650     else if (TypeName == "llvm_call_graph_profile")
651       Type = ELF::SHT_LLVM_CALL_GRAPH_PROFILE;
652     else if (TypeName == "llvm_dependent_libraries")
653       Type = ELF::SHT_LLVM_DEPENDENT_LIBRARIES;
654     else if (TypeName == "llvm_sympart")
655       Type = ELF::SHT_LLVM_SYMPART;
656     else if (TypeName == "llvm_bb_addr_map")
657       Type = ELF::SHT_LLVM_BB_ADDR_MAP;
658     else if (TypeName.getAsInteger(0, Type))
659       return TokError("unknown section type");
660   }
661 
662   if (UseLastGroup) {
663     MCSectionSubPair CurrentSection = getStreamer().getCurrentSection();
664     if (const MCSectionELF *Section =
665             cast_or_null<MCSectionELF>(CurrentSection.first))
666       if (const MCSymbol *Group = Section->getGroup()) {
667         GroupName = Group->getName();
668         IsComdat = Section->isComdat();
669         Flags |= ELF::SHF_GROUP;
670       }
671   }
672 
673   MCSectionELF *Section =
674       getContext().getELFSection(SectionName, Type, Flags, Size, GroupName,
675                                  IsComdat, UniqueID, LinkedToSym);
676   getStreamer().SwitchSection(Section, Subsection);
677   // Check that flags are used consistently. However, the GNU assembler permits
678   // to leave out in subsequent uses of the same sections; for compatibility,
679   // do likewise.
680   if (!TypeName.empty() && Section->getType() != Type &&
681       !allowSectionTypeMismatch(getContext().getTargetTriple(), SectionName,
682                                 Type))
683     Error(loc, "changed section type for " + SectionName + ", expected: 0x" +
684                    utohexstr(Section->getType()));
685   if ((extraFlags || Size || !TypeName.empty()) && Section->getFlags() != Flags)
686     Error(loc, "changed section flags for " + SectionName + ", expected: 0x" +
687                    utohexstr(Section->getFlags()));
688   if ((extraFlags || Size || !TypeName.empty()) &&
689       Section->getEntrySize() != Size)
690     Error(loc, "changed section entsize for " + SectionName +
691                    ", expected: " + Twine(Section->getEntrySize()));
692 
693   if (getContext().getGenDwarfForAssembly() &&
694       (Section->getFlags() & ELF::SHF_ALLOC) &&
695       (Section->getFlags() & ELF::SHF_EXECINSTR)) {
696     bool InsertResult = getContext().addGenDwarfSection(Section);
697     if (InsertResult) {
698       if (getContext().getDwarfVersion() <= 2)
699         Warning(loc, "DWARF2 only supports one section per compilation unit");
700 
701       if (!Section->getBeginSymbol()) {
702         MCSymbol *SectionStartSymbol = getContext().createTempSymbol();
703         getStreamer().emitLabel(SectionStartSymbol);
704         Section->setBeginSymbol(SectionStartSymbol);
705       }
706     }
707   }
708 
709   return false;
710 }
711 
712 bool ELFAsmParser::ParseDirectivePrevious(StringRef DirName, SMLoc) {
713   MCSectionSubPair PreviousSection = getStreamer().getPreviousSection();
714   if (PreviousSection.first == nullptr)
715       return TokError(".previous without corresponding .section");
716   getStreamer().SwitchSection(PreviousSection.first, PreviousSection.second);
717 
718   return false;
719 }
720 
721 static MCSymbolAttr MCAttrForString(StringRef Type) {
722   return StringSwitch<MCSymbolAttr>(Type)
723           .Cases("STT_FUNC", "function", MCSA_ELF_TypeFunction)
724           .Cases("STT_OBJECT", "object", MCSA_ELF_TypeObject)
725           .Cases("STT_TLS", "tls_object", MCSA_ELF_TypeTLS)
726           .Cases("STT_COMMON", "common", MCSA_ELF_TypeCommon)
727           .Cases("STT_NOTYPE", "notype", MCSA_ELF_TypeNoType)
728           .Cases("STT_GNU_IFUNC", "gnu_indirect_function",
729                  MCSA_ELF_TypeIndFunction)
730           .Case("gnu_unique_object", MCSA_ELF_TypeGnuUniqueObject)
731           .Default(MCSA_Invalid);
732 }
733 
734 /// ParseDirectiveELFType
735 ///  ::= .type identifier , STT_<TYPE_IN_UPPER_CASE>
736 ///  ::= .type identifier , #attribute
737 ///  ::= .type identifier , @attribute
738 ///  ::= .type identifier , %attribute
739 ///  ::= .type identifier , "attribute"
740 bool ELFAsmParser::ParseDirectiveType(StringRef, SMLoc) {
741   StringRef Name;
742   if (getParser().parseIdentifier(Name))
743     return TokError("expected identifier in directive");
744 
745   // Handle the identifier as the key symbol.
746   MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
747 
748   // NOTE the comma is optional in all cases.  It is only documented as being
749   // optional in the first case, however, GAS will silently treat the comma as
750   // optional in all cases.  Furthermore, although the documentation states that
751   // the first form only accepts STT_<TYPE_IN_UPPER_CASE>, in reality, GAS
752   // accepts both the upper case name as well as the lower case aliases.
753   if (getLexer().is(AsmToken::Comma))
754     Lex();
755 
756   if (getLexer().isNot(AsmToken::Identifier) &&
757       getLexer().isNot(AsmToken::Hash) &&
758       getLexer().isNot(AsmToken::Percent) &&
759       getLexer().isNot(AsmToken::String)) {
760     if (!getLexer().getAllowAtInIdentifier())
761       return TokError("expected STT_<TYPE_IN_UPPER_CASE>, '#<type>', "
762                       "'%<type>' or \"<type>\"");
763     else if (getLexer().isNot(AsmToken::At))
764       return TokError("expected STT_<TYPE_IN_UPPER_CASE>, '#<type>', '@<type>', "
765                       "'%<type>' or \"<type>\"");
766   }
767 
768   if (getLexer().isNot(AsmToken::String) &&
769       getLexer().isNot(AsmToken::Identifier))
770     Lex();
771 
772   SMLoc TypeLoc = getLexer().getLoc();
773 
774   StringRef Type;
775   if (getParser().parseIdentifier(Type))
776     return TokError("expected symbol type in directive");
777 
778   MCSymbolAttr Attr = MCAttrForString(Type);
779   if (Attr == MCSA_Invalid)
780     return Error(TypeLoc, "unsupported attribute in '.type' directive");
781 
782   if (getLexer().isNot(AsmToken::EndOfStatement))
783     return TokError("unexpected token in '.type' directive");
784   Lex();
785 
786   getStreamer().emitSymbolAttribute(Sym, Attr);
787 
788   return false;
789 }
790 
791 /// ParseDirectiveIdent
792 ///  ::= .ident string
793 bool ELFAsmParser::ParseDirectiveIdent(StringRef, SMLoc) {
794   if (getLexer().isNot(AsmToken::String))
795     return TokError("unexpected token in '.ident' directive");
796 
797   StringRef Data = getTok().getIdentifier();
798 
799   Lex();
800 
801   if (getLexer().isNot(AsmToken::EndOfStatement))
802     return TokError("unexpected token in '.ident' directive");
803   Lex();
804 
805   getStreamer().emitIdent(Data);
806   return false;
807 }
808 
809 /// ParseDirectiveSymver
810 ///  ::= .symver foo, bar2@zed
811 bool ELFAsmParser::ParseDirectiveSymver(StringRef, SMLoc) {
812   StringRef OriginalName, Name, Action;
813   if (getParser().parseIdentifier(OriginalName))
814     return TokError("expected identifier in directive");
815 
816   if (getLexer().isNot(AsmToken::Comma))
817     return TokError("expected a comma");
818 
819   // ARM assembly uses @ for a comment...
820   // except when parsing the second parameter of the .symver directive.
821   // Force the next symbol to allow @ in the identifier, which is
822   // required for this directive and then reset it to its initial state.
823   const bool AllowAtInIdentifier = getLexer().getAllowAtInIdentifier();
824   getLexer().setAllowAtInIdentifier(true);
825   Lex();
826   getLexer().setAllowAtInIdentifier(AllowAtInIdentifier);
827 
828   if (getParser().parseIdentifier(Name))
829     return TokError("expected identifier in directive");
830 
831   if (!Name.contains('@'))
832     return TokError("expected a '@' in the name");
833   bool KeepOriginalSym = !Name.contains("@@@");
834   if (parseOptionalToken(AsmToken::Comma)) {
835     if (getParser().parseIdentifier(Action) || Action != "remove")
836       return TokError("expected 'remove'");
837     KeepOriginalSym = false;
838   }
839   (void)parseOptionalToken(AsmToken::EndOfStatement);
840 
841   getStreamer().emitELFSymverDirective(
842       getContext().getOrCreateSymbol(OriginalName), Name, KeepOriginalSym);
843   return false;
844 }
845 
846 /// ParseDirectiveVersion
847 ///  ::= .version string
848 bool ELFAsmParser::ParseDirectiveVersion(StringRef, SMLoc) {
849   if (getLexer().isNot(AsmToken::String))
850     return TokError("unexpected token in '.version' directive");
851 
852   StringRef Data = getTok().getIdentifier();
853 
854   Lex();
855 
856   MCSection *Note = getContext().getELFSection(".note", ELF::SHT_NOTE, 0);
857 
858   getStreamer().PushSection();
859   getStreamer().SwitchSection(Note);
860   getStreamer().emitInt32(Data.size() + 1); // namesz
861   getStreamer().emitInt32(0);               // descsz = 0 (no description).
862   getStreamer().emitInt32(1);               // type = NT_VERSION
863   getStreamer().emitBytes(Data);            // name
864   getStreamer().emitInt8(0);                // NUL
865   getStreamer().emitValueToAlignment(4);
866   getStreamer().PopSection();
867   return false;
868 }
869 
870 /// ParseDirectiveWeakref
871 ///  ::= .weakref foo, bar
872 bool ELFAsmParser::ParseDirectiveWeakref(StringRef, SMLoc) {
873   // FIXME: Share code with the other alias building directives.
874 
875   StringRef AliasName;
876   if (getParser().parseIdentifier(AliasName))
877     return TokError("expected identifier in directive");
878 
879   if (getLexer().isNot(AsmToken::Comma))
880     return TokError("expected a comma");
881 
882   Lex();
883 
884   StringRef Name;
885   if (getParser().parseIdentifier(Name))
886     return TokError("expected identifier in directive");
887 
888   MCSymbol *Alias = getContext().getOrCreateSymbol(AliasName);
889 
890   MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
891 
892   getStreamer().emitWeakReference(Alias, Sym);
893   return false;
894 }
895 
896 bool ELFAsmParser::ParseDirectiveSubsection(StringRef, SMLoc) {
897   const MCExpr *Subsection = nullptr;
898   if (getLexer().isNot(AsmToken::EndOfStatement)) {
899     if (getParser().parseExpression(Subsection))
900      return true;
901   }
902 
903   if (getLexer().isNot(AsmToken::EndOfStatement))
904     return TokError("unexpected token in directive");
905 
906   Lex();
907 
908   getStreamer().SubSection(Subsection);
909   return false;
910 }
911 
912 bool ELFAsmParser::ParseDirectiveCGProfile(StringRef S, SMLoc Loc) {
913   return MCAsmParserExtension::ParseDirectiveCGProfile(S, Loc);
914 }
915 
916 namespace llvm {
917 
918 MCAsmParserExtension *createELFAsmParser() {
919   return new ELFAsmParser;
920 }
921 
922 } // end namespace llvm
923