1 //===-------------------------- cxa_demangle.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 
9 // FIXME: (possibly) incomplete list of features that clang mangles that this
10 // file does not yet support:
11 //   - C++ modules TS
12 
13 #include "demangle/ItaniumDemangle.h"
14 #include "__cxxabi_config.h"
15 #include <cassert>
16 #include <cctype>
17 #include <cstdio>
18 #include <cstdlib>
19 #include <cstring>
20 #include <functional>
21 #include <numeric>
22 #include <utility>
23 
24 using namespace itanium_demangle;
25 
26 constexpr const char *itanium_demangle::FloatData<float>::spec;
27 constexpr const char *itanium_demangle::FloatData<double>::spec;
28 constexpr const char *itanium_demangle::FloatData<long double>::spec;
29 
30 // <discriminator> := _ <non-negative number>      # when number < 10
31 //                 := __ <non-negative number> _   # when number >= 10
32 //  extension      := decimal-digit+               # at the end of string
33 const char *itanium_demangle::parse_discriminator(const char *first,
34                                                   const char *last) {
35   // parse but ignore discriminator
36   if (first != last) {
37     if (*first == '_') {
38       const char *t1 = first + 1;
39       if (t1 != last) {
40         if (std::isdigit(*t1))
41           first = t1 + 1;
42         else if (*t1 == '_') {
43           for (++t1; t1 != last && std::isdigit(*t1); ++t1)
44             ;
45           if (t1 != last && *t1 == '_')
46             first = t1 + 1;
47         }
48       }
49     } else if (std::isdigit(*first)) {
50       const char *t1 = first + 1;
51       for (; t1 != last && std::isdigit(*t1); ++t1)
52         ;
53       if (t1 == last)
54         first = last;
55     }
56   }
57   return first;
58 }
59 
60 #ifndef NDEBUG
61 namespace {
62 struct DumpVisitor {
63   unsigned Depth = 0;
64   bool PendingNewline = false;
65 
66   template<typename NodeT> static constexpr bool wantsNewline(const NodeT *) {
67     return true;
68   }
69   static bool wantsNewline(NodeArray A) { return !A.empty(); }
70   static constexpr bool wantsNewline(...) { return false; }
71 
72   template<typename ...Ts> static bool anyWantNewline(Ts ...Vs) {
73     for (bool B : {wantsNewline(Vs)...})
74       if (B)
75         return true;
76     return false;
77   }
78 
79   void printStr(const char *S) { fprintf(stderr, "%s", S); }
80   void print(StringView SV) {
81     fprintf(stderr, "\"%.*s\"", (int)SV.size(), SV.begin());
82   }
83   void print(const Node *N) {
84     if (N)
85       N->visit(std::ref(*this));
86     else
87       printStr("<null>");
88   }
89   void print(NodeOrString NS) {
90     if (NS.isNode())
91       print(NS.asNode());
92     else if (NS.isString())
93       print(NS.asString());
94     else
95       printStr("NodeOrString()");
96   }
97   void print(NodeArray A) {
98     ++Depth;
99     printStr("{");
100     bool First = true;
101     for (const Node *N : A) {
102       if (First)
103         print(N);
104       else
105         printWithComma(N);
106       First = false;
107     }
108     printStr("}");
109     --Depth;
110   }
111 
112   // Overload used when T is exactly 'bool', not merely convertible to 'bool'.
113   void print(bool B) { printStr(B ? "true" : "false"); }
114 
115   template <class T>
116   typename std::enable_if<std::is_unsigned<T>::value>::type print(T N) {
117     fprintf(stderr, "%llu", (unsigned long long)N);
118   }
119 
120   template <class T>
121   typename std::enable_if<std::is_signed<T>::value>::type print(T N) {
122     fprintf(stderr, "%lld", (long long)N);
123   }
124 
125   void print(ReferenceKind RK) {
126     switch (RK) {
127     case ReferenceKind::LValue:
128       return printStr("ReferenceKind::LValue");
129     case ReferenceKind::RValue:
130       return printStr("ReferenceKind::RValue");
131     }
132   }
133   void print(FunctionRefQual RQ) {
134     switch (RQ) {
135     case FunctionRefQual::FrefQualNone:
136       return printStr("FunctionRefQual::FrefQualNone");
137     case FunctionRefQual::FrefQualLValue:
138       return printStr("FunctionRefQual::FrefQualLValue");
139     case FunctionRefQual::FrefQualRValue:
140       return printStr("FunctionRefQual::FrefQualRValue");
141     }
142   }
143   void print(Qualifiers Qs) {
144     if (!Qs) return printStr("QualNone");
145     struct QualName { Qualifiers Q; const char *Name; } Names[] = {
146       {QualConst, "QualConst"},
147       {QualVolatile, "QualVolatile"},
148       {QualRestrict, "QualRestrict"},
149     };
150     for (QualName Name : Names) {
151       if (Qs & Name.Q) {
152         printStr(Name.Name);
153         Qs = Qualifiers(Qs & ~Name.Q);
154         if (Qs) printStr(" | ");
155       }
156     }
157   }
158   void print(SpecialSubKind SSK) {
159     switch (SSK) {
160     case SpecialSubKind::allocator:
161       return printStr("SpecialSubKind::allocator");
162     case SpecialSubKind::basic_string:
163       return printStr("SpecialSubKind::basic_string");
164     case SpecialSubKind::string:
165       return printStr("SpecialSubKind::string");
166     case SpecialSubKind::istream:
167       return printStr("SpecialSubKind::istream");
168     case SpecialSubKind::ostream:
169       return printStr("SpecialSubKind::ostream");
170     case SpecialSubKind::iostream:
171       return printStr("SpecialSubKind::iostream");
172     }
173   }
174   void print(TemplateParamKind TPK) {
175     switch (TPK) {
176     case TemplateParamKind::Type:
177       return printStr("TemplateParamKind::Type");
178     case TemplateParamKind::NonType:
179       return printStr("TemplateParamKind::NonType");
180     case TemplateParamKind::Template:
181       return printStr("TemplateParamKind::Template");
182     }
183   }
184 
185   void newLine() {
186     printStr("\n");
187     for (unsigned I = 0; I != Depth; ++I)
188       printStr(" ");
189     PendingNewline = false;
190   }
191 
192   template<typename T> void printWithPendingNewline(T V) {
193     print(V);
194     if (wantsNewline(V))
195       PendingNewline = true;
196   }
197 
198   template<typename T> void printWithComma(T V) {
199     if (PendingNewline || wantsNewline(V)) {
200       printStr(",");
201       newLine();
202     } else {
203       printStr(", ");
204     }
205 
206     printWithPendingNewline(V);
207   }
208 
209   struct CtorArgPrinter {
210     DumpVisitor &Visitor;
211 
212     template<typename T, typename ...Rest> void operator()(T V, Rest ...Vs) {
213       if (Visitor.anyWantNewline(V, Vs...))
214         Visitor.newLine();
215       Visitor.printWithPendingNewline(V);
216       int PrintInOrder[] = { (Visitor.printWithComma(Vs), 0)..., 0 };
217       (void)PrintInOrder;
218     }
219   };
220 
221   template<typename NodeT> void operator()(const NodeT *Node) {
222     Depth += 2;
223     fprintf(stderr, "%s(", itanium_demangle::NodeKind<NodeT>::name());
224     Node->match(CtorArgPrinter{*this});
225     fprintf(stderr, ")");
226     Depth -= 2;
227   }
228 
229   void operator()(const ForwardTemplateReference *Node) {
230     Depth += 2;
231     fprintf(stderr, "ForwardTemplateReference(");
232     if (Node->Ref && !Node->Printing) {
233       Node->Printing = true;
234       CtorArgPrinter{*this}(Node->Ref);
235       Node->Printing = false;
236     } else {
237       CtorArgPrinter{*this}(Node->Index);
238     }
239     fprintf(stderr, ")");
240     Depth -= 2;
241   }
242 };
243 }
244 
245 void itanium_demangle::Node::dump() const {
246   DumpVisitor V;
247   visit(std::ref(V));
248   V.newLine();
249 }
250 #endif
251 
252 namespace {
253 class BumpPointerAllocator {
254   struct BlockMeta {
255     BlockMeta* Next;
256     size_t Current;
257   };
258 
259   static constexpr size_t AllocSize = 4096;
260   static constexpr size_t UsableAllocSize = AllocSize - sizeof(BlockMeta);
261 
262   alignas(long double) char InitialBuffer[AllocSize];
263   BlockMeta* BlockList = nullptr;
264 
265   void grow() {
266     char* NewMeta = static_cast<char *>(std::malloc(AllocSize));
267     if (NewMeta == nullptr)
268       std::terminate();
269     BlockList = new (NewMeta) BlockMeta{BlockList, 0};
270   }
271 
272   void* allocateMassive(size_t NBytes) {
273     NBytes += sizeof(BlockMeta);
274     BlockMeta* NewMeta = reinterpret_cast<BlockMeta*>(std::malloc(NBytes));
275     if (NewMeta == nullptr)
276       std::terminate();
277     BlockList->Next = new (NewMeta) BlockMeta{BlockList->Next, 0};
278     return static_cast<void*>(NewMeta + 1);
279   }
280 
281 public:
282   BumpPointerAllocator()
283       : BlockList(new (InitialBuffer) BlockMeta{nullptr, 0}) {}
284 
285   void* allocate(size_t N) {
286     N = (N + 15u) & ~15u;
287     if (N + BlockList->Current >= UsableAllocSize) {
288       if (N > UsableAllocSize)
289         return allocateMassive(N);
290       grow();
291     }
292     BlockList->Current += N;
293     return static_cast<void*>(reinterpret_cast<char*>(BlockList + 1) +
294                               BlockList->Current - N);
295   }
296 
297   void reset() {
298     while (BlockList) {
299       BlockMeta* Tmp = BlockList;
300       BlockList = BlockList->Next;
301       if (reinterpret_cast<char*>(Tmp) != InitialBuffer)
302         std::free(Tmp);
303     }
304     BlockList = new (InitialBuffer) BlockMeta{nullptr, 0};
305   }
306 
307   ~BumpPointerAllocator() { reset(); }
308 };
309 
310 class DefaultAllocator {
311   BumpPointerAllocator Alloc;
312 
313 public:
314   void reset() { Alloc.reset(); }
315 
316   template<typename T, typename ...Args> T *makeNode(Args &&...args) {
317     return new (Alloc.allocate(sizeof(T)))
318         T(std::forward<Args>(args)...);
319   }
320 
321   void *allocateNodeArray(size_t sz) {
322     return Alloc.allocate(sizeof(Node *) * sz);
323   }
324 };
325 }  // unnamed namespace
326 
327 //===----------------------------------------------------------------------===//
328 // Code beyond this point should not be synchronized with LLVM.
329 //===----------------------------------------------------------------------===//
330 
331 using Demangler = itanium_demangle::ManglingParser<DefaultAllocator>;
332 
333 namespace {
334 enum : int {
335   demangle_invalid_args = -3,
336   demangle_invalid_mangled_name = -2,
337   demangle_memory_alloc_failure = -1,
338   demangle_success = 0,
339 };
340 }
341 
342 namespace __cxxabiv1 {
343 extern "C" _LIBCXXABI_FUNC_VIS char *
344 __cxa_demangle(const char *MangledName, char *Buf, size_t *N, int *Status) {
345   if (MangledName == nullptr || (Buf != nullptr && N == nullptr)) {
346     if (Status)
347       *Status = demangle_invalid_args;
348     return nullptr;
349   }
350 
351   int InternalStatus = demangle_success;
352   Demangler Parser(MangledName, MangledName + std::strlen(MangledName));
353   OutputStream S;
354 
355   Node *AST = Parser.parse();
356 
357   if (AST == nullptr)
358     InternalStatus = demangle_invalid_mangled_name;
359   else if (!initializeOutputStream(Buf, N, S, 1024))
360     InternalStatus = demangle_memory_alloc_failure;
361   else {
362     assert(Parser.ForwardTemplateRefs.empty());
363     AST->print(S);
364     S += '\0';
365     if (N != nullptr)
366       *N = S.getCurrentPosition();
367     Buf = S.getBuffer();
368   }
369 
370   if (Status)
371     *Status = InternalStatus;
372   return InternalStatus == demangle_success ? Buf : nullptr;
373 }
374 }  // __cxxabiv1
375