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