xref: /freebsd/contrib/llvm-project/llvm/lib/Demangle/Demangle.cpp (revision b49b6e0f95c89f8dcb5898424c360b46019254b4)
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  
16  static bool isItaniumEncoding(const std::string &MangledName) {
17    size_t Pos = MangledName.find_first_not_of('_');
18    // A valid Itanium encoding requires 1-4 leading underscores, followed by 'Z'.
19    return Pos > 0 && Pos <= 4 && MangledName[Pos] == 'Z';
20  }
21  
22  static bool isRustEncoding(const std::string &MangledName) {
23    return MangledName.size() >= 2 && MangledName[0] == '_' &&
24           MangledName[1] == 'R';
25  }
26  
27  std::string llvm::demangle(const std::string &MangledName) {
28    char *Demangled;
29    if (isItaniumEncoding(MangledName))
30      Demangled = itaniumDemangle(MangledName.c_str(), nullptr, nullptr, nullptr);
31    else if (isRustEncoding(MangledName))
32      Demangled = rustDemangle(MangledName.c_str(), nullptr, nullptr, nullptr);
33    else
34      Demangled = microsoftDemangle(MangledName.c_str(), nullptr, nullptr,
35                                    nullptr, nullptr);
36  
37    if (!Demangled)
38      return MangledName;
39  
40    std::string Ret = Demangled;
41    std::free(Demangled);
42    return Ret;
43  }
44