ItaniumDemangle.cpp 16 KB

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