brintos

brintos / llvm-project-archived public Read only

0
0
Text · 29.3 KiB · 8595f81 Raw
804 lines · cpp
1//===-- FormatManager.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 "lldb/DataFormatters/FormatManager.h"10 11#include "lldb/Core/Debugger.h"12#include "lldb/DataFormatters/FormattersHelpers.h"13#include "lldb/DataFormatters/LanguageCategory.h"14#include "lldb/Interpreter/ScriptInterpreter.h"15#include "lldb/Target/ExecutionContext.h"16#include "lldb/Target/Language.h"17#include "lldb/Utility/LLDBLog.h"18#include "lldb/Utility/Log.h"19#include "lldb/ValueObject/ValueObject.h"20#include "llvm/ADT/STLExtras.h"21 22using namespace lldb;23using namespace lldb_private;24using namespace lldb_private::formatters;25 26struct FormatInfo {27  Format format;28  const char format_char;  // One or more format characters that can be used for29                           // this format.30  const char *format_name; // Long format name that can be used to specify the31                           // current format32};33 34static constexpr FormatInfo g_format_infos[] = {35    {eFormatDefault, '\0', "default"},36    {eFormatBoolean, 'B', "boolean"},37    {eFormatBinary, 'b', "binary"},38    {eFormatBytes, 'y', "bytes"},39    {eFormatBytesWithASCII, 'Y', "bytes with ASCII"},40    {eFormatChar, 'c', "character"},41    {eFormatCharPrintable, 'C', "printable character"},42    {eFormatComplexFloat, 'F', "complex float"},43    {eFormatCString, 's', "c-string"},44    {eFormatDecimal, 'd', "decimal"},45    {eFormatEnum, 'E', "enumeration"},46    {eFormatHex, 'x', "hex"},47    {eFormatHexUppercase, 'X', "uppercase hex"},48    {eFormatFloat, 'f', "float"},49    {eFormatOctal, 'o', "octal"},50    {eFormatOSType, 'O', "OSType"},51    {eFormatUnicode16, 'U', "unicode16"},52    {eFormatUnicode32, '\0', "unicode32"},53    {eFormatUnsigned, 'u', "unsigned decimal"},54    {eFormatPointer, 'p', "pointer"},55    {eFormatVectorOfChar, '\0', "char[]"},56    {eFormatVectorOfSInt8, '\0', "int8_t[]"},57    {eFormatVectorOfUInt8, '\0', "uint8_t[]"},58    {eFormatVectorOfSInt16, '\0', "int16_t[]"},59    {eFormatVectorOfUInt16, '\0', "uint16_t[]"},60    {eFormatVectorOfSInt32, '\0', "int32_t[]"},61    {eFormatVectorOfUInt32, '\0', "uint32_t[]"},62    {eFormatVectorOfSInt64, '\0', "int64_t[]"},63    {eFormatVectorOfUInt64, '\0', "uint64_t[]"},64    {eFormatVectorOfFloat16, '\0', "float16[]"},65    {eFormatVectorOfFloat32, '\0', "float32[]"},66    {eFormatVectorOfFloat64, '\0', "float64[]"},67    {eFormatVectorOfUInt128, '\0', "uint128_t[]"},68    {eFormatComplexInteger, 'I', "complex integer"},69    {eFormatCharArray, 'a', "character array"},70    {eFormatAddressInfo, 'A', "address"},71    {eFormatHexFloat, '\0', "hex float"},72    {eFormatInstruction, 'i', "instruction"},73    {eFormatVoid, 'v', "void"},74    {eFormatUnicode8, 'u', "unicode8"},75    {eFormatFloat128, '\0', "float128"},76};77 78static_assert((sizeof(g_format_infos) / sizeof(g_format_infos[0])) ==79                  kNumFormats,80              "All formats must have a corresponding info entry.");81 82static uint32_t g_num_format_infos = std::size(g_format_infos);83 84static bool GetFormatFromFormatChar(char format_char, Format &format) {85  for (uint32_t i = 0; i < g_num_format_infos; ++i) {86    if (g_format_infos[i].format_char == format_char) {87      format = g_format_infos[i].format;88      return true;89    }90  }91  format = eFormatInvalid;92  return false;93}94 95static bool GetFormatFromFormatName(llvm::StringRef format_name,96                                    Format &format) {97  uint32_t i;98  for (i = 0; i < g_num_format_infos; ++i) {99    if (format_name.equals_insensitive(g_format_infos[i].format_name)) {100      format = g_format_infos[i].format;101      return true;102    }103  }104 105  for (i = 0; i < g_num_format_infos; ++i) {106    if (llvm::StringRef(g_format_infos[i].format_name)107            .starts_with_insensitive(format_name)) {108      format = g_format_infos[i].format;109      return true;110    }111  }112  format = eFormatInvalid;113  return false;114}115 116void FormatManager::Changed() {117  ++m_last_revision;118  m_format_cache.Clear();119  std::lock_guard<std::recursive_mutex> guard(m_language_categories_mutex);120  for (auto &iter : m_language_categories_map) {121    if (iter.second)122      iter.second->GetFormatCache().Clear();123  }124}125 126bool FormatManager::GetFormatFromCString(const char *format_cstr,127                                         lldb::Format &format) {128  bool success = false;129  if (format_cstr && format_cstr[0]) {130    if (format_cstr[1] == '\0') {131      success = GetFormatFromFormatChar(format_cstr[0], format);132      if (success)133        return true;134    }135 136    success = GetFormatFromFormatName(format_cstr, format);137  }138  if (!success)139    format = eFormatInvalid;140  return success;141}142 143char FormatManager::GetFormatAsFormatChar(lldb::Format format) {144  for (uint32_t i = 0; i < g_num_format_infos; ++i) {145    if (g_format_infos[i].format == format)146      return g_format_infos[i].format_char;147  }148  return '\0';149}150 151const char *FormatManager::GetFormatAsCString(Format format) {152  if (format >= eFormatDefault && format < kNumFormats)153    return g_format_infos[format].format_name;154  return nullptr;155}156 157void FormatManager::EnableAllCategories() {158  m_categories_map.EnableAllCategories();159  std::lock_guard<std::recursive_mutex> guard(m_language_categories_mutex);160  for (auto &iter : m_language_categories_map) {161    if (iter.second)162      iter.second->Enable();163  }164}165 166void FormatManager::DisableAllCategories() {167  m_categories_map.DisableAllCategories();168  std::lock_guard<std::recursive_mutex> guard(m_language_categories_mutex);169  for (auto &iter : m_language_categories_map) {170    if (iter.second)171      iter.second->Disable();172  }173}174 175void FormatManager::GetPossibleMatches(176    ValueObject &valobj, CompilerType compiler_type,177    lldb::DynamicValueType use_dynamic, FormattersMatchVector &entries,178    FormattersMatchCandidate::Flags current_flags, bool root_level,179    uint32_t ptr_stripped_depth) {180  compiler_type = compiler_type.GetTypeForFormatters();181  ConstString type_name(compiler_type.GetTypeName());182  // A ValueObject that couldn't be made correctly won't necessarily have a183  // target.  We aren't going to find a formatter in this case anyway, so we184  // should just exit.185  TargetSP target_sp = valobj.GetTargetSP();186  if (!target_sp)187    return;188  ScriptInterpreter *script_interpreter =189      target_sp->GetDebugger().GetScriptInterpreter();190  if (valobj.GetBitfieldBitSize() > 0) {191    StreamString sstring;192    sstring.Printf("%s:%d", type_name.AsCString(), valobj.GetBitfieldBitSize());193    ConstString bitfieldname(sstring.GetString());194    entries.push_back({bitfieldname, script_interpreter,195                       TypeImpl(compiler_type), current_flags,196                       ptr_stripped_depth});197  }198 199  if (!compiler_type.IsMeaninglessWithoutDynamicResolution()) {200    entries.push_back({type_name, script_interpreter, TypeImpl(compiler_type),201                       current_flags, ptr_stripped_depth});202 203    ConstString display_type_name(compiler_type.GetTypeName());204    if (display_type_name != type_name)205      entries.push_back({display_type_name, script_interpreter,206                         TypeImpl(compiler_type), current_flags,207                         ptr_stripped_depth});208  }209 210  for (bool is_rvalue_ref = true, j = true;211       j && compiler_type.IsReferenceType(nullptr, &is_rvalue_ref); j = false) {212    CompilerType non_ref_type = compiler_type.GetNonReferenceType();213    GetPossibleMatches(valobj, non_ref_type, use_dynamic, entries,214                       current_flags.WithStrippedReference(), root_level,215                       ptr_stripped_depth);216    if (non_ref_type.IsTypedefType()) {217      CompilerType deffed_referenced_type = non_ref_type.GetTypedefedType();218      deffed_referenced_type =219          is_rvalue_ref ? deffed_referenced_type.GetRValueReferenceType()220                        : deffed_referenced_type.GetLValueReferenceType();221      // this is not exactly the usual meaning of stripping typedefs222      GetPossibleMatches(valobj, deffed_referenced_type, use_dynamic, entries,223                         current_flags.WithStrippedTypedef(), root_level,224                         ptr_stripped_depth);225    }226  }227 228  if (compiler_type.IsPointerType()) {229    CompilerType non_ptr_type = compiler_type.GetPointeeType();230    GetPossibleMatches(valobj, non_ptr_type, use_dynamic, entries,231                       current_flags.WithStrippedPointer(), root_level,232                       ptr_stripped_depth + 1);233    if (non_ptr_type.IsTypedefType()) {234      CompilerType deffed_pointed_type =235          non_ptr_type.GetTypedefedType().GetPointerType();236      // this is not exactly the usual meaning of stripping typedefs237      GetPossibleMatches(valobj, deffed_pointed_type, use_dynamic, entries,238                         current_flags.WithStrippedTypedef(), root_level,239                         ptr_stripped_depth + 1);240    }241  }242 243  // For arrays with typedef-ed elements, we add a candidate with the typedef244  // stripped.245  uint64_t array_size;246  if (compiler_type.IsArrayType(nullptr, &array_size, nullptr)) {247    ExecutionContext exe_ctx(valobj.GetExecutionContextRef());248    CompilerType element_type = compiler_type.GetArrayElementType(249        exe_ctx.GetBestExecutionContextScope());250    if (element_type.IsTypedefType()) {251      // Get the stripped element type and compute the stripped array type252      // from it.253      CompilerType deffed_array_type =254          element_type.GetTypedefedType().GetArrayType(array_size);255      // this is not exactly the usual meaning of stripping typedefs256      GetPossibleMatches(valobj, deffed_array_type, use_dynamic, entries,257                         current_flags.WithStrippedTypedef(), root_level,258                         ptr_stripped_depth);259    }260  }261 262  for (lldb::LanguageType language_type :263       GetCandidateLanguages(valobj.GetObjectRuntimeLanguage())) {264    if (Language *language = Language::FindPlugin(language_type)) {265      for (const FormattersMatchCandidate& candidate :266           language->GetPossibleFormattersMatches(valobj, use_dynamic)) {267        entries.push_back(candidate);268      }269    }270  }271 272  // try to strip typedef chains273  if (compiler_type.IsTypedefType()) {274    CompilerType deffed_type = compiler_type.GetTypedefedType();275    GetPossibleMatches(valobj, deffed_type, use_dynamic, entries,276                       current_flags.WithStrippedTypedef(), root_level,277                       ptr_stripped_depth);278  }279 280  if (root_level) {281    do {282      if (!compiler_type.IsValid())283        break;284 285      CompilerType unqual_compiler_ast_type =286          compiler_type.GetFullyUnqualifiedType();287      if (!unqual_compiler_ast_type.IsValid())288        break;289      if (unqual_compiler_ast_type.GetOpaqueQualType() !=290          compiler_type.GetOpaqueQualType())291        GetPossibleMatches(valobj, unqual_compiler_ast_type, use_dynamic,292                           entries, current_flags, root_level,293                           ptr_stripped_depth);294    } while (false);295 296    // if all else fails, go to static type297    if (valobj.IsDynamic()) {298      lldb::ValueObjectSP static_value_sp(valobj.GetStaticValue());299      if (static_value_sp)300        GetPossibleMatches(*static_value_sp.get(),301                           static_value_sp->GetCompilerType(), use_dynamic,302                           entries, current_flags, true, ptr_stripped_depth);303    }304  }305}306 307lldb::TypeFormatImplSP308FormatManager::GetFormatForType(lldb::TypeNameSpecifierImplSP type_sp) {309  if (!type_sp)310    return lldb::TypeFormatImplSP();311  lldb::TypeFormatImplSP format_chosen_sp;312  uint32_t num_categories = m_categories_map.GetCount();313  lldb::TypeCategoryImplSP category_sp;314  uint32_t prio_category = UINT32_MAX;315  for (uint32_t category_id = 0; category_id < num_categories; category_id++) {316    category_sp = GetCategoryAtIndex(category_id);317    if (!category_sp->IsEnabled())318      continue;319    lldb::TypeFormatImplSP format_current_sp =320        category_sp->GetFormatForType(type_sp);321    if (format_current_sp &&322        (format_chosen_sp.get() == nullptr ||323         (prio_category > category_sp->GetEnabledPosition()))) {324      prio_category = category_sp->GetEnabledPosition();325      format_chosen_sp = format_current_sp;326    }327  }328  return format_chosen_sp;329}330 331lldb::TypeSummaryImplSP332FormatManager::GetSummaryForType(lldb::TypeNameSpecifierImplSP type_sp) {333  if (!type_sp)334    return lldb::TypeSummaryImplSP();335  lldb::TypeSummaryImplSP summary_chosen_sp;336  uint32_t num_categories = m_categories_map.GetCount();337  lldb::TypeCategoryImplSP category_sp;338  uint32_t prio_category = UINT32_MAX;339  for (uint32_t category_id = 0; category_id < num_categories; category_id++) {340    category_sp = GetCategoryAtIndex(category_id);341    if (!category_sp->IsEnabled())342      continue;343    lldb::TypeSummaryImplSP summary_current_sp =344        category_sp->GetSummaryForType(type_sp);345    if (summary_current_sp &&346        (summary_chosen_sp.get() == nullptr ||347         (prio_category > category_sp->GetEnabledPosition()))) {348      prio_category = category_sp->GetEnabledPosition();349      summary_chosen_sp = summary_current_sp;350    }351  }352  return summary_chosen_sp;353}354 355lldb::TypeFilterImplSP356FormatManager::GetFilterForType(lldb::TypeNameSpecifierImplSP type_sp) {357  if (!type_sp)358    return lldb::TypeFilterImplSP();359  lldb::TypeFilterImplSP filter_chosen_sp;360  uint32_t num_categories = m_categories_map.GetCount();361  lldb::TypeCategoryImplSP category_sp;362  uint32_t prio_category = UINT32_MAX;363  for (uint32_t category_id = 0; category_id < num_categories; category_id++) {364    category_sp = GetCategoryAtIndex(category_id);365    if (!category_sp->IsEnabled())366      continue;367    lldb::TypeFilterImplSP filter_current_sp(368        (TypeFilterImpl *)category_sp->GetFilterForType(type_sp).get());369    if (filter_current_sp &&370        (filter_chosen_sp.get() == nullptr ||371         (prio_category > category_sp->GetEnabledPosition()))) {372      prio_category = category_sp->GetEnabledPosition();373      filter_chosen_sp = filter_current_sp;374    }375  }376  return filter_chosen_sp;377}378 379lldb::ScriptedSyntheticChildrenSP380FormatManager::GetSyntheticForType(lldb::TypeNameSpecifierImplSP type_sp) {381  if (!type_sp)382    return lldb::ScriptedSyntheticChildrenSP();383  lldb::ScriptedSyntheticChildrenSP synth_chosen_sp;384  uint32_t num_categories = m_categories_map.GetCount();385  lldb::TypeCategoryImplSP category_sp;386  uint32_t prio_category = UINT32_MAX;387  for (uint32_t category_id = 0; category_id < num_categories; category_id++) {388    category_sp = GetCategoryAtIndex(category_id);389    if (!category_sp->IsEnabled())390      continue;391    lldb::ScriptedSyntheticChildrenSP synth_current_sp(392        (ScriptedSyntheticChildren *)category_sp->GetSyntheticForType(type_sp)393            .get());394    if (synth_current_sp &&395        (synth_chosen_sp.get() == nullptr ||396         (prio_category > category_sp->GetEnabledPosition()))) {397      prio_category = category_sp->GetEnabledPosition();398      synth_chosen_sp = synth_current_sp;399    }400  }401  return synth_chosen_sp;402}403 404void FormatManager::ForEachCategory(TypeCategoryMap::ForEachCallback callback) {405  m_categories_map.ForEach(callback);406  std::lock_guard<std::recursive_mutex> guard(m_language_categories_mutex);407  for (const auto &entry : m_language_categories_map) {408    if (auto category_sp = entry.second->GetCategory()) {409      if (!callback(category_sp))410        break;411    }412  }413}414 415lldb::TypeCategoryImplSP416FormatManager::GetCategory(ConstString category_name, bool can_create) {417  if (!category_name)418    return GetCategory(m_default_category_name);419  lldb::TypeCategoryImplSP category;420  if (m_categories_map.Get(category_name, category))421    return category;422 423  if (!can_create)424    return lldb::TypeCategoryImplSP();425 426  m_categories_map.Add(category_name,427                       std::make_shared<TypeCategoryImpl>(this, category_name));428  return GetCategory(category_name);429}430 431lldb::Format FormatManager::GetSingleItemFormat(lldb::Format vector_format) {432  switch (vector_format) {433  case eFormatVectorOfChar:434    return eFormatCharArray;435 436  case eFormatVectorOfSInt8:437  case eFormatVectorOfSInt16:438  case eFormatVectorOfSInt32:439  case eFormatVectorOfSInt64:440    return eFormatDecimal;441 442  case eFormatVectorOfUInt8:443  case eFormatVectorOfUInt16:444  case eFormatVectorOfUInt32:445  case eFormatVectorOfUInt64:446  case eFormatVectorOfUInt128:447    return eFormatHex;448 449  case eFormatVectorOfFloat16:450  case eFormatVectorOfFloat32:451  case eFormatVectorOfFloat64:452    return eFormatFloat;453 454  default:455    return lldb::eFormatInvalid;456  }457}458 459bool FormatManager::ShouldPrintAsOneLiner(ValueObject &valobj) {460  TargetSP target_sp = valobj.GetTargetSP();461  // if settings say no oneline whatsoever462  if (target_sp && !target_sp->GetDebugger().GetAutoOneLineSummaries())463    return false; // then don't oneline464 465  // if this object has a summary, then ask the summary466  if (valobj.GetSummaryFormat().get() != nullptr)467    return valobj.GetSummaryFormat()->IsOneLiner();468 469  const size_t max_num_children =470      (target_sp ? *target_sp : Target::GetGlobalProperties())471          .GetMaximumNumberOfChildrenToDisplay();472  auto num_children = valobj.GetNumChildren(max_num_children);473  if (!num_children) {474    llvm::consumeError(num_children.takeError());475    return true;476  }477  // no children, no party478  if (*num_children == 0)479    return false;480 481  // ask the type if it has any opinion about this eLazyBoolCalculate == no482  // opinion; other values should be self explanatory483  CompilerType compiler_type(valobj.GetCompilerType());484  if (compiler_type.IsValid()) {485    switch (compiler_type.ShouldPrintAsOneLiner(&valobj)) {486    case eLazyBoolNo:487      return false;488    case eLazyBoolYes:489      return true;490    case eLazyBoolCalculate:491      break;492    }493  }494 495  size_t total_children_name_len = 0;496 497  for (size_t idx = 0; idx < *num_children; idx++) {498    bool is_synth_val = false;499    ValueObjectSP child_sp(valobj.GetChildAtIndex(idx));500    // something is wrong here - bail out501    if (!child_sp)502      return false;503 504    // also ask the child's type if it has any opinion505    CompilerType child_compiler_type(child_sp->GetCompilerType());506    if (child_compiler_type.IsValid()) {507      switch (child_compiler_type.ShouldPrintAsOneLiner(child_sp.get())) {508      case eLazyBoolYes:509      // an opinion of yes is only binding for the child, so keep going510      case eLazyBoolCalculate:511        break;512      case eLazyBoolNo:513        // but if the child says no, then it's a veto on the whole thing514        return false;515      }516    }517 518    // if we decided to define synthetic children for a type, we probably care519    // enough to show them, but avoid nesting children in children520    if (child_sp->GetSyntheticChildren().get() != nullptr) {521      ValueObjectSP synth_sp(child_sp->GetSyntheticValue());522      // wait.. wat? just get out of here..523      if (!synth_sp)524        return false;525      // but if we only have them to provide a value, keep going526      if (!synth_sp->MightHaveChildren() &&527          synth_sp->DoesProvideSyntheticValue())528        is_synth_val = true;529      else530        return false;531    }532 533    total_children_name_len += child_sp->GetName().GetLength();534 535    // 50 itself is a "randomly" chosen number - the idea is that536    // overly long structs should not get this treatment537    // FIXME: maybe make this a user-tweakable setting?538    if (total_children_name_len > 50)539      return false;540 541    // if a summary is there..542    if (child_sp->GetSummaryFormat()) {543      // and it wants children, then bail out544      if (child_sp->GetSummaryFormat()->DoesPrintChildren(child_sp.get()))545        return false;546    }547 548    // if this child has children..549    if (child_sp->HasChildren()) {550      // ...and no summary...551      // (if it had a summary and the summary wanted children, we would have552      // bailed out anyway553      //  so this only makes us bail out if this has no summary and we would554      //  then print children)555      if (!child_sp->GetSummaryFormat() && !is_synth_val) // but again only do556                                                          // that if not a557                                                          // synthetic valued558                                                          // child559        return false;                                     // then bail out560    }561  }562  return true;563}564 565ConstString FormatManager::GetTypeForCache(ValueObject &valobj,566                                           lldb::DynamicValueType use_dynamic) {567  ValueObjectSP valobj_sp = valobj.GetQualifiedRepresentationIfAvailable(568      use_dynamic, valobj.IsSynthetic());569  if (valobj_sp && valobj_sp->GetCompilerType().IsValid()) {570    if (!valobj_sp->GetCompilerType().IsMeaninglessWithoutDynamicResolution())571      return valobj_sp->GetQualifiedTypeName();572  }573  return ConstString();574}575 576std::vector<lldb::LanguageType>577FormatManager::GetCandidateLanguages(lldb::LanguageType lang_type) {578  switch (lang_type) {579  case lldb::eLanguageTypeC:580  case lldb::eLanguageTypeC89:581  case lldb::eLanguageTypeC99:582  case lldb::eLanguageTypeC11:583  case lldb::eLanguageTypeC_plus_plus:584  case lldb::eLanguageTypeC_plus_plus_03:585  case lldb::eLanguageTypeC_plus_plus_11:586  case lldb::eLanguageTypeC_plus_plus_14:587    return {lldb::eLanguageTypeC_plus_plus, lldb::eLanguageTypeObjC};588  default:589    return {lang_type};590  }591  llvm_unreachable("Fully covered switch");592}593 594LanguageCategory *595FormatManager::GetCategoryForLanguage(lldb::LanguageType lang_type) {596  std::lock_guard<std::recursive_mutex> guard(m_language_categories_mutex);597  auto iter = m_language_categories_map.find(lang_type),598       end = m_language_categories_map.end();599  if (iter != end)600    return iter->second.get();601  LanguageCategory *lang_category = new LanguageCategory(lang_type);602  m_language_categories_map[lang_type] =603      LanguageCategory::UniquePointer(lang_category);604  return lang_category;605}606 607template <typename ImplSP>608ImplSP FormatManager::GetHardcoded(FormattersMatchData &match_data) {609  ImplSP retval_sp;610  for (lldb::LanguageType lang_type : match_data.GetCandidateLanguages()) {611    if (LanguageCategory *lang_category = GetCategoryForLanguage(lang_type)) {612      if (lang_category->GetHardcoded(*this, match_data, retval_sp))613        return retval_sp;614    }615  }616  return retval_sp;617}618 619namespace {620template <typename ImplSP> const char *FormatterKind;621template <> const char *FormatterKind<lldb::TypeFormatImplSP> = "format";622template <> const char *FormatterKind<lldb::TypeSummaryImplSP> = "summary";623template <> const char *FormatterKind<lldb::SyntheticChildrenSP> = "synthetic";624} // namespace625 626#define FORMAT_LOG(Message) "[%s] " Message, FormatterKind<ImplSP>627 628template <typename ImplSP>629ImplSP FormatManager::Get(ValueObject &valobj,630                          lldb::DynamicValueType use_dynamic) {631  FormattersMatchData match_data(valobj, use_dynamic);632  if (ImplSP retval_sp = GetCached<ImplSP>(match_data))633    return retval_sp;634 635  Log *log = GetLog(LLDBLog::DataFormatters);636 637  LLDB_LOGF(log, FORMAT_LOG("Search failed. Giving language a chance."));638  for (lldb::LanguageType lang_type : match_data.GetCandidateLanguages()) {639    if (LanguageCategory *lang_category = GetCategoryForLanguage(lang_type)) {640      ImplSP retval_sp;641      if (lang_category->Get(match_data, retval_sp))642        if (retval_sp) {643          LLDB_LOGF(log, FORMAT_LOG("Language search success. Returning."));644          return retval_sp;645        }646    }647  }648 649  LLDB_LOGF(log, FORMAT_LOG("Search failed. Giving hardcoded a chance."));650  return GetHardcoded<ImplSP>(match_data);651}652 653template <typename ImplSP>654ImplSP FormatManager::GetCached(FormattersMatchData &match_data) {655  ImplSP retval_sp;656  Log *log = GetLog(LLDBLog::DataFormatters);657  if (match_data.GetTypeForCache()) {658    LLDB_LOGF(log, "\n\n" FORMAT_LOG("Looking into cache for type %s"),659              match_data.GetTypeForCache().AsCString("<invalid>"));660    if (m_format_cache.Get(match_data.GetTypeForCache(), retval_sp)) {661      if (log) {662        LLDB_LOGF(log, FORMAT_LOG("Cache search success. Returning."));663        LLDB_LOGV(log, "Cache hits: {0} - Cache Misses: {1}",664                  m_format_cache.GetCacheHits(),665                  m_format_cache.GetCacheMisses());666      }667      return retval_sp;668    }669    LLDB_LOGF(log, FORMAT_LOG("Cache search failed. Going normal route"));670  }671 672  m_categories_map.Get(match_data, retval_sp);673  if (match_data.GetTypeForCache() && (!retval_sp || !retval_sp->NonCacheable())) {674    LLDB_LOGF(log, FORMAT_LOG("Caching %p for type %s"),675              static_cast<void *>(retval_sp.get()),676              match_data.GetTypeForCache().AsCString("<invalid>"));677    m_format_cache.Set(match_data.GetTypeForCache(), retval_sp);678  }679  LLDB_LOGV(log, "Cache hits: {0} - Cache Misses: {1}",680            m_format_cache.GetCacheHits(), m_format_cache.GetCacheMisses());681  return retval_sp;682}683 684#undef FORMAT_LOG685 686lldb::TypeFormatImplSP687FormatManager::GetFormat(ValueObject &valobj,688                         lldb::DynamicValueType use_dynamic) {689  return Get<lldb::TypeFormatImplSP>(valobj, use_dynamic);690}691 692lldb::TypeSummaryImplSP693FormatManager::GetSummaryFormat(ValueObject &valobj,694                                lldb::DynamicValueType use_dynamic) {695  return Get<lldb::TypeSummaryImplSP>(valobj, use_dynamic);696}697 698lldb::SyntheticChildrenSP699FormatManager::GetSyntheticChildren(ValueObject &valobj,700                                    lldb::DynamicValueType use_dynamic) {701  return Get<lldb::SyntheticChildrenSP>(valobj, use_dynamic);702}703 704FormatManager::FormatManager()705    : m_last_revision(0), m_format_cache(), m_language_categories_mutex(),706      m_language_categories_map(), m_named_summaries_map(this),707      m_categories_map(this), m_default_category_name(ConstString("default")),708      m_system_category_name(ConstString("system")),709      m_vectortypes_category_name(ConstString("VectorTypes")) {710  LoadSystemFormatters();711  LoadVectorFormatters();712 713  EnableCategory(m_vectortypes_category_name, TypeCategoryMap::Last,714                 lldb::eLanguageTypeObjC_plus_plus);715  EnableCategory(m_system_category_name, TypeCategoryMap::Last,716                 lldb::eLanguageTypeObjC_plus_plus);717}718 719void FormatManager::LoadSystemFormatters() {720  TypeSummaryImpl::Flags string_flags;721  string_flags.SetCascades(true)722      .SetSkipPointers(true)723      .SetSkipReferences(false)724      .SetDontShowChildren(true)725      .SetDontShowValue(false)726      .SetShowMembersOneLiner(false)727      .SetHideItemNames(false);728 729  TypeSummaryImpl::Flags string_array_flags;730  string_array_flags.SetCascades(true)731      .SetSkipPointers(true)732      .SetSkipReferences(false)733      .SetDontShowChildren(true)734      .SetDontShowValue(true)735      .SetShowMembersOneLiner(false)736      .SetHideItemNames(false);737 738  lldb::TypeSummaryImplSP string_format(739      new StringSummaryFormat(string_flags, "${var%s}"));740 741  lldb::TypeSummaryImplSP string_array_format(742      new StringSummaryFormat(string_array_flags, "${var%char[]}"));743 744  TypeCategoryImpl::SharedPointer sys_category_sp =745      GetCategory(m_system_category_name);746 747  sys_category_sp->AddTypeSummary(R"(^(unsigned )?char ?(\*|\[\])$)",748                                  eFormatterMatchRegex, string_format);749 750  sys_category_sp->AddTypeSummary(R"(^((un)?signed )?char ?\[[0-9]+\]$)",751                                  eFormatterMatchRegex, string_array_format);752 753  lldb::TypeSummaryImplSP ostype_summary(754      new StringSummaryFormat(TypeSummaryImpl::Flags()755                                  .SetCascades(false)756                                  .SetSkipPointers(true)757                                  .SetSkipReferences(true)758                                  .SetDontShowChildren(true)759                                  .SetDontShowValue(false)760                                  .SetShowMembersOneLiner(false)761                                  .SetHideItemNames(false),762                              "${var%O}"));763 764  sys_category_sp->AddTypeSummary("OSType", eFormatterMatchExact,765                                  ostype_summary);766 767  TypeFormatImpl::Flags fourchar_flags;768  fourchar_flags.SetCascades(true).SetSkipPointers(true).SetSkipReferences(769      true);770 771  AddFormat(sys_category_sp, lldb::eFormatOSType, "FourCharCode",772            fourchar_flags);773}774 775void FormatManager::LoadVectorFormatters() {776  TypeCategoryImpl::SharedPointer vectors_category_sp =777      GetCategory(m_vectortypes_category_name);778 779  TypeSummaryImpl::Flags vector_flags;780  vector_flags.SetCascades(true)781      .SetSkipPointers(true)782      .SetSkipReferences(false)783      .SetDontShowChildren(true)784      .SetDontShowValue(false)785      .SetShowMembersOneLiner(true)786      .SetHideItemNames(true);787 788  AddStringSummary(vectors_category_sp, "${var.uint128}", "builtin_type_vec128",789                   vector_flags);790  AddStringSummary(vectors_category_sp, "", "float[4]", vector_flags);791  AddStringSummary(vectors_category_sp, "", "int32_t[4]", vector_flags);792  AddStringSummary(vectors_category_sp, "", "int16_t[8]", vector_flags);793  AddStringSummary(vectors_category_sp, "", "vDouble", vector_flags);794  AddStringSummary(vectors_category_sp, "", "vFloat", vector_flags);795  AddStringSummary(vectors_category_sp, "", "vSInt8", vector_flags);796  AddStringSummary(vectors_category_sp, "", "vSInt16", vector_flags);797  AddStringSummary(vectors_category_sp, "", "vSInt32", vector_flags);798  AddStringSummary(vectors_category_sp, "", "vUInt16", vector_flags);799  AddStringSummary(vectors_category_sp, "", "vUInt8", vector_flags);800  AddStringSummary(vectors_category_sp, "", "vUInt16", vector_flags);801  AddStringSummary(vectors_category_sp, "", "vUInt32", vector_flags);802  AddStringSummary(vectors_category_sp, "", "vBool32", vector_flags);803}804