xref: /openbsd-src/gnu/llvm/libcxxabi/src/cxa_demangle.cpp (revision 8f1d572453a8bab44a2fe956e25efc4124e87e82)
1 //===----------------------------------------------------------------------===//
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
parse_discriminator(const char * first,const char * last)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 
wantsNewline__anon67b5abab0111::DumpVisitor66   template<typename NodeT> static constexpr bool wantsNewline(const NodeT *) {
67     return true;
68   }
wantsNewline__anon67b5abab0111::DumpVisitor69   static bool wantsNewline(NodeArray A) { return !A.empty(); }
wantsNewline__anon67b5abab0111::DumpVisitor70   static constexpr bool wantsNewline(...) { return false; }
71 
anyWantNewline__anon67b5abab0111::DumpVisitor72   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 
printStr__anon67b5abab0111::DumpVisitor79   void printStr(const char *S) { fprintf(stderr, "%s", S); }
print__anon67b5abab0111::DumpVisitor80   void print(StringView SV) {
81     fprintf(stderr, "\"%.*s\"", (int)SV.size(), SV.begin());
82   }
print__anon67b5abab0111::DumpVisitor83   void print(const Node *N) {
84     if (N)
85       N->visit(std::ref(*this));
86     else
87       printStr("<null>");
88   }
print__anon67b5abab0111::DumpVisitor89   void print(NodeArray A) {
90     ++Depth;
91     printStr("{");
92     bool First = true;
93     for (const Node *N : A) {
94       if (First)
95         print(N);
96       else
97         printWithComma(N);
98       First = false;
99     }
100     printStr("}");
101     --Depth;
102   }
103 
104   // Overload used when T is exactly 'bool', not merely convertible to 'bool'.
print__anon67b5abab0111::DumpVisitor105   void print(bool B) { printStr(B ? "true" : "false"); }
106 
107   template <class T>
print__anon67b5abab0111::DumpVisitor108   typename std::enable_if<std::is_unsigned<T>::value>::type print(T N) {
109     fprintf(stderr, "%llu", (unsigned long long)N);
110   }
111 
112   template <class T>
print__anon67b5abab0111::DumpVisitor113   typename std::enable_if<std::is_signed<T>::value>::type print(T N) {
114     fprintf(stderr, "%lld", (long long)N);
115   }
116 
print__anon67b5abab0111::DumpVisitor117   void print(ReferenceKind RK) {
118     switch (RK) {
119     case ReferenceKind::LValue:
120       return printStr("ReferenceKind::LValue");
121     case ReferenceKind::RValue:
122       return printStr("ReferenceKind::RValue");
123     }
124   }
print__anon67b5abab0111::DumpVisitor125   void print(FunctionRefQual RQ) {
126     switch (RQ) {
127     case FunctionRefQual::FrefQualNone:
128       return printStr("FunctionRefQual::FrefQualNone");
129     case FunctionRefQual::FrefQualLValue:
130       return printStr("FunctionRefQual::FrefQualLValue");
131     case FunctionRefQual::FrefQualRValue:
132       return printStr("FunctionRefQual::FrefQualRValue");
133     }
134   }
print__anon67b5abab0111::DumpVisitor135   void print(Qualifiers Qs) {
136     if (!Qs) return printStr("QualNone");
137     struct QualName { Qualifiers Q; const char *Name; } Names[] = {
138       {QualConst, "QualConst"},
139       {QualVolatile, "QualVolatile"},
140       {QualRestrict, "QualRestrict"},
141     };
142     for (QualName Name : Names) {
143       if (Qs & Name.Q) {
144         printStr(Name.Name);
145         Qs = Qualifiers(Qs & ~Name.Q);
146         if (Qs) printStr(" | ");
147       }
148     }
149   }
print__anon67b5abab0111::DumpVisitor150   void print(SpecialSubKind SSK) {
151     switch (SSK) {
152     case SpecialSubKind::allocator:
153       return printStr("SpecialSubKind::allocator");
154     case SpecialSubKind::basic_string:
155       return printStr("SpecialSubKind::basic_string");
156     case SpecialSubKind::string:
157       return printStr("SpecialSubKind::string");
158     case SpecialSubKind::istream:
159       return printStr("SpecialSubKind::istream");
160     case SpecialSubKind::ostream:
161       return printStr("SpecialSubKind::ostream");
162     case SpecialSubKind::iostream:
163       return printStr("SpecialSubKind::iostream");
164     }
165   }
print__anon67b5abab0111::DumpVisitor166   void print(TemplateParamKind TPK) {
167     switch (TPK) {
168     case TemplateParamKind::Type:
169       return printStr("TemplateParamKind::Type");
170     case TemplateParamKind::NonType:
171       return printStr("TemplateParamKind::NonType");
172     case TemplateParamKind::Template:
173       return printStr("TemplateParamKind::Template");
174     }
175   }
print__anon67b5abab0111::DumpVisitor176   void print(Node::Prec P) {
177     switch (P) {
178     case Node::Prec::Primary:
179       return printStr("Node::Prec::Primary");
180     case Node::Prec::Postfix:
181       return printStr("Node::Prec::Postfix");
182     case Node::Prec::Unary:
183       return printStr("Node::Prec::Unary");
184     case Node::Prec::Cast:
185       return printStr("Node::Prec::Cast");
186     case Node::Prec::PtrMem:
187       return printStr("Node::Prec::PtrMem");
188     case Node::Prec::Multiplicative:
189       return printStr("Node::Prec::Multiplicative");
190     case Node::Prec::Additive:
191       return printStr("Node::Prec::Additive");
192     case Node::Prec::Shift:
193       return printStr("Node::Prec::Shift");
194     case Node::Prec::Spaceship:
195       return printStr("Node::Prec::Spaceship");
196     case Node::Prec::Relational:
197       return printStr("Node::Prec::Relational");
198     case Node::Prec::Equality:
199       return printStr("Node::Prec::Equality");
200     case Node::Prec::And:
201       return printStr("Node::Prec::And");
202     case Node::Prec::Xor:
203       return printStr("Node::Prec::Xor");
204     case Node::Prec::Ior:
205       return printStr("Node::Prec::Ior");
206     case Node::Prec::AndIf:
207       return printStr("Node::Prec::AndIf");
208     case Node::Prec::OrIf:
209       return printStr("Node::Prec::OrIf");
210     case Node::Prec::Conditional:
211       return printStr("Node::Prec::Conditional");
212     case Node::Prec::Assign:
213       return printStr("Node::Prec::Assign");
214     case Node::Prec::Comma:
215       return printStr("Node::Prec::Comma");
216     case Node::Prec::Default:
217       return printStr("Node::Prec::Default");
218     }
219   }
220 
newLine__anon67b5abab0111::DumpVisitor221   void newLine() {
222     printStr("\n");
223     for (unsigned I = 0; I != Depth; ++I)
224       printStr(" ");
225     PendingNewline = false;
226   }
227 
printWithPendingNewline__anon67b5abab0111::DumpVisitor228   template<typename T> void printWithPendingNewline(T V) {
229     print(V);
230     if (wantsNewline(V))
231       PendingNewline = true;
232   }
233 
printWithComma__anon67b5abab0111::DumpVisitor234   template<typename T> void printWithComma(T V) {
235     if (PendingNewline || wantsNewline(V)) {
236       printStr(",");
237       newLine();
238     } else {
239       printStr(", ");
240     }
241 
242     printWithPendingNewline(V);
243   }
244 
245   struct CtorArgPrinter {
246     DumpVisitor &Visitor;
247 
operator ()__anon67b5abab0111::DumpVisitor::CtorArgPrinter248     template<typename T, typename ...Rest> void operator()(T V, Rest ...Vs) {
249       if (Visitor.anyWantNewline(V, Vs...))
250         Visitor.newLine();
251       Visitor.printWithPendingNewline(V);
252       int PrintInOrder[] = { (Visitor.printWithComma(Vs), 0)..., 0 };
253       (void)PrintInOrder;
254     }
255   };
256 
operator ()__anon67b5abab0111::DumpVisitor257   template<typename NodeT> void operator()(const NodeT *Node) {
258     Depth += 2;
259     fprintf(stderr, "%s(", itanium_demangle::NodeKind<NodeT>::name());
260     Node->match(CtorArgPrinter{*this});
261     fprintf(stderr, ")");
262     Depth -= 2;
263   }
264 
operator ()__anon67b5abab0111::DumpVisitor265   void operator()(const ForwardTemplateReference *Node) {
266     Depth += 2;
267     fprintf(stderr, "ForwardTemplateReference(");
268     if (Node->Ref && !Node->Printing) {
269       Node->Printing = true;
270       CtorArgPrinter{*this}(Node->Ref);
271       Node->Printing = false;
272     } else {
273       CtorArgPrinter{*this}(Node->Index);
274     }
275     fprintf(stderr, ")");
276     Depth -= 2;
277   }
278 };
279 }
280 
dump() const281 void itanium_demangle::Node::dump() const {
282   DumpVisitor V;
283   visit(std::ref(V));
284   V.newLine();
285 }
286 #endif
287 
288 namespace {
289 class BumpPointerAllocator {
290   struct BlockMeta {
291     BlockMeta* Next;
292     size_t Current;
293   };
294 
295   static constexpr size_t AllocSize = 4096;
296   static constexpr size_t UsableAllocSize = AllocSize - sizeof(BlockMeta);
297 
298   alignas(long double) char InitialBuffer[AllocSize];
299   BlockMeta* BlockList = nullptr;
300 
grow()301   void grow() {
302     char* NewMeta = static_cast<char *>(std::malloc(AllocSize));
303     if (NewMeta == nullptr)
304       std::terminate();
305     BlockList = new (NewMeta) BlockMeta{BlockList, 0};
306   }
307 
allocateMassive(size_t NBytes)308   void* allocateMassive(size_t NBytes) {
309     NBytes += sizeof(BlockMeta);
310     BlockMeta* NewMeta = reinterpret_cast<BlockMeta*>(std::malloc(NBytes));
311     if (NewMeta == nullptr)
312       std::terminate();
313     BlockList->Next = new (NewMeta) BlockMeta{BlockList->Next, 0};
314     return static_cast<void*>(NewMeta + 1);
315   }
316 
317 public:
BumpPointerAllocator()318   BumpPointerAllocator()
319       : BlockList(new (InitialBuffer) BlockMeta{nullptr, 0}) {}
320 
allocate(size_t N)321   void* allocate(size_t N) {
322     N = (N + 15u) & ~15u;
323     if (N + BlockList->Current >= UsableAllocSize) {
324       if (N > UsableAllocSize)
325         return allocateMassive(N);
326       grow();
327     }
328     BlockList->Current += N;
329     return static_cast<void*>(reinterpret_cast<char*>(BlockList + 1) +
330                               BlockList->Current - N);
331   }
332 
reset()333   void reset() {
334     while (BlockList) {
335       BlockMeta* Tmp = BlockList;
336       BlockList = BlockList->Next;
337       if (reinterpret_cast<char*>(Tmp) != InitialBuffer)
338         std::free(Tmp);
339     }
340     BlockList = new (InitialBuffer) BlockMeta{nullptr, 0};
341   }
342 
~BumpPointerAllocator()343   ~BumpPointerAllocator() { reset(); }
344 };
345 
346 class DefaultAllocator {
347   BumpPointerAllocator Alloc;
348 
349 public:
reset()350   void reset() { Alloc.reset(); }
351 
makeNode(Args &&...args)352   template<typename T, typename ...Args> T *makeNode(Args &&...args) {
353     return new (Alloc.allocate(sizeof(T)))
354         T(std::forward<Args>(args)...);
355   }
356 
allocateNodeArray(size_t sz)357   void *allocateNodeArray(size_t sz) {
358     return Alloc.allocate(sizeof(Node *) * sz);
359   }
360 };
361 }  // unnamed namespace
362 
363 //===----------------------------------------------------------------------===//
364 // Code beyond this point should not be synchronized with LLVM.
365 //===----------------------------------------------------------------------===//
366 
367 using Demangler = itanium_demangle::ManglingParser<DefaultAllocator>;
368 
369 namespace {
370 enum : int {
371   demangle_invalid_args = -3,
372   demangle_invalid_mangled_name = -2,
373   demangle_memory_alloc_failure = -1,
374   demangle_success = 0,
375 };
376 }
377 
378 namespace __cxxabiv1 {
379 extern "C" _LIBCXXABI_FUNC_VIS char *
__cxa_demangle(const char * MangledName,char * Buf,size_t * N,int * Status)380 __cxa_demangle(const char *MangledName, char *Buf, size_t *N, int *Status) {
381   if (MangledName == nullptr || (Buf != nullptr && N == nullptr)) {
382     if (Status)
383       *Status = demangle_invalid_args;
384     return nullptr;
385   }
386 
387   int InternalStatus = demangle_success;
388   Demangler Parser(MangledName, MangledName + std::strlen(MangledName));
389   Node *AST = Parser.parse();
390 
391   if (AST == nullptr)
392     InternalStatus = demangle_invalid_mangled_name;
393   else {
394     OutputBuffer O(Buf, N);
395     assert(Parser.ForwardTemplateRefs.empty());
396     AST->print(O);
397     O += '\0';
398     if (N != nullptr)
399       *N = O.getCurrentPosition();
400     Buf = O.getBuffer();
401   }
402 
403   if (Status)
404     *Status = InternalStatus;
405   return InternalStatus == demangle_success ? Buf : nullptr;
406 }
407 }  // __cxxabiv1
408