brintos

brintos / llvm-project-archived public Read only

0
0
Text · 17.1 KiB · 913678b Raw
494 lines · cpp
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-exception6//7//===----------------------------------------------------------------------===//8 9#include <cstring>10#include <iostream>11 12#include <memory>13 14#include "CPPLanguageRuntime.h"15#include "VerboseTrapFrameRecognizer.h"16 17#include "llvm/ADT/StringRef.h"18 19#include "lldb/Symbol/Block.h"20#include "lldb/Symbol/Variable.h"21#include "lldb/Symbol/VariableList.h"22 23#include "lldb/Core/PluginManager.h"24#include "lldb/Core/UniqueCStringMap.h"25#include "lldb/Symbol/CompileUnit.h"26#include "lldb/Target/ABI.h"27#include "lldb/Target/ExecutionContext.h"28#include "lldb/Target/RegisterContext.h"29#include "lldb/Target/SectionLoadList.h"30#include "lldb/Target/StackFrame.h"31#include "lldb/Target/StackFrameRecognizer.h"32#include "lldb/Target/ThreadPlanRunToAddress.h"33#include "lldb/Target/ThreadPlanStepInRange.h"34#include "lldb/Utility/Timer.h"35 36using namespace lldb;37using namespace lldb_private;38 39static ConstString g_this = ConstString("this");40// Artificial coroutine-related variables emitted by clang.41static ConstString g_promise = ConstString("__promise");42static ConstString g_coro_frame = ConstString("__coro_frame");43 44char CPPLanguageRuntime::ID = 0;45 46/// A frame recognizer that is installed to hide libc++ implementation47/// details from the backtrace.48class LibCXXFrameRecognizer : public StackFrameRecognizer {49  std::array<RegularExpression, 2> m_hidden_regex;50  RecognizedStackFrameSP m_hidden_frame;51 52  struct LibCXXHiddenFrame : public RecognizedStackFrame {53    bool ShouldHide() override { return true; }54  };55 56public:57  LibCXXFrameRecognizer()58      : m_hidden_regex{59            // internal implementation details in the `std::` namespace60            //    std::__1::__function::__alloc_func<void (*)(), std::__1::allocator<void (*)()>, void ()>::operator()[abi:ne200000]61            //    std::__1::__function::__func<void (*)(), std::__1::allocator<void (*)()>, void ()>::operator()62            //    std::__1::__function::__value_func<void ()>::operator()[abi:ne200000]() const63            //    std::__2::__function::__policy_invoker<void (int, int)>::__call_impl[abi:ne200000]<std::__2::__function::__default_alloc_func<int (*)(int, int), int (int, int)>>64            //    std::__1::__invoke[abi:ne200000]<void (*&)()>65            //    std::__1::__invoke_void_return_wrapper<void, true>::__call[abi:ne200000]<void (*&)()>66            RegularExpression{R"(^std::__[^:]*::__)"},67            // internal implementation details in the `std::ranges` namespace68            //    std::__1::ranges::__sort::__sort_fn_impl[abi:ne200000]<std::__1::__wrap_iter<int*>, std::__1::__wrap_iter<int*>, bool (*)(int, int), std::__1::identity>69            RegularExpression{R"(^std::__[^:]*::ranges::__)"},70        },71        m_hidden_frame(new LibCXXHiddenFrame()) {}72 73  std::string GetName() override { return "libc++ frame recognizer"; }74 75  lldb::RecognizedStackFrameSP76  RecognizeFrame(lldb::StackFrameSP frame_sp) override {77    if (!frame_sp)78      return {};79    const auto &sc = frame_sp->GetSymbolContext(lldb::eSymbolContextFunction);80    if (!sc.function)81      return {};82 83    // Check if we have a regex match84    for (RegularExpression &r : m_hidden_regex) {85      if (!r.Execute(sc.function->GetNameNoArguments()))86        continue;87 88      // Only hide this frame if the immediate caller is also within libc++.89      lldb::ThreadSP thread_sp = frame_sp->GetThread();90      if (!thread_sp)91        return {};92      lldb::StackFrameSP parent_frame_sp =93          thread_sp->GetStackFrameAtIndex(frame_sp->GetFrameIndex() + 1);94      if (!parent_frame_sp)95        return {};96      const auto &parent_sc =97          parent_frame_sp->GetSymbolContext(lldb::eSymbolContextFunction);98      if (!parent_sc.function)99        return {};100      if (parent_sc.function->GetNameNoArguments().GetStringRef().starts_with(101              "std::"))102        return m_hidden_frame;103    }104 105    return {};106  }107};108 109CPPLanguageRuntime::CPPLanguageRuntime(Process *process)110    : LanguageRuntime(process) {111  if (process) {112    process->GetTarget().GetFrameRecognizerManager().AddRecognizer(113        StackFrameRecognizerSP(new LibCXXFrameRecognizer()), {},114        std::make_shared<RegularExpression>("^std::__[^:]*::"),115        /*mangling_preference=*/Mangled::ePreferDemangledWithoutArguments,116        /*first_instruction_only=*/false);117 118    RegisterVerboseTrapFrameRecognizer(*process);119  }120}121 122bool CPPLanguageRuntime::IsAllowedRuntimeValue(ConstString name) {123  return name == g_this || name == g_promise || name == g_coro_frame;124}125 126llvm::Error CPPLanguageRuntime::GetObjectDescription(Stream &str,127                                                     ValueObject &object) {128  // C++ has no generic way to do this.129  return llvm::createStringError("C++ does not support object descriptions");130}131 132llvm::Error133CPPLanguageRuntime::GetObjectDescription(Stream &str, Value &value,134                                         ExecutionContextScope *exe_scope) {135  // C++ has no generic way to do this.136  return llvm::createStringError("C++ does not support object descriptions");137}138 139bool contains_lambda_identifier(llvm::StringRef &str_ref) {140  return str_ref.contains("$_") || str_ref.contains("'lambda'");141}142 143CPPLanguageRuntime::LibCppStdFunctionCallableInfo144line_entry_helper(Target &target, const SymbolContext &sc, Symbol *symbol,145                  llvm::StringRef first_template_param_sref, bool has_invoke) {146 147  CPPLanguageRuntime::LibCppStdFunctionCallableInfo optional_info;148 149  Address address = sc.GetFunctionOrSymbolAddress();150 151  Address addr;152  if (target.ResolveLoadAddress(address.GetCallableLoadAddress(&target),153                                addr)) {154    LineEntry line_entry;155    addr.CalculateSymbolContextLineEntry(line_entry);156 157    if (contains_lambda_identifier(first_template_param_sref) || has_invoke) {158      // Case 1 and 2159      optional_info.callable_case = lldb_private::CPPLanguageRuntime::160          LibCppStdFunctionCallableCase::Lambda;161    } else {162      // Case 3163      optional_info.callable_case = lldb_private::CPPLanguageRuntime::164          LibCppStdFunctionCallableCase::CallableObject;165    }166 167    optional_info.callable_symbol = *symbol;168    optional_info.callable_line_entry = line_entry;169    optional_info.callable_address = addr;170  }171 172  return optional_info;173}174 175CPPLanguageRuntime::LibCppStdFunctionCallableInfo176CPPLanguageRuntime::FindLibCppStdFunctionCallableInfo(177    lldb::ValueObjectSP &valobj_sp) {178  LLDB_SCOPED_TIMER();179 180  LibCppStdFunctionCallableInfo optional_info;181 182  if (!valobj_sp)183    return optional_info;184 185  // Member __f_ has type __base*, the contents of which will hold:186  // 1) a vtable entry which may hold type information needed to discover the187  //    lambda being called188  // 2) possibly hold a pointer to the callable object189  // e.g.190  //191  // (lldb) frame var -R  f_display192  // (std::__1::function<void (int)>) f_display = {193  //  __buf_ = {194  //  …195  // }196  //  __f_ = 0x00007ffeefbffa00197  // }198  // (lldb) memory read -fA 0x00007ffeefbffa00199  // 0x7ffeefbffa00: ... `vtable for std::__1::__function::__func<void (*) ...200  // 0x7ffeefbffa08: ... `print_num(int) at std_function_cppreference_exam ...201  //202  // We will be handling five cases below, std::function is wrapping:203  //204  // 1) a lambda we know at compile time. We will obtain the name of the lambda205  //    from the first template pameter from __func's vtable. We will look up206  //    the lambda's operator()() and obtain the line table entry.207  // 2) a lambda we know at runtime. A pointer to the lambdas __invoke method208  //    will be stored after the vtable. We will obtain the lambdas name from209  //    this entry and lookup operator()() and obtain the line table entry.210  // 3) a callable object via operator()(). We will obtain the name of the211  //    object from the first template parameter from __func's vtable. We will212  //    look up the objects operator()() and obtain the line table entry.213  // 4) a member function. A pointer to the function will stored after the214  //    we will obtain the name from this pointer.215  // 5) a free function. A pointer to the function will stored after the vtable216  //    we will obtain the name from this pointer.217  ValueObjectSP member_f_(valobj_sp->GetChildMemberWithName("__f_"));218 219  if (member_f_) {220    ValueObjectSP sub_member_f_(member_f_->GetChildMemberWithName("__f_"));221 222    if (sub_member_f_)223      member_f_ = sub_member_f_;224  }225 226  if (!member_f_)227    return optional_info;228 229  lldb::addr_t member_f_pointer_value = member_f_->GetValueAsUnsigned(0);230 231  optional_info.member_f_pointer_value = member_f_pointer_value;232 233  if (!member_f_pointer_value)234    return optional_info;235 236  ExecutionContext exe_ctx(valobj_sp->GetExecutionContextRef());237  Process *process = exe_ctx.GetProcessPtr();238 239  if (process == nullptr)240    return optional_info;241 242  uint32_t address_size = process->GetAddressByteSize();243  Status status;244 245  // First item pointed to by __f_ should be the pointer to the vtable for246  // a __base object.247  lldb::addr_t vtable_address =248      process->ReadPointerFromMemory(member_f_pointer_value, status);249 250  if (status.Fail())251    return optional_info;252 253  lldb::addr_t vtable_address_first_entry =254      process->ReadPointerFromMemory(vtable_address + address_size, status);255 256  if (status.Fail())257    return optional_info;258 259  lldb::addr_t address_after_vtable = member_f_pointer_value + address_size;260  // As commented above we may not have a function pointer but if we do we will261  // need it.262  lldb::addr_t possible_function_address =263      process->ReadPointerFromMemory(address_after_vtable, status);264 265  if (status.Fail())266    return optional_info;267 268  Target &target = process->GetTarget();269 270  if (!target.HasLoadedSections())271    return optional_info;272 273  Address vtable_first_entry_resolved;274 275  if (!target.ResolveLoadAddress(vtable_address_first_entry,276                                 vtable_first_entry_resolved))277    return optional_info;278 279  Address vtable_addr_resolved;280  SymbolContext sc;281  Symbol *symbol = nullptr;282 283  if (!target.ResolveLoadAddress(vtable_address, vtable_addr_resolved))284    return optional_info;285 286  target.GetImages().ResolveSymbolContextForAddress(287      vtable_addr_resolved, eSymbolContextEverything, sc);288  symbol = sc.symbol;289 290  if (symbol == nullptr)291    return optional_info;292 293  llvm::StringRef vtable_name(symbol->GetName().GetStringRef());294  bool found_expected_start_string =295      vtable_name.starts_with("vtable for std::__1::__function::__func<");296 297  if (!found_expected_start_string)298    return optional_info;299 300  // Given case 1 or 3 we have a vtable name, we are want to extract the first301  // template parameter302  //303  //  ... __func<main::$_0, std::__1::allocator<main::$_0> ...304  //             ^^^^^^^^^305  //306  // We could see names such as:307  //    main::$_0308  //    Bar::add_num2(int)::'lambda'(int)309  //    Bar310  //311  // We do this by find the first < and , and extracting in between.312  //313  // This covers the case of the lambda known at compile time.314  size_t first_open_angle_bracket = vtable_name.find('<') + 1;315  size_t first_comma = vtable_name.find(',');316 317  llvm::StringRef first_template_parameter =318      vtable_name.slice(first_open_angle_bracket, first_comma);319 320  Address function_address_resolved;321 322  // Setup for cases 2, 4 and 5 we have a pointer to a function after the323  // vtable. We will use a process of elimination to drop through each case324  // and obtain the data we need.325  if (target.ResolveLoadAddress(possible_function_address,326                                function_address_resolved)) {327    target.GetImages().ResolveSymbolContextForAddress(328        function_address_resolved, eSymbolContextEverything, sc);329    symbol = sc.symbol;330  }331 332  // These conditions are used several times to simplify statements later on.333  bool has_invoke =334      (symbol ? symbol->GetName().GetStringRef().contains("__invoke") : false);335  auto calculate_symbol_context_helper = [](auto &t,336                                            SymbolContextList &sc_list) {337    SymbolContext sc;338    t->CalculateSymbolContext(&sc);339    sc_list.Append(sc);340  };341 342  // Case 2343  if (has_invoke) {344    SymbolContextList scl;345    calculate_symbol_context_helper(symbol, scl);346 347    return line_entry_helper(target, scl[0], symbol, first_template_parameter,348                             has_invoke);349  }350 351  // Case 4 or 5352  if (symbol && !symbol->GetName().GetStringRef().starts_with("vtable for") &&353      !contains_lambda_identifier(first_template_parameter) && !has_invoke) {354    optional_info.callable_case =355        LibCppStdFunctionCallableCase::FreeOrMemberFunction;356    optional_info.callable_address = function_address_resolved;357    optional_info.callable_symbol = *symbol;358 359    return optional_info;360  }361 362  std::string func_to_match = first_template_parameter.str();363 364  auto it = CallableLookupCache.find(func_to_match);365  if (it != CallableLookupCache.end())366    return it->second;367 368  SymbolContextList scl;369 370  CompileUnit *vtable_cu =371      vtable_first_entry_resolved.CalculateSymbolContextCompileUnit();372  llvm::StringRef name_to_use = func_to_match;373 374  // Case 3, we have a callable object instead of a lambda375  //376  // TODO377  // We currently don't support this case a callable object may have multiple378  // operator()() varying on const/non-const and number of arguments and we379  // don't have a way to currently distinguish them so we will bail out now.380  if (!contains_lambda_identifier(name_to_use))381    return optional_info;382 383  if (vtable_cu && !has_invoke) {384    lldb::FunctionSP func_sp =385        vtable_cu->FindFunction([name_to_use](const FunctionSP &f) {386          auto name = f->GetName().GetStringRef();387          if (name.starts_with(name_to_use) && name.contains("operator"))388            return true;389 390          return false;391        });392 393    if (func_sp) {394      calculate_symbol_context_helper(func_sp, scl);395    }396  }397 398  if (symbol == nullptr)399    return optional_info;400 401  // Case 1 or 3402  if (scl.GetSize() >= 1) {403    optional_info = line_entry_helper(target, scl[0], symbol,404                                      first_template_parameter, has_invoke);405  }406 407  CallableLookupCache[func_to_match] = optional_info;408 409  return optional_info;410}411 412lldb::ThreadPlanSP413CPPLanguageRuntime::GetStepThroughTrampolinePlan(Thread &thread,414                                                 bool stop_others) {415  ThreadPlanSP ret_plan_sp;416 417  lldb::addr_t curr_pc = thread.GetRegisterContext()->GetPC();418 419  TargetSP target_sp(thread.CalculateTarget());420 421  if (!target_sp->HasLoadedSections())422    return ret_plan_sp;423 424  Address pc_addr_resolved;425  SymbolContext sc;426  Symbol *symbol;427 428  if (!target_sp->ResolveLoadAddress(curr_pc, pc_addr_resolved))429    return ret_plan_sp;430 431  target_sp->GetImages().ResolveSymbolContextForAddress(432      pc_addr_resolved, eSymbolContextEverything, sc);433  symbol = sc.symbol;434 435  if (symbol == nullptr)436    return ret_plan_sp;437 438  llvm::StringRef function_name(symbol->GetName().GetCString());439 440  // Handling the case where we are attempting to step into std::function.441  // The behavior will be that we will attempt to obtain the wrapped442  // callable via FindLibCppStdFunctionCallableInfo() and if we find it we443  // will return a ThreadPlanRunToAddress to the callable. Therefore we will444  // step into the wrapped callable.445  //446  bool found_expected_start_string =447      function_name.starts_with("std::__1::function<");448 449  if (!found_expected_start_string)450    return ret_plan_sp;451 452  AddressRange range_of_curr_func;453  sc.GetAddressRange(eSymbolContextEverything, 0, false, range_of_curr_func);454 455  StackFrameSP frame = thread.GetStackFrameAtIndex(0);456 457  if (frame) {458    ValueObjectSP value_sp = frame->FindVariable(g_this);459 460    CPPLanguageRuntime::LibCppStdFunctionCallableInfo callable_info =461        FindLibCppStdFunctionCallableInfo(value_sp);462 463    if (callable_info.callable_case != LibCppStdFunctionCallableCase::Invalid &&464        value_sp->GetValueIsValid()) {465      // We found the std::function wrapped callable and we have its address.466      // We now create a ThreadPlan to run to the callable.467      ret_plan_sp = std::make_shared<ThreadPlanRunToAddress>(468          thread, callable_info.callable_address, stop_others);469      return ret_plan_sp;470    } else {471      // We are in std::function but we could not obtain the callable.472      // We create a ThreadPlan to keep stepping through using the address range473      // of the current function.474      ret_plan_sp = std::make_shared<ThreadPlanStepInRange>(475          thread, range_of_curr_func, sc, nullptr, eOnlyThisThread,476          eLazyBoolYes, eLazyBoolYes);477      return ret_plan_sp;478    }479  }480 481  return ret_plan_sp;482}483 484bool CPPLanguageRuntime::IsSymbolARuntimeThunk(const Symbol &symbol) {485  llvm::StringRef mangled_name =486      symbol.GetMangled().GetMangledName().GetStringRef();487  // Virtual function overriding from a non-virtual base use a "Th" prefix.488  // Virtual function overriding from a virtual base must use a "Tv" prefix.489  // Virtual function overriding thunks with covariant returns use a "Tc"490  // prefix.491  return mangled_name.starts_with("_ZTh") || mangled_name.starts_with("_ZTv") ||492         mangled_name.starts_with("_ZTc");493}494