xref: /llvm-project/lldb/source/Plugins/LanguageRuntime/CPlusPlus/ItaniumABI/ItaniumABILanguageRuntime.cpp (revision b852fb1ec5fa15f0b913cc4988cbd09239b19904)
1 //===-- ItaniumABILanguageRuntime.cpp -------------------------------------===//
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 "ItaniumABILanguageRuntime.h"
10 
11 #include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
12 #include "lldb/Breakpoint/BreakpointLocation.h"
13 #include "lldb/Core/Mangled.h"
14 #include "lldb/Core/Module.h"
15 #include "lldb/Core/PluginManager.h"
16 #include "lldb/DataFormatters/FormattersHelpers.h"
17 #include "lldb/Expression/DiagnosticManager.h"
18 #include "lldb/Expression/FunctionCaller.h"
19 #include "lldb/Interpreter/CommandObject.h"
20 #include "lldb/Interpreter/CommandObjectMultiword.h"
21 #include "lldb/Interpreter/CommandReturnObject.h"
22 #include "lldb/Symbol/Symbol.h"
23 #include "lldb/Symbol/SymbolFile.h"
24 #include "lldb/Symbol/TypeList.h"
25 #include "lldb/Target/Process.h"
26 #include "lldb/Target/RegisterContext.h"
27 #include "lldb/Target/SectionLoadList.h"
28 #include "lldb/Target/StopInfo.h"
29 #include "lldb/Target/Target.h"
30 #include "lldb/Target/Thread.h"
31 #include "lldb/Utility/ConstString.h"
32 #include "lldb/Utility/LLDBLog.h"
33 #include "lldb/Utility/Log.h"
34 #include "lldb/Utility/Scalar.h"
35 #include "lldb/Utility/Status.h"
36 #include "lldb/ValueObject/ValueObject.h"
37 #include "lldb/ValueObject/ValueObjectMemory.h"
38 
39 #include <vector>
40 
41 using namespace lldb;
42 using namespace lldb_private;
43 
44 LLDB_PLUGIN_DEFINE_ADV(ItaniumABILanguageRuntime, CXXItaniumABI)
45 
46 static const char *vtable_demangled_prefix = "vtable for ";
47 
48 char ItaniumABILanguageRuntime::ID = 0;
49 
50 bool ItaniumABILanguageRuntime::CouldHaveDynamicValue(ValueObject &in_value) {
51   const bool check_cxx = true;
52   const bool check_objc = false;
53   return in_value.GetCompilerType().IsPossibleDynamicType(nullptr, check_cxx,
54                                                           check_objc);
55 }
56 
57 TypeAndOrName ItaniumABILanguageRuntime::GetTypeInfo(
58     ValueObject &in_value, const VTableInfo &vtable_info) {
59   if (vtable_info.addr.IsSectionOffset()) {
60     // See if we have cached info for this type already
61     TypeAndOrName type_info = GetDynamicTypeInfo(vtable_info.addr);
62     if (type_info)
63       return type_info;
64 
65     if (vtable_info.symbol) {
66       Log *log = GetLog(LLDBLog::Object);
67       llvm::StringRef symbol_name =
68           vtable_info.symbol->GetMangled().GetDemangledName().GetStringRef();
69       LLDB_LOGF(log,
70                 "0x%16.16" PRIx64
71                 ": static-type = '%s' has vtable symbol '%s'\n",
72                 in_value.GetPointerValue(),
73                 in_value.GetTypeName().GetCString(),
74                 symbol_name.str().c_str());
75       // We are a C++ class, that's good.  Get the class name and look it
76       // up:
77       llvm::StringRef class_name = symbol_name;
78       class_name.consume_front(vtable_demangled_prefix);
79       // We know the class name is absolute, so tell FindTypes that by
80       // prefixing it with the root namespace:
81       std::string lookup_name("::");
82       lookup_name.append(class_name.data(), class_name.size());
83 
84       type_info.SetName(class_name);
85       ConstString const_lookup_name(lookup_name);
86       TypeList class_types;
87       ModuleSP module_sp = vtable_info.symbol->CalculateSymbolContextModule();
88       // First look in the module that the vtable symbol came from and
89       // look for a single exact match.
90       TypeResults results;
91       TypeQuery query(const_lookup_name.GetStringRef(),
92                       TypeQueryOptions::e_exact_match |
93                           TypeQueryOptions::e_strict_namespaces |
94                           TypeQueryOptions::e_find_one);
95       if (module_sp) {
96         module_sp->FindTypes(query, results);
97         TypeSP type_sp = results.GetFirstType();
98         if (type_sp)
99           class_types.Insert(type_sp);
100       }
101 
102       // If we didn't find a symbol, then move on to the entire module
103       // list in the target and get as many unique matches as possible
104       if (class_types.Empty()) {
105         query.SetFindOne(false);
106         m_process->GetTarget().GetImages().FindTypes(nullptr, query, results);
107         for (const auto &type_sp : results.GetTypeMap().Types())
108           class_types.Insert(type_sp);
109       }
110 
111       lldb::TypeSP type_sp;
112       if (class_types.Empty()) {
113         LLDB_LOGF(log, "0x%16.16" PRIx64 ": is not dynamic\n",
114                   in_value.GetPointerValue());
115         return TypeAndOrName();
116       }
117       if (class_types.GetSize() == 1) {
118         type_sp = class_types.GetTypeAtIndex(0);
119         if (type_sp) {
120           if (TypeSystemClang::IsCXXClassType(
121                   type_sp->GetForwardCompilerType())) {
122             LLDB_LOGF(
123                 log,
124                 "0x%16.16" PRIx64
125                 ": static-type = '%s' has dynamic type: uid={0x%" PRIx64
126                 "}, type-name='%s'\n",
127                 in_value.GetPointerValue(), in_value.GetTypeName().AsCString(),
128                 type_sp->GetID(), type_sp->GetName().GetCString());
129             type_info.SetTypeSP(type_sp);
130           }
131         }
132       } else {
133         size_t i;
134         if (log) {
135           for (i = 0; i < class_types.GetSize(); i++) {
136             type_sp = class_types.GetTypeAtIndex(i);
137             if (type_sp) {
138               LLDB_LOGF(
139                   log,
140                   "0x%16.16" PRIx64
141                   ": static-type = '%s' has multiple matching dynamic "
142                   "types: uid={0x%" PRIx64 "}, type-name='%s'\n",
143                   in_value.GetPointerValue(),
144                   in_value.GetTypeName().AsCString(),
145                   type_sp->GetID(), type_sp->GetName().GetCString());
146             }
147           }
148         }
149 
150         for (i = 0; i < class_types.GetSize(); i++) {
151           type_sp = class_types.GetTypeAtIndex(i);
152           if (type_sp) {
153             if (TypeSystemClang::IsCXXClassType(
154                     type_sp->GetForwardCompilerType())) {
155               LLDB_LOGF(
156                   log,
157                   "0x%16.16" PRIx64 ": static-type = '%s' has multiple "
158                   "matching dynamic types, picking "
159                   "this one: uid={0x%" PRIx64 "}, type-name='%s'\n",
160                   in_value.GetPointerValue(),
161                   in_value.GetTypeName().AsCString(),
162                   type_sp->GetID(), type_sp->GetName().GetCString());
163               type_info.SetTypeSP(type_sp);
164             }
165           }
166         }
167 
168         if (log) {
169           LLDB_LOGF(log,
170                     "0x%16.16" PRIx64
171                     ": static-type = '%s' has multiple matching dynamic "
172                     "types, didn't find a C++ match\n",
173                     in_value.GetPointerValue(),
174                     in_value.GetTypeName().AsCString());
175         }
176       }
177       if (type_info)
178         SetDynamicTypeInfo(vtable_info.addr, type_info);
179       return type_info;
180     }
181   }
182   return TypeAndOrName();
183 }
184 
185 llvm::Error ItaniumABILanguageRuntime::TypeHasVTable(CompilerType type) {
186   // Check to make sure the class has a vtable.
187   CompilerType original_type = type;
188   if (type.IsPointerOrReferenceType()) {
189     CompilerType pointee_type = type.GetPointeeType();
190     if (pointee_type)
191       type = pointee_type;
192   }
193 
194   // Make sure this is a class or a struct first by checking the type class
195   // bitfield that gets returned.
196   if ((type.GetTypeClass() & (eTypeClassStruct | eTypeClassClass)) == 0) {
197     return llvm::createStringError(std::errc::invalid_argument,
198         "type \"%s\" is not a class or struct or a pointer to one",
199         original_type.GetTypeName().AsCString("<invalid>"));
200   }
201 
202   // Check if the type has virtual functions by asking it if it is polymorphic.
203   if (!type.IsPolymorphicClass()) {
204     return llvm::createStringError(std::errc::invalid_argument,
205         "type \"%s\" doesn't have a vtable",
206         type.GetTypeName().AsCString("<invalid>"));
207   }
208   return llvm::Error::success();
209 }
210 
211 // This function can accept both pointers or references to classes as well as
212 // instances of classes. If you are using this function during dynamic type
213 // detection, only valid ValueObjects that return true to
214 // CouldHaveDynamicValue(...) should call this function and \a check_type
215 // should be set to false. This function is also used by ValueObjectVTable
216 // and is can pass in instances of classes which is not suitable for dynamic
217 // type detection, these cases should pass true for \a check_type.
218 llvm::Expected<LanguageRuntime::VTableInfo>
219  ItaniumABILanguageRuntime::GetVTableInfo(ValueObject &in_value,
220                                           bool check_type) {
221 
222   CompilerType type = in_value.GetCompilerType();
223   if (check_type) {
224     if (llvm::Error err = TypeHasVTable(type))
225       return std::move(err);
226   }
227   ExecutionContext exe_ctx(in_value.GetExecutionContextRef());
228   Process *process = exe_ctx.GetProcessPtr();
229   if (process == nullptr)
230     return llvm::createStringError(std::errc::invalid_argument,
231                                    "invalid process");
232 
233   AddressType address_type;
234   lldb::addr_t original_ptr = LLDB_INVALID_ADDRESS;
235   if (type.IsPointerOrReferenceType())
236     original_ptr = in_value.GetPointerValue(&address_type);
237   else
238     original_ptr = in_value.GetAddressOf(/*scalar_is_load_address=*/true,
239                                          &address_type);
240   if (original_ptr == LLDB_INVALID_ADDRESS || address_type != eAddressTypeLoad)
241     return llvm::createStringError(std::errc::invalid_argument,
242                                    "failed to get the address of the value");
243 
244   Status error;
245   lldb::addr_t vtable_load_addr =
246       process->ReadPointerFromMemory(original_ptr, error);
247 
248   if (!error.Success() || vtable_load_addr == LLDB_INVALID_ADDRESS)
249     return llvm::createStringError(std::errc::invalid_argument,
250         "failed to read vtable pointer from memory at 0x%" PRIx64,
251         original_ptr);
252 
253   // The vtable load address can have authentication bits with
254   // AArch64 targets on Darwin.
255   vtable_load_addr = process->FixDataAddress(vtable_load_addr);
256 
257   // Find the symbol that contains the "vtable_load_addr" address
258   Address vtable_addr;
259   if (!process->GetTarget().ResolveLoadAddress(vtable_load_addr, vtable_addr))
260     return llvm::createStringError(std::errc::invalid_argument,
261                                    "failed to resolve vtable pointer 0x%"
262                                    PRIx64 "to a section", vtable_load_addr);
263 
264   // Check our cache first to see if we already have this info
265   {
266     std::lock_guard<std::mutex> locker(m_mutex);
267     auto pos = m_vtable_info_map.find(vtable_addr);
268     if (pos != m_vtable_info_map.end())
269       return pos->second;
270   }
271 
272   Symbol *symbol = vtable_addr.CalculateSymbolContextSymbol();
273   if (symbol == nullptr)
274     return llvm::createStringError(std::errc::invalid_argument,
275                                    "no symbol found for 0x%" PRIx64,
276                                    vtable_load_addr);
277   llvm::StringRef name = symbol->GetMangled().GetDemangledName().GetStringRef();
278   if (name.starts_with(vtable_demangled_prefix)) {
279     VTableInfo info = {vtable_addr, symbol};
280     std::lock_guard<std::mutex> locker(m_mutex);
281     auto pos = m_vtable_info_map[vtable_addr] = info;
282     return info;
283   }
284   return llvm::createStringError(std::errc::invalid_argument,
285       "symbol found that contains 0x%" PRIx64 " is not a vtable symbol",
286       vtable_load_addr);
287 }
288 
289 bool ItaniumABILanguageRuntime::GetDynamicTypeAndAddress(
290     ValueObject &in_value, lldb::DynamicValueType use_dynamic,
291     TypeAndOrName &class_type_or_name, Address &dynamic_address,
292     Value::ValueType &value_type) {
293   // For Itanium, if the type has a vtable pointer in the object, it will be at
294   // offset 0 in the object.  That will point to the "address point" within the
295   // vtable (not the beginning of the vtable.)  We can then look up the symbol
296   // containing this "address point" and that symbol's name demangled will
297   // contain the full class name. The second pointer above the "address point"
298   // is the "offset_to_top".  We'll use that to get the start of the value
299   // object which holds the dynamic type.
300   //
301 
302   class_type_or_name.Clear();
303   value_type = Value::ValueType::Scalar;
304 
305   if (!CouldHaveDynamicValue(in_value))
306     return false;
307 
308   // Check if we have a vtable pointer in this value. If we don't it will
309   // return an error, else it will return a valid resolved address. We don't
310   // want GetVTableInfo to check the type since we accept void * as a possible
311   // dynamic type and that won't pass the type check. We already checked the
312   // type above in CouldHaveDynamicValue(...).
313   llvm::Expected<VTableInfo> vtable_info_or_err =
314       GetVTableInfo(in_value, /*check_type=*/false);
315   if (!vtable_info_or_err) {
316     llvm::consumeError(vtable_info_or_err.takeError());
317     return false;
318   }
319 
320   const VTableInfo &vtable_info = vtable_info_or_err.get();
321   class_type_or_name = GetTypeInfo(in_value, vtable_info);
322 
323   if (!class_type_or_name)
324     return false;
325 
326   CompilerType type = class_type_or_name.GetCompilerType();
327   // There can only be one type with a given name, so we've just found
328   // duplicate definitions, and this one will do as well as any other. We
329   // don't consider something to have a dynamic type if it is the same as
330   // the static type.  So compare against the value we were handed.
331   if (!type)
332     return true;
333 
334   if (TypeSystemClang::AreTypesSame(in_value.GetCompilerType(), type)) {
335     // The dynamic type we found was the same type, so we don't have a
336     // dynamic type here...
337     return false;
338   }
339 
340   // The offset_to_top is two pointers above the vtable pointer.
341   Target &target = m_process->GetTarget();
342   const addr_t vtable_load_addr = vtable_info.addr.GetLoadAddress(&target);
343   if (vtable_load_addr == LLDB_INVALID_ADDRESS)
344     return false;
345   const uint32_t addr_byte_size = m_process->GetAddressByteSize();
346   const lldb::addr_t offset_to_top_location =
347       vtable_load_addr - 2 * addr_byte_size;
348   // Watch for underflow, offset_to_top_location should be less than
349   // vtable_load_addr
350   if (offset_to_top_location >= vtable_load_addr)
351     return false;
352   Status error;
353   const int64_t offset_to_top = m_process->ReadSignedIntegerFromMemory(
354       offset_to_top_location, addr_byte_size, INT64_MIN, error);
355 
356   if (offset_to_top == INT64_MIN)
357     return false;
358   // So the dynamic type is a value that starts at offset_to_top above
359   // the original address.
360   lldb::addr_t dynamic_addr = in_value.GetPointerValue() + offset_to_top;
361   if (!m_process->GetTarget().ResolveLoadAddress(
362           dynamic_addr, dynamic_address)) {
363     dynamic_address.SetRawAddress(dynamic_addr);
364   }
365   return true;
366 }
367 
368 TypeAndOrName ItaniumABILanguageRuntime::FixUpDynamicType(
369     const TypeAndOrName &type_and_or_name, ValueObject &static_value) {
370   CompilerType static_type(static_value.GetCompilerType());
371   Flags static_type_flags(static_type.GetTypeInfo());
372 
373   TypeAndOrName ret(type_and_or_name);
374   if (type_and_or_name.HasType()) {
375     // The type will always be the type of the dynamic object.  If our parent's
376     // type was a pointer, then our type should be a pointer to the type of the
377     // dynamic object.  If a reference, then the original type should be
378     // okay...
379     CompilerType orig_type = type_and_or_name.GetCompilerType();
380     CompilerType corrected_type = orig_type;
381     if (static_type_flags.AllSet(eTypeIsPointer))
382       corrected_type = orig_type.GetPointerType();
383     else if (static_type_flags.AllSet(eTypeIsReference))
384       corrected_type = orig_type.GetLValueReferenceType();
385     ret.SetCompilerType(corrected_type);
386   } else {
387     // If we are here we need to adjust our dynamic type name to include the
388     // correct & or * symbol
389     std::string corrected_name(type_and_or_name.GetName().GetCString());
390     if (static_type_flags.AllSet(eTypeIsPointer))
391       corrected_name.append(" *");
392     else if (static_type_flags.AllSet(eTypeIsReference))
393       corrected_name.append(" &");
394     // the parent type should be a correctly pointer'ed or referenc'ed type
395     ret.SetCompilerType(static_type);
396     ret.SetName(corrected_name.c_str());
397   }
398   return ret;
399 }
400 
401 // Static Functions
402 LanguageRuntime *
403 ItaniumABILanguageRuntime::CreateInstance(Process *process,
404                                           lldb::LanguageType language) {
405   // FIXME: We have to check the process and make sure we actually know that
406   // this process supports
407   // the Itanium ABI.
408   if (language == eLanguageTypeC_plus_plus ||
409       language == eLanguageTypeC_plus_plus_03 ||
410       language == eLanguageTypeC_plus_plus_11 ||
411       language == eLanguageTypeC_plus_plus_14)
412     return new ItaniumABILanguageRuntime(process);
413   else
414     return nullptr;
415 }
416 
417 class CommandObjectMultiwordItaniumABI_Demangle : public CommandObjectParsed {
418 public:
419   CommandObjectMultiwordItaniumABI_Demangle(CommandInterpreter &interpreter)
420       : CommandObjectParsed(
421             interpreter, "demangle", "Demangle a C++ mangled name.",
422             "language cplusplus demangle [<mangled-name> ...]") {
423     AddSimpleArgumentList(eArgTypeSymbol, eArgRepeatPlus);
424   }
425 
426   ~CommandObjectMultiwordItaniumABI_Demangle() override = default;
427 
428 protected:
429   void DoExecute(Args &command, CommandReturnObject &result) override {
430     bool demangled_any = false;
431     bool error_any = false;
432     for (auto &entry : command.entries()) {
433       if (entry.ref().empty())
434         continue;
435 
436       // the actual Mangled class should be strict about this, but on the
437       // command line if you're copying mangled names out of 'nm' on Darwin,
438       // they will come out with an extra underscore - be willing to strip this
439       // on behalf of the user.   This is the moral equivalent of the -_/-n
440       // options to c++filt
441       auto name = entry.ref();
442       if (name.starts_with("__Z"))
443         name = name.drop_front();
444 
445       Mangled mangled(name);
446       if (mangled.GuessLanguage() == lldb::eLanguageTypeC_plus_plus) {
447         ConstString demangled(mangled.GetDisplayDemangledName());
448         demangled_any = true;
449         result.AppendMessageWithFormat("%s ---> %s\n", entry.c_str(),
450                                        demangled.GetCString());
451       } else {
452         error_any = true;
453         result.AppendErrorWithFormat("%s is not a valid C++ mangled name\n",
454                                      entry.ref().str().c_str());
455       }
456     }
457 
458     result.SetStatus(
459         error_any ? lldb::eReturnStatusFailed
460                   : (demangled_any ? lldb::eReturnStatusSuccessFinishResult
461                                    : lldb::eReturnStatusSuccessFinishNoResult));
462   }
463 };
464 
465 class CommandObjectMultiwordItaniumABI : public CommandObjectMultiword {
466 public:
467   CommandObjectMultiwordItaniumABI(CommandInterpreter &interpreter)
468       : CommandObjectMultiword(
469             interpreter, "cplusplus",
470             "Commands for operating on the C++ language runtime.",
471             "cplusplus <subcommand> [<subcommand-options>]") {
472     LoadSubCommand(
473         "demangle",
474         CommandObjectSP(
475             new CommandObjectMultiwordItaniumABI_Demangle(interpreter)));
476   }
477 
478   ~CommandObjectMultiwordItaniumABI() override = default;
479 };
480 
481 void ItaniumABILanguageRuntime::Initialize() {
482   PluginManager::RegisterPlugin(
483       GetPluginNameStatic(), "Itanium ABI for the C++ language", CreateInstance,
484       [](CommandInterpreter &interpreter) -> lldb::CommandObjectSP {
485         return CommandObjectSP(
486             new CommandObjectMultiwordItaniumABI(interpreter));
487       });
488 }
489 
490 void ItaniumABILanguageRuntime::Terminate() {
491   PluginManager::UnregisterPlugin(CreateInstance);
492 }
493 
494 BreakpointResolverSP ItaniumABILanguageRuntime::CreateExceptionResolver(
495     const BreakpointSP &bkpt, bool catch_bp, bool throw_bp) {
496   return CreateExceptionResolver(bkpt, catch_bp, throw_bp, false);
497 }
498 
499 BreakpointResolverSP ItaniumABILanguageRuntime::CreateExceptionResolver(
500     const BreakpointSP &bkpt, bool catch_bp, bool throw_bp,
501     bool for_expressions) {
502   // One complication here is that most users DON'T want to stop at
503   // __cxa_allocate_expression, but until we can do anything better with
504   // predicting unwinding the expression parser does.  So we have two forms of
505   // the exception breakpoints, one for expressions that leaves out
506   // __cxa_allocate_exception, and one that includes it. The
507   // SetExceptionBreakpoints does the latter, the CreateExceptionBreakpoint in
508   // the runtime the former.
509   static const char *g_catch_name = "__cxa_begin_catch";
510   static const char *g_throw_name1 = "__cxa_throw";
511   static const char *g_throw_name2 = "__cxa_rethrow";
512   static const char *g_exception_throw_name = "__cxa_allocate_exception";
513   std::vector<const char *> exception_names;
514   exception_names.reserve(4);
515   if (catch_bp)
516     exception_names.push_back(g_catch_name);
517 
518   if (throw_bp) {
519     exception_names.push_back(g_throw_name1);
520     exception_names.push_back(g_throw_name2);
521   }
522 
523   if (for_expressions)
524     exception_names.push_back(g_exception_throw_name);
525 
526   BreakpointResolverSP resolver_sp(new BreakpointResolverName(
527       bkpt, exception_names.data(), exception_names.size(),
528       eFunctionNameTypeBase, eLanguageTypeUnknown, 0, eLazyBoolNo));
529 
530   return resolver_sp;
531 }
532 
533 lldb::SearchFilterSP ItaniumABILanguageRuntime::CreateExceptionSearchFilter() {
534   Target &target = m_process->GetTarget();
535 
536   FileSpecList filter_modules;
537   if (target.GetArchitecture().GetTriple().getVendor() == llvm::Triple::Apple) {
538     // Limit the number of modules that are searched for these breakpoints for
539     // Apple binaries.
540     filter_modules.EmplaceBack("libc++abi.dylib");
541     filter_modules.EmplaceBack("libSystem.B.dylib");
542     filter_modules.EmplaceBack("libc++abi.1.0.dylib");
543     filter_modules.EmplaceBack("libc++abi.1.dylib");
544   }
545   return target.GetSearchFilterForModuleList(&filter_modules);
546 }
547 
548 lldb::BreakpointSP ItaniumABILanguageRuntime::CreateExceptionBreakpoint(
549     bool catch_bp, bool throw_bp, bool for_expressions, bool is_internal) {
550   Target &target = m_process->GetTarget();
551   FileSpecList filter_modules;
552   BreakpointResolverSP exception_resolver_sp =
553       CreateExceptionResolver(nullptr, catch_bp, throw_bp, for_expressions);
554   SearchFilterSP filter_sp(CreateExceptionSearchFilter());
555   const bool hardware = false;
556   const bool resolve_indirect_functions = false;
557   return target.CreateBreakpoint(filter_sp, exception_resolver_sp, is_internal,
558                                  hardware, resolve_indirect_functions);
559 }
560 
561 void ItaniumABILanguageRuntime::SetExceptionBreakpoints() {
562   if (!m_process)
563     return;
564 
565   const bool catch_bp = false;
566   const bool throw_bp = true;
567   const bool is_internal = true;
568   const bool for_expressions = true;
569 
570   // For the exception breakpoints set by the Expression parser, we'll be a
571   // little more aggressive and stop at exception allocation as well.
572 
573   if (m_cxx_exception_bp_sp) {
574     m_cxx_exception_bp_sp->SetEnabled(true);
575   } else {
576     m_cxx_exception_bp_sp = CreateExceptionBreakpoint(
577         catch_bp, throw_bp, for_expressions, is_internal);
578     if (m_cxx_exception_bp_sp)
579       m_cxx_exception_bp_sp->SetBreakpointKind("c++ exception");
580   }
581 }
582 
583 void ItaniumABILanguageRuntime::ClearExceptionBreakpoints() {
584   if (!m_process)
585     return;
586 
587   if (m_cxx_exception_bp_sp) {
588     m_cxx_exception_bp_sp->SetEnabled(false);
589   }
590 }
591 
592 bool ItaniumABILanguageRuntime::ExceptionBreakpointsAreSet() {
593   return m_cxx_exception_bp_sp && m_cxx_exception_bp_sp->IsEnabled();
594 }
595 
596 bool ItaniumABILanguageRuntime::ExceptionBreakpointsExplainStop(
597     lldb::StopInfoSP stop_reason) {
598   if (!m_process)
599     return false;
600 
601   if (!stop_reason || stop_reason->GetStopReason() != eStopReasonBreakpoint)
602     return false;
603 
604   uint64_t break_site_id = stop_reason->GetValue();
605   return m_process->GetBreakpointSiteList().StopPointSiteContainsBreakpoint(
606       break_site_id, m_cxx_exception_bp_sp->GetID());
607 }
608 
609 ValueObjectSP ItaniumABILanguageRuntime::GetExceptionObjectForThread(
610     ThreadSP thread_sp) {
611   if (!thread_sp->SafeToCallFunctions())
612     return {};
613 
614   TypeSystemClangSP scratch_ts_sp =
615       ScratchTypeSystemClang::GetForTarget(m_process->GetTarget());
616   if (!scratch_ts_sp)
617     return {};
618 
619   CompilerType voidstar =
620       scratch_ts_sp->GetBasicType(eBasicTypeVoid).GetPointerType();
621 
622   DiagnosticManager diagnostics;
623   ExecutionContext exe_ctx;
624   EvaluateExpressionOptions options;
625 
626   options.SetUnwindOnError(true);
627   options.SetIgnoreBreakpoints(true);
628   options.SetStopOthers(true);
629   options.SetTimeout(m_process->GetUtilityExpressionTimeout());
630   options.SetTryAllThreads(false);
631   thread_sp->CalculateExecutionContext(exe_ctx);
632 
633   const ModuleList &modules = m_process->GetTarget().GetImages();
634   SymbolContextList contexts;
635   SymbolContext context;
636 
637   modules.FindSymbolsWithNameAndType(
638       ConstString("__cxa_current_exception_type"), eSymbolTypeCode, contexts);
639   contexts.GetContextAtIndex(0, context);
640   if (!context.symbol) {
641     return {};
642   }
643   Address addr = context.symbol->GetAddress();
644 
645   Status error;
646   FunctionCaller *function_caller =
647       m_process->GetTarget().GetFunctionCallerForLanguage(
648           eLanguageTypeC, voidstar, addr, ValueList(), "caller", error);
649 
650   ExpressionResults func_call_ret;
651   Value results;
652   func_call_ret = function_caller->ExecuteFunction(exe_ctx, nullptr, options,
653                                                    diagnostics, results);
654   if (func_call_ret != eExpressionCompleted || !error.Success()) {
655     return ValueObjectSP();
656   }
657 
658   size_t ptr_size = m_process->GetAddressByteSize();
659   addr_t result_ptr = results.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
660   addr_t exception_addr =
661       m_process->ReadPointerFromMemory(result_ptr - ptr_size, error);
662 
663   if (!error.Success()) {
664     return ValueObjectSP();
665   }
666 
667   lldb_private::formatters::InferiorSizedWord exception_isw(exception_addr,
668                                                             *m_process);
669   ValueObjectSP exception = ValueObject::CreateValueObjectFromData(
670       "exception", exception_isw.GetAsData(m_process->GetByteOrder()), exe_ctx,
671       voidstar);
672   ValueObjectSP dyn_exception
673       = exception->GetDynamicValue(eDynamicDontRunTarget);
674   // If we succeed in making a dynamic value, return that:
675   if (dyn_exception)
676      return dyn_exception;
677 
678   return exception;
679 }
680 
681 TypeAndOrName ItaniumABILanguageRuntime::GetDynamicTypeInfo(
682     const lldb_private::Address &vtable_addr) {
683   std::lock_guard<std::mutex> locker(m_mutex);
684   DynamicTypeCache::const_iterator pos = m_dynamic_type_map.find(vtable_addr);
685   if (pos == m_dynamic_type_map.end())
686     return TypeAndOrName();
687   else
688     return pos->second;
689 }
690 
691 void ItaniumABILanguageRuntime::SetDynamicTypeInfo(
692     const lldb_private::Address &vtable_addr, const TypeAndOrName &type_info) {
693   std::lock_guard<std::mutex> locker(m_mutex);
694   m_dynamic_type_map[vtable_addr] = type_info;
695 }
696