1 //===-- Mangled.cpp ---------------------------------------------*- C++ -*-===//
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 #include "lldb/Core/Mangled.h"
10 
11 #if defined(_WIN32)
12 #include "lldb/Host/windows/windows.h"
13 
14 #include <dbghelp.h>
15 #pragma comment(lib, "dbghelp.lib")
16 #endif
17 
18 #include "lldb/Core/RichManglingContext.h"
19 #include "lldb/Utility/ConstString.h"
20 #include "lldb/Utility/Log.h"
21 #include "lldb/Utility/Logging.h"
22 #include "lldb/Utility/RegularExpression.h"
23 #include "lldb/Utility/Stream.h"
24 #include "lldb/Utility/Timer.h"
25 #include "lldb/lldb-enumerations.h"
26 
27 #include "Plugins/Language/CPlusPlus/CPlusPlusLanguage.h"
28 #include "Plugins/Language/ObjC/ObjCLanguage.h"
29 
30 #include "llvm/ADT/StringRef.h"
31 #include "llvm/Demangle/Demangle.h"
32 #include "llvm/Support/Compiler.h"
33 
34 #include <mutex>
35 #include <string>
36 #include <utility>
37 
38 #include <stdlib.h>
39 #include <string.h>
40 using namespace lldb_private;
41 
42 #if defined(_MSC_VER)
43 static DWORD safeUndecorateName(const char *Mangled, char *Demangled,
44                                 DWORD DemangledLength) {
45   static std::mutex M;
46   std::lock_guard<std::mutex> Lock(M);
47   return ::UnDecorateSymbolName(
48       Mangled, Demangled, DemangledLength,
49       UNDNAME_NO_ACCESS_SPECIFIERS |       // Strip public, private, protected
50                                            // keywords
51           UNDNAME_NO_ALLOCATION_LANGUAGE | // Strip __thiscall, __stdcall,
52                                            // etc keywords
53           UNDNAME_NO_THROW_SIGNATURES |    // Strip throw() specifications
54           UNDNAME_NO_MEMBER_TYPE |         // Strip virtual, static, etc
55                                            // specifiers
56           UNDNAME_NO_MS_KEYWORDS           // Strip all MS extension keywords
57       );
58 }
59 #endif
60 
61 static inline Mangled::ManglingScheme cstring_mangling_scheme(const char *s) {
62   if (s) {
63     if (s[0] == '?')
64       return Mangled::eManglingSchemeMSVC;
65     if (s[0] == '_' && s[1] == 'Z')
66       return Mangled::eManglingSchemeItanium;
67   }
68   return Mangled::eManglingSchemeNone;
69 }
70 
71 static inline bool cstring_is_mangled(const char *s) {
72   return cstring_mangling_scheme(s) != Mangled::eManglingSchemeNone;
73 }
74 
75 static ConstString
76 get_demangled_name_without_arguments(ConstString mangled,
77                                      ConstString demangled) {
78   // This pair is <mangled name, demangled name without function arguments>
79   static std::pair<ConstString, ConstString>
80       g_most_recent_mangled_to_name_sans_args;
81 
82   // Need to have the mangled & demangled names we're currently examining as
83   // statics so we can return a const ref to them at the end of the func if we
84   // don't have anything better.
85   static ConstString g_last_mangled;
86   static ConstString g_last_demangled;
87 
88   if (mangled && g_most_recent_mangled_to_name_sans_args.first == mangled) {
89     return g_most_recent_mangled_to_name_sans_args.second;
90   }
91 
92   g_last_demangled = demangled;
93   g_last_mangled = mangled;
94 
95   const char *mangled_name_cstr = mangled.GetCString();
96 
97   if (demangled && mangled_name_cstr && mangled_name_cstr[0]) {
98     if (mangled_name_cstr[0] == '_' && mangled_name_cstr[1] == 'Z' &&
99         (mangled_name_cstr[2] != 'T' && // avoid virtual table, VTT structure,
100                                         // typeinfo structure, and typeinfo
101                                         // mangled_name
102          mangled_name_cstr[2] != 'G' && // avoid guard variables
103          mangled_name_cstr[2] != 'Z')) // named local entities (if we eventually
104                                        // handle eSymbolTypeData, we will want
105                                        // this back)
106     {
107       CPlusPlusLanguage::MethodName cxx_method(demangled);
108       if (!cxx_method.GetBasename().empty()) {
109         std::string shortname;
110         if (!cxx_method.GetContext().empty())
111           shortname = cxx_method.GetContext().str() + "::";
112         shortname += cxx_method.GetBasename().str();
113         ConstString result(shortname.c_str());
114         g_most_recent_mangled_to_name_sans_args.first = mangled;
115         g_most_recent_mangled_to_name_sans_args.second = result;
116         return g_most_recent_mangled_to_name_sans_args.second;
117       }
118     }
119   }
120 
121   if (demangled)
122     return g_last_demangled;
123   return g_last_mangled;
124 }
125 
126 #pragma mark Mangled
127 
128 Mangled::Mangled(ConstString s) : m_mangled(), m_demangled() {
129   if (s)
130     SetValue(s);
131 }
132 
133 Mangled::Mangled(llvm::StringRef name) {
134   if (!name.empty())
135     SetValue(ConstString(name));
136 }
137 
138 // Convert to pointer operator. This allows code to check any Mangled objects
139 // to see if they contain anything valid using code such as:
140 //
141 //  Mangled mangled(...);
142 //  if (mangled)
143 //  { ...
144 Mangled::operator void *() const {
145   return (m_mangled) ? const_cast<Mangled *>(this) : nullptr;
146 }
147 
148 // Logical NOT operator. This allows code to check any Mangled objects to see
149 // if they are invalid using code such as:
150 //
151 //  Mangled mangled(...);
152 //  if (!file_spec)
153 //  { ...
154 bool Mangled::operator!() const { return !m_mangled; }
155 
156 // Clear the mangled and demangled values.
157 void Mangled::Clear() {
158   m_mangled.Clear();
159   m_demangled.Clear();
160 }
161 
162 // Compare the string values.
163 int Mangled::Compare(const Mangled &a, const Mangled &b) {
164   return ConstString::Compare(
165       a.GetName(lldb::eLanguageTypeUnknown, ePreferMangled),
166       b.GetName(lldb::eLanguageTypeUnknown, ePreferMangled));
167 }
168 
169 // Set the string value in this objects. If "mangled" is true, then the mangled
170 // named is set with the new value in "s", else the demangled name is set.
171 void Mangled::SetValue(ConstString s, bool mangled) {
172   if (s) {
173     if (mangled) {
174       m_demangled.Clear();
175       m_mangled = s;
176     } else {
177       m_demangled = s;
178       m_mangled.Clear();
179     }
180   } else {
181     m_demangled.Clear();
182     m_mangled.Clear();
183   }
184 }
185 
186 void Mangled::SetValue(ConstString name) {
187   if (name) {
188     if (cstring_is_mangled(name.GetCString())) {
189       m_demangled.Clear();
190       m_mangled = name;
191     } else {
192       m_demangled = name;
193       m_mangled.Clear();
194     }
195   } else {
196     m_demangled.Clear();
197     m_mangled.Clear();
198   }
199 }
200 
201 // Local helpers for different demangling implementations.
202 static char *GetMSVCDemangledStr(const char *M) {
203 #if defined(_MSC_VER)
204   const size_t demangled_length = 2048;
205   char *demangled_cstr = static_cast<char *>(::malloc(demangled_length));
206   ::ZeroMemory(demangled_cstr, demangled_length);
207   DWORD result = safeUndecorateName(M, demangled_cstr, demangled_length);
208 
209   if (Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_DEMANGLE)) {
210     if (demangled_cstr && demangled_cstr[0])
211       LLDB_LOGF(log, "demangled msvc: %s -> \"%s\"", M, demangled_cstr);
212     else
213       LLDB_LOGF(log, "demangled msvc: %s -> error: 0x%lu", M, result);
214   }
215 
216   if (result != 0) {
217     return demangled_cstr;
218   } else {
219     ::free(demangled_cstr);
220     return nullptr;
221   }
222 #else
223   return nullptr;
224 #endif
225 }
226 
227 static char *GetItaniumDemangledStr(const char *M) {
228   char *demangled_cstr = nullptr;
229 
230   llvm::ItaniumPartialDemangler ipd;
231   bool err = ipd.partialDemangle(M);
232   if (!err) {
233     // Default buffer and size (will realloc in case it's too small).
234     size_t demangled_size = 80;
235     demangled_cstr = static_cast<char *>(std::malloc(demangled_size));
236     demangled_cstr = ipd.finishDemangle(demangled_cstr, &demangled_size);
237 
238     assert(demangled_cstr &&
239            "finishDemangle must always succeed if partialDemangle did");
240     assert(demangled_cstr[demangled_size - 1] == '\0' &&
241            "Expected demangled_size to return length including trailing null");
242   }
243 
244   if (Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_DEMANGLE)) {
245     if (demangled_cstr)
246       LLDB_LOGF(log, "demangled itanium: %s -> \"%s\"", M, demangled_cstr);
247     else
248       LLDB_LOGF(log, "demangled itanium: %s -> error: failed to demangle", M);
249   }
250 
251   return demangled_cstr;
252 }
253 
254 // Explicit demangling for scheduled requests during batch processing. This
255 // makes use of ItaniumPartialDemangler's rich demangle info
256 bool Mangled::DemangleWithRichManglingInfo(
257     RichManglingContext &context, SkipMangledNameFn *skip_mangled_name) {
258   // We need to generate and cache the demangled name.
259   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
260   Timer scoped_timer(func_cat,
261                      "Mangled::DemangleWithRichNameIndexInfo (m_mangled = %s)",
262                      m_mangled.GetCString());
263 
264   // Others are not meant to arrive here. ObjC names or C's main() for example
265   // have their names stored in m_demangled, while m_mangled is empty.
266   assert(m_mangled);
267 
268   // Check whether or not we are interested in this name at all.
269   ManglingScheme scheme = cstring_mangling_scheme(m_mangled.GetCString());
270   if (skip_mangled_name && skip_mangled_name(m_mangled.GetStringRef(), scheme))
271     return false;
272 
273   switch (scheme) {
274   case eManglingSchemeNone:
275     // The current mangled_name_filter would allow llvm_unreachable here.
276     return false;
277 
278   case eManglingSchemeItanium:
279     // We want the rich mangling info here, so we don't care whether or not
280     // there is a demangled string in the pool already.
281     if (context.FromItaniumName(m_mangled)) {
282       // If we got an info, we have a name. Copy to string pool and connect the
283       // counterparts to accelerate later access in GetDemangledName().
284       context.ParseFullName();
285       m_demangled.SetStringWithMangledCounterpart(context.GetBufferRef(),
286                                                   m_mangled);
287       return true;
288     } else {
289       m_demangled.SetCString("");
290       return false;
291     }
292 
293   case eManglingSchemeMSVC: {
294     // We have no rich mangling for MSVC-mangled names yet, so first try to
295     // demangle it if necessary.
296     if (!m_demangled && !m_mangled.GetMangledCounterpart(m_demangled)) {
297       if (char *d = GetMSVCDemangledStr(m_mangled.GetCString())) {
298         // If we got an info, we have a name. Copy to string pool and connect
299         // the counterparts to accelerate later access in GetDemangledName().
300         m_demangled.SetStringWithMangledCounterpart(llvm::StringRef(d),
301                                                     m_mangled);
302         ::free(d);
303       } else {
304         m_demangled.SetCString("");
305       }
306     }
307 
308     if (m_demangled.IsEmpty()) {
309       // Cannot demangle it, so don't try parsing.
310       return false;
311     } else {
312       // Demangled successfully, we can try and parse it with
313       // CPlusPlusLanguage::MethodName.
314       return context.FromCxxMethodName(m_demangled);
315     }
316   }
317   }
318   llvm_unreachable("Fully covered switch above!");
319 }
320 
321 // Generate the demangled name on demand using this accessor. Code in this
322 // class will need to use this accessor if it wishes to decode the demangled
323 // name. The result is cached and will be kept until a new string value is
324 // supplied to this object, or until the end of the object's lifetime.
325 ConstString
326 Mangled::GetDemangledName(lldb::LanguageType language) const {
327   // Check to make sure we have a valid mangled name and that we haven't
328   // already decoded our mangled name.
329   if (m_mangled && m_demangled.IsNull()) {
330     // We need to generate and cache the demangled name.
331     static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
332     Timer scoped_timer(func_cat, "Mangled::GetDemangledName (m_mangled = %s)",
333                        m_mangled.GetCString());
334 
335     // Don't bother running anything that isn't mangled
336     const char *mangled_name = m_mangled.GetCString();
337     ManglingScheme mangling_scheme{cstring_mangling_scheme(mangled_name)};
338     if (mangling_scheme != eManglingSchemeNone &&
339         !m_mangled.GetMangledCounterpart(m_demangled)) {
340       // We didn't already mangle this name, demangle it and if all goes well
341       // add it to our map.
342       char *demangled_name = nullptr;
343       switch (mangling_scheme) {
344       case eManglingSchemeMSVC:
345         demangled_name = GetMSVCDemangledStr(mangled_name);
346         break;
347       case eManglingSchemeItanium: {
348         demangled_name = GetItaniumDemangledStr(mangled_name);
349         break;
350       }
351       case eManglingSchemeNone:
352         llvm_unreachable("eManglingSchemeNone was handled already");
353       }
354       if (demangled_name) {
355         m_demangled.SetStringWithMangledCounterpart(
356             llvm::StringRef(demangled_name), m_mangled);
357         free(demangled_name);
358       }
359     }
360     if (m_demangled.IsNull()) {
361       // Set the demangled string to the empty string to indicate we tried to
362       // parse it once and failed.
363       m_demangled.SetCString("");
364     }
365   }
366 
367   return m_demangled;
368 }
369 
370 ConstString
371 Mangled::GetDisplayDemangledName(lldb::LanguageType language) const {
372   return GetDemangledName(language);
373 }
374 
375 bool Mangled::NameMatches(const RegularExpression &regex,
376                           lldb::LanguageType language) const {
377   if (m_mangled && regex.Execute(m_mangled.AsCString()))
378     return true;
379 
380   ConstString demangled = GetDemangledName(language);
381   return demangled && regex.Execute(demangled.AsCString());
382 }
383 
384 // Get the demangled name if there is one, else return the mangled name.
385 ConstString Mangled::GetName(lldb::LanguageType language,
386                              Mangled::NamePreference preference) const {
387   if (preference == ePreferMangled && m_mangled)
388     return m_mangled;
389 
390   ConstString demangled = GetDemangledName(language);
391 
392   if (preference == ePreferDemangledWithoutArguments) {
393     return get_demangled_name_without_arguments(m_mangled, demangled);
394   }
395   if (preference == ePreferDemangled) {
396     // Call the accessor to make sure we get a demangled name in case it hasn't
397     // been demangled yet...
398     if (demangled)
399       return demangled;
400     return m_mangled;
401   }
402   return demangled;
403 }
404 
405 // Dump a Mangled object to stream "s". We don't force our demangled name to be
406 // computed currently (we don't use the accessor).
407 void Mangled::Dump(Stream *s) const {
408   if (m_mangled) {
409     *s << ", mangled = " << m_mangled;
410   }
411   if (m_demangled) {
412     const char *demangled = m_demangled.AsCString();
413     s->Printf(", demangled = %s", demangled[0] ? demangled : "<error>");
414   }
415 }
416 
417 // Dumps a debug version of this string with extra object and state information
418 // to stream "s".
419 void Mangled::DumpDebug(Stream *s) const {
420   s->Printf("%*p: Mangled mangled = ", static_cast<int>(sizeof(void *) * 2),
421             static_cast<const void *>(this));
422   m_mangled.DumpDebug(s);
423   s->Printf(", demangled = ");
424   m_demangled.DumpDebug(s);
425 }
426 
427 // Return the size in byte that this object takes in memory. The size includes
428 // the size of the objects it owns, and not the strings that it references
429 // because they are shared strings.
430 size_t Mangled::MemorySize() const {
431   return m_mangled.MemorySize() + m_demangled.MemorySize();
432 }
433 
434 // We "guess" the language because we can't determine a symbol's language from
435 // it's name.  For example, a Pascal symbol can be mangled using the C++
436 // Itanium scheme, and defined in a compilation unit within the same module as
437 // other C++ units.  In addition, different targets could have different ways
438 // of mangling names from a given language, likewise the compilation units
439 // within those targets.
440 lldb::LanguageType Mangled::GuessLanguage() const {
441   ConstString mangled = GetMangledName();
442   if (mangled) {
443     const char *mangled_name = mangled.GetCString();
444     if (CPlusPlusLanguage::IsCPPMangledName(mangled_name))
445       return lldb::eLanguageTypeC_plus_plus;
446     else if (ObjCLanguage::IsPossibleObjCMethodName(mangled_name))
447       return lldb::eLanguageTypeObjC;
448   } else {
449     // ObjC names aren't really mangled, so they won't necessarily be in the
450     // mangled name slot.
451     ConstString demangled_name = GetDemangledName(lldb::eLanguageTypeUnknown);
452     if (demangled_name
453         && ObjCLanguage::IsPossibleObjCMethodName(demangled_name.GetCString()))
454       return lldb::eLanguageTypeObjC;
455 
456   }
457   return lldb::eLanguageTypeUnknown;
458 }
459 
460 // Dump OBJ to the supplied stream S.
461 Stream &operator<<(Stream &s, const Mangled &obj) {
462   if (obj.GetMangledName())
463     s << "mangled = '" << obj.GetMangledName() << "'";
464 
465   ConstString demangled =
466       obj.GetDemangledName(lldb::eLanguageTypeUnknown);
467   if (demangled)
468     s << ", demangled = '" << demangled << '\'';
469   else
470     s << ", demangled = <error>";
471   return s;
472 }
473