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