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
17#include "llvm/ADT/StringRef.h"
18
19#include "lldb/Symbol/Block.h"
22
26#include "lldb/Target/ABI.h"
34#include "lldb/Utility/Timer.h"
35
36using namespace lldb;
37using namespace lldb_private;
38
40// Artificial coroutine-related variables emitted by clang.
41static ConstString g_promise = ConstString("__promise");
42static ConstString g_coro_frame = ConstString("__coro_frame");
43
45
46/// A frame recognizer that is installed to hide libc++ implementation
47/// details from the backtrace.
49 std::array<RegularExpression, 2> m_hidden_regex;
51
53 bool ShouldHide() override { return true; }
54 };
55
56public:
59 // internal implementation details in the `std::` namespace
60 // std::__1::__function::__alloc_func<void (*)(), std::__1::allocator<void (*)()>, void ()>::operator()[abi:ne200000]
61 // std::__1::__function::__func<void (*)(), std::__1::allocator<void (*)()>, void ()>::operator()
62 // std::__1::__function::__value_func<void ()>::operator()[abi:ne200000]() const
63 // std::__2::__function::__policy_invoker<void (int, int)>::__call_impl[abi:ne200000]<std::__2::__function::__default_alloc_func<int (*)(int, int), int (int, int)>>
64 // std::__1::__invoke[abi:ne200000]<void (*&)()>
65 // std::__1::__invoke_void_return_wrapper<void, true>::__call[abi:ne200000]<void (*&)()>
66 RegularExpression{R"(^std::__[^:]*::__)"},
67 // internal implementation details in the `std::ranges` namespace
68 // 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>
69 RegularExpression{R"(^std::__[^:]*::ranges::__)"},
70 },
72
73 std::string GetName() override { return "libc++ frame recognizer"; }
74
77 if (!frame_sp)
78 return {};
79 const auto &sc = frame_sp->GetSymbolContext(lldb::eSymbolContextFunction);
80 if (!sc.function)
81 return {};
82
83 // Check if we have a regex match
85 if (!r.Execute(sc.function->GetNameNoArguments()))
86 continue;
87
88 // Only hide this frame if the immediate caller is also within libc++.
89 lldb::ThreadSP thread_sp = frame_sp->GetThread();
90 if (!thread_sp)
91 return {};
92 lldb::StackFrameSP parent_frame_sp =
93 thread_sp->GetStackFrameAtIndex(frame_sp->GetFrameIndex() + 1);
94 if (!parent_frame_sp)
95 return {};
96 const auto &parent_sc =
97 parent_frame_sp->GetSymbolContext(lldb::eSymbolContextFunction);
98 if (!parent_sc.function)
99 return {};
100 if (parent_sc.function->GetNameNoArguments().GetStringRef().starts_with(
101 "std::"))
102 return m_hidden_frame;
103 }
104
105 return {};
106 }
107};
108
110 : LanguageRuntime(process) {
111 if (process) {
114 std::make_shared<RegularExpression>("^std::__[^:]*::"),
115 /*mangling_preference=*/Mangled::ePreferDemangledWithoutArguments,
116 /*first_instruction_only=*/false);
117
119 }
120}
121
123 return name == g_this || name == g_promise || name == g_coro_frame;
124}
125
127 ValueObject &object) {
128 // C++ has no generic way to do this.
129 return llvm::createStringError("C++ does not support object descriptions");
130}
131
132llvm::Error
134 ExecutionContextScope *exe_scope) {
135 // C++ has no generic way to do this.
136 return llvm::createStringError("C++ does not support object descriptions");
137}
138
139bool contains_lambda_identifier(llvm::StringRef &str_ref) {
140 return str_ref.contains("$_") || str_ref.contains("'lambda'");
141}
142
144line_entry_helper(Target &target, const SymbolContext &sc, Symbol *symbol,
145 llvm::StringRef first_template_param_sref, bool has_invoke) {
146
148
149 Address address = sc.GetFunctionOrSymbolAddress();
150
151 Address addr;
152 if (target.ResolveLoadAddress(address.GetCallableLoadAddress(&target),
153 addr)) {
154 LineEntry line_entry;
155 addr.CalculateSymbolContextLineEntry(line_entry);
156
157 if (contains_lambda_identifier(first_template_param_sref) || has_invoke) {
158 // Case 1 and 2
159 optional_info.callable_case = lldb_private::CPPLanguageRuntime::
160 LibCppStdFunctionCallableCase::Lambda;
161 } else {
162 // Case 3
163 optional_info.callable_case = lldb_private::CPPLanguageRuntime::
164 LibCppStdFunctionCallableCase::CallableObject;
165 }
166
167 optional_info.callable_symbol = *symbol;
168 optional_info.callable_line_entry = line_entry;
169 optional_info.callable_address = addr;
170 }
171
172 return optional_info;
173}
174
177 lldb::ValueObjectSP &valobj_sp) {
179
180 LibCppStdFunctionCallableInfo optional_info;
181
182 if (!valobj_sp)
183 return optional_info;
184
185 // Member __f_ has type __base*, the contents of which will hold:
186 // 1) a vtable entry which may hold type information needed to discover the
187 // lambda being called
188 // 2) possibly hold a pointer to the callable object
189 // e.g.
190 //
191 // (lldb) frame var -R f_display
192 // (std::__1::function<void (int)>) f_display = {
193 // __buf_ = {
194 // …
195 // }
196 // __f_ = 0x00007ffeefbffa00
197 // }
198 // (lldb) memory read -fA 0x00007ffeefbffa00
199 // 0x7ffeefbffa00: ... `vtable for std::__1::__function::__func<void (*) ...
200 // 0x7ffeefbffa08: ... `print_num(int) at std_function_cppreference_exam ...
201 //
202 // We will be handling five cases below, std::function is wrapping:
203 //
204 // 1) a lambda we know at compile time. We will obtain the name of the lambda
205 // from the first template pameter from __func's vtable. We will look up
206 // the lambda's operator()() and obtain the line table entry.
207 // 2) a lambda we know at runtime. A pointer to the lambdas __invoke method
208 // will be stored after the vtable. We will obtain the lambdas name from
209 // this entry and lookup operator()() and obtain the line table entry.
210 // 3) a callable object via operator()(). We will obtain the name of the
211 // object from the first template parameter from __func's vtable. We will
212 // look up the objects operator()() and obtain the line table entry.
213 // 4) a member function. A pointer to the function will stored after the
214 // we will obtain the name from this pointer.
215 // 5) a free function. A pointer to the function will stored after the vtable
216 // we will obtain the name from this pointer.
217 ValueObjectSP member_f_(valobj_sp->GetChildMemberWithName("__f_"));
218
219 if (member_f_) {
220 ValueObjectSP sub_member_f_(member_f_->GetChildMemberWithName("__f_"));
221
222 if (sub_member_f_)
223 member_f_ = sub_member_f_;
224 }
225
226 if (!member_f_)
227 return optional_info;
228
229 lldb::addr_t member_f_pointer_value = member_f_->GetValueAsUnsigned(0);
230
231 optional_info.member_f_pointer_value = member_f_pointer_value;
232
233 if (!member_f_pointer_value)
234 return optional_info;
235
236 ExecutionContext exe_ctx(valobj_sp->GetExecutionContextRef());
237 Process *process = exe_ctx.GetProcessPtr();
238
239 if (process == nullptr)
240 return optional_info;
241
242 uint32_t address_size = process->GetAddressByteSize();
243 Status status;
244
245 // First item pointed to by __f_ should be the pointer to the vtable for
246 // a __base object.
247 lldb::addr_t vtable_address =
248 process->ReadPointerFromMemory(member_f_pointer_value, status);
249
250 if (status.Fail())
251 return optional_info;
252
253 lldb::addr_t vtable_address_first_entry =
254 process->ReadPointerFromMemory(vtable_address + address_size, status);
255
256 if (status.Fail())
257 return optional_info;
258
259 lldb::addr_t address_after_vtable = member_f_pointer_value + address_size;
260 // As commented above we may not have a function pointer but if we do we will
261 // need it.
262 lldb::addr_t possible_function_address =
263 process->ReadPointerFromMemory(address_after_vtable, status);
264
265 if (status.Fail())
266 return optional_info;
267
268 Target &target = process->GetTarget();
269
270 if (!target.HasLoadedSections())
271 return optional_info;
272
273 Address vtable_first_entry_resolved;
274
275 if (!target.ResolveLoadAddress(vtable_address_first_entry,
276 vtable_first_entry_resolved))
277 return optional_info;
278
279 Address vtable_addr_resolved;
280 SymbolContext sc;
281 Symbol *symbol = nullptr;
282
283 if (!target.ResolveLoadAddress(vtable_address, vtable_addr_resolved))
284 return optional_info;
285
287 vtable_addr_resolved, eSymbolContextEverything, sc);
288 symbol = sc.symbol;
289
290 if (symbol == nullptr)
291 return optional_info;
292
293 llvm::StringRef vtable_name(symbol->GetName().GetStringRef());
294 bool found_expected_start_string =
295 vtable_name.starts_with("vtable for std::__1::__function::__func<");
296
297 if (!found_expected_start_string)
298 return optional_info;
299
300 // Given case 1 or 3 we have a vtable name, we are want to extract the first
301 // template parameter
302 //
303 // ... __func<main::$_0, std::__1::allocator<main::$_0> ...
304 // ^^^^^^^^^
305 //
306 // We could see names such as:
307 // main::$_0
308 // Bar::add_num2(int)::'lambda'(int)
309 // Bar
310 //
311 // We do this by find the first < and , and extracting in between.
312 //
313 // This covers the case of the lambda known at compile time.
314 size_t first_open_angle_bracket = vtable_name.find('<') + 1;
315 size_t first_comma = vtable_name.find(',');
316
317 llvm::StringRef first_template_parameter =
318 vtable_name.slice(first_open_angle_bracket, first_comma);
319
320 Address function_address_resolved;
321
322 // Setup for cases 2, 4 and 5 we have a pointer to a function after the
323 // vtable. We will use a process of elimination to drop through each case
324 // and obtain the data we need.
325 if (target.ResolveLoadAddress(possible_function_address,
326 function_address_resolved)) {
328 function_address_resolved, eSymbolContextEverything, sc);
329 symbol = sc.symbol;
330 }
331
332 // These conditions are used several times to simplify statements later on.
333 bool has_invoke =
334 (symbol ? symbol->GetName().GetStringRef().contains("__invoke") : false);
335 auto calculate_symbol_context_helper = [](auto &t,
336 SymbolContextList &sc_list) {
337 SymbolContext sc;
338 t->CalculateSymbolContext(&sc);
339 sc_list.Append(sc);
340 };
341
342 // Case 2
343 if (has_invoke) {
345 calculate_symbol_context_helper(symbol, scl);
346
347 return line_entry_helper(target, scl[0], symbol, first_template_parameter,
348 has_invoke);
349 }
350
351 // Case 4 or 5
352 if (symbol && !symbol->GetName().GetStringRef().starts_with("vtable for") &&
353 !contains_lambda_identifier(first_template_parameter) && !has_invoke) {
354 optional_info.callable_case =
356 optional_info.callable_address = function_address_resolved;
357 optional_info.callable_symbol = *symbol;
358
359 return optional_info;
360 }
361
362 std::string func_to_match = first_template_parameter.str();
363
364 auto it = CallableLookupCache.find(func_to_match);
365 if (it != CallableLookupCache.end())
366 return it->second;
367
369
370 CompileUnit *vtable_cu =
371 vtable_first_entry_resolved.CalculateSymbolContextCompileUnit();
372 llvm::StringRef name_to_use = func_to_match;
373
374 // Case 3, we have a callable object instead of a lambda
375 //
376 // TODO
377 // We currently don't support this case a callable object may have multiple
378 // operator()() varying on const/non-const and number of arguments and we
379 // don't have a way to currently distinguish them so we will bail out now.
380 if (!contains_lambda_identifier(name_to_use))
381 return optional_info;
382
383 if (vtable_cu && !has_invoke) {
384 lldb::FunctionSP func_sp =
385 vtable_cu->FindFunction([name_to_use](const FunctionSP &f) {
386 auto name = f->GetName().GetStringRef();
387 if (name.starts_with(name_to_use) && name.contains("operator"))
388 return true;
389
390 return false;
391 });
392
393 if (func_sp) {
394 calculate_symbol_context_helper(func_sp, scl);
395 }
396 }
397
398 if (symbol == nullptr)
399 return optional_info;
400
401 // Case 1 or 3
402 if (scl.GetSize() >= 1) {
403 optional_info = line_entry_helper(target, scl[0], symbol,
404 first_template_parameter, has_invoke);
405 }
406
407 CallableLookupCache[func_to_match] = optional_info;
408
409 return optional_info;
410}
411
414 bool stop_others) {
415 ThreadPlanSP ret_plan_sp;
416
417 lldb::addr_t curr_pc = thread.GetRegisterContext()->GetPC();
418
419 TargetSP target_sp(thread.CalculateTarget());
420
421 if (!target_sp->HasLoadedSections())
422 return ret_plan_sp;
423
424 Address pc_addr_resolved;
425 SymbolContext sc;
426 Symbol *symbol;
427
428 if (!target_sp->ResolveLoadAddress(curr_pc, pc_addr_resolved))
429 return ret_plan_sp;
430
431 target_sp->GetImages().ResolveSymbolContextForAddress(
432 pc_addr_resolved, eSymbolContextEverything, sc);
433 symbol = sc.symbol;
434
435 if (symbol == nullptr)
436 return ret_plan_sp;
437
438 llvm::StringRef function_name(symbol->GetName().GetCString());
439
440 // Handling the case where we are attempting to step into std::function.
441 // The behavior will be that we will attempt to obtain the wrapped
442 // callable via FindLibCppStdFunctionCallableInfo() and if we find it we
443 // will return a ThreadPlanRunToAddress to the callable. Therefore we will
444 // step into the wrapped callable.
445 //
446 bool found_expected_start_string =
447 function_name.starts_with("std::__1::function<");
448
449 if (!found_expected_start_string)
450 return ret_plan_sp;
451
452 AddressRange range_of_curr_func;
453 sc.GetAddressRange(eSymbolContextEverything, 0, false, range_of_curr_func);
454
455 StackFrameSP frame = thread.GetStackFrameAtIndex(0);
456
457 if (frame) {
458 ValueObjectSP value_sp = frame->FindVariable(g_this);
459
462
464 value_sp->GetValueIsValid()) {
465 // We found the std::function wrapped callable and we have its address.
466 // We now create a ThreadPlan to run to the callable.
467 ret_plan_sp = std::make_shared<ThreadPlanRunToAddress>(
468 thread, callable_info.callable_address, stop_others);
469 return ret_plan_sp;
470 } else {
471 // We are in std::function but we could not obtain the callable.
472 // We create a ThreadPlan to keep stepping through using the address range
473 // of the current function.
474 ret_plan_sp = std::make_shared<ThreadPlanStepInRange>(
475 thread, range_of_curr_func, sc, nullptr, eOnlyThisThread,
477 return ret_plan_sp;
478 }
479 }
480
481 return ret_plan_sp;
482}
483
485 llvm::StringRef mangled_name =
487 // Virtual function overriding from a non-virtual base use a "Th" prefix.
488 // Virtual function overriding from a virtual base must use a "Tv" prefix.
489 // Virtual function overriding thunks with covariant returns use a "Tc"
490 // prefix.
491 return mangled_name.starts_with("_ZTh") || mangled_name.starts_with("_ZTv") ||
492 mangled_name.starts_with("_ZTc");
493}
static ConstString g_promise
static ConstString g_coro_frame
bool contains_lambda_identifier(llvm::StringRef &str_ref)
static ConstString g_this
CPPLanguageRuntime::LibCppStdFunctionCallableInfo line_entry_helper(Target &target, const SymbolContext &sc, Symbol *symbol, llvm::StringRef first_template_param_sref, bool has_invoke)
#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 GetCallableLoadAddress(Target *target, bool is_indirect=false) const
Get the load address as a callable code load address.
Definition Address.cpp:326
bool CalculateSymbolContextLineEntry(LineEntry &line_entry) const
Definition Address.cpp:902
CompileUnit * CalculateSymbolContextCompileUnit() const
Definition Address.cpp:846
llvm::Error GetObjectDescription(Stream &str, ValueObject &object) override
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.
OperatorStringToCallableInfoMap CallableLookupCache
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.
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.
"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.
@ ePreferDemangledWithoutArguments
Definition Mangled.h:39
ConstString GetMangledName() const
Mangled name get accessor.
Definition Mangled.h:152
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&)
A plug-in interface definition class for debugging a process.
Definition Process.h:354
lldb::addr_t ReadPointerFromMemory(lldb::addr_t vm_addr, Status &error)
Definition Process.cpp:2301
uint32_t GetAddressByteSize() const
Definition Process.cpp:3662
Target & GetTarget()
Get the target object pointer for this module.
Definition Process.h:1267
This class provides extra information about a stack frame that was provided by a specific stack frame...
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:294
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.
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:147
ConstString GetName() const
Definition Symbol.cpp:511
bool ResolveLoadAddress(lldb::addr_t load_addr, Address &so_addr, uint32_t stop_id=SectionLoadHistory::eStopIDNow, bool allow_section_end=false)
Definition Target.cpp:3320
StackFrameRecognizerManager & GetFrameRecognizerManager()
Definition Target.h:1600
const ModuleList & GetImages() const
Get accessor for the images for this process.
Definition Target.h:1039
A class that represents a running process on the host machine.
void RegisterVerboseTrapFrameRecognizer(Process &process)
std::shared_ptr< lldb_private::Function > FunctionSP
std::shared_ptr< lldb_private::ThreadPlan > ThreadPlanSP
std::shared_ptr< lldb_private::StackFrame > StackFrameSP
std::shared_ptr< lldb_private::RecognizedStackFrame > RecognizedStackFrameSP
std::shared_ptr< lldb_private::Thread > ThreadSP
std::shared_ptr< lldb_private::ValueObject > ValueObjectSP
std::shared_ptr< lldb_private::StackFrameRecognizer > StackFrameRecognizerSP
uint64_t addr_t
Definition lldb-types.h:80
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