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
41 CPPLanguageRuntime::~CPPLanguageRuntime() {}
42 
43 CPPLanguageRuntime::CPPLanguageRuntime(Process *process)
44     : LanguageRuntime(process) {}
45 
46 bool CPPLanguageRuntime::IsAllowedRuntimeValue(ConstString name) {
47   return name == g_this;
48 }
49 
50 bool CPPLanguageRuntime::GetObjectDescription(Stream &str,
51                                               ValueObject &object) {
52   // C++ has no generic way to do this.
53   return false;
54 }
55 
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 
62 bool contains_lambda_identifier(llvm::StringRef &str_ref) {
63   return str_ref.contains("$_") || str_ref.contains("'lambda'");
64 }
65 
66 CPPLanguageRuntime::LibCppStdFunctionCallableInfo
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
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   if (!member__f_)
158     return optional_info;
159 
160   lldb::addr_t member__f_pointer_value = member__f_->GetValueAsUnsigned(0);
161 
162   optional_info.member__f_pointer_value = member__f_pointer_value;
163 
164   if (!member__f_pointer_value)
165     return optional_info;
166 
167   ExecutionContext exe_ctx(valobj_sp->GetExecutionContextRef());
168   Process *process = exe_ctx.GetProcessPtr();
169 
170   if (process == nullptr)
171     return optional_info;
172 
173   uint32_t address_size = process->GetAddressByteSize();
174   Status status;
175 
176   // First item pointed to by __f_ should be the pointer to the vtable for
177   // a __base object.
178   lldb::addr_t vtable_address =
179       process->ReadPointerFromMemory(member__f_pointer_value, status);
180 
181   if (status.Fail())
182     return optional_info;
183 
184   lldb::addr_t vtable_address_first_entry =
185       process->ReadPointerFromMemory(vtable_address + address_size, status);
186 
187   if (status.Fail())
188     return optional_info;
189 
190   lldb::addr_t address_after_vtable = member__f_pointer_value + address_size;
191   // As commented above we may not have a function pointer but if we do we will
192   // need it.
193   lldb::addr_t possible_function_address =
194       process->ReadPointerFromMemory(address_after_vtable, status);
195 
196   if (status.Fail())
197     return optional_info;
198 
199   Target &target = process->GetTarget();
200 
201   if (target.GetSectionLoadList().IsEmpty())
202     return optional_info;
203 
204   Address vtable_first_entry_resolved;
205 
206   if (!target.GetSectionLoadList().ResolveLoadAddress(
207           vtable_address_first_entry, vtable_first_entry_resolved))
208     return optional_info;
209 
210   Address vtable_addr_resolved;
211   SymbolContext sc;
212   Symbol *symbol = nullptr;
213 
214   if (!target.GetSectionLoadList().ResolveLoadAddress(vtable_address,
215                                                       vtable_addr_resolved))
216     return optional_info;
217 
218   target.GetImages().ResolveSymbolContextForAddress(
219       vtable_addr_resolved, eSymbolContextEverything, sc);
220   symbol = sc.symbol;
221 
222   if (symbol == nullptr)
223     return optional_info;
224 
225   llvm::StringRef vtable_name(symbol->GetName().GetStringRef());
226   bool found_expected_start_string =
227       vtable_name.startswith("vtable for std::__1::__function::__func<");
228 
229   if (!found_expected_start_string)
230     return optional_info;
231 
232   // Given case 1 or 3 we have a vtable name, we are want to extract the first
233   // template parameter
234   //
235   //  ... __func<main::$_0, std::__1::allocator<main::$_0> ...
236   //             ^^^^^^^^^
237   //
238   // We could see names such as:
239   //    main::$_0
240   //    Bar::add_num2(int)::'lambda'(int)
241   //    Bar
242   //
243   // We do this by find the first < and , and extracting in between.
244   //
245   // This covers the case of the lambda known at compile time.
246   size_t first_open_angle_bracket = vtable_name.find('<') + 1;
247   size_t first_comma = vtable_name.find(',');
248 
249   llvm::StringRef first_template_parameter =
250       vtable_name.slice(first_open_angle_bracket, first_comma);
251 
252   Address function_address_resolved;
253 
254   // Setup for cases 2, 4 and 5 we have a pointer to a function after the
255   // vtable. We will use a process of elimination to drop through each case
256   // and obtain the data we need.
257   if (target.GetSectionLoadList().ResolveLoadAddress(
258           possible_function_address, function_address_resolved)) {
259     target.GetImages().ResolveSymbolContextForAddress(
260         function_address_resolved, eSymbolContextEverything, sc);
261     symbol = sc.symbol;
262   }
263 
264   // These conditions are used several times to simplify statements later on.
265   bool has___invoke =
266       (symbol ? symbol->GetName().GetStringRef().contains("__invoke") : false);
267   auto calculate_symbol_context_helper = [](auto &t,
268                                             SymbolContextList &sc_list) {
269     SymbolContext sc;
270     t->CalculateSymbolContext(&sc);
271     sc_list.Append(sc);
272   };
273 
274   // Case 2
275   if (has___invoke) {
276     SymbolContextList scl;
277     calculate_symbol_context_helper(symbol, scl);
278 
279     return line_entry_helper(target, scl[0], symbol, first_template_parameter,
280                              has___invoke);
281   }
282 
283   // Case 4 or 5
284   if (symbol && !symbol->GetName().GetStringRef().startswith("vtable for") &&
285       !contains_lambda_identifier(first_template_parameter) && !has___invoke) {
286     optional_info.callable_case =
287         LibCppStdFunctionCallableCase::FreeOrMemberFunction;
288     optional_info.callable_address = function_address_resolved;
289     optional_info.callable_symbol = *symbol;
290 
291     return optional_info;
292   }
293 
294   std::string func_to_match = first_template_parameter.str();
295 
296   auto it = CallableLookupCache.find(func_to_match);
297   if (it != CallableLookupCache.end())
298     return it->second;
299 
300   SymbolContextList scl;
301 
302   CompileUnit *vtable_cu =
303       vtable_first_entry_resolved.CalculateSymbolContextCompileUnit();
304   llvm::StringRef name_to_use = func_to_match;
305 
306   // Case 3, we have a callable object instead of a lambda
307   //
308   // TODO
309   // We currently don't support this case a callable object may have multiple
310   // operator()() varying on const/non-const and number of arguments and we
311   // don't have a way to currently distinguish them so we will bail out now.
312   if (!contains_lambda_identifier(name_to_use))
313     return optional_info;
314 
315   if (vtable_cu && !has___invoke) {
316     lldb::FunctionSP func_sp =
317         vtable_cu->FindFunction([name_to_use](const FunctionSP &f) {
318           auto name = f->GetName().GetStringRef();
319           if (name.startswith(name_to_use) && name.contains("operator"))
320             return true;
321 
322           return false;
323         });
324 
325     if (func_sp) {
326       calculate_symbol_context_helper(func_sp, scl);
327     }
328   }
329 
330   // Case 1 or 3
331   if (scl.GetSize() >= 1) {
332     optional_info = line_entry_helper(target, scl[0], symbol,
333                                       first_template_parameter, has___invoke);
334   }
335 
336   CallableLookupCache[func_to_match] = optional_info;
337 
338   return optional_info;
339 }
340 
341 lldb::ThreadPlanSP
342 CPPLanguageRuntime::GetStepThroughTrampolinePlan(Thread &thread,
343                                                  bool stop_others) {
344   ThreadPlanSP ret_plan_sp;
345 
346   lldb::addr_t curr_pc = thread.GetRegisterContext()->GetPC();
347 
348   TargetSP target_sp(thread.CalculateTarget());
349 
350   if (target_sp->GetSectionLoadList().IsEmpty())
351     return ret_plan_sp;
352 
353   Address pc_addr_resolved;
354   SymbolContext sc;
355   Symbol *symbol;
356 
357   if (!target_sp->GetSectionLoadList().ResolveLoadAddress(curr_pc,
358                                                           pc_addr_resolved))
359     return ret_plan_sp;
360 
361   target_sp->GetImages().ResolveSymbolContextForAddress(
362       pc_addr_resolved, eSymbolContextEverything, sc);
363   symbol = sc.symbol;
364 
365   if (symbol == nullptr)
366     return ret_plan_sp;
367 
368   llvm::StringRef function_name(symbol->GetName().GetCString());
369 
370   // Handling the case where we are attempting to step into std::function.
371   // The behavior will be that we will attempt to obtain the wrapped
372   // callable via FindLibCppStdFunctionCallableInfo() and if we find it we
373   // will return a ThreadPlanRunToAddress to the callable. Therefore we will
374   // step into the wrapped callable.
375   //
376   bool found_expected_start_string =
377       function_name.startswith("std::__1::function<");
378 
379   if (!found_expected_start_string)
380     return ret_plan_sp;
381 
382   AddressRange range_of_curr_func;
383   sc.GetAddressRange(eSymbolContextEverything, 0, false, range_of_curr_func);
384 
385   StackFrameSP frame = thread.GetStackFrameAtIndex(0);
386 
387   if (frame) {
388     ValueObjectSP value_sp = frame->FindVariable(g_this);
389 
390     CPPLanguageRuntime::LibCppStdFunctionCallableInfo callable_info =
391         FindLibCppStdFunctionCallableInfo(value_sp);
392 
393     if (callable_info.callable_case != LibCppStdFunctionCallableCase::Invalid &&
394         value_sp->GetValueIsValid()) {
395       // We found the std::function wrapped callable and we have its address.
396       // We now create a ThreadPlan to run to the callable.
397       ret_plan_sp = std::make_shared<ThreadPlanRunToAddress>(
398           thread, callable_info.callable_address, stop_others);
399       return ret_plan_sp;
400     } else {
401       // We are in std::function but we could not obtain the callable.
402       // We create a ThreadPlan to keep stepping through using the address range
403       // of the current function.
404       ret_plan_sp = std::make_shared<ThreadPlanStepInRange>(
405           thread, range_of_curr_func, sc, eOnlyThisThread, eLazyBoolYes,
406           eLazyBoolYes);
407       return ret_plan_sp;
408     }
409   }
410 
411   return ret_plan_sp;
412 }
413