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