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