1 //===-- Mangled.cpp -------------------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "lldb/Core/Mangled.h"
11 #include "lldb/Core/RichManglingContext.h"
12 #include "lldb/Utility/ConstString.h"
13 #include "lldb/Utility/Log.h"
14 #include "lldb/Utility/Logging.h"
15 #include "lldb/Utility/RegularExpression.h"
16 #include "lldb/Utility/Stream.h"
17 #include "lldb/Utility/Timer.h"
18 #include "lldb/lldb-enumerations.h"
20 #include "Plugins/Language/CPlusPlus/CPlusPlusLanguage.h"
21 #include "Plugins/Language/ObjC/ObjCLanguage.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/Demangle/Demangle.h"
25 #include "llvm/Support/Compiler.h"
33 using namespace lldb_private;
35 static inline bool cstring_is_mangled(llvm::StringRef s) {
36 return Mangled::GetManglingScheme(s) != Mangled::eManglingSchemeNone;
40 get_demangled_name_without_arguments(ConstString mangled,
41 ConstString demangled) {
42 // This pair is <mangled name, demangled name without function arguments>
43 static std::pair<ConstString, ConstString>
44 g_most_recent_mangled_to_name_sans_args;
46 // Need to have the mangled & demangled names we're currently examining as
47 // statics so we can return a const ref to them at the end of the func if we
48 // don't have anything better.
49 static ConstString g_last_mangled;
50 static ConstString g_last_demangled;
52 if (mangled && g_most_recent_mangled_to_name_sans_args.first == mangled) {
53 return g_most_recent_mangled_to_name_sans_args.second;
56 g_last_demangled = demangled;
57 g_last_mangled = mangled;
59 const char *mangled_name_cstr = mangled.GetCString();
61 if (demangled && mangled_name_cstr && mangled_name_cstr[0]) {
62 if (mangled_name_cstr[0] == '_' && mangled_name_cstr[1] == 'Z' &&
63 (mangled_name_cstr[2] != 'T' && // avoid virtual table, VTT structure,
64 // typeinfo structure, and typeinfo
66 mangled_name_cstr[2] != 'G' && // avoid guard variables
67 mangled_name_cstr[2] != 'Z')) // named local entities (if we eventually
68 // handle eSymbolTypeData, we will want
71 CPlusPlusLanguage::MethodName cxx_method(demangled);
72 if (!cxx_method.GetBasename().empty()) {
73 std::string shortname;
74 if (!cxx_method.GetContext().empty())
75 shortname = cxx_method.GetContext().str() + "::";
76 shortname += cxx_method.GetBasename().str();
77 ConstString result(shortname.c_str());
78 g_most_recent_mangled_to_name_sans_args.first = mangled;
79 g_most_recent_mangled_to_name_sans_args.second = result;
80 return g_most_recent_mangled_to_name_sans_args.second;
86 return g_last_demangled;
87 return g_last_mangled;
92 Mangled::ManglingScheme Mangled::GetManglingScheme(llvm::StringRef const name) {
94 return Mangled::eManglingSchemeNone;
96 if (name.startswith("?"))
97 return Mangled::eManglingSchemeMSVC;
99 if (name.startswith("_Z"))
100 return Mangled::eManglingSchemeItanium;
102 // ___Z is a clang extension of block invocations
103 if (name.startswith("___Z"))
104 return Mangled::eManglingSchemeItanium;
106 return Mangled::eManglingSchemeNone;
109 Mangled::Mangled(ConstString s) : m_mangled(), m_demangled() {
114 Mangled::Mangled(llvm::StringRef name) {
116 SetValue(ConstString(name));
119 // Convert to pointer operator. This allows code to check any Mangled objects
120 // to see if they contain anything valid using code such as:
122 // Mangled mangled(...);
125 Mangled::operator void *() const {
126 return (m_mangled) ? const_cast<Mangled *>(this) : nullptr;
129 // Logical NOT operator. This allows code to check any Mangled objects to see
130 // if they are invalid using code such as:
132 // Mangled mangled(...);
135 bool Mangled::operator!() const { return !m_mangled; }
137 // Clear the mangled and demangled values.
138 void Mangled::Clear() {
143 // Compare the string values.
144 int Mangled::Compare(const Mangled &a, const Mangled &b) {
145 return ConstString::Compare(a.GetName(ePreferMangled),
146 b.GetName(ePreferMangled));
149 // Set the string value in this objects. If "mangled" is true, then the mangled
150 // named is set with the new value in "s", else the demangled name is set.
151 void Mangled::SetValue(ConstString s, bool mangled) {
166 void Mangled::SetValue(ConstString name) {
168 if (cstring_is_mangled(name.GetStringRef())) {
181 // Local helpers for different demangling implementations.
182 static char *GetMSVCDemangledStr(const char *M) {
183 char *demangled_cstr = llvm::microsoftDemangle(
184 M, nullptr, nullptr, nullptr, nullptr,
185 llvm::MSDemangleFlags(llvm::MSDF_NoAccessSpecifier |
186 llvm::MSDF_NoCallingConvention |
187 llvm::MSDF_NoMemberType));
189 if (Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_DEMANGLE)) {
190 if (demangled_cstr && demangled_cstr[0])
191 LLDB_LOGF(log, "demangled msvc: %s -> \"%s\"", M, demangled_cstr);
193 LLDB_LOGF(log, "demangled msvc: %s -> error", M);
196 return demangled_cstr;
199 static char *GetItaniumDemangledStr(const char *M) {
200 char *demangled_cstr = nullptr;
202 llvm::ItaniumPartialDemangler ipd;
203 bool err = ipd.partialDemangle(M);
205 // Default buffer and size (will realloc in case it's too small).
206 size_t demangled_size = 80;
207 demangled_cstr = static_cast<char *>(std::malloc(demangled_size));
208 demangled_cstr = ipd.finishDemangle(demangled_cstr, &demangled_size);
210 assert(demangled_cstr &&
211 "finishDemangle must always succeed if partialDemangle did");
212 assert(demangled_cstr[demangled_size - 1] == '\0' &&
213 "Expected demangled_size to return length including trailing null");
216 if (Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_DEMANGLE)) {
218 LLDB_LOGF(log, "demangled itanium: %s -> \"%s\"", M, demangled_cstr);
220 LLDB_LOGF(log, "demangled itanium: %s -> error: failed to demangle", M);
223 return demangled_cstr;
226 // Explicit demangling for scheduled requests during batch processing. This
227 // makes use of ItaniumPartialDemangler's rich demangle info
228 bool Mangled::DemangleWithRichManglingInfo(
229 RichManglingContext &context, SkipMangledNameFn *skip_mangled_name) {
230 // We need to generate and cache the demangled name.
231 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
232 Timer scoped_timer(func_cat,
233 "Mangled::DemangleWithRichNameIndexInfo (m_mangled = %s)",
234 m_mangled.GetCString());
236 // Others are not meant to arrive here. ObjC names or C's main() for example
237 // have their names stored in m_demangled, while m_mangled is empty.
240 // Check whether or not we are interested in this name at all.
241 ManglingScheme scheme = GetManglingScheme(m_mangled.GetStringRef());
242 if (skip_mangled_name && skip_mangled_name(m_mangled.GetStringRef(), scheme))
246 case eManglingSchemeNone:
247 // The current mangled_name_filter would allow llvm_unreachable here.
250 case eManglingSchemeItanium:
251 // We want the rich mangling info here, so we don't care whether or not
252 // there is a demangled string in the pool already.
253 if (context.FromItaniumName(m_mangled)) {
254 // If we got an info, we have a name. Copy to string pool and connect the
255 // counterparts to accelerate later access in GetDemangledName().
256 context.ParseFullName();
257 m_demangled.SetStringWithMangledCounterpart(context.GetBufferRef(),
261 m_demangled.SetCString("");
265 case eManglingSchemeMSVC: {
266 // We have no rich mangling for MSVC-mangled names yet, so first try to
267 // demangle it if necessary.
268 if (!m_demangled && !m_mangled.GetMangledCounterpart(m_demangled)) {
269 if (char *d = GetMSVCDemangledStr(m_mangled.GetCString())) {
270 // If we got an info, we have a name. Copy to string pool and connect
271 // the counterparts to accelerate later access in GetDemangledName().
272 m_demangled.SetStringWithMangledCounterpart(llvm::StringRef(d),
276 m_demangled.SetCString("");
280 if (m_demangled.IsEmpty()) {
281 // Cannot demangle it, so don't try parsing.
284 // Demangled successfully, we can try and parse it with
285 // CPlusPlusLanguage::MethodName.
286 return context.FromCxxMethodName(m_demangled);
290 llvm_unreachable("Fully covered switch above!");
293 // Generate the demangled name on demand using this accessor. Code in this
294 // class will need to use this accessor if it wishes to decode the demangled
295 // name. The result is cached and will be kept until a new string value is
296 // supplied to this object, or until the end of the object's lifetime.
297 ConstString Mangled::GetDemangledName() const {
298 // Check to make sure we have a valid mangled name and that we haven't
299 // already decoded our mangled name.
300 if (m_mangled && m_demangled.IsNull()) {
301 // We need to generate and cache the demangled name.
302 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
303 Timer scoped_timer(func_cat, "Mangled::GetDemangledName (m_mangled = %s)",
304 m_mangled.GetCString());
306 // Don't bother running anything that isn't mangled
307 const char *mangled_name = m_mangled.GetCString();
308 ManglingScheme mangling_scheme = GetManglingScheme(m_mangled.GetStringRef());
309 if (mangling_scheme != eManglingSchemeNone &&
310 !m_mangled.GetMangledCounterpart(m_demangled)) {
311 // We didn't already mangle this name, demangle it and if all goes well
312 // add it to our map.
313 char *demangled_name = nullptr;
314 switch (mangling_scheme) {
315 case eManglingSchemeMSVC:
316 demangled_name = GetMSVCDemangledStr(mangled_name);
318 case eManglingSchemeItanium: {
319 demangled_name = GetItaniumDemangledStr(mangled_name);
322 case eManglingSchemeNone:
323 llvm_unreachable("eManglingSchemeNone was handled already");
325 if (demangled_name) {
326 m_demangled.SetStringWithMangledCounterpart(
327 llvm::StringRef(demangled_name), m_mangled);
328 free(demangled_name);
331 if (m_demangled.IsNull()) {
332 // Set the demangled string to the empty string to indicate we tried to
333 // parse it once and failed.
334 m_demangled.SetCString("");
342 Mangled::GetDisplayDemangledName() const {
343 return GetDemangledName();
346 bool Mangled::NameMatches(const RegularExpression ®ex) const {
347 if (m_mangled && regex.Execute(m_mangled.GetStringRef()))
350 ConstString demangled = GetDemangledName();
351 return demangled && regex.Execute(demangled.GetStringRef());
354 // Get the demangled name if there is one, else return the mangled name.
355 ConstString Mangled::GetName(Mangled::NamePreference preference) const {
356 if (preference == ePreferMangled && m_mangled)
359 ConstString demangled = GetDemangledName();
361 if (preference == ePreferDemangledWithoutArguments) {
362 return get_demangled_name_without_arguments(m_mangled, demangled);
364 if (preference == ePreferDemangled) {
365 // Call the accessor to make sure we get a demangled name in case it hasn't
366 // been demangled yet...
374 // Dump a Mangled object to stream "s". We don't force our demangled name to be
375 // computed currently (we don't use the accessor).
376 void Mangled::Dump(Stream *s) const {
378 *s << ", mangled = " << m_mangled;
381 const char *demangled = m_demangled.AsCString();
382 s->Printf(", demangled = %s", demangled[0] ? demangled : "<error>");
386 // Dumps a debug version of this string with extra object and state information
388 void Mangled::DumpDebug(Stream *s) const {
389 s->Printf("%*p: Mangled mangled = ", static_cast<int>(sizeof(void *) * 2),
390 static_cast<const void *>(this));
391 m_mangled.DumpDebug(s);
392 s->Printf(", demangled = ");
393 m_demangled.DumpDebug(s);
396 // Return the size in byte that this object takes in memory. The size includes
397 // the size of the objects it owns, and not the strings that it references
398 // because they are shared strings.
399 size_t Mangled::MemorySize() const {
400 return m_mangled.MemorySize() + m_demangled.MemorySize();
403 // We "guess" the language because we can't determine a symbol's language from
404 // it's name. For example, a Pascal symbol can be mangled using the C++
405 // Itanium scheme, and defined in a compilation unit within the same module as
406 // other C++ units. In addition, different targets could have different ways
407 // of mangling names from a given language, likewise the compilation units
408 // within those targets.
409 lldb::LanguageType Mangled::GuessLanguage() const {
410 ConstString mangled = GetMangledName();
413 const char *mangled_name = mangled.GetCString();
414 if (CPlusPlusLanguage::IsCPPMangledName(mangled_name))
415 return lldb::eLanguageTypeC_plus_plus;
417 // ObjC names aren't really mangled, so they won't necessarily be in the
418 // mangled name slot.
419 ConstString demangled_name = GetDemangledName();
421 && ObjCLanguage::IsPossibleObjCMethodName(demangled_name.GetCString()))
422 return lldb::eLanguageTypeObjC;
425 return lldb::eLanguageTypeUnknown;
428 // Dump OBJ to the supplied stream S.
429 Stream &operator<<(Stream &s, const Mangled &obj) {
430 if (obj.GetMangledName())
431 s << "mangled = '" << obj.GetMangledName() << "'";
433 ConstString demangled = obj.GetDemangledName();
435 s << ", demangled = '" << demangled << '\'';
437 s << ", demangled = <error>";