1 //===-- ValueObject.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/Core/ValueObject.h"
10 
11 #include "lldb/Core/Address.h"
12 #include "lldb/Core/Declaration.h"
13 #include "lldb/Core/Module.h"
14 #include "lldb/Core/ValueObjectCast.h"
15 #include "lldb/Core/ValueObjectChild.h"
16 #include "lldb/Core/ValueObjectConstResult.h"
17 #include "lldb/Core/ValueObjectDynamicValue.h"
18 #include "lldb/Core/ValueObjectMemory.h"
19 #include "lldb/Core/ValueObjectSyntheticFilter.h"
20 #include "lldb/DataFormatters/DataVisualization.h"
21 #include "lldb/DataFormatters/DumpValueObjectOptions.h"
22 #include "lldb/DataFormatters/FormatManager.h"
23 #include "lldb/DataFormatters/StringPrinter.h"
24 #include "lldb/DataFormatters/TypeFormat.h"
25 #include "lldb/DataFormatters/TypeSummary.h"
26 #include "lldb/DataFormatters/ValueObjectPrinter.h"
27 #include "lldb/Expression/ExpressionVariable.h"
28 #include "lldb/Host/Config.h"
29 #include "lldb/Symbol/CompileUnit.h"
30 #include "lldb/Symbol/CompilerType.h"
31 #include "lldb/Symbol/SymbolContext.h"
32 #include "lldb/Symbol/Type.h"
33 #include "lldb/Symbol/Variable.h"
34 #include "lldb/Target/ExecutionContext.h"
35 #include "lldb/Target/Language.h"
36 #include "lldb/Target/LanguageRuntime.h"
37 #include "lldb/Target/Process.h"
38 #include "lldb/Target/StackFrame.h"
39 #include "lldb/Target/Target.h"
40 #include "lldb/Target/Thread.h"
41 #include "lldb/Target/ThreadList.h"
42 #include "lldb/Utility/DataBuffer.h"
43 #include "lldb/Utility/DataBufferHeap.h"
44 #include "lldb/Utility/Flags.h"
45 #include "lldb/Utility/LLDBLog.h"
46 #include "lldb/Utility/Log.h"
47 #include "lldb/Utility/Scalar.h"
48 #include "lldb/Utility/Stream.h"
49 #include "lldb/Utility/StreamString.h"
50 #include "lldb/lldb-private-types.h"
51 
52 #include "llvm/Support/Compiler.h"
53 
54 #include <algorithm>
55 #include <cstdint>
56 #include <cstdlib>
57 #include <memory>
58 #include <optional>
59 #include <tuple>
60 
61 #include <cassert>
62 #include <cinttypes>
63 #include <cstdio>
64 #include <cstring>
65 
66 #include <lldb/Core/ValueObject.h>
67 
68 namespace lldb_private {
69 class ExecutionContextScope;
70 }
71 namespace lldb_private {
72 class SymbolContextScope;
73 }
74 
75 using namespace lldb;
76 using namespace lldb_private;
77 
78 static user_id_t g_value_obj_uid = 0;
79 
80 // ValueObject constructor
81 ValueObject::ValueObject(ValueObject &parent)
82     : m_parent(&parent), m_update_point(parent.GetUpdatePoint()),
83       m_manager(parent.GetManager()), m_id(++g_value_obj_uid) {
84   m_flags.m_is_synthetic_children_generated =
85       parent.m_flags.m_is_synthetic_children_generated;
86   m_data.SetByteOrder(parent.GetDataExtractor().GetByteOrder());
87   m_data.SetAddressByteSize(parent.GetDataExtractor().GetAddressByteSize());
88   m_manager->ManageObject(this);
89 }
90 
91 // ValueObject constructor
92 ValueObject::ValueObject(ExecutionContextScope *exe_scope,
93                          ValueObjectManager &manager,
94                          AddressType child_ptr_or_ref_addr_type)
95     : m_update_point(exe_scope), m_manager(&manager),
96       m_address_type_of_ptr_or_ref_children(child_ptr_or_ref_addr_type),
97       m_id(++g_value_obj_uid) {
98   if (exe_scope) {
99     TargetSP target_sp(exe_scope->CalculateTarget());
100     if (target_sp) {
101       const ArchSpec &arch = target_sp->GetArchitecture();
102       m_data.SetByteOrder(arch.GetByteOrder());
103       m_data.SetAddressByteSize(arch.GetAddressByteSize());
104     }
105   }
106   m_manager->ManageObject(this);
107 }
108 
109 // Destructor
110 ValueObject::~ValueObject() = default;
111 
112 bool ValueObject::UpdateValueIfNeeded(bool update_format) {
113 
114   bool did_change_formats = false;
115 
116   if (update_format)
117     did_change_formats = UpdateFormatsIfNeeded();
118 
119   // If this is a constant value, then our success is predicated on whether we
120   // have an error or not
121   if (GetIsConstant()) {
122     // if you are constant, things might still have changed behind your back
123     // (e.g. you are a frozen object and things have changed deeper than you
124     // cared to freeze-dry yourself) in this case, your value has not changed,
125     // but "computed" entries might have, so you might now have a different
126     // summary, or a different object description. clear these so we will
127     // recompute them
128     if (update_format && !did_change_formats)
129       ClearUserVisibleData(eClearUserVisibleDataItemsSummary |
130                            eClearUserVisibleDataItemsDescription);
131     return m_error.Success();
132   }
133 
134   bool first_update = IsChecksumEmpty();
135 
136   if (NeedsUpdating()) {
137     m_update_point.SetUpdated();
138 
139     // Save the old value using swap to avoid a string copy which also will
140     // clear our m_value_str
141     if (m_value_str.empty()) {
142       m_flags.m_old_value_valid = false;
143     } else {
144       m_flags.m_old_value_valid = true;
145       m_old_value_str.swap(m_value_str);
146       ClearUserVisibleData(eClearUserVisibleDataItemsValue);
147     }
148 
149     ClearUserVisibleData();
150 
151     if (IsInScope()) {
152       const bool value_was_valid = GetValueIsValid();
153       SetValueDidChange(false);
154 
155       m_error.Clear();
156 
157       // Call the pure virtual function to update the value
158 
159       bool need_compare_checksums = false;
160       llvm::SmallVector<uint8_t, 16> old_checksum;
161 
162       if (!first_update && CanProvideValue()) {
163         need_compare_checksums = true;
164         old_checksum.resize(m_value_checksum.size());
165         std::copy(m_value_checksum.begin(), m_value_checksum.end(),
166                   old_checksum.begin());
167       }
168 
169       bool success = UpdateValue();
170 
171       SetValueIsValid(success);
172 
173       if (success) {
174         UpdateChildrenAddressType();
175         const uint64_t max_checksum_size = 128;
176         m_data.Checksum(m_value_checksum, max_checksum_size);
177       } else {
178         need_compare_checksums = false;
179         m_value_checksum.clear();
180       }
181 
182       assert(!need_compare_checksums ||
183              (!old_checksum.empty() && !m_value_checksum.empty()));
184 
185       if (first_update)
186         SetValueDidChange(false);
187       else if (!m_flags.m_value_did_change && !success) {
188         // The value wasn't gotten successfully, so we mark this as changed if
189         // the value used to be valid and now isn't
190         SetValueDidChange(value_was_valid);
191       } else if (need_compare_checksums) {
192         SetValueDidChange(memcmp(&old_checksum[0], &m_value_checksum[0],
193                                  m_value_checksum.size()));
194       }
195 
196     } else {
197       m_error.SetErrorString("out of scope");
198     }
199   }
200   return m_error.Success();
201 }
202 
203 bool ValueObject::UpdateFormatsIfNeeded() {
204   Log *log = GetLog(LLDBLog::DataFormatters);
205   LLDB_LOGF(log,
206             "[%s %p] checking for FormatManager revisions. ValueObject "
207             "rev: %d - Global rev: %d",
208             GetName().GetCString(), static_cast<void *>(this),
209             m_last_format_mgr_revision,
210             DataVisualization::GetCurrentRevision());
211 
212   bool any_change = false;
213 
214   if ((m_last_format_mgr_revision != DataVisualization::GetCurrentRevision())) {
215     m_last_format_mgr_revision = DataVisualization::GetCurrentRevision();
216     any_change = true;
217 
218     SetValueFormat(DataVisualization::GetFormat(*this, eNoDynamicValues));
219     SetSummaryFormat(
220         DataVisualization::GetSummaryFormat(*this, GetDynamicValueType()));
221 #if LLDB_ENABLE_PYTHON
222     SetSyntheticChildren(
223         DataVisualization::GetSyntheticChildren(*this, GetDynamicValueType()));
224 #endif
225   }
226 
227   return any_change;
228 }
229 
230 void ValueObject::SetNeedsUpdate() {
231   m_update_point.SetNeedsUpdate();
232   // We have to clear the value string here so ConstResult children will notice
233   // if their values are changed by hand (i.e. with SetValueAsCString).
234   ClearUserVisibleData(eClearUserVisibleDataItemsValue);
235 }
236 
237 void ValueObject::ClearDynamicTypeInformation() {
238   m_flags.m_children_count_valid = false;
239   m_flags.m_did_calculate_complete_objc_class_type = false;
240   m_last_format_mgr_revision = 0;
241   m_override_type = CompilerType();
242   SetValueFormat(lldb::TypeFormatImplSP());
243   SetSummaryFormat(lldb::TypeSummaryImplSP());
244   SetSyntheticChildren(lldb::SyntheticChildrenSP());
245 }
246 
247 CompilerType ValueObject::MaybeCalculateCompleteType() {
248   CompilerType compiler_type(GetCompilerTypeImpl());
249 
250   if (m_flags.m_did_calculate_complete_objc_class_type) {
251     if (m_override_type.IsValid())
252       return m_override_type;
253     else
254       return compiler_type;
255   }
256 
257   m_flags.m_did_calculate_complete_objc_class_type = true;
258 
259   ProcessSP process_sp(
260       GetUpdatePoint().GetExecutionContextRef().GetProcessSP());
261 
262   if (!process_sp)
263     return compiler_type;
264 
265   if (auto *runtime =
266           process_sp->GetLanguageRuntime(GetObjectRuntimeLanguage())) {
267     if (std::optional<CompilerType> complete_type =
268             runtime->GetRuntimeType(compiler_type)) {
269       m_override_type = *complete_type;
270       if (m_override_type.IsValid())
271         return m_override_type;
272     }
273   }
274   return compiler_type;
275 }
276 
277 
278 
279 DataExtractor &ValueObject::GetDataExtractor() {
280   UpdateValueIfNeeded(false);
281   return m_data;
282 }
283 
284 const Status &ValueObject::GetError() {
285   UpdateValueIfNeeded(false);
286   return m_error;
287 }
288 
289 const char *ValueObject::GetLocationAsCStringImpl(const Value &value,
290                                                   const DataExtractor &data) {
291   if (UpdateValueIfNeeded(false)) {
292     if (m_location_str.empty()) {
293       StreamString sstr;
294 
295       Value::ValueType value_type = value.GetValueType();
296 
297       switch (value_type) {
298       case Value::ValueType::Invalid:
299         m_location_str = "invalid";
300         break;
301       case Value::ValueType::Scalar:
302         if (value.GetContextType() == Value::ContextType::RegisterInfo) {
303           RegisterInfo *reg_info = value.GetRegisterInfo();
304           if (reg_info) {
305             if (reg_info->name)
306               m_location_str = reg_info->name;
307             else if (reg_info->alt_name)
308               m_location_str = reg_info->alt_name;
309             if (m_location_str.empty())
310               m_location_str = (reg_info->encoding == lldb::eEncodingVector)
311                                    ? "vector"
312                                    : "scalar";
313           }
314         }
315         if (m_location_str.empty())
316           m_location_str = "scalar";
317         break;
318 
319       case Value::ValueType::LoadAddress:
320       case Value::ValueType::FileAddress:
321       case Value::ValueType::HostAddress: {
322         uint32_t addr_nibble_size = data.GetAddressByteSize() * 2;
323         sstr.Printf("0x%*.*llx", addr_nibble_size, addr_nibble_size,
324                     value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS));
325         m_location_str = std::string(sstr.GetString());
326       } break;
327       }
328     }
329   }
330   return m_location_str.c_str();
331 }
332 
333 bool ValueObject::ResolveValue(Scalar &scalar) {
334   if (UpdateValueIfNeeded(
335           false)) // make sure that you are up to date before returning anything
336   {
337     ExecutionContext exe_ctx(GetExecutionContextRef());
338     Value tmp_value(m_value);
339     scalar = tmp_value.ResolveValue(&exe_ctx);
340     if (scalar.IsValid()) {
341       const uint32_t bitfield_bit_size = GetBitfieldBitSize();
342       if (bitfield_bit_size)
343         return scalar.ExtractBitfield(bitfield_bit_size,
344                                       GetBitfieldBitOffset());
345       return true;
346     }
347   }
348   return false;
349 }
350 
351 bool ValueObject::IsLogicalTrue(Status &error) {
352   if (Language *language = Language::FindPlugin(GetObjectRuntimeLanguage())) {
353     LazyBool is_logical_true = language->IsLogicalTrue(*this, error);
354     switch (is_logical_true) {
355     case eLazyBoolYes:
356     case eLazyBoolNo:
357       return (is_logical_true == true);
358     case eLazyBoolCalculate:
359       break;
360     }
361   }
362 
363   Scalar scalar_value;
364 
365   if (!ResolveValue(scalar_value)) {
366     error.SetErrorString("failed to get a scalar result");
367     return false;
368   }
369 
370   bool ret;
371   ret = scalar_value.ULongLong(1) != 0;
372   error.Clear();
373   return ret;
374 }
375 
376 ValueObjectSP ValueObject::GetChildAtIndex(size_t idx, bool can_create) {
377   ValueObjectSP child_sp;
378   // We may need to update our value if we are dynamic
379   if (IsPossibleDynamicType())
380     UpdateValueIfNeeded(false);
381   if (idx < GetNumChildren()) {
382     // Check if we have already made the child value object?
383     if (can_create && !m_children.HasChildAtIndex(idx)) {
384       // No we haven't created the child at this index, so lets have our
385       // subclass do it and cache the result for quick future access.
386       m_children.SetChildAtIndex(idx, CreateChildAtIndex(idx, false, 0));
387     }
388 
389     ValueObject *child = m_children.GetChildAtIndex(idx);
390     if (child != nullptr)
391       return child->GetSP();
392   }
393   return child_sp;
394 }
395 
396 lldb::ValueObjectSP
397 ValueObject::GetChildAtIndexPath(llvm::ArrayRef<size_t> idxs,
398                                  size_t *index_of_error) {
399   if (idxs.size() == 0)
400     return GetSP();
401   ValueObjectSP root(GetSP());
402   for (size_t idx : idxs) {
403     root = root->GetChildAtIndex(idx);
404     if (!root) {
405       if (index_of_error)
406         *index_of_error = idx;
407       return root;
408     }
409   }
410   return root;
411 }
412 
413 lldb::ValueObjectSP ValueObject::GetChildAtIndexPath(
414   llvm::ArrayRef<std::pair<size_t, bool>> idxs, size_t *index_of_error) {
415   if (idxs.size() == 0)
416     return GetSP();
417   ValueObjectSP root(GetSP());
418   for (std::pair<size_t, bool> idx : idxs) {
419     root = root->GetChildAtIndex(idx.first, idx.second);
420     if (!root) {
421       if (index_of_error)
422         *index_of_error = idx.first;
423       return root;
424     }
425   }
426   return root;
427 }
428 
429 lldb::ValueObjectSP
430 ValueObject::GetChildAtNamePath(llvm::ArrayRef<llvm::StringRef> names) {
431   if (names.size() == 0)
432     return GetSP();
433   ValueObjectSP root(GetSP());
434   for (llvm::StringRef name : names) {
435     root = root->GetChildMemberWithName(name);
436     if (!root) {
437       return root;
438     }
439   }
440   return root;
441 }
442 
443 lldb::ValueObjectSP ValueObject::GetChildAtNamePath(
444     llvm::ArrayRef<std::pair<ConstString, bool>> names,
445     ConstString *name_of_error) {
446   if (names.size() == 0)
447     return GetSP();
448   ValueObjectSP root(GetSP());
449   for (std::pair<ConstString, bool> name : names) {
450     root = root->GetChildMemberWithName(name.first, name.second);
451     if (!root) {
452       if (name_of_error)
453         *name_of_error = name.first;
454       return root;
455     }
456   }
457   return root;
458 }
459 
460 size_t ValueObject::GetIndexOfChildWithName(llvm::StringRef name) {
461   bool omit_empty_base_classes = true;
462   return GetCompilerType().GetIndexOfChildWithName(name,
463                                                    omit_empty_base_classes);
464 }
465 
466 ValueObjectSP ValueObject::GetChildMemberWithName(llvm::StringRef name,
467                                                   bool can_create) {
468   // We may need to update our value if we are dynamic.
469   if (IsPossibleDynamicType())
470     UpdateValueIfNeeded(false);
471 
472   // When getting a child by name, it could be buried inside some base classes
473   // (which really aren't part of the expression path), so we need a vector of
474   // indexes that can get us down to the correct child.
475   std::vector<uint32_t> child_indexes;
476   bool omit_empty_base_classes = true;
477 
478   if (!GetCompilerType().IsValid())
479     return ValueObjectSP();
480 
481   const size_t num_child_indexes =
482       GetCompilerType().GetIndexOfChildMemberWithName(
483           name, omit_empty_base_classes, child_indexes);
484   if (num_child_indexes == 0)
485     return nullptr;
486 
487   ValueObjectSP child_sp = GetSP();
488   for (uint32_t idx : child_indexes)
489     if (child_sp)
490       child_sp = child_sp->GetChildAtIndex(idx, can_create);
491   return child_sp;
492 }
493 
494 size_t ValueObject::GetNumChildren(uint32_t max) {
495   UpdateValueIfNeeded();
496 
497   if (max < UINT32_MAX) {
498     if (m_flags.m_children_count_valid) {
499       size_t children_count = m_children.GetChildrenCount();
500       return children_count <= max ? children_count : max;
501     } else
502       return CalculateNumChildren(max);
503   }
504 
505   if (!m_flags.m_children_count_valid) {
506     SetNumChildren(CalculateNumChildren());
507   }
508   return m_children.GetChildrenCount();
509 }
510 
511 bool ValueObject::MightHaveChildren() {
512   bool has_children = false;
513   const uint32_t type_info = GetTypeInfo();
514   if (type_info) {
515     if (type_info & (eTypeHasChildren | eTypeIsPointer | eTypeIsReference))
516       has_children = true;
517   } else {
518     has_children = GetNumChildren() > 0;
519   }
520   return has_children;
521 }
522 
523 // Should only be called by ValueObject::GetNumChildren()
524 void ValueObject::SetNumChildren(size_t num_children) {
525   m_flags.m_children_count_valid = true;
526   m_children.SetChildrenCount(num_children);
527 }
528 
529 ValueObject *ValueObject::CreateChildAtIndex(size_t idx,
530                                              bool synthetic_array_member,
531                                              int32_t synthetic_index) {
532   ValueObject *valobj = nullptr;
533 
534   bool omit_empty_base_classes = true;
535   bool ignore_array_bounds = synthetic_array_member;
536   std::string child_name_str;
537   uint32_t child_byte_size = 0;
538   int32_t child_byte_offset = 0;
539   uint32_t child_bitfield_bit_size = 0;
540   uint32_t child_bitfield_bit_offset = 0;
541   bool child_is_base_class = false;
542   bool child_is_deref_of_parent = false;
543   uint64_t language_flags = 0;
544 
545   const bool transparent_pointers = !synthetic_array_member;
546   CompilerType child_compiler_type;
547 
548   ExecutionContext exe_ctx(GetExecutionContextRef());
549 
550   child_compiler_type = GetCompilerType().GetChildCompilerTypeAtIndex(
551       &exe_ctx, idx, transparent_pointers, omit_empty_base_classes,
552       ignore_array_bounds, child_name_str, child_byte_size, child_byte_offset,
553       child_bitfield_bit_size, child_bitfield_bit_offset, child_is_base_class,
554       child_is_deref_of_parent, this, language_flags);
555   if (child_compiler_type) {
556     if (synthetic_index)
557       child_byte_offset += child_byte_size * synthetic_index;
558 
559     ConstString child_name;
560     if (!child_name_str.empty())
561       child_name.SetCString(child_name_str.c_str());
562 
563     valobj = new ValueObjectChild(
564         *this, child_compiler_type, child_name, child_byte_size,
565         child_byte_offset, child_bitfield_bit_size, child_bitfield_bit_offset,
566         child_is_base_class, child_is_deref_of_parent, eAddressTypeInvalid,
567         language_flags);
568   }
569 
570   // In case of an incomplete type, try to use the ValueObject's
571   // synthetic value to create the child ValueObject.
572   if (!valobj && synthetic_array_member) {
573     if (ValueObjectSP synth_valobj_sp = GetSyntheticValue()) {
574       valobj = synth_valobj_sp
575                    ->GetChildAtIndex(synthetic_index, synthetic_array_member)
576                    .get();
577     }
578   }
579 
580   return valobj;
581 }
582 
583 bool ValueObject::GetSummaryAsCString(TypeSummaryImpl *summary_ptr,
584                                       std::string &destination,
585                                       lldb::LanguageType lang) {
586   return GetSummaryAsCString(summary_ptr, destination,
587                              TypeSummaryOptions().SetLanguage(lang));
588 }
589 
590 bool ValueObject::GetSummaryAsCString(TypeSummaryImpl *summary_ptr,
591                                       std::string &destination,
592                                       const TypeSummaryOptions &options) {
593   destination.clear();
594 
595   // If we have a forcefully completed type, don't try and show a summary from
596   // a valid summary string or function because the type is not complete and
597   // no member variables or member functions will be available.
598   if (GetCompilerType().IsForcefullyCompleted()) {
599       destination = "<incomplete type>";
600       return true;
601   }
602 
603   // ideally we would like to bail out if passing NULL, but if we do so we end
604   // up not providing the summary for function pointers anymore
605   if (/*summary_ptr == NULL ||*/ m_flags.m_is_getting_summary)
606     return false;
607 
608   m_flags.m_is_getting_summary = true;
609 
610   TypeSummaryOptions actual_options(options);
611 
612   if (actual_options.GetLanguage() == lldb::eLanguageTypeUnknown)
613     actual_options.SetLanguage(GetPreferredDisplayLanguage());
614 
615   // this is a hot path in code and we prefer to avoid setting this string all
616   // too often also clearing out other information that we might care to see in
617   // a crash log. might be useful in very specific situations though.
618   /*Host::SetCrashDescriptionWithFormat("Trying to fetch a summary for %s %s.
619    Summary provider's description is %s",
620    GetTypeName().GetCString(),
621    GetName().GetCString(),
622    summary_ptr->GetDescription().c_str());*/
623 
624   if (UpdateValueIfNeeded(false) && summary_ptr) {
625     if (HasSyntheticValue())
626       m_synthetic_value->UpdateValueIfNeeded(); // the summary might depend on
627                                                 // the synthetic children being
628                                                 // up-to-date (e.g. ${svar%#})
629     summary_ptr->FormatObject(this, destination, actual_options);
630   }
631   m_flags.m_is_getting_summary = false;
632   return !destination.empty();
633 }
634 
635 const char *ValueObject::GetSummaryAsCString(lldb::LanguageType lang) {
636   if (UpdateValueIfNeeded(true) && m_summary_str.empty()) {
637     TypeSummaryOptions summary_options;
638     summary_options.SetLanguage(lang);
639     GetSummaryAsCString(GetSummaryFormat().get(), m_summary_str,
640                         summary_options);
641   }
642   if (m_summary_str.empty())
643     return nullptr;
644   return m_summary_str.c_str();
645 }
646 
647 bool ValueObject::GetSummaryAsCString(std::string &destination,
648                                       const TypeSummaryOptions &options) {
649   return GetSummaryAsCString(GetSummaryFormat().get(), destination, options);
650 }
651 
652 bool ValueObject::IsCStringContainer(bool check_pointer) {
653   CompilerType pointee_or_element_compiler_type;
654   const Flags type_flags(GetTypeInfo(&pointee_or_element_compiler_type));
655   bool is_char_arr_ptr(type_flags.AnySet(eTypeIsArray | eTypeIsPointer) &&
656                        pointee_or_element_compiler_type.IsCharType());
657   if (!is_char_arr_ptr)
658     return false;
659   if (!check_pointer)
660     return true;
661   if (type_flags.Test(eTypeIsArray))
662     return true;
663   addr_t cstr_address = LLDB_INVALID_ADDRESS;
664   AddressType cstr_address_type = eAddressTypeInvalid;
665   cstr_address = GetPointerValue(&cstr_address_type);
666   return (cstr_address != LLDB_INVALID_ADDRESS);
667 }
668 
669 size_t ValueObject::GetPointeeData(DataExtractor &data, uint32_t item_idx,
670                                    uint32_t item_count) {
671   CompilerType pointee_or_element_compiler_type;
672   const uint32_t type_info = GetTypeInfo(&pointee_or_element_compiler_type);
673   const bool is_pointer_type = type_info & eTypeIsPointer;
674   const bool is_array_type = type_info & eTypeIsArray;
675   if (!(is_pointer_type || is_array_type))
676     return 0;
677 
678   if (item_count == 0)
679     return 0;
680 
681   ExecutionContext exe_ctx(GetExecutionContextRef());
682 
683   std::optional<uint64_t> item_type_size =
684       pointee_or_element_compiler_type.GetByteSize(
685           exe_ctx.GetBestExecutionContextScope());
686   if (!item_type_size)
687     return 0;
688   const uint64_t bytes = item_count * *item_type_size;
689   const uint64_t offset = item_idx * *item_type_size;
690 
691   if (item_idx == 0 && item_count == 1) // simply a deref
692   {
693     if (is_pointer_type) {
694       Status error;
695       ValueObjectSP pointee_sp = Dereference(error);
696       if (error.Fail() || pointee_sp.get() == nullptr)
697         return 0;
698       return pointee_sp->GetData(data, error);
699     } else {
700       ValueObjectSP child_sp = GetChildAtIndex(0);
701       if (child_sp.get() == nullptr)
702         return 0;
703       Status error;
704       return child_sp->GetData(data, error);
705     }
706     return true;
707   } else /* (items > 1) */
708   {
709     Status error;
710     lldb_private::DataBufferHeap *heap_buf_ptr = nullptr;
711     lldb::DataBufferSP data_sp(heap_buf_ptr =
712                                    new lldb_private::DataBufferHeap());
713 
714     AddressType addr_type;
715     lldb::addr_t addr = is_pointer_type ? GetPointerValue(&addr_type)
716                                         : GetAddressOf(true, &addr_type);
717 
718     switch (addr_type) {
719     case eAddressTypeFile: {
720       ModuleSP module_sp(GetModule());
721       if (module_sp) {
722         addr = addr + offset;
723         Address so_addr;
724         module_sp->ResolveFileAddress(addr, so_addr);
725         ExecutionContext exe_ctx(GetExecutionContextRef());
726         Target *target = exe_ctx.GetTargetPtr();
727         if (target) {
728           heap_buf_ptr->SetByteSize(bytes);
729           size_t bytes_read = target->ReadMemory(
730               so_addr, heap_buf_ptr->GetBytes(), bytes, error, true);
731           if (error.Success()) {
732             data.SetData(data_sp);
733             return bytes_read;
734           }
735         }
736       }
737     } break;
738     case eAddressTypeLoad: {
739       ExecutionContext exe_ctx(GetExecutionContextRef());
740       Process *process = exe_ctx.GetProcessPtr();
741       if (process) {
742         heap_buf_ptr->SetByteSize(bytes);
743         size_t bytes_read = process->ReadMemory(
744             addr + offset, heap_buf_ptr->GetBytes(), bytes, error);
745         if (error.Success() || bytes_read > 0) {
746           data.SetData(data_sp);
747           return bytes_read;
748         }
749       }
750     } break;
751     case eAddressTypeHost: {
752       auto max_bytes =
753           GetCompilerType().GetByteSize(exe_ctx.GetBestExecutionContextScope());
754       if (max_bytes && *max_bytes > offset) {
755         size_t bytes_read = std::min<uint64_t>(*max_bytes - offset, bytes);
756         addr = m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
757         if (addr == 0 || addr == LLDB_INVALID_ADDRESS)
758           break;
759         heap_buf_ptr->CopyData((uint8_t *)(addr + offset), bytes_read);
760         data.SetData(data_sp);
761         return bytes_read;
762       }
763     } break;
764     case eAddressTypeInvalid:
765       break;
766     }
767   }
768   return 0;
769 }
770 
771 uint64_t ValueObject::GetData(DataExtractor &data, Status &error) {
772   UpdateValueIfNeeded(false);
773   ExecutionContext exe_ctx(GetExecutionContextRef());
774   error = m_value.GetValueAsData(&exe_ctx, data, GetModule().get());
775   if (error.Fail()) {
776     if (m_data.GetByteSize()) {
777       data = m_data;
778       error.Clear();
779       return data.GetByteSize();
780     } else {
781       return 0;
782     }
783   }
784   data.SetAddressByteSize(m_data.GetAddressByteSize());
785   data.SetByteOrder(m_data.GetByteOrder());
786   return data.GetByteSize();
787 }
788 
789 bool ValueObject::SetData(DataExtractor &data, Status &error) {
790   error.Clear();
791   // Make sure our value is up to date first so that our location and location
792   // type is valid.
793   if (!UpdateValueIfNeeded(false)) {
794     error.SetErrorString("unable to read value");
795     return false;
796   }
797 
798   uint64_t count = 0;
799   const Encoding encoding = GetCompilerType().GetEncoding(count);
800 
801   const size_t byte_size = GetByteSize().value_or(0);
802 
803   Value::ValueType value_type = m_value.GetValueType();
804 
805   switch (value_type) {
806   case Value::ValueType::Invalid:
807     error.SetErrorString("invalid location");
808     return false;
809   case Value::ValueType::Scalar: {
810     Status set_error =
811         m_value.GetScalar().SetValueFromData(data, encoding, byte_size);
812 
813     if (!set_error.Success()) {
814       error.SetErrorStringWithFormat("unable to set scalar value: %s",
815                                      set_error.AsCString());
816       return false;
817     }
818   } break;
819   case Value::ValueType::LoadAddress: {
820     // If it is a load address, then the scalar value is the storage location
821     // of the data, and we have to shove this value down to that load location.
822     ExecutionContext exe_ctx(GetExecutionContextRef());
823     Process *process = exe_ctx.GetProcessPtr();
824     if (process) {
825       addr_t target_addr = m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
826       size_t bytes_written = process->WriteMemory(
827           target_addr, data.GetDataStart(), byte_size, error);
828       if (!error.Success())
829         return false;
830       if (bytes_written != byte_size) {
831         error.SetErrorString("unable to write value to memory");
832         return false;
833       }
834     }
835   } break;
836   case Value::ValueType::HostAddress: {
837     // If it is a host address, then we stuff the scalar as a DataBuffer into
838     // the Value's data.
839     DataBufferSP buffer_sp(new DataBufferHeap(byte_size, 0));
840     m_data.SetData(buffer_sp, 0);
841     data.CopyByteOrderedData(0, byte_size,
842                              const_cast<uint8_t *>(m_data.GetDataStart()),
843                              byte_size, m_data.GetByteOrder());
844     m_value.GetScalar() = (uintptr_t)m_data.GetDataStart();
845   } break;
846   case Value::ValueType::FileAddress:
847     break;
848   }
849 
850   // If we have reached this point, then we have successfully changed the
851   // value.
852   SetNeedsUpdate();
853   return true;
854 }
855 
856 static bool CopyStringDataToBufferSP(const StreamString &source,
857                                      lldb::WritableDataBufferSP &destination) {
858   llvm::StringRef src = source.GetString();
859   src = src.rtrim('\0');
860   destination = std::make_shared<DataBufferHeap>(src.size(), 0);
861   memcpy(destination->GetBytes(), src.data(), src.size());
862   return true;
863 }
864 
865 std::pair<size_t, bool>
866 ValueObject::ReadPointedString(lldb::WritableDataBufferSP &buffer_sp,
867                                Status &error, uint32_t max_length,
868                                bool honor_array, Format item_format) {
869   bool was_capped = false;
870   StreamString s;
871   ExecutionContext exe_ctx(GetExecutionContextRef());
872   Target *target = exe_ctx.GetTargetPtr();
873 
874   if (!target) {
875     s << "<no target to read from>";
876     error.SetErrorString("no target to read from");
877     CopyStringDataToBufferSP(s, buffer_sp);
878     return {0, was_capped};
879   }
880 
881   if (max_length == 0)
882     max_length = target->GetMaximumSizeOfStringSummary();
883 
884   size_t bytes_read = 0;
885   size_t total_bytes_read = 0;
886 
887   CompilerType compiler_type = GetCompilerType();
888   CompilerType elem_or_pointee_compiler_type;
889   const Flags type_flags(GetTypeInfo(&elem_or_pointee_compiler_type));
890   if (type_flags.AnySet(eTypeIsArray | eTypeIsPointer) &&
891       elem_or_pointee_compiler_type.IsCharType()) {
892     addr_t cstr_address = LLDB_INVALID_ADDRESS;
893     AddressType cstr_address_type = eAddressTypeInvalid;
894 
895     size_t cstr_len = 0;
896     bool capped_data = false;
897     const bool is_array = type_flags.Test(eTypeIsArray);
898     if (is_array) {
899       // We have an array
900       uint64_t array_size = 0;
901       if (compiler_type.IsArrayType(nullptr, &array_size)) {
902         cstr_len = array_size;
903         if (cstr_len > max_length) {
904           capped_data = true;
905           cstr_len = max_length;
906         }
907       }
908       cstr_address = GetAddressOf(true, &cstr_address_type);
909     } else {
910       // We have a pointer
911       cstr_address = GetPointerValue(&cstr_address_type);
912     }
913 
914     if (cstr_address == 0 || cstr_address == LLDB_INVALID_ADDRESS) {
915       if (cstr_address_type == eAddressTypeHost && is_array) {
916         const char *cstr = GetDataExtractor().PeekCStr(0);
917         if (cstr == nullptr) {
918           s << "<invalid address>";
919           error.SetErrorString("invalid address");
920           CopyStringDataToBufferSP(s, buffer_sp);
921           return {0, was_capped};
922         }
923         s << llvm::StringRef(cstr, cstr_len);
924         CopyStringDataToBufferSP(s, buffer_sp);
925         return {cstr_len, was_capped};
926       } else {
927         s << "<invalid address>";
928         error.SetErrorString("invalid address");
929         CopyStringDataToBufferSP(s, buffer_sp);
930         return {0, was_capped};
931       }
932     }
933 
934     Address cstr_so_addr(cstr_address);
935     DataExtractor data;
936     if (cstr_len > 0 && honor_array) {
937       // I am using GetPointeeData() here to abstract the fact that some
938       // ValueObjects are actually frozen pointers in the host but the pointed-
939       // to data lives in the debuggee, and GetPointeeData() automatically
940       // takes care of this
941       GetPointeeData(data, 0, cstr_len);
942 
943       if ((bytes_read = data.GetByteSize()) > 0) {
944         total_bytes_read = bytes_read;
945         for (size_t offset = 0; offset < bytes_read; offset++)
946           s.Printf("%c", *data.PeekData(offset, 1));
947         if (capped_data)
948           was_capped = true;
949       }
950     } else {
951       cstr_len = max_length;
952       const size_t k_max_buf_size = 64;
953 
954       size_t offset = 0;
955 
956       int cstr_len_displayed = -1;
957       bool capped_cstr = false;
958       // I am using GetPointeeData() here to abstract the fact that some
959       // ValueObjects are actually frozen pointers in the host but the pointed-
960       // to data lives in the debuggee, and GetPointeeData() automatically
961       // takes care of this
962       while ((bytes_read = GetPointeeData(data, offset, k_max_buf_size)) > 0) {
963         total_bytes_read += bytes_read;
964         const char *cstr = data.PeekCStr(0);
965         size_t len = strnlen(cstr, k_max_buf_size);
966         if (cstr_len_displayed < 0)
967           cstr_len_displayed = len;
968 
969         if (len == 0)
970           break;
971         cstr_len_displayed += len;
972         if (len > bytes_read)
973           len = bytes_read;
974         if (len > cstr_len)
975           len = cstr_len;
976 
977         for (size_t offset = 0; offset < bytes_read; offset++)
978           s.Printf("%c", *data.PeekData(offset, 1));
979 
980         if (len < k_max_buf_size)
981           break;
982 
983         if (len >= cstr_len) {
984           capped_cstr = true;
985           break;
986         }
987 
988         cstr_len -= len;
989         offset += len;
990       }
991 
992       if (cstr_len_displayed >= 0) {
993         if (capped_cstr)
994           was_capped = true;
995       }
996     }
997   } else {
998     error.SetErrorString("not a string object");
999     s << "<not a string object>";
1000   }
1001   CopyStringDataToBufferSP(s, buffer_sp);
1002   return {total_bytes_read, was_capped};
1003 }
1004 
1005 const char *ValueObject::GetObjectDescription() {
1006   if (!UpdateValueIfNeeded(true))
1007     return nullptr;
1008 
1009   // Return cached value.
1010   if (!m_object_desc_str.empty())
1011     return m_object_desc_str.c_str();
1012 
1013   ExecutionContext exe_ctx(GetExecutionContextRef());
1014   Process *process = exe_ctx.GetProcessPtr();
1015   if (!process)
1016     return nullptr;
1017 
1018   // Returns the object description produced by one language runtime.
1019   auto get_object_description = [&](LanguageType language) -> const char * {
1020     if (LanguageRuntime *runtime = process->GetLanguageRuntime(language)) {
1021       StreamString s;
1022       if (runtime->GetObjectDescription(s, *this)) {
1023         m_object_desc_str.append(std::string(s.GetString()));
1024         return m_object_desc_str.c_str();
1025       }
1026     }
1027     return nullptr;
1028   };
1029 
1030   // Try the native language runtime first.
1031   LanguageType native_language = GetObjectRuntimeLanguage();
1032   if (const char *desc = get_object_description(native_language))
1033     return desc;
1034 
1035   // Try the Objective-C language runtime. This fallback is necessary
1036   // for Objective-C++ and mixed Objective-C / C++ programs.
1037   if (Language::LanguageIsCFamily(native_language))
1038     return get_object_description(eLanguageTypeObjC);
1039   return nullptr;
1040 }
1041 
1042 bool ValueObject::GetValueAsCString(const lldb_private::TypeFormatImpl &format,
1043                                     std::string &destination) {
1044   if (UpdateValueIfNeeded(false))
1045     return format.FormatObject(this, destination);
1046   else
1047     return false;
1048 }
1049 
1050 bool ValueObject::GetValueAsCString(lldb::Format format,
1051                                     std::string &destination) {
1052   return GetValueAsCString(TypeFormatImpl_Format(format), destination);
1053 }
1054 
1055 const char *ValueObject::GetValueAsCString() {
1056   if (UpdateValueIfNeeded(true)) {
1057     lldb::TypeFormatImplSP format_sp;
1058     lldb::Format my_format = GetFormat();
1059     if (my_format == lldb::eFormatDefault) {
1060       if (m_type_format_sp)
1061         format_sp = m_type_format_sp;
1062       else {
1063         if (m_flags.m_is_bitfield_for_scalar)
1064           my_format = eFormatUnsigned;
1065         else {
1066           if (m_value.GetContextType() == Value::ContextType::RegisterInfo) {
1067             const RegisterInfo *reg_info = m_value.GetRegisterInfo();
1068             if (reg_info)
1069               my_format = reg_info->format;
1070           } else {
1071             my_format = GetValue().GetCompilerType().GetFormat();
1072           }
1073         }
1074       }
1075     }
1076     if (my_format != m_last_format || m_value_str.empty()) {
1077       m_last_format = my_format;
1078       if (!format_sp)
1079         format_sp = std::make_shared<TypeFormatImpl_Format>(my_format);
1080       if (GetValueAsCString(*format_sp.get(), m_value_str)) {
1081         if (!m_flags.m_value_did_change && m_flags.m_old_value_valid) {
1082           // The value was gotten successfully, so we consider the value as
1083           // changed if the value string differs
1084           SetValueDidChange(m_old_value_str != m_value_str);
1085         }
1086       }
1087     }
1088   }
1089   if (m_value_str.empty())
1090     return nullptr;
1091   return m_value_str.c_str();
1092 }
1093 
1094 // if > 8bytes, 0 is returned. this method should mostly be used to read
1095 // address values out of pointers
1096 uint64_t ValueObject::GetValueAsUnsigned(uint64_t fail_value, bool *success) {
1097   // If our byte size is zero this is an aggregate type that has children
1098   if (CanProvideValue()) {
1099     Scalar scalar;
1100     if (ResolveValue(scalar)) {
1101       if (success)
1102         *success = true;
1103       scalar.MakeUnsigned();
1104       return scalar.ULongLong(fail_value);
1105     }
1106     // fallthrough, otherwise...
1107   }
1108 
1109   if (success)
1110     *success = false;
1111   return fail_value;
1112 }
1113 
1114 int64_t ValueObject::GetValueAsSigned(int64_t fail_value, bool *success) {
1115   // If our byte size is zero this is an aggregate type that has children
1116   if (CanProvideValue()) {
1117     Scalar scalar;
1118     if (ResolveValue(scalar)) {
1119       if (success)
1120         *success = true;
1121       scalar.MakeSigned();
1122       return scalar.SLongLong(fail_value);
1123     }
1124     // fallthrough, otherwise...
1125   }
1126 
1127   if (success)
1128     *success = false;
1129   return fail_value;
1130 }
1131 
1132 // if any more "special cases" are added to
1133 // ValueObject::DumpPrintableRepresentation() please keep this call up to date
1134 // by returning true for your new special cases. We will eventually move to
1135 // checking this call result before trying to display special cases
1136 bool ValueObject::HasSpecialPrintableRepresentation(
1137     ValueObjectRepresentationStyle val_obj_display, Format custom_format) {
1138   Flags flags(GetTypeInfo());
1139   if (flags.AnySet(eTypeIsArray | eTypeIsPointer) &&
1140       val_obj_display == ValueObject::eValueObjectRepresentationStyleValue) {
1141     if (IsCStringContainer(true) &&
1142         (custom_format == eFormatCString || custom_format == eFormatCharArray ||
1143          custom_format == eFormatChar || custom_format == eFormatVectorOfChar))
1144       return true;
1145 
1146     if (flags.Test(eTypeIsArray)) {
1147       if ((custom_format == eFormatBytes) ||
1148           (custom_format == eFormatBytesWithASCII))
1149         return true;
1150 
1151       if ((custom_format == eFormatVectorOfChar) ||
1152           (custom_format == eFormatVectorOfFloat32) ||
1153           (custom_format == eFormatVectorOfFloat64) ||
1154           (custom_format == eFormatVectorOfSInt16) ||
1155           (custom_format == eFormatVectorOfSInt32) ||
1156           (custom_format == eFormatVectorOfSInt64) ||
1157           (custom_format == eFormatVectorOfSInt8) ||
1158           (custom_format == eFormatVectorOfUInt128) ||
1159           (custom_format == eFormatVectorOfUInt16) ||
1160           (custom_format == eFormatVectorOfUInt32) ||
1161           (custom_format == eFormatVectorOfUInt64) ||
1162           (custom_format == eFormatVectorOfUInt8))
1163         return true;
1164     }
1165   }
1166   return false;
1167 }
1168 
1169 bool ValueObject::DumpPrintableRepresentation(
1170     Stream &s, ValueObjectRepresentationStyle val_obj_display,
1171     Format custom_format, PrintableRepresentationSpecialCases special,
1172     bool do_dump_error) {
1173 
1174   // If the ValueObject has an error, we might end up dumping the type, which
1175   // is useful, but if we don't even have a type, then don't examine the object
1176   // further as that's not meaningful, only the error is.
1177   if (m_error.Fail() && !GetCompilerType().IsValid()) {
1178     if (do_dump_error)
1179       s.Printf("<%s>", m_error.AsCString());
1180     return false;
1181   }
1182 
1183   Flags flags(GetTypeInfo());
1184 
1185   bool allow_special =
1186       (special == ValueObject::PrintableRepresentationSpecialCases::eAllow);
1187   const bool only_special = false;
1188 
1189   if (allow_special) {
1190     if (flags.AnySet(eTypeIsArray | eTypeIsPointer) &&
1191         val_obj_display == ValueObject::eValueObjectRepresentationStyleValue) {
1192       // when being asked to get a printable display an array or pointer type
1193       // directly, try to "do the right thing"
1194 
1195       if (IsCStringContainer(true) &&
1196           (custom_format == eFormatCString ||
1197            custom_format == eFormatCharArray || custom_format == eFormatChar ||
1198            custom_format ==
1199                eFormatVectorOfChar)) // print char[] & char* directly
1200       {
1201         Status error;
1202         lldb::WritableDataBufferSP buffer_sp;
1203         std::pair<size_t, bool> read_string = ReadPointedString(
1204             buffer_sp, error, 0, (custom_format == eFormatVectorOfChar) ||
1205                                      (custom_format == eFormatCharArray));
1206         lldb_private::formatters::StringPrinter::
1207             ReadBufferAndDumpToStreamOptions options(*this);
1208         options.SetData(DataExtractor(
1209             buffer_sp, lldb::eByteOrderInvalid,
1210             8)); // none of this matters for a string - pass some defaults
1211         options.SetStream(&s);
1212         options.SetPrefixToken(nullptr);
1213         options.SetQuote('"');
1214         options.SetSourceSize(buffer_sp->GetByteSize());
1215         options.SetIsTruncated(read_string.second);
1216         options.SetBinaryZeroIsTerminator(custom_format != eFormatVectorOfChar);
1217         formatters::StringPrinter::ReadBufferAndDumpToStream<
1218             lldb_private::formatters::StringPrinter::StringElementType::ASCII>(
1219             options);
1220         return !error.Fail();
1221       }
1222 
1223       if (custom_format == eFormatEnum)
1224         return false;
1225 
1226       // this only works for arrays, because I have no way to know when the
1227       // pointed memory ends, and no special \0 end of data marker
1228       if (flags.Test(eTypeIsArray)) {
1229         if ((custom_format == eFormatBytes) ||
1230             (custom_format == eFormatBytesWithASCII)) {
1231           const size_t count = GetNumChildren();
1232 
1233           s << '[';
1234           for (size_t low = 0; low < count; low++) {
1235 
1236             if (low)
1237               s << ',';
1238 
1239             ValueObjectSP child = GetChildAtIndex(low);
1240             if (!child.get()) {
1241               s << "<invalid child>";
1242               continue;
1243             }
1244             child->DumpPrintableRepresentation(
1245                 s, ValueObject::eValueObjectRepresentationStyleValue,
1246                 custom_format);
1247           }
1248 
1249           s << ']';
1250 
1251           return true;
1252         }
1253 
1254         if ((custom_format == eFormatVectorOfChar) ||
1255             (custom_format == eFormatVectorOfFloat32) ||
1256             (custom_format == eFormatVectorOfFloat64) ||
1257             (custom_format == eFormatVectorOfSInt16) ||
1258             (custom_format == eFormatVectorOfSInt32) ||
1259             (custom_format == eFormatVectorOfSInt64) ||
1260             (custom_format == eFormatVectorOfSInt8) ||
1261             (custom_format == eFormatVectorOfUInt128) ||
1262             (custom_format == eFormatVectorOfUInt16) ||
1263             (custom_format == eFormatVectorOfUInt32) ||
1264             (custom_format == eFormatVectorOfUInt64) ||
1265             (custom_format == eFormatVectorOfUInt8)) // arrays of bytes, bytes
1266                                                      // with ASCII or any vector
1267                                                      // format should be printed
1268                                                      // directly
1269         {
1270           const size_t count = GetNumChildren();
1271 
1272           Format format = FormatManager::GetSingleItemFormat(custom_format);
1273 
1274           s << '[';
1275           for (size_t low = 0; low < count; low++) {
1276 
1277             if (low)
1278               s << ',';
1279 
1280             ValueObjectSP child = GetChildAtIndex(low);
1281             if (!child.get()) {
1282               s << "<invalid child>";
1283               continue;
1284             }
1285             child->DumpPrintableRepresentation(
1286                 s, ValueObject::eValueObjectRepresentationStyleValue, format);
1287           }
1288 
1289           s << ']';
1290 
1291           return true;
1292         }
1293       }
1294 
1295       if ((custom_format == eFormatBoolean) ||
1296           (custom_format == eFormatBinary) || (custom_format == eFormatChar) ||
1297           (custom_format == eFormatCharPrintable) ||
1298           (custom_format == eFormatComplexFloat) ||
1299           (custom_format == eFormatDecimal) || (custom_format == eFormatHex) ||
1300           (custom_format == eFormatHexUppercase) ||
1301           (custom_format == eFormatFloat) || (custom_format == eFormatOctal) ||
1302           (custom_format == eFormatOSType) ||
1303           (custom_format == eFormatUnicode16) ||
1304           (custom_format == eFormatUnicode32) ||
1305           (custom_format == eFormatUnsigned) ||
1306           (custom_format == eFormatPointer) ||
1307           (custom_format == eFormatComplexInteger) ||
1308           (custom_format == eFormatComplex) ||
1309           (custom_format == eFormatDefault)) // use the [] operator
1310         return false;
1311     }
1312   }
1313 
1314   if (only_special)
1315     return false;
1316 
1317   bool var_success = false;
1318 
1319   {
1320     llvm::StringRef str;
1321 
1322     // this is a local stream that we are using to ensure that the data pointed
1323     // to by cstr survives long enough for us to copy it to its destination -
1324     // it is necessary to have this temporary storage area for cases where our
1325     // desired output is not backed by some other longer-term storage
1326     StreamString strm;
1327 
1328     if (custom_format != eFormatInvalid)
1329       SetFormat(custom_format);
1330 
1331     switch (val_obj_display) {
1332     case eValueObjectRepresentationStyleValue:
1333       str = GetValueAsCString();
1334       break;
1335 
1336     case eValueObjectRepresentationStyleSummary:
1337       str = GetSummaryAsCString();
1338       break;
1339 
1340     case eValueObjectRepresentationStyleLanguageSpecific:
1341       str = GetObjectDescription();
1342       break;
1343 
1344     case eValueObjectRepresentationStyleLocation:
1345       str = GetLocationAsCString();
1346       break;
1347 
1348     case eValueObjectRepresentationStyleChildrenCount:
1349       strm.Printf("%" PRIu64 "", (uint64_t)GetNumChildren());
1350       str = strm.GetString();
1351       break;
1352 
1353     case eValueObjectRepresentationStyleType:
1354       str = GetTypeName().GetStringRef();
1355       break;
1356 
1357     case eValueObjectRepresentationStyleName:
1358       str = GetName().GetStringRef();
1359       break;
1360 
1361     case eValueObjectRepresentationStyleExpressionPath:
1362       GetExpressionPath(strm);
1363       str = strm.GetString();
1364       break;
1365     }
1366 
1367     if (str.empty()) {
1368       if (val_obj_display == eValueObjectRepresentationStyleValue)
1369         str = GetSummaryAsCString();
1370       else if (val_obj_display == eValueObjectRepresentationStyleSummary) {
1371         if (!CanProvideValue()) {
1372           strm.Printf("%s @ %s", GetTypeName().AsCString(),
1373                       GetLocationAsCString());
1374           str = strm.GetString();
1375         } else
1376           str = GetValueAsCString();
1377       }
1378     }
1379 
1380     if (!str.empty())
1381       s << str;
1382     else {
1383       // We checked for errors at the start, but do it again here in case
1384       // realizing the value for dumping produced an error.
1385       if (m_error.Fail()) {
1386         if (do_dump_error)
1387           s.Printf("<%s>", m_error.AsCString());
1388         else
1389           return false;
1390       } else if (val_obj_display == eValueObjectRepresentationStyleSummary)
1391         s.PutCString("<no summary available>");
1392       else if (val_obj_display == eValueObjectRepresentationStyleValue)
1393         s.PutCString("<no value available>");
1394       else if (val_obj_display ==
1395                eValueObjectRepresentationStyleLanguageSpecific)
1396         s.PutCString("<not a valid Objective-C object>"); // edit this if we
1397                                                           // have other runtimes
1398                                                           // that support a
1399                                                           // description
1400       else
1401         s.PutCString("<no printable representation>");
1402     }
1403 
1404     // we should only return false here if we could not do *anything* even if
1405     // we have an error message as output, that's a success from our callers'
1406     // perspective, so return true
1407     var_success = true;
1408 
1409     if (custom_format != eFormatInvalid)
1410       SetFormat(eFormatDefault);
1411   }
1412 
1413   return var_success;
1414 }
1415 
1416 addr_t ValueObject::GetAddressOf(bool scalar_is_load_address,
1417                                  AddressType *address_type) {
1418   // Can't take address of a bitfield
1419   if (IsBitfield())
1420     return LLDB_INVALID_ADDRESS;
1421 
1422   if (!UpdateValueIfNeeded(false))
1423     return LLDB_INVALID_ADDRESS;
1424 
1425   switch (m_value.GetValueType()) {
1426   case Value::ValueType::Invalid:
1427     return LLDB_INVALID_ADDRESS;
1428   case Value::ValueType::Scalar:
1429     if (scalar_is_load_address) {
1430       if (address_type)
1431         *address_type = eAddressTypeLoad;
1432       return m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
1433     }
1434     break;
1435 
1436   case Value::ValueType::LoadAddress:
1437   case Value::ValueType::FileAddress: {
1438     if (address_type)
1439       *address_type = m_value.GetValueAddressType();
1440     return m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
1441   } break;
1442   case Value::ValueType::HostAddress: {
1443     if (address_type)
1444       *address_type = m_value.GetValueAddressType();
1445     return LLDB_INVALID_ADDRESS;
1446   } break;
1447   }
1448   if (address_type)
1449     *address_type = eAddressTypeInvalid;
1450   return LLDB_INVALID_ADDRESS;
1451 }
1452 
1453 addr_t ValueObject::GetPointerValue(AddressType *address_type) {
1454   addr_t address = LLDB_INVALID_ADDRESS;
1455   if (address_type)
1456     *address_type = eAddressTypeInvalid;
1457 
1458   if (!UpdateValueIfNeeded(false))
1459     return address;
1460 
1461   switch (m_value.GetValueType()) {
1462   case Value::ValueType::Invalid:
1463     return LLDB_INVALID_ADDRESS;
1464   case Value::ValueType::Scalar:
1465     address = m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
1466     break;
1467 
1468   case Value::ValueType::HostAddress:
1469   case Value::ValueType::LoadAddress:
1470   case Value::ValueType::FileAddress: {
1471     lldb::offset_t data_offset = 0;
1472     address = m_data.GetAddress(&data_offset);
1473   } break;
1474   }
1475 
1476   if (address_type)
1477     *address_type = GetAddressTypeOfChildren();
1478 
1479   return address;
1480 }
1481 
1482 bool ValueObject::SetValueFromCString(const char *value_str, Status &error) {
1483   error.Clear();
1484   // Make sure our value is up to date first so that our location and location
1485   // type is valid.
1486   if (!UpdateValueIfNeeded(false)) {
1487     error.SetErrorString("unable to read value");
1488     return false;
1489   }
1490 
1491   uint64_t count = 0;
1492   const Encoding encoding = GetCompilerType().GetEncoding(count);
1493 
1494   const size_t byte_size = GetByteSize().value_or(0);
1495 
1496   Value::ValueType value_type = m_value.GetValueType();
1497 
1498   if (value_type == Value::ValueType::Scalar) {
1499     // If the value is already a scalar, then let the scalar change itself:
1500     m_value.GetScalar().SetValueFromCString(value_str, encoding, byte_size);
1501   } else if (byte_size <= 16) {
1502     // If the value fits in a scalar, then make a new scalar and again let the
1503     // scalar code do the conversion, then figure out where to put the new
1504     // value.
1505     Scalar new_scalar;
1506     error = new_scalar.SetValueFromCString(value_str, encoding, byte_size);
1507     if (error.Success()) {
1508       switch (value_type) {
1509       case Value::ValueType::LoadAddress: {
1510         // If it is a load address, then the scalar value is the storage
1511         // location of the data, and we have to shove this value down to that
1512         // load location.
1513         ExecutionContext exe_ctx(GetExecutionContextRef());
1514         Process *process = exe_ctx.GetProcessPtr();
1515         if (process) {
1516           addr_t target_addr =
1517               m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
1518           size_t bytes_written = process->WriteScalarToMemory(
1519               target_addr, new_scalar, byte_size, error);
1520           if (!error.Success())
1521             return false;
1522           if (bytes_written != byte_size) {
1523             error.SetErrorString("unable to write value to memory");
1524             return false;
1525           }
1526         }
1527       } break;
1528       case Value::ValueType::HostAddress: {
1529         // If it is a host address, then we stuff the scalar as a DataBuffer
1530         // into the Value's data.
1531         DataExtractor new_data;
1532         new_data.SetByteOrder(m_data.GetByteOrder());
1533 
1534         DataBufferSP buffer_sp(new DataBufferHeap(byte_size, 0));
1535         m_data.SetData(buffer_sp, 0);
1536         bool success = new_scalar.GetData(new_data);
1537         if (success) {
1538           new_data.CopyByteOrderedData(
1539               0, byte_size, const_cast<uint8_t *>(m_data.GetDataStart()),
1540               byte_size, m_data.GetByteOrder());
1541         }
1542         m_value.GetScalar() = (uintptr_t)m_data.GetDataStart();
1543 
1544       } break;
1545       case Value::ValueType::Invalid:
1546         error.SetErrorString("invalid location");
1547         return false;
1548       case Value::ValueType::FileAddress:
1549       case Value::ValueType::Scalar:
1550         break;
1551       }
1552     } else {
1553       return false;
1554     }
1555   } else {
1556     // We don't support setting things bigger than a scalar at present.
1557     error.SetErrorString("unable to write aggregate data type");
1558     return false;
1559   }
1560 
1561   // If we have reached this point, then we have successfully changed the
1562   // value.
1563   SetNeedsUpdate();
1564   return true;
1565 }
1566 
1567 bool ValueObject::GetDeclaration(Declaration &decl) {
1568   decl.Clear();
1569   return false;
1570 }
1571 
1572 void ValueObject::AddSyntheticChild(ConstString key,
1573                                     ValueObject *valobj) {
1574   m_synthetic_children[key] = valobj;
1575 }
1576 
1577 ValueObjectSP ValueObject::GetSyntheticChild(ConstString key) const {
1578   ValueObjectSP synthetic_child_sp;
1579   std::map<ConstString, ValueObject *>::const_iterator pos =
1580       m_synthetic_children.find(key);
1581   if (pos != m_synthetic_children.end())
1582     synthetic_child_sp = pos->second->GetSP();
1583   return synthetic_child_sp;
1584 }
1585 
1586 bool ValueObject::IsPossibleDynamicType() {
1587   ExecutionContext exe_ctx(GetExecutionContextRef());
1588   Process *process = exe_ctx.GetProcessPtr();
1589   if (process)
1590     return process->IsPossibleDynamicValue(*this);
1591   else
1592     return GetCompilerType().IsPossibleDynamicType(nullptr, true, true);
1593 }
1594 
1595 bool ValueObject::IsRuntimeSupportValue() {
1596   Process *process(GetProcessSP().get());
1597   if (!process)
1598     return false;
1599 
1600   // We trust that the compiler did the right thing and marked runtime support
1601   // values as artificial.
1602   if (!GetVariable() || !GetVariable()->IsArtificial())
1603     return false;
1604 
1605   if (auto *runtime = process->GetLanguageRuntime(GetVariable()->GetLanguage()))
1606     if (runtime->IsAllowedRuntimeValue(GetName()))
1607       return false;
1608 
1609   return true;
1610 }
1611 
1612 bool ValueObject::IsNilReference() {
1613   if (Language *language = Language::FindPlugin(GetObjectRuntimeLanguage())) {
1614     return language->IsNilReference(*this);
1615   }
1616   return false;
1617 }
1618 
1619 bool ValueObject::IsUninitializedReference() {
1620   if (Language *language = Language::FindPlugin(GetObjectRuntimeLanguage())) {
1621     return language->IsUninitializedReference(*this);
1622   }
1623   return false;
1624 }
1625 
1626 // This allows you to create an array member using and index that doesn't not
1627 // fall in the normal bounds of the array. Many times structure can be defined
1628 // as: struct Collection {
1629 //     uint32_t item_count;
1630 //     Item item_array[0];
1631 // };
1632 // The size of the "item_array" is 1, but many times in practice there are more
1633 // items in "item_array".
1634 
1635 ValueObjectSP ValueObject::GetSyntheticArrayMember(size_t index,
1636                                                    bool can_create) {
1637   ValueObjectSP synthetic_child_sp;
1638   if (IsPointerType() || IsArrayType()) {
1639     std::string index_str = llvm::formatv("[{0}]", index);
1640     ConstString index_const_str(index_str);
1641     // Check if we have already created a synthetic array member in this valid
1642     // object. If we have we will re-use it.
1643     synthetic_child_sp = GetSyntheticChild(index_const_str);
1644     if (!synthetic_child_sp) {
1645       ValueObject *synthetic_child;
1646       // We haven't made a synthetic array member for INDEX yet, so lets make
1647       // one and cache it for any future reference.
1648       synthetic_child = CreateChildAtIndex(0, true, index);
1649 
1650       // Cache the value if we got one back...
1651       if (synthetic_child) {
1652         AddSyntheticChild(index_const_str, synthetic_child);
1653         synthetic_child_sp = synthetic_child->GetSP();
1654         synthetic_child_sp->SetName(ConstString(index_str));
1655         synthetic_child_sp->m_flags.m_is_array_item_for_pointer = true;
1656       }
1657     }
1658   }
1659   return synthetic_child_sp;
1660 }
1661 
1662 ValueObjectSP ValueObject::GetSyntheticBitFieldChild(uint32_t from, uint32_t to,
1663                                                      bool can_create) {
1664   ValueObjectSP synthetic_child_sp;
1665   if (IsScalarType()) {
1666     std::string index_str = llvm::formatv("[{0}-{1}]", from, to);
1667     ConstString index_const_str(index_str);
1668     // Check if we have already created a synthetic array member in this valid
1669     // object. If we have we will re-use it.
1670     synthetic_child_sp = GetSyntheticChild(index_const_str);
1671     if (!synthetic_child_sp) {
1672       uint32_t bit_field_size = to - from + 1;
1673       uint32_t bit_field_offset = from;
1674       if (GetDataExtractor().GetByteOrder() == eByteOrderBig)
1675         bit_field_offset =
1676             GetByteSize().value_or(0) * 8 - bit_field_size - bit_field_offset;
1677       // We haven't made a synthetic array member for INDEX yet, so lets make
1678       // one and cache it for any future reference.
1679       ValueObjectChild *synthetic_child = new ValueObjectChild(
1680           *this, GetCompilerType(), index_const_str, GetByteSize().value_or(0),
1681           0, bit_field_size, bit_field_offset, false, false,
1682           eAddressTypeInvalid, 0);
1683 
1684       // Cache the value if we got one back...
1685       if (synthetic_child) {
1686         AddSyntheticChild(index_const_str, synthetic_child);
1687         synthetic_child_sp = synthetic_child->GetSP();
1688         synthetic_child_sp->SetName(ConstString(index_str));
1689         synthetic_child_sp->m_flags.m_is_bitfield_for_scalar = true;
1690       }
1691     }
1692   }
1693   return synthetic_child_sp;
1694 }
1695 
1696 ValueObjectSP ValueObject::GetSyntheticChildAtOffset(
1697     uint32_t offset, const CompilerType &type, bool can_create,
1698     ConstString name_const_str) {
1699 
1700   ValueObjectSP synthetic_child_sp;
1701 
1702   if (name_const_str.IsEmpty()) {
1703     name_const_str.SetString("@" + std::to_string(offset));
1704   }
1705 
1706   // Check if we have already created a synthetic array member in this valid
1707   // object. If we have we will re-use it.
1708   synthetic_child_sp = GetSyntheticChild(name_const_str);
1709 
1710   if (synthetic_child_sp.get())
1711     return synthetic_child_sp;
1712 
1713   if (!can_create)
1714     return {};
1715 
1716   ExecutionContext exe_ctx(GetExecutionContextRef());
1717   std::optional<uint64_t> size =
1718       type.GetByteSize(exe_ctx.GetBestExecutionContextScope());
1719   if (!size)
1720     return {};
1721   ValueObjectChild *synthetic_child =
1722       new ValueObjectChild(*this, type, name_const_str, *size, offset, 0, 0,
1723                            false, false, eAddressTypeInvalid, 0);
1724   if (synthetic_child) {
1725     AddSyntheticChild(name_const_str, synthetic_child);
1726     synthetic_child_sp = synthetic_child->GetSP();
1727     synthetic_child_sp->SetName(name_const_str);
1728     synthetic_child_sp->m_flags.m_is_child_at_offset = true;
1729   }
1730   return synthetic_child_sp;
1731 }
1732 
1733 ValueObjectSP ValueObject::GetSyntheticBase(uint32_t offset,
1734                                             const CompilerType &type,
1735                                             bool can_create,
1736                                             ConstString name_const_str) {
1737   ValueObjectSP synthetic_child_sp;
1738 
1739   if (name_const_str.IsEmpty()) {
1740     char name_str[128];
1741     snprintf(name_str, sizeof(name_str), "base%s@%i",
1742              type.GetTypeName().AsCString("<unknown>"), offset);
1743     name_const_str.SetCString(name_str);
1744   }
1745 
1746   // Check if we have already created a synthetic array member in this valid
1747   // object. If we have we will re-use it.
1748   synthetic_child_sp = GetSyntheticChild(name_const_str);
1749 
1750   if (synthetic_child_sp.get())
1751     return synthetic_child_sp;
1752 
1753   if (!can_create)
1754     return {};
1755 
1756   const bool is_base_class = true;
1757 
1758   ExecutionContext exe_ctx(GetExecutionContextRef());
1759   std::optional<uint64_t> size =
1760       type.GetByteSize(exe_ctx.GetBestExecutionContextScope());
1761   if (!size)
1762     return {};
1763   ValueObjectChild *synthetic_child =
1764       new ValueObjectChild(*this, type, name_const_str, *size, offset, 0, 0,
1765                            is_base_class, false, eAddressTypeInvalid, 0);
1766   if (synthetic_child) {
1767     AddSyntheticChild(name_const_str, synthetic_child);
1768     synthetic_child_sp = synthetic_child->GetSP();
1769     synthetic_child_sp->SetName(name_const_str);
1770   }
1771   return synthetic_child_sp;
1772 }
1773 
1774 // your expression path needs to have a leading . or -> (unless it somehow
1775 // "looks like" an array, in which case it has a leading [ symbol). while the [
1776 // is meaningful and should be shown to the user, . and -> are just parser
1777 // design, but by no means added information for the user.. strip them off
1778 static const char *SkipLeadingExpressionPathSeparators(const char *expression) {
1779   if (!expression || !expression[0])
1780     return expression;
1781   if (expression[0] == '.')
1782     return expression + 1;
1783   if (expression[0] == '-' && expression[1] == '>')
1784     return expression + 2;
1785   return expression;
1786 }
1787 
1788 ValueObjectSP
1789 ValueObject::GetSyntheticExpressionPathChild(const char *expression,
1790                                              bool can_create) {
1791   ValueObjectSP synthetic_child_sp;
1792   ConstString name_const_string(expression);
1793   // Check if we have already created a synthetic array member in this valid
1794   // object. If we have we will re-use it.
1795   synthetic_child_sp = GetSyntheticChild(name_const_string);
1796   if (!synthetic_child_sp) {
1797     // We haven't made a synthetic array member for expression yet, so lets
1798     // make one and cache it for any future reference.
1799     synthetic_child_sp = GetValueForExpressionPath(
1800         expression, nullptr, nullptr,
1801         GetValueForExpressionPathOptions().SetSyntheticChildrenTraversal(
1802             GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
1803                 None));
1804 
1805     // Cache the value if we got one back...
1806     if (synthetic_child_sp.get()) {
1807       // FIXME: this causes a "real" child to end up with its name changed to
1808       // the contents of expression
1809       AddSyntheticChild(name_const_string, synthetic_child_sp.get());
1810       synthetic_child_sp->SetName(
1811           ConstString(SkipLeadingExpressionPathSeparators(expression)));
1812     }
1813   }
1814   return synthetic_child_sp;
1815 }
1816 
1817 void ValueObject::CalculateSyntheticValue() {
1818   TargetSP target_sp(GetTargetSP());
1819   if (target_sp && !target_sp->GetEnableSyntheticValue()) {
1820     m_synthetic_value = nullptr;
1821     return;
1822   }
1823 
1824   lldb::SyntheticChildrenSP current_synth_sp(m_synthetic_children_sp);
1825 
1826   if (!UpdateFormatsIfNeeded() && m_synthetic_value)
1827     return;
1828 
1829   if (m_synthetic_children_sp.get() == nullptr)
1830     return;
1831 
1832   if (current_synth_sp == m_synthetic_children_sp && m_synthetic_value)
1833     return;
1834 
1835   m_synthetic_value = new ValueObjectSynthetic(*this, m_synthetic_children_sp);
1836 }
1837 
1838 void ValueObject::CalculateDynamicValue(DynamicValueType use_dynamic) {
1839   if (use_dynamic == eNoDynamicValues)
1840     return;
1841 
1842   if (!m_dynamic_value && !IsDynamic()) {
1843     ExecutionContext exe_ctx(GetExecutionContextRef());
1844     Process *process = exe_ctx.GetProcessPtr();
1845     if (process && process->IsPossibleDynamicValue(*this)) {
1846       ClearDynamicTypeInformation();
1847       m_dynamic_value = new ValueObjectDynamicValue(*this, use_dynamic);
1848     }
1849   }
1850 }
1851 
1852 ValueObjectSP ValueObject::GetDynamicValue(DynamicValueType use_dynamic) {
1853   if (use_dynamic == eNoDynamicValues)
1854     return ValueObjectSP();
1855 
1856   if (!IsDynamic() && m_dynamic_value == nullptr) {
1857     CalculateDynamicValue(use_dynamic);
1858   }
1859   if (m_dynamic_value && m_dynamic_value->GetError().Success())
1860     return m_dynamic_value->GetSP();
1861   else
1862     return ValueObjectSP();
1863 }
1864 
1865 ValueObjectSP ValueObject::GetSyntheticValue() {
1866   CalculateSyntheticValue();
1867 
1868   if (m_synthetic_value)
1869     return m_synthetic_value->GetSP();
1870   else
1871     return ValueObjectSP();
1872 }
1873 
1874 bool ValueObject::HasSyntheticValue() {
1875   UpdateFormatsIfNeeded();
1876 
1877   if (m_synthetic_children_sp.get() == nullptr)
1878     return false;
1879 
1880   CalculateSyntheticValue();
1881 
1882   return m_synthetic_value != nullptr;
1883 }
1884 
1885 ValueObject *ValueObject::GetNonBaseClassParent() {
1886   if (GetParent()) {
1887     if (GetParent()->IsBaseClass())
1888       return GetParent()->GetNonBaseClassParent();
1889     else
1890       return GetParent();
1891   }
1892   return nullptr;
1893 }
1894 
1895 bool ValueObject::IsBaseClass(uint32_t &depth) {
1896   if (!IsBaseClass()) {
1897     depth = 0;
1898     return false;
1899   }
1900   if (GetParent()) {
1901     GetParent()->IsBaseClass(depth);
1902     depth = depth + 1;
1903     return true;
1904   }
1905   // TODO: a base of no parent? weird..
1906   depth = 1;
1907   return true;
1908 }
1909 
1910 void ValueObject::GetExpressionPath(Stream &s,
1911                                     GetExpressionPathFormat epformat) {
1912   // synthetic children do not actually "exist" as part of the hierarchy, and
1913   // sometimes they are consed up in ways that don't make sense from an
1914   // underlying language/API standpoint. So, use a special code path here to
1915   // return something that can hopefully be used in expression
1916   if (m_flags.m_is_synthetic_children_generated) {
1917     UpdateValueIfNeeded();
1918 
1919     if (m_value.GetValueType() == Value::ValueType::LoadAddress) {
1920       if (IsPointerOrReferenceType()) {
1921         s.Printf("((%s)0x%" PRIx64 ")", GetTypeName().AsCString("void"),
1922                  GetValueAsUnsigned(0));
1923         return;
1924       } else {
1925         uint64_t load_addr =
1926             m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
1927         if (load_addr != LLDB_INVALID_ADDRESS) {
1928           s.Printf("(*( (%s *)0x%" PRIx64 "))", GetTypeName().AsCString("void"),
1929                    load_addr);
1930           return;
1931         }
1932       }
1933     }
1934 
1935     if (CanProvideValue()) {
1936       s.Printf("((%s)%s)", GetTypeName().AsCString("void"),
1937                GetValueAsCString());
1938       return;
1939     }
1940 
1941     return;
1942   }
1943 
1944   const bool is_deref_of_parent = IsDereferenceOfParent();
1945 
1946   if (is_deref_of_parent &&
1947       epformat == eGetExpressionPathFormatDereferencePointers) {
1948     // this is the original format of GetExpressionPath() producing code like
1949     // *(a_ptr).memberName, which is entirely fine, until you put this into
1950     // StackFrame::GetValueForVariableExpressionPath() which prefers to see
1951     // a_ptr->memberName. the eHonorPointers mode is meant to produce strings
1952     // in this latter format
1953     s.PutCString("*(");
1954   }
1955 
1956   ValueObject *parent = GetParent();
1957 
1958   if (parent)
1959     parent->GetExpressionPath(s, epformat);
1960 
1961   // if we are a deref_of_parent just because we are synthetic array members
1962   // made up to allow ptr[%d] syntax to work in variable printing, then add our
1963   // name ([%d]) to the expression path
1964   if (m_flags.m_is_array_item_for_pointer &&
1965       epformat == eGetExpressionPathFormatHonorPointers)
1966     s.PutCString(m_name.GetStringRef());
1967 
1968   if (!IsBaseClass()) {
1969     if (!is_deref_of_parent) {
1970       ValueObject *non_base_class_parent = GetNonBaseClassParent();
1971       if (non_base_class_parent &&
1972           !non_base_class_parent->GetName().IsEmpty()) {
1973         CompilerType non_base_class_parent_compiler_type =
1974             non_base_class_parent->GetCompilerType();
1975         if (non_base_class_parent_compiler_type) {
1976           if (parent && parent->IsDereferenceOfParent() &&
1977               epformat == eGetExpressionPathFormatHonorPointers) {
1978             s.PutCString("->");
1979           } else {
1980             const uint32_t non_base_class_parent_type_info =
1981                 non_base_class_parent_compiler_type.GetTypeInfo();
1982 
1983             if (non_base_class_parent_type_info & eTypeIsPointer) {
1984               s.PutCString("->");
1985             } else if ((non_base_class_parent_type_info & eTypeHasChildren) &&
1986                        !(non_base_class_parent_type_info & eTypeIsArray)) {
1987               s.PutChar('.');
1988             }
1989           }
1990         }
1991       }
1992 
1993       const char *name = GetName().GetCString();
1994       if (name)
1995         s.PutCString(name);
1996     }
1997   }
1998 
1999   if (is_deref_of_parent &&
2000       epformat == eGetExpressionPathFormatDereferencePointers) {
2001     s.PutChar(')');
2002   }
2003 }
2004 
2005 ValueObjectSP ValueObject::GetValueForExpressionPath(
2006     llvm::StringRef expression, ExpressionPathScanEndReason *reason_to_stop,
2007     ExpressionPathEndResultType *final_value_type,
2008     const GetValueForExpressionPathOptions &options,
2009     ExpressionPathAftermath *final_task_on_target) {
2010 
2011   ExpressionPathScanEndReason dummy_reason_to_stop =
2012       ValueObject::eExpressionPathScanEndReasonUnknown;
2013   ExpressionPathEndResultType dummy_final_value_type =
2014       ValueObject::eExpressionPathEndResultTypeInvalid;
2015   ExpressionPathAftermath dummy_final_task_on_target =
2016       ValueObject::eExpressionPathAftermathNothing;
2017 
2018   ValueObjectSP ret_val = GetValueForExpressionPath_Impl(
2019       expression, reason_to_stop ? reason_to_stop : &dummy_reason_to_stop,
2020       final_value_type ? final_value_type : &dummy_final_value_type, options,
2021       final_task_on_target ? final_task_on_target
2022                            : &dummy_final_task_on_target);
2023 
2024   if (!final_task_on_target ||
2025       *final_task_on_target == ValueObject::eExpressionPathAftermathNothing)
2026     return ret_val;
2027 
2028   if (ret_val.get() &&
2029       ((final_value_type ? *final_value_type : dummy_final_value_type) ==
2030        eExpressionPathEndResultTypePlain)) // I can only deref and takeaddress
2031                                            // of plain objects
2032   {
2033     if ((final_task_on_target ? *final_task_on_target
2034                               : dummy_final_task_on_target) ==
2035         ValueObject::eExpressionPathAftermathDereference) {
2036       Status error;
2037       ValueObjectSP final_value = ret_val->Dereference(error);
2038       if (error.Fail() || !final_value.get()) {
2039         if (reason_to_stop)
2040           *reason_to_stop =
2041               ValueObject::eExpressionPathScanEndReasonDereferencingFailed;
2042         if (final_value_type)
2043           *final_value_type = ValueObject::eExpressionPathEndResultTypeInvalid;
2044         return ValueObjectSP();
2045       } else {
2046         if (final_task_on_target)
2047           *final_task_on_target = ValueObject::eExpressionPathAftermathNothing;
2048         return final_value;
2049       }
2050     }
2051     if (*final_task_on_target ==
2052         ValueObject::eExpressionPathAftermathTakeAddress) {
2053       Status error;
2054       ValueObjectSP final_value = ret_val->AddressOf(error);
2055       if (error.Fail() || !final_value.get()) {
2056         if (reason_to_stop)
2057           *reason_to_stop =
2058               ValueObject::eExpressionPathScanEndReasonTakingAddressFailed;
2059         if (final_value_type)
2060           *final_value_type = ValueObject::eExpressionPathEndResultTypeInvalid;
2061         return ValueObjectSP();
2062       } else {
2063         if (final_task_on_target)
2064           *final_task_on_target = ValueObject::eExpressionPathAftermathNothing;
2065         return final_value;
2066       }
2067     }
2068   }
2069   return ret_val; // final_task_on_target will still have its original value, so
2070                   // you know I did not do it
2071 }
2072 
2073 ValueObjectSP ValueObject::GetValueForExpressionPath_Impl(
2074     llvm::StringRef expression, ExpressionPathScanEndReason *reason_to_stop,
2075     ExpressionPathEndResultType *final_result,
2076     const GetValueForExpressionPathOptions &options,
2077     ExpressionPathAftermath *what_next) {
2078   ValueObjectSP root = GetSP();
2079 
2080   if (!root)
2081     return nullptr;
2082 
2083   llvm::StringRef remainder = expression;
2084 
2085   while (true) {
2086     llvm::StringRef temp_expression = remainder;
2087 
2088     CompilerType root_compiler_type = root->GetCompilerType();
2089     CompilerType pointee_compiler_type;
2090     Flags pointee_compiler_type_info;
2091 
2092     Flags root_compiler_type_info(
2093         root_compiler_type.GetTypeInfo(&pointee_compiler_type));
2094     if (pointee_compiler_type)
2095       pointee_compiler_type_info.Reset(pointee_compiler_type.GetTypeInfo());
2096 
2097     if (temp_expression.empty()) {
2098       *reason_to_stop = ValueObject::eExpressionPathScanEndReasonEndOfString;
2099       return root;
2100     }
2101 
2102     switch (temp_expression.front()) {
2103     case '-': {
2104       temp_expression = temp_expression.drop_front();
2105       if (options.m_check_dot_vs_arrow_syntax &&
2106           root_compiler_type_info.Test(eTypeIsPointer)) // if you are trying to
2107                                                         // use -> on a
2108                                                         // non-pointer and I
2109                                                         // must catch the error
2110       {
2111         *reason_to_stop =
2112             ValueObject::eExpressionPathScanEndReasonArrowInsteadOfDot;
2113         *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2114         return ValueObjectSP();
2115       }
2116       if (root_compiler_type_info.Test(eTypeIsObjC) && // if yo are trying to
2117                                                        // extract an ObjC IVar
2118                                                        // when this is forbidden
2119           root_compiler_type_info.Test(eTypeIsPointer) &&
2120           options.m_no_fragile_ivar) {
2121         *reason_to_stop =
2122             ValueObject::eExpressionPathScanEndReasonFragileIVarNotAllowed;
2123         *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2124         return ValueObjectSP();
2125       }
2126       if (!temp_expression.startswith(">")) {
2127         *reason_to_stop =
2128             ValueObject::eExpressionPathScanEndReasonUnexpectedSymbol;
2129         *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2130         return ValueObjectSP();
2131       }
2132     }
2133       [[fallthrough]];
2134     case '.': // or fallthrough from ->
2135     {
2136       if (options.m_check_dot_vs_arrow_syntax &&
2137           temp_expression.front() == '.' &&
2138           root_compiler_type_info.Test(eTypeIsPointer)) // if you are trying to
2139                                                         // use . on a pointer
2140                                                         // and I must catch the
2141                                                         // error
2142       {
2143         *reason_to_stop =
2144             ValueObject::eExpressionPathScanEndReasonDotInsteadOfArrow;
2145         *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2146         return nullptr;
2147       }
2148       temp_expression = temp_expression.drop_front(); // skip . or >
2149 
2150       size_t next_sep_pos = temp_expression.find_first_of("-.[", 1);
2151       ConstString child_name;
2152       if (next_sep_pos == llvm::StringRef::npos) // if no other separator just
2153                                                  // expand this last layer
2154       {
2155         child_name.SetString(temp_expression);
2156         ValueObjectSP child_valobj_sp =
2157             root->GetChildMemberWithName(child_name);
2158 
2159         if (child_valobj_sp.get()) // we know we are done, so just return
2160         {
2161           *reason_to_stop =
2162               ValueObject::eExpressionPathScanEndReasonEndOfString;
2163           *final_result = ValueObject::eExpressionPathEndResultTypePlain;
2164           return child_valobj_sp;
2165         } else {
2166           switch (options.m_synthetic_children_traversal) {
2167           case GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2168               None:
2169             break;
2170           case GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2171               FromSynthetic:
2172             if (root->IsSynthetic()) {
2173               child_valobj_sp = root->GetNonSyntheticValue();
2174               if (child_valobj_sp.get())
2175                 child_valobj_sp =
2176                     child_valobj_sp->GetChildMemberWithName(child_name);
2177             }
2178             break;
2179           case GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2180               ToSynthetic:
2181             if (!root->IsSynthetic()) {
2182               child_valobj_sp = root->GetSyntheticValue();
2183               if (child_valobj_sp.get())
2184                 child_valobj_sp =
2185                     child_valobj_sp->GetChildMemberWithName(child_name);
2186             }
2187             break;
2188           case GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2189               Both:
2190             if (root->IsSynthetic()) {
2191               child_valobj_sp = root->GetNonSyntheticValue();
2192               if (child_valobj_sp.get())
2193                 child_valobj_sp =
2194                     child_valobj_sp->GetChildMemberWithName(child_name);
2195             } else {
2196               child_valobj_sp = root->GetSyntheticValue();
2197               if (child_valobj_sp.get())
2198                 child_valobj_sp =
2199                     child_valobj_sp->GetChildMemberWithName(child_name);
2200             }
2201             break;
2202           }
2203         }
2204 
2205         // if we are here and options.m_no_synthetic_children is true,
2206         // child_valobj_sp is going to be a NULL SP, so we hit the "else"
2207         // branch, and return an error
2208         if (child_valobj_sp.get()) // if it worked, just return
2209         {
2210           *reason_to_stop =
2211               ValueObject::eExpressionPathScanEndReasonEndOfString;
2212           *final_result = ValueObject::eExpressionPathEndResultTypePlain;
2213           return child_valobj_sp;
2214         } else {
2215           *reason_to_stop =
2216               ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2217           *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2218           return nullptr;
2219         }
2220       } else // other layers do expand
2221       {
2222         llvm::StringRef next_separator = temp_expression.substr(next_sep_pos);
2223 
2224         child_name.SetString(temp_expression.slice(0, next_sep_pos));
2225 
2226         ValueObjectSP child_valobj_sp =
2227             root->GetChildMemberWithName(child_name);
2228         if (child_valobj_sp.get()) // store the new root and move on
2229         {
2230           root = child_valobj_sp;
2231           remainder = next_separator;
2232           *final_result = ValueObject::eExpressionPathEndResultTypePlain;
2233           continue;
2234         } else {
2235           switch (options.m_synthetic_children_traversal) {
2236           case GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2237               None:
2238             break;
2239           case GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2240               FromSynthetic:
2241             if (root->IsSynthetic()) {
2242               child_valobj_sp = root->GetNonSyntheticValue();
2243               if (child_valobj_sp.get())
2244                 child_valobj_sp =
2245                     child_valobj_sp->GetChildMemberWithName(child_name);
2246             }
2247             break;
2248           case GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2249               ToSynthetic:
2250             if (!root->IsSynthetic()) {
2251               child_valobj_sp = root->GetSyntheticValue();
2252               if (child_valobj_sp.get())
2253                 child_valobj_sp =
2254                     child_valobj_sp->GetChildMemberWithName(child_name);
2255             }
2256             break;
2257           case GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2258               Both:
2259             if (root->IsSynthetic()) {
2260               child_valobj_sp = root->GetNonSyntheticValue();
2261               if (child_valobj_sp.get())
2262                 child_valobj_sp =
2263                     child_valobj_sp->GetChildMemberWithName(child_name);
2264             } else {
2265               child_valobj_sp = root->GetSyntheticValue();
2266               if (child_valobj_sp.get())
2267                 child_valobj_sp =
2268                     child_valobj_sp->GetChildMemberWithName(child_name);
2269             }
2270             break;
2271           }
2272         }
2273 
2274         // if we are here and options.m_no_synthetic_children is true,
2275         // child_valobj_sp is going to be a NULL SP, so we hit the "else"
2276         // branch, and return an error
2277         if (child_valobj_sp.get()) // if it worked, move on
2278         {
2279           root = child_valobj_sp;
2280           remainder = next_separator;
2281           *final_result = ValueObject::eExpressionPathEndResultTypePlain;
2282           continue;
2283         } else {
2284           *reason_to_stop =
2285               ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2286           *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2287           return nullptr;
2288         }
2289       }
2290       break;
2291     }
2292     case '[': {
2293       if (!root_compiler_type_info.Test(eTypeIsArray) &&
2294           !root_compiler_type_info.Test(eTypeIsPointer) &&
2295           !root_compiler_type_info.Test(
2296               eTypeIsVector)) // if this is not a T[] nor a T*
2297       {
2298         if (!root_compiler_type_info.Test(
2299                 eTypeIsScalar)) // if this is not even a scalar...
2300         {
2301           if (options.m_synthetic_children_traversal ==
2302               GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2303                   None) // ...only chance left is synthetic
2304           {
2305             *reason_to_stop =
2306                 ValueObject::eExpressionPathScanEndReasonRangeOperatorInvalid;
2307             *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2308             return ValueObjectSP();
2309           }
2310         } else if (!options.m_allow_bitfields_syntax) // if this is a scalar,
2311                                                       // check that we can
2312                                                       // expand bitfields
2313         {
2314           *reason_to_stop =
2315               ValueObject::eExpressionPathScanEndReasonRangeOperatorNotAllowed;
2316           *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2317           return ValueObjectSP();
2318         }
2319       }
2320       if (temp_expression[1] ==
2321           ']') // if this is an unbounded range it only works for arrays
2322       {
2323         if (!root_compiler_type_info.Test(eTypeIsArray)) {
2324           *reason_to_stop =
2325               ValueObject::eExpressionPathScanEndReasonEmptyRangeNotAllowed;
2326           *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2327           return nullptr;
2328         } else // even if something follows, we cannot expand unbounded ranges,
2329                // just let the caller do it
2330         {
2331           *reason_to_stop =
2332               ValueObject::eExpressionPathScanEndReasonArrayRangeOperatorMet;
2333           *final_result =
2334               ValueObject::eExpressionPathEndResultTypeUnboundedRange;
2335           return root;
2336         }
2337       }
2338 
2339       size_t close_bracket_position = temp_expression.find(']', 1);
2340       if (close_bracket_position ==
2341           llvm::StringRef::npos) // if there is no ], this is a syntax error
2342       {
2343         *reason_to_stop =
2344             ValueObject::eExpressionPathScanEndReasonUnexpectedSymbol;
2345         *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2346         return nullptr;
2347       }
2348 
2349       llvm::StringRef bracket_expr =
2350           temp_expression.slice(1, close_bracket_position);
2351 
2352       // If this was an empty expression it would have been caught by the if
2353       // above.
2354       assert(!bracket_expr.empty());
2355 
2356       if (!bracket_expr.contains('-')) {
2357         // if no separator, this is of the form [N].  Note that this cannot be
2358         // an unbounded range of the form [], because that case was handled
2359         // above with an unconditional return.
2360         unsigned long index = 0;
2361         if (bracket_expr.getAsInteger(0, index)) {
2362           *reason_to_stop =
2363               ValueObject::eExpressionPathScanEndReasonUnexpectedSymbol;
2364           *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2365           return nullptr;
2366         }
2367 
2368         // from here on we do have a valid index
2369         if (root_compiler_type_info.Test(eTypeIsArray)) {
2370           ValueObjectSP child_valobj_sp = root->GetChildAtIndex(index);
2371           if (!child_valobj_sp)
2372             child_valobj_sp = root->GetSyntheticArrayMember(index, true);
2373           if (!child_valobj_sp)
2374             if (root->HasSyntheticValue() &&
2375                 root->GetSyntheticValue()->GetNumChildren() > index)
2376               child_valobj_sp =
2377                   root->GetSyntheticValue()->GetChildAtIndex(index);
2378           if (child_valobj_sp) {
2379             root = child_valobj_sp;
2380             remainder =
2381                 temp_expression.substr(close_bracket_position + 1); // skip ]
2382             *final_result = ValueObject::eExpressionPathEndResultTypePlain;
2383             continue;
2384           } else {
2385             *reason_to_stop =
2386                 ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2387             *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2388             return nullptr;
2389           }
2390         } else if (root_compiler_type_info.Test(eTypeIsPointer)) {
2391           if (*what_next ==
2392                   ValueObject::
2393                       eExpressionPathAftermathDereference && // if this is a
2394                                                              // ptr-to-scalar, I
2395                                                              // am accessing it
2396                                                              // by index and I
2397                                                              // would have
2398                                                              // deref'ed anyway,
2399                                                              // then do it now
2400                                                              // and use this as
2401                                                              // a bitfield
2402               pointee_compiler_type_info.Test(eTypeIsScalar)) {
2403             Status error;
2404             root = root->Dereference(error);
2405             if (error.Fail() || !root) {
2406               *reason_to_stop =
2407                   ValueObject::eExpressionPathScanEndReasonDereferencingFailed;
2408               *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2409               return nullptr;
2410             } else {
2411               *what_next = eExpressionPathAftermathNothing;
2412               continue;
2413             }
2414           } else {
2415             if (root->GetCompilerType().GetMinimumLanguage() ==
2416                     eLanguageTypeObjC &&
2417                 pointee_compiler_type_info.AllClear(eTypeIsPointer) &&
2418                 root->HasSyntheticValue() &&
2419                 (options.m_synthetic_children_traversal ==
2420                      GetValueForExpressionPathOptions::
2421                          SyntheticChildrenTraversal::ToSynthetic ||
2422                  options.m_synthetic_children_traversal ==
2423                      GetValueForExpressionPathOptions::
2424                          SyntheticChildrenTraversal::Both)) {
2425               root = root->GetSyntheticValue()->GetChildAtIndex(index);
2426             } else
2427               root = root->GetSyntheticArrayMember(index, true);
2428             if (!root) {
2429               *reason_to_stop =
2430                   ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2431               *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2432               return nullptr;
2433             } else {
2434               remainder =
2435                   temp_expression.substr(close_bracket_position + 1); // skip ]
2436               *final_result = ValueObject::eExpressionPathEndResultTypePlain;
2437               continue;
2438             }
2439           }
2440         } else if (root_compiler_type_info.Test(eTypeIsScalar)) {
2441           root = root->GetSyntheticBitFieldChild(index, index, true);
2442           if (!root) {
2443             *reason_to_stop =
2444                 ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2445             *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2446             return nullptr;
2447           } else // we do not know how to expand members of bitfields, so we
2448                  // just return and let the caller do any further processing
2449           {
2450             *reason_to_stop = ValueObject::
2451                 eExpressionPathScanEndReasonBitfieldRangeOperatorMet;
2452             *final_result = ValueObject::eExpressionPathEndResultTypeBitfield;
2453             return root;
2454           }
2455         } else if (root_compiler_type_info.Test(eTypeIsVector)) {
2456           root = root->GetChildAtIndex(index);
2457           if (!root) {
2458             *reason_to_stop =
2459                 ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2460             *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2461             return ValueObjectSP();
2462           } else {
2463             remainder =
2464                 temp_expression.substr(close_bracket_position + 1); // skip ]
2465             *final_result = ValueObject::eExpressionPathEndResultTypePlain;
2466             continue;
2467           }
2468         } else if (options.m_synthetic_children_traversal ==
2469                        GetValueForExpressionPathOptions::
2470                            SyntheticChildrenTraversal::ToSynthetic ||
2471                    options.m_synthetic_children_traversal ==
2472                        GetValueForExpressionPathOptions::
2473                            SyntheticChildrenTraversal::Both) {
2474           if (root->HasSyntheticValue())
2475             root = root->GetSyntheticValue();
2476           else if (!root->IsSynthetic()) {
2477             *reason_to_stop =
2478                 ValueObject::eExpressionPathScanEndReasonSyntheticValueMissing;
2479             *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2480             return nullptr;
2481           }
2482           // if we are here, then root itself is a synthetic VO.. should be
2483           // good to go
2484 
2485           if (!root) {
2486             *reason_to_stop =
2487                 ValueObject::eExpressionPathScanEndReasonSyntheticValueMissing;
2488             *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2489             return nullptr;
2490           }
2491           root = root->GetChildAtIndex(index);
2492           if (!root) {
2493             *reason_to_stop =
2494                 ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2495             *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2496             return nullptr;
2497           } else {
2498             remainder =
2499                 temp_expression.substr(close_bracket_position + 1); // skip ]
2500             *final_result = ValueObject::eExpressionPathEndResultTypePlain;
2501             continue;
2502           }
2503         } else {
2504           *reason_to_stop =
2505               ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2506           *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2507           return nullptr;
2508         }
2509       } else {
2510         // we have a low and a high index
2511         llvm::StringRef sleft, sright;
2512         unsigned long low_index, high_index;
2513         std::tie(sleft, sright) = bracket_expr.split('-');
2514         if (sleft.getAsInteger(0, low_index) ||
2515             sright.getAsInteger(0, high_index)) {
2516           *reason_to_stop =
2517               ValueObject::eExpressionPathScanEndReasonUnexpectedSymbol;
2518           *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2519           return nullptr;
2520         }
2521 
2522         if (low_index > high_index) // swap indices if required
2523           std::swap(low_index, high_index);
2524 
2525         if (root_compiler_type_info.Test(
2526                 eTypeIsScalar)) // expansion only works for scalars
2527         {
2528           root = root->GetSyntheticBitFieldChild(low_index, high_index, true);
2529           if (!root) {
2530             *reason_to_stop =
2531                 ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2532             *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2533             return nullptr;
2534           } else {
2535             *reason_to_stop = ValueObject::
2536                 eExpressionPathScanEndReasonBitfieldRangeOperatorMet;
2537             *final_result = ValueObject::eExpressionPathEndResultTypeBitfield;
2538             return root;
2539           }
2540         } else if (root_compiler_type_info.Test(
2541                        eTypeIsPointer) && // if this is a ptr-to-scalar, I am
2542                                           // accessing it by index and I would
2543                                           // have deref'ed anyway, then do it
2544                                           // now and use this as a bitfield
2545                    *what_next ==
2546                        ValueObject::eExpressionPathAftermathDereference &&
2547                    pointee_compiler_type_info.Test(eTypeIsScalar)) {
2548           Status error;
2549           root = root->Dereference(error);
2550           if (error.Fail() || !root) {
2551             *reason_to_stop =
2552                 ValueObject::eExpressionPathScanEndReasonDereferencingFailed;
2553             *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2554             return nullptr;
2555           } else {
2556             *what_next = ValueObject::eExpressionPathAftermathNothing;
2557             continue;
2558           }
2559         } else {
2560           *reason_to_stop =
2561               ValueObject::eExpressionPathScanEndReasonArrayRangeOperatorMet;
2562           *final_result = ValueObject::eExpressionPathEndResultTypeBoundedRange;
2563           return root;
2564         }
2565       }
2566       break;
2567     }
2568     default: // some non-separator is in the way
2569     {
2570       *reason_to_stop =
2571           ValueObject::eExpressionPathScanEndReasonUnexpectedSymbol;
2572       *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2573       return nullptr;
2574     }
2575     }
2576   }
2577 }
2578 
2579 void ValueObject::Dump(Stream &s) { Dump(s, DumpValueObjectOptions(*this)); }
2580 
2581 void ValueObject::Dump(Stream &s, const DumpValueObjectOptions &options) {
2582   ValueObjectPrinter printer(this, &s, options);
2583   printer.PrintValueObject();
2584 }
2585 
2586 ValueObjectSP ValueObject::CreateConstantValue(ConstString name) {
2587   ValueObjectSP valobj_sp;
2588 
2589   if (UpdateValueIfNeeded(false) && m_error.Success()) {
2590     ExecutionContext exe_ctx(GetExecutionContextRef());
2591 
2592     DataExtractor data;
2593     data.SetByteOrder(m_data.GetByteOrder());
2594     data.SetAddressByteSize(m_data.GetAddressByteSize());
2595 
2596     if (IsBitfield()) {
2597       Value v(Scalar(GetValueAsUnsigned(UINT64_MAX)));
2598       m_error = v.GetValueAsData(&exe_ctx, data, GetModule().get());
2599     } else
2600       m_error = m_value.GetValueAsData(&exe_ctx, data, GetModule().get());
2601 
2602     valobj_sp = ValueObjectConstResult::Create(
2603         exe_ctx.GetBestExecutionContextScope(), GetCompilerType(), name, data,
2604         GetAddressOf());
2605   }
2606 
2607   if (!valobj_sp) {
2608     ExecutionContext exe_ctx(GetExecutionContextRef());
2609     valobj_sp = ValueObjectConstResult::Create(
2610         exe_ctx.GetBestExecutionContextScope(), m_error);
2611   }
2612   return valobj_sp;
2613 }
2614 
2615 ValueObjectSP ValueObject::GetQualifiedRepresentationIfAvailable(
2616     lldb::DynamicValueType dynValue, bool synthValue) {
2617   ValueObjectSP result_sp(GetSP());
2618 
2619   switch (dynValue) {
2620   case lldb::eDynamicCanRunTarget:
2621   case lldb::eDynamicDontRunTarget: {
2622     if (!result_sp->IsDynamic()) {
2623       if (result_sp->GetDynamicValue(dynValue))
2624         result_sp = result_sp->GetDynamicValue(dynValue);
2625     }
2626   } break;
2627   case lldb::eNoDynamicValues: {
2628     if (result_sp->IsDynamic()) {
2629       if (result_sp->GetStaticValue())
2630         result_sp = result_sp->GetStaticValue();
2631     }
2632   } break;
2633   }
2634 
2635   if (synthValue) {
2636     if (!result_sp->IsSynthetic()) {
2637       if (result_sp->GetSyntheticValue())
2638         result_sp = result_sp->GetSyntheticValue();
2639     }
2640   } else {
2641     if (result_sp->IsSynthetic()) {
2642       if (result_sp->GetNonSyntheticValue())
2643         result_sp = result_sp->GetNonSyntheticValue();
2644     }
2645   }
2646 
2647   return result_sp;
2648 }
2649 
2650 ValueObjectSP ValueObject::Dereference(Status &error) {
2651   if (m_deref_valobj)
2652     return m_deref_valobj->GetSP();
2653 
2654   const bool is_pointer_or_reference_type = IsPointerOrReferenceType();
2655   if (is_pointer_or_reference_type) {
2656     bool omit_empty_base_classes = true;
2657     bool ignore_array_bounds = false;
2658 
2659     std::string child_name_str;
2660     uint32_t child_byte_size = 0;
2661     int32_t child_byte_offset = 0;
2662     uint32_t child_bitfield_bit_size = 0;
2663     uint32_t child_bitfield_bit_offset = 0;
2664     bool child_is_base_class = false;
2665     bool child_is_deref_of_parent = false;
2666     const bool transparent_pointers = false;
2667     CompilerType compiler_type = GetCompilerType();
2668     CompilerType child_compiler_type;
2669     uint64_t language_flags = 0;
2670 
2671     ExecutionContext exe_ctx(GetExecutionContextRef());
2672 
2673     child_compiler_type = compiler_type.GetChildCompilerTypeAtIndex(
2674         &exe_ctx, 0, transparent_pointers, omit_empty_base_classes,
2675         ignore_array_bounds, child_name_str, child_byte_size, child_byte_offset,
2676         child_bitfield_bit_size, child_bitfield_bit_offset, child_is_base_class,
2677         child_is_deref_of_parent, this, language_flags);
2678     if (child_compiler_type && child_byte_size) {
2679       ConstString child_name;
2680       if (!child_name_str.empty())
2681         child_name.SetCString(child_name_str.c_str());
2682 
2683       m_deref_valobj = new ValueObjectChild(
2684           *this, child_compiler_type, child_name, child_byte_size,
2685           child_byte_offset, child_bitfield_bit_size, child_bitfield_bit_offset,
2686           child_is_base_class, child_is_deref_of_parent, eAddressTypeInvalid,
2687           language_flags);
2688     }
2689 
2690     // In case of incomplete child compiler type, use the pointee type and try
2691     // to recreate a new ValueObjectChild using it.
2692     if (!m_deref_valobj) {
2693       // FIXME(#59012): C++ stdlib formatters break with incomplete types (e.g.
2694       // `std::vector<int> &`). Remove ObjC restriction once that's resolved.
2695       if (Language::LanguageIsObjC(GetPreferredDisplayLanguage()) &&
2696           HasSyntheticValue()) {
2697         child_compiler_type = compiler_type.GetPointeeType();
2698 
2699         if (child_compiler_type) {
2700           ConstString child_name;
2701           if (!child_name_str.empty())
2702             child_name.SetCString(child_name_str.c_str());
2703 
2704           m_deref_valobj = new ValueObjectChild(
2705               *this, child_compiler_type, child_name, child_byte_size,
2706               child_byte_offset, child_bitfield_bit_size,
2707               child_bitfield_bit_offset, child_is_base_class,
2708               child_is_deref_of_parent, eAddressTypeInvalid, language_flags);
2709         }
2710       }
2711     }
2712 
2713   } else if (HasSyntheticValue()) {
2714     m_deref_valobj =
2715         GetSyntheticValue()->GetChildMemberWithName("$$dereference$$").get();
2716   } else if (IsSynthetic()) {
2717     m_deref_valobj = GetChildMemberWithName("$$dereference$$").get();
2718   }
2719 
2720   if (m_deref_valobj) {
2721     error.Clear();
2722     return m_deref_valobj->GetSP();
2723   } else {
2724     StreamString strm;
2725     GetExpressionPath(strm);
2726 
2727     if (is_pointer_or_reference_type)
2728       error.SetErrorStringWithFormat("dereference failed: (%s) %s",
2729                                      GetTypeName().AsCString("<invalid type>"),
2730                                      strm.GetData());
2731     else
2732       error.SetErrorStringWithFormat("not a pointer or reference type: (%s) %s",
2733                                      GetTypeName().AsCString("<invalid type>"),
2734                                      strm.GetData());
2735     return ValueObjectSP();
2736   }
2737 }
2738 
2739 ValueObjectSP ValueObject::AddressOf(Status &error) {
2740   if (m_addr_of_valobj_sp)
2741     return m_addr_of_valobj_sp;
2742 
2743   AddressType address_type = eAddressTypeInvalid;
2744   const bool scalar_is_load_address = false;
2745   addr_t addr = GetAddressOf(scalar_is_load_address, &address_type);
2746   error.Clear();
2747   if (addr != LLDB_INVALID_ADDRESS && address_type != eAddressTypeHost) {
2748     switch (address_type) {
2749     case eAddressTypeInvalid: {
2750       StreamString expr_path_strm;
2751       GetExpressionPath(expr_path_strm);
2752       error.SetErrorStringWithFormat("'%s' is not in memory",
2753                                      expr_path_strm.GetData());
2754     } break;
2755 
2756     case eAddressTypeFile:
2757     case eAddressTypeLoad: {
2758       CompilerType compiler_type = GetCompilerType();
2759       if (compiler_type) {
2760         std::string name(1, '&');
2761         name.append(m_name.AsCString(""));
2762         ExecutionContext exe_ctx(GetExecutionContextRef());
2763         m_addr_of_valobj_sp = ValueObjectConstResult::Create(
2764             exe_ctx.GetBestExecutionContextScope(),
2765             compiler_type.GetPointerType(), ConstString(name.c_str()), addr,
2766             eAddressTypeInvalid, m_data.GetAddressByteSize());
2767       }
2768     } break;
2769     default:
2770       break;
2771     }
2772   } else {
2773     StreamString expr_path_strm;
2774     GetExpressionPath(expr_path_strm);
2775     error.SetErrorStringWithFormat("'%s' doesn't have a valid address",
2776                                    expr_path_strm.GetData());
2777   }
2778 
2779   return m_addr_of_valobj_sp;
2780 }
2781 
2782 ValueObjectSP ValueObject::DoCast(const CompilerType &compiler_type) {
2783     return ValueObjectCast::Create(*this, GetName(), compiler_type);
2784 }
2785 
2786 ValueObjectSP ValueObject::Cast(const CompilerType &compiler_type) {
2787   // Only allow casts if the original type is equal or larger than the cast
2788   // type.  We don't know how to fetch more data for all the ConstResult types,
2789   // so we can't guarantee this will work:
2790   Status error;
2791   CompilerType my_type = GetCompilerType();
2792 
2793   ExecutionContextScope *exe_scope
2794       = ExecutionContext(GetExecutionContextRef())
2795           .GetBestExecutionContextScope();
2796   if (compiler_type.GetByteSize(exe_scope)
2797       <= GetCompilerType().GetByteSize(exe_scope)) {
2798         return DoCast(compiler_type);
2799   }
2800   error.SetErrorString("Can only cast to a type that is equal to or smaller "
2801                        "than the orignal type.");
2802 
2803   return ValueObjectConstResult::Create(
2804       ExecutionContext(GetExecutionContextRef()).GetBestExecutionContextScope(),
2805                        error);
2806 }
2807 
2808 lldb::ValueObjectSP ValueObject::Clone(ConstString new_name) {
2809   return ValueObjectCast::Create(*this, new_name, GetCompilerType());
2810 }
2811 
2812 ValueObjectSP ValueObject::CastPointerType(const char *name,
2813                                            CompilerType &compiler_type) {
2814   ValueObjectSP valobj_sp;
2815   AddressType address_type;
2816   addr_t ptr_value = GetPointerValue(&address_type);
2817 
2818   if (ptr_value != LLDB_INVALID_ADDRESS) {
2819     Address ptr_addr(ptr_value);
2820     ExecutionContext exe_ctx(GetExecutionContextRef());
2821     valobj_sp = ValueObjectMemory::Create(
2822         exe_ctx.GetBestExecutionContextScope(), name, ptr_addr, compiler_type);
2823   }
2824   return valobj_sp;
2825 }
2826 
2827 ValueObjectSP ValueObject::CastPointerType(const char *name, TypeSP &type_sp) {
2828   ValueObjectSP valobj_sp;
2829   AddressType address_type;
2830   addr_t ptr_value = GetPointerValue(&address_type);
2831 
2832   if (ptr_value != LLDB_INVALID_ADDRESS) {
2833     Address ptr_addr(ptr_value);
2834     ExecutionContext exe_ctx(GetExecutionContextRef());
2835     valobj_sp = ValueObjectMemory::Create(
2836         exe_ctx.GetBestExecutionContextScope(), name, ptr_addr, type_sp);
2837   }
2838   return valobj_sp;
2839 }
2840 
2841 ValueObject::EvaluationPoint::EvaluationPoint() : m_mod_id(), m_exe_ctx_ref() {}
2842 
2843 ValueObject::EvaluationPoint::EvaluationPoint(ExecutionContextScope *exe_scope,
2844                                               bool use_selected)
2845     : m_mod_id(), m_exe_ctx_ref() {
2846   ExecutionContext exe_ctx(exe_scope);
2847   TargetSP target_sp(exe_ctx.GetTargetSP());
2848   if (target_sp) {
2849     m_exe_ctx_ref.SetTargetSP(target_sp);
2850     ProcessSP process_sp(exe_ctx.GetProcessSP());
2851     if (!process_sp)
2852       process_sp = target_sp->GetProcessSP();
2853 
2854     if (process_sp) {
2855       m_mod_id = process_sp->GetModID();
2856       m_exe_ctx_ref.SetProcessSP(process_sp);
2857 
2858       ThreadSP thread_sp(exe_ctx.GetThreadSP());
2859 
2860       if (!thread_sp) {
2861         if (use_selected)
2862           thread_sp = process_sp->GetThreadList().GetSelectedThread();
2863       }
2864 
2865       if (thread_sp) {
2866         m_exe_ctx_ref.SetThreadSP(thread_sp);
2867 
2868         StackFrameSP frame_sp(exe_ctx.GetFrameSP());
2869         if (!frame_sp) {
2870           if (use_selected)
2871             frame_sp = thread_sp->GetSelectedFrame(DoNoSelectMostRelevantFrame);
2872         }
2873         if (frame_sp)
2874           m_exe_ctx_ref.SetFrameSP(frame_sp);
2875       }
2876     }
2877   }
2878 }
2879 
2880 ValueObject::EvaluationPoint::EvaluationPoint(
2881     const ValueObject::EvaluationPoint &rhs)
2882     : m_mod_id(), m_exe_ctx_ref(rhs.m_exe_ctx_ref) {}
2883 
2884 ValueObject::EvaluationPoint::~EvaluationPoint() = default;
2885 
2886 // This function checks the EvaluationPoint against the current process state.
2887 // If the current state matches the evaluation point, or the evaluation point
2888 // is already invalid, then we return false, meaning "no change".  If the
2889 // current state is different, we update our state, and return true meaning
2890 // "yes, change".  If we did see a change, we also set m_needs_update to true,
2891 // so future calls to NeedsUpdate will return true. exe_scope will be set to
2892 // the current execution context scope.
2893 
2894 bool ValueObject::EvaluationPoint::SyncWithProcessState(
2895     bool accept_invalid_exe_ctx) {
2896   // Start with the target, if it is NULL, then we're obviously not going to
2897   // get any further:
2898   const bool thread_and_frame_only_if_stopped = true;
2899   ExecutionContext exe_ctx(
2900       m_exe_ctx_ref.Lock(thread_and_frame_only_if_stopped));
2901 
2902   if (exe_ctx.GetTargetPtr() == nullptr)
2903     return false;
2904 
2905   // If we don't have a process nothing can change.
2906   Process *process = exe_ctx.GetProcessPtr();
2907   if (process == nullptr)
2908     return false;
2909 
2910   // If our stop id is the current stop ID, nothing has changed:
2911   ProcessModID current_mod_id = process->GetModID();
2912 
2913   // If the current stop id is 0, either we haven't run yet, or the process
2914   // state has been cleared. In either case, we aren't going to be able to sync
2915   // with the process state.
2916   if (current_mod_id.GetStopID() == 0)
2917     return false;
2918 
2919   bool changed = false;
2920   const bool was_valid = m_mod_id.IsValid();
2921   if (was_valid) {
2922     if (m_mod_id == current_mod_id) {
2923       // Everything is already up to date in this object, no need to update the
2924       // execution context scope.
2925       changed = false;
2926     } else {
2927       m_mod_id = current_mod_id;
2928       m_needs_update = true;
2929       changed = true;
2930     }
2931   }
2932 
2933   // Now re-look up the thread and frame in case the underlying objects have
2934   // gone away & been recreated. That way we'll be sure to return a valid
2935   // exe_scope. If we used to have a thread or a frame but can't find it
2936   // anymore, then mark ourselves as invalid.
2937 
2938   if (!accept_invalid_exe_ctx) {
2939     if (m_exe_ctx_ref.HasThreadRef()) {
2940       ThreadSP thread_sp(m_exe_ctx_ref.GetThreadSP());
2941       if (thread_sp) {
2942         if (m_exe_ctx_ref.HasFrameRef()) {
2943           StackFrameSP frame_sp(m_exe_ctx_ref.GetFrameSP());
2944           if (!frame_sp) {
2945             // We used to have a frame, but now it is gone
2946             SetInvalid();
2947             changed = was_valid;
2948           }
2949         }
2950       } else {
2951         // We used to have a thread, but now it is gone
2952         SetInvalid();
2953         changed = was_valid;
2954       }
2955     }
2956   }
2957 
2958   return changed;
2959 }
2960 
2961 void ValueObject::EvaluationPoint::SetUpdated() {
2962   ProcessSP process_sp(m_exe_ctx_ref.GetProcessSP());
2963   if (process_sp)
2964     m_mod_id = process_sp->GetModID();
2965   m_needs_update = false;
2966 }
2967 
2968 void ValueObject::ClearUserVisibleData(uint32_t clear_mask) {
2969   if ((clear_mask & eClearUserVisibleDataItemsValue) ==
2970       eClearUserVisibleDataItemsValue)
2971     m_value_str.clear();
2972 
2973   if ((clear_mask & eClearUserVisibleDataItemsLocation) ==
2974       eClearUserVisibleDataItemsLocation)
2975     m_location_str.clear();
2976 
2977   if ((clear_mask & eClearUserVisibleDataItemsSummary) ==
2978       eClearUserVisibleDataItemsSummary)
2979     m_summary_str.clear();
2980 
2981   if ((clear_mask & eClearUserVisibleDataItemsDescription) ==
2982       eClearUserVisibleDataItemsDescription)
2983     m_object_desc_str.clear();
2984 
2985   if ((clear_mask & eClearUserVisibleDataItemsSyntheticChildren) ==
2986       eClearUserVisibleDataItemsSyntheticChildren) {
2987     if (m_synthetic_value)
2988       m_synthetic_value = nullptr;
2989   }
2990 }
2991 
2992 SymbolContextScope *ValueObject::GetSymbolContextScope() {
2993   if (m_parent) {
2994     if (!m_parent->IsPointerOrReferenceType())
2995       return m_parent->GetSymbolContextScope();
2996   }
2997   return nullptr;
2998 }
2999 
3000 lldb::ValueObjectSP
3001 ValueObject::CreateValueObjectFromExpression(llvm::StringRef name,
3002                                              llvm::StringRef expression,
3003                                              const ExecutionContext &exe_ctx) {
3004   return CreateValueObjectFromExpression(name, expression, exe_ctx,
3005                                          EvaluateExpressionOptions());
3006 }
3007 
3008 lldb::ValueObjectSP ValueObject::CreateValueObjectFromExpression(
3009     llvm::StringRef name, llvm::StringRef expression,
3010     const ExecutionContext &exe_ctx, const EvaluateExpressionOptions &options) {
3011   lldb::ValueObjectSP retval_sp;
3012   lldb::TargetSP target_sp(exe_ctx.GetTargetSP());
3013   if (!target_sp)
3014     return retval_sp;
3015   if (expression.empty())
3016     return retval_sp;
3017   target_sp->EvaluateExpression(expression, exe_ctx.GetFrameSP().get(),
3018                                 retval_sp, options);
3019   if (retval_sp && !name.empty())
3020     retval_sp->SetName(ConstString(name));
3021   return retval_sp;
3022 }
3023 
3024 lldb::ValueObjectSP ValueObject::CreateValueObjectFromAddress(
3025     llvm::StringRef name, uint64_t address, const ExecutionContext &exe_ctx,
3026     CompilerType type) {
3027   if (type) {
3028     CompilerType pointer_type(type.GetPointerType());
3029     if (pointer_type) {
3030       lldb::DataBufferSP buffer(
3031           new lldb_private::DataBufferHeap(&address, sizeof(lldb::addr_t)));
3032       lldb::ValueObjectSP ptr_result_valobj_sp(ValueObjectConstResult::Create(
3033           exe_ctx.GetBestExecutionContextScope(), pointer_type,
3034           ConstString(name), buffer, exe_ctx.GetByteOrder(),
3035           exe_ctx.GetAddressByteSize()));
3036       if (ptr_result_valobj_sp) {
3037         ptr_result_valobj_sp->GetValue().SetValueType(
3038             Value::ValueType::LoadAddress);
3039         Status err;
3040         ptr_result_valobj_sp = ptr_result_valobj_sp->Dereference(err);
3041         if (ptr_result_valobj_sp && !name.empty())
3042           ptr_result_valobj_sp->SetName(ConstString(name));
3043       }
3044       return ptr_result_valobj_sp;
3045     }
3046   }
3047   return lldb::ValueObjectSP();
3048 }
3049 
3050 lldb::ValueObjectSP ValueObject::CreateValueObjectFromData(
3051     llvm::StringRef name, const DataExtractor &data,
3052     const ExecutionContext &exe_ctx, CompilerType type) {
3053   lldb::ValueObjectSP new_value_sp;
3054   new_value_sp = ValueObjectConstResult::Create(
3055       exe_ctx.GetBestExecutionContextScope(), type, ConstString(name), data,
3056       LLDB_INVALID_ADDRESS);
3057   new_value_sp->SetAddressTypeOfChildren(eAddressTypeLoad);
3058   if (new_value_sp && !name.empty())
3059     new_value_sp->SetName(ConstString(name));
3060   return new_value_sp;
3061 }
3062 
3063 ModuleSP ValueObject::GetModule() {
3064   ValueObject *root(GetRoot());
3065   if (root != this)
3066     return root->GetModule();
3067   return lldb::ModuleSP();
3068 }
3069 
3070 ValueObject *ValueObject::GetRoot() {
3071   if (m_root)
3072     return m_root;
3073   return (m_root = FollowParentChain([](ValueObject *vo) -> bool {
3074             return (vo->m_parent != nullptr);
3075           }));
3076 }
3077 
3078 ValueObject *
3079 ValueObject::FollowParentChain(std::function<bool(ValueObject *)> f) {
3080   ValueObject *vo = this;
3081   while (vo) {
3082     if (!f(vo))
3083       break;
3084     vo = vo->m_parent;
3085   }
3086   return vo;
3087 }
3088 
3089 AddressType ValueObject::GetAddressTypeOfChildren() {
3090   if (m_address_type_of_ptr_or_ref_children == eAddressTypeInvalid) {
3091     ValueObject *root(GetRoot());
3092     if (root != this)
3093       return root->GetAddressTypeOfChildren();
3094   }
3095   return m_address_type_of_ptr_or_ref_children;
3096 }
3097 
3098 lldb::DynamicValueType ValueObject::GetDynamicValueType() {
3099   ValueObject *with_dv_info = this;
3100   while (with_dv_info) {
3101     if (with_dv_info->HasDynamicValueTypeInfo())
3102       return with_dv_info->GetDynamicValueTypeImpl();
3103     with_dv_info = with_dv_info->m_parent;
3104   }
3105   return lldb::eNoDynamicValues;
3106 }
3107 
3108 lldb::Format ValueObject::GetFormat() const {
3109   const ValueObject *with_fmt_info = this;
3110   while (with_fmt_info) {
3111     if (with_fmt_info->m_format != lldb::eFormatDefault)
3112       return with_fmt_info->m_format;
3113     with_fmt_info = with_fmt_info->m_parent;
3114   }
3115   return m_format;
3116 }
3117 
3118 lldb::LanguageType ValueObject::GetPreferredDisplayLanguage() {
3119   lldb::LanguageType type = m_preferred_display_language;
3120   if (m_preferred_display_language == lldb::eLanguageTypeUnknown) {
3121     if (GetRoot()) {
3122       if (GetRoot() == this) {
3123         if (StackFrameSP frame_sp = GetFrameSP()) {
3124           const SymbolContext &sc(
3125               frame_sp->GetSymbolContext(eSymbolContextCompUnit));
3126           if (CompileUnit *cu = sc.comp_unit)
3127             type = cu->GetLanguage();
3128         }
3129       } else {
3130         type = GetRoot()->GetPreferredDisplayLanguage();
3131       }
3132     }
3133   }
3134   return (m_preferred_display_language = type); // only compute it once
3135 }
3136 
3137 void ValueObject::SetPreferredDisplayLanguageIfNeeded(lldb::LanguageType lt) {
3138   if (m_preferred_display_language == lldb::eLanguageTypeUnknown)
3139     SetPreferredDisplayLanguage(lt);
3140 }
3141 
3142 bool ValueObject::CanProvideValue() {
3143   // we need to support invalid types as providers of values because some bare-
3144   // board debugging scenarios have no notion of types, but still manage to
3145   // have raw numeric values for things like registers. sigh.
3146   CompilerType type = GetCompilerType();
3147   return (!type.IsValid()) || (0 != (type.GetTypeInfo() & eTypeHasValue));
3148 }
3149 
3150 
3151 
3152 ValueObjectSP ValueObject::Persist() {
3153   if (!UpdateValueIfNeeded())
3154     return nullptr;
3155 
3156   TargetSP target_sp(GetTargetSP());
3157   if (!target_sp)
3158     return nullptr;
3159 
3160   PersistentExpressionState *persistent_state =
3161       target_sp->GetPersistentExpressionStateForLanguage(
3162           GetPreferredDisplayLanguage());
3163 
3164   if (!persistent_state)
3165     return nullptr;
3166 
3167   ConstString name = persistent_state->GetNextPersistentVariableName();
3168 
3169   ValueObjectSP const_result_sp =
3170       ValueObjectConstResult::Create(target_sp.get(), GetValue(), name);
3171 
3172   ExpressionVariableSP persistent_var_sp =
3173       persistent_state->CreatePersistentVariable(const_result_sp);
3174   persistent_var_sp->m_live_sp = persistent_var_sp->m_frozen_sp;
3175   persistent_var_sp->m_flags |= ExpressionVariable::EVIsProgramReference;
3176 
3177   return persistent_var_sp->GetValueObject();
3178 }
3179