• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
CPPLanguageRuntime(Process * process)40 CPPLanguageRuntime::CPPLanguageRuntime(Process *process)
41     : LanguageRuntime(process) {}
42 
IsAllowedRuntimeValue(ConstString name)43 bool CPPLanguageRuntime::IsAllowedRuntimeValue(ConstString name) {
44   return name == g_this;
45 }
46 
GetObjectDescription(Stream & str,ValueObject & object)47 bool CPPLanguageRuntime::GetObjectDescription(Stream &str,
48                                               ValueObject &object) {
49   // C++ has no generic way to do this.
50   return false;
51 }
52 
GetObjectDescription(Stream & str,Value & value,ExecutionContextScope * exe_scope)53 bool CPPLanguageRuntime::GetObjectDescription(
54     Stream &str, Value &value, ExecutionContextScope *exe_scope) {
55   // C++ has no generic way to do this.
56   return false;
57 }
58 
contains_lambda_identifier(llvm::StringRef & str_ref)59 bool contains_lambda_identifier(llvm::StringRef &str_ref) {
60   return str_ref.contains("$_") || str_ref.contains("'lambda'");
61 }
62 
63 CPPLanguageRuntime::LibCppStdFunctionCallableInfo
line_entry_helper(Target & target,const SymbolContext & sc,Symbol * symbol,llvm::StringRef first_template_param_sref,bool has___invoke)64 line_entry_helper(Target &target, const SymbolContext &sc, Symbol *symbol,
65                   llvm::StringRef first_template_param_sref,
66                   bool has___invoke) {
67 
68   CPPLanguageRuntime::LibCppStdFunctionCallableInfo optional_info;
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
83       optional_info.callable_case = lldb_private::CPPLanguageRuntime::
84           LibCppStdFunctionCallableCase::Lambda;
85     } else {
86       // Case 3
87       optional_info.callable_case = lldb_private::CPPLanguageRuntime::
88           LibCppStdFunctionCallableCase::CallableObject;
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 
99 CPPLanguageRuntime::LibCppStdFunctionCallableInfo
FindLibCppStdFunctionCallableInfo(lldb::ValueObjectSP & valobj_sp)100 CPPLanguageRuntime::FindLibCppStdFunctionCallableInfo(
101     lldb::ValueObjectSP &valobj_sp) {
102   static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
103   Timer scoped_timer(func_cat,
104                      "CPPLanguageRuntime::FindLibCppStdFunctionCallableInfo");
105 
106   LibCppStdFunctionCallableInfo optional_info;
107 
108   if (!valobj_sp)
109     return optional_info;
110 
111   // Member __f_ has type __base*, the contents of which will hold:
112   // 1) a vtable entry which may hold type information needed to discover the
113   //    lambda being called
114   // 2) possibly hold a pointer to the callable object
115   // e.g.
116   //
117   // (lldb) frame var -R  f_display
118   // (std::__1::function<void (int)>) f_display = {
119   //  __buf_ = {
120   //  …
121   // }
122   //  __f_ = 0x00007ffeefbffa00
123   // }
124   // (lldb) memory read -fA 0x00007ffeefbffa00
125   // 0x7ffeefbffa00: ... `vtable for std::__1::__function::__func<void (*) ...
126   // 0x7ffeefbffa08: ... `print_num(int) at std_function_cppreference_exam ...
127   //
128   // We will be handling five cases below, std::function is wrapping:
129   //
130   // 1) a lambda we know at compile time. We will obtain the name of the lambda
131   //    from the first template pameter from __func's vtable. We will look up
132   //    the lambda's operator()() and obtain the line table entry.
133   // 2) a lambda we know at runtime. A pointer to the lambdas __invoke method
134   //    will be stored after the vtable. We will obtain the lambdas name from
135   //    this entry and lookup operator()() and obtain the line table entry.
136   // 3) a callable object via operator()(). We will obtain the name of the
137   //    object from the first template parameter from __func's vtable. We will
138   //    look up the objects operator()() and obtain the line table entry.
139   // 4) a member function. A pointer to the function will stored after the
140   //    we will obtain the name from this pointer.
141   // 5) a free function. A pointer to the function will stored after the vtable
142   //    we will obtain the name from this pointer.
143   ValueObjectSP member__f_(
144       valobj_sp->GetChildMemberWithName(ConstString("__f_"), true));
145 
146   if (member__f_) {
147     ValueObjectSP sub_member__f_(
148        member__f_->GetChildMemberWithName(ConstString("__f_"), true));
149 
150     if (sub_member__f_)
151         member__f_ = sub_member__f_;
152   }
153 
154   if (!member__f_)
155     return optional_info;
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