Coverage Report

Created: 2022-01-22 13:19

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