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 "llvm/Demangle/StringViewExtras.h"
15#include <cstdlib>
16#include <string_view>
17
18using llvm::itanium_demangle::starts_with;
19
20std::string llvm::demangle(std::string_view MangledName) {
21 std::string Result;
22
23 if (nonMicrosoftDemangle(MangledName, Result))
24 return Result;
25
26 if (starts_with(self: MangledName, C: '_') &&
27 nonMicrosoftDemangle(MangledName: MangledName.substr(pos: 1), Result,
28 /*CanHaveLeadingDot=*/false))
29 return Result;
30
31 if (char *Demangled = microsoftDemangle(mangled_name: MangledName, n_read: nullptr, status: nullptr)) {
32 Result = Demangled;
33 std::free(ptr: Demangled);
34 } else {
35 Result = MangledName;
36 }
37 return Result;
38}
39
40static bool isItaniumEncoding(std::string_view S) {
41 // Itanium demangler supports prefixes with 1-4 underscores.
42 const size_t Pos = S.find_first_not_of(c: '_');
43 return Pos > 0 && Pos <= 4 && S[Pos] == 'Z';
44}
45
46static bool isRustEncoding(std::string_view S) { return starts_with(haystack: S, needle: "_R"); }
47
48static bool isDLangEncoding(std::string_view S) { return starts_with(haystack: S, needle: "_D"); }
49
50bool llvm::nonMicrosoftDemangle(std::string_view MangledName,
51 std::string &Result, bool CanHaveLeadingDot,
52 bool ParseParams) {
53 char *Demangled = nullptr;
54
55 // Do not consider the dot prefix as part of the demangled symbol name.
56 if (CanHaveLeadingDot && MangledName.size() > 0 && MangledName[0] == '.') {
57 MangledName.remove_prefix(n: 1);
58 Result = ".";
59 }
60
61 if (isItaniumEncoding(S: MangledName))
62 Demangled = itaniumDemangle(mangled_name: MangledName, ParseParams);
63 else if (isRustEncoding(S: MangledName))
64 Demangled = rustDemangle(MangledName);
65 else if (isDLangEncoding(S: MangledName))
66 Demangled = dlangDemangle(MangledName);
67
68 if (!Demangled)
69 return false;
70
71 Result += Demangled;
72 std::free(ptr: Demangled);
73 return true;
74}
75