ItaniumDemangle.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  1. //===------------------------- ItaniumDemangle.cpp ------------------------===//
  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. // FIXME: (possibly) incomplete list of features that clang mangles that this
  9. // file does not yet support:
  10. // - C++ modules TS
  11. #include "llvm/Demangle/Demangle.h"
  12. #include "llvm/Demangle/ItaniumDemangle.h"
  13. #include <cassert>
  14. #include <cctype>
  15. #include <cstdio>
  16. #include <cstdlib>
  17. #include <cstring>
  18. #include <functional>
  19. #include <utility>
  20. using namespace llvm;
  21. using namespace llvm::itanium_demangle;
  22. constexpr const char *itanium_demangle::FloatData<float>::spec;
  23. constexpr const char *itanium_demangle::FloatData<double>::spec;
  24. constexpr const char *itanium_demangle::FloatData<long double>::spec;
  25. // <discriminator> := _ <non-negative number> # when number < 10
  26. // := __ <non-negative number> _ # when number >= 10
  27. // extension := decimal-digit+ # at the end of string
  28. const char *itanium_demangle::parse_discriminator(const char *first,
  29. const char *last) {
  30. // parse but ignore discriminator
  31. if (first != last) {
  32. if (*first == '_') {
  33. const char *t1 = first + 1;
  34. if (t1 != last) {
  35. if (std::isdigit(*t1))
  36. first = t1 + 1;
  37. else if (*t1 == '_') {
  38. for (++t1; t1 != last && std::isdigit(*t1); ++t1)
  39. ;
  40. if (t1 != last && *t1 == '_')
  41. first = t1 + 1;
  42. }
  43. }
  44. } else if (std::isdigit(*first)) {
  45. const char *t1 = first + 1;
  46. for (; t1 != last && std::isdigit(*t1); ++t1)
  47. ;
  48. if (t1 == last)
  49. first = last;
  50. }
  51. }
  52. return first;
  53. }
  54. #ifndef NDEBUG
  55. namespace {
  56. struct DumpVisitor {
  57. unsigned Depth = 0;
  58. bool PendingNewline = false;
  59. template<typename NodeT> static constexpr bool wantsNewline(const NodeT *) {
  60. return true;
  61. }
  62. static bool wantsNewline(NodeArray A) { return !A.empty(); }
  63. static constexpr bool wantsNewline(...) { return false; }
  64. template<typename ...Ts> static bool anyWantNewline(Ts ...Vs) {
  65. for (bool B : {wantsNewline(Vs)...})
  66. if (B)
  67. return true;
  68. return false;
  69. }
  70. void printStr(const char *S) { fprintf(stderr, "%s", S); }
  71. void print(StringView SV) {
  72. fprintf(stderr, "\"%.*s\"", (int)SV.size(), SV.begin());
  73. }
  74. void print(const Node *N) {
  75. if (N)
  76. N->visit(std::ref(*this));
  77. else
  78. printStr("<null>");
  79. }
  80. void print(NodeArray A) {
  81. ++Depth;
  82. printStr("{");
  83. bool First = true;
  84. for (const Node *N : A) {
  85. if (First)
  86. print(N);
  87. else
  88. printWithComma(N);
  89. First = false;
  90. }
  91. printStr("}");
  92. --Depth;
  93. }
  94. // Overload used when T is exactly 'bool', not merely convertible to 'bool'.
  95. void print(bool B) { printStr(B ? "true" : "false"); }
  96. template <class T> std::enable_if_t<std::is_unsigned<T>::value> print(T N) {
  97. fprintf(stderr, "%llu", (unsigned long long)N);
  98. }
  99. template <class T> std::enable_if_t<std::is_signed<T>::value> print(T N) {
  100. fprintf(stderr, "%lld", (long long)N);
  101. }
  102. void print(ReferenceKind RK) {
  103. switch (RK) {
  104. case ReferenceKind::LValue:
  105. return printStr("ReferenceKind::LValue");
  106. case ReferenceKind::RValue:
  107. return printStr("ReferenceKind::RValue");
  108. }
  109. }
  110. void print(FunctionRefQual RQ) {
  111. switch (RQ) {
  112. case FunctionRefQual::FrefQualNone:
  113. return printStr("FunctionRefQual::FrefQualNone");
  114. case FunctionRefQual::FrefQualLValue:
  115. return printStr("FunctionRefQual::FrefQualLValue");
  116. case FunctionRefQual::FrefQualRValue:
  117. return printStr("FunctionRefQual::FrefQualRValue");
  118. }
  119. }
  120. void print(Qualifiers Qs) {
  121. if (!Qs) return printStr("QualNone");
  122. struct QualName { Qualifiers Q; const char *Name; } Names[] = {
  123. {QualConst, "QualConst"},
  124. {QualVolatile, "QualVolatile"},
  125. {QualRestrict, "QualRestrict"},
  126. };
  127. for (QualName Name : Names) {
  128. if (Qs & Name.Q) {
  129. printStr(Name.Name);
  130. Qs = Qualifiers(Qs & ~Name.Q);
  131. if (Qs) printStr(" | ");
  132. }
  133. }
  134. }
  135. void print(SpecialSubKind SSK) {
  136. switch (SSK) {
  137. case SpecialSubKind::allocator:
  138. return printStr("SpecialSubKind::allocator");
  139. case SpecialSubKind::basic_string:
  140. return printStr("SpecialSubKind::basic_string");
  141. case SpecialSubKind::string:
  142. return printStr("SpecialSubKind::string");
  143. case SpecialSubKind::istream:
  144. return printStr("SpecialSubKind::istream");
  145. case SpecialSubKind::ostream:
  146. return printStr("SpecialSubKind::ostream");
  147. case SpecialSubKind::iostream:
  148. return printStr("SpecialSubKind::iostream");
  149. }
  150. }
  151. void print(TemplateParamKind TPK) {
  152. switch (TPK) {
  153. case TemplateParamKind::Type:
  154. return printStr("TemplateParamKind::Type");
  155. case TemplateParamKind::NonType:
  156. return printStr("TemplateParamKind::NonType");
  157. case TemplateParamKind::Template:
  158. return printStr("TemplateParamKind::Template");
  159. }
  160. }
  161. void newLine() {
  162. printStr("\n");
  163. for (unsigned I = 0; I != Depth; ++I)
  164. printStr(" ");
  165. PendingNewline = false;
  166. }
  167. template<typename T> void printWithPendingNewline(T V) {
  168. print(V);
  169. if (wantsNewline(V))
  170. PendingNewline = true;
  171. }
  172. template<typename T> void printWithComma(T V) {
  173. if (PendingNewline || wantsNewline(V)) {
  174. printStr(",");
  175. newLine();
  176. } else {
  177. printStr(", ");
  178. }
  179. printWithPendingNewline(V);
  180. }
  181. struct CtorArgPrinter {
  182. DumpVisitor &Visitor;
  183. template<typename T, typename ...Rest> void operator()(T V, Rest ...Vs) {
  184. if (Visitor.anyWantNewline(V, Vs...))
  185. Visitor.newLine();
  186. Visitor.printWithPendingNewline(V);
  187. int PrintInOrder[] = { (Visitor.printWithComma(Vs), 0)..., 0 };
  188. (void)PrintInOrder;
  189. }
  190. };
  191. template<typename NodeT> void operator()(const NodeT *Node) {
  192. Depth += 2;
  193. fprintf(stderr, "%s(", itanium_demangle::NodeKind<NodeT>::name());
  194. Node->match(CtorArgPrinter{*this});
  195. fprintf(stderr, ")");
  196. Depth -= 2;
  197. }
  198. void operator()(const ForwardTemplateReference *Node) {
  199. Depth += 2;
  200. fprintf(stderr, "ForwardTemplateReference(");
  201. if (Node->Ref && !Node->Printing) {
  202. Node->Printing = true;
  203. CtorArgPrinter{*this}(Node->Ref);
  204. Node->Printing = false;
  205. } else {
  206. CtorArgPrinter{*this}(Node->Index);
  207. }
  208. fprintf(stderr, ")");
  209. Depth -= 2;
  210. }
  211. };
  212. }
  213. void itanium_demangle::Node::dump() const {
  214. DumpVisitor V;
  215. visit(std::ref(V));
  216. V.newLine();
  217. }
  218. #endif
  219. namespace {
  220. class BumpPointerAllocator {
  221. struct BlockMeta {
  222. BlockMeta* Next;
  223. size_t Current;
  224. };
  225. static constexpr size_t AllocSize = 4096;
  226. static constexpr size_t UsableAllocSize = AllocSize - sizeof(BlockMeta);
  227. alignas(long double) char InitialBuffer[AllocSize];
  228. BlockMeta* BlockList = nullptr;
  229. void grow() {
  230. char* NewMeta = static_cast<char *>(std::malloc(AllocSize));
  231. if (NewMeta == nullptr)
  232. std::terminate();
  233. BlockList = new (NewMeta) BlockMeta{BlockList, 0};
  234. }
  235. void* allocateMassive(size_t NBytes) {
  236. NBytes += sizeof(BlockMeta);
  237. BlockMeta* NewMeta = reinterpret_cast<BlockMeta*>(std::malloc(NBytes));
  238. if (NewMeta == nullptr)
  239. std::terminate();
  240. BlockList->Next = new (NewMeta) BlockMeta{BlockList->Next, 0};
  241. return static_cast<void*>(NewMeta + 1);
  242. }
  243. public:
  244. BumpPointerAllocator()
  245. : BlockList(new (InitialBuffer) BlockMeta{nullptr, 0}) {}
  246. void* allocate(size_t N) {
  247. N = (N + 15u) & ~15u;
  248. if (N + BlockList->Current >= UsableAllocSize) {
  249. if (N > UsableAllocSize)
  250. return allocateMassive(N);
  251. grow();
  252. }
  253. BlockList->Current += N;
  254. return static_cast<void*>(reinterpret_cast<char*>(BlockList + 1) +
  255. BlockList->Current - N);
  256. }
  257. void reset() {
  258. while (BlockList) {
  259. BlockMeta* Tmp = BlockList;
  260. BlockList = BlockList->Next;
  261. if (reinterpret_cast<char*>(Tmp) != InitialBuffer)
  262. std::free(Tmp);
  263. }
  264. BlockList = new (InitialBuffer) BlockMeta{nullptr, 0};
  265. }
  266. ~BumpPointerAllocator() { reset(); }
  267. };
  268. class DefaultAllocator {
  269. BumpPointerAllocator Alloc;
  270. public:
  271. void reset() { Alloc.reset(); }
  272. template<typename T, typename ...Args> T *makeNode(Args &&...args) {
  273. return new (Alloc.allocate(sizeof(T)))
  274. T(std::forward<Args>(args)...);
  275. }
  276. void *allocateNodeArray(size_t sz) {
  277. return Alloc.allocate(sizeof(Node *) * sz);
  278. }
  279. };
  280. } // unnamed namespace
  281. //===----------------------------------------------------------------------===//
  282. // Code beyond this point should not be synchronized with libc++abi.
  283. //===----------------------------------------------------------------------===//
  284. using Demangler = itanium_demangle::ManglingParser<DefaultAllocator>;
  285. void llvm::itanium_demangle::demangleAST(const char *MangledName, IASTProcessor *Processor) {
  286. Demangler Parser(MangledName, MangledName + std::strlen(MangledName));
  287. Node* node = Parser.parse();
  288. Processor->Process(node);
  289. }
  290. char *llvm::itaniumDemangle(const char *MangledName, char *Buf,
  291. size_t *N, int *Status) {
  292. if (MangledName == nullptr || (Buf != nullptr && N == nullptr)) {
  293. if (Status)
  294. *Status = demangle_invalid_args;
  295. return nullptr;
  296. }
  297. int InternalStatus = demangle_success;
  298. Demangler Parser(MangledName, MangledName + std::strlen(MangledName));
  299. OutputBuffer OB;
  300. Node *AST = Parser.parse();
  301. if (AST == nullptr)
  302. InternalStatus = demangle_invalid_mangled_name;
  303. else if (!initializeOutputBuffer(Buf, N, OB, 1024))
  304. InternalStatus = demangle_memory_alloc_failure;
  305. else {
  306. assert(Parser.ForwardTemplateRefs.empty());
  307. AST->print(OB);
  308. OB += '\0';
  309. if (N != nullptr)
  310. *N = OB.getCurrentPosition();
  311. Buf = OB.getBuffer();
  312. }
  313. if (Status)
  314. *Status = InternalStatus;
  315. return InternalStatus == demangle_success ? Buf : nullptr;
  316. }
  317. ItaniumPartialDemangler::ItaniumPartialDemangler()
  318. : RootNode(nullptr), Context(new Demangler{nullptr, nullptr}) {}
  319. ItaniumPartialDemangler::~ItaniumPartialDemangler() {
  320. delete static_cast<Demangler *>(Context);
  321. }
  322. ItaniumPartialDemangler::ItaniumPartialDemangler(
  323. ItaniumPartialDemangler &&Other)
  324. : RootNode(Other.RootNode), Context(Other.Context) {
  325. Other.Context = Other.RootNode = nullptr;
  326. }
  327. ItaniumPartialDemangler &ItaniumPartialDemangler::
  328. operator=(ItaniumPartialDemangler &&Other) {
  329. std::swap(RootNode, Other.RootNode);
  330. std::swap(Context, Other.Context);
  331. return *this;
  332. }
  333. // Demangle MangledName into an AST, storing it into this->RootNode.
  334. bool ItaniumPartialDemangler::partialDemangle(const char *MangledName) {
  335. Demangler *Parser = static_cast<Demangler *>(Context);
  336. size_t Len = std::strlen(MangledName);
  337. Parser->reset(MangledName, MangledName + Len);
  338. RootNode = Parser->parse();
  339. return RootNode == nullptr;
  340. }
  341. static char *printNode(const Node *RootNode, char *Buf, size_t *N) {
  342. OutputBuffer OB;
  343. if (!initializeOutputBuffer(Buf, N, OB, 128))
  344. return nullptr;
  345. RootNode->print(OB);
  346. OB += '\0';
  347. if (N != nullptr)
  348. *N = OB.getCurrentPosition();
  349. return OB.getBuffer();
  350. }
  351. char *ItaniumPartialDemangler::getFunctionBaseName(char *Buf, size_t *N) const {
  352. if (!isFunction())
  353. return nullptr;
  354. const Node *Name = static_cast<const FunctionEncoding *>(RootNode)->getName();
  355. while (true) {
  356. switch (Name->getKind()) {
  357. case Node::KAbiTagAttr:
  358. Name = static_cast<const AbiTagAttr *>(Name)->Base;
  359. continue;
  360. case Node::KStdQualifiedName:
  361. Name = static_cast<const StdQualifiedName *>(Name)->Child;
  362. continue;
  363. case Node::KNestedName:
  364. Name = static_cast<const NestedName *>(Name)->Name;
  365. continue;
  366. case Node::KLocalName:
  367. Name = static_cast<const LocalName *>(Name)->Entity;
  368. continue;
  369. case Node::KNameWithTemplateArgs:
  370. Name = static_cast<const NameWithTemplateArgs *>(Name)->Name;
  371. continue;
  372. default:
  373. return printNode(Name, Buf, N);
  374. }
  375. }
  376. }
  377. char *ItaniumPartialDemangler::getFunctionDeclContextName(char *Buf,
  378. size_t *N) const {
  379. if (!isFunction())
  380. return nullptr;
  381. const Node *Name = static_cast<const FunctionEncoding *>(RootNode)->getName();
  382. OutputBuffer OB;
  383. if (!initializeOutputBuffer(Buf, N, OB, 128))
  384. return nullptr;
  385. KeepGoingLocalFunction:
  386. while (true) {
  387. if (Name->getKind() == Node::KAbiTagAttr) {
  388. Name = static_cast<const AbiTagAttr *>(Name)->Base;
  389. continue;
  390. }
  391. if (Name->getKind() == Node::KNameWithTemplateArgs) {
  392. Name = static_cast<const NameWithTemplateArgs *>(Name)->Name;
  393. continue;
  394. }
  395. break;
  396. }
  397. switch (Name->getKind()) {
  398. case Node::KStdQualifiedName:
  399. OB += "std";
  400. break;
  401. case Node::KNestedName:
  402. static_cast<const NestedName *>(Name)->Qual->print(OB);
  403. break;
  404. case Node::KLocalName: {
  405. auto *LN = static_cast<const LocalName *>(Name);
  406. LN->Encoding->print(OB);
  407. OB += "::";
  408. Name = LN->Entity;
  409. goto KeepGoingLocalFunction;
  410. }
  411. default:
  412. break;
  413. }
  414. OB += '\0';
  415. if (N != nullptr)
  416. *N = OB.getCurrentPosition();
  417. return OB.getBuffer();
  418. }
  419. char *ItaniumPartialDemangler::getFunctionName(char *Buf, size_t *N) const {
  420. if (!isFunction())
  421. return nullptr;
  422. auto *Name = static_cast<FunctionEncoding *>(RootNode)->getName();
  423. return printNode(Name, Buf, N);
  424. }
  425. char *ItaniumPartialDemangler::getFunctionParameters(char *Buf,
  426. size_t *N) const {
  427. if (!isFunction())
  428. return nullptr;
  429. NodeArray Params = static_cast<FunctionEncoding *>(RootNode)->getParams();
  430. OutputBuffer OB;
  431. if (!initializeOutputBuffer(Buf, N, OB, 128))
  432. return nullptr;
  433. OB += '(';
  434. Params.printWithComma(OB);
  435. OB += ')';
  436. OB += '\0';
  437. if (N != nullptr)
  438. *N = OB.getCurrentPosition();
  439. return OB.getBuffer();
  440. }
  441. char *ItaniumPartialDemangler::getFunctionReturnType(
  442. char *Buf, size_t *N) const {
  443. if (!isFunction())
  444. return nullptr;
  445. OutputBuffer OB;
  446. if (!initializeOutputBuffer(Buf, N, OB, 128))
  447. return nullptr;
  448. if (const Node *Ret =
  449. static_cast<const FunctionEncoding *>(RootNode)->getReturnType())
  450. Ret->print(OB);
  451. OB += '\0';
  452. if (N != nullptr)
  453. *N = OB.getCurrentPosition();
  454. return OB.getBuffer();
  455. }
  456. char *ItaniumPartialDemangler::finishDemangle(char *Buf, size_t *N) const {
  457. assert(RootNode != nullptr && "must call partialDemangle()");
  458. return printNode(static_cast<Node *>(RootNode), Buf, N);
  459. }
  460. bool ItaniumPartialDemangler::hasFunctionQualifiers() const {
  461. assert(RootNode != nullptr && "must call partialDemangle()");
  462. if (!isFunction())
  463. return false;
  464. auto *E = static_cast<const FunctionEncoding *>(RootNode);
  465. return E->getCVQuals() != QualNone || E->getRefQual() != FrefQualNone;
  466. }
  467. bool ItaniumPartialDemangler::isCtorOrDtor() const {
  468. const Node *N = static_cast<const Node *>(RootNode);
  469. while (N) {
  470. switch (N->getKind()) {
  471. default:
  472. return false;
  473. case Node::KCtorDtorName:
  474. return true;
  475. case Node::KAbiTagAttr:
  476. N = static_cast<const AbiTagAttr *>(N)->Base;
  477. break;
  478. case Node::KFunctionEncoding:
  479. N = static_cast<const FunctionEncoding *>(N)->getName();
  480. break;
  481. case Node::KLocalName:
  482. N = static_cast<const LocalName *>(N)->Entity;
  483. break;
  484. case Node::KNameWithTemplateArgs:
  485. N = static_cast<const NameWithTemplateArgs *>(N)->Name;
  486. break;
  487. case Node::KNestedName:
  488. N = static_cast<const NestedName *>(N)->Name;
  489. break;
  490. case Node::KStdQualifiedName:
  491. N = static_cast<const StdQualifiedName *>(N)->Child;
  492. break;
  493. }
  494. }
  495. return false;
  496. }
  497. bool ItaniumPartialDemangler::isFunction() const {
  498. assert(RootNode != nullptr && "must call partialDemangle()");
  499. return static_cast<const Node *>(RootNode)->getKind() ==
  500. Node::KFunctionEncoding;
  501. }
  502. bool ItaniumPartialDemangler::isSpecialName() const {
  503. assert(RootNode != nullptr && "must call partialDemangle()");
  504. auto K = static_cast<const Node *>(RootNode)->getKind();
  505. return K == Node::KSpecialName || K == Node::KCtorVtableSpecialName;
  506. }
  507. bool ItaniumPartialDemangler::isData() const {
  508. return !isFunction() && !isSpecialName();
  509. }