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