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
11#include <memory>
12
13#include "CPPLanguageRuntime.h"
14
15#include "llvm/ADT/StringRef.h"
16
17#include "lldb/Symbol/Block.h"
20
24#include "lldb/Target/ABI.h"
32#include "lldb/Utility/Timer.h"
33
34using namespace lldb;
35using namespace lldb_private;
36
38// Artificial coroutine-related variables emitted by clang.
39static ConstString g_promise = ConstString("__promise");
40static ConstString g_coro_frame = ConstString("__coro_frame");
41
43
44/// A frame recognizer that is installed to hide libc++ implementation
45/// details from the backtrace.
49
51 bool ShouldHide() override { return true; }
52 };
53
54public:
57 R"(^std::__1::(__function.*::operator\‍(\)|__invoke))"
58 R"((\[.*\])?)" // ABI tag.
59 R"(( const)?$)"), // const.
61
62 std::string GetName() override { return "libc++ frame recognizer"; }
63
66 if (!frame_sp)
67 return {};
68 const auto &sc = frame_sp->GetSymbolContext(lldb::eSymbolContextFunction);
69 if (!sc.function)
70 return {};
71
72 if (m_hidden_function_regex.Execute(sc.function->GetNameNoArguments()))
73 return m_hidden_frame;
74
75 return {};
76 }
77};
78
80 : LanguageRuntime(process) {
81 if (process)
84 std::make_shared<RegularExpression>("^std::__1::"),
85 /*first_instruction_only*/ false);
86}
87
89 return name == g_this || name == g_promise || name == g_coro_frame;
90}
91
93 ValueObject &object) {
94 // C++ has no generic way to do this.
95 return llvm::createStringError("C++ does not support object descriptions");
96}
97
98llvm::Error
100 ExecutionContextScope *exe_scope) {
101 // C++ has no generic way to do this.
102 return llvm::createStringError("C++ does not support object descriptions");
103}
104
105bool contains_lambda_identifier(llvm::StringRef &str_ref) {
106 return str_ref.contains("$_") || str_ref.contains("'lambda'");
107}
108
110line_entry_helper(Target &target, const SymbolContext &sc, Symbol *symbol,
111 llvm::StringRef first_template_param_sref,
112 bool has_invoke) {
113
115
116 AddressRange range;
117 sc.GetAddressRange(eSymbolContextEverything, 0, false, range);
118
119 Address address = range.GetBaseAddress();
120
121 Address addr;
122 if (target.ResolveLoadAddress(address.GetCallableLoadAddress(&target),
123 addr)) {
124 LineEntry line_entry;
125 addr.CalculateSymbolContextLineEntry(line_entry);
126
127 if (contains_lambda_identifier(first_template_param_sref) || has_invoke) {
128 // Case 1 and 2
131 } else {
132 // Case 3
135 }
136
137 optional_info.callable_symbol = *symbol;
138 optional_info.callable_line_entry = line_entry;
139 optional_info.callable_address = addr;
140 }
141
142 return optional_info;
143}
144
147 lldb::ValueObjectSP &valobj_sp) {
149
150 LibCppStdFunctionCallableInfo optional_info;
151
152 if (!valobj_sp)
153 return optional_info;
154
155 // Member __f_ has type __base*, the contents of which will hold:
156 // 1) a vtable entry which may hold type information needed to discover the
157 // lambda being called
158 // 2) possibly hold a pointer to the callable object
159 // e.g.
160 //
161 // (lldb) frame var -R f_display
162 // (std::__1::function<void (int)>) f_display = {
163 // __buf_ = {
164 // …
165 // }
166 // __f_ = 0x00007ffeefbffa00
167 // }
168 // (lldb) memory read -fA 0x00007ffeefbffa00
169 // 0x7ffeefbffa00: ... `vtable for std::__1::__function::__func<void (*) ...
170 // 0x7ffeefbffa08: ... `print_num(int) at std_function_cppreference_exam ...
171 //
172 // We will be handling five cases below, std::function is wrapping:
173 //
174 // 1) a lambda we know at compile time. We will obtain the name of the lambda
175 // from the first template pameter from __func's vtable. We will look up
176 // the lambda's operator()() and obtain the line table entry.
177 // 2) a lambda we know at runtime. A pointer to the lambdas __invoke method
178 // will be stored after the vtable. We will obtain the lambdas name from
179 // this entry and lookup operator()() and obtain the line table entry.
180 // 3) a callable object via operator()(). We will obtain the name of the
181 // object from the first template parameter from __func's vtable. We will
182 // look up the objects operator()() and obtain the line table entry.
183 // 4) a member function. A pointer to the function will stored after the
184 // we will obtain the name from this pointer.
185 // 5) a free function. A pointer to the function will stored after the vtable
186 // we will obtain the name from this pointer.
187 ValueObjectSP member_f_(valobj_sp->GetChildMemberWithName("__f_"));
188
189 if (member_f_) {
190 ValueObjectSP sub_member_f_(member_f_->GetChildMemberWithName("__f_"));
191
192 if (sub_member_f_)
193 member_f_ = sub_member_f_;
194 }
195
196 if (!member_f_)
197 return optional_info;
198
199 lldb::addr_t member_f_pointer_value = member_f_->GetValueAsUnsigned(0);
200
201 optional_info.member_f_pointer_value = member_f_pointer_value;
202
203 if (!member_f_pointer_value)
204 return optional_info;
205
206 ExecutionContext exe_ctx(valobj_sp->GetExecutionContextRef());
207 Process *process = exe_ctx.GetProcessPtr();
208
209 if (process == nullptr)
210 return optional_info;
211
212 uint32_t address_size = process->GetAddressByteSize();
213 Status status;
214
215 // First item pointed to by __f_ should be the pointer to the vtable for
216 // a __base object.
217 lldb::addr_t vtable_address =
218 process->ReadPointerFromMemory(member_f_pointer_value, status);
219
220 if (status.Fail())
221 return optional_info;
222
223 lldb::addr_t vtable_address_first_entry =
224 process->ReadPointerFromMemory(vtable_address + address_size, status);
225
226 if (status.Fail())
227 return optional_info;
228
229 lldb::addr_t address_after_vtable = member_f_pointer_value + address_size;
230 // As commented above we may not have a function pointer but if we do we will
231 // need it.
232 lldb::addr_t possible_function_address =
233 process->ReadPointerFromMemory(address_after_vtable, status);
234
235 if (status.Fail())
236 return optional_info;
237
238 Target &target = process->GetTarget();
239
240 if (target.GetSectionLoadList().IsEmpty())
241 return optional_info;
242
243 Address vtable_first_entry_resolved;
244
246 vtable_address_first_entry, vtable_first_entry_resolved))
247 return optional_info;
248
249 Address vtable_addr_resolved;
250 SymbolContext sc;
251 Symbol *symbol = nullptr;
252
253 if (!target.GetSectionLoadList().ResolveLoadAddress(vtable_address,
254 vtable_addr_resolved))
255 return optional_info;
256
258 vtable_addr_resolved, eSymbolContextEverything, sc);
259 symbol = sc.symbol;
260
261 if (symbol == nullptr)
262 return optional_info;
263
264 llvm::StringRef vtable_name(symbol->GetName().GetStringRef());
265 bool found_expected_start_string =
266 vtable_name.starts_with("vtable for std::__1::__function::__func<");
267
268 if (!found_expected_start_string)
269 return optional_info;
270
271 // Given case 1 or 3 we have a vtable name, we are want to extract the first
272 // template parameter
273 //
274 // ... __func<main::$_0, std::__1::allocator<main::$_0> ...
275 // ^^^^^^^^^
276 //
277 // We could see names such as:
278 // main::$_0
279 // Bar::add_num2(int)::'lambda'(int)
280 // Bar
281 //
282 // We do this by find the first < and , and extracting in between.
283 //
284 // This covers the case of the lambda known at compile time.
285 size_t first_open_angle_bracket = vtable_name.find('<') + 1;
286 size_t first_comma = vtable_name.find(',');
287
288 llvm::StringRef first_template_parameter =
289 vtable_name.slice(first_open_angle_bracket, first_comma);
290
291 Address function_address_resolved;
292
293 // Setup for cases 2, 4 and 5 we have a pointer to a function after the
294 // vtable. We will use a process of elimination to drop through each case
295 // and obtain the data we need.
297 possible_function_address, function_address_resolved)) {
299 function_address_resolved, eSymbolContextEverything, sc);
300 symbol = sc.symbol;
301 }
302
303 // These conditions are used several times to simplify statements later on.
304 bool has_invoke =
305 (symbol ? symbol->GetName().GetStringRef().contains("__invoke") : false);
306 auto calculate_symbol_context_helper = [](auto &t,
307 SymbolContextList &sc_list) {
308 SymbolContext sc;
309 t->CalculateSymbolContext(&sc);
310 sc_list.Append(sc);
311 };
312
313 // Case 2
314 if (has_invoke) {
316 calculate_symbol_context_helper(symbol, scl);
317
318 return line_entry_helper(target, scl[0], symbol, first_template_parameter,
319 has_invoke);
320 }
321
322 // Case 4 or 5
323 if (symbol && !symbol->GetName().GetStringRef().starts_with("vtable for") &&
324 !contains_lambda_identifier(first_template_parameter) && !has_invoke) {
325 optional_info.callable_case =
327 optional_info.callable_address = function_address_resolved;
328 optional_info.callable_symbol = *symbol;
329
330 return optional_info;
331 }
332
333 std::string func_to_match = first_template_parameter.str();
334
335 auto it = CallableLookupCache.find(func_to_match);
336 if (it != CallableLookupCache.end())
337 return it->second;
338
340
341 CompileUnit *vtable_cu =
342 vtable_first_entry_resolved.CalculateSymbolContextCompileUnit();
343 llvm::StringRef name_to_use = func_to_match;
344
345 // Case 3, we have a callable object instead of a lambda
346 //
347 // TODO
348 // We currently don't support this case a callable object may have multiple
349 // operator()() varying on const/non-const and number of arguments and we
350 // don't have a way to currently distinguish them so we will bail out now.
351 if (!contains_lambda_identifier(name_to_use))
352 return optional_info;
353
354 if (vtable_cu && !has_invoke) {
355 lldb::FunctionSP func_sp =
356 vtable_cu->FindFunction([name_to_use](const FunctionSP &f) {
357 auto name = f->GetName().GetStringRef();
358 if (name.starts_with(name_to_use) && name.contains("operator"))
359 return true;
360
361 return false;
362 });
363
364 if (func_sp) {
365 calculate_symbol_context_helper(func_sp, scl);
366 }
367 }
368
369 if (symbol == nullptr)
370 return optional_info;
371
372 // Case 1 or 3
373 if (scl.GetSize() >= 1) {
374 optional_info = line_entry_helper(target, scl[0], symbol,
375 first_template_parameter, has_invoke);
376 }
377
378 CallableLookupCache[func_to_match] = optional_info;
379
380 return optional_info;
381}
382
385 bool stop_others) {
386 ThreadPlanSP ret_plan_sp;
387
388 lldb::addr_t curr_pc = thread.GetRegisterContext()->GetPC();
389
390 TargetSP target_sp(thread.CalculateTarget());
391
392 if (target_sp->GetSectionLoadList().IsEmpty())
393 return ret_plan_sp;
394
395 Address pc_addr_resolved;
396 SymbolContext sc;
397 Symbol *symbol;
398
399 if (!target_sp->GetSectionLoadList().ResolveLoadAddress(curr_pc,
400 pc_addr_resolved))
401 return ret_plan_sp;
402
403 target_sp->GetImages().ResolveSymbolContextForAddress(
404 pc_addr_resolved, eSymbolContextEverything, sc);
405 symbol = sc.symbol;
406
407 if (symbol == nullptr)
408 return ret_plan_sp;
409
410 llvm::StringRef function_name(symbol->GetName().GetCString());
411
412 // Handling the case where we are attempting to step into std::function.
413 // The behavior will be that we will attempt to obtain the wrapped
414 // callable via FindLibCppStdFunctionCallableInfo() and if we find it we
415 // will return a ThreadPlanRunToAddress to the callable. Therefore we will
416 // step into the wrapped callable.
417 //
418 bool found_expected_start_string =
419 function_name.starts_with("std::__1::function<");
420
421 if (!found_expected_start_string)
422 return ret_plan_sp;
423
424 AddressRange range_of_curr_func;
425 sc.GetAddressRange(eSymbolContextEverything, 0, false, range_of_curr_func);
426
427 StackFrameSP frame = thread.GetStackFrameAtIndex(0);
428
429 if (frame) {
430 ValueObjectSP value_sp = frame->FindVariable(g_this);
431
434
436 value_sp->GetValueIsValid()) {
437 // We found the std::function wrapped callable and we have its address.
438 // We now create a ThreadPlan to run to the callable.
439 ret_plan_sp = std::make_shared<ThreadPlanRunToAddress>(
440 thread, callable_info.callable_address, stop_others);
441 return ret_plan_sp;
442 } else {
443 // We are in std::function but we could not obtain the callable.
444 // We create a ThreadPlan to keep stepping through using the address range
445 // of the current function.
446 ret_plan_sp = std::make_shared<ThreadPlanStepInRange>(
447 thread, range_of_curr_func, sc, nullptr, eOnlyThisThread,
449 return ret_plan_sp;
450 }
451 }
452
453 return ret_plan_sp;
454}
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
RegularExpression m_hidden_function_regex
RecognizedStackFrameSP m_hidden_frame
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.
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:341
lldb::addr_t ReadPointerFromMemory(lldb::addr_t vm_addr, Status &error)
Definition: Process.cpp:2259
uint32_t GetAddressByteSize() const
Definition: Process.cpp:3600
Target & GetTarget()
Get the target object pointer for this module.
Definition: Process.h:1285
This class provides extra information about a stack frame that was provided by a specific stack frame...
bool Execute(llvm::StringRef string, llvm::SmallVectorImpl< llvm::StringRef > *matches=nullptr) const
Execute a regular expression match using the compiled regular expression that is already in this obje...
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, bool first_instruction_only=true)
A base class for frame recognizers.
An error handling class.
Definition: Status.h:44
bool Fail() const
Test for error condition.
Definition: Status.cpp:180
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:1143
StackFrameRecognizerManager & GetFrameRecognizerManager()
Definition: Target.h:1473
bool ResolveLoadAddress(lldb::addr_t load_addr, Address &so_addr, uint32_t stop_id=SectionLoadHistory::eStopIDNow)
Definition: Target.cpp:3114
const ModuleList & GetImages() const
Get accessor for the images for this process.
Definition: Target.h:986
virtual lldb::StackFrameSP GetStackFrameAtIndex(uint32_t idx)
Definition: Thread.h:408
virtual lldb::RegisterContextSP GetRegisterContext()=0
lldb::TargetSP CalculateTarget() override
Definition: Thread.cpp:1401
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:353
std::shared_ptr< lldb_private::ThreadPlan > ThreadPlanSP
Definition: lldb-forward.h:449
std::shared_ptr< lldb_private::StackFrame > StackFrameSP
Definition: lldb-forward.h:420
std::shared_ptr< lldb_private::RecognizedStackFrame > RecognizedStackFrameSP
Definition: lldb-forward.h:401
std::shared_ptr< lldb_private::ValueObject > ValueObjectSP
Definition: lldb-forward.h:480
std::shared_ptr< lldb_private::StackFrameRecognizer > StackFrameRecognizerSP
Definition: lldb-forward.h:424
uint64_t addr_t
Definition: lldb-types.h:80
std::shared_ptr< lldb_private::Target > TargetSP
Definition: lldb-forward.h:444
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