1 //===-- ItaniumABILanguageRuntime.cpp --------------------------------------*-
2 //C++ -*-===//
3 //
4 //                     The LLVM Compiler Infrastructure
5 //
6 // This file is distributed under the University of Illinois Open Source
7 // License. See LICENSE.TXT for details.
8 //
9 //===----------------------------------------------------------------------===//
10 
11 #include "ItaniumABILanguageRuntime.h"
12 
13 #include "lldb/Breakpoint/BreakpointLocation.h"
14 #include "lldb/Core/Mangled.h"
15 #include "lldb/Core/Module.h"
16 #include "lldb/Core/PluginManager.h"
17 #include "lldb/Core/ValueObject.h"
18 #include "lldb/Core/ValueObjectMemory.h"
19 #include "lldb/Interpreter/CommandObject.h"
20 #include "lldb/Interpreter/CommandObjectMultiword.h"
21 #include "lldb/Interpreter/CommandReturnObject.h"
22 #include "lldb/Symbol/ClangASTContext.h"
23 #include "lldb/Symbol/Symbol.h"
24 #include "lldb/Symbol/SymbolFile.h"
25 #include "lldb/Symbol/TypeList.h"
26 #include "lldb/Target/Process.h"
27 #include "lldb/Target/RegisterContext.h"
28 #include "lldb/Target/SectionLoadList.h"
29 #include "lldb/Target/StopInfo.h"
30 #include "lldb/Target/Target.h"
31 #include "lldb/Target/Thread.h"
32 #include "lldb/Utility/ConstString.h"
33 #include "lldb/Utility/Log.h"
34 #include "lldb/Utility/Scalar.h"
35 #include "lldb/Utility/Status.h"
36 
37 #include <vector>
38 
39 using namespace lldb;
40 using namespace lldb_private;
41 
42 static const char *vtable_demangled_prefix = "vtable for ";
43 
44 bool ItaniumABILanguageRuntime::CouldHaveDynamicValue(ValueObject &in_value) {
45   const bool check_cxx = true;
46   const bool check_objc = false;
47   return in_value.GetCompilerType().IsPossibleDynamicType(NULL, check_cxx,
48                                                           check_objc);
49 }
50 
51 TypeAndOrName ItaniumABILanguageRuntime::GetTypeInfoFromVTableAddress(
52     ValueObject &in_value, lldb::addr_t original_ptr,
53     lldb::addr_t vtable_load_addr) {
54   if (m_process && vtable_load_addr != LLDB_INVALID_ADDRESS) {
55     // Find the symbol that contains the "vtable_load_addr" address
56     Address vtable_addr;
57     Target &target = m_process->GetTarget();
58     if (!target.GetSectionLoadList().IsEmpty()) {
59       if (target.GetSectionLoadList().ResolveLoadAddress(vtable_load_addr,
60                                                          vtable_addr)) {
61         // See if we have cached info for this type already
62         TypeAndOrName type_info = GetDynamicTypeInfo(vtable_addr);
63         if (type_info)
64           return type_info;
65 
66         SymbolContext sc;
67         target.GetImages().ResolveSymbolContextForAddress(
68             vtable_addr, eSymbolContextSymbol, sc);
69         Symbol *symbol = sc.symbol;
70         if (symbol != NULL) {
71           const char *name =
72               symbol->GetMangled()
73                   .GetDemangledName(lldb::eLanguageTypeC_plus_plus)
74                   .AsCString();
75           if (name && strstr(name, vtable_demangled_prefix) == name) {
76             Log *log(
77                 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
78             if (log)
79               log->Printf("0x%16.16" PRIx64
80                           ": static-type = '%s' has vtable symbol '%s'\n",
81                           original_ptr, in_value.GetTypeName().GetCString(),
82                           name);
83             // We are a C++ class, that's good.  Get the class name and look it
84             // up:
85             const char *class_name = name + strlen(vtable_demangled_prefix);
86             // We know the class name is absolute, so tell FindTypes that by
87             // prefixing it with the root namespace:
88             std::string lookup_name("::");
89             lookup_name.append(class_name);
90 
91             type_info.SetName(class_name);
92             const bool exact_match = true;
93             TypeList class_types;
94 
95             uint32_t num_matches = 0;
96             // First look in the module that the vtable symbol came from and
97             // look for a single exact match.
98             llvm::DenseSet<SymbolFile *> searched_symbol_files;
99             if (sc.module_sp) {
100               num_matches = sc.module_sp->FindTypes(
101                   sc, ConstString(lookup_name), exact_match, 1,
102                   searched_symbol_files, class_types);
103             }
104 
105             // If we didn't find a symbol, then move on to the entire module
106             // list in the target and get as many unique matches as possible
107             if (num_matches == 0) {
108               num_matches = target.GetImages().FindTypes(
109                   sc, ConstString(lookup_name), exact_match, UINT32_MAX,
110                   searched_symbol_files, class_types);
111             }
112 
113             lldb::TypeSP type_sp;
114             if (num_matches == 0) {
115               if (log)
116                 log->Printf("0x%16.16" PRIx64 ": is not dynamic\n",
117                             original_ptr);
118               return TypeAndOrName();
119             }
120             if (num_matches == 1) {
121               type_sp = class_types.GetTypeAtIndex(0);
122               if (type_sp) {
123                 if (ClangASTContext::IsCXXClassType(
124                         type_sp->GetForwardCompilerType())) {
125                   if (log)
126                     log->Printf(
127                         "0x%16.16" PRIx64
128                         ": static-type = '%s' has dynamic type: uid={0x%" PRIx64
129                         "}, type-name='%s'\n",
130                         original_ptr, in_value.GetTypeName().AsCString(),
131                         type_sp->GetID(), type_sp->GetName().GetCString());
132                   type_info.SetTypeSP(type_sp);
133                 }
134               }
135             } else if (num_matches > 1) {
136               size_t i;
137               if (log) {
138                 for (i = 0; i < num_matches; i++) {
139                   type_sp = class_types.GetTypeAtIndex(i);
140                   if (type_sp) {
141                     if (log)
142                       log->Printf(
143                           "0x%16.16" PRIx64
144                           ": static-type = '%s' has multiple matching dynamic "
145                           "types: uid={0x%" PRIx64 "}, type-name='%s'\n",
146                           original_ptr, in_value.GetTypeName().AsCString(),
147                           type_sp->GetID(), type_sp->GetName().GetCString());
148                   }
149                 }
150               }
151 
152               for (i = 0; i < num_matches; i++) {
153                 type_sp = class_types.GetTypeAtIndex(i);
154                 if (type_sp) {
155                   if (ClangASTContext::IsCXXClassType(
156                           type_sp->GetForwardCompilerType())) {
157                     if (log)
158                       log->Printf(
159                           "0x%16.16" PRIx64 ": static-type = '%s' has multiple "
160                                             "matching dynamic types, picking "
161                                             "this one: uid={0x%" PRIx64
162                           "}, type-name='%s'\n",
163                           original_ptr, in_value.GetTypeName().AsCString(),
164                           type_sp->GetID(), type_sp->GetName().GetCString());
165                     type_info.SetTypeSP(type_sp);
166                   }
167                 }
168               }
169 
170               if (log && i == num_matches) {
171                 log->Printf(
172                     "0x%16.16" PRIx64
173                     ": static-type = '%s' has multiple matching dynamic "
174                     "types, didn't find a C++ match\n",
175                     original_ptr, in_value.GetTypeName().AsCString());
176               }
177             }
178             if (type_info)
179               SetDynamicTypeInfo(vtable_addr, type_info);
180             return type_info;
181           }
182         }
183       }
184     }
185   }
186   return TypeAndOrName();
187 }
188 
189 bool ItaniumABILanguageRuntime::GetDynamicTypeAndAddress(
190     ValueObject &in_value, lldb::DynamicValueType use_dynamic,
191     TypeAndOrName &class_type_or_name, Address &dynamic_address,
192     Value::ValueType &value_type) {
193   // For Itanium, if the type has a vtable pointer in the object, it will be at
194   // offset 0 in the object.  That will point to the "address point" within the
195   // vtable (not the beginning of the vtable.)  We can then look up the symbol
196   // containing this "address point" and that symbol's name demangled will
197   // contain the full class name. The second pointer above the "address point"
198   // is the "offset_to_top".  We'll use that to get the start of the value
199   // object which holds the dynamic type.
200   //
201 
202   class_type_or_name.Clear();
203   value_type = Value::ValueType::eValueTypeScalar;
204 
205   // Only a pointer or reference type can have a different dynamic and static
206   // type:
207   if (!CouldHaveDynamicValue(in_value))
208     return false;
209 
210   // First job, pull out the address at 0 offset from the object.
211   AddressType address_type;
212   lldb::addr_t original_ptr = in_value.GetPointerValue(&address_type);
213   if (original_ptr == LLDB_INVALID_ADDRESS)
214     return false;
215 
216   ExecutionContext exe_ctx(in_value.GetExecutionContextRef());
217 
218   Process *process = exe_ctx.GetProcessPtr();
219 
220   if (process == nullptr)
221     return false;
222 
223   Status error;
224   const lldb::addr_t vtable_address_point =
225       process->ReadPointerFromMemory(original_ptr, error);
226 
227   if (!error.Success() || vtable_address_point == LLDB_INVALID_ADDRESS)
228     return false;
229 
230   class_type_or_name = GetTypeInfoFromVTableAddress(in_value, original_ptr,
231                                                     vtable_address_point);
232 
233   if (!class_type_or_name)
234     return false;
235 
236   TypeSP type_sp = class_type_or_name.GetTypeSP();
237   // There can only be one type with a given name, so we've just found
238   // duplicate definitions, and this one will do as well as any other. We
239   // don't consider something to have a dynamic type if it is the same as
240   // the static type.  So compare against the value we were handed.
241   if (!type_sp)
242     return true;
243 
244   if (ClangASTContext::AreTypesSame(in_value.GetCompilerType(),
245                                     type_sp->GetForwardCompilerType())) {
246     // The dynamic type we found was the same type, so we don't have a
247     // dynamic type here...
248     return false;
249   }
250 
251   // The offset_to_top is two pointers above the vtable pointer.
252   const uint32_t addr_byte_size = process->GetAddressByteSize();
253   const lldb::addr_t offset_to_top_location =
254       vtable_address_point - 2 * addr_byte_size;
255   // Watch for underflow, offset_to_top_location should be less than
256   // vtable_address_point
257   if (offset_to_top_location >= vtable_address_point)
258     return false;
259   const int64_t offset_to_top = process->ReadSignedIntegerFromMemory(
260       offset_to_top_location, addr_byte_size, INT64_MIN, error);
261 
262   if (offset_to_top == INT64_MIN)
263     return false;
264   // So the dynamic type is a value that starts at offset_to_top above
265   // the original address.
266   lldb::addr_t dynamic_addr = original_ptr + offset_to_top;
267   if (!process->GetTarget().GetSectionLoadList().ResolveLoadAddress(
268           dynamic_addr, dynamic_address)) {
269     dynamic_address.SetRawAddress(dynamic_addr);
270   }
271   return true;
272 }
273 
274 TypeAndOrName ItaniumABILanguageRuntime::FixUpDynamicType(
275     const TypeAndOrName &type_and_or_name, ValueObject &static_value) {
276   CompilerType static_type(static_value.GetCompilerType());
277   Flags static_type_flags(static_type.GetTypeInfo());
278 
279   TypeAndOrName ret(type_and_or_name);
280   if (type_and_or_name.HasType()) {
281     // The type will always be the type of the dynamic object.  If our parent's
282     // type was a pointer, then our type should be a pointer to the type of the
283     // dynamic object.  If a reference, then the original type should be
284     // okay...
285     CompilerType orig_type = type_and_or_name.GetCompilerType();
286     CompilerType corrected_type = orig_type;
287     if (static_type_flags.AllSet(eTypeIsPointer))
288       corrected_type = orig_type.GetPointerType();
289     else if (static_type_flags.AllSet(eTypeIsReference))
290       corrected_type = orig_type.GetLValueReferenceType();
291     ret.SetCompilerType(corrected_type);
292   } else {
293     // If we are here we need to adjust our dynamic type name to include the
294     // correct & or * symbol
295     std::string corrected_name(type_and_or_name.GetName().GetCString());
296     if (static_type_flags.AllSet(eTypeIsPointer))
297       corrected_name.append(" *");
298     else if (static_type_flags.AllSet(eTypeIsReference))
299       corrected_name.append(" &");
300     // the parent type should be a correctly pointer'ed or referenc'ed type
301     ret.SetCompilerType(static_type);
302     ret.SetName(corrected_name.c_str());
303   }
304   return ret;
305 }
306 
307 bool ItaniumABILanguageRuntime::IsVTableName(const char *name) {
308   if (name == NULL)
309     return false;
310 
311   // Can we maybe ask Clang about this?
312   return strstr(name, "_vptr$") == name;
313 }
314 
315 //------------------------------------------------------------------
316 // Static Functions
317 //------------------------------------------------------------------
318 LanguageRuntime *
319 ItaniumABILanguageRuntime::CreateInstance(Process *process,
320                                           lldb::LanguageType language) {
321   // FIXME: We have to check the process and make sure we actually know that
322   // this process supports
323   // the Itanium ABI.
324   if (language == eLanguageTypeC_plus_plus ||
325       language == eLanguageTypeC_plus_plus_03 ||
326       language == eLanguageTypeC_plus_plus_11 ||
327       language == eLanguageTypeC_plus_plus_14)
328     return new ItaniumABILanguageRuntime(process);
329   else
330     return NULL;
331 }
332 
333 class CommandObjectMultiwordItaniumABI_Demangle : public CommandObjectParsed {
334 public:
335   CommandObjectMultiwordItaniumABI_Demangle(CommandInterpreter &interpreter)
336       : CommandObjectParsed(interpreter, "demangle",
337                             "Demangle a C++ mangled name.",
338                             "language cplusplus demangle") {
339     CommandArgumentEntry arg;
340     CommandArgumentData index_arg;
341 
342     // Define the first (and only) variant of this arg.
343     index_arg.arg_type = eArgTypeSymbol;
344     index_arg.arg_repetition = eArgRepeatPlus;
345 
346     // There is only one variant this argument could be; put it into the
347     // argument entry.
348     arg.push_back(index_arg);
349 
350     // Push the data for the first argument into the m_arguments vector.
351     m_arguments.push_back(arg);
352   }
353 
354   ~CommandObjectMultiwordItaniumABI_Demangle() override = default;
355 
356 protected:
357   bool DoExecute(Args &command, CommandReturnObject &result) override {
358     bool demangled_any = false;
359     bool error_any = false;
360     for (auto &entry : command.entries()) {
361       if (entry.ref.empty())
362         continue;
363 
364       // the actual Mangled class should be strict about this, but on the
365       // command line if you're copying mangled names out of 'nm' on Darwin,
366       // they will come out with an extra underscore - be willing to strip this
367       // on behalf of the user.   This is the moral equivalent of the -_/-n
368       // options to c++filt
369       auto name = entry.ref;
370       if (name.startswith("__Z"))
371         name = name.drop_front();
372 
373       Mangled mangled(name, true);
374       if (mangled.GuessLanguage() == lldb::eLanguageTypeC_plus_plus) {
375         ConstString demangled(
376             mangled.GetDisplayDemangledName(lldb::eLanguageTypeC_plus_plus));
377         demangled_any = true;
378         result.AppendMessageWithFormat("%s ---> %s\n", entry.ref.str().c_str(),
379                                        demangled.GetCString());
380       } else {
381         error_any = true;
382         result.AppendErrorWithFormat("%s is not a valid C++ mangled name\n",
383                                      entry.ref.str().c_str());
384       }
385     }
386 
387     result.SetStatus(
388         error_any ? lldb::eReturnStatusFailed
389                   : (demangled_any ? lldb::eReturnStatusSuccessFinishResult
390                                    : lldb::eReturnStatusSuccessFinishNoResult));
391     return result.Succeeded();
392   }
393 };
394 
395 class CommandObjectMultiwordItaniumABI : public CommandObjectMultiword {
396 public:
397   CommandObjectMultiwordItaniumABI(CommandInterpreter &interpreter)
398       : CommandObjectMultiword(
399             interpreter, "cplusplus",
400             "Commands for operating on the C++ language runtime.",
401             "cplusplus <subcommand> [<subcommand-options>]") {
402     LoadSubCommand(
403         "demangle",
404         CommandObjectSP(
405             new CommandObjectMultiwordItaniumABI_Demangle(interpreter)));
406   }
407 
408   ~CommandObjectMultiwordItaniumABI() override = default;
409 };
410 
411 void ItaniumABILanguageRuntime::Initialize() {
412   PluginManager::RegisterPlugin(
413       GetPluginNameStatic(), "Itanium ABI for the C++ language", CreateInstance,
414       [](CommandInterpreter &interpreter) -> lldb::CommandObjectSP {
415         return CommandObjectSP(
416             new CommandObjectMultiwordItaniumABI(interpreter));
417       });
418 }
419 
420 void ItaniumABILanguageRuntime::Terminate() {
421   PluginManager::UnregisterPlugin(CreateInstance);
422 }
423 
424 lldb_private::ConstString ItaniumABILanguageRuntime::GetPluginNameStatic() {
425   static ConstString g_name("itanium");
426   return g_name;
427 }
428 
429 //------------------------------------------------------------------
430 // PluginInterface protocol
431 //------------------------------------------------------------------
432 lldb_private::ConstString ItaniumABILanguageRuntime::GetPluginName() {
433   return GetPluginNameStatic();
434 }
435 
436 uint32_t ItaniumABILanguageRuntime::GetPluginVersion() { return 1; }
437 
438 BreakpointResolverSP ItaniumABILanguageRuntime::CreateExceptionResolver(
439     Breakpoint *bkpt, bool catch_bp, bool throw_bp) {
440   return CreateExceptionResolver(bkpt, catch_bp, throw_bp, false);
441 }
442 
443 BreakpointResolverSP ItaniumABILanguageRuntime::CreateExceptionResolver(
444     Breakpoint *bkpt, bool catch_bp, bool throw_bp, bool for_expressions) {
445   // One complication here is that most users DON'T want to stop at
446   // __cxa_allocate_expression, but until we can do anything better with
447   // predicting unwinding the expression parser does.  So we have two forms of
448   // the exception breakpoints, one for expressions that leaves out
449   // __cxa_allocate_exception, and one that includes it. The
450   // SetExceptionBreakpoints does the latter, the CreateExceptionBreakpoint in
451   // the runtime the former.
452   static const char *g_catch_name = "__cxa_begin_catch";
453   static const char *g_throw_name1 = "__cxa_throw";
454   static const char *g_throw_name2 = "__cxa_rethrow";
455   static const char *g_exception_throw_name = "__cxa_allocate_exception";
456   std::vector<const char *> exception_names;
457   exception_names.reserve(4);
458   if (catch_bp)
459     exception_names.push_back(g_catch_name);
460 
461   if (throw_bp) {
462     exception_names.push_back(g_throw_name1);
463     exception_names.push_back(g_throw_name2);
464   }
465 
466   if (for_expressions)
467     exception_names.push_back(g_exception_throw_name);
468 
469   BreakpointResolverSP resolver_sp(new BreakpointResolverName(
470       bkpt, exception_names.data(), exception_names.size(),
471       eFunctionNameTypeBase, eLanguageTypeUnknown, 0, eLazyBoolNo));
472 
473   return resolver_sp;
474 }
475 
476 lldb::SearchFilterSP ItaniumABILanguageRuntime::CreateExceptionSearchFilter() {
477   Target &target = m_process->GetTarget();
478 
479   if (target.GetArchitecture().GetTriple().getVendor() == llvm::Triple::Apple) {
480     // Limit the number of modules that are searched for these breakpoints for
481     // Apple binaries.
482     FileSpecList filter_modules;
483     filter_modules.Append(FileSpec("libc++abi.dylib"));
484     filter_modules.Append(FileSpec("libSystem.B.dylib"));
485     return target.GetSearchFilterForModuleList(&filter_modules);
486   } else {
487     return LanguageRuntime::CreateExceptionSearchFilter();
488   }
489 }
490 
491 lldb::BreakpointSP ItaniumABILanguageRuntime::CreateExceptionBreakpoint(
492     bool catch_bp, bool throw_bp, bool for_expressions, bool is_internal) {
493   Target &target = m_process->GetTarget();
494   FileSpecList filter_modules;
495   BreakpointResolverSP exception_resolver_sp =
496       CreateExceptionResolver(NULL, catch_bp, throw_bp, for_expressions);
497   SearchFilterSP filter_sp(CreateExceptionSearchFilter());
498   const bool hardware = false;
499   const bool resolve_indirect_functions = false;
500   return target.CreateBreakpoint(filter_sp, exception_resolver_sp, is_internal,
501                                  hardware, resolve_indirect_functions);
502 }
503 
504 void ItaniumABILanguageRuntime::SetExceptionBreakpoints() {
505   if (!m_process)
506     return;
507 
508   const bool catch_bp = false;
509   const bool throw_bp = true;
510   const bool is_internal = true;
511   const bool for_expressions = true;
512 
513   // For the exception breakpoints set by the Expression parser, we'll be a
514   // little more aggressive and stop at exception allocation as well.
515 
516   if (m_cxx_exception_bp_sp) {
517     m_cxx_exception_bp_sp->SetEnabled(true);
518   } else {
519     m_cxx_exception_bp_sp = CreateExceptionBreakpoint(
520         catch_bp, throw_bp, for_expressions, is_internal);
521     if (m_cxx_exception_bp_sp)
522       m_cxx_exception_bp_sp->SetBreakpointKind("c++ exception");
523   }
524 }
525 
526 void ItaniumABILanguageRuntime::ClearExceptionBreakpoints() {
527   if (!m_process)
528     return;
529 
530   if (m_cxx_exception_bp_sp) {
531     m_cxx_exception_bp_sp->SetEnabled(false);
532   }
533 }
534 
535 bool ItaniumABILanguageRuntime::ExceptionBreakpointsAreSet() {
536   return m_cxx_exception_bp_sp && m_cxx_exception_bp_sp->IsEnabled();
537 }
538 
539 bool ItaniumABILanguageRuntime::ExceptionBreakpointsExplainStop(
540     lldb::StopInfoSP stop_reason) {
541   if (!m_process)
542     return false;
543 
544   if (!stop_reason || stop_reason->GetStopReason() != eStopReasonBreakpoint)
545     return false;
546 
547   uint64_t break_site_id = stop_reason->GetValue();
548   return m_process->GetBreakpointSiteList().BreakpointSiteContainsBreakpoint(
549       break_site_id, m_cxx_exception_bp_sp->GetID());
550 }
551 
552 TypeAndOrName ItaniumABILanguageRuntime::GetDynamicTypeInfo(
553     const lldb_private::Address &vtable_addr) {
554   std::lock_guard<std::mutex> locker(m_dynamic_type_map_mutex);
555   DynamicTypeCache::const_iterator pos = m_dynamic_type_map.find(vtable_addr);
556   if (pos == m_dynamic_type_map.end())
557     return TypeAndOrName();
558   else
559     return pos->second;
560 }
561 
562 void ItaniumABILanguageRuntime::SetDynamicTypeInfo(
563     const lldb_private::Address &vtable_addr, const TypeAndOrName &type_info) {
564   std::lock_guard<std::mutex> locker(m_dynamic_type_map_mutex);
565   m_dynamic_type_map[vtable_addr] = type_info;
566 }
567