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 <string.h>
10 
11 #include <memory>
12 
13 #include "CPPLanguageRuntime.h"
14 
15 #include "llvm/ADT/StringRef.h"
16 
17 #include "lldb/Symbol/Block.h"
18 #include "lldb/Symbol/Variable.h"
19 #include "lldb/Symbol/VariableList.h"
20 
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"
32 
33 using namespace lldb;
34 using namespace lldb_private;
35 
36 static ConstString g_this = ConstString("this");
37 
38 char CPPLanguageRuntime::ID = 0;
39 
40 // Destructor
~CPPLanguageRuntime()41 CPPLanguageRuntime::~CPPLanguageRuntime() {}
42 
CPPLanguageRuntime(Process * process)43 CPPLanguageRuntime::CPPLanguageRuntime(Process *process)
44     : LanguageRuntime(process) {}
45 
IsAllowedRuntimeValue(ConstString name)46 bool CPPLanguageRuntime::IsAllowedRuntimeValue(ConstString name) {
47   return name == g_this;
48 }
49 
GetObjectDescription(Stream & str,ValueObject & object)50 bool CPPLanguageRuntime::GetObjectDescription(Stream &str,
51                                               ValueObject &object) {
52   // C++ has no generic way to do this.
53   return false;
54 }
55 
GetObjectDescription(Stream & str,Value & value,ExecutionContextScope * exe_scope)56 bool CPPLanguageRuntime::GetObjectDescription(
57     Stream &str, Value &value, ExecutionContextScope *exe_scope) {
58   // C++ has no generic way to do this.
59   return false;
60 }
61 
contains_lambda_identifier(llvm::StringRef & str_ref)62 bool contains_lambda_identifier(llvm::StringRef &str_ref) {
63   return str_ref.contains("$_") || str_ref.contains("'lambda'");
64 }
65 
66 CPPLanguageRuntime::LibCppStdFunctionCallableInfo
line_entry_helper(Target & target,const SymbolContext & sc,Symbol * symbol,llvm::StringRef first_template_param_sref,bool has___invoke)67 line_entry_helper(Target &target, const SymbolContext &sc, Symbol *symbol,
68                   llvm::StringRef first_template_param_sref,
69                   bool has___invoke) {
70 
71   CPPLanguageRuntime::LibCppStdFunctionCallableInfo optional_info;
72 
73   AddressRange range;
74   sc.GetAddressRange(eSymbolContextEverything, 0, false, range);
75 
76   Address address = range.GetBaseAddress();
77 
78   Address addr;
79   if (target.ResolveLoadAddress(address.GetCallableLoadAddress(&target),
80                                 addr)) {
81     LineEntry line_entry;
82     addr.CalculateSymbolContextLineEntry(line_entry);
83 
84     if (contains_lambda_identifier(first_template_param_sref) || has___invoke) {
85       // Case 1 and 2
86       optional_info.callable_case = lldb_private::CPPLanguageRuntime::
87           LibCppStdFunctionCallableCase::Lambda;
88     } else {
89       // Case 3
90       optional_info.callable_case = lldb_private::CPPLanguageRuntime::
91           LibCppStdFunctionCallableCase::CallableObject;
92     }
93 
94     optional_info.callable_symbol = *symbol;
95     optional_info.callable_line_entry = line_entry;
96     optional_info.callable_address = addr;
97   }
98 
99   return optional_info;
100 }
101 
102 CPPLanguageRuntime::LibCppStdFunctionCallableInfo
FindLibCppStdFunctionCallableInfo(lldb::ValueObjectSP & valobj_sp)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");
108 
109   LibCppStdFunctionCallableInfo optional_info;
110 
111   if (!valobj_sp)
112     return optional_info;
113 
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
118   // e.g.
119   //
120   // (lldb) frame var -R  f_display
121   // (std::__1::function<void (int)>) f_display = {
122   //  __buf_ = {
123   //  …
124   // }
125   //  __f_ = 0x00007ffeefbffa00
126   // }
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 ...
130   //
131   // We will be handling five cases below, std::function is wrapping:
132   //
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));
148 
149   if (member__f_) {
150     ValueObjectSP sub_member__f_(
151        member__f_->GetChildMemberWithName(ConstString("__f_"), true));
152 
153     if (sub_member__f_)
154         member__f_ = sub_member__f_;
155   }
156 
157   lldb::addr_t member__f_pointer_value = member__f_->GetValueAsUnsigned(0);
158 
159   optional_info.member__f_pointer_value = member__f_pointer_value;
160 
161   if (!member__f_pointer_value)
162     return optional_info;
163 
164   ExecutionContext exe_ctx(valobj_sp->GetExecutionContextRef());
165   Process *process = exe_ctx.GetProcessPtr();
166 
167   if (process == nullptr)
168     return optional_info;
169 
170   uint32_t address_size = process->GetAddressByteSize();
171   Status status;
172 
173   // First item pointed to by __f_ should be the pointer to the vtable for
174   // a __base object.
175   lldb::addr_t vtable_address =
176       process->ReadPointerFromMemory(member__f_pointer_value, status);
177 
178   if (status.Fail())
179     return optional_info;
180 
181   lldb::addr_t vtable_address_first_entry =
182       process->ReadPointerFromMemory(vtable_address + address_size, status);
183 
184   if (status.Fail())
185     return optional_info;
186 
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
189   // need it.
190   lldb::addr_t possible_function_address =
191       process->ReadPointerFromMemory(address_after_vtable, status);
192 
193   if (status.Fail())
194     return optional_info;
195 
196   Target &target = process->GetTarget();
197 
198   if (target.GetSectionLoadList().IsEmpty())
199     return optional_info;
200 
201   Address vtable_first_entry_resolved;
202 
203   if (!target.GetSectionLoadList().ResolveLoadAddress(
204           vtable_address_first_entry, vtable_first_entry_resolved))
205     return optional_info;
206 
207   Address vtable_addr_resolved;
208   SymbolContext sc;
209   Symbol *symbol = nullptr;
210 
211   if (!target.GetSectionLoadList().ResolveLoadAddress(vtable_address,
212                                                       vtable_addr_resolved))
213     return optional_info;
214 
215   target.GetImages().ResolveSymbolContextForAddress(
216       vtable_addr_resolved, eSymbolContextEverything, sc);
217   symbol = sc.symbol;
218 
219   if (symbol == nullptr)
220     return optional_info;
221 
222   llvm::StringRef vtable_name(symbol->GetName().GetStringRef());
223   bool found_expected_start_string =
224       vtable_name.startswith("vtable for std::__1::__function::__func<");
225 
226   if (!found_expected_start_string)
227     return optional_info;
228 
229   // Given case 1 or 3 we have a vtable name, we are want to extract the first
230   // template parameter
231   //
232   //  ... __func<main::$_0, std::__1::allocator<main::$_0> ...
233   //             ^^^^^^^^^
234   //
235   // We could see names such as:
236   //    main::$_0
237   //    Bar::add_num2(int)::'lambda'(int)
238   //    Bar
239   //
240   // We do this by find the first < and , and extracting in between.
241   //
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(',');
245 
246   llvm::StringRef first_template_parameter =
247       vtable_name.slice(first_open_angle_bracket, first_comma);
248 
249   Address function_address_resolved;
250 
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);
258     symbol = sc.symbol;
259   }
260 
261   // These conditions are used several times to simplify statements later on.
262   bool has___invoke =
263       (symbol ? symbol->GetName().GetStringRef().contains("__invoke") : false);
264   auto calculate_symbol_context_helper = [](auto &t,
265                                             SymbolContextList &sc_list) {
266     SymbolContext sc;
267     t->CalculateSymbolContext(&sc);
268     sc_list.Append(sc);
269   };
270 
271   // Case 2
272   if (has___invoke) {
273     SymbolContextList scl;
274     calculate_symbol_context_helper(symbol, scl);
275 
276     return line_entry_helper(target, scl[0], symbol, first_template_parameter,
277                              has___invoke);
278   }
279 
280   // Case 4 or 5
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;
287 
288     return optional_info;
289   }
290 
291   std::string func_to_match = first_template_parameter.str();
292 
293   auto it = CallableLookupCache.find(func_to_match);
294   if (it != CallableLookupCache.end())
295     return it->second;
296 
297   SymbolContextList scl;
298 
299   CompileUnit *vtable_cu =
300       vtable_first_entry_resolved.CalculateSymbolContextCompileUnit();
301   llvm::StringRef name_to_use = func_to_match;
302 
303   // Case 3, we have a callable object instead of a lambda
304   //
305   // TODO
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;
311 
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"))
317             return true;
318 
319           return false;
320         });
321 
322     if (func_sp) {
323       calculate_symbol_context_helper(func_sp, scl);
324     }
325   }
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 
338 lldb::ThreadPlanSP
GetStepThroughTrampolinePlan(Thread & thread,bool stop_others)339 CPPLanguageRuntime::GetStepThroughTrampolinePlan(Thread &thread,
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 
387     CPPLanguageRuntime::LibCppStdFunctionCallableInfo callable_info =
388         FindLibCppStdFunctionCallableInfo(value_sp);
389 
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);
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, eOnlyThisThread, eLazyBoolYes,
403           eLazyBoolYes);
404       return ret_plan_sp;
405     }
406   }
407 
408   return ret_plan_sp;
409 }
410