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