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