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
21#include "lldb/Symbol/Block.h"
24
28#include "lldb/Target/ABI.h"
37#include "lldb/Utility/Timer.h"
38
39using namespace lldb;
40using namespace lldb_private;
41
43
45// Artificial coroutine-related variables emitted by clang.
46static ConstString g_promise = ConstString("__promise");
47static ConstString g_coro_frame = ConstString("__coro_frame");
48
49char CPPLanguageRuntime::ID = 0;
50
51/// A frame recognizer that is installed to hide libc++ implementation
52/// details from the backtrace.
54 std::array<RegularExpression, 2> m_hidden_regex;
56
58 bool ShouldHide() override { return true; }
59 };
60
61public:
64 // internal implementation details in the `std::` namespace
65 // std::__1::__function::__alloc_func<void (*)(), std::__1::allocator<void (*)()>, void ()>::operator()[abi:ne200000]
66 // std::__1::__function::__func<void (*)(), std::__1::allocator<void (*)()>, void ()>::operator()
67 // std::__1::__function::__value_func<void ()>::operator()[abi:ne200000]() const
68 // std::__2::__function::__policy_invoker<void (int, int)>::__call_impl[abi:ne200000]<std::__2::__function::__default_alloc_func<int (*)(int, int), int (int, int)>>
69 // std::__1::__invoke[abi:ne200000]<void (*&)()>
70 // std::__1::__invoke_void_return_wrapper<void, true>::__call[abi:ne200000]<void (*&)()>
71 RegularExpression{R"(^std::__[^:]*::__)"},
72 // internal implementation details in the `std::ranges` namespace
73 // 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>
74 RegularExpression{R"(^std::__[^:]*::ranges::__)"},
75 },
77
78 std::string GetName() override { return "libc++ frame recognizer"; }
79
82 if (!frame_sp)
83 return {};
84 const auto &sc = frame_sp->GetSymbolContext(lldb::eSymbolContextFunction);
85 if (!sc.function)
86 return {};
87
88 // Check if we have a regex match
90 if (!r.Execute(sc.function->GetNameNoArguments()))
91 continue;
92
93 // Only hide this frame if the immediate caller is also within libc++.
94 lldb::ThreadSP thread_sp = frame_sp->GetThread();
95 if (!thread_sp)
96 return {};
97 lldb::StackFrameSP parent_frame_sp =
98 thread_sp->GetStackFrameAtIndex(frame_sp->GetFrameIndex() + 1);
99 if (!parent_frame_sp)
100 return {};
101 const auto &parent_sc =
102 parent_frame_sp->GetSymbolContext(lldb::eSymbolContextFunction);
103 if (!parent_sc.function)
104 return {};
105 if (parent_sc.function->GetNameNoArguments().GetStringRef().starts_with(
106 "std::"))
107 return m_hidden_frame;
108 }
109
110 return {};
111 }
112};
113
115 : LanguageRuntime(process) {
116 if (process) {
119 std::make_shared<RegularExpression>("^std::__[^:]*::"),
120 /*mangling_preference=*/Mangled::ePreferDemangledWithoutArguments,
121 /*first_instruction_only=*/false);
122
124 }
125
126 m_abi_runtimes.emplace_back(new ItaniumABIRuntime(process));
127}
128
130 return name == g_this || name == g_promise || name == g_coro_frame;
131}
132
134 ValueObject &object) {
135 // C++ has no generic way to do this.
136 return llvm::createStringError("C++ does not support object descriptions");
137}
138
139llvm::Error
141 ExecutionContextScope *exe_scope) {
142 // C++ has no generic way to do this.
143 return llvm::createStringError("C++ does not support object descriptions");
144}
145
146bool contains_lambda_identifier(llvm::StringRef &str_ref) {
147 return str_ref.contains("$_") || str_ref.contains("'lambda'");
148}
149
151line_entry_helper(Target &target, const SymbolContext &sc, Symbol *symbol,
152 llvm::StringRef first_template_param_sref, bool has_invoke) {
153
155
156 Address address = sc.GetFunctionOrSymbolAddress();
157
158 Address addr;
159 if (target.ResolveLoadAddress(address.GetCallableLoadAddress(&target),
160 addr)) {
161 LineEntry line_entry;
162 addr.CalculateSymbolContextLineEntry(line_entry);
163
164 if (contains_lambda_identifier(first_template_param_sref) || has_invoke) {
165 // Case 1 and 2
166 optional_info.callable_case = lldb_private::CPPLanguageRuntime::
167 LibCppStdFunctionCallableCase::Lambda;
168 } else {
169 // Case 3
170 optional_info.callable_case = lldb_private::CPPLanguageRuntime::
171 LibCppStdFunctionCallableCase::CallableObject;
172 }
173
174 optional_info.callable_symbol = *symbol;
175 optional_info.callable_line_entry = line_entry;
176 optional_info.callable_address = addr;
177 }
178
179 return optional_info;
180}
181
184 lldb::ValueObjectSP &valobj_sp) {
186
187 LibCppStdFunctionCallableInfo optional_info;
188
189 if (!valobj_sp)
190 return optional_info;
191
192 // Member __f_ has type __base*, the contents of which will hold:
193 // 1) a vtable entry which may hold type information needed to discover the
194 // lambda being called
195 // 2) possibly hold a pointer to the callable object
196 // e.g.
197 //
198 // (lldb) frame var -R f_display
199 // (std::__1::function<void (int)>) f_display = {
200 // __buf_ = {
201 // …
202 // }
203 // __f_ = 0x00007ffeefbffa00
204 // }
205 // (lldb) memory read -fA 0x00007ffeefbffa00
206 // 0x7ffeefbffa00: ... `vtable for std::__1::__function::__func<void (*) ...
207 // 0x7ffeefbffa08: ... `print_num(int) at std_function_cppreference_exam ...
208 //
209 // We will be handling five cases below, std::function is wrapping:
210 //
211 // 1) a lambda we know at compile time. We will obtain the name of the lambda
212 // from the first template pameter from __func's vtable. We will look up
213 // the lambda's operator()() and obtain the line table entry.
214 // 2) a lambda we know at runtime. A pointer to the lambdas __invoke method
215 // will be stored after the vtable. We will obtain the lambdas name from
216 // this entry and lookup operator()() and obtain the line table entry.
217 // 3) a callable object via operator()(). We will obtain the name of the
218 // object from the first template parameter from __func's vtable. We will
219 // look up the objects operator()() and obtain the line table entry.
220 // 4) a member function. A pointer to the function will stored after the
221 // we will obtain the name from this pointer.
222 // 5) a free function. A pointer to the function will stored after the vtable
223 // we will obtain the name from this pointer.
224 ValueObjectSP member_f_(valobj_sp->GetChildMemberWithName("__f_"));
225
226 if (member_f_) {
227 ValueObjectSP sub_member_f_(member_f_->GetChildMemberWithName("__f_"));
228
229 if (sub_member_f_)
230 member_f_ = sub_member_f_;
231 }
232
233 if (!member_f_)
234 return optional_info;
235
236 lldb::addr_t member_f_pointer_value = member_f_->GetValueAsUnsigned(0);
237
238 optional_info.member_f_pointer_value = member_f_pointer_value;
239
240 if (!member_f_pointer_value)
241 return optional_info;
242
243 ExecutionContext exe_ctx(valobj_sp->GetExecutionContextRef());
244 Process *process = exe_ctx.GetProcessPtr();
245
246 if (process == nullptr)
247 return optional_info;
248
249 uint32_t address_size = process->GetAddressByteSize();
250 Status status;
251
252 // First item pointed to by __f_ should be the pointer to the vtable for
253 // a __base object.
254 lldb::addr_t vtable_address =
255 process->ReadPointerFromMemory(member_f_pointer_value, status);
256
257 ABISP abi_sp = process->GetABI();
258 if (abi_sp)
259 vtable_address = abi_sp->FixCodeAddress(vtable_address);
260
261 if (status.Fail())
262 return optional_info;
263
264 lldb::addr_t vtable_address_first_entry =
265 process->ReadPointerFromMemory(vtable_address + address_size, status);
266
267 if (abi_sp)
268 vtable_address_first_entry =
269 abi_sp->FixCodeAddress(vtable_address_first_entry);
270
271 if (status.Fail())
272 return optional_info;
273
274 lldb::addr_t address_after_vtable = member_f_pointer_value + address_size;
275 // As commented above we may not have a function pointer but if we do we will
276 // need it.
277 lldb::addr_t possible_function_address =
278 process->ReadPointerFromMemory(address_after_vtable, status);
279
280 if (abi_sp)
281 possible_function_address =
282 abi_sp->FixCodeAddress(possible_function_address);
283
284 if (status.Fail())
285 return optional_info;
286
287 Target &target = process->GetTarget();
288
289 if (!target.HasLoadedSections())
290 return optional_info;
291
292 Address vtable_first_entry_resolved;
293
294 if (!target.ResolveLoadAddress(vtable_address_first_entry,
295 vtable_first_entry_resolved))
296 return optional_info;
297
298 Address vtable_addr_resolved;
299 SymbolContext sc;
300 Symbol *symbol = nullptr;
301
302 if (!target.ResolveLoadAddress(vtable_address, vtable_addr_resolved))
303 return optional_info;
304
306 vtable_addr_resolved, eSymbolContextEverything, sc);
307 symbol = sc.symbol;
308
309 if (symbol == nullptr)
310 return optional_info;
311
312 llvm::StringRef vtable_name(symbol->GetName().GetStringRef());
313 bool found_expected_start_string =
314 vtable_name.starts_with("vtable for std::__1::__function::__func<");
315
316 if (!found_expected_start_string)
317 return optional_info;
318
319 // Given case 1 or 3 we have a vtable name, we are want to extract the first
320 // template parameter
321 //
322 // ... __func<main::$_0, std::__1::allocator<main::$_0> ...
323 // ^^^^^^^^^
324 //
325 // We could see names such as:
326 // main::$_0
327 // Bar::add_num2(int)::'lambda'(int)
328 // Bar
329 //
330 // We do this by find the first < and , and extracting in between.
331 //
332 // This covers the case of the lambda known at compile time.
333 size_t first_open_angle_bracket = vtable_name.find('<') + 1;
334 size_t first_comma = vtable_name.find(',');
335
336 llvm::StringRef first_template_parameter =
337 vtable_name.slice(first_open_angle_bracket, first_comma);
338
339 Address function_address_resolved;
340
341 // Setup for cases 2, 4 and 5 we have a pointer to a function after the
342 // vtable. We will use a process of elimination to drop through each case
343 // and obtain the data we need.
344 if (target.ResolveLoadAddress(possible_function_address,
345 function_address_resolved)) {
347 function_address_resolved, eSymbolContextEverything, sc);
348 symbol = sc.symbol;
349 }
350
351 // These conditions are used several times to simplify statements later on.
352 bool has_invoke =
353 (symbol ? symbol->GetName().GetStringRef().contains("__invoke") : false);
354 auto calculate_symbol_context_helper = [](auto &t,
355 SymbolContextList &sc_list) {
356 SymbolContext sc;
357 t->CalculateSymbolContext(&sc);
358 sc_list.Append(sc);
359 };
360
361 // Case 2
362 if (has_invoke) {
364 calculate_symbol_context_helper(symbol, scl);
365
366 return line_entry_helper(target, scl[0], symbol, first_template_parameter,
367 has_invoke);
368 }
369
370 // Case 4 or 5
371 if (symbol && !symbol->GetName().GetStringRef().starts_with("vtable for") &&
372 !contains_lambda_identifier(first_template_parameter) && !has_invoke) {
373 optional_info.callable_case =
375 optional_info.callable_address = function_address_resolved;
376 optional_info.callable_symbol = *symbol;
377
378 return optional_info;
379 }
380
381 std::string func_to_match = first_template_parameter.str();
382
383 auto it = CallableLookupCache.find(func_to_match);
384 if (it != CallableLookupCache.end())
385 return it->second;
386
388
389 CompileUnit *vtable_cu =
390 vtable_first_entry_resolved.CalculateSymbolContextCompileUnit();
391 llvm::StringRef name_to_use = func_to_match;
392
393 // Case 3, we have a callable object instead of a lambda
394 //
395 // TODO
396 // We currently don't support this case a callable object may have multiple
397 // operator()() varying on const/non-const and number of arguments and we
398 // don't have a way to currently distinguish them so we will bail out now.
399 if (!contains_lambda_identifier(name_to_use))
400 return optional_info;
401
402 if (vtable_cu && !has_invoke) {
403 lldb::FunctionSP func_sp =
404 vtable_cu->FindFunction([name_to_use](const FunctionSP &f) {
405 auto name = f->GetName().GetStringRef();
406 if (name.starts_with(name_to_use) && name.contains("operator"))
407 return true;
408
409 return false;
410 });
411
412 if (func_sp) {
413 calculate_symbol_context_helper(func_sp, scl);
414 }
415 }
416
417 if (symbol == nullptr)
418 return optional_info;
419
420 // Case 1 or 3
421 if (scl.GetSize() >= 1) {
422 optional_info = line_entry_helper(target, scl[0], symbol,
423 first_template_parameter, has_invoke);
424 }
425
426 CallableLookupCache[func_to_match] = optional_info;
427
428 return optional_info;
429}
430
433 bool stop_others) {
434 ThreadPlanSP ret_plan_sp;
435
436 lldb::addr_t curr_pc = thread.GetRegisterContext()->GetPC();
437
438 TargetSP target_sp(thread.CalculateTarget());
439
440 if (!target_sp->HasLoadedSections())
441 return ret_plan_sp;
442
443 Address pc_addr_resolved;
444 SymbolContext sc;
445 Symbol *symbol;
446
447 if (!target_sp->ResolveLoadAddress(curr_pc, pc_addr_resolved))
448 return ret_plan_sp;
449
450 target_sp->GetImages().ResolveSymbolContextForAddress(
451 pc_addr_resolved, eSymbolContextEverything, sc);
452 symbol = sc.symbol;
453
454 if (symbol == nullptr)
455 return ret_plan_sp;
456
457 llvm::StringRef function_name(symbol->GetName().GetCString());
458
459 // Handling the case where we are attempting to step into std::function.
460 // The behavior will be that we will attempt to obtain the wrapped
461 // callable via FindLibCppStdFunctionCallableInfo() and if we find it we
462 // will return a ThreadPlanRunToAddress to the callable. Therefore we will
463 // step into the wrapped callable.
464 //
465 bool found_expected_start_string =
466 function_name.starts_with("std::__1::function<");
467
468 if (!found_expected_start_string)
469 return ret_plan_sp;
470
471 AddressRange range_of_curr_func;
472 sc.GetAddressRange(eSymbolContextEverything, 0, false, range_of_curr_func);
473
474 StackFrameSP frame = thread.GetStackFrameAtIndex(0);
475
476 if (frame) {
477 Address func_start_address =
478 sc.function ? sc.function->GetAddress() : symbol->GetAddress();
479 lldb::addr_t func_start =
480 func_start_address.GetLoadAddress(target_sp.get());
481
482 if (func_start == LLDB_INVALID_ADDRESS)
483 return ret_plan_sp;
484
485 // Advance past the prologue if we stopped there.
486 uint32_t prologue_size = sc.function ? sc.function->GetPrologueByteSize()
487 : symbol->GetPrologueByteSize();
488 if (curr_pc < func_start + prologue_size) {
489 func_start_address.Slide(prologue_size);
490 return std::make_shared<ThreadPlanRunToAddress>(
491 thread, func_start_address, stop_others);
492 }
493
494 ValueObjectSP value_sp = frame->FindVariable(g_this);
495
498
500 value_sp->GetValueIsValid()) {
501 // We found the std::function wrapped callable and we have its address.
502 // We now create a ThreadPlan to run to the callable.
503 ret_plan_sp = std::make_shared<ThreadPlanRunToAddress>(
504 thread, callable_info.callable_address, stop_others);
505 return ret_plan_sp;
506 } else {
507 // We are in std::function but we could not obtain the callable.
508 // We create a ThreadPlan to keep stepping through using the address range
509 // of the current function.
510 ret_plan_sp = std::make_shared<ThreadPlanStepInRange>(
511 thread, range_of_curr_func, sc, std::string(), eOnlyThisThread,
513 return ret_plan_sp;
514 }
515 }
516
517 return ret_plan_sp;
518}
519
521 llvm::StringRef mangled_name =
523 // Virtual function overriding from a non-virtual base use a "Th" prefix.
524 // Virtual function overriding from a virtual base must use a "Tv" prefix.
525 // Virtual function overriding thunks with covariant returns use a "Tc"
526 // prefix.
527 return mangled_name.starts_with("_ZTh") || mangled_name.starts_with("_ZTv") ||
528 mangled_name.starts_with("_ZTc");
529}
530
532 const bool check_cxx = true;
533 const bool check_objc = false;
534 return in_value.GetCompilerType().IsPossibleDynamicType(nullptr, check_cxx,
535 check_objc);
536}
537
539 ValueObject &in_value, lldb::DynamicValueType use_dynamic,
540 TypeAndOrName &class_type_or_name, Address &dynamic_address,
541 Value::ValueType &value_type, llvm::ArrayRef<uint8_t> &local_buffer) {
542 class_type_or_name.Clear();
543 value_type = Value::ValueType::Scalar;
544
545 if (!CouldHaveDynamicValue(in_value))
546 return false;
547
548 llvm::Expected<VTableInfoEntry> entry =
549 GetVTableInfoEntry(in_value, /*check_type=*/false);
550 if (!entry) {
551 llvm::consumeError(entry.takeError());
552 return false;
553 }
554
555 return entry->runtime->GetDynamicTypeAndAddress(
556 in_value, use_dynamic, entry->info, class_type_or_name, dynamic_address);
557}
558
561 ValueObject &static_value) {
562 CompilerType static_type(static_value.GetCompilerType());
563 Flags static_type_flags(static_type.GetTypeInfo());
564
565 TypeAndOrName ret(type_and_or_name);
566 if (type_and_or_name.HasType()) {
567 // The type will always be the type of the dynamic object. If our parent's
568 // type was a pointer, then our type should be a pointer to the type of the
569 // dynamic object. If a reference, then the original type should be
570 // okay...
571 CompilerType orig_type = type_and_or_name.GetCompilerType();
572 CompilerType corrected_type = orig_type;
573 if (static_type_flags.AllSet(eTypeIsPointer))
574 corrected_type = orig_type.GetPointerType();
575 else if (static_type_flags.AllSet(eTypeIsReference))
576 corrected_type = orig_type.GetLValueReferenceType();
577 ret.SetCompilerType(corrected_type);
578 } else {
579 // If we are here we need to adjust our dynamic type name to include the
580 // correct & or * symbol
581 std::string corrected_name(type_and_or_name.GetName().GetCString());
582 if (static_type_flags.AllSet(eTypeIsPointer))
583 corrected_name.append(" *");
584 else if (static_type_flags.AllSet(eTypeIsReference))
585 corrected_name.append(" &");
586 // the parent type should be a correctly pointer'ed or referenc'ed type
587 ret.SetCompilerType(static_type);
588 ret.SetName(corrected_name.c_str());
589 }
590 return ret;
591}
592
595 lldb::LanguageType language) {
596 if (language == eLanguageTypeC_plus_plus ||
597 language == eLanguageTypeC_plus_plus_03 ||
598 language == eLanguageTypeC_plus_plus_11 ||
599 language == eLanguageTypeC_plus_plus_14)
600 return new CPPLanguageRuntime(process);
601 else
602 return nullptr;
603}
604
607 GetPluginNameStatic(), "C++ language runtime", CreateInstance,
608 [](CommandInterpreter &interpreter) -> lldb::CommandObjectSP {
609 return CommandObjectSP(new CommandObjectCPlusPlus(interpreter));
610 });
611}
612
616
617llvm::Expected<LanguageRuntime::VTableInfo>
619 llvm::Expected<VTableInfoEntry> entry =
620 GetVTableInfoEntry(in_value, check_type);
621 if (!entry)
622 return entry.takeError();
623 return entry->info;
624}
625
628 bool catch_bp, bool throw_bp) {
629 return CreateExceptionResolver(bkpt, catch_bp, throw_bp, false);
630}
631
634 bool catch_bp, bool throw_bp,
635 bool for_expressions) {
636 std::vector<const char *> exception_names;
637 for (const auto &runtime : m_abi_runtimes)
638 runtime->AppendExceptionBreakpointFunctions(exception_names, catch_bp,
639 throw_bp, for_expressions);
640
642 bkpt, exception_names.data(), exception_names.size(),
643 eFunctionNameTypeBase, eLanguageTypeUnknown, 0, eLazyBoolNo));
644
645 return resolver_sp;
646}
647
649 Target &target = m_process->GetTarget();
650
651 FileSpecList filter_modules;
652 for (const auto &runtime : m_abi_runtimes)
653 runtime->AppendExceptionBreakpointFilterModules(filter_modules, target);
654
655 return target.GetSearchFilterForModuleList(&filter_modules);
656}
657
659 bool catch_bp, bool throw_bp, bool for_expressions, bool is_internal) {
660 Target &target = m_process->GetTarget();
661 FileSpecList filter_modules;
662 BreakpointResolverSP exception_resolver_sp =
663 CreateExceptionResolver(nullptr, catch_bp, throw_bp, for_expressions);
665 const bool hardware = false;
666 const bool resolve_indirect_functions = false;
667 return target.CreateBreakpoint(filter_sp, exception_resolver_sp, is_internal,
668 hardware, resolve_indirect_functions);
669}
670
672 if (!m_process)
673 return;
674
675 const bool catch_bp = false;
676 const bool throw_bp = true;
677 const bool is_internal = true;
678 const bool for_expressions = true;
679
680 // For the exception breakpoints set by the Expression parser, we'll be a
681 // little more aggressive and stop at exception allocation as well.
682
684 m_cxx_exception_bp_sp->SetEnabled(true);
685 } else {
687 catch_bp, throw_bp, for_expressions, is_internal);
689 m_cxx_exception_bp_sp->SetBreakpointKind("c++ exception");
690 }
691}
692
694 if (!m_process)
695 return;
696
698 m_cxx_exception_bp_sp->SetEnabled(false);
699 }
700}
701
705
707 lldb::StopInfoSP stop_reason) {
708 if (!m_process)
709 return false;
710
711 if (!stop_reason || stop_reason->GetStopReason() != eStopReasonBreakpoint)
712 return false;
713
714 uint64_t break_site_id = stop_reason->GetValue();
715 return m_process->GetBreakpointSiteList().StopPointSiteContainsBreakpoint(
716 break_site_id, m_cxx_exception_bp_sp->GetID());
717}
718
721 for (const auto &runtime : m_abi_runtimes) {
722 ValueObjectSP valobj = runtime->GetExceptionObjectForThread(thread_sp);
723 if (valobj)
724 return valobj;
725 }
726 return {};
727}
728
729static llvm::Error TypeHasVTable(CompilerType type) {
730 // Check to make sure the class has a vtable.
731 CompilerType original_type = type;
732 if (type.IsPointerOrReferenceType()) {
733 CompilerType pointee_type = type.GetPointeeType();
734 if (pointee_type)
735 type = pointee_type;
736 }
737
738 // Make sure this is a class or a struct first by checking the type class
739 // bitfield that gets returned.
740 if ((type.GetTypeClass() & (eTypeClassStruct | eTypeClassClass)) == 0) {
741 return llvm::createStringError(
742 std::errc::invalid_argument,
743 "type \"%s\" is not a class or struct or a pointer to one",
744 original_type.GetTypeName().AsCString("<invalid>"));
745 }
746
747 // Check if the type has virtual functions by asking it if it is polymorphic.
748 if (!type.IsPolymorphicClass()) {
749 return llvm::createStringError(std::errc::invalid_argument,
750 "type \"%s\" doesn't have a vtable",
751 type.GetTypeName().AsCString("<invalid>"));
752 }
753 return llvm::Error::success();
754}
755
756// This function can accept both pointers or references to classes as well as
757// instances of classes. If you are using this function during dynamic type
758// detection, only valid ValueObjects that return true to
759// CouldHaveDynamicValue(...) should call this function and \a check_type
760// should be set to false. This function is also used by ValueObjectVTable
761// and is can pass in instances of classes which is not suitable for dynamic
762// type detection, these cases should pass true for \a check_type.
763llvm::Expected<CPPLanguageRuntime::VTableInfoEntry>
765
766 CompilerType type = in_value.GetCompilerType();
767 if (check_type) {
768 if (llvm::Error err = TypeHasVTable(type))
769 return std::move(err);
770 }
771 ExecutionContext exe_ctx(in_value.GetExecutionContextRef());
772 Process *process = exe_ctx.GetProcessPtr();
773 if (process == nullptr)
774 return llvm::createStringError(std::errc::invalid_argument,
775 "invalid process");
776
777 auto [original_ptr, address_type] =
779 ? in_value.GetPointerValue()
780 : in_value.GetAddressOf(/*scalar_is_load_address=*/true);
781 if (original_ptr == LLDB_INVALID_ADDRESS || address_type != eAddressTypeLoad)
782 return llvm::createStringError(std::errc::invalid_argument,
783 "failed to get the address of the value");
784
786 lldb::addr_t vtable_load_addr =
787 process->ReadPointerFromMemory(original_ptr, error);
788
789 if (!error.Success() || vtable_load_addr == LLDB_INVALID_ADDRESS)
790 return llvm::createStringError(
791 std::errc::invalid_argument,
792 "failed to read vtable pointer from memory at 0x%" PRIx64,
793 original_ptr);
794
795 // The vtable load address can have authentication bits with
796 // AArch64 targets on Darwin.
797 vtable_load_addr = process->FixDataAddress(vtable_load_addr);
798
799 // Find the symbol that contains the "vtable_load_addr" address
800 Address vtable_addr;
801 if (!process->GetTarget().ResolveLoadAddress(vtable_load_addr, vtable_addr))
802 return llvm::createStringError(std::errc::invalid_argument,
803 "failed to resolve vtable pointer 0x%" PRIx64
804 "to a section",
805 vtable_load_addr);
806
807 // Check our cache first to see if we already have this info
808 {
809 std::lock_guard<std::mutex> locker(m_vtable_mutex);
810 auto pos = m_vtable_info_map.find(vtable_addr);
811 if (pos != m_vtable_info_map.end())
812 return pos->second;
813 }
814
815 Symbol *symbol = vtable_addr.CalculateSymbolContextSymbol();
816 if (symbol == nullptr)
817 return llvm::createStringError(std::errc::invalid_argument,
818 "no symbol found for 0x%" PRIx64,
819 vtable_load_addr);
820
821 Mangled &mangled = symbol->GetMangled();
822 Log *log = GetLog(LLDBLog::Object);
823 for (const auto &runtime : m_abi_runtimes) {
824 if (runtime->IsVTableSymbol(symbol->GetMangled())) {
825 LLDB_LOG(log, "{0:x16} ({1}): symbol='{2}' matches {3}", original_ptr,
826 in_value.GetTypeName(), mangled.GetDemangledName(),
827 runtime->GetName());
828
829 VTableInfoEntry entry{
830 /*info=*/VTableInfo{vtable_addr, symbol},
831 /*runtime=*/runtime.get(),
832 };
833 std::lock_guard<std::mutex> locker(m_vtable_mutex);
834 m_vtable_info_map[vtable_addr] = entry;
835 return entry;
836 }
837 }
838 return llvm::createStringError(std::errc::invalid_argument,
839 "symbol found that contains 0x%" PRIx64
840 " is not a vtable symbol",
841 vtable_load_addr);
842}
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 llvm::raw_ostream & error(Stream &strm)
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:301
lldb::addr_t GetCallableLoadAddress(Target *target, bool is_indirect=false) const
Get the load address as a callable code load address.
Definition Address.cpp:326
bool Slide(int64_t offset)
Definition Address.h:446
bool CalculateSymbolContextLineEntry(LineEntry &line_entry) const
Definition Address.cpp:901
CompileUnit * CalculateSymbolContextCompileUnit() const
Definition Address.cpp:845
Symbol * CalculateSymbolContextSymbol() const
Definition Address.cpp:887
"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:360
lldb::addr_t FixDataAddress(lldb::addr_t pc)
Definition Process.cpp:6235
lldb::addr_t ReadPointerFromMemory(lldb::addr_t vm_addr, Status &error)
Definition Process.cpp:2519
uint32_t GetAddressByteSize() const
Definition Process.cpp:3932
const lldb::ABISP & GetABI()
Definition Process.cpp:1492
Target & GetTarget()
Get the target object pointer for this module.
Definition Process.h:1259
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.
An error handling class.
Definition Status.h:118
bool Fail() const
Test for error condition.
Definition Status.cpp:293
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:164
ConstString GetName() const
Definition Symbol.cpp:554
Address GetAddress() const
Definition Symbol.h:102
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