xref: /llvm-project/lldb/source/DataFormatters/FormatManager.cpp (revision b31f60b9c2e7cc452d9600e1014d42822a2cd7c6)
1 //===-- FormatManager.cpp ----------------------------------------*- C++-*-===//
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 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 
74 static uint32_t g_num_format_infos = llvm::array_lengthof(g_format_infos);
75 
76 static bool GetFormatFromFormatChar(char format_char, Format &format) {
77   for (uint32_t i = 0; i < g_num_format_infos; ++i) {
78     if (g_format_infos[i].format_char == format_char) {
79       format = g_format_infos[i].format;
80       return true;
81     }
82   }
83   format = eFormatInvalid;
84   return false;
85 }
86 
87 static bool GetFormatFromFormatName(const char *format_name,
88                                     bool partial_match_ok, Format &format) {
89   uint32_t i;
90   for (i = 0; i < g_num_format_infos; ++i) {
91     if (strcasecmp(g_format_infos[i].format_name, format_name) == 0) {
92       format = g_format_infos[i].format;
93       return true;
94     }
95   }
96 
97   if (partial_match_ok) {
98     for (i = 0; i < g_num_format_infos; ++i) {
99       if (strcasestr(g_format_infos[i].format_name, format_name) ==
100           g_format_infos[i].format_name) {
101         format = g_format_infos[i].format;
102         return true;
103       }
104     }
105   }
106   format = eFormatInvalid;
107   return false;
108 }
109 
110 void FormatManager::Changed() {
111   ++m_last_revision;
112   m_format_cache.Clear();
113   std::lock_guard<std::recursive_mutex> guard(m_language_categories_mutex);
114   for (auto &iter : m_language_categories_map) {
115     if (iter.second)
116       iter.second->GetFormatCache().Clear();
117   }
118 }
119 
120 bool FormatManager::GetFormatFromCString(const char *format_cstr,
121                                          bool partial_match_ok,
122                                          lldb::Format &format) {
123   bool success = false;
124   if (format_cstr && format_cstr[0]) {
125     if (format_cstr[1] == '\0') {
126       success = GetFormatFromFormatChar(format_cstr[0], format);
127       if (success)
128         return true;
129     }
130 
131     success = GetFormatFromFormatName(format_cstr, partial_match_ok, format);
132   }
133   if (!success)
134     format = eFormatInvalid;
135   return success;
136 }
137 
138 char FormatManager::GetFormatAsFormatChar(lldb::Format format) {
139   for (uint32_t i = 0; i < g_num_format_infos; ++i) {
140     if (g_format_infos[i].format == format)
141       return g_format_infos[i].format_char;
142   }
143   return '\0';
144 }
145 
146 const char *FormatManager::GetFormatAsCString(Format format) {
147   if (format >= eFormatDefault && format < kNumFormats)
148     return g_format_infos[format].format_name;
149   return nullptr;
150 }
151 
152 void FormatManager::EnableAllCategories() {
153   m_categories_map.EnableAllCategories();
154   std::lock_guard<std::recursive_mutex> guard(m_language_categories_mutex);
155   for (auto &iter : m_language_categories_map) {
156     if (iter.second)
157       iter.second->Enable();
158   }
159 }
160 
161 void FormatManager::DisableAllCategories() {
162   m_categories_map.DisableAllCategories();
163   std::lock_guard<std::recursive_mutex> guard(m_language_categories_mutex);
164   for (auto &iter : m_language_categories_map) {
165     if (iter.second)
166       iter.second->Disable();
167   }
168 }
169 
170 void FormatManager::GetPossibleMatches(
171     ValueObject &valobj, CompilerType compiler_type, uint32_t reason,
172     lldb::DynamicValueType use_dynamic, FormattersMatchVector &entries,
173     bool did_strip_ptr, bool did_strip_ref, bool did_strip_typedef,
174     bool root_level) {
175   compiler_type = compiler_type.GetTypeForFormatters();
176   ConstString type_name(compiler_type.GetConstTypeName());
177   if (valobj.GetBitfieldBitSize() > 0) {
178     StreamString sstring;
179     sstring.Printf("%s:%d", type_name.AsCString(), valobj.GetBitfieldBitSize());
180     ConstString bitfieldname(sstring.GetString());
181     entries.push_back(
182         {bitfieldname, 0, did_strip_ptr, did_strip_ref, did_strip_typedef});
183     reason |= lldb_private::eFormatterChoiceCriterionStrippedBitField;
184   }
185 
186   entries.push_back(
187       {type_name, reason, did_strip_ptr, did_strip_ref, did_strip_typedef});
188 
189   ConstString display_type_name(compiler_type.GetDisplayTypeName());
190   if (display_type_name != type_name)
191     entries.push_back({display_type_name, reason, did_strip_ptr, did_strip_ref,
192                        did_strip_typedef});
193 
194   for (bool is_rvalue_ref = true, j = true;
195        j && compiler_type.IsReferenceType(nullptr, &is_rvalue_ref); j = false) {
196     CompilerType non_ref_type = compiler_type.GetNonReferenceType();
197     GetPossibleMatches(
198         valobj, non_ref_type,
199         reason |
200             lldb_private::eFormatterChoiceCriterionStrippedPointerReference,
201         use_dynamic, entries, did_strip_ptr, true, did_strip_typedef);
202     if (non_ref_type.IsTypedefType()) {
203       CompilerType deffed_referenced_type = non_ref_type.GetTypedefedType();
204       deffed_referenced_type =
205           is_rvalue_ref ? deffed_referenced_type.GetRValueReferenceType()
206                         : deffed_referenced_type.GetLValueReferenceType();
207       GetPossibleMatches(
208           valobj, deffed_referenced_type,
209           reason | lldb_private::eFormatterChoiceCriterionNavigatedTypedefs,
210           use_dynamic, entries, did_strip_ptr, did_strip_ref,
211           true); // this is not exactly the usual meaning of stripping typedefs
212     }
213   }
214 
215   if (compiler_type.IsPointerType()) {
216     CompilerType non_ptr_type = compiler_type.GetPointeeType();
217     GetPossibleMatches(
218         valobj, non_ptr_type,
219         reason |
220             lldb_private::eFormatterChoiceCriterionStrippedPointerReference,
221         use_dynamic, entries, true, did_strip_ref, did_strip_typedef);
222     if (non_ptr_type.IsTypedefType()) {
223       CompilerType deffed_pointed_type =
224           non_ptr_type.GetTypedefedType().GetPointerType();
225       GetPossibleMatches(
226           valobj, deffed_pointed_type,
227           reason | lldb_private::eFormatterChoiceCriterionNavigatedTypedefs,
228           use_dynamic, entries, did_strip_ptr, did_strip_ref,
229           true); // this is not exactly the usual meaning of stripping typedefs
230     }
231   }
232 
233   for (lldb::LanguageType language_type : GetCandidateLanguages(valobj)) {
234     if (Language *language = Language::FindPlugin(language_type)) {
235       for (ConstString candidate :
236            language->GetPossibleFormattersMatches(valobj, use_dynamic)) {
237         entries.push_back(
238             {candidate,
239              reason | lldb_private::eFormatterChoiceCriterionLanguagePlugin,
240              did_strip_ptr, did_strip_ref, did_strip_typedef});
241       }
242     }
243   }
244 
245   // try to strip typedef chains
246   if (compiler_type.IsTypedefType()) {
247     CompilerType deffed_type = compiler_type.GetTypedefedType();
248     GetPossibleMatches(
249         valobj, deffed_type,
250         reason | lldb_private::eFormatterChoiceCriterionNavigatedTypedefs,
251         use_dynamic, entries, did_strip_ptr, did_strip_ref, true);
252   }
253 
254   if (root_level) {
255     do {
256       if (!compiler_type.IsValid())
257         break;
258 
259       CompilerType unqual_compiler_ast_type =
260           compiler_type.GetFullyUnqualifiedType();
261       if (!unqual_compiler_ast_type.IsValid())
262         break;
263       if (unqual_compiler_ast_type.GetOpaqueQualType() !=
264           compiler_type.GetOpaqueQualType())
265         GetPossibleMatches(valobj, unqual_compiler_ast_type, reason,
266                            use_dynamic, entries, did_strip_ptr, did_strip_ref,
267                            did_strip_typedef);
268     } while (false);
269 
270     // if all else fails, go to static type
271     if (valobj.IsDynamic()) {
272       lldb::ValueObjectSP static_value_sp(valobj.GetStaticValue());
273       if (static_value_sp)
274         GetPossibleMatches(
275             *static_value_sp.get(), static_value_sp->GetCompilerType(),
276             reason | lldb_private::eFormatterChoiceCriterionWentToStaticValue,
277             use_dynamic, entries, did_strip_ptr, did_strip_ref,
278             did_strip_typedef, true);
279     }
280   }
281 }
282 
283 lldb::TypeFormatImplSP
284 FormatManager::GetFormatForType(lldb::TypeNameSpecifierImplSP type_sp) {
285   if (!type_sp)
286     return lldb::TypeFormatImplSP();
287   lldb::TypeFormatImplSP format_chosen_sp;
288   uint32_t num_categories = m_categories_map.GetCount();
289   lldb::TypeCategoryImplSP category_sp;
290   uint32_t prio_category = UINT32_MAX;
291   for (uint32_t category_id = 0; category_id < num_categories; category_id++) {
292     category_sp = GetCategoryAtIndex(category_id);
293     if (!category_sp->IsEnabled())
294       continue;
295     lldb::TypeFormatImplSP format_current_sp =
296         category_sp->GetFormatForType(type_sp);
297     if (format_current_sp &&
298         (format_chosen_sp.get() == nullptr ||
299          (prio_category > category_sp->GetEnabledPosition()))) {
300       prio_category = category_sp->GetEnabledPosition();
301       format_chosen_sp = format_current_sp;
302     }
303   }
304   return format_chosen_sp;
305 }
306 
307 lldb::TypeSummaryImplSP
308 FormatManager::GetSummaryForType(lldb::TypeNameSpecifierImplSP type_sp) {
309   if (!type_sp)
310     return lldb::TypeSummaryImplSP();
311   lldb::TypeSummaryImplSP summary_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::TypeSummaryImplSP summary_current_sp =
320         category_sp->GetSummaryForType(type_sp);
321     if (summary_current_sp &&
322         (summary_chosen_sp.get() == nullptr ||
323          (prio_category > category_sp->GetEnabledPosition()))) {
324       prio_category = category_sp->GetEnabledPosition();
325       summary_chosen_sp = summary_current_sp;
326     }
327   }
328   return summary_chosen_sp;
329 }
330 
331 lldb::TypeFilterImplSP
332 FormatManager::GetFilterForType(lldb::TypeNameSpecifierImplSP type_sp) {
333   if (!type_sp)
334     return lldb::TypeFilterImplSP();
335   lldb::TypeFilterImplSP filter_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::TypeFilterImplSP filter_current_sp(
344         (TypeFilterImpl *)category_sp->GetFilterForType(type_sp).get());
345     if (filter_current_sp &&
346         (filter_chosen_sp.get() == nullptr ||
347          (prio_category > category_sp->GetEnabledPosition()))) {
348       prio_category = category_sp->GetEnabledPosition();
349       filter_chosen_sp = filter_current_sp;
350     }
351   }
352   return filter_chosen_sp;
353 }
354 
355 lldb::ScriptedSyntheticChildrenSP
356 FormatManager::GetSyntheticForType(lldb::TypeNameSpecifierImplSP type_sp) {
357   if (!type_sp)
358     return lldb::ScriptedSyntheticChildrenSP();
359   lldb::ScriptedSyntheticChildrenSP synth_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::ScriptedSyntheticChildrenSP synth_current_sp(
368         (ScriptedSyntheticChildren *)category_sp->GetSyntheticForType(type_sp)
369             .get());
370     if (synth_current_sp &&
371         (synth_chosen_sp.get() == nullptr ||
372          (prio_category > category_sp->GetEnabledPosition()))) {
373       prio_category = category_sp->GetEnabledPosition();
374       synth_chosen_sp = synth_current_sp;
375     }
376   }
377   return synth_chosen_sp;
378 }
379 
380 lldb::TypeValidatorImplSP
381 FormatManager::GetValidatorForType(lldb::TypeNameSpecifierImplSP type_sp) {
382   if (!type_sp)
383     return lldb::TypeValidatorImplSP();
384   lldb::TypeValidatorImplSP validator_chosen_sp;
385   uint32_t num_categories = m_categories_map.GetCount();
386   lldb::TypeCategoryImplSP category_sp;
387   uint32_t prio_category = UINT32_MAX;
388   for (uint32_t category_id = 0; category_id < num_categories; category_id++) {
389     category_sp = GetCategoryAtIndex(category_id);
390     if (!category_sp->IsEnabled())
391       continue;
392     lldb::TypeValidatorImplSP validator_current_sp(
393         category_sp->GetValidatorForType(type_sp).get());
394     if (validator_current_sp &&
395         (validator_chosen_sp.get() == nullptr ||
396          (prio_category > category_sp->GetEnabledPosition()))) {
397       prio_category = category_sp->GetEnabledPosition();
398       validator_chosen_sp = validator_current_sp;
399     }
400   }
401   return validator_chosen_sp;
402 }
403 
404 void 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 
415 lldb::TypeCategoryImplSP
416 FormatManager::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(
427       category_name,
428       lldb::TypeCategoryImplSP(new TypeCategoryImpl(this, category_name)));
429   return GetCategory(category_name);
430 }
431 
432 lldb::Format FormatManager::GetSingleItemFormat(lldb::Format vector_format) {
433   switch (vector_format) {
434   case eFormatVectorOfChar:
435     return eFormatCharArray;
436 
437   case eFormatVectorOfSInt8:
438   case eFormatVectorOfSInt16:
439   case eFormatVectorOfSInt32:
440   case eFormatVectorOfSInt64:
441     return eFormatDecimal;
442 
443   case eFormatVectorOfUInt8:
444   case eFormatVectorOfUInt16:
445   case eFormatVectorOfUInt32:
446   case eFormatVectorOfUInt64:
447   case eFormatVectorOfUInt128:
448     return eFormatHex;
449 
450   case eFormatVectorOfFloat16:
451   case eFormatVectorOfFloat32:
452   case eFormatVectorOfFloat64:
453     return eFormatFloat;
454 
455   default:
456     return lldb::eFormatInvalid;
457   }
458 }
459 
460 bool FormatManager::ShouldPrintAsOneLiner(ValueObject &valobj) {
461   // if settings say no oneline whatsoever
462   if (valobj.GetTargetSP().get() &&
463       !valobj.GetTargetSP()->GetDebugger().GetAutoOneLineSummaries())
464     return false; // then don't oneline
465 
466   // if this object has a summary, then ask the summary
467   if (valobj.GetSummaryFormat().get() != nullptr)
468     return valobj.GetSummaryFormat()->IsOneLiner();
469 
470   // no children, no party
471   if (valobj.GetNumChildren() == 0)
472     return false;
473 
474   // ask the type if it has any opinion about this eLazyBoolCalculate == no
475   // opinion; other values should be self explanatory
476   CompilerType compiler_type(valobj.GetCompilerType());
477   if (compiler_type.IsValid()) {
478     switch (compiler_type.ShouldPrintAsOneLiner(&valobj)) {
479     case eLazyBoolNo:
480       return false;
481     case eLazyBoolYes:
482       return true;
483     case eLazyBoolCalculate:
484       break;
485     }
486   }
487 
488   size_t total_children_name_len = 0;
489 
490   for (size_t idx = 0; idx < valobj.GetNumChildren(); idx++) {
491     bool is_synth_val = false;
492     ValueObjectSP child_sp(valobj.GetChildAtIndex(idx, true));
493     // something is wrong here - bail out
494     if (!child_sp)
495       return false;
496 
497     // also ask the child's type if it has any opinion
498     CompilerType child_compiler_type(child_sp->GetCompilerType());
499     if (child_compiler_type.IsValid()) {
500       switch (child_compiler_type.ShouldPrintAsOneLiner(child_sp.get())) {
501       case eLazyBoolYes:
502       // an opinion of yes is only binding for the child, so keep going
503       case eLazyBoolCalculate:
504         break;
505       case eLazyBoolNo:
506         // but if the child says no, then it's a veto on the whole thing
507         return false;
508       }
509     }
510 
511     // if we decided to define synthetic children for a type, we probably care
512     // enough to show them, but avoid nesting children in children
513     if (child_sp->GetSyntheticChildren().get() != nullptr) {
514       ValueObjectSP synth_sp(child_sp->GetSyntheticValue());
515       // wait.. wat? just get out of here..
516       if (!synth_sp)
517         return false;
518       // but if we only have them to provide a value, keep going
519       if (!synth_sp->MightHaveChildren() &&
520           synth_sp->DoesProvideSyntheticValue())
521         is_synth_val = true;
522       else
523         return false;
524     }
525 
526     total_children_name_len += child_sp->GetName().GetLength();
527 
528     // 50 itself is a "randomly" chosen number - the idea is that
529     // overly long structs should not get this treatment
530     // FIXME: maybe make this a user-tweakable setting?
531     if (total_children_name_len > 50)
532       return false;
533 
534     // if a summary is there..
535     if (child_sp->GetSummaryFormat()) {
536       // and it wants children, then bail out
537       if (child_sp->GetSummaryFormat()->DoesPrintChildren(child_sp.get()))
538         return false;
539     }
540 
541     // if this child has children..
542     if (child_sp->GetNumChildren()) {
543       // ...and no summary...
544       // (if it had a summary and the summary wanted children, we would have
545       // bailed out anyway
546       //  so this only makes us bail out if this has no summary and we would
547       //  then print children)
548       if (!child_sp->GetSummaryFormat() && !is_synth_val) // but again only do
549                                                           // that if not a
550                                                           // synthetic valued
551                                                           // child
552         return false;                                     // then bail out
553     }
554   }
555   return true;
556 }
557 
558 ConstString FormatManager::GetValidTypeName(ConstString type) {
559   return ::GetValidTypeName_Impl(type);
560 }
561 
562 ConstString FormatManager::GetTypeForCache(ValueObject &valobj,
563                                            lldb::DynamicValueType use_dynamic) {
564   ValueObjectSP valobj_sp = valobj.GetQualifiedRepresentationIfAvailable(
565       use_dynamic, valobj.IsSynthetic());
566   if (valobj_sp && valobj_sp->GetCompilerType().IsValid())
567     return valobj_sp->GetQualifiedTypeName();
568   return ConstString();
569 }
570 
571 std::vector<lldb::LanguageType>
572 FormatManager::GetCandidateLanguages(ValueObject &valobj) {
573   lldb::LanguageType lang_type = valobj.GetObjectRuntimeLanguage();
574   return GetCandidateLanguages(lang_type);
575 }
576 
577 std::vector<lldb::LanguageType>
578 FormatManager::GetCandidateLanguages(lldb::LanguageType lang_type) {
579   switch (lang_type) {
580   case lldb::eLanguageTypeC:
581   case lldb::eLanguageTypeC89:
582   case lldb::eLanguageTypeC99:
583   case lldb::eLanguageTypeC11:
584   case lldb::eLanguageTypeC_plus_plus:
585   case lldb::eLanguageTypeC_plus_plus_03:
586   case lldb::eLanguageTypeC_plus_plus_11:
587   case lldb::eLanguageTypeC_plus_plus_14:
588     return {lldb::eLanguageTypeC_plus_plus, lldb::eLanguageTypeObjC};
589   default:
590     return {lang_type};
591   }
592 }
593 
594 LanguageCategory *
595 FormatManager::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 
607 lldb::TypeFormatImplSP
608 FormatManager::GetHardcodedFormat(FormattersMatchData &match_data) {
609   TypeFormatImplSP retval_sp;
610 
611   for (lldb::LanguageType lang_type : match_data.GetCandidateLanguages()) {
612     if (LanguageCategory *lang_category = GetCategoryForLanguage(lang_type)) {
613       if (lang_category->GetHardcoded(*this, match_data, retval_sp))
614         break;
615     }
616   }
617 
618   return retval_sp;
619 }
620 
621 lldb::TypeFormatImplSP
622 FormatManager::GetFormat(ValueObject &valobj,
623                          lldb::DynamicValueType use_dynamic) {
624   FormattersMatchData match_data(valobj, use_dynamic);
625 
626   TypeFormatImplSP retval;
627   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_DATAFORMATTERS));
628   if (match_data.GetTypeForCache()) {
629     LLDB_LOGF(log,
630               "\n\n[FormatManager::GetFormat] Looking into cache for type %s",
631               match_data.GetTypeForCache().AsCString("<invalid>"));
632     if (m_format_cache.GetFormat(match_data.GetTypeForCache(), retval)) {
633       if (log) {
634         LLDB_LOGF(
635             log, "[FormatManager::GetFormat] Cache search success. Returning.");
636         LLDB_LOGV(log, "Cache hits: {0} - Cache Misses: {1}",
637                   m_format_cache.GetCacheHits(),
638                   m_format_cache.GetCacheMisses());
639       }
640       return retval;
641     }
642     LLDB_LOGF(
643         log,
644         "[FormatManager::GetFormat] Cache search failed. Going normal route");
645   }
646 
647   retval = m_categories_map.GetFormat(match_data);
648   if (!retval) {
649     LLDB_LOGF(log,
650               "[FormatManager::GetFormat] Search failed. Giving language a "
651               "chance.");
652     for (lldb::LanguageType lang_type : match_data.GetCandidateLanguages()) {
653       if (LanguageCategory *lang_category = GetCategoryForLanguage(lang_type)) {
654         if (lang_category->Get(match_data, retval))
655           break;
656       }
657     }
658     if (retval) {
659       LLDB_LOGF(
660           log,
661           "[FormatManager::GetFormat] Language search success. Returning.");
662       return retval;
663     }
664   }
665   if (!retval) {
666     LLDB_LOGF(log, "[FormatManager::GetFormat] Search failed. Giving hardcoded "
667                    "a chance.");
668     retval = GetHardcodedFormat(match_data);
669   }
670 
671   if (match_data.GetTypeForCache() && (!retval || !retval->NonCacheable())) {
672     LLDB_LOGF(log, "[FormatManager::GetFormat] Caching %p for type %s",
673               static_cast<void *>(retval.get()),
674               match_data.GetTypeForCache().AsCString("<invalid>"));
675     m_format_cache.SetFormat(match_data.GetTypeForCache(), retval);
676   }
677   LLDB_LOGV(log, "Cache hits: {0} - Cache Misses: {1}",
678             m_format_cache.GetCacheHits(), m_format_cache.GetCacheMisses());
679   return retval;
680 }
681 
682 lldb::TypeSummaryImplSP
683 FormatManager::GetHardcodedSummaryFormat(FormattersMatchData &match_data) {
684   TypeSummaryImplSP retval_sp;
685 
686   for (lldb::LanguageType lang_type : match_data.GetCandidateLanguages()) {
687     if (LanguageCategory *lang_category = GetCategoryForLanguage(lang_type)) {
688       if (lang_category->GetHardcoded(*this, match_data, retval_sp))
689         break;
690     }
691   }
692 
693   return retval_sp;
694 }
695 
696 lldb::TypeSummaryImplSP
697 FormatManager::GetSummaryFormat(ValueObject &valobj,
698                                 lldb::DynamicValueType use_dynamic) {
699   FormattersMatchData match_data(valobj, use_dynamic);
700 
701   TypeSummaryImplSP retval;
702   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_DATAFORMATTERS));
703   if (match_data.GetTypeForCache()) {
704     LLDB_LOGF(log,
705               "\n\n[FormatManager::GetSummaryFormat] Looking into cache "
706               "for type %s",
707               match_data.GetTypeForCache().AsCString("<invalid>"));
708     if (m_format_cache.GetSummary(match_data.GetTypeForCache(), retval)) {
709       if (log) {
710         LLDB_LOGF(log,
711                   "[FormatManager::GetSummaryFormat] Cache search success. "
712                   "Returning.");
713         LLDB_LOGV(log, "Cache hits: {0} - Cache Misses: {1}",
714                   m_format_cache.GetCacheHits(),
715                   m_format_cache.GetCacheMisses());
716       }
717       return retval;
718     }
719     LLDB_LOGF(log, "[FormatManager::GetSummaryFormat] Cache search failed. "
720                    "Going normal route");
721   }
722 
723   retval = m_categories_map.GetSummaryFormat(match_data);
724   if (!retval) {
725     LLDB_LOGF(log, "[FormatManager::GetSummaryFormat] Search failed. Giving "
726                    "language a chance.");
727     for (lldb::LanguageType lang_type : match_data.GetCandidateLanguages()) {
728       if (LanguageCategory *lang_category = GetCategoryForLanguage(lang_type)) {
729         if (lang_category->Get(match_data, retval))
730           break;
731       }
732     }
733     if (retval) {
734       LLDB_LOGF(log, "[FormatManager::GetSummaryFormat] Language search "
735                      "success. Returning.");
736       return retval;
737     }
738   }
739   if (!retval) {
740     LLDB_LOGF(log, "[FormatManager::GetSummaryFormat] Search failed. Giving "
741                    "hardcoded a chance.");
742     retval = GetHardcodedSummaryFormat(match_data);
743   }
744 
745   if (match_data.GetTypeForCache() && (!retval || !retval->NonCacheable())) {
746     LLDB_LOGF(log, "[FormatManager::GetSummaryFormat] Caching %p for type %s",
747               static_cast<void *>(retval.get()),
748               match_data.GetTypeForCache().AsCString("<invalid>"));
749     m_format_cache.SetSummary(match_data.GetTypeForCache(), retval);
750   }
751   LLDB_LOGV(log, "Cache hits: {0} - Cache Misses: {1}",
752             m_format_cache.GetCacheHits(), m_format_cache.GetCacheMisses());
753   return retval;
754 }
755 
756 lldb::SyntheticChildrenSP
757 FormatManager::GetHardcodedSyntheticChildren(FormattersMatchData &match_data) {
758   SyntheticChildrenSP retval_sp;
759 
760   for (lldb::LanguageType lang_type : match_data.GetCandidateLanguages()) {
761     if (LanguageCategory *lang_category = GetCategoryForLanguage(lang_type)) {
762       if (lang_category->GetHardcoded(*this, match_data, retval_sp))
763         break;
764     }
765   }
766 
767   return retval_sp;
768 }
769 
770 lldb::SyntheticChildrenSP
771 FormatManager::GetSyntheticChildren(ValueObject &valobj,
772                                     lldb::DynamicValueType use_dynamic) {
773   FormattersMatchData match_data(valobj, use_dynamic);
774 
775   SyntheticChildrenSP retval;
776   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_DATAFORMATTERS));
777   if (match_data.GetTypeForCache()) {
778     LLDB_LOGF(log,
779               "\n\n[FormatManager::GetSyntheticChildren] Looking into "
780               "cache for type %s",
781               match_data.GetTypeForCache().AsCString("<invalid>"));
782     if (m_format_cache.GetSynthetic(match_data.GetTypeForCache(), retval)) {
783       if (log) {
784         LLDB_LOGF(log, "[FormatManager::GetSyntheticChildren] Cache search "
785                        "success. Returning.");
786         LLDB_LOGV(log, "Cache hits: {0} - Cache Misses: {1}",
787                   m_format_cache.GetCacheHits(),
788                   m_format_cache.GetCacheMisses());
789       }
790       return retval;
791     }
792     LLDB_LOGF(log, "[FormatManager::GetSyntheticChildren] Cache search failed. "
793                    "Going normal route");
794   }
795 
796   retval = m_categories_map.GetSyntheticChildren(match_data);
797   if (!retval) {
798     LLDB_LOGF(log,
799               "[FormatManager::GetSyntheticChildren] Search failed. Giving "
800               "language a chance.");
801     for (lldb::LanguageType lang_type : match_data.GetCandidateLanguages()) {
802       if (LanguageCategory *lang_category = GetCategoryForLanguage(lang_type)) {
803         if (lang_category->Get(match_data, retval))
804           break;
805       }
806     }
807     if (retval) {
808       LLDB_LOGF(log, "[FormatManager::GetSyntheticChildren] Language search "
809                      "success. Returning.");
810       return retval;
811     }
812   }
813   if (!retval) {
814     LLDB_LOGF(log,
815               "[FormatManager::GetSyntheticChildren] Search failed. Giving "
816               "hardcoded a chance.");
817     retval = GetHardcodedSyntheticChildren(match_data);
818   }
819 
820   if (match_data.GetTypeForCache() && (!retval || !retval->NonCacheable())) {
821     LLDB_LOGF(log,
822               "[FormatManager::GetSyntheticChildren] Caching %p for type %s",
823               static_cast<void *>(retval.get()),
824               match_data.GetTypeForCache().AsCString("<invalid>"));
825     m_format_cache.SetSynthetic(match_data.GetTypeForCache(), retval);
826   }
827   LLDB_LOGV(log, "Cache hits: {0} - Cache Misses: {1}",
828             m_format_cache.GetCacheHits(), m_format_cache.GetCacheMisses());
829   return retval;
830 }
831 
832 lldb::TypeValidatorImplSP
833 FormatManager::GetValidator(ValueObject &valobj,
834                             lldb::DynamicValueType use_dynamic) {
835   FormattersMatchData match_data(valobj, use_dynamic);
836 
837   TypeValidatorImplSP retval;
838   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_DATAFORMATTERS));
839   if (match_data.GetTypeForCache()) {
840     LLDB_LOGF(
841         log, "\n\n[FormatManager::GetValidator] Looking into cache for type %s",
842         match_data.GetTypeForCache().AsCString("<invalid>"));
843     if (m_format_cache.GetValidator(match_data.GetTypeForCache(), retval)) {
844       if (log) {
845         LLDB_LOGF(
846             log,
847             "[FormatManager::GetValidator] Cache search success. Returning.");
848         LLDB_LOGV(log, "Cache hits: {0} - Cache Misses: {1}",
849                   m_format_cache.GetCacheHits(),
850                   m_format_cache.GetCacheMisses());
851       }
852       return retval;
853     }
854     LLDB_LOGF(log, "[FormatManager::GetValidator] Cache search failed. Going "
855                    "normal route");
856   }
857 
858   retval = m_categories_map.GetValidator(match_data);
859   if (!retval) {
860     LLDB_LOGF(log, "[FormatManager::GetValidator] Search failed. Giving "
861                    "language a chance.");
862     for (lldb::LanguageType lang_type : match_data.GetCandidateLanguages()) {
863       if (LanguageCategory *lang_category = GetCategoryForLanguage(lang_type)) {
864         if (lang_category->Get(match_data, retval))
865           break;
866       }
867     }
868     if (retval) {
869       LLDB_LOGF(log, "[FormatManager::GetValidator] Language search success. "
870                      "Returning.");
871       return retval;
872     }
873   }
874   if (!retval) {
875     LLDB_LOGF(log, "[FormatManager::GetValidator] Search failed. Giving "
876                    "hardcoded a chance.");
877     retval = GetHardcodedValidator(match_data);
878   }
879 
880   if (match_data.GetTypeForCache() && (!retval || !retval->NonCacheable())) {
881     LLDB_LOGF(log, "[FormatManager::GetValidator] Caching %p for type %s",
882               static_cast<void *>(retval.get()),
883               match_data.GetTypeForCache().AsCString("<invalid>"));
884     m_format_cache.SetValidator(match_data.GetTypeForCache(), retval);
885   }
886   LLDB_LOGV(log, "Cache hits: {0} - Cache Misses: {1}",
887             m_format_cache.GetCacheHits(), m_format_cache.GetCacheMisses());
888   return retval;
889 }
890 
891 lldb::TypeValidatorImplSP
892 FormatManager::GetHardcodedValidator(FormattersMatchData &match_data) {
893   TypeValidatorImplSP retval_sp;
894 
895   for (lldb::LanguageType lang_type : match_data.GetCandidateLanguages()) {
896     if (LanguageCategory *lang_category = GetCategoryForLanguage(lang_type)) {
897       if (lang_category->GetHardcoded(*this, match_data, retval_sp))
898         break;
899     }
900   }
901 
902   return retval_sp;
903 }
904 
905 FormatManager::FormatManager()
906     : m_last_revision(0), m_format_cache(), m_language_categories_mutex(),
907       m_language_categories_map(), m_named_summaries_map(this),
908       m_categories_map(this), m_default_category_name(ConstString("default")),
909       m_system_category_name(ConstString("system")),
910       m_vectortypes_category_name(ConstString("VectorTypes")) {
911   LoadSystemFormatters();
912   LoadVectorFormatters();
913 
914   EnableCategory(m_vectortypes_category_name, TypeCategoryMap::Last,
915                  lldb::eLanguageTypeObjC_plus_plus);
916   EnableCategory(m_system_category_name, TypeCategoryMap::Last,
917                  lldb::eLanguageTypeObjC_plus_plus);
918 }
919 
920 void FormatManager::LoadSystemFormatters() {
921   TypeSummaryImpl::Flags string_flags;
922   string_flags.SetCascades(true)
923       .SetSkipPointers(true)
924       .SetSkipReferences(false)
925       .SetDontShowChildren(true)
926       .SetDontShowValue(false)
927       .SetShowMembersOneLiner(false)
928       .SetHideItemNames(false);
929 
930   TypeSummaryImpl::Flags string_array_flags;
931   string_array_flags.SetCascades(true)
932       .SetSkipPointers(true)
933       .SetSkipReferences(false)
934       .SetDontShowChildren(true)
935       .SetDontShowValue(true)
936       .SetShowMembersOneLiner(false)
937       .SetHideItemNames(false);
938 
939   lldb::TypeSummaryImplSP string_format(
940       new StringSummaryFormat(string_flags, "${var%s}"));
941 
942   lldb::TypeSummaryImplSP string_array_format(
943       new StringSummaryFormat(string_array_flags, "${var%s}"));
944 
945   lldb::RegularExpressionSP any_size_char_arr(
946       new RegularExpression(llvm::StringRef("char \\[[0-9]+\\]")));
947   lldb::RegularExpressionSP any_size_wchar_arr(
948       new RegularExpression(llvm::StringRef("wchar_t \\[[0-9]+\\]")));
949 
950   TypeCategoryImpl::SharedPointer sys_category_sp =
951       GetCategory(m_system_category_name);
952 
953   sys_category_sp->GetTypeSummariesContainer()->Add(ConstString("char *"),
954                                                     string_format);
955   sys_category_sp->GetTypeSummariesContainer()->Add(
956       ConstString("unsigned char *"), string_format);
957   sys_category_sp->GetRegexTypeSummariesContainer()->Add(any_size_char_arr,
958                                                          string_array_format);
959 
960   lldb::TypeSummaryImplSP ostype_summary(
961       new StringSummaryFormat(TypeSummaryImpl::Flags()
962                                   .SetCascades(false)
963                                   .SetSkipPointers(true)
964                                   .SetSkipReferences(true)
965                                   .SetDontShowChildren(true)
966                                   .SetDontShowValue(false)
967                                   .SetShowMembersOneLiner(false)
968                                   .SetHideItemNames(false),
969                               "${var%O}"));
970 
971   sys_category_sp->GetTypeSummariesContainer()->Add(ConstString("OSType"),
972                                                     ostype_summary);
973 
974   TypeFormatImpl::Flags fourchar_flags;
975   fourchar_flags.SetCascades(true).SetSkipPointers(true).SetSkipReferences(
976       true);
977 
978   AddFormat(sys_category_sp, lldb::eFormatOSType, ConstString("FourCharCode"),
979             fourchar_flags);
980 }
981 
982 void FormatManager::LoadVectorFormatters() {
983   TypeCategoryImpl::SharedPointer vectors_category_sp =
984       GetCategory(m_vectortypes_category_name);
985 
986   TypeSummaryImpl::Flags vector_flags;
987   vector_flags.SetCascades(true)
988       .SetSkipPointers(true)
989       .SetSkipReferences(false)
990       .SetDontShowChildren(true)
991       .SetDontShowValue(false)
992       .SetShowMembersOneLiner(true)
993       .SetHideItemNames(true);
994 
995   AddStringSummary(vectors_category_sp, "${var.uint128}",
996                    ConstString("builtin_type_vec128"), vector_flags);
997 
998   AddStringSummary(vectors_category_sp, "", ConstString("float [4]"),
999                    vector_flags);
1000   AddStringSummary(vectors_category_sp, "", ConstString("int32_t [4]"),
1001                    vector_flags);
1002   AddStringSummary(vectors_category_sp, "", ConstString("int16_t [8]"),
1003                    vector_flags);
1004   AddStringSummary(vectors_category_sp, "", ConstString("vDouble"),
1005                    vector_flags);
1006   AddStringSummary(vectors_category_sp, "", ConstString("vFloat"),
1007                    vector_flags);
1008   AddStringSummary(vectors_category_sp, "", ConstString("vSInt8"),
1009                    vector_flags);
1010   AddStringSummary(vectors_category_sp, "", ConstString("vSInt16"),
1011                    vector_flags);
1012   AddStringSummary(vectors_category_sp, "", ConstString("vSInt32"),
1013                    vector_flags);
1014   AddStringSummary(vectors_category_sp, "", ConstString("vUInt16"),
1015                    vector_flags);
1016   AddStringSummary(vectors_category_sp, "", ConstString("vUInt8"),
1017                    vector_flags);
1018   AddStringSummary(vectors_category_sp, "", ConstString("vUInt16"),
1019                    vector_flags);
1020   AddStringSummary(vectors_category_sp, "", ConstString("vUInt32"),
1021                    vector_flags);
1022   AddStringSummary(vectors_category_sp, "", ConstString("vBool32"),
1023                    vector_flags);
1024 }
1025