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