LLDB mainline
CPPLanguageRuntime.cpp
Go to the documentation of this file.
1//===-- CPPLanguageRuntime.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 <cstring>
10#include <iostream>
11
12#include <memory>
13
14#include "CPPLanguageRuntime.h"
16#include "ItaniumABIRuntime.h"
18
19#include "llvm/ADT/StringRef.h"
20#include "llvm/Support/Error.h"
21
22#include "lldb/Symbol/Block.h"
25
29#include "lldb/Target/ABI.h"
38#include "lldb/Utility/Timer.h"
39
40using namespace lldb;
41using namespace lldb_private;
42
44
46// Artificial coroutine-related variables emitted by clang.
47static ConstString g_promise = ConstString("__promise");
48static ConstString g_coro_frame = ConstString("__coro_frame");
49
50char CPPLanguageRuntime::ID = 0;
51
52/// A frame recognizer that is installed to hide libc++ implementation
53/// details from the backtrace.
55 std::array<RegularExpression, 2> m_hidden_regex;
57
59 bool ShouldHide() override { return true; }
60 };
61
62public:
65 // internal implementation details in the `std::` namespace
66 // std::__1::__function::__alloc_func<void (*)(), std::__1::allocator<void (*)()>, void ()>::operator()[abi:ne200000]
67 // std::__1::__function::__func<void (*)(), std::__1::allocator<void (*)()>, void ()>::operator()
68 // std::__1::__function::__value_func<void ()>::operator()[abi:ne200000]() const
69 // std::__2::__function::__policy_invoker<void (int, int)>::__call_impl[abi:ne200000]<std::__2::__function::__default_alloc_func<int (*)(int, int), int (int, int)>>
70 // std::__1::__invoke[abi:ne200000]<void (*&)()>
71 // std::__1::__invoke_void_return_wrapper<void, true>::__call[abi:ne200000]<void (*&)()>
72 RegularExpression{R"(^std::__[^:]*::__)"},
73 // internal implementation details in the `std::ranges` namespace
74 // std::__1::ranges::__sort::__sort_fn_impl[abi:ne200000]<std::__1::__wrap_iter<int*>, std::__1::__wrap_iter<int*>, bool (*)(int, int), std::__1::identity>
75 RegularExpression{R"(^std::__[^:]*::ranges::__)"},
76 },
78
79 std::string GetName() override { return "libc++ frame recognizer"; }
80
83 if (!frame_sp)
84 return {};
85 const auto &sc = frame_sp->GetSymbolContext(lldb::eSymbolContextFunction);
86 if (!sc.function)
87 return {};
88
89 // Check if we have a regex match
91 if (!r.Execute(sc.function->GetNameNoArguments()))
92 continue;
93
94 // Only hide this frame if the immediate caller is also within libc++.
95 lldb::ThreadSP thread_sp = frame_sp->GetThread();
96 if (!thread_sp)
97 return {};
98 lldb::StackFrameSP parent_frame_sp =
99 thread_sp->GetStackFrameAtIndex(frame_sp->GetFrameIndex() + 1);
100 if (!parent_frame_sp)
101 return {};
102 const auto &parent_sc =
103 parent_frame_sp->GetSymbolContext(lldb::eSymbolContextFunction);
104 if (!parent_sc.function)
105 return {};
106 if (parent_sc.function->GetNameNoArguments().GetStringRef().starts_with(
107 "std::"))
108 return m_hidden_frame;
109 }
110
111 return {};
112 }
113};
114
116 : LanguageRuntime(process) {
117 if (process) {
120 std::make_shared<RegularExpression>("^std::__[^:]*::"),
121 /*mangling_preference=*/Mangled::ePreferDemangledWithoutArguments,
122 /*first_instruction_only=*/false);
123
125 }
126
127 m_abi_runtimes.emplace_back(new ItaniumABIRuntime(process));
128}
129
131 return name == g_this || name == g_promise || name == g_coro_frame;
132}
133
135 ValueObject &object) {
136 // C++ has no generic way to do this.
137 return llvm::createStringError("C++ does not support object descriptions");
138}
139
140llvm::Error
142 ExecutionContextScope *exe_scope) {
143 // C++ has no generic way to do this.
144 return llvm::createStringError("C++ does not support object descriptions");
145}
146
147bool contains_lambda_identifier(llvm::StringRef &str_ref) {
148 return str_ref.contains("$_") || str_ref.contains("'lambda'");
149}
150
152line_entry_helper(Target &target, const SymbolContext &sc, Symbol *symbol,
153 llvm::StringRef first_template_param_sref, bool has_invoke) {
154
156
157 Address address = sc.GetFunctionOrSymbolAddress();
158
159 Address addr;
160 if (target.ResolveLoadAddress(address.GetCallableLoadAddress(&target),
161 addr)) {
162 LineEntry line_entry;
163 addr.CalculateSymbolContextLineEntry(line_entry);
164
165 if (contains_lambda_identifier(first_template_param_sref) || has_invoke) {
166 // Case 1 and 2
167 optional_info.callable_case = lldb_private::CPPLanguageRuntime::
168 LibCppStdFunctionCallableCase::Lambda;
169 } else {
170 // Case 3
171 optional_info.callable_case = lldb_private::CPPLanguageRuntime::
172 LibCppStdFunctionCallableCase::CallableObject;
173 }
174
175 optional_info.callable_symbol = *symbol;
176 optional_info.callable_line_entry = line_entry;
177 optional_info.callable_address = addr;
178 }
179
180 return optional_info;
181}
182
185 lldb::ValueObjectSP &valobj_sp) {
187
188 LibCppStdFunctionCallableInfo optional_info;
189
190 if (!valobj_sp)
191 return optional_info;
192
193 // Member __f_ has type __base*, the contents of which will hold:
194 // 1) a vtable entry which may hold type information needed to discover the
195 // lambda being called
196 // 2) possibly hold a pointer to the callable object
197 // e.g.
198 //
199 // (lldb) frame var -R f_display
200 // (std::__1::function<void (int)>) f_display = {
201 // __buf_ = {
202 // …
203 // }
204 // __f_ = 0x00007ffeefbffa00
205 // }
206 // (lldb) memory read -fA 0x00007ffeefbffa00
207 // 0x7ffeefbffa00: ... `vtable for std::__1::__function::__func<void (*) ...
208 // 0x7ffeefbffa08: ... `print_num(int) at std_function_cppreference_exam ...
209 //
210 // We will be handling five cases below, std::function is wrapping:
211 //
212 // 1) a lambda we know at compile time. We will obtain the name of the lambda
213 // from the first template pameter from __func's vtable. We will look up
214 // the lambda's operator()() and obtain the line table entry.
215 // 2) a lambda we know at runtime. A pointer to the lambdas __invoke method
216 // will be stored after the vtable. We will obtain the lambdas name from
217 // this entry and lookup operator()() and obtain the line table entry.
218 // 3) a callable object via operator()(). We will obtain the name of the
219 // object from the first template parameter from __func's vtable. We will
220 // look up the objects operator()() and obtain the line table entry.
221 // 4) a member function. A pointer to the function will stored after the
222 // we will obtain the name from this pointer.
223 // 5) a free function. A pointer to the function will stored after the vtable
224 // we will obtain the name from this pointer.
225 ValueObjectSP member_f_(valobj_sp->GetChildMemberWithName("__f_"));
226
227 if (member_f_) {
228 ValueObjectSP sub_member_f_(member_f_->GetChildMemberWithName("__f_"));
229
230 if (sub_member_f_)
231 member_f_ = sub_member_f_;
232 }
233
234 if (!member_f_)
235 return optional_info;
236
237 lldb::addr_t member_f_pointer_value = member_f_->GetValueAsUnsigned(0);
238
239 optional_info.member_f_pointer_value = member_f_pointer_value;
240
241 if (!member_f_pointer_value)
242 return optional_info;
243
244 ExecutionContext exe_ctx(valobj_sp->GetExecutionContextRef());
245 Process *process = exe_ctx.GetProcessPtr();
246
247 if (process == nullptr)
248 return optional_info;
249
250 uint32_t address_size = process->GetAddressByteSize();
251
252 // First item pointed to by __f_ should be the pointer to the vtable for
253 // a __base object.
254 llvm::Expected<lldb::addr_t> vtable_address_or_err =
255 process->ReadPointerFromMemory(member_f_pointer_value);
256 if (!vtable_address_or_err) {
257 llvm::consumeError(vtable_address_or_err.takeError());
258 return optional_info;
259 }
260 lldb::addr_t vtable_address = *vtable_address_or_err;
261
262 ABISP abi_sp = process->GetABI();
263 if (abi_sp)
264 vtable_address = abi_sp->FixCodeAddress(vtable_address);
265
266 llvm::Expected<lldb::addr_t> vtable_address_first_entry_or_err =
267 process->ReadPointerFromMemory(vtable_address + address_size);
268 if (!vtable_address_first_entry_or_err) {
269 llvm::consumeError(vtable_address_first_entry_or_err.takeError());
270 return optional_info;
271 }
272 lldb::addr_t vtable_address_first_entry = *vtable_address_first_entry_or_err;
273
274 if (abi_sp)
275 vtable_address_first_entry =
276 abi_sp->FixCodeAddress(vtable_address_first_entry);
277
278 lldb::addr_t address_after_vtable = member_f_pointer_value + address_size;
279 // As commented above we may not have a function pointer but if we do we will
280 // need it.
281 llvm::Expected<lldb::addr_t> possible_function_address_or_err =
282 process->ReadPointerFromMemory(address_after_vtable);
283 if (!possible_function_address_or_err) {
284 llvm::consumeError(possible_function_address_or_err.takeError());
285 return optional_info;
286 }
287 lldb::addr_t possible_function_address = *possible_function_address_or_err;
288
289 if (abi_sp)
290 possible_function_address =
291 abi_sp->FixCodeAddress(possible_function_address);
292
293 Target &target = process->GetTarget();
294
295 if (!target.HasLoadedSections())
296 return optional_info;
297
298 Address vtable_first_entry_resolved;
299
300 if (!target.ResolveLoadAddress(vtable_address_first_entry,
301 vtable_first_entry_resolved))
302 return optional_info;
303
304 Address vtable_addr_resolved;
305 SymbolContext sc;
306 Symbol *symbol = nullptr;
307
308 if (!target.ResolveLoadAddress(vtable_address, vtable_addr_resolved))
309 return optional_info;
310
312 vtable_addr_resolved, eSymbolContextEverything, sc);
313 symbol = sc.symbol;
314
315 if (symbol == nullptr)
316 return optional_info;
317
318 llvm::StringRef vtable_name(symbol->GetName().GetStringRef());
319 bool found_expected_start_string =
320 vtable_name.starts_with("vtable for std::__1::__function::__func<");
321
322 if (!found_expected_start_string)
323 return optional_info;
324
325 // Given case 1 or 3 we have a vtable name, we are want to extract the first
326 // template parameter
327 //
328 // ... __func<main::$_0, std::__1::allocator<main::$_0> ...
329 // ^^^^^^^^^
330 //
331 // We could see names such as:
332 // main::$_0
333 // Bar::add_num2(int)::'lambda'(int)
334 // Bar
335 //
336 // We do this by find the first < and , and extracting in between.
337 //
338 // This covers the case of the lambda known at compile time.
339 size_t first_open_angle_bracket = vtable_name.find('<') + 1;
340 size_t first_comma = vtable_name.find(',');
341
342 llvm::StringRef first_template_parameter =
343 vtable_name.slice(first_open_angle_bracket, first_comma);
344
345 Address function_address_resolved;
346
347 // Setup for cases 2, 4 and 5 we have a pointer to a function after the
348 // vtable. We will use a process of elimination to drop through each case
349 // and obtain the data we need.
350 if (target.ResolveLoadAddress(possible_function_address,
351 function_address_resolved)) {
353 function_address_resolved, eSymbolContextEverything, sc);
354 symbol = sc.symbol;
355 }
356
357 // These conditions are used several times to simplify statements later on.
358 bool has_invoke =
359 (symbol ? symbol->GetName().GetStringRef().contains("__invoke") : false);
360 auto calculate_symbol_context_helper = [](auto &t,
361 SymbolContextList &sc_list) {
362 SymbolContext sc;
363 t->CalculateSymbolContext(&sc);
364 sc_list.Append(sc);
365 };
366
367 // Case 2
368 if (has_invoke) {
370 calculate_symbol_context_helper(symbol, scl);
371
372 return line_entry_helper(target, scl[0], symbol, first_template_parameter,
373 has_invoke);
374 }
375
376 // Case 4 or 5
377 if (symbol && !symbol->GetName().GetStringRef().starts_with("vtable for") &&
378 !contains_lambda_identifier(first_template_parameter) && !has_invoke) {
379 optional_info.callable_case =
381 optional_info.callable_address = function_address_resolved;
382 optional_info.callable_symbol = *symbol;
383
384 return optional_info;
385 }
386
387 std::string func_to_match = first_template_parameter.str();
388
389 auto it = CallableLookupCache.find(func_to_match);
390 if (it != CallableLookupCache.end())
391 return it->second;
392
394
395 CompileUnit *vtable_cu =
396 vtable_first_entry_resolved.CalculateSymbolContextCompileUnit();
397 llvm::StringRef name_to_use = func_to_match;
398
399 // Case 3, we have a callable object instead of a lambda
400 //
401 // TODO
402 // We currently don't support this case a callable object may have multiple
403 // operator()() varying on const/non-const and number of arguments and we
404 // don't have a way to currently distinguish them so we will bail out now.
405 if (!contains_lambda_identifier(name_to_use))
406 return optional_info;
407
408 if (vtable_cu && !has_invoke) {
409 lldb::FunctionSP func_sp =
410 vtable_cu->FindFunction([name_to_use](const FunctionSP &f) {
411 auto name = f->GetName().GetStringRef();
412 if (name.starts_with(name_to_use) && name.contains("operator"))
413 return true;
414
415 return false;
416 });
417
418 if (func_sp) {
419 calculate_symbol_context_helper(func_sp, scl);
420 }
421 }
422
423 if (symbol == nullptr)
424 return optional_info;
425
426 // Case 1 or 3
427 if (scl.GetSize() >= 1) {
428 optional_info = line_entry_helper(target, scl[0], symbol,
429 first_template_parameter, has_invoke);
430 }
431
432 CallableLookupCache[func_to_match] = optional_info;
433
434 return optional_info;
435}
436
439 bool stop_others) {
440 ThreadPlanSP ret_plan_sp;
441
442 lldb::addr_t curr_pc = thread.GetRegisterContext()->GetPC();
443
444 TargetSP target_sp(thread.CalculateTarget());
445
446 if (!target_sp->HasLoadedSections())
447 return ret_plan_sp;
448
449 Address pc_addr_resolved;
450 SymbolContext sc;
451 Symbol *symbol;
452
453 if (!target_sp->ResolveLoadAddress(curr_pc, pc_addr_resolved))
454 return ret_plan_sp;
455
456 target_sp->GetImages().ResolveSymbolContextForAddress(
457 pc_addr_resolved, eSymbolContextEverything, sc);
458 symbol = sc.symbol;
459
460 if (symbol == nullptr)
461 return ret_plan_sp;
462
463 llvm::StringRef function_name(symbol->GetName().GetCString());
464
465 // Handling the case where we are attempting to step into std::function.
466 // The behavior will be that we will attempt to obtain the wrapped
467 // callable via FindLibCppStdFunctionCallableInfo() and if we find it we
468 // will return a ThreadPlanRunToAddress to the callable. Therefore we will
469 // step into the wrapped callable.
470 //
471 bool found_expected_start_string =
472 function_name.starts_with("std::__1::function<");
473
474 if (!found_expected_start_string)
475 return ret_plan_sp;
476
477 AddressRange range_of_curr_func;
478 sc.GetAddressRange(eSymbolContextEverything, 0, false, range_of_curr_func);
479
480 StackFrameSP frame = thread.GetStackFrameAtIndex(0);
481
482 if (frame) {
483 Address func_start_address =
484 sc.function ? sc.function->GetAddress() : symbol->GetAddress();
485 lldb::addr_t func_start =
486 func_start_address.GetLoadAddress(target_sp.get());
487
488 if (func_start == LLDB_INVALID_ADDRESS)
489 return ret_plan_sp;
490
491 // Advance past the prologue if we stopped there.
492 uint32_t prologue_size = sc.function ? sc.function->GetPrologueByteSize()
493 : symbol->GetPrologueByteSize();
494 if (curr_pc < func_start + prologue_size) {
495 func_start_address.Slide(prologue_size);
496 return std::make_shared<ThreadPlanRunToAddress>(
497 thread, func_start_address, stop_others);
498 }
499
500 ValueObjectSP value_sp = frame->FindVariable(g_this);
501
504
506 value_sp->GetValueIsValid()) {
507 // We found the std::function wrapped callable and we have its address.
508 // We now create a ThreadPlan to run to the callable.
509 ret_plan_sp = std::make_shared<ThreadPlanRunToAddress>(
510 thread, callable_info.callable_address, stop_others);
511 return ret_plan_sp;
512 } else {
513 // We are in std::function but we could not obtain the callable.
514 // We create a ThreadPlan to keep stepping through using the address range
515 // of the current function.
516 ret_plan_sp = std::make_shared<ThreadPlanStepInRange>(
517 thread, range_of_curr_func, sc, std::string(), eOnlyThisThread,
519 return ret_plan_sp;
520 }
521 }
522
523 return ret_plan_sp;
524}
525
527 llvm::StringRef mangled_name =
529 // Virtual function overriding from a non-virtual base use a "Th" prefix.
530 // Virtual function overriding from a virtual base must use a "Tv" prefix.
531 // Virtual function overriding thunks with covariant returns use a "Tc"
532 // prefix.
533 return mangled_name.starts_with("_ZTh") || mangled_name.starts_with("_ZTv") ||
534 mangled_name.starts_with("_ZTc");
535}
536
538 const bool check_cxx = true;
539 const bool check_objc = false;
540 return in_value.GetCompilerType().IsPossibleDynamicType(nullptr, check_cxx,
541 check_objc);
542}
543
545 ValueObject &in_value, lldb::DynamicValueType use_dynamic,
546 TypeAndOrName &class_type_or_name, Address &dynamic_address,
547 Value::ValueType &value_type, llvm::ArrayRef<uint8_t> &local_buffer) {
548 class_type_or_name.Clear();
549 value_type = Value::ValueType::Scalar;
550
551 if (!CouldHaveDynamicValue(in_value))
552 return false;
553
554 llvm::Expected<VTableInfoEntry> entry =
555 GetVTableInfoEntry(in_value, /*check_type=*/false);
556 if (!entry) {
557 llvm::consumeError(entry.takeError());
558 return false;
559 }
560
561 return entry->runtime->GetDynamicTypeAndAddress(
562 in_value, use_dynamic, entry->info, class_type_or_name, dynamic_address);
563}
564
567 ValueObject &static_value) {
568 CompilerType static_type(static_value.GetCompilerType());
569 Flags static_type_flags(static_type.GetTypeInfo());
570
571 TypeAndOrName ret(type_and_or_name);
572 if (type_and_or_name.HasType()) {
573 // The type will always be the type of the dynamic object. If our parent's
574 // type was a pointer, then our type should be a pointer to the type of the
575 // dynamic object. If a reference, then the original type should be
576 // okay...
577 CompilerType orig_type = type_and_or_name.GetCompilerType();
578 CompilerType corrected_type = orig_type;
579 if (static_type_flags.AllSet(eTypeIsPointer))
580 corrected_type = orig_type.GetPointerType();
581 else if (static_type_flags.AllSet(eTypeIsReference))
582 corrected_type = orig_type.GetLValueReferenceType();
583 ret.SetCompilerType(corrected_type);
584 } else {
585 // If we are here we need to adjust our dynamic type name to include the
586 // correct & or * symbol
587 std::string corrected_name(type_and_or_name.GetName().GetCString());
588 if (static_type_flags.AllSet(eTypeIsPointer))
589 corrected_name.append(" *");
590 else if (static_type_flags.AllSet(eTypeIsReference))
591 corrected_name.append(" &");
592 // the parent type should be a correctly pointer'ed or referenc'ed type
593 ret.SetCompilerType(static_type);
594 ret.SetName(corrected_name.c_str());
595 }
596 return ret;
597}
598
601 lldb::LanguageType language) {
602 if (language == eLanguageTypeC_plus_plus ||
603 language == eLanguageTypeC_plus_plus_03 ||
604 language == eLanguageTypeC_plus_plus_11 ||
605 language == eLanguageTypeC_plus_plus_14)
606 return new CPPLanguageRuntime(process);
607 else
608 return nullptr;
609}
610
613 GetPluginNameStatic(), "C++ language runtime", CreateInstance,
614 [](CommandInterpreter &interpreter) -> lldb::CommandObjectSP {
615 return CommandObjectSP(new CommandObjectCPlusPlus(interpreter));
616 });
617}
618
622
623llvm::Expected<LanguageRuntime::VTableInfo>
625 llvm::Expected<VTableInfoEntry> entry =
626 GetVTableInfoEntry(in_value, check_type);
627 if (!entry)
628 return entry.takeError();
629 return entry->info;
630}
631
634 bool catch_bp, bool throw_bp) {
635 return CreateExceptionResolver(bkpt, catch_bp, throw_bp, false);
636}
637
640 bool catch_bp, bool throw_bp,
641 bool for_expressions) {
642 std::vector<const char *> exception_names;
643 for (const auto &runtime : m_abi_runtimes)
644 runtime->AppendExceptionBreakpointFunctions(exception_names, catch_bp,
645 throw_bp, for_expressions);
646
648 bkpt, exception_names.data(), exception_names.size(),
649 eFunctionNameTypeBase, eLanguageTypeUnknown, 0, eLazyBoolNo));
650
651 return resolver_sp;
652}
653
655 Target &target = m_process->GetTarget();
656
657 FileSpecList filter_modules;
658 for (const auto &runtime : m_abi_runtimes)
659 runtime->AppendExceptionBreakpointFilterModules(filter_modules, target);
660
661 return target.GetSearchFilterForModuleList(&filter_modules);
662}
663
665 bool catch_bp, bool throw_bp, bool for_expressions, bool is_internal) {
666 Target &target = m_process->GetTarget();
667 FileSpecList filter_modules;
668 BreakpointResolverSP exception_resolver_sp =
669 CreateExceptionResolver(nullptr, catch_bp, throw_bp, for_expressions);
671 const bool hardware = false;
672 const bool resolve_indirect_functions = false;
673 return target.CreateBreakpoint(filter_sp, exception_resolver_sp, is_internal,
674 hardware, resolve_indirect_functions);
675}
676
678 if (!m_process)
679 return;
680
681 const bool catch_bp = false;
682 const bool throw_bp = true;
683 const bool is_internal = true;
684 const bool for_expressions = true;
685
686 // For the exception breakpoints set by the Expression parser, we'll be a
687 // little more aggressive and stop at exception allocation as well.
688
690 m_cxx_exception_bp_sp->SetEnabled(true);
691 } else {
693 catch_bp, throw_bp, for_expressions, is_internal);
695 m_cxx_exception_bp_sp->SetBreakpointKind("c++ exception");
696 }
697}
698
700 if (!m_process)
701 return;
702
704 m_cxx_exception_bp_sp->SetEnabled(false);
705 }
706}
707
711
713 lldb::StopInfoSP stop_reason) {
714 if (!m_process)
715 return false;
716
717 if (!stop_reason || stop_reason->GetStopReason() != eStopReasonBreakpoint)
718 return false;
719
720 uint64_t break_site_id = stop_reason->GetValue();
721 return m_process->GetBreakpointSiteList().StopPointSiteContainsBreakpoint(
722 break_site_id, m_cxx_exception_bp_sp->GetID());
723}
724
727 for (const auto &runtime : m_abi_runtimes) {
728 ValueObjectSP valobj = runtime->GetExceptionObjectForThread(thread_sp);
729 if (valobj)
730 return valobj;
731 }
732 return {};
733}
734
735static llvm::Error TypeHasVTable(CompilerType type) {
736 // Check to make sure the class has a vtable.
737 CompilerType original_type = type;
738 if (type.IsPointerOrReferenceType()) {
739 CompilerType pointee_type = type.GetPointeeType();
740 if (pointee_type)
741 type = pointee_type;
742 }
743
744 // Make sure this is a class or a struct first by checking the type class
745 // bitfield that gets returned.
746 if ((type.GetTypeClass() & (eTypeClassStruct | eTypeClassClass)) == 0) {
747 return llvm::createStringError(
748 std::errc::invalid_argument,
749 "type \"%s\" is not a class or struct or a pointer to one",
750 original_type.GetTypeName().AsCString("<invalid>"));
751 }
752
753 // Check if the type has virtual functions by asking it if it is polymorphic.
754 if (!type.IsPolymorphicClass()) {
755 return llvm::createStringError(std::errc::invalid_argument,
756 "type \"%s\" doesn't have a vtable",
757 type.GetTypeName().AsCString("<invalid>"));
758 }
759 return llvm::Error::success();
760}
761
762// This function can accept both pointers or references to classes as well as
763// instances of classes. If you are using this function during dynamic type
764// detection, only valid ValueObjects that return true to
765// CouldHaveDynamicValue(...) should call this function and \a check_type
766// should be set to false. This function is also used by ValueObjectVTable
767// and is can pass in instances of classes which is not suitable for dynamic
768// type detection, these cases should pass true for \a check_type.
769llvm::Expected<CPPLanguageRuntime::VTableInfoEntry>
771
772 CompilerType type = in_value.GetCompilerType();
773 if (check_type) {
774 if (llvm::Error err = TypeHasVTable(type))
775 return std::move(err);
776 }
777 ExecutionContext exe_ctx(in_value.GetExecutionContextRef());
778 Process *process = exe_ctx.GetProcessPtr();
779 if (process == nullptr)
780 return llvm::createStringError(std::errc::invalid_argument,
781 "invalid process");
782
783 auto [original_ptr, address_type] =
785 ? in_value.GetPointerValue()
786 : in_value.GetAddressOf(/*scalar_is_load_address=*/true);
787 if (original_ptr == LLDB_INVALID_ADDRESS || address_type != eAddressTypeLoad)
788 return llvm::createStringError(std::errc::invalid_argument,
789 "failed to get the address of the value");
790
791 llvm::Expected<lldb::addr_t> vtable_load_addr_or_err =
792 process->ReadPointerFromMemory(original_ptr);
793 if (!vtable_load_addr_or_err)
794 return vtable_load_addr_or_err.takeError();
795 lldb::addr_t vtable_load_addr = *vtable_load_addr_or_err;
796
797 // The vtable load address can have authentication bits with
798 // AArch64 targets on Darwin.
799 vtable_load_addr = process->FixDataAddress(vtable_load_addr);
800
801 // Find the symbol that contains the "vtable_load_addr" address
802 Address vtable_addr;
803 if (!process->GetTarget().ResolveLoadAddress(vtable_load_addr, vtable_addr))
804 return llvm::createStringError(std::errc::invalid_argument,
805 "failed to resolve vtable pointer 0x%" PRIx64
806 "to a section",
807 vtable_load_addr);
808
809 // Check our cache first to see if we already have this info
810 {
811 std::lock_guard<std::mutex> locker(m_vtable_mutex);
812 auto pos = m_vtable_info_map.find(vtable_addr);
813 if (pos != m_vtable_info_map.end())
814 return pos->second;
815 }
816
817 Symbol *symbol = vtable_addr.CalculateSymbolContextSymbol();
818 if (symbol == nullptr)
819 return llvm::createStringError(std::errc::invalid_argument,
820 "no symbol found for 0x%" PRIx64,
821 vtable_load_addr);
822
823 Mangled &mangled = symbol->GetMangled();
824 Log *log = GetLog(LLDBLog::Object);
825 for (const auto &runtime : m_abi_runtimes) {
826 if (runtime->IsVTableSymbol(symbol->GetMangled())) {
827 LLDB_LOG(log, "{0:x16} ({1}): symbol='{2}' matches {3}", original_ptr,
828 in_value.GetTypeName(), mangled.GetDemangledName(),
829 runtime->GetName());
830
831 VTableInfoEntry entry{
832 /*info=*/VTableInfo{vtable_addr, symbol},
833 /*runtime=*/runtime.get(),
834 };
835 std::lock_guard<std::mutex> locker(m_vtable_mutex);
836 m_vtable_info_map[vtable_addr] = entry;
837 return entry;
838 }
839 }
840 return llvm::createStringError(std::errc::invalid_argument,
841 "symbol found that contains 0x%" PRIx64
842 " is not a vtable symbol",
843 vtable_load_addr);
844}
static ConstString g_promise
static ConstString g_coro_frame
bool contains_lambda_identifier(llvm::StringRef &str_ref)
static ConstString g_this
static llvm::Error TypeHasVTable(CompilerType type)
CPPLanguageRuntime::LibCppStdFunctionCallableInfo line_entry_helper(Target &target, const SymbolContext &sc, Symbol *symbol, llvm::StringRef first_template_param_sref, bool has_invoke)
static char ID
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:375
#define LLDB_PLUGIN_DEFINE_ADV(ClassName, PluginName)
#define LLDB_SCOPED_TIMER()
Definition Timer.h:83
A frame recognizer that is installed to hide libc++ implementation details from the backtrace.
lldb::RecognizedStackFrameSP RecognizeFrame(lldb::StackFrameSP frame_sp) override
RecognizedStackFrameSP m_hidden_frame
std::array< RegularExpression, 2 > m_hidden_regex
std::string GetName() override
A section + offset based address range class.
A section + offset based address class.
Definition Address.h:62
lldb::addr_t GetLoadAddress(Target *target) const
Get the load address.
Definition Address.cpp:303
lldb::addr_t GetCallableLoadAddress(Target *target, bool is_indirect=false) const
Get the load address as a callable code load address.
Definition Address.cpp:328
bool Slide(int64_t offset)
Definition Address.h:446
bool CalculateSymbolContextLineEntry(LineEntry &line_entry) const
Definition Address.cpp:902
CompileUnit * CalculateSymbolContextCompileUnit() const
Definition Address.cpp:846
Symbol * CalculateSymbolContextSymbol() const
Definition Address.cpp:888
"lldb/Breakpoint/BreakpointResolverName.h" This class sets breakpoints on a given function name,...
llvm::Expected< LanguageRuntime::VTableInfo > GetVTableInfo(ValueObject &in_value, bool check_type) override
Get the vtable information for a given value.
std::map< Address, VTableInfoEntry > m_vtable_info_map
TypeAndOrName FixUpDynamicType(const TypeAndOrName &type_and_or_name, ValueObject &static_value) override
bool CouldHaveDynamicValue(ValueObject &in_value) override
lldb::BreakpointSP CreateExceptionBreakpoint(bool catch_bp, bool throw_bp, bool for_expressions, bool is_internal)
static lldb_private::LanguageRuntime * CreateInstance(Process *process, lldb::LanguageType language)
llvm::Error GetObjectDescription(Stream &str, ValueObject &object) override
lldb::SearchFilterSP CreateExceptionSearchFilter() override
lldb::ValueObjectSP GetExceptionObjectForThread(lldb::ThreadSP thread_sp) override
llvm::Expected< VTableInfoEntry > GetVTableInfoEntry(ValueObject &in_value, bool check_type)
bool IsSymbolARuntimeThunk(const Symbol &symbol) override
bool IsAllowedRuntimeValue(ConstString name) override
Identify whether a name is a runtime value that should not be hidden by from the user interface.
LibCppStdFunctionCallableInfo FindLibCppStdFunctionCallableInfo(lldb::ValueObjectSP &valobj_sp)
lldb::ThreadPlanSP GetStepThroughTrampolinePlan(Thread &thread, bool stop_others) override
Obtain a ThreadPlan to get us into C++ constructs such as std::function.
lldb::BreakpointResolverSP CreateExceptionResolver(const lldb::BreakpointSP &bkpt, bool catch_bp, bool throw_bp) override
OperatorStringToCallableInfoMap CallableLookupCache
static llvm::StringRef GetPluginNameStatic()
std::vector< std::unique_ptr< CommonABIRuntime > > m_abi_runtimes
bool GetDynamicTypeAndAddress(ValueObject &in_value, lldb::DynamicValueType use_dynamic, TypeAndOrName &class_type_or_name, Address &address, Value::ValueType &value_type, llvm::ArrayRef< uint8_t > &local_buffer) override
This call should return true if it could set the name and/or the type Sets address to the address of ...
bool ExceptionBreakpointsExplainStop(lldb::StopInfoSP stop_reason) override
A class that describes a compilation unit.
Definition CompileUnit.h:43
lldb::FunctionSP FindFunction(llvm::function_ref< bool(const lldb::FunctionSP &)> matching_lambda)
Find a function in the compile unit based on the predicate matching_lambda.
Generic representation of a type in a programming language.
bool IsPossibleDynamicType(CompilerType *target_type, bool check_cplusplus, bool check_objc) const
CompilerType GetPointerType() const
Return a new CompilerType that is a pointer to this type.
lldb::TypeClass GetTypeClass() const
CompilerType GetLValueReferenceType() const
Return a new CompilerType that is a L value reference to this type if this type is valid and the type...
ConstString GetTypeName(bool BaseOnly=false) const
CompilerType GetPointeeType() const
If this type is a pointer type, return the type that the pointer points to, else return an invalid ty...
uint32_t GetTypeInfo(CompilerType *pointee_or_element_compiler_type=nullptr) const
bool IsPointerOrReferenceType(CompilerType *pointee_type=nullptr) const
A uniqued constant string class.
Definition ConstString.h:40
llvm::StringRef GetStringRef() const
Get the string value as a llvm::StringRef.
const char * GetCString() const
Get the string value as a C string.
const char * AsCString(const char *value_if_empty) const
Get the string value as a C string.
"lldb/Target/ExecutionContextScope.h" Inherit from this if your object can reconstruct its execution ...
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
Process * GetProcessPtr() const
Returns a pointer to the process object.
A file collection class.
A class to manage flags.
Definition Flags.h:22
bool AllSet(ValueType mask) const
Test if all bits in mask are 1 in the current flags.
Definition Flags.h:83
const Address & GetAddress() const
Return the address of the function (its entry point).
Definition Function.h:430
uint32_t GetPrologueByteSize()
Get the size of the prologue instructions for this function.
Definition Function.cpp:594
A class that handles mangled names.
Definition Mangled.h:34
@ ePreferDemangledWithoutArguments
Definition Mangled.h:39
ConstString GetMangledName() const
Mangled name get accessor.
Definition Mangled.h:174
ConstString GetDemangledName() const
Demangled name get accessor.
Definition Mangled.cpp:284
uint32_t ResolveSymbolContextForAddress(const Address &so_addr, lldb::SymbolContextItem resolve_scope, SymbolContext &sc) const
Resolve the symbol context for the given address. (const Address&,uint32_t,SymbolContext&)
static bool RegisterPlugin(llvm::StringRef name, llvm::StringRef description, ABICreateInstance create_callback)
static bool UnregisterPlugin(ABICreateInstance create_callback)
A plug-in interface definition class for debugging a process.
Definition Process.h:367
lldb::addr_t FixDataAddress(lldb::addr_t pc)
Definition Process.cpp:6280
llvm::Expected< lldb::addr_t > ReadPointerFromMemory(lldb::addr_t vm_addr)
Definition Process.cpp:2561
uint32_t GetAddressByteSize() const
Definition Process.cpp:3977
const lldb::ABISP & GetABI()
Definition Process.cpp:1506
Target & GetTarget()
Get the target object pointer for this module.
Definition Process.h:1266
This class provides extra information about a stack frame that was provided by a specific stack frame...
Process * m_process
Definition Runtime.h:29
void AddRecognizer(lldb::StackFrameRecognizerSP recognizer, ConstString module, llvm::ArrayRef< ConstString > symbols, Mangled::NamePreference symbol_mangling, bool first_instruction_only=true)
Add a new recognizer that triggers on a given symbol name.
A base class for frame recognizers.
A stream class that can stream formatted output to a file.
Definition Stream.h:28
Defines a list of symbol context objects.
uint32_t GetSize() const
Get accessor for a symbol context list size.
Defines a symbol context baton that can be handed other debug core functions.
Function * function
The Function for a given query.
bool GetAddressRange(uint32_t scope, uint32_t range_idx, bool use_inline_block_range, AddressRange &range) const
Get the address range contained within a symbol context.
Symbol * symbol
The Symbol for a given query.
Address GetFunctionOrSymbolAddress() const
Get the address of the function or symbol represented by this symbol context.
Mangled & GetMangled()
Definition Symbol.h:162
ConstString GetName() const
Definition Symbol.cpp:612
Address GetAddress() const
Definition Symbol.h:98
uint32_t GetPrologueByteSize()
Definition Symbol.cpp:348
lldb::SearchFilterSP GetSearchFilterForModuleList(const FileSpecList *containingModuleList)
Definition Target.cpp:706
bool ResolveLoadAddress(lldb::addr_t load_addr, Address &so_addr, uint32_t stop_id=SectionLoadHistory::eStopIDNow, bool allow_section_end=false)
Definition Target.cpp:3495
StackFrameRecognizerManager & GetFrameRecognizerManager()
Definition Target.h:2004
lldb::BreakpointSP CreateBreakpoint(const FileSpecList *containingModules, const FileSpec &file, uint32_t line_no, uint32_t column, lldb::addr_t offset, LazyBool check_inlines, LazyBool skip_prologue, bool internal, bool request_hardware, LazyBool move_to_nearest_code)
Definition Target.cpp:505
const ModuleList & GetImages() const
Get accessor for the images for this process.
Definition Target.h:1254
Sometimes you can find the name of the type corresponding to an object, but we don't have debug infor...
Definition Type.h:780
void SetName(ConstString type_name)
Definition Type.cpp:911
CompilerType GetCompilerType() const
Definition Type.h:794
ConstString GetName() const
Definition Type.cpp:903
void SetCompilerType(CompilerType compiler_type)
Definition Type.cpp:931
bool HasType() const
Definition Type.h:812
virtual ConstString GetTypeName()
CompilerType GetCompilerType()
const ExecutionContextRef & GetExecutionContextRef() const
virtual AddrAndType GetAddressOf(bool scalar_is_load_address=true)
ValueType
Type that describes Value::m_value.
Definition Value.h:42
@ Scalar
A raw scalar value.
Definition Value.h:46
#define LLDB_INVALID_ADDRESS
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:338
void RegisterVerboseTrapFrameRecognizer(Process &process)
@ eAddressTypeLoad
Address is an address as in the current target inferior process.
std::shared_ptr< lldb_private::Function > FunctionSP
std::shared_ptr< lldb_private::ThreadPlan > ThreadPlanSP
std::shared_ptr< lldb_private::ABI > ABISP
std::shared_ptr< lldb_private::StackFrame > StackFrameSP
std::shared_ptr< lldb_private::RecognizedStackFrame > RecognizedStackFrameSP
std::shared_ptr< lldb_private::SearchFilter > SearchFilterSP
std::shared_ptr< lldb_private::BreakpointResolver > BreakpointResolverSP
std::shared_ptr< lldb_private::Thread > ThreadSP
std::shared_ptr< lldb_private::CommandObject > CommandObjectSP
std::shared_ptr< lldb_private::ValueObject > ValueObjectSP
LanguageType
Programming language type.
@ eLanguageTypeC_plus_plus_14
ISO C++:2014.
@ eLanguageTypeC_plus_plus_03
ISO C++:2003.
@ eLanguageTypeUnknown
Unknown or invalid language value.
@ eLanguageTypeC_plus_plus_11
ISO C++:2011.
@ eLanguageTypeC_plus_plus
ISO C++:1998.
std::shared_ptr< lldb_private::Breakpoint > BreakpointSP
std::shared_ptr< lldb_private::StackFrameRecognizer > StackFrameRecognizerSP
std::shared_ptr< lldb_private::StopInfo > StopInfoSP
uint64_t addr_t
Definition lldb-types.h:80
@ eStopReasonBreakpoint
std::shared_ptr< lldb_private::Target > TargetSP
bool ShouldHide() override
Controls whether this frame should be filtered out when displaying backtraces, for example.
A line table entry class.
Definition LineEntry.h:21