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"
31#include "lldb/Utility/Timer.h"
32
33using namespace lldb;
34using namespace lldb_private;
35
37
39
41 : LanguageRuntime(process) {}
42
44 return name == g_this;
45}
46
48 ValueObject &object) {
49 // C++ has no generic way to do this.
50 return false;
51}
52
54 Stream &str, Value &value, ExecutionContextScope *exe_scope) {
55 // C++ has no generic way to do this.
56 return false;
57}
58
59bool contains_lambda_identifier(llvm::StringRef &str_ref) {
60 return str_ref.contains("$_") || str_ref.contains("'lambda'");
61}
62
64line_entry_helper(Target &target, const SymbolContext &sc, Symbol *symbol,
65 llvm::StringRef first_template_param_sref,
66 bool has_invoke) {
67
69
70 AddressRange range;
71 sc.GetAddressRange(eSymbolContextEverything, 0, false, range);
72
73 Address address = range.GetBaseAddress();
74
75 Address addr;
76 if (target.ResolveLoadAddress(address.GetCallableLoadAddress(&target),
77 addr)) {
78 LineEntry line_entry;
79 addr.CalculateSymbolContextLineEntry(line_entry);
80
81 if (contains_lambda_identifier(first_template_param_sref) || has_invoke) {
82 // Case 1 and 2
85 } else {
86 // Case 3
89 }
90
91 optional_info.callable_symbol = *symbol;
92 optional_info.callable_line_entry = line_entry;
93 optional_info.callable_address = addr;
94 }
95
96 return optional_info;
97}
98
101 lldb::ValueObjectSP &valobj_sp) {
103
104 LibCppStdFunctionCallableInfo optional_info;
105
106 if (!valobj_sp)
107 return optional_info;
108
109 // Member __f_ has type __base*, the contents of which will hold:
110 // 1) a vtable entry which may hold type information needed to discover the
111 // lambda being called
112 // 2) possibly hold a pointer to the callable object
113 // e.g.
114 //
115 // (lldb) frame var -R f_display
116 // (std::__1::function<void (int)>) f_display = {
117 // __buf_ = {
118 // …
119 // }
120 // __f_ = 0x00007ffeefbffa00
121 // }
122 // (lldb) memory read -fA 0x00007ffeefbffa00
123 // 0x7ffeefbffa00: ... `vtable for std::__1::__function::__func<void (*) ...
124 // 0x7ffeefbffa08: ... `print_num(int) at std_function_cppreference_exam ...
125 //
126 // We will be handling five cases below, std::function is wrapping:
127 //
128 // 1) a lambda we know at compile time. We will obtain the name of the lambda
129 // from the first template pameter from __func's vtable. We will look up
130 // the lambda's operator()() and obtain the line table entry.
131 // 2) a lambda we know at runtime. A pointer to the lambdas __invoke method
132 // will be stored after the vtable. We will obtain the lambdas name from
133 // this entry and lookup operator()() and obtain the line table entry.
134 // 3) a callable object via operator()(). We will obtain the name of the
135 // object from the first template parameter from __func's vtable. We will
136 // look up the objects operator()() and obtain the line table entry.
137 // 4) a member function. A pointer to the function will stored after the
138 // we will obtain the name from this pointer.
139 // 5) a free function. A pointer to the function will stored after the vtable
140 // we will obtain the name from this pointer.
141 ValueObjectSP member_f_(valobj_sp->GetChildMemberWithName("__f_", true));
142
143 if (member_f_) {
144 ValueObjectSP sub_member_f_(
145 member_f_->GetChildMemberWithName("__f_", true));
146
147 if (sub_member_f_)
148 member_f_ = sub_member_f_;
149 }
150
151 if (!member_f_)
152 return optional_info;
153
154 lldb::addr_t member_f_pointer_value = member_f_->GetValueAsUnsigned(0);
155
156 optional_info.member_f_pointer_value = member_f_pointer_value;
157
158 if (!member_f_pointer_value)
159 return optional_info;
160
161 ExecutionContext exe_ctx(valobj_sp->GetExecutionContextRef());
162 Process *process = exe_ctx.GetProcessPtr();
163
164 if (process == nullptr)
165 return optional_info;
166
167 uint32_t address_size = process->GetAddressByteSize();
168 Status status;
169
170 // First item pointed to by __f_ should be the pointer to the vtable for
171 // a __base object.
172 lldb::addr_t vtable_address =
173 process->ReadPointerFromMemory(member_f_pointer_value, status);
174
175 if (status.Fail())
176 return optional_info;
177
178 lldb::addr_t vtable_address_first_entry =
179 process->ReadPointerFromMemory(vtable_address + address_size, status);
180
181 if (status.Fail())
182 return optional_info;
183
184 lldb::addr_t address_after_vtable = member_f_pointer_value + address_size;
185 // As commented above we may not have a function pointer but if we do we will
186 // need it.
187 lldb::addr_t possible_function_address =
188 process->ReadPointerFromMemory(address_after_vtable, status);
189
190 if (status.Fail())
191 return optional_info;
192
193 Target &target = process->GetTarget();
194
195 if (target.GetSectionLoadList().IsEmpty())
196 return optional_info;
197
198 Address vtable_first_entry_resolved;
199
201 vtable_address_first_entry, vtable_first_entry_resolved))
202 return optional_info;
203
204 Address vtable_addr_resolved;
205 SymbolContext sc;
206 Symbol *symbol = nullptr;
207
208 if (!target.GetSectionLoadList().ResolveLoadAddress(vtable_address,
209 vtable_addr_resolved))
210 return optional_info;
211
213 vtable_addr_resolved, eSymbolContextEverything, sc);
214 symbol = sc.symbol;
215
216 if (symbol == nullptr)
217 return optional_info;
218
219 llvm::StringRef vtable_name(symbol->GetName().GetStringRef());
220 bool found_expected_start_string =
221 vtable_name.startswith("vtable for std::__1::__function::__func<");
222
223 if (!found_expected_start_string)
224 return optional_info;
225
226 // Given case 1 or 3 we have a vtable name, we are want to extract the first
227 // template parameter
228 //
229 // ... __func<main::$_0, std::__1::allocator<main::$_0> ...
230 // ^^^^^^^^^
231 //
232 // We could see names such as:
233 // main::$_0
234 // Bar::add_num2(int)::'lambda'(int)
235 // Bar
236 //
237 // We do this by find the first < and , and extracting in between.
238 //
239 // This covers the case of the lambda known at compile time.
240 size_t first_open_angle_bracket = vtable_name.find('<') + 1;
241 size_t first_comma = vtable_name.find(',');
242
243 llvm::StringRef first_template_parameter =
244 vtable_name.slice(first_open_angle_bracket, first_comma);
245
246 Address function_address_resolved;
247
248 // Setup for cases 2, 4 and 5 we have a pointer to a function after the
249 // vtable. We will use a process of elimination to drop through each case
250 // and obtain the data we need.
252 possible_function_address, function_address_resolved)) {
254 function_address_resolved, eSymbolContextEverything, sc);
255 symbol = sc.symbol;
256 }
257
258 // These conditions are used several times to simplify statements later on.
259 bool has_invoke =
260 (symbol ? symbol->GetName().GetStringRef().contains("__invoke") : false);
261 auto calculate_symbol_context_helper = [](auto &t,
262 SymbolContextList &sc_list) {
263 SymbolContext sc;
264 t->CalculateSymbolContext(&sc);
265 sc_list.Append(sc);
266 };
267
268 // Case 2
269 if (has_invoke) {
271 calculate_symbol_context_helper(symbol, scl);
272
273 return line_entry_helper(target, scl[0], symbol, first_template_parameter,
274 has_invoke);
275 }
276
277 // Case 4 or 5
278 if (symbol && !symbol->GetName().GetStringRef().startswith("vtable for") &&
279 !contains_lambda_identifier(first_template_parameter) && !has_invoke) {
280 optional_info.callable_case =
282 optional_info.callable_address = function_address_resolved;
283 optional_info.callable_symbol = *symbol;
284
285 return optional_info;
286 }
287
288 std::string func_to_match = first_template_parameter.str();
289
290 auto it = CallableLookupCache.find(func_to_match);
291 if (it != CallableLookupCache.end())
292 return it->second;
293
295
296 CompileUnit *vtable_cu =
297 vtable_first_entry_resolved.CalculateSymbolContextCompileUnit();
298 llvm::StringRef name_to_use = func_to_match;
299
300 // Case 3, we have a callable object instead of a lambda
301 //
302 // TODO
303 // We currently don't support this case a callable object may have multiple
304 // operator()() varying on const/non-const and number of arguments and we
305 // don't have a way to currently distinguish them so we will bail out now.
306 if (!contains_lambda_identifier(name_to_use))
307 return optional_info;
308
309 if (vtable_cu && !has_invoke) {
310 lldb::FunctionSP func_sp =
311 vtable_cu->FindFunction([name_to_use](const FunctionSP &f) {
312 auto name = f->GetName().GetStringRef();
313 if (name.startswith(name_to_use) && name.contains("operator"))
314 return true;
315
316 return false;
317 });
318
319 if (func_sp) {
320 calculate_symbol_context_helper(func_sp, scl);
321 }
322 }
323
324 if (symbol == nullptr)
325 return optional_info;
326
327 // Case 1 or 3
328 if (scl.GetSize() >= 1) {
329 optional_info = line_entry_helper(target, scl[0], symbol,
330 first_template_parameter, has_invoke);
331 }
332
333 CallableLookupCache[func_to_match] = optional_info;
334
335 return optional_info;
336}
337
338lldb::ThreadPlanSP
340 bool stop_others) {
341 ThreadPlanSP ret_plan_sp;
342
343 lldb::addr_t curr_pc = thread.GetRegisterContext()->GetPC();
344
345 TargetSP target_sp(thread.CalculateTarget());
346
347 if (target_sp->GetSectionLoadList().IsEmpty())
348 return ret_plan_sp;
349
350 Address pc_addr_resolved;
351 SymbolContext sc;
352 Symbol *symbol;
353
354 if (!target_sp->GetSectionLoadList().ResolveLoadAddress(curr_pc,
355 pc_addr_resolved))
356 return ret_plan_sp;
357
358 target_sp->GetImages().ResolveSymbolContextForAddress(
359 pc_addr_resolved, eSymbolContextEverything, sc);
360 symbol = sc.symbol;
361
362 if (symbol == nullptr)
363 return ret_plan_sp;
364
365 llvm::StringRef function_name(symbol->GetName().GetCString());
366
367 // Handling the case where we are attempting to step into std::function.
368 // The behavior will be that we will attempt to obtain the wrapped
369 // callable via FindLibCppStdFunctionCallableInfo() and if we find it we
370 // will return a ThreadPlanRunToAddress to the callable. Therefore we will
371 // step into the wrapped callable.
372 //
373 bool found_expected_start_string =
374 function_name.startswith("std::__1::function<");
375
376 if (!found_expected_start_string)
377 return ret_plan_sp;
378
379 AddressRange range_of_curr_func;
380 sc.GetAddressRange(eSymbolContextEverything, 0, false, range_of_curr_func);
381
382 StackFrameSP frame = thread.GetStackFrameAtIndex(0);
383
384 if (frame) {
385 ValueObjectSP value_sp = frame->FindVariable(g_this);
386
389
391 value_sp->GetValueIsValid()) {
392 // We found the std::function wrapped callable and we have its address.
393 // We now create a ThreadPlan to run to the callable.
394 ret_plan_sp = std::make_shared<ThreadPlanRunToAddress>(
395 thread, callable_info.callable_address, stop_others);
396 return ret_plan_sp;
397 } else {
398 // We are in std::function but we could not obtain the callable.
399 // We create a ThreadPlan to keep stepping through using the address range
400 // of the current function.
401 ret_plan_sp = std::make_shared<ThreadPlanStepInRange>(
402 thread, range_of_curr_func, sc, nullptr, eOnlyThisThread,
404 return ret_plan_sp;
405 }
406 }
407
408 return ret_plan_sp;
409}
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 section + offset based address range class.
Definition: AddressRange.h:25
Address & GetBaseAddress()
Get accessor for the base address of the range.
Definition: AddressRange.h:209
A section + offset based address class.
Definition: Address.h:59
lldb::addr_t GetCallableLoadAddress(Target *target, bool is_indirect=false) const
Get the load address as a callable code load address.
Definition: Address.cpp:336
bool CalculateSymbolContextLineEntry(LineEntry &line_entry) const
Definition: Address.cpp:907
CompileUnit * CalculateSymbolContextCompileUnit() const
Definition: Address.cpp:851
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
bool GetObjectDescription(Stream &str, ValueObject &object) override
A class that describes a compilation unit.
Definition: CompileUnit.h:41
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:77
A uniqued constant string class.
Definition: ConstString.h:40
llvm::StringRef GetStringRef() const
Get the string value as a llvm::StringRef.
Definition: ConstString.h:207
const char * GetCString() const
Get the string value as a C string.
Definition: ConstString.h:221
"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:671
A plug-in interface definition class for debugging a process.
Definition: Process.h:335
lldb::addr_t ReadPointerFromMemory(lldb::addr_t vm_addr, Status &error)
Definition: Process.cpp:2104
uint32_t GetAddressByteSize() const
Definition: Process.cpp:3404
Target & GetTarget()
Get the target object pointer for this module.
Definition: Process.h:1224
bool ResolveLoadAddress(lldb::addr_t load_addr, Address &so_addr, bool allow_section_end=false) const
An error handling class.
Definition: Status.h:44
bool Fail() const
Test for error condition.
Definition: Status.cpp:181
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:33
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:544
SectionLoadList & GetSectionLoadList()
Definition: Target.h:1120
bool ResolveLoadAddress(lldb::addr_t load_addr, Address &so_addr, uint32_t stop_id=SectionLoadHistory::eStopIDNow)
Definition: Target.cpp:3031
const ModuleList & GetImages() const
Get accessor for the images for this process.
Definition: Target.h:965
virtual lldb::StackFrameSP GetStackFrameAtIndex(uint32_t idx)
Definition: Thread.h:397
virtual lldb::RegisterContextSP GetRegisterContext()=0
lldb::TargetSP CalculateTarget() override
Definition: Thread.cpp:1382
A class that represents a running process on the host machine.
Definition: SBAttachInfo.h:14
Definition: SBAddress.h:15
uint64_t addr_t
Definition: lldb-types.h:79
A line table entry class.
Definition: LineEntry.h:20