LLVM  9.0.0svn
ELFAsmParser.cpp
Go to the documentation of this file.
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"
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"
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,
47 
48 public:
49  ELFAsmParser() { BracketExpressionsSupported = true; }
50 
51  void Initialize(MCAsmParser &Parser) override {
52  // Call the base implementation.
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,
96  }
97  bool ParseSectionDirectiveText(StringRef, SMLoc) {
98  return ParseSectionSwitch(".text", ELF::SHT_PROGBITS,
101  }
102  bool ParseSectionDirectiveBSS(StringRef, SMLoc) {
103  return ParseSectionSwitch(".bss", ELF::SHT_NOBITS,
106  }
107  bool ParseSectionDirectiveRoData(StringRef, SMLoc) {
108  return ParseSectionSwitch(".rodata", ELF::SHT_PROGBITS,
111  }
112  bool ParseSectionDirectiveTData(StringRef, SMLoc) {
113  return ParseSectionSwitch(".tdata", ELF::SHT_PROGBITS,
117  }
118  bool ParseSectionDirectiveTBSS(StringRef, SMLoc) {
119  return ParseSectionSwitch(".tbss", ELF::SHT_NOBITS,
123  }
124  bool ParseSectionDirectiveDataRel(StringRef, SMLoc) {
125  return ParseSectionSwitch(".data.rel", ELF::SHT_PROGBITS,
128  }
129  bool ParseSectionDirectiveDataRelRo(StringRef, SMLoc) {
130  return ParseSectionSwitch(".data.rel.ro", ELF::SHT_PROGBITS,
134  }
135  bool ParseSectionDirectiveEhFrame(StringRef, SMLoc) {
136  return ParseSectionSwitch(".eh_frame", ELF::SHT_PROGBITS,
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 parseMetadataSym(MCSymbolELF *&Associated);
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)
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::parseMetadataSym(MCSymbolELF *&Associated) {
447  MCAsmLexer &L = getLexer();
448  if (L.isNot(AsmToken::Comma))
449  return TokError("expected metadata symbol");
450  Lex();
451  StringRef Name;
452  if (getParser().parseIdentifier(Name))
453  return TokError("invalid metadata symbol");
454  Associated = dyn_cast_or_null<MCSymbolELF>(getContext().lookupSymbol(Name));
455  if (!Associated || !Associated->isInSection())
456  return TokError("symbol is not in a section: " + Name);
457  return false;
458 }
459 
460 bool ELFAsmParser::maybeParseUniqueID(int64_t &UniqueID) {
461  MCAsmLexer &L = getLexer();
462  if (L.isNot(AsmToken::Comma))
463  return false;
464  Lex();
465  StringRef UniqueStr;
466  if (getParser().parseIdentifier(UniqueStr))
467  return TokError("expected identifier in directive");
468  if (UniqueStr != "unique")
469  return TokError("expected 'unique'");
470  if (L.isNot(AsmToken::Comma))
471  return TokError("expected commma");
472  Lex();
473  if (getParser().parseAbsoluteExpression(UniqueID))
474  return true;
475  if (UniqueID < 0)
476  return TokError("unique id must be positive");
477  if (!isUInt<32>(UniqueID) || UniqueID == ~0U)
478  return TokError("unique id is too large");
479  return false;
480 }
481 
482 static bool hasPrefix(StringRef SectionName, StringRef Prefix) {
483  return SectionName.startswith(Prefix) || SectionName == Prefix.drop_back();
484 }
485 
486 bool ELFAsmParser::ParseSectionArguments(bool IsPush, SMLoc loc) {
488 
489  if (ParseSectionName(SectionName))
490  return TokError("expected identifier in directive");
491 
493  int64_t Size = 0;
494  StringRef GroupName;
495  unsigned Flags = 0;
496  const MCExpr *Subsection = nullptr;
497  bool UseLastGroup = false;
498  MCSymbolELF *Associated = nullptr;
499  int64_t UniqueID = ~0;
500 
501  // Set the defaults first.
502  if (hasPrefix(SectionName, ".rodata.") || SectionName == ".rodata1")
503  Flags |= ELF::SHF_ALLOC;
504  else if (SectionName == ".fini" || SectionName == ".init" ||
505  hasPrefix(SectionName, ".text."))
507  else if (hasPrefix(SectionName, ".data.") || SectionName == ".data1" ||
508  hasPrefix(SectionName, ".bss.") ||
509  hasPrefix(SectionName, ".init_array.") ||
510  hasPrefix(SectionName, ".fini_array.") ||
511  hasPrefix(SectionName, ".preinit_array."))
512  Flags |= ELF::SHF_ALLOC | ELF::SHF_WRITE;
513  else if (hasPrefix(SectionName, ".tdata.") ||
514  hasPrefix(SectionName, ".tbss."))
516 
517  if (getLexer().is(AsmToken::Comma)) {
518  Lex();
519 
520  if (IsPush && getLexer().isNot(AsmToken::String)) {
521  if (getParser().parseExpression(Subsection))
522  return true;
523  if (getLexer().isNot(AsmToken::Comma))
524  goto EndStmt;
525  Lex();
526  }
527 
528  unsigned extraFlags;
529 
530  if (getLexer().isNot(AsmToken::String)) {
531  if (!getContext().getAsmInfo()->usesSunStyleELFSectionSwitchSyntax()
532  || getLexer().isNot(AsmToken::Hash))
533  return TokError("expected string in directive");
534  extraFlags = parseSunStyleSectionFlags();
535  } else {
536  StringRef FlagsStr = getTok().getStringContents();
537  Lex();
538  extraFlags = parseSectionFlags(FlagsStr, &UseLastGroup);
539  }
540 
541  if (extraFlags == -1U)
542  return TokError("unknown flag");
543  Flags |= extraFlags;
544 
545  bool Mergeable = Flags & ELF::SHF_MERGE;
546  bool Group = Flags & ELF::SHF_GROUP;
547  if (Group && UseLastGroup)
548  return TokError("Section cannot specifiy a group name while also acting "
549  "as a member of the last group");
550 
551  if (maybeParseSectionType(TypeName))
552  return true;
553 
554  MCAsmLexer &L = getLexer();
555  if (TypeName.empty()) {
556  if (Mergeable)
557  return TokError("Mergeable section must specify the type");
558  if (Group)
559  return TokError("Group section must specify the type");
561  return TokError("unexpected token in directive");
562  }
563 
564  if (Mergeable)
565  if (parseMergeSize(Size))
566  return true;
567  if (Group)
568  if (parseGroup(GroupName))
569  return true;
570  if (Flags & ELF::SHF_LINK_ORDER)
571  if (parseMetadataSym(Associated))
572  return true;
573  if (maybeParseUniqueID(UniqueID))
574  return true;
575  }
576 
577 EndStmt:
578  if (getLexer().isNot(AsmToken::EndOfStatement))
579  return TokError("unexpected token in directive");
580  Lex();
581 
582  unsigned Type = ELF::SHT_PROGBITS;
583 
584  if (TypeName.empty()) {
585  if (SectionName.startswith(".note"))
586  Type = ELF::SHT_NOTE;
587  else if (hasPrefix(SectionName, ".init_array."))
588  Type = ELF::SHT_INIT_ARRAY;
589  else if (hasPrefix(SectionName, ".bss."))
590  Type = ELF::SHT_NOBITS;
591  else if (hasPrefix(SectionName, ".tbss."))
592  Type = ELF::SHT_NOBITS;
593  else if (hasPrefix(SectionName, ".fini_array."))
594  Type = ELF::SHT_FINI_ARRAY;
595  else if (hasPrefix(SectionName, ".preinit_array."))
596  Type = ELF::SHT_PREINIT_ARRAY;
597  } else {
598  if (TypeName == "init_array")
599  Type = ELF::SHT_INIT_ARRAY;
600  else if (TypeName == "fini_array")
601  Type = ELF::SHT_FINI_ARRAY;
602  else if (TypeName == "preinit_array")
603  Type = ELF::SHT_PREINIT_ARRAY;
604  else if (TypeName == "nobits")
605  Type = ELF::SHT_NOBITS;
606  else if (TypeName == "progbits")
607  Type = ELF::SHT_PROGBITS;
608  else if (TypeName == "note")
609  Type = ELF::SHT_NOTE;
610  else if (TypeName == "unwind")
611  Type = ELF::SHT_X86_64_UNWIND;
612  else if (TypeName == "llvm_odrtab")
613  Type = ELF::SHT_LLVM_ODRTAB;
614  else if (TypeName == "llvm_linker_options")
616  else if (TypeName == "llvm_call_graph_profile")
618  else if (TypeName == "llvm_dependent_libraries")
620  else if (TypeName.getAsInteger(0, Type))
621  return TokError("unknown section type");
622  }
623 
624  if (UseLastGroup) {
625  MCSectionSubPair CurrentSection = getStreamer().getCurrentSection();
626  if (const MCSectionELF *Section =
627  cast_or_null<MCSectionELF>(CurrentSection.first))
628  if (const MCSymbol *Group = Section->getGroup()) {
629  GroupName = Group->getName();
630  Flags |= ELF::SHF_GROUP;
631  }
632  }
633 
634  MCSection *ELFSection =
635  getContext().getELFSection(SectionName, Type, Flags, Size, GroupName,
636  UniqueID, Associated);
637  getStreamer().SwitchSection(ELFSection, Subsection);
638 
639  if (getContext().getGenDwarfForAssembly()) {
640  bool InsertResult = getContext().addGenDwarfSection(ELFSection);
641  if (InsertResult) {
642  if (getContext().getDwarfVersion() <= 2)
643  Warning(loc, "DWARF2 only supports one section per compilation unit");
644 
645  if (!ELFSection->getBeginSymbol()) {
646  MCSymbol *SectionStartSymbol = getContext().createTempSymbol();
647  getStreamer().EmitLabel(SectionStartSymbol);
648  ELFSection->setBeginSymbol(SectionStartSymbol);
649  }
650  }
651  }
652 
653  return false;
654 }
655 
656 bool ELFAsmParser::ParseDirectivePrevious(StringRef DirName, SMLoc) {
657  MCSectionSubPair PreviousSection = getStreamer().getPreviousSection();
658  if (PreviousSection.first == nullptr)
659  return TokError(".previous without corresponding .section");
660  getStreamer().SwitchSection(PreviousSection.first, PreviousSection.second);
661 
662  return false;
663 }
664 
666  return StringSwitch<MCSymbolAttr>(Type)
667  .Cases("STT_FUNC", "function", MCSA_ELF_TypeFunction)
668  .Cases("STT_OBJECT", "object", MCSA_ELF_TypeObject)
669  .Cases("STT_TLS", "tls_object", MCSA_ELF_TypeTLS)
670  .Cases("STT_COMMON", "common", MCSA_ELF_TypeCommon)
671  .Cases("STT_NOTYPE", "notype", MCSA_ELF_TypeNoType)
672  .Cases("STT_GNU_IFUNC", "gnu_indirect_function",
674  .Case("gnu_unique_object", MCSA_ELF_TypeGnuUniqueObject)
676 }
677 
678 /// ParseDirectiveELFType
679 /// ::= .type identifier , STT_<TYPE_IN_UPPER_CASE>
680 /// ::= .type identifier , #attribute
681 /// ::= .type identifier , @attribute
682 /// ::= .type identifier , %attribute
683 /// ::= .type identifier , "attribute"
684 bool ELFAsmParser::ParseDirectiveType(StringRef, SMLoc) {
685  StringRef Name;
686  if (getParser().parseIdentifier(Name))
687  return TokError("expected identifier in directive");
688 
689  // Handle the identifier as the key symbol.
690  MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
691 
692  // NOTE the comma is optional in all cases. It is only documented as being
693  // optional in the first case, however, GAS will silently treat the comma as
694  // optional in all cases. Furthermore, although the documentation states that
695  // the first form only accepts STT_<TYPE_IN_UPPER_CASE>, in reality, GAS
696  // accepts both the upper case name as well as the lower case aliases.
697  if (getLexer().is(AsmToken::Comma))
698  Lex();
699 
700  if (getLexer().isNot(AsmToken::Identifier) &&
701  getLexer().isNot(AsmToken::Hash) &&
702  getLexer().isNot(AsmToken::Percent) &&
703  getLexer().isNot(AsmToken::String)) {
704  if (!getLexer().getAllowAtInIdentifier())
705  return TokError("expected STT_<TYPE_IN_UPPER_CASE>, '#<type>', "
706  "'%<type>' or \"<type>\"");
707  else if (getLexer().isNot(AsmToken::At))
708  return TokError("expected STT_<TYPE_IN_UPPER_CASE>, '#<type>', '@<type>', "
709  "'%<type>' or \"<type>\"");
710  }
711 
712  if (getLexer().isNot(AsmToken::String) &&
713  getLexer().isNot(AsmToken::Identifier))
714  Lex();
715 
716  SMLoc TypeLoc = getLexer().getLoc();
717 
718  StringRef Type;
719  if (getParser().parseIdentifier(Type))
720  return TokError("expected symbol type in directive");
721 
722  MCSymbolAttr Attr = MCAttrForString(Type);
723  if (Attr == MCSA_Invalid)
724  return Error(TypeLoc, "unsupported attribute in '.type' directive");
725 
726  if (getLexer().isNot(AsmToken::EndOfStatement))
727  return TokError("unexpected token in '.type' directive");
728  Lex();
729 
730  getStreamer().EmitSymbolAttribute(Sym, Attr);
731 
732  return false;
733 }
734 
735 /// ParseDirectiveIdent
736 /// ::= .ident string
737 bool ELFAsmParser::ParseDirectiveIdent(StringRef, SMLoc) {
738  if (getLexer().isNot(AsmToken::String))
739  return TokError("unexpected token in '.ident' directive");
740 
741  StringRef Data = getTok().getIdentifier();
742 
743  Lex();
744 
745  if (getLexer().isNot(AsmToken::EndOfStatement))
746  return TokError("unexpected token in '.ident' directive");
747  Lex();
748 
749  getStreamer().EmitIdent(Data);
750  return false;
751 }
752 
753 /// ParseDirectiveSymver
754 /// ::= .symver foo, bar2@zed
755 bool ELFAsmParser::ParseDirectiveSymver(StringRef, SMLoc) {
756  StringRef Name;
757  if (getParser().parseIdentifier(Name))
758  return TokError("expected identifier in directive");
759 
760  if (getLexer().isNot(AsmToken::Comma))
761  return TokError("expected a comma");
762 
763  // ARM assembly uses @ for a comment...
764  // except when parsing the second parameter of the .symver directive.
765  // Force the next symbol to allow @ in the identifier, which is
766  // required for this directive and then reset it to its initial state.
767  const bool AllowAtInIdentifier = getLexer().getAllowAtInIdentifier();
768  getLexer().setAllowAtInIdentifier(true);
769  Lex();
770  getLexer().setAllowAtInIdentifier(AllowAtInIdentifier);
771 
772  StringRef AliasName;
773  if (getParser().parseIdentifier(AliasName))
774  return TokError("expected identifier in directive");
775 
776  if (AliasName.find('@') == StringRef::npos)
777  return TokError("expected a '@' in the name");
778 
779  MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
780  getStreamer().emitELFSymverDirective(AliasName, Sym);
781  return false;
782 }
783 
784 /// ParseDirectiveVersion
785 /// ::= .version string
786 bool ELFAsmParser::ParseDirectiveVersion(StringRef, SMLoc) {
787  if (getLexer().isNot(AsmToken::String))
788  return TokError("unexpected token in '.version' directive");
789 
790  StringRef Data = getTok().getIdentifier();
791 
792  Lex();
793 
794  MCSection *Note = getContext().getELFSection(".note", ELF::SHT_NOTE, 0);
795 
796  getStreamer().PushSection();
797  getStreamer().SwitchSection(Note);
798  getStreamer().EmitIntValue(Data.size()+1, 4); // namesz.
799  getStreamer().EmitIntValue(0, 4); // descsz = 0 (no description).
800  getStreamer().EmitIntValue(1, 4); // type = NT_VERSION.
801  getStreamer().EmitBytes(Data); // name.
802  getStreamer().EmitIntValue(0, 1); // terminate the string.
803  getStreamer().EmitValueToAlignment(4); // ensure 4 byte alignment.
804  getStreamer().PopSection();
805  return false;
806 }
807 
808 /// ParseDirectiveWeakref
809 /// ::= .weakref foo, bar
810 bool ELFAsmParser::ParseDirectiveWeakref(StringRef, SMLoc) {
811  // FIXME: Share code with the other alias building directives.
812 
813  StringRef AliasName;
814  if (getParser().parseIdentifier(AliasName))
815  return TokError("expected identifier in directive");
816 
817  if (getLexer().isNot(AsmToken::Comma))
818  return TokError("expected a comma");
819 
820  Lex();
821 
822  StringRef Name;
823  if (getParser().parseIdentifier(Name))
824  return TokError("expected identifier in directive");
825 
826  MCSymbol *Alias = getContext().getOrCreateSymbol(AliasName);
827 
828  MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
829 
830  getStreamer().EmitWeakReference(Alias, Sym);
831  return false;
832 }
833 
834 bool ELFAsmParser::ParseDirectiveSubsection(StringRef, SMLoc) {
835  const MCExpr *Subsection = nullptr;
836  if (getLexer().isNot(AsmToken::EndOfStatement)) {
837  if (getParser().parseExpression(Subsection))
838  return true;
839  }
840 
841  if (getLexer().isNot(AsmToken::EndOfStatement))
842  return TokError("unexpected token in directive");
843 
844  Lex();
845 
846  getStreamer().SubSection(Subsection);
847  return false;
848 }
849 
850 /// ParseDirectiveCGProfile
851 /// ::= .cg_profile identifier, identifier, <number>
852 bool ELFAsmParser::ParseDirectiveCGProfile(StringRef, SMLoc) {
853  StringRef From;
854  SMLoc FromLoc = getLexer().getLoc();
855  if (getParser().parseIdentifier(From))
856  return TokError("expected identifier in directive");
857 
858  if (getLexer().isNot(AsmToken::Comma))
859  return TokError("expected a comma");
860  Lex();
861 
862  StringRef To;
863  SMLoc ToLoc = getLexer().getLoc();
864  if (getParser().parseIdentifier(To))
865  return TokError("expected identifier in directive");
866 
867  if (getLexer().isNot(AsmToken::Comma))
868  return TokError("expected a comma");
869  Lex();
870 
871  int64_t Count;
872  if (getParser().parseIntToken(
873  Count, "expected integer count in '.cg_profile' directive"))
874  return true;
875 
876  if (getLexer().isNot(AsmToken::EndOfStatement))
877  return TokError("unexpected token in directive");
878 
879  MCSymbol *FromSym = getContext().getOrCreateSymbol(From);
880  MCSymbol *ToSym = getContext().getOrCreateSymbol(To);
881 
882  getStreamer().emitCGProfileEntry(
883  MCSymbolRefExpr::create(FromSym, MCSymbolRefExpr::VK_None, getContext(),
884  FromLoc),
886  ToLoc),
887  Count);
888  return false;
889 }
890 
891 namespace llvm {
892 
894  return new ELFAsmParser;
895 }
896 
897 } // end namespace llvm
constexpr bool isUInt< 32 >(uint64_t x)
Definition: MathExtras.h:348
Instances of this class represent a uniqued identifier for a section in the current translation unit...
Definition: MCSection.h:38
static SectionKind getData()
Definition: SectionKind.h:201
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx)
Definition: MCExpr.h:321
This class represents lattice values for constants.
Definition: AllocatorList.h:23
.type _foo, STT_OBJECT # aka
Definition: MCDirectives.h:25
bool is(AsmToken::TokenKind K) const
Check if the current token has kind K.
Definition: MCAsmLexer.h:135
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:41
All sections with the "d" flag are grouped together by the linker to form the data section and the dp...
Definition: ELF.h:929
Not a valid directive.
Definition: MCDirectives.h:19
Generic assembler parser interface, for use by target specific assembly parsers.
Definition: MCAsmParser.h:109
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
virtual void Initialize(MCAsmParser &Parser)
Initialize the extension for parsing using the given Parser.
LLVM_NODISCARD bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:256
static unsigned parseSectionFlags(StringRef flagsStr, bool *UseLastGroup)
static MCSymbolAttr MCAttrForString(StringRef Type)
.type _foo, STT_NOTYPE # aka
Definition: MCDirectives.h:28
All sections with the "c" flag are grouped together by the linker to form the constant pool and the c...
Definition: ELF.h:934
StringSwitch & Case(StringLiteral S, T Value)
Definition: StringSwitch.h:67
MCAsmParserExtension * createELFAsmParser()
static SectionKind getBSS()
Definition: SectionKind.h:197
Generic assembler lexer interface, for use by target specific assembly lexers.
Definition: MCAsmLexer.h:39
static bool hasPrefix(StringRef SectionName, StringRef Prefix)
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:35
bool isInSection() const
isInSection - Check if this symbol is defined in some section (i.e., it is defined but not absolute)...
Definition: MCSymbol.h:251
LLVM_NODISCARD R Default(T Value)
Definition: StringSwitch.h:181
.local (ELF)
Definition: MCDirectives.h:35
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:126
.type _foo, STT_GNU_IFUNC
Definition: MCDirectives.h:24
.protected (ELF)
Definition: MCDirectives.h:40
LLVM_NODISCARD size_t size() const
size - Get the string size.
Definition: StringRef.h:130
static SectionKind getThreadData()
Definition: SectionKind.h:196
.hidden (ELF)
Definition: MCDirectives.h:31
const char * getPointer() const
Definition: SMLoc.h:34
A switch()-like statement whose cases are string literals.
Definition: StringSwitch.h:42
StringSwitch & Cases(StringLiteral S0, StringLiteral S1, T Value)
Definition: StringSwitch.h:88
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
LLVM_NODISCARD size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition: StringRef.h:285
constexpr char TypeName[]
Key for Kernel::Arg::Metadata::mTypeName.
SectionKind - This is a simple POD value that classifies the properties of a section.
Definition: SectionKind.h:22
bool getAllowAtInIdentifier()
Definition: MCAsmLexer.h:143
std::enable_if< std::numeric_limits< T >::is_signed, bool >::type getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition: StringRef.h:478
static SectionKind getThreadBSS()
Definition: SectionKind.h:195
std::pair< MCSection *, const MCExpr * > MCSectionSubPair
Definition: MCStreamer.h:56
BlockVerifier::State From
.type _foo, STT_TLS # aka
Definition: MCDirectives.h:26
static SectionKind getReadOnlyWithRel()
Definition: SectionKind.h:202
MCSymbol * getBeginSymbol()
Definition: MCSection.h:109
MCSymbolAttr
Definition: MCDirectives.h:18
.internal (ELF)
Definition: MCDirectives.h:33
.type _foo, STT_COMMON # aka
Definition: MCDirectives.h:27
static const size_t npos
Definition: StringRef.h:50
.type _foo, STT_FUNC # aka
Definition: MCDirectives.h:23
This represents a section on linux, lots of unix variants and some bare metal systems.
Definition: MCSectionELF.h:27
uint32_t Size
Definition: Profile.cpp:46
bool isNot(AsmToken::TokenKind K) const
Check if the current token has kind K.
Definition: MCAsmLexer.h:138
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Generic interface for extending the MCAsmParser, which is implemented by target and object file assem...
LLVM_NODISCARD StringRef drop_back(size_t N=1) const
Return a StringRef equal to &#39;this&#39; but with the last N elements dropped.
Definition: StringRef.h:628
std::pair< MCAsmParserExtension *, DirectiveHandler > ExtensionDirectiveHandler
Definition: MCAsmParser.h:113
const char SectionName[]
Definition: AMDGPUPTNote.h:23
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
Represents a location in source code.
Definition: SMLoc.h:23
static SectionKind getReadOnly()
Definition: SectionKind.h:181
static SectionKind getText()
Definition: SectionKind.h:179
void setBeginSymbol(MCSymbol *Sym)
Definition: MCSection.h:113