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/Scalar.h"
18 #include "lldb/Core/ValueObject.h"
19 #include "lldb/Core/ValueObjectMemory.h"
20 #include "lldb/Interpreter/CommandObject.h"
21 #include "lldb/Interpreter/CommandObjectMultiword.h"
22 #include "lldb/Interpreter/CommandReturnObject.h"
23 #include "lldb/Symbol/ClangASTContext.h"
24 #include "lldb/Symbol/Symbol.h"
25 #include "lldb/Symbol/SymbolFile.h"
26 #include "lldb/Symbol/TypeList.h"
27 #include "lldb/Target/Process.h"
28 #include "lldb/Target/RegisterContext.h"
29 #include "lldb/Target/SectionLoadList.h"
30 #include "lldb/Target/StopInfo.h"
31 #include "lldb/Target/Target.h"
32 #include "lldb/Target/Thread.h"
33 #include "lldb/Utility/ConstString.h"
34 #include "lldb/Utility/Log.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     // First job, pull out the address at 0 offset from the object.
209     AddressType address_type;
210     lldb::addr_t original_ptr = in_value.GetPointerValue(&address_type);
211     if (original_ptr == LLDB_INVALID_ADDRESS)
212       return false;
213 
214     ExecutionContext exe_ctx(in_value.GetExecutionContextRef());
215 
216     Process *process = exe_ctx.GetProcessPtr();
217 
218     if (process == nullptr)
219       return false;
220 
221     Status error;
222     const lldb::addr_t vtable_address_point =
223         process->ReadPointerFromMemory(original_ptr, error);
224 
225     if (!error.Success() || vtable_address_point == LLDB_INVALID_ADDRESS) {
226       return false;
227     }
228 
229     class_type_or_name = GetTypeInfoFromVTableAddress(in_value, original_ptr,
230                                                       vtable_address_point);
231 
232     if (class_type_or_name) {
233       TypeSP type_sp = class_type_or_name.GetTypeSP();
234       // There can only be one type with a given name, so we've just found
235       // duplicate definitions, and this one will do as well as any other. We
236       // don't consider something to have a dynamic type if it is the same as
237       // the static type.  So compare against the value we were handed.
238       if (type_sp) {
239         if (ClangASTContext::AreTypesSame(in_value.GetCompilerType(),
240                                           type_sp->GetForwardCompilerType())) {
241           // The dynamic type we found was the same type, so we don't have a
242           // dynamic type here...
243           return false;
244         }
245 
246         // The offset_to_top is two pointers above the vtable pointer.
247         const uint32_t addr_byte_size = process->GetAddressByteSize();
248         const lldb::addr_t offset_to_top_location =
249             vtable_address_point - 2 * addr_byte_size;
250         // Watch for underflow, offset_to_top_location should be less than
251         // vtable_address_point
252         if (offset_to_top_location >= vtable_address_point)
253           return false;
254         const int64_t offset_to_top = process->ReadSignedIntegerFromMemory(
255             offset_to_top_location, addr_byte_size, INT64_MIN, error);
256 
257         if (offset_to_top == INT64_MIN)
258           return false;
259         // So the dynamic type is a value that starts at offset_to_top above
260         // the original address.
261         lldb::addr_t dynamic_addr = original_ptr + offset_to_top;
262         if (!process->GetTarget().GetSectionLoadList().ResolveLoadAddress(
263                 dynamic_addr, dynamic_address)) {
264           dynamic_address.SetRawAddress(dynamic_addr);
265         }
266         return true;
267       }
268     }
269   }
270 
271   return class_type_or_name.IsEmpty() == false;
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   if (strstr(name, "_vptr$") == name)
313     return true;
314   else
315     return false;
316 }
317 
318 //------------------------------------------------------------------
319 // Static Functions
320 //------------------------------------------------------------------
321 LanguageRuntime *
322 ItaniumABILanguageRuntime::CreateInstance(Process *process,
323                                           lldb::LanguageType language) {
324   // FIXME: We have to check the process and make sure we actually know that
325   // this process supports
326   // the Itanium ABI.
327   if (language == eLanguageTypeC_plus_plus ||
328       language == eLanguageTypeC_plus_plus_03 ||
329       language == eLanguageTypeC_plus_plus_11 ||
330       language == eLanguageTypeC_plus_plus_14)
331     return new ItaniumABILanguageRuntime(process);
332   else
333     return NULL;
334 }
335 
336 class CommandObjectMultiwordItaniumABI_Demangle : public CommandObjectParsed {
337 public:
338   CommandObjectMultiwordItaniumABI_Demangle(CommandInterpreter &interpreter)
339       : CommandObjectParsed(interpreter, "demangle",
340                             "Demangle a C++ mangled name.",
341                             "language cplusplus demangle") {
342     CommandArgumentEntry arg;
343     CommandArgumentData index_arg;
344 
345     // Define the first (and only) variant of this arg.
346     index_arg.arg_type = eArgTypeSymbol;
347     index_arg.arg_repetition = eArgRepeatPlus;
348 
349     // There is only one variant this argument could be; put it into the
350     // argument entry.
351     arg.push_back(index_arg);
352 
353     // Push the data for the first argument into the m_arguments vector.
354     m_arguments.push_back(arg);
355   }
356 
357   ~CommandObjectMultiwordItaniumABI_Demangle() override = default;
358 
359 protected:
360   bool DoExecute(Args &command, CommandReturnObject &result) override {
361     bool demangled_any = false;
362     bool error_any = false;
363     for (auto &entry : command.entries()) {
364       if (entry.ref.empty())
365         continue;
366 
367       // the actual Mangled class should be strict about this, but on the
368       // command line if you're copying mangled names out of 'nm' on Darwin,
369       // they will come out with an extra underscore - be willing to strip this
370       // on behalf of the user.   This is the moral equivalent of the -_/-n
371       // options to c++filt
372       auto name = entry.ref;
373       if (name.startswith("__Z"))
374         name = name.drop_front();
375 
376       Mangled mangled(name, true);
377       if (mangled.GuessLanguage() == lldb::eLanguageTypeC_plus_plus) {
378         ConstString demangled(
379             mangled.GetDisplayDemangledName(lldb::eLanguageTypeC_plus_plus));
380         demangled_any = true;
381         result.AppendMessageWithFormat("%s ---> %s\n", entry.ref.str().c_str(),
382                                        demangled.GetCString());
383       } else {
384         error_any = true;
385         result.AppendErrorWithFormat("%s is not a valid C++ mangled name\n",
386                                      entry.ref.str().c_str());
387       }
388     }
389 
390     result.SetStatus(
391         error_any ? lldb::eReturnStatusFailed
392                   : (demangled_any ? lldb::eReturnStatusSuccessFinishResult
393                                    : lldb::eReturnStatusSuccessFinishNoResult));
394     return result.Succeeded();
395   }
396 };
397 
398 class CommandObjectMultiwordItaniumABI : public CommandObjectMultiword {
399 public:
400   CommandObjectMultiwordItaniumABI(CommandInterpreter &interpreter)
401       : CommandObjectMultiword(
402             interpreter, "cplusplus",
403             "Commands for operating on the C++ language runtime.",
404             "cplusplus <subcommand> [<subcommand-options>]") {
405     LoadSubCommand(
406         "demangle",
407         CommandObjectSP(
408             new CommandObjectMultiwordItaniumABI_Demangle(interpreter)));
409   }
410 
411   ~CommandObjectMultiwordItaniumABI() override = default;
412 };
413 
414 void ItaniumABILanguageRuntime::Initialize() {
415   PluginManager::RegisterPlugin(
416       GetPluginNameStatic(), "Itanium ABI for the C++ language", CreateInstance,
417       [](CommandInterpreter &interpreter) -> lldb::CommandObjectSP {
418         return CommandObjectSP(
419             new CommandObjectMultiwordItaniumABI(interpreter));
420       });
421 }
422 
423 void ItaniumABILanguageRuntime::Terminate() {
424   PluginManager::UnregisterPlugin(CreateInstance);
425 }
426 
427 lldb_private::ConstString ItaniumABILanguageRuntime::GetPluginNameStatic() {
428   static ConstString g_name("itanium");
429   return g_name;
430 }
431 
432 //------------------------------------------------------------------
433 // PluginInterface protocol
434 //------------------------------------------------------------------
435 lldb_private::ConstString ItaniumABILanguageRuntime::GetPluginName() {
436   return GetPluginNameStatic();
437 }
438 
439 uint32_t ItaniumABILanguageRuntime::GetPluginVersion() { return 1; }
440 
441 BreakpointResolverSP ItaniumABILanguageRuntime::CreateExceptionResolver(
442     Breakpoint *bkpt, bool catch_bp, bool throw_bp) {
443   return CreateExceptionResolver(bkpt, catch_bp, throw_bp, false);
444 }
445 
446 BreakpointResolverSP ItaniumABILanguageRuntime::CreateExceptionResolver(
447     Breakpoint *bkpt, bool catch_bp, bool throw_bp, bool for_expressions) {
448   // One complication here is that most users DON'T want to stop at
449   // __cxa_allocate_expression, but until we can do anything better with
450   // predicting unwinding the expression parser does.  So we have two forms of
451   // the exception breakpoints, one for expressions that leaves out
452   // __cxa_allocate_exception, and one that includes it. The
453   // SetExceptionBreakpoints does the latter, the CreateExceptionBreakpoint in
454   // the runtime the former.
455   static const char *g_catch_name = "__cxa_begin_catch";
456   static const char *g_throw_name1 = "__cxa_throw";
457   static const char *g_throw_name2 = "__cxa_rethrow";
458   static const char *g_exception_throw_name = "__cxa_allocate_exception";
459   std::vector<const char *> exception_names;
460   exception_names.reserve(4);
461   if (catch_bp)
462     exception_names.push_back(g_catch_name);
463 
464   if (throw_bp) {
465     exception_names.push_back(g_throw_name1);
466     exception_names.push_back(g_throw_name2);
467   }
468 
469   if (for_expressions)
470     exception_names.push_back(g_exception_throw_name);
471 
472   BreakpointResolverSP resolver_sp(new BreakpointResolverName(
473       bkpt, exception_names.data(), exception_names.size(),
474       eFunctionNameTypeBase, eLanguageTypeUnknown, 0, eLazyBoolNo));
475 
476   return resolver_sp;
477 }
478 
479 lldb::SearchFilterSP ItaniumABILanguageRuntime::CreateExceptionSearchFilter() {
480   Target &target = m_process->GetTarget();
481 
482   if (target.GetArchitecture().GetTriple().getVendor() == llvm::Triple::Apple) {
483     // Limit the number of modules that are searched for these breakpoints for
484     // Apple binaries.
485     FileSpecList filter_modules;
486     filter_modules.Append(FileSpec("libc++abi.dylib", false));
487     filter_modules.Append(FileSpec("libSystem.B.dylib", false));
488     return target.GetSearchFilterForModuleList(&filter_modules);
489   } else {
490     return LanguageRuntime::CreateExceptionSearchFilter();
491   }
492 }
493 
494 lldb::BreakpointSP ItaniumABILanguageRuntime::CreateExceptionBreakpoint(
495     bool catch_bp, bool throw_bp, bool for_expressions, bool is_internal) {
496   Target &target = m_process->GetTarget();
497   FileSpecList filter_modules;
498   BreakpointResolverSP exception_resolver_sp =
499       CreateExceptionResolver(NULL, catch_bp, throw_bp, for_expressions);
500   SearchFilterSP filter_sp(CreateExceptionSearchFilter());
501   const bool hardware = false;
502   const bool resolve_indirect_functions = false;
503   return target.CreateBreakpoint(filter_sp, exception_resolver_sp, is_internal,
504                                  hardware, resolve_indirect_functions);
505 }
506 
507 void ItaniumABILanguageRuntime::SetExceptionBreakpoints() {
508   if (!m_process)
509     return;
510 
511   const bool catch_bp = false;
512   const bool throw_bp = true;
513   const bool is_internal = true;
514   const bool for_expressions = true;
515 
516   // For the exception breakpoints set by the Expression parser, we'll be a
517   // little more aggressive and stop at exception allocation as well.
518 
519   if (m_cxx_exception_bp_sp) {
520     m_cxx_exception_bp_sp->SetEnabled(true);
521   } else {
522     m_cxx_exception_bp_sp = CreateExceptionBreakpoint(
523         catch_bp, throw_bp, for_expressions, is_internal);
524     if (m_cxx_exception_bp_sp)
525       m_cxx_exception_bp_sp->SetBreakpointKind("c++ exception");
526   }
527 }
528 
529 void ItaniumABILanguageRuntime::ClearExceptionBreakpoints() {
530   if (!m_process)
531     return;
532 
533   if (m_cxx_exception_bp_sp) {
534     m_cxx_exception_bp_sp->SetEnabled(false);
535   }
536 }
537 
538 bool ItaniumABILanguageRuntime::ExceptionBreakpointsAreSet() {
539   return m_cxx_exception_bp_sp && m_cxx_exception_bp_sp->IsEnabled();
540 }
541 
542 bool ItaniumABILanguageRuntime::ExceptionBreakpointsExplainStop(
543     lldb::StopInfoSP stop_reason) {
544   if (!m_process)
545     return false;
546 
547   if (!stop_reason || stop_reason->GetStopReason() != eStopReasonBreakpoint)
548     return false;
549 
550   uint64_t break_site_id = stop_reason->GetValue();
551   return m_process->GetBreakpointSiteList().BreakpointSiteContainsBreakpoint(
552       break_site_id, m_cxx_exception_bp_sp->GetID());
553 }
554 
555 TypeAndOrName ItaniumABILanguageRuntime::GetDynamicTypeInfo(
556     const lldb_private::Address &vtable_addr) {
557   std::lock_guard<std::mutex> locker(m_dynamic_type_map_mutex);
558   DynamicTypeCache::const_iterator pos = m_dynamic_type_map.find(vtable_addr);
559   if (pos == m_dynamic_type_map.end())
560     return TypeAndOrName();
561   else
562     return pos->second;
563 }
564 
565 void ItaniumABILanguageRuntime::SetDynamicTypeInfo(
566     const lldb_private::Address &vtable_addr, const TypeAndOrName &type_info) {
567   std::lock_guard<std::mutex> locker(m_dynamic_type_map_mutex);
568   m_dynamic_type_map[vtable_addr] = type_info;
569 }
570