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