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     LanguageRuntime *runtime =
1700         process->GetLanguageRuntime(GetObjectRuntimeLanguage());
1701     if (!runtime)
1702       runtime = ObjCLanguageRuntime::Get(*process);
1703     if (runtime)
1704       return runtime->IsRuntimeSupportValue(*this);
1705     // If there is no language runtime, trust the compiler to mark all
1706     // runtime support variables as artificial.
1707     return GetVariable() && GetVariable()->IsArtificial();
1708   }
1709   return false;
1710 }
1711 
1712 bool ValueObject::IsNilReference() {
1713   if (Language *language = Language::FindPlugin(GetObjectRuntimeLanguage())) {
1714     return language->IsNilReference(*this);
1715   }
1716   return false;
1717 }
1718 
1719 bool ValueObject::IsUninitializedReference() {
1720   if (Language *language = Language::FindPlugin(GetObjectRuntimeLanguage())) {
1721     return language->IsUninitializedReference(*this);
1722   }
1723   return false;
1724 }
1725 
1726 // This allows you to create an array member using and index that doesn't not
1727 // fall in the normal bounds of the array. Many times structure can be defined
1728 // as: struct Collection {
1729 //     uint32_t item_count;
1730 //     Item item_array[0];
1731 // };
1732 // The size of the "item_array" is 1, but many times in practice there are more
1733 // items in "item_array".
1734 
1735 ValueObjectSP ValueObject::GetSyntheticArrayMember(size_t index,
1736                                                    bool can_create) {
1737   ValueObjectSP synthetic_child_sp;
1738   if (IsPointerType() || IsArrayType()) {
1739     char index_str[64];
1740     snprintf(index_str, sizeof(index_str), "[%" PRIu64 "]", (uint64_t)index);
1741     ConstString index_const_str(index_str);
1742     // Check if we have already created a synthetic array member in this valid
1743     // object. If we have we will re-use it.
1744     synthetic_child_sp = GetSyntheticChild(index_const_str);
1745     if (!synthetic_child_sp) {
1746       ValueObject *synthetic_child;
1747       // We haven't made a synthetic array member for INDEX yet, so lets make
1748       // one and cache it for any future reference.
1749       synthetic_child = CreateChildAtIndex(0, true, index);
1750 
1751       // Cache the value if we got one back...
1752       if (synthetic_child) {
1753         AddSyntheticChild(index_const_str, synthetic_child);
1754         synthetic_child_sp = synthetic_child->GetSP();
1755         synthetic_child_sp->SetName(ConstString(index_str));
1756         synthetic_child_sp->m_is_array_item_for_pointer = true;
1757       }
1758     }
1759   }
1760   return synthetic_child_sp;
1761 }
1762 
1763 ValueObjectSP ValueObject::GetSyntheticBitFieldChild(uint32_t from, uint32_t to,
1764                                                      bool can_create) {
1765   ValueObjectSP synthetic_child_sp;
1766   if (IsScalarType()) {
1767     char index_str[64];
1768     snprintf(index_str, sizeof(index_str), "[%i-%i]", from, to);
1769     ConstString index_const_str(index_str);
1770     // Check if we have already created a synthetic array member in this valid
1771     // object. If we have we will re-use it.
1772     synthetic_child_sp = GetSyntheticChild(index_const_str);
1773     if (!synthetic_child_sp) {
1774       uint32_t bit_field_size = to - from + 1;
1775       uint32_t bit_field_offset = from;
1776       if (GetDataExtractor().GetByteOrder() == eByteOrderBig)
1777         bit_field_offset =
1778             GetByteSize() * 8 - bit_field_size - bit_field_offset;
1779       // We haven't made a synthetic array member for INDEX yet, so lets make
1780       // one and cache it for any future reference.
1781       ValueObjectChild *synthetic_child = new ValueObjectChild(
1782           *this, GetCompilerType(), index_const_str, GetByteSize(), 0,
1783           bit_field_size, bit_field_offset, false, false, eAddressTypeInvalid,
1784           0);
1785 
1786       // Cache the value if we got one back...
1787       if (synthetic_child) {
1788         AddSyntheticChild(index_const_str, synthetic_child);
1789         synthetic_child_sp = synthetic_child->GetSP();
1790         synthetic_child_sp->SetName(ConstString(index_str));
1791         synthetic_child_sp->m_is_bitfield_for_scalar = true;
1792       }
1793     }
1794   }
1795   return synthetic_child_sp;
1796 }
1797 
1798 ValueObjectSP ValueObject::GetSyntheticChildAtOffset(
1799     uint32_t offset, const CompilerType &type, bool can_create,
1800     ConstString name_const_str) {
1801 
1802   ValueObjectSP synthetic_child_sp;
1803 
1804   if (name_const_str.IsEmpty()) {
1805     char name_str[64];
1806     snprintf(name_str, sizeof(name_str), "@%i", offset);
1807     name_const_str.SetCString(name_str);
1808   }
1809 
1810   // Check if we have already created a synthetic array member in this valid
1811   // object. If we have we will re-use it.
1812   synthetic_child_sp = GetSyntheticChild(name_const_str);
1813 
1814   if (synthetic_child_sp.get())
1815     return synthetic_child_sp;
1816 
1817   if (!can_create)
1818     return {};
1819 
1820   ExecutionContext exe_ctx(GetExecutionContextRef());
1821   llvm::Optional<uint64_t> size =
1822       type.GetByteSize(exe_ctx.GetBestExecutionContextScope());
1823   if (!size)
1824     return {};
1825   ValueObjectChild *synthetic_child =
1826       new ValueObjectChild(*this, type, name_const_str, *size, offset, 0, 0,
1827                            false, false, eAddressTypeInvalid, 0);
1828   if (synthetic_child) {
1829     AddSyntheticChild(name_const_str, synthetic_child);
1830     synthetic_child_sp = synthetic_child->GetSP();
1831     synthetic_child_sp->SetName(name_const_str);
1832     synthetic_child_sp->m_is_child_at_offset = true;
1833   }
1834   return synthetic_child_sp;
1835 }
1836 
1837 ValueObjectSP ValueObject::GetSyntheticBase(uint32_t offset,
1838                                             const CompilerType &type,
1839                                             bool can_create,
1840                                             ConstString name_const_str) {
1841   ValueObjectSP synthetic_child_sp;
1842 
1843   if (name_const_str.IsEmpty()) {
1844     char name_str[128];
1845     snprintf(name_str, sizeof(name_str), "base%s@%i",
1846              type.GetTypeName().AsCString("<unknown>"), offset);
1847     name_const_str.SetCString(name_str);
1848   }
1849 
1850   // Check if we have already created a synthetic array member in this valid
1851   // object. If we have we will re-use it.
1852   synthetic_child_sp = GetSyntheticChild(name_const_str);
1853 
1854   if (synthetic_child_sp.get())
1855     return synthetic_child_sp;
1856 
1857   if (!can_create)
1858     return {};
1859 
1860   const bool is_base_class = true;
1861 
1862   ExecutionContext exe_ctx(GetExecutionContextRef());
1863   llvm::Optional<uint64_t> size =
1864       type.GetByteSize(exe_ctx.GetBestExecutionContextScope());
1865   if (!size)
1866     return {};
1867   ValueObjectChild *synthetic_child =
1868       new ValueObjectChild(*this, type, name_const_str, *size, offset, 0, 0,
1869                            is_base_class, false, eAddressTypeInvalid, 0);
1870   if (synthetic_child) {
1871     AddSyntheticChild(name_const_str, synthetic_child);
1872     synthetic_child_sp = synthetic_child->GetSP();
1873     synthetic_child_sp->SetName(name_const_str);
1874   }
1875   return synthetic_child_sp;
1876 }
1877 
1878 // your expression path needs to have a leading . or -> (unless it somehow
1879 // "looks like" an array, in which case it has a leading [ symbol). while the [
1880 // is meaningful and should be shown to the user, . and -> are just parser
1881 // design, but by no means added information for the user.. strip them off
1882 static const char *SkipLeadingExpressionPathSeparators(const char *expression) {
1883   if (!expression || !expression[0])
1884     return expression;
1885   if (expression[0] == '.')
1886     return expression + 1;
1887   if (expression[0] == '-' && expression[1] == '>')
1888     return expression + 2;
1889   return expression;
1890 }
1891 
1892 ValueObjectSP
1893 ValueObject::GetSyntheticExpressionPathChild(const char *expression,
1894                                              bool can_create) {
1895   ValueObjectSP synthetic_child_sp;
1896   ConstString name_const_string(expression);
1897   // Check if we have already created a synthetic array member in this valid
1898   // object. If we have we will re-use it.
1899   synthetic_child_sp = GetSyntheticChild(name_const_string);
1900   if (!synthetic_child_sp) {
1901     // We haven't made a synthetic array member for expression yet, so lets
1902     // make one and cache it for any future reference.
1903     synthetic_child_sp = GetValueForExpressionPath(
1904         expression, nullptr, nullptr,
1905         GetValueForExpressionPathOptions().SetSyntheticChildrenTraversal(
1906             GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
1907                 None));
1908 
1909     // Cache the value if we got one back...
1910     if (synthetic_child_sp.get()) {
1911       // FIXME: this causes a "real" child to end up with its name changed to
1912       // the contents of expression
1913       AddSyntheticChild(name_const_string, synthetic_child_sp.get());
1914       synthetic_child_sp->SetName(
1915           ConstString(SkipLeadingExpressionPathSeparators(expression)));
1916     }
1917   }
1918   return synthetic_child_sp;
1919 }
1920 
1921 void ValueObject::CalculateSyntheticValue(bool use_synthetic) {
1922   if (!use_synthetic)
1923     return;
1924 
1925   TargetSP target_sp(GetTargetSP());
1926   if (target_sp && !target_sp->GetEnableSyntheticValue()) {
1927     m_synthetic_value = nullptr;
1928     return;
1929   }
1930 
1931   lldb::SyntheticChildrenSP current_synth_sp(m_synthetic_children_sp);
1932 
1933   if (!UpdateFormatsIfNeeded() && m_synthetic_value)
1934     return;
1935 
1936   if (m_synthetic_children_sp.get() == nullptr)
1937     return;
1938 
1939   if (current_synth_sp == m_synthetic_children_sp && m_synthetic_value)
1940     return;
1941 
1942   m_synthetic_value = new ValueObjectSynthetic(*this, m_synthetic_children_sp);
1943 }
1944 
1945 void ValueObject::CalculateDynamicValue(DynamicValueType use_dynamic) {
1946   if (use_dynamic == eNoDynamicValues)
1947     return;
1948 
1949   if (!m_dynamic_value && !IsDynamic()) {
1950     ExecutionContext exe_ctx(GetExecutionContextRef());
1951     Process *process = exe_ctx.GetProcessPtr();
1952     if (process && process->IsPossibleDynamicValue(*this)) {
1953       ClearDynamicTypeInformation();
1954       m_dynamic_value = new ValueObjectDynamicValue(*this, use_dynamic);
1955     }
1956   }
1957 }
1958 
1959 ValueObjectSP ValueObject::GetDynamicValue(DynamicValueType use_dynamic) {
1960   if (use_dynamic == eNoDynamicValues)
1961     return ValueObjectSP();
1962 
1963   if (!IsDynamic() && m_dynamic_value == nullptr) {
1964     CalculateDynamicValue(use_dynamic);
1965   }
1966   if (m_dynamic_value)
1967     return m_dynamic_value->GetSP();
1968   else
1969     return ValueObjectSP();
1970 }
1971 
1972 ValueObjectSP ValueObject::GetStaticValue() { return GetSP(); }
1973 
1974 lldb::ValueObjectSP ValueObject::GetNonSyntheticValue() { return GetSP(); }
1975 
1976 ValueObjectSP ValueObject::GetSyntheticValue(bool use_synthetic) {
1977   if (!use_synthetic)
1978     return ValueObjectSP();
1979 
1980   CalculateSyntheticValue(use_synthetic);
1981 
1982   if (m_synthetic_value)
1983     return m_synthetic_value->GetSP();
1984   else
1985     return ValueObjectSP();
1986 }
1987 
1988 bool ValueObject::HasSyntheticValue() {
1989   UpdateFormatsIfNeeded();
1990 
1991   if (m_synthetic_children_sp.get() == nullptr)
1992     return false;
1993 
1994   CalculateSyntheticValue(true);
1995 
1996   return m_synthetic_value != nullptr;
1997 }
1998 
1999 bool ValueObject::GetBaseClassPath(Stream &s) {
2000   if (IsBaseClass()) {
2001     bool parent_had_base_class =
2002         GetParent() && GetParent()->GetBaseClassPath(s);
2003     CompilerType compiler_type = GetCompilerType();
2004     std::string cxx_class_name;
2005     bool this_had_base_class =
2006         ClangASTContext::GetCXXClassName(compiler_type, cxx_class_name);
2007     if (this_had_base_class) {
2008       if (parent_had_base_class)
2009         s.PutCString("::");
2010       s.PutCString(cxx_class_name);
2011     }
2012     return parent_had_base_class || this_had_base_class;
2013   }
2014   return false;
2015 }
2016 
2017 ValueObject *ValueObject::GetNonBaseClassParent() {
2018   if (GetParent()) {
2019     if (GetParent()->IsBaseClass())
2020       return GetParent()->GetNonBaseClassParent();
2021     else
2022       return GetParent();
2023   }
2024   return nullptr;
2025 }
2026 
2027 bool ValueObject::IsBaseClass(uint32_t &depth) {
2028   if (!IsBaseClass()) {
2029     depth = 0;
2030     return false;
2031   }
2032   if (GetParent()) {
2033     GetParent()->IsBaseClass(depth);
2034     depth = depth + 1;
2035     return true;
2036   }
2037   // TODO: a base of no parent? weird..
2038   depth = 1;
2039   return true;
2040 }
2041 
2042 void ValueObject::GetExpressionPath(Stream &s, bool qualify_cxx_base_classes,
2043                                     GetExpressionPathFormat epformat) {
2044   // synthetic children do not actually "exist" as part of the hierarchy, and
2045   // sometimes they are consed up in ways that don't make sense from an
2046   // underlying language/API standpoint. So, use a special code path here to
2047   // return something that can hopefully be used in expression
2048   if (m_is_synthetic_children_generated) {
2049     UpdateValueIfNeeded();
2050 
2051     if (m_value.GetValueType() == Value::eValueTypeLoadAddress) {
2052       if (IsPointerOrReferenceType()) {
2053         s.Printf("((%s)0x%" PRIx64 ")", GetTypeName().AsCString("void"),
2054                  GetValueAsUnsigned(0));
2055         return;
2056       } else {
2057         uint64_t load_addr =
2058             m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
2059         if (load_addr != LLDB_INVALID_ADDRESS) {
2060           s.Printf("(*( (%s *)0x%" PRIx64 "))", GetTypeName().AsCString("void"),
2061                    load_addr);
2062           return;
2063         }
2064       }
2065     }
2066 
2067     if (CanProvideValue()) {
2068       s.Printf("((%s)%s)", GetTypeName().AsCString("void"),
2069                GetValueAsCString());
2070       return;
2071     }
2072 
2073     return;
2074   }
2075 
2076   const bool is_deref_of_parent = IsDereferenceOfParent();
2077 
2078   if (is_deref_of_parent &&
2079       epformat == eGetExpressionPathFormatDereferencePointers) {
2080     // this is the original format of GetExpressionPath() producing code like
2081     // *(a_ptr).memberName, which is entirely fine, until you put this into
2082     // StackFrame::GetValueForVariableExpressionPath() which prefers to see
2083     // a_ptr->memberName. the eHonorPointers mode is meant to produce strings
2084     // in this latter format
2085     s.PutCString("*(");
2086   }
2087 
2088   ValueObject *parent = GetParent();
2089 
2090   if (parent)
2091     parent->GetExpressionPath(s, qualify_cxx_base_classes, epformat);
2092 
2093   // if we are a deref_of_parent just because we are synthetic array members
2094   // made up to allow ptr[%d] syntax to work in variable printing, then add our
2095   // name ([%d]) to the expression path
2096   if (m_is_array_item_for_pointer &&
2097       epformat == eGetExpressionPathFormatHonorPointers)
2098     s.PutCString(m_name.AsCString());
2099 
2100   if (!IsBaseClass()) {
2101     if (!is_deref_of_parent) {
2102       ValueObject *non_base_class_parent = GetNonBaseClassParent();
2103       if (non_base_class_parent &&
2104           !non_base_class_parent->GetName().IsEmpty()) {
2105         CompilerType non_base_class_parent_compiler_type =
2106             non_base_class_parent->GetCompilerType();
2107         if (non_base_class_parent_compiler_type) {
2108           if (parent && parent->IsDereferenceOfParent() &&
2109               epformat == eGetExpressionPathFormatHonorPointers) {
2110             s.PutCString("->");
2111           } else {
2112             const uint32_t non_base_class_parent_type_info =
2113                 non_base_class_parent_compiler_type.GetTypeInfo();
2114 
2115             if (non_base_class_parent_type_info & eTypeIsPointer) {
2116               s.PutCString("->");
2117             } else if ((non_base_class_parent_type_info & eTypeHasChildren) &&
2118                        !(non_base_class_parent_type_info & eTypeIsArray)) {
2119               s.PutChar('.');
2120             }
2121           }
2122         }
2123       }
2124 
2125       const char *name = GetName().GetCString();
2126       if (name) {
2127         if (qualify_cxx_base_classes) {
2128           if (GetBaseClassPath(s))
2129             s.PutCString("::");
2130         }
2131         s.PutCString(name);
2132       }
2133     }
2134   }
2135 
2136   if (is_deref_of_parent &&
2137       epformat == eGetExpressionPathFormatDereferencePointers) {
2138     s.PutChar(')');
2139   }
2140 }
2141 
2142 ValueObjectSP ValueObject::GetValueForExpressionPath(
2143     llvm::StringRef expression, ExpressionPathScanEndReason *reason_to_stop,
2144     ExpressionPathEndResultType *final_value_type,
2145     const GetValueForExpressionPathOptions &options,
2146     ExpressionPathAftermath *final_task_on_target) {
2147 
2148   ExpressionPathScanEndReason dummy_reason_to_stop =
2149       ValueObject::eExpressionPathScanEndReasonUnknown;
2150   ExpressionPathEndResultType dummy_final_value_type =
2151       ValueObject::eExpressionPathEndResultTypeInvalid;
2152   ExpressionPathAftermath dummy_final_task_on_target =
2153       ValueObject::eExpressionPathAftermathNothing;
2154 
2155   ValueObjectSP ret_val = GetValueForExpressionPath_Impl(
2156       expression, reason_to_stop ? reason_to_stop : &dummy_reason_to_stop,
2157       final_value_type ? final_value_type : &dummy_final_value_type, options,
2158       final_task_on_target ? final_task_on_target
2159                            : &dummy_final_task_on_target);
2160 
2161   if (!final_task_on_target ||
2162       *final_task_on_target == ValueObject::eExpressionPathAftermathNothing)
2163     return ret_val;
2164 
2165   if (ret_val.get() &&
2166       ((final_value_type ? *final_value_type : dummy_final_value_type) ==
2167        eExpressionPathEndResultTypePlain)) // I can only deref and takeaddress
2168                                            // of plain objects
2169   {
2170     if ((final_task_on_target ? *final_task_on_target
2171                               : dummy_final_task_on_target) ==
2172         ValueObject::eExpressionPathAftermathDereference) {
2173       Status error;
2174       ValueObjectSP final_value = ret_val->Dereference(error);
2175       if (error.Fail() || !final_value.get()) {
2176         if (reason_to_stop)
2177           *reason_to_stop =
2178               ValueObject::eExpressionPathScanEndReasonDereferencingFailed;
2179         if (final_value_type)
2180           *final_value_type = ValueObject::eExpressionPathEndResultTypeInvalid;
2181         return ValueObjectSP();
2182       } else {
2183         if (final_task_on_target)
2184           *final_task_on_target = ValueObject::eExpressionPathAftermathNothing;
2185         return final_value;
2186       }
2187     }
2188     if (*final_task_on_target ==
2189         ValueObject::eExpressionPathAftermathTakeAddress) {
2190       Status error;
2191       ValueObjectSP final_value = ret_val->AddressOf(error);
2192       if (error.Fail() || !final_value.get()) {
2193         if (reason_to_stop)
2194           *reason_to_stop =
2195               ValueObject::eExpressionPathScanEndReasonTakingAddressFailed;
2196         if (final_value_type)
2197           *final_value_type = ValueObject::eExpressionPathEndResultTypeInvalid;
2198         return ValueObjectSP();
2199       } else {
2200         if (final_task_on_target)
2201           *final_task_on_target = ValueObject::eExpressionPathAftermathNothing;
2202         return final_value;
2203       }
2204     }
2205   }
2206   return ret_val; // final_task_on_target will still have its original value, so
2207                   // you know I did not do it
2208 }
2209 
2210 ValueObjectSP ValueObject::GetValueForExpressionPath_Impl(
2211     llvm::StringRef expression, ExpressionPathScanEndReason *reason_to_stop,
2212     ExpressionPathEndResultType *final_result,
2213     const GetValueForExpressionPathOptions &options,
2214     ExpressionPathAftermath *what_next) {
2215   ValueObjectSP root = GetSP();
2216 
2217   if (!root)
2218     return nullptr;
2219 
2220   llvm::StringRef remainder = expression;
2221 
2222   while (true) {
2223     llvm::StringRef temp_expression = remainder;
2224 
2225     CompilerType root_compiler_type = root->GetCompilerType();
2226     CompilerType pointee_compiler_type;
2227     Flags pointee_compiler_type_info;
2228 
2229     Flags root_compiler_type_info(
2230         root_compiler_type.GetTypeInfo(&pointee_compiler_type));
2231     if (pointee_compiler_type)
2232       pointee_compiler_type_info.Reset(pointee_compiler_type.GetTypeInfo());
2233 
2234     if (temp_expression.empty()) {
2235       *reason_to_stop = ValueObject::eExpressionPathScanEndReasonEndOfString;
2236       return root;
2237     }
2238 
2239     switch (temp_expression.front()) {
2240     case '-': {
2241       temp_expression = temp_expression.drop_front();
2242       if (options.m_check_dot_vs_arrow_syntax &&
2243           root_compiler_type_info.Test(eTypeIsPointer)) // if you are trying to
2244                                                         // use -> on a
2245                                                         // non-pointer and I
2246                                                         // must catch the error
2247       {
2248         *reason_to_stop =
2249             ValueObject::eExpressionPathScanEndReasonArrowInsteadOfDot;
2250         *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2251         return ValueObjectSP();
2252       }
2253       if (root_compiler_type_info.Test(eTypeIsObjC) && // if yo are trying to
2254                                                        // extract an ObjC IVar
2255                                                        // when this is forbidden
2256           root_compiler_type_info.Test(eTypeIsPointer) &&
2257           options.m_no_fragile_ivar) {
2258         *reason_to_stop =
2259             ValueObject::eExpressionPathScanEndReasonFragileIVarNotAllowed;
2260         *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2261         return ValueObjectSP();
2262       }
2263       if (!temp_expression.startswith(">")) {
2264         *reason_to_stop =
2265             ValueObject::eExpressionPathScanEndReasonUnexpectedSymbol;
2266         *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2267         return ValueObjectSP();
2268       }
2269     }
2270       LLVM_FALLTHROUGH;
2271     case '.': // or fallthrough from ->
2272     {
2273       if (options.m_check_dot_vs_arrow_syntax &&
2274           temp_expression.front() == '.' &&
2275           root_compiler_type_info.Test(eTypeIsPointer)) // if you are trying to
2276                                                         // use . on a pointer
2277                                                         // and I must catch the
2278                                                         // error
2279       {
2280         *reason_to_stop =
2281             ValueObject::eExpressionPathScanEndReasonDotInsteadOfArrow;
2282         *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2283         return nullptr;
2284       }
2285       temp_expression = temp_expression.drop_front(); // skip . or >
2286 
2287       size_t next_sep_pos = temp_expression.find_first_of("-.[", 1);
2288       ConstString child_name;
2289       if (next_sep_pos == llvm::StringRef::npos) // if no other separator just
2290                                                  // expand this last layer
2291       {
2292         child_name.SetString(temp_expression);
2293         ValueObjectSP child_valobj_sp =
2294             root->GetChildMemberWithName(child_name, true);
2295 
2296         if (child_valobj_sp.get()) // we know we are done, so just return
2297         {
2298           *reason_to_stop =
2299               ValueObject::eExpressionPathScanEndReasonEndOfString;
2300           *final_result = ValueObject::eExpressionPathEndResultTypePlain;
2301           return child_valobj_sp;
2302         } else {
2303           switch (options.m_synthetic_children_traversal) {
2304           case GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2305               None:
2306             break;
2307           case GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2308               FromSynthetic:
2309             if (root->IsSynthetic()) {
2310               child_valobj_sp = root->GetNonSyntheticValue();
2311               if (child_valobj_sp.get())
2312                 child_valobj_sp =
2313                     child_valobj_sp->GetChildMemberWithName(child_name, true);
2314             }
2315             break;
2316           case GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2317               ToSynthetic:
2318             if (!root->IsSynthetic()) {
2319               child_valobj_sp = root->GetSyntheticValue();
2320               if (child_valobj_sp.get())
2321                 child_valobj_sp =
2322                     child_valobj_sp->GetChildMemberWithName(child_name, true);
2323             }
2324             break;
2325           case GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2326               Both:
2327             if (root->IsSynthetic()) {
2328               child_valobj_sp = root->GetNonSyntheticValue();
2329               if (child_valobj_sp.get())
2330                 child_valobj_sp =
2331                     child_valobj_sp->GetChildMemberWithName(child_name, true);
2332             } else {
2333               child_valobj_sp = root->GetSyntheticValue();
2334               if (child_valobj_sp.get())
2335                 child_valobj_sp =
2336                     child_valobj_sp->GetChildMemberWithName(child_name, true);
2337             }
2338             break;
2339           }
2340         }
2341 
2342         // if we are here and options.m_no_synthetic_children is true,
2343         // child_valobj_sp is going to be a NULL SP, so we hit the "else"
2344         // branch, and return an error
2345         if (child_valobj_sp.get()) // if it worked, just return
2346         {
2347           *reason_to_stop =
2348               ValueObject::eExpressionPathScanEndReasonEndOfString;
2349           *final_result = ValueObject::eExpressionPathEndResultTypePlain;
2350           return child_valobj_sp;
2351         } else {
2352           *reason_to_stop =
2353               ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2354           *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2355           return nullptr;
2356         }
2357       } else // other layers do expand
2358       {
2359         llvm::StringRef next_separator = temp_expression.substr(next_sep_pos);
2360 
2361         child_name.SetString(temp_expression.slice(0, next_sep_pos));
2362 
2363         ValueObjectSP child_valobj_sp =
2364             root->GetChildMemberWithName(child_name, true);
2365         if (child_valobj_sp.get()) // store the new root and move on
2366         {
2367           root = child_valobj_sp;
2368           remainder = next_separator;
2369           *final_result = ValueObject::eExpressionPathEndResultTypePlain;
2370           continue;
2371         } else {
2372           switch (options.m_synthetic_children_traversal) {
2373           case GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2374               None:
2375             break;
2376           case GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2377               FromSynthetic:
2378             if (root->IsSynthetic()) {
2379               child_valobj_sp = root->GetNonSyntheticValue();
2380               if (child_valobj_sp.get())
2381                 child_valobj_sp =
2382                     child_valobj_sp->GetChildMemberWithName(child_name, true);
2383             }
2384             break;
2385           case GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2386               ToSynthetic:
2387             if (!root->IsSynthetic()) {
2388               child_valobj_sp = root->GetSyntheticValue();
2389               if (child_valobj_sp.get())
2390                 child_valobj_sp =
2391                     child_valobj_sp->GetChildMemberWithName(child_name, true);
2392             }
2393             break;
2394           case GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2395               Both:
2396             if (root->IsSynthetic()) {
2397               child_valobj_sp = root->GetNonSyntheticValue();
2398               if (child_valobj_sp.get())
2399                 child_valobj_sp =
2400                     child_valobj_sp->GetChildMemberWithName(child_name, true);
2401             } else {
2402               child_valobj_sp = root->GetSyntheticValue();
2403               if (child_valobj_sp.get())
2404                 child_valobj_sp =
2405                     child_valobj_sp->GetChildMemberWithName(child_name, true);
2406             }
2407             break;
2408           }
2409         }
2410 
2411         // if we are here and options.m_no_synthetic_children is true,
2412         // child_valobj_sp is going to be a NULL SP, so we hit the "else"
2413         // branch, and return an error
2414         if (child_valobj_sp.get()) // if it worked, move on
2415         {
2416           root = child_valobj_sp;
2417           remainder = next_separator;
2418           *final_result = ValueObject::eExpressionPathEndResultTypePlain;
2419           continue;
2420         } else {
2421           *reason_to_stop =
2422               ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2423           *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2424           return nullptr;
2425         }
2426       }
2427       break;
2428     }
2429     case '[': {
2430       if (!root_compiler_type_info.Test(eTypeIsArray) &&
2431           !root_compiler_type_info.Test(eTypeIsPointer) &&
2432           !root_compiler_type_info.Test(
2433               eTypeIsVector)) // if this is not a T[] nor a T*
2434       {
2435         if (!root_compiler_type_info.Test(
2436                 eTypeIsScalar)) // if this is not even a scalar...
2437         {
2438           if (options.m_synthetic_children_traversal ==
2439               GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2440                   None) // ...only chance left is synthetic
2441           {
2442             *reason_to_stop =
2443                 ValueObject::eExpressionPathScanEndReasonRangeOperatorInvalid;
2444             *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2445             return ValueObjectSP();
2446           }
2447         } else if (!options.m_allow_bitfields_syntax) // if this is a scalar,
2448                                                       // check that we can
2449                                                       // expand bitfields
2450         {
2451           *reason_to_stop =
2452               ValueObject::eExpressionPathScanEndReasonRangeOperatorNotAllowed;
2453           *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2454           return ValueObjectSP();
2455         }
2456       }
2457       if (temp_expression[1] ==
2458           ']') // if this is an unbounded range it only works for arrays
2459       {
2460         if (!root_compiler_type_info.Test(eTypeIsArray)) {
2461           *reason_to_stop =
2462               ValueObject::eExpressionPathScanEndReasonEmptyRangeNotAllowed;
2463           *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2464           return nullptr;
2465         } else // even if something follows, we cannot expand unbounded ranges,
2466                // just let the caller do it
2467         {
2468           *reason_to_stop =
2469               ValueObject::eExpressionPathScanEndReasonArrayRangeOperatorMet;
2470           *final_result =
2471               ValueObject::eExpressionPathEndResultTypeUnboundedRange;
2472           return root;
2473         }
2474       }
2475 
2476       size_t close_bracket_position = temp_expression.find(']', 1);
2477       if (close_bracket_position ==
2478           llvm::StringRef::npos) // if there is no ], this is a syntax error
2479       {
2480         *reason_to_stop =
2481             ValueObject::eExpressionPathScanEndReasonUnexpectedSymbol;
2482         *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2483         return nullptr;
2484       }
2485 
2486       llvm::StringRef bracket_expr =
2487           temp_expression.slice(1, close_bracket_position);
2488 
2489       // If this was an empty expression it would have been caught by the if
2490       // above.
2491       assert(!bracket_expr.empty());
2492 
2493       if (!bracket_expr.contains('-')) {
2494         // if no separator, this is of the form [N].  Note that this cannot be
2495         // an unbounded range of the form [], because that case was handled
2496         // above with an unconditional return.
2497         unsigned long index = 0;
2498         if (bracket_expr.getAsInteger(0, index)) {
2499           *reason_to_stop =
2500               ValueObject::eExpressionPathScanEndReasonUnexpectedSymbol;
2501           *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2502           return nullptr;
2503         }
2504 
2505         // from here on we do have a valid index
2506         if (root_compiler_type_info.Test(eTypeIsArray)) {
2507           ValueObjectSP child_valobj_sp = root->GetChildAtIndex(index, true);
2508           if (!child_valobj_sp)
2509             child_valobj_sp = root->GetSyntheticArrayMember(index, true);
2510           if (!child_valobj_sp)
2511             if (root->HasSyntheticValue() &&
2512                 root->GetSyntheticValue()->GetNumChildren() > index)
2513               child_valobj_sp =
2514                   root->GetSyntheticValue()->GetChildAtIndex(index, true);
2515           if (child_valobj_sp) {
2516             root = child_valobj_sp;
2517             remainder =
2518                 temp_expression.substr(close_bracket_position + 1); // skip ]
2519             *final_result = ValueObject::eExpressionPathEndResultTypePlain;
2520             continue;
2521           } else {
2522             *reason_to_stop =
2523                 ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2524             *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2525             return nullptr;
2526           }
2527         } else if (root_compiler_type_info.Test(eTypeIsPointer)) {
2528           if (*what_next ==
2529                   ValueObject::
2530                       eExpressionPathAftermathDereference && // if this is a
2531                                                              // ptr-to-scalar, I
2532                                                              // am accessing it
2533                                                              // by index and I
2534                                                              // would have
2535                                                              // deref'ed anyway,
2536                                                              // then do it now
2537                                                              // and use this as
2538                                                              // a bitfield
2539               pointee_compiler_type_info.Test(eTypeIsScalar)) {
2540             Status error;
2541             root = root->Dereference(error);
2542             if (error.Fail() || !root) {
2543               *reason_to_stop =
2544                   ValueObject::eExpressionPathScanEndReasonDereferencingFailed;
2545               *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2546               return nullptr;
2547             } else {
2548               *what_next = eExpressionPathAftermathNothing;
2549               continue;
2550             }
2551           } else {
2552             if (root->GetCompilerType().GetMinimumLanguage() ==
2553                     eLanguageTypeObjC &&
2554                 pointee_compiler_type_info.AllClear(eTypeIsPointer) &&
2555                 root->HasSyntheticValue() &&
2556                 (options.m_synthetic_children_traversal ==
2557                      GetValueForExpressionPathOptions::
2558                          SyntheticChildrenTraversal::ToSynthetic ||
2559                  options.m_synthetic_children_traversal ==
2560                      GetValueForExpressionPathOptions::
2561                          SyntheticChildrenTraversal::Both)) {
2562               root = root->GetSyntheticValue()->GetChildAtIndex(index, true);
2563             } else
2564               root = root->GetSyntheticArrayMember(index, true);
2565             if (!root) {
2566               *reason_to_stop =
2567                   ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2568               *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2569               return nullptr;
2570             } else {
2571               remainder =
2572                   temp_expression.substr(close_bracket_position + 1); // skip ]
2573               *final_result = ValueObject::eExpressionPathEndResultTypePlain;
2574               continue;
2575             }
2576           }
2577         } else if (root_compiler_type_info.Test(eTypeIsScalar)) {
2578           root = root->GetSyntheticBitFieldChild(index, index, true);
2579           if (!root) {
2580             *reason_to_stop =
2581                 ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2582             *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2583             return nullptr;
2584           } else // we do not know how to expand members of bitfields, so we
2585                  // just return and let the caller do any further processing
2586           {
2587             *reason_to_stop = ValueObject::
2588                 eExpressionPathScanEndReasonBitfieldRangeOperatorMet;
2589             *final_result = ValueObject::eExpressionPathEndResultTypeBitfield;
2590             return root;
2591           }
2592         } else if (root_compiler_type_info.Test(eTypeIsVector)) {
2593           root = root->GetChildAtIndex(index, true);
2594           if (!root) {
2595             *reason_to_stop =
2596                 ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2597             *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2598             return ValueObjectSP();
2599           } else {
2600             remainder =
2601                 temp_expression.substr(close_bracket_position + 1); // skip ]
2602             *final_result = ValueObject::eExpressionPathEndResultTypePlain;
2603             continue;
2604           }
2605         } else if (options.m_synthetic_children_traversal ==
2606                        GetValueForExpressionPathOptions::
2607                            SyntheticChildrenTraversal::ToSynthetic ||
2608                    options.m_synthetic_children_traversal ==
2609                        GetValueForExpressionPathOptions::
2610                            SyntheticChildrenTraversal::Both) {
2611           if (root->HasSyntheticValue())
2612             root = root->GetSyntheticValue();
2613           else if (!root->IsSynthetic()) {
2614             *reason_to_stop =
2615                 ValueObject::eExpressionPathScanEndReasonSyntheticValueMissing;
2616             *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2617             return nullptr;
2618           }
2619           // if we are here, then root itself is a synthetic VO.. should be
2620           // good to go
2621 
2622           if (!root) {
2623             *reason_to_stop =
2624                 ValueObject::eExpressionPathScanEndReasonSyntheticValueMissing;
2625             *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2626             return nullptr;
2627           }
2628           root = root->GetChildAtIndex(index, true);
2629           if (!root) {
2630             *reason_to_stop =
2631                 ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2632             *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2633             return nullptr;
2634           } else {
2635             remainder =
2636                 temp_expression.substr(close_bracket_position + 1); // skip ]
2637             *final_result = ValueObject::eExpressionPathEndResultTypePlain;
2638             continue;
2639           }
2640         } else {
2641           *reason_to_stop =
2642               ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2643           *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2644           return nullptr;
2645         }
2646       } else {
2647         // we have a low and a high index
2648         llvm::StringRef sleft, sright;
2649         unsigned long low_index, high_index;
2650         std::tie(sleft, sright) = bracket_expr.split('-');
2651         if (sleft.getAsInteger(0, low_index) ||
2652             sright.getAsInteger(0, high_index)) {
2653           *reason_to_stop =
2654               ValueObject::eExpressionPathScanEndReasonUnexpectedSymbol;
2655           *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2656           return nullptr;
2657         }
2658 
2659         if (low_index > high_index) // swap indices if required
2660           std::swap(low_index, high_index);
2661 
2662         if (root_compiler_type_info.Test(
2663                 eTypeIsScalar)) // expansion only works for scalars
2664         {
2665           root = root->GetSyntheticBitFieldChild(low_index, high_index, true);
2666           if (!root) {
2667             *reason_to_stop =
2668                 ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2669             *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2670             return nullptr;
2671           } else {
2672             *reason_to_stop = ValueObject::
2673                 eExpressionPathScanEndReasonBitfieldRangeOperatorMet;
2674             *final_result = ValueObject::eExpressionPathEndResultTypeBitfield;
2675             return root;
2676           }
2677         } else if (root_compiler_type_info.Test(
2678                        eTypeIsPointer) && // if this is a ptr-to-scalar, I am
2679                                           // accessing it by index and I would
2680                                           // have deref'ed anyway, then do it
2681                                           // now and use this as a bitfield
2682                    *what_next ==
2683                        ValueObject::eExpressionPathAftermathDereference &&
2684                    pointee_compiler_type_info.Test(eTypeIsScalar)) {
2685           Status error;
2686           root = root->Dereference(error);
2687           if (error.Fail() || !root) {
2688             *reason_to_stop =
2689                 ValueObject::eExpressionPathScanEndReasonDereferencingFailed;
2690             *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2691             return nullptr;
2692           } else {
2693             *what_next = ValueObject::eExpressionPathAftermathNothing;
2694             continue;
2695           }
2696         } else {
2697           *reason_to_stop =
2698               ValueObject::eExpressionPathScanEndReasonArrayRangeOperatorMet;
2699           *final_result = ValueObject::eExpressionPathEndResultTypeBoundedRange;
2700           return root;
2701         }
2702       }
2703       break;
2704     }
2705     default: // some non-separator is in the way
2706     {
2707       *reason_to_stop =
2708           ValueObject::eExpressionPathScanEndReasonUnexpectedSymbol;
2709       *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2710       return nullptr;
2711     }
2712     }
2713   }
2714 }
2715 
2716 void ValueObject::LogValueObject(Log *log) {
2717   if (log)
2718     return LogValueObject(log, DumpValueObjectOptions(*this));
2719 }
2720 
2721 void ValueObject::LogValueObject(Log *log,
2722                                  const DumpValueObjectOptions &options) {
2723   if (log) {
2724     StreamString s;
2725     Dump(s, options);
2726     if (s.GetSize())
2727       log->PutCString(s.GetData());
2728   }
2729 }
2730 
2731 void ValueObject::Dump(Stream &s) { Dump(s, DumpValueObjectOptions(*this)); }
2732 
2733 void ValueObject::Dump(Stream &s, const DumpValueObjectOptions &options) {
2734   ValueObjectPrinter printer(this, &s, options);
2735   printer.PrintValueObject();
2736 }
2737 
2738 ValueObjectSP ValueObject::CreateConstantValue(ConstString name) {
2739   ValueObjectSP valobj_sp;
2740 
2741   if (UpdateValueIfNeeded(false) && m_error.Success()) {
2742     ExecutionContext exe_ctx(GetExecutionContextRef());
2743 
2744     DataExtractor data;
2745     data.SetByteOrder(m_data.GetByteOrder());
2746     data.SetAddressByteSize(m_data.GetAddressByteSize());
2747 
2748     if (IsBitfield()) {
2749       Value v(Scalar(GetValueAsUnsigned(UINT64_MAX)));
2750       m_error = v.GetValueAsData(&exe_ctx, data, 0, GetModule().get());
2751     } else
2752       m_error = m_value.GetValueAsData(&exe_ctx, data, 0, GetModule().get());
2753 
2754     valobj_sp = ValueObjectConstResult::Create(
2755         exe_ctx.GetBestExecutionContextScope(), GetCompilerType(), name, data,
2756         GetAddressOf());
2757   }
2758 
2759   if (!valobj_sp) {
2760     ExecutionContext exe_ctx(GetExecutionContextRef());
2761     valobj_sp = ValueObjectConstResult::Create(
2762         exe_ctx.GetBestExecutionContextScope(), m_error);
2763   }
2764   return valobj_sp;
2765 }
2766 
2767 ValueObjectSP ValueObject::GetQualifiedRepresentationIfAvailable(
2768     lldb::DynamicValueType dynValue, bool synthValue) {
2769   ValueObjectSP result_sp(GetSP());
2770 
2771   switch (dynValue) {
2772   case lldb::eDynamicCanRunTarget:
2773   case lldb::eDynamicDontRunTarget: {
2774     if (!result_sp->IsDynamic()) {
2775       if (result_sp->GetDynamicValue(dynValue))
2776         result_sp = result_sp->GetDynamicValue(dynValue);
2777     }
2778   } break;
2779   case lldb::eNoDynamicValues: {
2780     if (result_sp->IsDynamic()) {
2781       if (result_sp->GetStaticValue())
2782         result_sp = result_sp->GetStaticValue();
2783     }
2784   } break;
2785   }
2786 
2787   if (synthValue) {
2788     if (!result_sp->IsSynthetic()) {
2789       if (result_sp->GetSyntheticValue())
2790         result_sp = result_sp->GetSyntheticValue();
2791     }
2792   } else {
2793     if (result_sp->IsSynthetic()) {
2794       if (result_sp->GetNonSyntheticValue())
2795         result_sp = result_sp->GetNonSyntheticValue();
2796     }
2797   }
2798 
2799   return result_sp;
2800 }
2801 
2802 ValueObjectSP ValueObject::Dereference(Status &error) {
2803   if (m_deref_valobj)
2804     return m_deref_valobj->GetSP();
2805 
2806   const bool is_pointer_or_reference_type = IsPointerOrReferenceType();
2807   if (is_pointer_or_reference_type) {
2808     bool omit_empty_base_classes = true;
2809     bool ignore_array_bounds = false;
2810 
2811     std::string child_name_str;
2812     uint32_t child_byte_size = 0;
2813     int32_t child_byte_offset = 0;
2814     uint32_t child_bitfield_bit_size = 0;
2815     uint32_t child_bitfield_bit_offset = 0;
2816     bool child_is_base_class = false;
2817     bool child_is_deref_of_parent = false;
2818     const bool transparent_pointers = false;
2819     CompilerType compiler_type = GetCompilerType();
2820     CompilerType child_compiler_type;
2821     uint64_t language_flags;
2822 
2823     ExecutionContext exe_ctx(GetExecutionContextRef());
2824 
2825     child_compiler_type = compiler_type.GetChildCompilerTypeAtIndex(
2826         &exe_ctx, 0, transparent_pointers, omit_empty_base_classes,
2827         ignore_array_bounds, child_name_str, child_byte_size, child_byte_offset,
2828         child_bitfield_bit_size, child_bitfield_bit_offset, child_is_base_class,
2829         child_is_deref_of_parent, this, language_flags);
2830     if (child_compiler_type && child_byte_size) {
2831       ConstString child_name;
2832       if (!child_name_str.empty())
2833         child_name.SetCString(child_name_str.c_str());
2834 
2835       m_deref_valobj = new ValueObjectChild(
2836           *this, child_compiler_type, child_name, child_byte_size,
2837           child_byte_offset, child_bitfield_bit_size, child_bitfield_bit_offset,
2838           child_is_base_class, child_is_deref_of_parent, eAddressTypeInvalid,
2839           language_flags);
2840     }
2841   } else if (HasSyntheticValue()) {
2842     m_deref_valobj =
2843         GetSyntheticValue()
2844             ->GetChildMemberWithName(ConstString("$$dereference$$"), true)
2845             .get();
2846   }
2847 
2848   if (m_deref_valobj) {
2849     error.Clear();
2850     return m_deref_valobj->GetSP();
2851   } else {
2852     StreamString strm;
2853     GetExpressionPath(strm, true);
2854 
2855     if (is_pointer_or_reference_type)
2856       error.SetErrorStringWithFormat("dereference failed: (%s) %s",
2857                                      GetTypeName().AsCString("<invalid type>"),
2858                                      strm.GetData());
2859     else
2860       error.SetErrorStringWithFormat("not a pointer or reference type: (%s) %s",
2861                                      GetTypeName().AsCString("<invalid type>"),
2862                                      strm.GetData());
2863     return ValueObjectSP();
2864   }
2865 }
2866 
2867 ValueObjectSP ValueObject::AddressOf(Status &error) {
2868   if (m_addr_of_valobj_sp)
2869     return m_addr_of_valobj_sp;
2870 
2871   AddressType address_type = eAddressTypeInvalid;
2872   const bool scalar_is_load_address = false;
2873   addr_t addr = GetAddressOf(scalar_is_load_address, &address_type);
2874   error.Clear();
2875   if (addr != LLDB_INVALID_ADDRESS && address_type != eAddressTypeHost) {
2876     switch (address_type) {
2877     case eAddressTypeInvalid: {
2878       StreamString expr_path_strm;
2879       GetExpressionPath(expr_path_strm, true);
2880       error.SetErrorStringWithFormat("'%s' is not in memory",
2881                                      expr_path_strm.GetData());
2882     } break;
2883 
2884     case eAddressTypeFile:
2885     case eAddressTypeLoad: {
2886       CompilerType compiler_type = GetCompilerType();
2887       if (compiler_type) {
2888         std::string name(1, '&');
2889         name.append(m_name.AsCString(""));
2890         ExecutionContext exe_ctx(GetExecutionContextRef());
2891         m_addr_of_valobj_sp = ValueObjectConstResult::Create(
2892             exe_ctx.GetBestExecutionContextScope(),
2893             compiler_type.GetPointerType(), ConstString(name.c_str()), addr,
2894             eAddressTypeInvalid, m_data.GetAddressByteSize());
2895       }
2896     } break;
2897     default:
2898       break;
2899     }
2900   } else {
2901     StreamString expr_path_strm;
2902     GetExpressionPath(expr_path_strm, true);
2903     error.SetErrorStringWithFormat("'%s' doesn't have a valid address",
2904                                    expr_path_strm.GetData());
2905   }
2906 
2907   return m_addr_of_valobj_sp;
2908 }
2909 
2910 ValueObjectSP ValueObject::Cast(const CompilerType &compiler_type) {
2911   return ValueObjectCast::Create(*this, GetName(), compiler_type);
2912 }
2913 
2914 lldb::ValueObjectSP ValueObject::Clone(ConstString new_name) {
2915   return ValueObjectCast::Create(*this, new_name, GetCompilerType());
2916 }
2917 
2918 ValueObjectSP ValueObject::CastPointerType(const char *name,
2919                                            CompilerType &compiler_type) {
2920   ValueObjectSP valobj_sp;
2921   AddressType address_type;
2922   addr_t ptr_value = GetPointerValue(&address_type);
2923 
2924   if (ptr_value != LLDB_INVALID_ADDRESS) {
2925     Address ptr_addr(ptr_value);
2926     ExecutionContext exe_ctx(GetExecutionContextRef());
2927     valobj_sp = ValueObjectMemory::Create(
2928         exe_ctx.GetBestExecutionContextScope(), name, ptr_addr, compiler_type);
2929   }
2930   return valobj_sp;
2931 }
2932 
2933 ValueObjectSP ValueObject::CastPointerType(const char *name, TypeSP &type_sp) {
2934   ValueObjectSP valobj_sp;
2935   AddressType address_type;
2936   addr_t ptr_value = GetPointerValue(&address_type);
2937 
2938   if (ptr_value != LLDB_INVALID_ADDRESS) {
2939     Address ptr_addr(ptr_value);
2940     ExecutionContext exe_ctx(GetExecutionContextRef());
2941     valobj_sp = ValueObjectMemory::Create(
2942         exe_ctx.GetBestExecutionContextScope(), name, ptr_addr, type_sp);
2943   }
2944   return valobj_sp;
2945 }
2946 
2947 ValueObject::EvaluationPoint::EvaluationPoint()
2948     : m_mod_id(), m_exe_ctx_ref(), m_needs_update(true) {}
2949 
2950 ValueObject::EvaluationPoint::EvaluationPoint(ExecutionContextScope *exe_scope,
2951                                               bool use_selected)
2952     : m_mod_id(), m_exe_ctx_ref(), m_needs_update(true) {
2953   ExecutionContext exe_ctx(exe_scope);
2954   TargetSP target_sp(exe_ctx.GetTargetSP());
2955   if (target_sp) {
2956     m_exe_ctx_ref.SetTargetSP(target_sp);
2957     ProcessSP process_sp(exe_ctx.GetProcessSP());
2958     if (!process_sp)
2959       process_sp = target_sp->GetProcessSP();
2960 
2961     if (process_sp) {
2962       m_mod_id = process_sp->GetModID();
2963       m_exe_ctx_ref.SetProcessSP(process_sp);
2964 
2965       ThreadSP thread_sp(exe_ctx.GetThreadSP());
2966 
2967       if (!thread_sp) {
2968         if (use_selected)
2969           thread_sp = process_sp->GetThreadList().GetSelectedThread();
2970       }
2971 
2972       if (thread_sp) {
2973         m_exe_ctx_ref.SetThreadSP(thread_sp);
2974 
2975         StackFrameSP frame_sp(exe_ctx.GetFrameSP());
2976         if (!frame_sp) {
2977           if (use_selected)
2978             frame_sp = thread_sp->GetSelectedFrame();
2979         }
2980         if (frame_sp)
2981           m_exe_ctx_ref.SetFrameSP(frame_sp);
2982       }
2983     }
2984   }
2985 }
2986 
2987 ValueObject::EvaluationPoint::EvaluationPoint(
2988     const ValueObject::EvaluationPoint &rhs)
2989     : m_mod_id(), m_exe_ctx_ref(rhs.m_exe_ctx_ref), m_needs_update(true) {}
2990 
2991 ValueObject::EvaluationPoint::~EvaluationPoint() {}
2992 
2993 // This function checks the EvaluationPoint against the current process state.
2994 // If the current state matches the evaluation point, or the evaluation point
2995 // is already invalid, then we return false, meaning "no change".  If the
2996 // current state is different, we update our state, and return true meaning
2997 // "yes, change".  If we did see a change, we also set m_needs_update to true,
2998 // so future calls to NeedsUpdate will return true. exe_scope will be set to
2999 // the current execution context scope.
3000 
3001 bool ValueObject::EvaluationPoint::SyncWithProcessState(
3002     bool accept_invalid_exe_ctx) {
3003   // Start with the target, if it is NULL, then we're obviously not going to
3004   // get any further:
3005   const bool thread_and_frame_only_if_stopped = true;
3006   ExecutionContext exe_ctx(
3007       m_exe_ctx_ref.Lock(thread_and_frame_only_if_stopped));
3008 
3009   if (exe_ctx.GetTargetPtr() == nullptr)
3010     return false;
3011 
3012   // If we don't have a process nothing can change.
3013   Process *process = exe_ctx.GetProcessPtr();
3014   if (process == nullptr)
3015     return false;
3016 
3017   // If our stop id is the current stop ID, nothing has changed:
3018   ProcessModID current_mod_id = process->GetModID();
3019 
3020   // If the current stop id is 0, either we haven't run yet, or the process
3021   // state has been cleared. In either case, we aren't going to be able to sync
3022   // with the process state.
3023   if (current_mod_id.GetStopID() == 0)
3024     return false;
3025 
3026   bool changed = false;
3027   const bool was_valid = m_mod_id.IsValid();
3028   if (was_valid) {
3029     if (m_mod_id == current_mod_id) {
3030       // Everything is already up to date in this object, no need to update the
3031       // execution context scope.
3032       changed = false;
3033     } else {
3034       m_mod_id = current_mod_id;
3035       m_needs_update = true;
3036       changed = true;
3037     }
3038   }
3039 
3040   // Now re-look up the thread and frame in case the underlying objects have
3041   // gone away & been recreated. That way we'll be sure to return a valid
3042   // exe_scope. If we used to have a thread or a frame but can't find it
3043   // anymore, then mark ourselves as invalid.
3044 
3045   if (!accept_invalid_exe_ctx) {
3046     if (m_exe_ctx_ref.HasThreadRef()) {
3047       ThreadSP thread_sp(m_exe_ctx_ref.GetThreadSP());
3048       if (thread_sp) {
3049         if (m_exe_ctx_ref.HasFrameRef()) {
3050           StackFrameSP frame_sp(m_exe_ctx_ref.GetFrameSP());
3051           if (!frame_sp) {
3052             // We used to have a frame, but now it is gone
3053             SetInvalid();
3054             changed = was_valid;
3055           }
3056         }
3057       } else {
3058         // We used to have a thread, but now it is gone
3059         SetInvalid();
3060         changed = was_valid;
3061       }
3062     }
3063   }
3064 
3065   return changed;
3066 }
3067 
3068 void ValueObject::EvaluationPoint::SetUpdated() {
3069   ProcessSP process_sp(m_exe_ctx_ref.GetProcessSP());
3070   if (process_sp)
3071     m_mod_id = process_sp->GetModID();
3072   m_needs_update = false;
3073 }
3074 
3075 void ValueObject::ClearUserVisibleData(uint32_t clear_mask) {
3076   if ((clear_mask & eClearUserVisibleDataItemsValue) ==
3077       eClearUserVisibleDataItemsValue)
3078     m_value_str.clear();
3079 
3080   if ((clear_mask & eClearUserVisibleDataItemsLocation) ==
3081       eClearUserVisibleDataItemsLocation)
3082     m_location_str.clear();
3083 
3084   if ((clear_mask & eClearUserVisibleDataItemsSummary) ==
3085       eClearUserVisibleDataItemsSummary)
3086     m_summary_str.clear();
3087 
3088   if ((clear_mask & eClearUserVisibleDataItemsDescription) ==
3089       eClearUserVisibleDataItemsDescription)
3090     m_object_desc_str.clear();
3091 
3092   if ((clear_mask & eClearUserVisibleDataItemsSyntheticChildren) ==
3093       eClearUserVisibleDataItemsSyntheticChildren) {
3094     if (m_synthetic_value)
3095       m_synthetic_value = nullptr;
3096   }
3097 
3098   if ((clear_mask & eClearUserVisibleDataItemsValidator) ==
3099       eClearUserVisibleDataItemsValidator)
3100     m_validation_result.reset();
3101 }
3102 
3103 SymbolContextScope *ValueObject::GetSymbolContextScope() {
3104   if (m_parent) {
3105     if (!m_parent->IsPointerOrReferenceType())
3106       return m_parent->GetSymbolContextScope();
3107   }
3108   return nullptr;
3109 }
3110 
3111 lldb::ValueObjectSP
3112 ValueObject::CreateValueObjectFromExpression(llvm::StringRef name,
3113                                              llvm::StringRef expression,
3114                                              const ExecutionContext &exe_ctx) {
3115   return CreateValueObjectFromExpression(name, expression, exe_ctx,
3116                                          EvaluateExpressionOptions());
3117 }
3118 
3119 lldb::ValueObjectSP ValueObject::CreateValueObjectFromExpression(
3120     llvm::StringRef name, llvm::StringRef expression,
3121     const ExecutionContext &exe_ctx, const EvaluateExpressionOptions &options) {
3122   lldb::ValueObjectSP retval_sp;
3123   lldb::TargetSP target_sp(exe_ctx.GetTargetSP());
3124   if (!target_sp)
3125     return retval_sp;
3126   if (expression.empty())
3127     return retval_sp;
3128   target_sp->EvaluateExpression(expression, exe_ctx.GetFrameSP().get(),
3129                                 retval_sp, options);
3130   if (retval_sp && !name.empty())
3131     retval_sp->SetName(ConstString(name));
3132   return retval_sp;
3133 }
3134 
3135 lldb::ValueObjectSP ValueObject::CreateValueObjectFromAddress(
3136     llvm::StringRef name, uint64_t address, const ExecutionContext &exe_ctx,
3137     CompilerType type) {
3138   if (type) {
3139     CompilerType pointer_type(type.GetPointerType());
3140     if (pointer_type) {
3141       lldb::DataBufferSP buffer(
3142           new lldb_private::DataBufferHeap(&address, sizeof(lldb::addr_t)));
3143       lldb::ValueObjectSP ptr_result_valobj_sp(ValueObjectConstResult::Create(
3144           exe_ctx.GetBestExecutionContextScope(), pointer_type,
3145           ConstString(name), buffer, exe_ctx.GetByteOrder(),
3146           exe_ctx.GetAddressByteSize()));
3147       if (ptr_result_valobj_sp) {
3148         ptr_result_valobj_sp->GetValue().SetValueType(
3149             Value::eValueTypeLoadAddress);
3150         Status err;
3151         ptr_result_valobj_sp = ptr_result_valobj_sp->Dereference(err);
3152         if (ptr_result_valobj_sp && !name.empty())
3153           ptr_result_valobj_sp->SetName(ConstString(name));
3154       }
3155       return ptr_result_valobj_sp;
3156     }
3157   }
3158   return lldb::ValueObjectSP();
3159 }
3160 
3161 lldb::ValueObjectSP ValueObject::CreateValueObjectFromData(
3162     llvm::StringRef name, const DataExtractor &data,
3163     const ExecutionContext &exe_ctx, CompilerType type) {
3164   lldb::ValueObjectSP new_value_sp;
3165   new_value_sp = ValueObjectConstResult::Create(
3166       exe_ctx.GetBestExecutionContextScope(), type, ConstString(name), data,
3167       LLDB_INVALID_ADDRESS);
3168   new_value_sp->SetAddressTypeOfChildren(eAddressTypeLoad);
3169   if (new_value_sp && !name.empty())
3170     new_value_sp->SetName(ConstString(name));
3171   return new_value_sp;
3172 }
3173 
3174 ModuleSP ValueObject::GetModule() {
3175   ValueObject *root(GetRoot());
3176   if (root != this)
3177     return root->GetModule();
3178   return lldb::ModuleSP();
3179 }
3180 
3181 ValueObject *ValueObject::GetRoot() {
3182   if (m_root)
3183     return m_root;
3184   return (m_root = FollowParentChain([](ValueObject *vo) -> bool {
3185             return (vo->m_parent != nullptr);
3186           }));
3187 }
3188 
3189 ValueObject *
3190 ValueObject::FollowParentChain(std::function<bool(ValueObject *)> f) {
3191   ValueObject *vo = this;
3192   while (vo) {
3193     if (!f(vo))
3194       break;
3195     vo = vo->m_parent;
3196   }
3197   return vo;
3198 }
3199 
3200 AddressType ValueObject::GetAddressTypeOfChildren() {
3201   if (m_address_type_of_ptr_or_ref_children == eAddressTypeInvalid) {
3202     ValueObject *root(GetRoot());
3203     if (root != this)
3204       return root->GetAddressTypeOfChildren();
3205   }
3206   return m_address_type_of_ptr_or_ref_children;
3207 }
3208 
3209 lldb::DynamicValueType ValueObject::GetDynamicValueType() {
3210   ValueObject *with_dv_info = this;
3211   while (with_dv_info) {
3212     if (with_dv_info->HasDynamicValueTypeInfo())
3213       return with_dv_info->GetDynamicValueTypeImpl();
3214     with_dv_info = with_dv_info->m_parent;
3215   }
3216   return lldb::eNoDynamicValues;
3217 }
3218 
3219 lldb::Format ValueObject::GetFormat() const {
3220   const ValueObject *with_fmt_info = this;
3221   while (with_fmt_info) {
3222     if (with_fmt_info->m_format != lldb::eFormatDefault)
3223       return with_fmt_info->m_format;
3224     with_fmt_info = with_fmt_info->m_parent;
3225   }
3226   return m_format;
3227 }
3228 
3229 lldb::LanguageType ValueObject::GetPreferredDisplayLanguage() {
3230   lldb::LanguageType type = m_preferred_display_language;
3231   if (m_preferred_display_language == lldb::eLanguageTypeUnknown) {
3232     if (GetRoot()) {
3233       if (GetRoot() == this) {
3234         if (StackFrameSP frame_sp = GetFrameSP()) {
3235           const SymbolContext &sc(
3236               frame_sp->GetSymbolContext(eSymbolContextCompUnit));
3237           if (CompileUnit *cu = sc.comp_unit)
3238             type = cu->GetLanguage();
3239         }
3240       } else {
3241         type = GetRoot()->GetPreferredDisplayLanguage();
3242       }
3243     }
3244   }
3245   return (m_preferred_display_language = type); // only compute it once
3246 }
3247 
3248 void ValueObject::SetPreferredDisplayLanguage(lldb::LanguageType lt) {
3249   m_preferred_display_language = lt;
3250 }
3251 
3252 void ValueObject::SetPreferredDisplayLanguageIfNeeded(lldb::LanguageType lt) {
3253   if (m_preferred_display_language == lldb::eLanguageTypeUnknown)
3254     SetPreferredDisplayLanguage(lt);
3255 }
3256 
3257 bool ValueObject::CanProvideValue() {
3258   // we need to support invalid types as providers of values because some bare-
3259   // board debugging scenarios have no notion of types, but still manage to
3260   // have raw numeric values for things like registers. sigh.
3261   const CompilerType &type(GetCompilerType());
3262   return (!type.IsValid()) || (0 != (type.GetTypeInfo() & eTypeHasValue));
3263 }
3264 
3265 bool ValueObject::IsChecksumEmpty() { return m_value_checksum.empty(); }
3266 
3267 ValueObjectSP ValueObject::Persist() {
3268   if (!UpdateValueIfNeeded())
3269     return nullptr;
3270 
3271   TargetSP target_sp(GetTargetSP());
3272   if (!target_sp)
3273     return nullptr;
3274 
3275   PersistentExpressionState *persistent_state =
3276       target_sp->GetPersistentExpressionStateForLanguage(
3277           GetPreferredDisplayLanguage());
3278 
3279   if (!persistent_state)
3280     return nullptr;
3281 
3282   auto prefix = persistent_state->GetPersistentVariablePrefix();
3283   ConstString name =
3284       persistent_state->GetNextPersistentVariableName(*target_sp, prefix);
3285 
3286   ValueObjectSP const_result_sp =
3287       ValueObjectConstResult::Create(target_sp.get(), GetValue(), name);
3288 
3289   ExpressionVariableSP clang_var_sp =
3290       persistent_state->CreatePersistentVariable(const_result_sp);
3291   clang_var_sp->m_live_sp = clang_var_sp->m_frozen_sp;
3292   clang_var_sp->m_flags |= ExpressionVariable::EVIsProgramReference;
3293 
3294   return clang_var_sp->GetValueObject();
3295 }
3296 
3297 bool ValueObject::IsSyntheticChildrenGenerated() {
3298   return m_is_synthetic_children_generated;
3299 }
3300 
3301 void ValueObject::SetSyntheticChildrenGenerated(bool b) {
3302   m_is_synthetic_children_generated = b;
3303 }
3304 
3305 uint64_t ValueObject::GetLanguageFlags() { return m_language_flags; }
3306 
3307 void ValueObject::SetLanguageFlags(uint64_t flags) { m_language_flags = flags; }
3308 
3309 ValueObjectManager::ValueObjectManager(lldb::ValueObjectSP in_valobj_sp,
3310                                        lldb::DynamicValueType use_dynamic,
3311                                        bool use_synthetic) : m_root_valobj_sp(),
3312     m_user_valobj_sp(), m_use_dynamic(use_dynamic), m_stop_id(UINT32_MAX),
3313     m_use_synthetic(use_synthetic) {
3314   if (!in_valobj_sp)
3315     return;
3316   // If the user passes in a value object that is dynamic or synthetic, then
3317   // water it down to the static type.
3318   m_root_valobj_sp = in_valobj_sp->GetQualifiedRepresentationIfAvailable(lldb::eNoDynamicValues, false);
3319 }
3320 
3321 bool ValueObjectManager::IsValid() const {
3322   if (!m_root_valobj_sp)
3323     return false;
3324   lldb::TargetSP target_sp = GetTargetSP();
3325   if (target_sp)
3326     return target_sp->IsValid();
3327   return false;
3328 }
3329 
3330 lldb::ValueObjectSP ValueObjectManager::GetSP() {
3331   lldb::ProcessSP process_sp = GetProcessSP();
3332   if (!process_sp)
3333     return lldb::ValueObjectSP();
3334 
3335   const uint32_t current_stop_id = process_sp->GetLastNaturalStopID();
3336   if (current_stop_id == m_stop_id)
3337     return m_user_valobj_sp;
3338 
3339   m_stop_id = current_stop_id;
3340 
3341   if (!m_root_valobj_sp) {
3342     m_user_valobj_sp.reset();
3343     return m_root_valobj_sp;
3344   }
3345 
3346   m_user_valobj_sp = m_root_valobj_sp;
3347 
3348   if (m_use_dynamic != lldb::eNoDynamicValues) {
3349     lldb::ValueObjectSP dynamic_sp = m_user_valobj_sp->GetDynamicValue(m_use_dynamic);
3350     if (dynamic_sp)
3351       m_user_valobj_sp = dynamic_sp;
3352   }
3353 
3354   if (m_use_synthetic) {
3355     lldb::ValueObjectSP synthetic_sp = m_user_valobj_sp->GetSyntheticValue(m_use_synthetic);
3356     if (synthetic_sp)
3357       m_user_valobj_sp = synthetic_sp;
3358   }
3359 
3360   return m_user_valobj_sp;
3361 }
3362 
3363 void ValueObjectManager::SetUseDynamic(lldb::DynamicValueType use_dynamic) {
3364   if (use_dynamic != m_use_dynamic) {
3365     m_use_dynamic = use_dynamic;
3366     m_user_valobj_sp.reset();
3367     m_stop_id = UINT32_MAX;
3368   }
3369 }
3370 
3371 void ValueObjectManager::SetUseSynthetic(bool use_synthetic) {
3372   if (m_use_synthetic != use_synthetic) {
3373     m_use_synthetic = use_synthetic;
3374     m_user_valobj_sp.reset();
3375     m_stop_id = UINT32_MAX;
3376   }
3377 }
3378 
3379 lldb::TargetSP ValueObjectManager::GetTargetSP() const {
3380   if (!m_root_valobj_sp)
3381     return m_root_valobj_sp->GetTargetSP();
3382   return lldb::TargetSP();
3383 }
3384 
3385 lldb::ProcessSP ValueObjectManager::GetProcessSP() const {
3386   if (m_root_valobj_sp)
3387     return m_root_valobj_sp->GetProcessSP();
3388   return lldb::ProcessSP();
3389 }
3390 
3391 lldb::ThreadSP ValueObjectManager::GetThreadSP() const {
3392   if (m_root_valobj_sp)
3393     return m_root_valobj_sp->GetThreadSP();
3394   return lldb::ThreadSP();
3395 }
3396 
3397 lldb::StackFrameSP ValueObjectManager::GetFrameSP() const {
3398   if (m_root_valobj_sp)
3399     return m_root_valobj_sp->GetFrameSP();
3400   return lldb::StackFrameSP();
3401 }
3402