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