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 'R':
330       flags |= ELF::SHF_GNU_RETAIN;
331       break;
332     case '?':
333       *UseLastGroup = true;
334       break;
335     default:
336       return -1U;
337     }
338   }
339 
340   return flags;
341 }
342 
343 unsigned ELFAsmParser::parseSunStyleSectionFlags() {
344   unsigned flags = 0;
345   while (getLexer().is(AsmToken::Hash)) {
346     Lex(); // Eat the #.
347 
348     if (!getLexer().is(AsmToken::Identifier))
349       return -1U;
350 
351     StringRef flagId = getTok().getIdentifier();
352     if (flagId == "alloc")
353       flags |= ELF::SHF_ALLOC;
354     else if (flagId == "execinstr")
355       flags |= ELF::SHF_EXECINSTR;
356     else if (flagId == "write")
357       flags |= ELF::SHF_WRITE;
358     else if (flagId == "tls")
359       flags |= ELF::SHF_TLS;
360     else
361       return -1U;
362 
363     Lex(); // Eat the flag.
364 
365     if (!getLexer().is(AsmToken::Comma))
366         break;
367     Lex(); // Eat the comma.
368   }
369   return flags;
370 }
371 
372 
373 bool ELFAsmParser::ParseDirectivePushSection(StringRef s, SMLoc loc) {
374   getStreamer().PushSection();
375 
376   if (ParseSectionArguments(/*IsPush=*/true, loc)) {
377     getStreamer().PopSection();
378     return true;
379   }
380 
381   return false;
382 }
383 
384 bool ELFAsmParser::ParseDirectivePopSection(StringRef, SMLoc) {
385   if (!getStreamer().PopSection())
386     return TokError(".popsection without corresponding .pushsection");
387   return false;
388 }
389 
390 bool ELFAsmParser::ParseDirectiveSection(StringRef, SMLoc loc) {
391   return ParseSectionArguments(/*IsPush=*/false, loc);
392 }
393 
394 bool ELFAsmParser::maybeParseSectionType(StringRef &TypeName) {
395   MCAsmLexer &L = getLexer();
396   if (L.isNot(AsmToken::Comma))
397     return false;
398   Lex();
399   if (L.isNot(AsmToken::At) && L.isNot(AsmToken::Percent) &&
400       L.isNot(AsmToken::String)) {
401     if (L.getAllowAtInIdentifier())
402       return TokError("expected '@<type>', '%<type>' or \"<type>\"");
403     else
404       return TokError("expected '%<type>' or \"<type>\"");
405   }
406   if (!L.is(AsmToken::String))
407     Lex();
408   if (L.is(AsmToken::Integer)) {
409     TypeName = getTok().getString();
410     Lex();
411   } else if (getParser().parseIdentifier(TypeName))
412     return TokError("expected identifier in directive");
413   return false;
414 }
415 
416 bool ELFAsmParser::parseMergeSize(int64_t &Size) {
417   if (getLexer().isNot(AsmToken::Comma))
418     return TokError("expected the entry size");
419   Lex();
420   if (getParser().parseAbsoluteExpression(Size))
421     return true;
422   if (Size <= 0)
423     return TokError("entry size must be positive");
424   return false;
425 }
426 
427 bool ELFAsmParser::parseGroup(StringRef &GroupName) {
428   MCAsmLexer &L = getLexer();
429   if (L.isNot(AsmToken::Comma))
430     return TokError("expected group name");
431   Lex();
432   if (L.is(AsmToken::Integer)) {
433     GroupName = getTok().getString();
434     Lex();
435   } else if (getParser().parseIdentifier(GroupName)) {
436     return TokError("invalid group name");
437   }
438   if (L.is(AsmToken::Comma)) {
439     Lex();
440     StringRef Linkage;
441     if (getParser().parseIdentifier(Linkage))
442       return TokError("invalid linkage");
443     if (Linkage != "comdat")
444       return TokError("Linkage must be 'comdat'");
445   }
446   return false;
447 }
448 
449 bool ELFAsmParser::parseLinkedToSym(MCSymbolELF *&LinkedToSym) {
450   MCAsmLexer &L = getLexer();
451   if (L.isNot(AsmToken::Comma))
452     return TokError("expected linked-to symbol");
453   Lex();
454   StringRef Name;
455   SMLoc StartLoc = L.getLoc();
456   if (getParser().parseIdentifier(Name)) {
457     if (getParser().getTok().getString() == "0") {
458       getParser().Lex();
459       LinkedToSym = nullptr;
460       return false;
461     }
462     return TokError("invalid linked-to symbol");
463   }
464   LinkedToSym = dyn_cast_or_null<MCSymbolELF>(getContext().lookupSymbol(Name));
465   if (!LinkedToSym || !LinkedToSym->isInSection())
466     return Error(StartLoc, "linked-to symbol is not in a section: " + Name);
467   return false;
468 }
469 
470 bool ELFAsmParser::maybeParseUniqueID(int64_t &UniqueID) {
471   MCAsmLexer &L = getLexer();
472   if (L.isNot(AsmToken::Comma))
473     return false;
474   Lex();
475   StringRef UniqueStr;
476   if (getParser().parseIdentifier(UniqueStr))
477     return TokError("expected identifier in directive");
478   if (UniqueStr != "unique")
479     return TokError("expected 'unique'");
480   if (L.isNot(AsmToken::Comma))
481     return TokError("expected commma");
482   Lex();
483   if (getParser().parseAbsoluteExpression(UniqueID))
484     return true;
485   if (UniqueID < 0)
486     return TokError("unique id must be positive");
487   if (!isUInt<32>(UniqueID) || UniqueID == ~0U)
488     return TokError("unique id is too large");
489   return false;
490 }
491 
492 static bool hasPrefix(StringRef SectionName, StringRef Prefix) {
493   return SectionName.startswith(Prefix) || SectionName == Prefix.drop_back();
494 }
495 
496 bool ELFAsmParser::ParseSectionArguments(bool IsPush, SMLoc loc) {
497   StringRef SectionName;
498 
499   if (ParseSectionName(SectionName))
500     return TokError("expected identifier in directive");
501 
502   StringRef TypeName;
503   int64_t Size = 0;
504   StringRef GroupName;
505   unsigned Flags = 0;
506   unsigned extraFlags = 0;
507   const MCExpr *Subsection = nullptr;
508   bool UseLastGroup = false;
509   MCSymbolELF *LinkedToSym = nullptr;
510   int64_t UniqueID = ~0;
511 
512   // Set the defaults first.
513   if (hasPrefix(SectionName, ".rodata.") || SectionName == ".rodata1")
514     Flags |= ELF::SHF_ALLOC;
515   else if (SectionName == ".fini" || SectionName == ".init" ||
516            hasPrefix(SectionName, ".text."))
517     Flags |= ELF::SHF_ALLOC | ELF::SHF_EXECINSTR;
518   else if (hasPrefix(SectionName, ".data.") || SectionName == ".data1" ||
519            hasPrefix(SectionName, ".bss.") ||
520            hasPrefix(SectionName, ".init_array.") ||
521            hasPrefix(SectionName, ".fini_array.") ||
522            hasPrefix(SectionName, ".preinit_array."))
523     Flags |= ELF::SHF_ALLOC | ELF::SHF_WRITE;
524   else if (hasPrefix(SectionName, ".tdata.") ||
525            hasPrefix(SectionName, ".tbss."))
526     Flags |= ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_TLS;
527 
528   if (getLexer().is(AsmToken::Comma)) {
529     Lex();
530 
531     if (IsPush && getLexer().isNot(AsmToken::String)) {
532       if (getParser().parseExpression(Subsection))
533         return true;
534       if (getLexer().isNot(AsmToken::Comma))
535         goto EndStmt;
536       Lex();
537     }
538 
539     if (getLexer().isNot(AsmToken::String)) {
540       if (!getContext().getAsmInfo()->usesSunStyleELFSectionSwitchSyntax()
541           || getLexer().isNot(AsmToken::Hash))
542         return TokError("expected string in directive");
543       extraFlags = parseSunStyleSectionFlags();
544     } else {
545       StringRef FlagsStr = getTok().getStringContents();
546       Lex();
547       extraFlags = parseSectionFlags(FlagsStr, &UseLastGroup);
548     }
549 
550     if (extraFlags == -1U)
551       return TokError("unknown flag");
552     Flags |= extraFlags;
553 
554     bool Mergeable = Flags & ELF::SHF_MERGE;
555     bool Group = Flags & ELF::SHF_GROUP;
556     if (Group && UseLastGroup)
557       return TokError("Section cannot specifiy a group name while also acting "
558                       "as a member of the last group");
559 
560     if (maybeParseSectionType(TypeName))
561       return true;
562 
563     MCAsmLexer &L = getLexer();
564     if (TypeName.empty()) {
565       if (Mergeable)
566         return TokError("Mergeable section must specify the type");
567       if (Group)
568         return TokError("Group section must specify the type");
569       if (L.isNot(AsmToken::EndOfStatement))
570         return TokError("unexpected token in directive");
571     }
572 
573     if (Mergeable)
574       if (parseMergeSize(Size))
575         return true;
576     if (Group)
577       if (parseGroup(GroupName))
578         return true;
579     if (Flags & ELF::SHF_LINK_ORDER)
580       if (parseLinkedToSym(LinkedToSym))
581         return true;
582     if (maybeParseUniqueID(UniqueID))
583       return true;
584   }
585 
586 EndStmt:
587   if (getLexer().isNot(AsmToken::EndOfStatement))
588     return TokError("unexpected token in directive");
589   Lex();
590 
591   unsigned Type = ELF::SHT_PROGBITS;
592 
593   if (TypeName.empty()) {
594     if (SectionName.startswith(".note"))
595       Type = ELF::SHT_NOTE;
596     else if (hasPrefix(SectionName, ".init_array."))
597       Type = ELF::SHT_INIT_ARRAY;
598     else if (hasPrefix(SectionName, ".bss."))
599       Type = ELF::SHT_NOBITS;
600     else if (hasPrefix(SectionName, ".tbss."))
601       Type = ELF::SHT_NOBITS;
602     else if (hasPrefix(SectionName, ".fini_array."))
603       Type = ELF::SHT_FINI_ARRAY;
604     else if (hasPrefix(SectionName, ".preinit_array."))
605       Type = ELF::SHT_PREINIT_ARRAY;
606   } else {
607     if (TypeName == "init_array")
608       Type = ELF::SHT_INIT_ARRAY;
609     else if (TypeName == "fini_array")
610       Type = ELF::SHT_FINI_ARRAY;
611     else if (TypeName == "preinit_array")
612       Type = ELF::SHT_PREINIT_ARRAY;
613     else if (TypeName == "nobits")
614       Type = ELF::SHT_NOBITS;
615     else if (TypeName == "progbits")
616       Type = ELF::SHT_PROGBITS;
617     else if (TypeName == "note")
618       Type = ELF::SHT_NOTE;
619     else if (TypeName == "unwind")
620       Type = ELF::SHT_X86_64_UNWIND;
621     else if (TypeName == "llvm_odrtab")
622       Type = ELF::SHT_LLVM_ODRTAB;
623     else if (TypeName == "llvm_linker_options")
624       Type = ELF::SHT_LLVM_LINKER_OPTIONS;
625     else if (TypeName == "llvm_call_graph_profile")
626       Type = ELF::SHT_LLVM_CALL_GRAPH_PROFILE;
627     else if (TypeName == "llvm_dependent_libraries")
628       Type = ELF::SHT_LLVM_DEPENDENT_LIBRARIES;
629     else if (TypeName == "llvm_sympart")
630       Type = ELF::SHT_LLVM_SYMPART;
631     else if (TypeName == "llvm_bb_addr_map")
632       Type = ELF::SHT_LLVM_BB_ADDR_MAP;
633     else if (TypeName.getAsInteger(0, Type))
634       return TokError("unknown section type");
635   }
636 
637   if (UseLastGroup) {
638     MCSectionSubPair CurrentSection = getStreamer().getCurrentSection();
639     if (const MCSectionELF *Section =
640             cast_or_null<MCSectionELF>(CurrentSection.first))
641       if (const MCSymbol *Group = Section->getGroup()) {
642         GroupName = Group->getName();
643         Flags |= ELF::SHF_GROUP;
644       }
645   }
646 
647   MCSectionELF *Section = getContext().getELFSection(
648       SectionName, Type, Flags, Size, GroupName, UniqueID, LinkedToSym);
649   getStreamer().SwitchSection(Section, Subsection);
650   // x86-64 psABI names SHT_X86_64_UNWIND as the canonical type for .eh_frame,
651   // but GNU as emits SHT_PROGBITS .eh_frame for .cfi_* directives. Don't error
652   // for SHT_PROGBITS .eh_frame
653   if (Section->getType() != Type &&
654       !(SectionName == ".eh_frame" && Type == ELF::SHT_PROGBITS))
655     Error(loc, "changed section type for " + SectionName + ", expected: 0x" +
656                    utohexstr(Section->getType()));
657   // Check that flags are used consistently. However, the GNU assembler permits
658   // to leave out in subsequent uses of the same sections; for compatibility,
659   // do likewise.
660   if ((extraFlags || Size || !TypeName.empty()) && Section->getFlags() != Flags)
661     Error(loc, "changed section flags for " + SectionName + ", expected: 0x" +
662                    utohexstr(Section->getFlags()));
663   if ((extraFlags || Size || !TypeName.empty()) &&
664       Section->getEntrySize() != Size)
665     Error(loc, "changed section entsize for " + SectionName +
666                    ", expected: " + Twine(Section->getEntrySize()));
667 
668   if (getContext().getGenDwarfForAssembly() &&
669       (Section->getFlags() & ELF::SHF_ALLOC) &&
670       (Section->getFlags() & ELF::SHF_EXECINSTR)) {
671     bool InsertResult = getContext().addGenDwarfSection(Section);
672     if (InsertResult) {
673       if (getContext().getDwarfVersion() <= 2)
674         Warning(loc, "DWARF2 only supports one section per compilation unit");
675 
676       if (!Section->getBeginSymbol()) {
677         MCSymbol *SectionStartSymbol = getContext().createTempSymbol();
678         getStreamer().emitLabel(SectionStartSymbol);
679         Section->setBeginSymbol(SectionStartSymbol);
680       }
681     }
682   }
683 
684   return false;
685 }
686 
687 bool ELFAsmParser::ParseDirectivePrevious(StringRef DirName, SMLoc) {
688   MCSectionSubPair PreviousSection = getStreamer().getPreviousSection();
689   if (PreviousSection.first == nullptr)
690       return TokError(".previous without corresponding .section");
691   getStreamer().SwitchSection(PreviousSection.first, PreviousSection.second);
692 
693   return false;
694 }
695 
696 static MCSymbolAttr MCAttrForString(StringRef Type) {
697   return StringSwitch<MCSymbolAttr>(Type)
698           .Cases("STT_FUNC", "function", MCSA_ELF_TypeFunction)
699           .Cases("STT_OBJECT", "object", MCSA_ELF_TypeObject)
700           .Cases("STT_TLS", "tls_object", MCSA_ELF_TypeTLS)
701           .Cases("STT_COMMON", "common", MCSA_ELF_TypeCommon)
702           .Cases("STT_NOTYPE", "notype", MCSA_ELF_TypeNoType)
703           .Cases("STT_GNU_IFUNC", "gnu_indirect_function",
704                  MCSA_ELF_TypeIndFunction)
705           .Case("gnu_unique_object", MCSA_ELF_TypeGnuUniqueObject)
706           .Default(MCSA_Invalid);
707 }
708 
709 /// ParseDirectiveELFType
710 ///  ::= .type identifier , STT_<TYPE_IN_UPPER_CASE>
711 ///  ::= .type identifier , #attribute
712 ///  ::= .type identifier , @attribute
713 ///  ::= .type identifier , %attribute
714 ///  ::= .type identifier , "attribute"
715 bool ELFAsmParser::ParseDirectiveType(StringRef, SMLoc) {
716   StringRef Name;
717   if (getParser().parseIdentifier(Name))
718     return TokError("expected identifier in directive");
719 
720   // Handle the identifier as the key symbol.
721   MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
722 
723   // NOTE the comma is optional in all cases.  It is only documented as being
724   // optional in the first case, however, GAS will silently treat the comma as
725   // optional in all cases.  Furthermore, although the documentation states that
726   // the first form only accepts STT_<TYPE_IN_UPPER_CASE>, in reality, GAS
727   // accepts both the upper case name as well as the lower case aliases.
728   if (getLexer().is(AsmToken::Comma))
729     Lex();
730 
731   if (getLexer().isNot(AsmToken::Identifier) &&
732       getLexer().isNot(AsmToken::Hash) &&
733       getLexer().isNot(AsmToken::Percent) &&
734       getLexer().isNot(AsmToken::String)) {
735     if (!getLexer().getAllowAtInIdentifier())
736       return TokError("expected STT_<TYPE_IN_UPPER_CASE>, '#<type>', "
737                       "'%<type>' or \"<type>\"");
738     else if (getLexer().isNot(AsmToken::At))
739       return TokError("expected STT_<TYPE_IN_UPPER_CASE>, '#<type>', '@<type>', "
740                       "'%<type>' or \"<type>\"");
741   }
742 
743   if (getLexer().isNot(AsmToken::String) &&
744       getLexer().isNot(AsmToken::Identifier))
745     Lex();
746 
747   SMLoc TypeLoc = getLexer().getLoc();
748 
749   StringRef Type;
750   if (getParser().parseIdentifier(Type))
751     return TokError("expected symbol type in directive");
752 
753   MCSymbolAttr Attr = MCAttrForString(Type);
754   if (Attr == MCSA_Invalid)
755     return Error(TypeLoc, "unsupported attribute in '.type' directive");
756 
757   if (getLexer().isNot(AsmToken::EndOfStatement))
758     return TokError("unexpected token in '.type' directive");
759   Lex();
760 
761   getStreamer().emitSymbolAttribute(Sym, Attr);
762 
763   return false;
764 }
765 
766 /// ParseDirectiveIdent
767 ///  ::= .ident string
768 bool ELFAsmParser::ParseDirectiveIdent(StringRef, SMLoc) {
769   if (getLexer().isNot(AsmToken::String))
770     return TokError("unexpected token in '.ident' directive");
771 
772   StringRef Data = getTok().getIdentifier();
773 
774   Lex();
775 
776   if (getLexer().isNot(AsmToken::EndOfStatement))
777     return TokError("unexpected token in '.ident' directive");
778   Lex();
779 
780   getStreamer().emitIdent(Data);
781   return false;
782 }
783 
784 /// ParseDirectiveSymver
785 ///  ::= .symver foo, bar2@zed
786 bool ELFAsmParser::ParseDirectiveSymver(StringRef, SMLoc) {
787   StringRef Name;
788   if (getParser().parseIdentifier(Name))
789     return TokError("expected identifier in directive");
790 
791   if (getLexer().isNot(AsmToken::Comma))
792     return TokError("expected a comma");
793 
794   // ARM assembly uses @ for a comment...
795   // except when parsing the second parameter of the .symver directive.
796   // Force the next symbol to allow @ in the identifier, which is
797   // required for this directive and then reset it to its initial state.
798   const bool AllowAtInIdentifier = getLexer().getAllowAtInIdentifier();
799   getLexer().setAllowAtInIdentifier(true);
800   Lex();
801   getLexer().setAllowAtInIdentifier(AllowAtInIdentifier);
802 
803   StringRef AliasName;
804   if (getParser().parseIdentifier(AliasName))
805     return TokError("expected identifier in directive");
806 
807   if (AliasName.find('@') == StringRef::npos)
808     return TokError("expected a '@' in the name");
809 
810   MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
811   getStreamer().emitELFSymverDirective(AliasName, Sym);
812   return false;
813 }
814 
815 /// ParseDirectiveVersion
816 ///  ::= .version string
817 bool ELFAsmParser::ParseDirectiveVersion(StringRef, SMLoc) {
818   if (getLexer().isNot(AsmToken::String))
819     return TokError("unexpected token in '.version' directive");
820 
821   StringRef Data = getTok().getIdentifier();
822 
823   Lex();
824 
825   MCSection *Note = getContext().getELFSection(".note", ELF::SHT_NOTE, 0);
826 
827   getStreamer().PushSection();
828   getStreamer().SwitchSection(Note);
829   getStreamer().emitInt32(Data.size() + 1); // namesz
830   getStreamer().emitInt32(0);               // descsz = 0 (no description).
831   getStreamer().emitInt32(1);               // type = NT_VERSION
832   getStreamer().emitBytes(Data);            // name
833   getStreamer().emitInt8(0);                // NUL
834   getStreamer().emitValueToAlignment(4);
835   getStreamer().PopSection();
836   return false;
837 }
838 
839 /// ParseDirectiveWeakref
840 ///  ::= .weakref foo, bar
841 bool ELFAsmParser::ParseDirectiveWeakref(StringRef, SMLoc) {
842   // FIXME: Share code with the other alias building directives.
843 
844   StringRef AliasName;
845   if (getParser().parseIdentifier(AliasName))
846     return TokError("expected identifier in directive");
847 
848   if (getLexer().isNot(AsmToken::Comma))
849     return TokError("expected a comma");
850 
851   Lex();
852 
853   StringRef Name;
854   if (getParser().parseIdentifier(Name))
855     return TokError("expected identifier in directive");
856 
857   MCSymbol *Alias = getContext().getOrCreateSymbol(AliasName);
858 
859   MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
860 
861   getStreamer().emitWeakReference(Alias, Sym);
862   return false;
863 }
864 
865 bool ELFAsmParser::ParseDirectiveSubsection(StringRef, SMLoc) {
866   const MCExpr *Subsection = nullptr;
867   if (getLexer().isNot(AsmToken::EndOfStatement)) {
868     if (getParser().parseExpression(Subsection))
869      return true;
870   }
871 
872   if (getLexer().isNot(AsmToken::EndOfStatement))
873     return TokError("unexpected token in directive");
874 
875   Lex();
876 
877   getStreamer().SubSection(Subsection);
878   return false;
879 }
880 
881 bool ELFAsmParser::ParseDirectiveCGProfile(StringRef S, SMLoc Loc) {
882   return MCAsmParserExtension::ParseDirectiveCGProfile(S, Loc);
883 }
884 
885 namespace llvm {
886 
887 MCAsmParserExtension *createELFAsmParser() {
888   return new ELFAsmParser;
889 }
890 
891 } // end namespace llvm
892