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