1 //===-- CPPLanguageRuntime.cpp---------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
13 #include "CPPLanguageRuntime.h"
15 #include "llvm/ADT/StringRef.h"
17 #include "lldb/Symbol/Block.h"
18 #include "lldb/Symbol/Variable.h"
19 #include "lldb/Symbol/VariableList.h"
21 #include "lldb/Core/PluginManager.h"
22 #include "lldb/Core/UniqueCStringMap.h"
23 #include "lldb/Symbol/CompileUnit.h"
24 #include "lldb/Target/ABI.h"
25 #include "lldb/Target/ExecutionContext.h"
26 #include "lldb/Target/RegisterContext.h"
27 #include "lldb/Target/SectionLoadList.h"
28 #include "lldb/Target/StackFrame.h"
29 #include "lldb/Target/ThreadPlanRunToAddress.h"
30 #include "lldb/Target/ThreadPlanStepInRange.h"
31 #include "lldb/Utility/Timer.h"
34 using namespace lldb_private;
36 static ConstString g_this = ConstString("this");
38 char CPPLanguageRuntime::ID = 0;
41 CPPLanguageRuntime::~CPPLanguageRuntime() {}
43 CPPLanguageRuntime::CPPLanguageRuntime(Process *process)
44 : LanguageRuntime(process) {}
46 bool CPPLanguageRuntime::IsAllowedRuntimeValue(ConstString name) {
47 return name == g_this;
50 bool CPPLanguageRuntime::GetObjectDescription(Stream &str,
51 ValueObject &object) {
52 // C++ has no generic way to do this.
56 bool CPPLanguageRuntime::GetObjectDescription(
57 Stream &str, Value &value, ExecutionContextScope *exe_scope) {
58 // C++ has no generic way to do this.
62 bool contains_lambda_identifier(llvm::StringRef &str_ref) {
63 return str_ref.contains("$_") || str_ref.contains("'lambda'");
66 CPPLanguageRuntime::LibCppStdFunctionCallableInfo
67 line_entry_helper(Target &target, const SymbolContext &sc, Symbol *symbol,
68 llvm::StringRef first_template_param_sref,
71 CPPLanguageRuntime::LibCppStdFunctionCallableInfo optional_info;
74 sc.GetAddressRange(eSymbolContextEverything, 0, false, range);
76 Address address = range.GetBaseAddress();
79 if (target.ResolveLoadAddress(address.GetCallableLoadAddress(&target),
82 addr.CalculateSymbolContextLineEntry(line_entry);
84 if (contains_lambda_identifier(first_template_param_sref) || has___invoke) {
86 optional_info.callable_case = lldb_private::CPPLanguageRuntime::
87 LibCppStdFunctionCallableCase::Lambda;
90 optional_info.callable_case = lldb_private::CPPLanguageRuntime::
91 LibCppStdFunctionCallableCase::CallableObject;
94 optional_info.callable_symbol = *symbol;
95 optional_info.callable_line_entry = line_entry;
96 optional_info.callable_address = addr;
102 CPPLanguageRuntime::LibCppStdFunctionCallableInfo
103 CPPLanguageRuntime::FindLibCppStdFunctionCallableInfo(
104 lldb::ValueObjectSP &valobj_sp) {
105 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
106 Timer scoped_timer(func_cat,
107 "CPPLanguageRuntime::FindLibCppStdFunctionCallableInfo");
109 LibCppStdFunctionCallableInfo optional_info;
112 return optional_info;
114 // Member __f_ has type __base*, the contents of which will hold:
115 // 1) a vtable entry which may hold type information needed to discover the
116 // lambda being called
117 // 2) possibly hold a pointer to the callable object
120 // (lldb) frame var -R f_display
121 // (std::__1::function<void (int)>) f_display = {
125 // __f_ = 0x00007ffeefbffa00
127 // (lldb) memory read -fA 0x00007ffeefbffa00
128 // 0x7ffeefbffa00: ... `vtable for std::__1::__function::__func<void (*) ...
129 // 0x7ffeefbffa08: ... `print_num(int) at std_function_cppreference_exam ...
131 // We will be handling five cases below, std::function is wrapping:
133 // 1) a lambda we know at compile time. We will obtain the name of the lambda
134 // from the first template pameter from __func's vtable. We will look up
135 // the lambda's operator()() and obtain the line table entry.
136 // 2) a lambda we know at runtime. A pointer to the lambdas __invoke method
137 // will be stored after the vtable. We will obtain the lambdas name from
138 // this entry and lookup operator()() and obtain the line table entry.
139 // 3) a callable object via operator()(). We will obtain the name of the
140 // object from the first template parameter from __func's vtable. We will
141 // look up the objects operator()() and obtain the line table entry.
142 // 4) a member function. A pointer to the function will stored after the
143 // we will obtain the name from this pointer.
144 // 5) a free function. A pointer to the function will stored after the vtable
145 // we will obtain the name from this pointer.
146 ValueObjectSP member__f_(
147 valobj_sp->GetChildMemberWithName(ConstString("__f_"), true));
150 ValueObjectSP sub_member__f_(
151 member__f_->GetChildMemberWithName(ConstString("__f_"), true));
154 member__f_ = sub_member__f_;
157 lldb::addr_t member__f_pointer_value = member__f_->GetValueAsUnsigned(0);
159 optional_info.member__f_pointer_value = member__f_pointer_value;
161 if (!member__f_pointer_value)
162 return optional_info;
164 ExecutionContext exe_ctx(valobj_sp->GetExecutionContextRef());
165 Process *process = exe_ctx.GetProcessPtr();
167 if (process == nullptr)
168 return optional_info;
170 uint32_t address_size = process->GetAddressByteSize();
173 // First item pointed to by __f_ should be the pointer to the vtable for
175 lldb::addr_t vtable_address =
176 process->ReadPointerFromMemory(member__f_pointer_value, status);
179 return optional_info;
181 lldb::addr_t vtable_address_first_entry =
182 process->ReadPointerFromMemory(vtable_address + address_size, status);
185 return optional_info;
187 lldb::addr_t address_after_vtable = member__f_pointer_value + address_size;
188 // As commented above we may not have a function pointer but if we do we will
190 lldb::addr_t possible_function_address =
191 process->ReadPointerFromMemory(address_after_vtable, status);
194 return optional_info;
196 Target &target = process->GetTarget();
198 if (target.GetSectionLoadList().IsEmpty())
199 return optional_info;
201 Address vtable_first_entry_resolved;
203 if (!target.GetSectionLoadList().ResolveLoadAddress(
204 vtable_address_first_entry, vtable_first_entry_resolved))
205 return optional_info;
207 Address vtable_addr_resolved;
209 Symbol *symbol = nullptr;
211 if (!target.GetSectionLoadList().ResolveLoadAddress(vtable_address,
212 vtable_addr_resolved))
213 return optional_info;
215 target.GetImages().ResolveSymbolContextForAddress(
216 vtable_addr_resolved, eSymbolContextEverything, sc);
219 if (symbol == nullptr)
220 return optional_info;
222 llvm::StringRef vtable_name(symbol->GetName().GetStringRef());
223 bool found_expected_start_string =
224 vtable_name.startswith("vtable for std::__1::__function::__func<");
226 if (!found_expected_start_string)
227 return optional_info;
229 // Given case 1 or 3 we have a vtable name, we are want to extract the first
230 // template parameter
232 // ... __func<main::$_0, std::__1::allocator<main::$_0> ...
235 // We could see names such as:
237 // Bar::add_num2(int)::'lambda'(int)
240 // We do this by find the first < and , and extracting in between.
242 // This covers the case of the lambda known at compile time.
243 size_t first_open_angle_bracket = vtable_name.find('<') + 1;
244 size_t first_comma = vtable_name.find(',');
246 llvm::StringRef first_template_parameter =
247 vtable_name.slice(first_open_angle_bracket, first_comma);
249 Address function_address_resolved;
251 // Setup for cases 2, 4 and 5 we have a pointer to a function after the
252 // vtable. We will use a process of elimination to drop through each case
253 // and obtain the data we need.
254 if (target.GetSectionLoadList().ResolveLoadAddress(
255 possible_function_address, function_address_resolved)) {
256 target.GetImages().ResolveSymbolContextForAddress(
257 function_address_resolved, eSymbolContextEverything, sc);
261 // These conditions are used several times to simplify statements later on.
263 (symbol ? symbol->GetName().GetStringRef().contains("__invoke") : false);
264 auto calculate_symbol_context_helper = [](auto &t,
265 SymbolContextList &sc_list) {
267 t->CalculateSymbolContext(&sc);
273 SymbolContextList scl;
274 calculate_symbol_context_helper(symbol, scl);
276 return line_entry_helper(target, scl[0], symbol, first_template_parameter,
281 if (symbol && !symbol->GetName().GetStringRef().startswith("vtable for") &&
282 !contains_lambda_identifier(first_template_parameter) && !has___invoke) {
283 optional_info.callable_case =
284 LibCppStdFunctionCallableCase::FreeOrMemberFunction;
285 optional_info.callable_address = function_address_resolved;
286 optional_info.callable_symbol = *symbol;
288 return optional_info;
291 std::string func_to_match = first_template_parameter.str();
293 auto it = CallableLookupCache.find(func_to_match);
294 if (it != CallableLookupCache.end())
297 SymbolContextList scl;
299 CompileUnit *vtable_cu =
300 vtable_first_entry_resolved.CalculateSymbolContextCompileUnit();
301 llvm::StringRef name_to_use = func_to_match;
303 // Case 3, we have a callable object instead of a lambda
306 // We currently don't support this case a callable object may have multiple
307 // operator()() varying on const/non-const and number of arguments and we
308 // don't have a way to currently distinguish them so we will bail out now.
309 if (!contains_lambda_identifier(name_to_use))
310 return optional_info;
312 if (vtable_cu && !has___invoke) {
313 lldb::FunctionSP func_sp =
314 vtable_cu->FindFunction([name_to_use](const FunctionSP &f) {
315 auto name = f->GetName().GetStringRef();
316 if (name.startswith(name_to_use) && name.contains("operator"))
323 calculate_symbol_context_helper(func_sp, scl);
328 if (scl.GetSize() >= 1) {
329 optional_info = line_entry_helper(target, scl[0], symbol,
330 first_template_parameter, has___invoke);
333 CallableLookupCache[func_to_match] = optional_info;
335 return optional_info;
339 CPPLanguageRuntime::GetStepThroughTrampolinePlan(Thread &thread,
341 ThreadPlanSP ret_plan_sp;
343 lldb::addr_t curr_pc = thread.GetRegisterContext()->GetPC();
345 TargetSP target_sp(thread.CalculateTarget());
347 if (target_sp->GetSectionLoadList().IsEmpty())
350 Address pc_addr_resolved;
354 if (!target_sp->GetSectionLoadList().ResolveLoadAddress(curr_pc,
358 target_sp->GetImages().ResolveSymbolContextForAddress(
359 pc_addr_resolved, eSymbolContextEverything, sc);
362 if (symbol == nullptr)
365 llvm::StringRef function_name(symbol->GetName().GetCString());
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.
373 bool found_expected_start_string =
374 function_name.startswith("std::__1::function<");
376 if (!found_expected_start_string)
379 AddressRange range_of_curr_func;
380 sc.GetAddressRange(eSymbolContextEverything, 0, false, range_of_curr_func);
382 StackFrameSP frame = thread.GetStackFrameAtIndex(0);
385 ValueObjectSP value_sp = frame->FindVariable(g_this);
387 CPPLanguageRuntime::LibCppStdFunctionCallableInfo callable_info =
388 FindLibCppStdFunctionCallableInfo(value_sp);
390 if (callable_info.callable_case != LibCppStdFunctionCallableCase::Invalid &&
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);
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, eOnlyThisThread, eLazyBoolYes,