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