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