1 //===-- Demangle.cpp - Common demangling functions ------------------------===//
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 /// \file This file contains definitions of common demangling functions.
10 ///
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/Demangle/Demangle.h"
14 #include <cstdlib>
15 #include <cstring>
16 
17 static bool isItaniumEncoding(const char *S) {
18   // Itanium encoding requires 1 or 3 leading underscores, followed by 'Z'.
19   return std::strncmp(S, "_Z", 2) == 0 || std::strncmp(S, "___Z", 4) == 0;
20 }
21 
22 static bool isRustEncoding(const char *S) { return S[0] == '_' && S[1] == 'R'; }
23 
24 std::string llvm::demangle(const std::string &MangledName) {
25   std::string Result;
26   const char *S = MangledName.c_str();
27 
28   if (nonMicrosoftDemangle(S, Result))
29     return Result;
30 
31   if (S[0] == '_' && nonMicrosoftDemangle(S + 1, Result))
32     return Result;
33 
34   if (char *Demangled =
35           microsoftDemangle(S, nullptr, nullptr, nullptr, nullptr)) {
36     Result = Demangled;
37     std::free(Demangled);
38     return Result;
39   }
40 
41   return MangledName;
42 }
43 
44 bool llvm::nonMicrosoftDemangle(const char *MangledName, std::string &Result) {
45   char *Demangled = nullptr;
46   if (isItaniumEncoding(MangledName))
47     Demangled = itaniumDemangle(MangledName, nullptr, nullptr, nullptr);
48   else if (isRustEncoding(MangledName))
49     Demangled = rustDemangle(MangledName, nullptr, nullptr, nullptr);
50 
51   if (!Demangled)
52     return false;
53 
54   Result = Demangled;
55   std::free(Demangled);
56   return true;
57 }
58