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