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 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(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'. 105 void print(bool B) { printStr(B ? "true" : "false"); } 106 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 112 template <class T> 113 typename std::enable_if<std::is_signed<T>::value>::type print(T N) { 114 fprintf(stderr, "%lld", (long long)N); 115 } 116 117 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 } 125 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 } 135 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 } 150 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 } 166 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 } 176 void print(Node::Prec) { 177 // FIXME: Print Prec enumerator 178 } 179 180 void newLine() { 181 printStr("\n"); 182 for (unsigned I = 0; I != Depth; ++I) 183 printStr(" "); 184 PendingNewline = false; 185 } 186 187 template<typename T> void printWithPendingNewline(T V) { 188 print(V); 189 if (wantsNewline(V)) 190 PendingNewline = true; 191 } 192 193 template<typename T> void printWithComma(T V) { 194 if (PendingNewline || wantsNewline(V)) { 195 printStr(","); 196 newLine(); 197 } else { 198 printStr(", "); 199 } 200 201 printWithPendingNewline(V); 202 } 203 204 struct CtorArgPrinter { 205 DumpVisitor &Visitor; 206 207 template<typename T, typename ...Rest> void operator()(T V, Rest ...Vs) { 208 if (Visitor.anyWantNewline(V, Vs...)) 209 Visitor.newLine(); 210 Visitor.printWithPendingNewline(V); 211 int PrintInOrder[] = { (Visitor.printWithComma(Vs), 0)..., 0 }; 212 (void)PrintInOrder; 213 } 214 }; 215 216 template<typename NodeT> void operator()(const NodeT *Node) { 217 Depth += 2; 218 fprintf(stderr, "%s(", itanium_demangle::NodeKind<NodeT>::name()); 219 Node->match(CtorArgPrinter{*this}); 220 fprintf(stderr, ")"); 221 Depth -= 2; 222 } 223 224 void operator()(const ForwardTemplateReference *Node) { 225 Depth += 2; 226 fprintf(stderr, "ForwardTemplateReference("); 227 if (Node->Ref && !Node->Printing) { 228 Node->Printing = true; 229 CtorArgPrinter{*this}(Node->Ref); 230 Node->Printing = false; 231 } else { 232 CtorArgPrinter{*this}(Node->Index); 233 } 234 fprintf(stderr, ")"); 235 Depth -= 2; 236 } 237 }; 238 } 239 240 void itanium_demangle::Node::dump() const { 241 DumpVisitor V; 242 visit(std::ref(V)); 243 V.newLine(); 244 } 245 #endif 246 247 namespace { 248 class BumpPointerAllocator { 249 struct BlockMeta { 250 BlockMeta* Next; 251 size_t Current; 252 }; 253 254 static constexpr size_t AllocSize = 4096; 255 static constexpr size_t UsableAllocSize = AllocSize - sizeof(BlockMeta); 256 257 alignas(long double) char InitialBuffer[AllocSize]; 258 BlockMeta* BlockList = nullptr; 259 260 void grow() { 261 char* NewMeta = static_cast<char *>(std::malloc(AllocSize)); 262 if (NewMeta == nullptr) 263 std::terminate(); 264 BlockList = new (NewMeta) BlockMeta{BlockList, 0}; 265 } 266 267 void* allocateMassive(size_t NBytes) { 268 NBytes += sizeof(BlockMeta); 269 BlockMeta* NewMeta = reinterpret_cast<BlockMeta*>(std::malloc(NBytes)); 270 if (NewMeta == nullptr) 271 std::terminate(); 272 BlockList->Next = new (NewMeta) BlockMeta{BlockList->Next, 0}; 273 return static_cast<void*>(NewMeta + 1); 274 } 275 276 public: 277 BumpPointerAllocator() 278 : BlockList(new (InitialBuffer) BlockMeta{nullptr, 0}) {} 279 280 void* allocate(size_t N) { 281 N = (N + 15u) & ~15u; 282 if (N + BlockList->Current >= UsableAllocSize) { 283 if (N > UsableAllocSize) 284 return allocateMassive(N); 285 grow(); 286 } 287 BlockList->Current += N; 288 return static_cast<void*>(reinterpret_cast<char*>(BlockList + 1) + 289 BlockList->Current - N); 290 } 291 292 void reset() { 293 while (BlockList) { 294 BlockMeta* Tmp = BlockList; 295 BlockList = BlockList->Next; 296 if (reinterpret_cast<char*>(Tmp) != InitialBuffer) 297 std::free(Tmp); 298 } 299 BlockList = new (InitialBuffer) BlockMeta{nullptr, 0}; 300 } 301 302 ~BumpPointerAllocator() { reset(); } 303 }; 304 305 class DefaultAllocator { 306 BumpPointerAllocator Alloc; 307 308 public: 309 void reset() { Alloc.reset(); } 310 311 template<typename T, typename ...Args> T *makeNode(Args &&...args) { 312 return new (Alloc.allocate(sizeof(T))) 313 T(std::forward<Args>(args)...); 314 } 315 316 void *allocateNodeArray(size_t sz) { 317 return Alloc.allocate(sizeof(Node *) * sz); 318 } 319 }; 320 } // unnamed namespace 321 322 //===----------------------------------------------------------------------===// 323 // Code beyond this point should not be synchronized with LLVM. 324 //===----------------------------------------------------------------------===// 325 326 using Demangler = itanium_demangle::ManglingParser<DefaultAllocator>; 327 328 namespace { 329 enum : int { 330 demangle_invalid_args = -3, 331 demangle_invalid_mangled_name = -2, 332 demangle_memory_alloc_failure = -1, 333 demangle_success = 0, 334 }; 335 } 336 337 namespace __cxxabiv1 { 338 extern "C" _LIBCXXABI_FUNC_VIS char * 339 __cxa_demangle(const char *MangledName, char *Buf, size_t *N, int *Status) { 340 if (MangledName == nullptr || (Buf != nullptr && N == nullptr)) { 341 if (Status) 342 *Status = demangle_invalid_args; 343 return nullptr; 344 } 345 346 int InternalStatus = demangle_success; 347 Demangler Parser(MangledName, MangledName + std::strlen(MangledName)); 348 OutputBuffer O; 349 350 Node *AST = Parser.parse(); 351 352 if (AST == nullptr) 353 InternalStatus = demangle_invalid_mangled_name; 354 else if (!initializeOutputBuffer(Buf, N, O, 1024)) 355 InternalStatus = demangle_memory_alloc_failure; 356 else { 357 assert(Parser.ForwardTemplateRefs.empty()); 358 AST->print(O); 359 O += '\0'; 360 if (N != nullptr) 361 *N = O.getCurrentPosition(); 362 Buf = O.getBuffer(); 363 } 364 365 if (Status) 366 *Status = InternalStatus; 367 return InternalStatus == demangle_success ? Buf : nullptr; 368 } 369 } // __cxxabiv1 370