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"
15
16#include "llvm/ADT/StringRef.h"
17
18#include "lldb/Symbol/Block.h"
21
25#include "lldb/Target/ABI.h"
33#include "lldb/Utility/Timer.h"
34
35using namespace lldb;
36using namespace lldb_private;
37
39// Artificial coroutine-related variables emitted by clang.
40static ConstString g_promise = ConstString("__promise");
41static ConstString g_coro_frame = ConstString("__coro_frame");
42
44
45/// A frame recognizer that is installed to hide libc++ implementation
46/// details from the backtrace.
48 std::array<RegularExpression, 2> m_hidden_regex;
50
52 bool ShouldHide() override { return true; }
53 };
54
55public:
58 // internal implementation details in the `std::` namespace
59 // std::__1::__function::__alloc_func<void (*)(), std::__1::allocator<void (*)()>, void ()>::operator()[abi:ne200000]
60 // std::__1::__function::__func<void (*)(), std::__1::allocator<void (*)()>, void ()>::operator()
61 // std::__1::__function::__value_func<void ()>::operator()[abi:ne200000]() const
62 // std::__2::__function::__policy_invoker<void (int, int)>::__call_impl[abi:ne200000]<std::__2::__function::__default_alloc_func<int (*)(int, int), int (int, int)>>
63 // std::__1::__invoke[abi:ne200000]<void (*&)()>
64 // std::__1::__invoke_void_return_wrapper<void, true>::__call[abi:ne200000]<void (*&)()>
65 RegularExpression{R"(^std::__[^:]*::__)"},
66 // internal implementation details in the `std::ranges` namespace
67 // 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>
68 RegularExpression{R"(^std::__[^:]*::ranges::__)"},
69 },
71
72 std::string GetName() override { return "libc++ frame recognizer"; }
73
76 if (!frame_sp)
77 return {};
78 const auto &sc = frame_sp->GetSymbolContext(lldb::eSymbolContextFunction);
79 if (!sc.function)
80 return {};
81
82 // Check if we have a regex match
84 if (!r.Execute(sc.function->GetNameNoArguments()))
85 continue;
86
87 // Only hide this frame if the immediate caller is also within libc++.
88 lldb::ThreadSP thread_sp = frame_sp->GetThread();
89 if (!thread_sp)
90 return {};
91 lldb::StackFrameSP parent_frame_sp =
92 thread_sp->GetStackFrameAtIndex(frame_sp->GetFrameIndex() + 1);
93 if (!parent_frame_sp)
94 return {};
95 const auto &parent_sc =
96 parent_frame_sp->GetSymbolContext(lldb::eSymbolContextFunction);
97 if (!parent_sc.function)
98 return {};
99 if (parent_sc.function->GetNameNoArguments().GetStringRef().starts_with(
100 "std::"))
101 return m_hidden_frame;
102 }
103
104 return {};
105 }
106};
107
109 : LanguageRuntime(process) {
110 if (process)
113 std::make_shared<RegularExpression>("^std::__[^:]*::"),
114 /*mangling_preference=*/Mangled::ePreferDemangledWithoutArguments,
115 /*first_instruction_only=*/false);
116}
117
119 return name == g_this || name == g_promise || name == g_coro_frame;
120}
121
123 ValueObject &object) {
124 // C++ has no generic way to do this.
125 return llvm::createStringError("C++ does not support object descriptions");
126}
127
128llvm::Error
130 ExecutionContextScope *exe_scope) {
131 // C++ has no generic way to do this.
132 return llvm::createStringError("C++ does not support object descriptions");
133}
134
135bool contains_lambda_identifier(llvm::StringRef &str_ref) {
136 return str_ref.contains("$_") || str_ref.contains("'lambda'");
137}
138
140line_entry_helper(Target &target, const SymbolContext &sc, Symbol *symbol,
141 llvm::StringRef first_template_param_sref, bool has_invoke) {
142
144
145 AddressRange range;
146 sc.GetAddressRange(eSymbolContextEverything, 0, false, range);
147
148 Address address = range.GetBaseAddress();
149
150 Address addr;
151 if (target.ResolveLoadAddress(address.GetCallableLoadAddress(&target),
152 addr)) {
153 LineEntry line_entry;
154 addr.CalculateSymbolContextLineEntry(line_entry);
155
156 if (contains_lambda_identifier(first_template_param_sref) || has_invoke) {
157 // Case 1 and 2
160 } else {
161 // Case 3
164 }
165
166 optional_info.callable_symbol = *symbol;
167 optional_info.callable_line_entry = line_entry;
168 optional_info.callable_address = addr;
169 }
170
171 return optional_info;
172}
173
176 lldb::ValueObjectSP &valobj_sp) {
178
179 LibCppStdFunctionCallableInfo optional_info;
180
181 if (!valobj_sp)
182 return optional_info;
183
184 // Member __f_ has type __base*, the contents of which will hold:
185 // 1) a vtable entry which may hold type information needed to discover the
186 // lambda being called
187 // 2) possibly hold a pointer to the callable object
188 // e.g.
189 //
190 // (lldb) frame var -R f_display
191 // (std::__1::function<void (int)>) f_display = {
192 // __buf_ = {
193 // …
194 // }
195 // __f_ = 0x00007ffeefbffa00
196 // }
197 // (lldb) memory read -fA 0x00007ffeefbffa00
198 // 0x7ffeefbffa00: ... `vtable for std::__1::__function::__func<void (*) ...
199 // 0x7ffeefbffa08: ... `print_num(int) at std_function_cppreference_exam ...
200 //
201 // We will be handling five cases below, std::function is wrapping:
202 //
203 // 1) a lambda we know at compile time. We will obtain the name of the lambda
204 // from the first template pameter from __func's vtable. We will look up
205 // the lambda's operator()() and obtain the line table entry.
206 // 2) a lambda we know at runtime. A pointer to the lambdas __invoke method
207 // will be stored after the vtable. We will obtain the lambdas name from
208 // this entry and lookup operator()() and obtain the line table entry.
209 // 3) a callable object via operator()(). We will obtain the name of the
210 // object from the first template parameter from __func's vtable. We will
211 // look up the objects operator()() and obtain the line table entry.
212 // 4) a member function. A pointer to the function will stored after the
213 // we will obtain the name from this pointer.
214 // 5) a free function. A pointer to the function will stored after the vtable
215 // we will obtain the name from this pointer.
216 ValueObjectSP member_f_(valobj_sp->GetChildMemberWithName("__f_"));
217
218 if (member_f_) {
219 ValueObjectSP sub_member_f_(member_f_->GetChildMemberWithName("__f_"));
220
221 if (sub_member_f_)
222 member_f_ = sub_member_f_;
223 }
224
225 if (!member_f_)
226 return optional_info;
227
228 lldb::addr_t member_f_pointer_value = member_f_->GetValueAsUnsigned(0);
229
230 optional_info.member_f_pointer_value = member_f_pointer_value;
231
232 if (!member_f_pointer_value)
233 return optional_info;
234
235 ExecutionContext exe_ctx(valobj_sp->GetExecutionContextRef());
236 Process *process = exe_ctx.GetProcessPtr();
237
238 if (process == nullptr)
239 return optional_info;
240
241 uint32_t address_size = process->GetAddressByteSize();
242 Status status;
243
244 // First item pointed to by __f_ should be the pointer to the vtable for
245 // a __base object.
246 lldb::addr_t vtable_address =
247 process->ReadPointerFromMemory(member_f_pointer_value, status);
248
249 if (status.Fail())
250 return optional_info;
251
252 lldb::addr_t vtable_address_first_entry =
253 process->ReadPointerFromMemory(vtable_address + address_size, status);
254
255 if (status.Fail())
256 return optional_info;
257
258 lldb::addr_t address_after_vtable = member_f_pointer_value + address_size;
259 // As commented above we may not have a function pointer but if we do we will
260 // need it.
261 lldb::addr_t possible_function_address =
262 process->ReadPointerFromMemory(address_after_vtable, status);
263
264 if (status.Fail())
265 return optional_info;
266
267 Target &target = process->GetTarget();
268
269 if (target.GetSectionLoadList().IsEmpty())
270 return optional_info;
271
272 Address vtable_first_entry_resolved;
273
275 vtable_address_first_entry, vtable_first_entry_resolved))
276 return optional_info;
277
278 Address vtable_addr_resolved;
279 SymbolContext sc;
280 Symbol *symbol = nullptr;
281
282 if (!target.GetSectionLoadList().ResolveLoadAddress(vtable_address,
283 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.
326 possible_function_address, 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->GetSectionLoadList().IsEmpty())
422 return ret_plan_sp;
423
424 Address pc_addr_resolved;
425 SymbolContext sc;
426 Symbol *symbol;
427
428 if (!target_sp->GetSectionLoadList().ResolveLoadAddress(curr_pc,
429 pc_addr_resolved))
430 return ret_plan_sp;
431
432 target_sp->GetImages().ResolveSymbolContextForAddress(
433 pc_addr_resolved, eSymbolContextEverything, sc);
434 symbol = sc.symbol;
435
436 if (symbol == nullptr)
437 return ret_plan_sp;
438
439 llvm::StringRef function_name(symbol->GetName().GetCString());
440
441 // Handling the case where we are attempting to step into std::function.
442 // The behavior will be that we will attempt to obtain the wrapped
443 // callable via FindLibCppStdFunctionCallableInfo() and if we find it we
444 // will return a ThreadPlanRunToAddress to the callable. Therefore we will
445 // step into the wrapped callable.
446 //
447 bool found_expected_start_string =
448 function_name.starts_with("std::__1::function<");
449
450 if (!found_expected_start_string)
451 return ret_plan_sp;
452
453 AddressRange range_of_curr_func;
454 sc.GetAddressRange(eSymbolContextEverything, 0, false, range_of_curr_func);
455
456 StackFrameSP frame = thread.GetStackFrameAtIndex(0);
457
458 if (frame) {
459 ValueObjectSP value_sp = frame->FindVariable(g_this);
460
463
465 value_sp->GetValueIsValid()) {
466 // We found the std::function wrapped callable and we have its address.
467 // We now create a ThreadPlan to run to the callable.
468 ret_plan_sp = std::make_shared<ThreadPlanRunToAddress>(
469 thread, callable_info.callable_address, stop_others);
470 return ret_plan_sp;
471 } else {
472 // We are in std::function but we could not obtain the callable.
473 // We create a ThreadPlan to keep stepping through using the address range
474 // of the current function.
475 ret_plan_sp = std::make_shared<ThreadPlanStepInRange>(
476 thread, range_of_curr_func, sc, nullptr, eOnlyThisThread,
478 return ret_plan_sp;
479 }
480 }
481
482 return ret_plan_sp;
483}
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.
Definition: AddressRange.h:25
Address & GetBaseAddress()
Get accessor for the base address of the range.
Definition: AddressRange.h:211
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:338
bool CalculateSymbolContextLineEntry(LineEntry &line_entry) const
Definition: Address.cpp:914
CompileUnit * CalculateSymbolContextCompileUnit() const
Definition: Address.cpp:858
llvm::Error GetObjectDescription(Stream &str, ValueObject &object) 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.
Definition: CompileUnit.cpp:81
A uniqued constant string class.
Definition: ConstString.h:40
llvm::StringRef GetStringRef() const
Get the string value as a llvm::StringRef.
Definition: ConstString.h:197
const char * GetCString() const
Get the string value as a C string.
Definition: ConstString.h:216
"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:38
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&)
Definition: ModuleList.cpp:682
A plug-in interface definition class for debugging a process.
Definition: Process.h:343
lldb::addr_t ReadPointerFromMemory(lldb::addr_t vm_addr, Status &error)
Definition: Process.cpp:2239
uint32_t GetAddressByteSize() const
Definition: Process.cpp:3615
Target & GetTarget()
Get the target object pointer for this module.
Definition: Process.h:1246
This class provides extra information about a stack frame that was provided by a specific stack frame...
bool ResolveLoadAddress(lldb::addr_t load_addr, Address &so_addr, bool allow_section_end=false) const
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:115
bool Fail() const
Test for error condition.
Definition: Status.cpp:270
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.
Definition: SymbolContext.h:34
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.
ConstString GetName() const
Definition: Symbol.cpp:548
SectionLoadList & GetSectionLoadList()
Definition: Target.h:1154
StackFrameRecognizerManager & GetFrameRecognizerManager()
Definition: Target.h:1487
bool ResolveLoadAddress(lldb::addr_t load_addr, Address &so_addr, uint32_t stop_id=SectionLoadHistory::eStopIDNow)
Definition: Target.cpp:3219
const ModuleList & GetImages() const
Get accessor for the images for this process.
Definition: Target.h:997
virtual lldb::StackFrameSP GetStackFrameAtIndex(uint32_t idx)
Definition: Thread.h:408
virtual lldb::RegisterContextSP GetRegisterContext()=0
lldb::TargetSP CalculateTarget() override
Definition: Thread.cpp:1408
A class that represents a running process on the host machine.
Definition: SBAddress.h:15
std::shared_ptr< lldb_private::Function > FunctionSP
Definition: lldb-forward.h:355
std::shared_ptr< lldb_private::ThreadPlan > ThreadPlanSP
Definition: lldb-forward.h:453
std::shared_ptr< lldb_private::StackFrame > StackFrameSP
Definition: lldb-forward.h:424
std::shared_ptr< lldb_private::RecognizedStackFrame > RecognizedStackFrameSP
Definition: lldb-forward.h:403
std::shared_ptr< lldb_private::Thread > ThreadSP
Definition: lldb-forward.h:450
std::shared_ptr< lldb_private::ValueObject > ValueObjectSP
Definition: lldb-forward.h:484
std::shared_ptr< lldb_private::StackFrameRecognizer > StackFrameRecognizerSP
Definition: lldb-forward.h:428
uint64_t addr_t
Definition: lldb-types.h:80
std::shared_ptr< lldb_private::Target > TargetSP
Definition: lldb-forward.h:448
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