1 //===-- ItaniumABILanguageRuntime.cpp --------------------------------------*-
4 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5 // See https://llvm.org/LICENSE.txt for license information.
6 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
8 //===----------------------------------------------------------------------===//
10 #include "ItaniumABILanguageRuntime.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/Core/ValueObject.h"
17 #include "lldb/Core/ValueObjectMemory.h"
18 #include "lldb/DataFormatters/FormattersHelpers.h"
19 #include "lldb/Expression/DiagnosticManager.h"
20 #include "lldb/Expression/FunctionCaller.h"
21 #include "lldb/Interpreter/CommandObject.h"
22 #include "lldb/Interpreter/CommandObjectMultiword.h"
23 #include "lldb/Interpreter/CommandReturnObject.h"
24 #include "lldb/Symbol/ClangASTContext.h"
25 #include "lldb/Symbol/Symbol.h"
26 #include "lldb/Symbol/SymbolFile.h"
27 #include "lldb/Symbol/TypeList.h"
28 #include "lldb/Target/Process.h"
29 #include "lldb/Target/RegisterContext.h"
30 #include "lldb/Target/SectionLoadList.h"
31 #include "lldb/Target/StopInfo.h"
32 #include "lldb/Target/Target.h"
33 #include "lldb/Target/Thread.h"
34 #include "lldb/Utility/ConstString.h"
35 #include "lldb/Utility/Log.h"
36 #include "lldb/Utility/Scalar.h"
37 #include "lldb/Utility/Status.h"
42 using namespace lldb_private;
44 static const char *vtable_demangled_prefix = "vtable for ";
46 char ItaniumABILanguageRuntime::ID = 0;
48 bool ItaniumABILanguageRuntime::CouldHaveDynamicValue(ValueObject &in_value) {
49 const bool check_cxx = true;
50 const bool check_objc = false;
51 return in_value.GetCompilerType().IsPossibleDynamicType(nullptr, check_cxx,
55 TypeAndOrName ItaniumABILanguageRuntime::GetTypeInfoFromVTableAddress(
56 ValueObject &in_value, lldb::addr_t original_ptr,
57 lldb::addr_t vtable_load_addr) {
58 if (m_process && vtable_load_addr != LLDB_INVALID_ADDRESS) {
59 // Find the symbol that contains the "vtable_load_addr" address
61 Target &target = m_process->GetTarget();
62 if (!target.GetSectionLoadList().IsEmpty()) {
63 if (target.GetSectionLoadList().ResolveLoadAddress(vtable_load_addr,
65 // See if we have cached info for this type already
66 TypeAndOrName type_info = GetDynamicTypeInfo(vtable_addr);
71 target.GetImages().ResolveSymbolContextForAddress(
72 vtable_addr, eSymbolContextSymbol, sc);
73 Symbol *symbol = sc.symbol;
74 if (symbol != nullptr) {
77 .GetDemangledName(lldb::eLanguageTypeC_plus_plus)
79 if (name && strstr(name, vtable_demangled_prefix) == name) {
81 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
83 log->Printf("0x%16.16" PRIx64
84 ": static-type = '%s' has vtable symbol '%s'\n",
85 original_ptr, in_value.GetTypeName().GetCString(),
87 // We are a C++ class, that's good. Get the class name and look it
89 const char *class_name = name + strlen(vtable_demangled_prefix);
90 // We know the class name is absolute, so tell FindTypes that by
91 // prefixing it with the root namespace:
92 std::string lookup_name("::");
93 lookup_name.append(class_name);
95 type_info.SetName(class_name);
96 const bool exact_match = true;
99 uint32_t num_matches = 0;
100 // First look in the module that the vtable symbol came from and
101 // look for a single exact match.
102 llvm::DenseSet<SymbolFile *> searched_symbol_files;
104 num_matches = sc.module_sp->FindTypes(
105 ConstString(lookup_name), exact_match, 1,
106 searched_symbol_files, class_types);
109 // If we didn't find a symbol, then move on to the entire module
110 // list in the target and get as many unique matches as possible
111 if (num_matches == 0) {
112 num_matches = target.GetImages().FindTypes(
113 nullptr, ConstString(lookup_name), exact_match, UINT32_MAX,
114 searched_symbol_files, class_types);
117 lldb::TypeSP type_sp;
118 if (num_matches == 0) {
120 log->Printf("0x%16.16" PRIx64 ": is not dynamic\n",
122 return TypeAndOrName();
124 if (num_matches == 1) {
125 type_sp = class_types.GetTypeAtIndex(0);
127 if (ClangASTContext::IsCXXClassType(
128 type_sp->GetForwardCompilerType())) {
132 ": static-type = '%s' has dynamic type: uid={0x%" PRIx64
133 "}, type-name='%s'\n",
134 original_ptr, in_value.GetTypeName().AsCString(),
135 type_sp->GetID(), type_sp->GetName().GetCString());
136 type_info.SetTypeSP(type_sp);
139 } else if (num_matches > 1) {
142 for (i = 0; i < num_matches; i++) {
143 type_sp = class_types.GetTypeAtIndex(i);
148 ": static-type = '%s' has multiple matching dynamic "
149 "types: uid={0x%" PRIx64 "}, type-name='%s'\n",
150 original_ptr, in_value.GetTypeName().AsCString(),
151 type_sp->GetID(), type_sp->GetName().GetCString());
156 for (i = 0; i < num_matches; i++) {
157 type_sp = class_types.GetTypeAtIndex(i);
159 if (ClangASTContext::IsCXXClassType(
160 type_sp->GetForwardCompilerType())) {
163 "0x%16.16" PRIx64 ": static-type = '%s' has multiple "
164 "matching dynamic types, picking "
165 "this one: uid={0x%" PRIx64
166 "}, type-name='%s'\n",
167 original_ptr, in_value.GetTypeName().AsCString(),
168 type_sp->GetID(), type_sp->GetName().GetCString());
169 type_info.SetTypeSP(type_sp);
174 if (log && i == num_matches) {
177 ": static-type = '%s' has multiple matching dynamic "
178 "types, didn't find a C++ match\n",
179 original_ptr, in_value.GetTypeName().AsCString());
183 SetDynamicTypeInfo(vtable_addr, type_info);
190 return TypeAndOrName();
193 bool ItaniumABILanguageRuntime::GetDynamicTypeAndAddress(
194 ValueObject &in_value, lldb::DynamicValueType use_dynamic,
195 TypeAndOrName &class_type_or_name, Address &dynamic_address,
196 Value::ValueType &value_type) {
197 // For Itanium, if the type has a vtable pointer in the object, it will be at
198 // offset 0 in the object. That will point to the "address point" within the
199 // vtable (not the beginning of the vtable.) We can then look up the symbol
200 // containing this "address point" and that symbol's name demangled will
201 // contain the full class name. The second pointer above the "address point"
202 // is the "offset_to_top". We'll use that to get the start of the value
203 // object which holds the dynamic type.
206 class_type_or_name.Clear();
207 value_type = Value::ValueType::eValueTypeScalar;
209 // Only a pointer or reference type can have a different dynamic and static
211 if (!CouldHaveDynamicValue(in_value))
214 // First job, pull out the address at 0 offset from the object.
215 AddressType address_type;
216 lldb::addr_t original_ptr = in_value.GetPointerValue(&address_type);
217 if (original_ptr == LLDB_INVALID_ADDRESS)
220 ExecutionContext exe_ctx(in_value.GetExecutionContextRef());
222 Process *process = exe_ctx.GetProcessPtr();
224 if (process == nullptr)
228 const lldb::addr_t vtable_address_point =
229 process->ReadPointerFromMemory(original_ptr, error);
231 if (!error.Success() || vtable_address_point == LLDB_INVALID_ADDRESS)
234 class_type_or_name = GetTypeInfoFromVTableAddress(in_value, original_ptr,
235 vtable_address_point);
237 if (!class_type_or_name)
240 CompilerType type = class_type_or_name.GetCompilerType();
241 // There can only be one type with a given name, so we've just found
242 // duplicate definitions, and this one will do as well as any other. We
243 // don't consider something to have a dynamic type if it is the same as
244 // the static type. So compare against the value we were handed.
248 if (ClangASTContext::AreTypesSame(in_value.GetCompilerType(), type)) {
249 // The dynamic type we found was the same type, so we don't have a
250 // dynamic type here...
254 // The offset_to_top is two pointers above the vtable pointer.
255 const uint32_t addr_byte_size = process->GetAddressByteSize();
256 const lldb::addr_t offset_to_top_location =
257 vtable_address_point - 2 * addr_byte_size;
258 // Watch for underflow, offset_to_top_location should be less than
259 // vtable_address_point
260 if (offset_to_top_location >= vtable_address_point)
262 const int64_t offset_to_top = process->ReadSignedIntegerFromMemory(
263 offset_to_top_location, addr_byte_size, INT64_MIN, error);
265 if (offset_to_top == INT64_MIN)
267 // So the dynamic type is a value that starts at offset_to_top above
268 // the original address.
269 lldb::addr_t dynamic_addr = original_ptr + offset_to_top;
270 if (!process->GetTarget().GetSectionLoadList().ResolveLoadAddress(
271 dynamic_addr, dynamic_address)) {
272 dynamic_address.SetRawAddress(dynamic_addr);
277 TypeAndOrName ItaniumABILanguageRuntime::FixUpDynamicType(
278 const TypeAndOrName &type_and_or_name, ValueObject &static_value) {
279 CompilerType static_type(static_value.GetCompilerType());
280 Flags static_type_flags(static_type.GetTypeInfo());
282 TypeAndOrName ret(type_and_or_name);
283 if (type_and_or_name.HasType()) {
284 // The type will always be the type of the dynamic object. If our parent's
285 // type was a pointer, then our type should be a pointer to the type of the
286 // dynamic object. If a reference, then the original type should be
288 CompilerType orig_type = type_and_or_name.GetCompilerType();
289 CompilerType corrected_type = orig_type;
290 if (static_type_flags.AllSet(eTypeIsPointer))
291 corrected_type = orig_type.GetPointerType();
292 else if (static_type_flags.AllSet(eTypeIsReference))
293 corrected_type = orig_type.GetLValueReferenceType();
294 ret.SetCompilerType(corrected_type);
296 // If we are here we need to adjust our dynamic type name to include the
297 // correct & or * symbol
298 std::string corrected_name(type_and_or_name.GetName().GetCString());
299 if (static_type_flags.AllSet(eTypeIsPointer))
300 corrected_name.append(" *");
301 else if (static_type_flags.AllSet(eTypeIsReference))
302 corrected_name.append(" &");
303 // the parent type should be a correctly pointer'ed or referenc'ed type
304 ret.SetCompilerType(static_type);
305 ret.SetName(corrected_name.c_str());
312 ItaniumABILanguageRuntime::CreateInstance(Process *process,
313 lldb::LanguageType language) {
314 // FIXME: We have to check the process and make sure we actually know that
315 // this process supports
317 if (language == eLanguageTypeC_plus_plus ||
318 language == eLanguageTypeC_plus_plus_03 ||
319 language == eLanguageTypeC_plus_plus_11 ||
320 language == eLanguageTypeC_plus_plus_14)
321 return new ItaniumABILanguageRuntime(process);
326 class CommandObjectMultiwordItaniumABI_Demangle : public CommandObjectParsed {
328 CommandObjectMultiwordItaniumABI_Demangle(CommandInterpreter &interpreter)
329 : CommandObjectParsed(interpreter, "demangle",
330 "Demangle a C++ mangled name.",
331 "language cplusplus demangle") {
332 CommandArgumentEntry arg;
333 CommandArgumentData index_arg;
335 // Define the first (and only) variant of this arg.
336 index_arg.arg_type = eArgTypeSymbol;
337 index_arg.arg_repetition = eArgRepeatPlus;
339 // There is only one variant this argument could be; put it into the
341 arg.push_back(index_arg);
343 // Push the data for the first argument into the m_arguments vector.
344 m_arguments.push_back(arg);
347 ~CommandObjectMultiwordItaniumABI_Demangle() override = default;
350 bool DoExecute(Args &command, CommandReturnObject &result) override {
351 bool demangled_any = false;
352 bool error_any = false;
353 for (auto &entry : command.entries()) {
354 if (entry.ref.empty())
357 // the actual Mangled class should be strict about this, but on the
358 // command line if you're copying mangled names out of 'nm' on Darwin,
359 // they will come out with an extra underscore - be willing to strip this
360 // on behalf of the user. This is the moral equivalent of the -_/-n
361 // options to c++filt
362 auto name = entry.ref;
363 if (name.startswith("__Z"))
364 name = name.drop_front();
366 Mangled mangled(name, true);
367 if (mangled.GuessLanguage() == lldb::eLanguageTypeC_plus_plus) {
368 ConstString demangled(
369 mangled.GetDisplayDemangledName(lldb::eLanguageTypeC_plus_plus));
370 demangled_any = true;
371 result.AppendMessageWithFormat("%s ---> %s\n", entry.ref.str().c_str(),
372 demangled.GetCString());
375 result.AppendErrorWithFormat("%s is not a valid C++ mangled name\n",
376 entry.ref.str().c_str());
381 error_any ? lldb::eReturnStatusFailed
382 : (demangled_any ? lldb::eReturnStatusSuccessFinishResult
383 : lldb::eReturnStatusSuccessFinishNoResult));
384 return result.Succeeded();
388 class CommandObjectMultiwordItaniumABI : public CommandObjectMultiword {
390 CommandObjectMultiwordItaniumABI(CommandInterpreter &interpreter)
391 : CommandObjectMultiword(
392 interpreter, "cplusplus",
393 "Commands for operating on the C++ language runtime.",
394 "cplusplus <subcommand> [<subcommand-options>]") {
398 new CommandObjectMultiwordItaniumABI_Demangle(interpreter)));
401 ~CommandObjectMultiwordItaniumABI() override = default;
404 void ItaniumABILanguageRuntime::Initialize() {
405 PluginManager::RegisterPlugin(
406 GetPluginNameStatic(), "Itanium ABI for the C++ language", CreateInstance,
407 [](CommandInterpreter &interpreter) -> lldb::CommandObjectSP {
408 return CommandObjectSP(
409 new CommandObjectMultiwordItaniumABI(interpreter));
413 void ItaniumABILanguageRuntime::Terminate() {
414 PluginManager::UnregisterPlugin(CreateInstance);
417 lldb_private::ConstString ItaniumABILanguageRuntime::GetPluginNameStatic() {
418 static ConstString g_name("itanium");
422 // PluginInterface protocol
423 lldb_private::ConstString ItaniumABILanguageRuntime::GetPluginName() {
424 return GetPluginNameStatic();
427 uint32_t ItaniumABILanguageRuntime::GetPluginVersion() { return 1; }
429 BreakpointResolverSP ItaniumABILanguageRuntime::CreateExceptionResolver(
430 Breakpoint *bkpt, bool catch_bp, bool throw_bp) {
431 return CreateExceptionResolver(bkpt, catch_bp, throw_bp, false);
434 BreakpointResolverSP ItaniumABILanguageRuntime::CreateExceptionResolver(
435 Breakpoint *bkpt, bool catch_bp, bool throw_bp, bool for_expressions) {
436 // One complication here is that most users DON'T want to stop at
437 // __cxa_allocate_expression, but until we can do anything better with
438 // predicting unwinding the expression parser does. So we have two forms of
439 // the exception breakpoints, one for expressions that leaves out
440 // __cxa_allocate_exception, and one that includes it. The
441 // SetExceptionBreakpoints does the latter, the CreateExceptionBreakpoint in
442 // the runtime the former.
443 static const char *g_catch_name = "__cxa_begin_catch";
444 static const char *g_throw_name1 = "__cxa_throw";
445 static const char *g_throw_name2 = "__cxa_rethrow";
446 static const char *g_exception_throw_name = "__cxa_allocate_exception";
447 std::vector<const char *> exception_names;
448 exception_names.reserve(4);
450 exception_names.push_back(g_catch_name);
453 exception_names.push_back(g_throw_name1);
454 exception_names.push_back(g_throw_name2);
458 exception_names.push_back(g_exception_throw_name);
460 BreakpointResolverSP resolver_sp(new BreakpointResolverName(
461 bkpt, exception_names.data(), exception_names.size(),
462 eFunctionNameTypeBase, eLanguageTypeUnknown, 0, eLazyBoolNo));
467 lldb::SearchFilterSP ItaniumABILanguageRuntime::CreateExceptionSearchFilter() {
468 Target &target = m_process->GetTarget();
470 FileSpecList filter_modules;
471 if (target.GetArchitecture().GetTriple().getVendor() == llvm::Triple::Apple) {
472 // Limit the number of modules that are searched for these breakpoints for
474 filter_modules.Append(FileSpec("libc++abi.dylib"));
475 filter_modules.Append(FileSpec("libSystem.B.dylib"));
477 return target.GetSearchFilterForModuleList(&filter_modules);
480 lldb::BreakpointSP ItaniumABILanguageRuntime::CreateExceptionBreakpoint(
481 bool catch_bp, bool throw_bp, bool for_expressions, bool is_internal) {
482 Target &target = m_process->GetTarget();
483 FileSpecList filter_modules;
484 BreakpointResolverSP exception_resolver_sp =
485 CreateExceptionResolver(nullptr, catch_bp, throw_bp, for_expressions);
486 SearchFilterSP filter_sp(CreateExceptionSearchFilter());
487 const bool hardware = false;
488 const bool resolve_indirect_functions = false;
489 return target.CreateBreakpoint(filter_sp, exception_resolver_sp, is_internal,
490 hardware, resolve_indirect_functions);
493 void ItaniumABILanguageRuntime::SetExceptionBreakpoints() {
497 const bool catch_bp = false;
498 const bool throw_bp = true;
499 const bool is_internal = true;
500 const bool for_expressions = true;
502 // For the exception breakpoints set by the Expression parser, we'll be a
503 // little more aggressive and stop at exception allocation as well.
505 if (m_cxx_exception_bp_sp) {
506 m_cxx_exception_bp_sp->SetEnabled(true);
508 m_cxx_exception_bp_sp = CreateExceptionBreakpoint(
509 catch_bp, throw_bp, for_expressions, is_internal);
510 if (m_cxx_exception_bp_sp)
511 m_cxx_exception_bp_sp->SetBreakpointKind("c++ exception");
515 void ItaniumABILanguageRuntime::ClearExceptionBreakpoints() {
519 if (m_cxx_exception_bp_sp) {
520 m_cxx_exception_bp_sp->SetEnabled(false);
524 bool ItaniumABILanguageRuntime::ExceptionBreakpointsAreSet() {
525 return m_cxx_exception_bp_sp && m_cxx_exception_bp_sp->IsEnabled();
528 bool ItaniumABILanguageRuntime::ExceptionBreakpointsExplainStop(
529 lldb::StopInfoSP stop_reason) {
533 if (!stop_reason || stop_reason->GetStopReason() != eStopReasonBreakpoint)
536 uint64_t break_site_id = stop_reason->GetValue();
537 return m_process->GetBreakpointSiteList().BreakpointSiteContainsBreakpoint(
538 break_site_id, m_cxx_exception_bp_sp->GetID());
541 ValueObjectSP ItaniumABILanguageRuntime::GetExceptionObjectForThread(
542 ThreadSP thread_sp) {
543 if (!thread_sp->SafeToCallFunctions())
546 ClangASTContext *clang_ast_context =
547 m_process->GetTarget().GetScratchClangASTContext();
548 CompilerType voidstar =
549 clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
551 DiagnosticManager diagnostics;
552 ExecutionContext exe_ctx;
553 EvaluateExpressionOptions options;
555 options.SetUnwindOnError(true);
556 options.SetIgnoreBreakpoints(true);
557 options.SetStopOthers(true);
558 options.SetTimeout(m_process->GetUtilityExpressionTimeout());
559 options.SetTryAllThreads(false);
560 thread_sp->CalculateExecutionContext(exe_ctx);
562 const ModuleList &modules = m_process->GetTarget().GetImages();
563 SymbolContextList contexts;
564 SymbolContext context;
566 modules.FindSymbolsWithNameAndType(
567 ConstString("__cxa_current_exception_type"), eSymbolTypeCode, contexts);
568 contexts.GetContextAtIndex(0, context);
569 Address addr = context.symbol->GetAddress();
572 FunctionCaller *function_caller =
573 m_process->GetTarget().GetFunctionCallerForLanguage(
574 eLanguageTypeC, voidstar, addr, ValueList(), "caller", error);
576 ExpressionResults func_call_ret;
578 func_call_ret = function_caller->ExecuteFunction(exe_ctx, nullptr, options,
579 diagnostics, results);
580 if (func_call_ret != eExpressionCompleted || !error.Success()) {
581 return ValueObjectSP();
584 size_t ptr_size = m_process->GetAddressByteSize();
585 addr_t result_ptr = results.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
586 addr_t exception_addr =
587 m_process->ReadPointerFromMemory(result_ptr - ptr_size, error);
589 if (!error.Success()) {
590 return ValueObjectSP();
593 lldb_private::formatters::InferiorSizedWord exception_isw(exception_addr,
595 ValueObjectSP exception = ValueObject::CreateValueObjectFromData(
596 "exception", exception_isw.GetAsData(m_process->GetByteOrder()), exe_ctx,
598 exception = exception->GetDynamicValue(eDynamicDontRunTarget);
603 TypeAndOrName ItaniumABILanguageRuntime::GetDynamicTypeInfo(
604 const lldb_private::Address &vtable_addr) {
605 std::lock_guard<std::mutex> locker(m_dynamic_type_map_mutex);
606 DynamicTypeCache::const_iterator pos = m_dynamic_type_map.find(vtable_addr);
607 if (pos == m_dynamic_type_map.end())
608 return TypeAndOrName();
613 void ItaniumABILanguageRuntime::SetDynamicTypeInfo(
614 const lldb_private::Address &vtable_addr, const TypeAndOrName &type_info) {
615 std::lock_guard<std::mutex> locker(m_dynamic_type_map_mutex);
616 m_dynamic_type_map[vtable_addr] = type_info;