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     llvm::Optional<std::string> cxx_class_name =
2027         ClangASTContext::GetCXXClassName(compiler_type);
2028     if (cxx_class_name) {
2029       if (parent_had_base_class)
2030         s.PutCString("::");
2031       s.PutCString(cxx_class_name.getValue());
2032     }
2033     return parent_had_base_class || cxx_class_name;
2034   }
2035   return false;
2036 }
2037 
2038 ValueObject *ValueObject::GetNonBaseClassParent() {
2039   if (GetParent()) {
2040     if (GetParent()->IsBaseClass())
2041       return GetParent()->GetNonBaseClassParent();
2042     else
2043       return GetParent();
2044   }
2045   return nullptr;
2046 }
2047 
2048 bool ValueObject::IsBaseClass(uint32_t &depth) {
2049   if (!IsBaseClass()) {
2050     depth = 0;
2051     return false;
2052   }
2053   if (GetParent()) {
2054     GetParent()->IsBaseClass(depth);
2055     depth = depth + 1;
2056     return true;
2057   }
2058   // TODO: a base of no parent? weird..
2059   depth = 1;
2060   return true;
2061 }
2062 
2063 void ValueObject::GetExpressionPath(Stream &s, bool qualify_cxx_base_classes,
2064                                     GetExpressionPathFormat epformat) {
2065   // synthetic children do not actually "exist" as part of the hierarchy, and
2066   // sometimes they are consed up in ways that don't make sense from an
2067   // underlying language/API standpoint. So, use a special code path here to
2068   // return something that can hopefully be used in expression
2069   if (m_is_synthetic_children_generated) {
2070     UpdateValueIfNeeded();
2071 
2072     if (m_value.GetValueType() == Value::eValueTypeLoadAddress) {
2073       if (IsPointerOrReferenceType()) {
2074         s.Printf("((%s)0x%" PRIx64 ")", GetTypeName().AsCString("void"),
2075                  GetValueAsUnsigned(0));
2076         return;
2077       } else {
2078         uint64_t load_addr =
2079             m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
2080         if (load_addr != LLDB_INVALID_ADDRESS) {
2081           s.Printf("(*( (%s *)0x%" PRIx64 "))", GetTypeName().AsCString("void"),
2082                    load_addr);
2083           return;
2084         }
2085       }
2086     }
2087 
2088     if (CanProvideValue()) {
2089       s.Printf("((%s)%s)", GetTypeName().AsCString("void"),
2090                GetValueAsCString());
2091       return;
2092     }
2093 
2094     return;
2095   }
2096 
2097   const bool is_deref_of_parent = IsDereferenceOfParent();
2098 
2099   if (is_deref_of_parent &&
2100       epformat == eGetExpressionPathFormatDereferencePointers) {
2101     // this is the original format of GetExpressionPath() producing code like
2102     // *(a_ptr).memberName, which is entirely fine, until you put this into
2103     // StackFrame::GetValueForVariableExpressionPath() which prefers to see
2104     // a_ptr->memberName. the eHonorPointers mode is meant to produce strings
2105     // in this latter format
2106     s.PutCString("*(");
2107   }
2108 
2109   ValueObject *parent = GetParent();
2110 
2111   if (parent)
2112     parent->GetExpressionPath(s, qualify_cxx_base_classes, epformat);
2113 
2114   // if we are a deref_of_parent just because we are synthetic array members
2115   // made up to allow ptr[%d] syntax to work in variable printing, then add our
2116   // name ([%d]) to the expression path
2117   if (m_is_array_item_for_pointer &&
2118       epformat == eGetExpressionPathFormatHonorPointers)
2119     s.PutCString(m_name.AsCString());
2120 
2121   if (!IsBaseClass()) {
2122     if (!is_deref_of_parent) {
2123       ValueObject *non_base_class_parent = GetNonBaseClassParent();
2124       if (non_base_class_parent &&
2125           !non_base_class_parent->GetName().IsEmpty()) {
2126         CompilerType non_base_class_parent_compiler_type =
2127             non_base_class_parent->GetCompilerType();
2128         if (non_base_class_parent_compiler_type) {
2129           if (parent && parent->IsDereferenceOfParent() &&
2130               epformat == eGetExpressionPathFormatHonorPointers) {
2131             s.PutCString("->");
2132           } else {
2133             const uint32_t non_base_class_parent_type_info =
2134                 non_base_class_parent_compiler_type.GetTypeInfo();
2135 
2136             if (non_base_class_parent_type_info & eTypeIsPointer) {
2137               s.PutCString("->");
2138             } else if ((non_base_class_parent_type_info & eTypeHasChildren) &&
2139                        !(non_base_class_parent_type_info & eTypeIsArray)) {
2140               s.PutChar('.');
2141             }
2142           }
2143         }
2144       }
2145 
2146       const char *name = GetName().GetCString();
2147       if (name) {
2148         if (qualify_cxx_base_classes) {
2149           if (GetBaseClassPath(s))
2150             s.PutCString("::");
2151         }
2152         s.PutCString(name);
2153       }
2154     }
2155   }
2156 
2157   if (is_deref_of_parent &&
2158       epformat == eGetExpressionPathFormatDereferencePointers) {
2159     s.PutChar(')');
2160   }
2161 }
2162 
2163 ValueObjectSP ValueObject::GetValueForExpressionPath(
2164     llvm::StringRef expression, ExpressionPathScanEndReason *reason_to_stop,
2165     ExpressionPathEndResultType *final_value_type,
2166     const GetValueForExpressionPathOptions &options,
2167     ExpressionPathAftermath *final_task_on_target) {
2168 
2169   ExpressionPathScanEndReason dummy_reason_to_stop =
2170       ValueObject::eExpressionPathScanEndReasonUnknown;
2171   ExpressionPathEndResultType dummy_final_value_type =
2172       ValueObject::eExpressionPathEndResultTypeInvalid;
2173   ExpressionPathAftermath dummy_final_task_on_target =
2174       ValueObject::eExpressionPathAftermathNothing;
2175 
2176   ValueObjectSP ret_val = GetValueForExpressionPath_Impl(
2177       expression, reason_to_stop ? reason_to_stop : &dummy_reason_to_stop,
2178       final_value_type ? final_value_type : &dummy_final_value_type, options,
2179       final_task_on_target ? final_task_on_target
2180                            : &dummy_final_task_on_target);
2181 
2182   if (!final_task_on_target ||
2183       *final_task_on_target == ValueObject::eExpressionPathAftermathNothing)
2184     return ret_val;
2185 
2186   if (ret_val.get() &&
2187       ((final_value_type ? *final_value_type : dummy_final_value_type) ==
2188        eExpressionPathEndResultTypePlain)) // I can only deref and takeaddress
2189                                            // of plain objects
2190   {
2191     if ((final_task_on_target ? *final_task_on_target
2192                               : dummy_final_task_on_target) ==
2193         ValueObject::eExpressionPathAftermathDereference) {
2194       Status error;
2195       ValueObjectSP final_value = ret_val->Dereference(error);
2196       if (error.Fail() || !final_value.get()) {
2197         if (reason_to_stop)
2198           *reason_to_stop =
2199               ValueObject::eExpressionPathScanEndReasonDereferencingFailed;
2200         if (final_value_type)
2201           *final_value_type = ValueObject::eExpressionPathEndResultTypeInvalid;
2202         return ValueObjectSP();
2203       } else {
2204         if (final_task_on_target)
2205           *final_task_on_target = ValueObject::eExpressionPathAftermathNothing;
2206         return final_value;
2207       }
2208     }
2209     if (*final_task_on_target ==
2210         ValueObject::eExpressionPathAftermathTakeAddress) {
2211       Status error;
2212       ValueObjectSP final_value = ret_val->AddressOf(error);
2213       if (error.Fail() || !final_value.get()) {
2214         if (reason_to_stop)
2215           *reason_to_stop =
2216               ValueObject::eExpressionPathScanEndReasonTakingAddressFailed;
2217         if (final_value_type)
2218           *final_value_type = ValueObject::eExpressionPathEndResultTypeInvalid;
2219         return ValueObjectSP();
2220       } else {
2221         if (final_task_on_target)
2222           *final_task_on_target = ValueObject::eExpressionPathAftermathNothing;
2223         return final_value;
2224       }
2225     }
2226   }
2227   return ret_val; // final_task_on_target will still have its original value, so
2228                   // you know I did not do it
2229 }
2230 
2231 ValueObjectSP ValueObject::GetValueForExpressionPath_Impl(
2232     llvm::StringRef expression, ExpressionPathScanEndReason *reason_to_stop,
2233     ExpressionPathEndResultType *final_result,
2234     const GetValueForExpressionPathOptions &options,
2235     ExpressionPathAftermath *what_next) {
2236   ValueObjectSP root = GetSP();
2237 
2238   if (!root)
2239     return nullptr;
2240 
2241   llvm::StringRef remainder = expression;
2242 
2243   while (true) {
2244     llvm::StringRef temp_expression = remainder;
2245 
2246     CompilerType root_compiler_type = root->GetCompilerType();
2247     CompilerType pointee_compiler_type;
2248     Flags pointee_compiler_type_info;
2249 
2250     Flags root_compiler_type_info(
2251         root_compiler_type.GetTypeInfo(&pointee_compiler_type));
2252     if (pointee_compiler_type)
2253       pointee_compiler_type_info.Reset(pointee_compiler_type.GetTypeInfo());
2254 
2255     if (temp_expression.empty()) {
2256       *reason_to_stop = ValueObject::eExpressionPathScanEndReasonEndOfString;
2257       return root;
2258     }
2259 
2260     switch (temp_expression.front()) {
2261     case '-': {
2262       temp_expression = temp_expression.drop_front();
2263       if (options.m_check_dot_vs_arrow_syntax &&
2264           root_compiler_type_info.Test(eTypeIsPointer)) // if you are trying to
2265                                                         // use -> on a
2266                                                         // non-pointer and I
2267                                                         // must catch the error
2268       {
2269         *reason_to_stop =
2270             ValueObject::eExpressionPathScanEndReasonArrowInsteadOfDot;
2271         *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2272         return ValueObjectSP();
2273       }
2274       if (root_compiler_type_info.Test(eTypeIsObjC) && // if yo are trying to
2275                                                        // extract an ObjC IVar
2276                                                        // when this is forbidden
2277           root_compiler_type_info.Test(eTypeIsPointer) &&
2278           options.m_no_fragile_ivar) {
2279         *reason_to_stop =
2280             ValueObject::eExpressionPathScanEndReasonFragileIVarNotAllowed;
2281         *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2282         return ValueObjectSP();
2283       }
2284       if (!temp_expression.startswith(">")) {
2285         *reason_to_stop =
2286             ValueObject::eExpressionPathScanEndReasonUnexpectedSymbol;
2287         *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2288         return ValueObjectSP();
2289       }
2290     }
2291       LLVM_FALLTHROUGH;
2292     case '.': // or fallthrough from ->
2293     {
2294       if (options.m_check_dot_vs_arrow_syntax &&
2295           temp_expression.front() == '.' &&
2296           root_compiler_type_info.Test(eTypeIsPointer)) // if you are trying to
2297                                                         // use . on a pointer
2298                                                         // and I must catch the
2299                                                         // error
2300       {
2301         *reason_to_stop =
2302             ValueObject::eExpressionPathScanEndReasonDotInsteadOfArrow;
2303         *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2304         return nullptr;
2305       }
2306       temp_expression = temp_expression.drop_front(); // skip . or >
2307 
2308       size_t next_sep_pos = temp_expression.find_first_of("-.[", 1);
2309       ConstString child_name;
2310       if (next_sep_pos == llvm::StringRef::npos) // if no other separator just
2311                                                  // expand this last layer
2312       {
2313         child_name.SetString(temp_expression);
2314         ValueObjectSP child_valobj_sp =
2315             root->GetChildMemberWithName(child_name, true);
2316 
2317         if (child_valobj_sp.get()) // we know we are done, so just return
2318         {
2319           *reason_to_stop =
2320               ValueObject::eExpressionPathScanEndReasonEndOfString;
2321           *final_result = ValueObject::eExpressionPathEndResultTypePlain;
2322           return child_valobj_sp;
2323         } else {
2324           switch (options.m_synthetic_children_traversal) {
2325           case GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2326               None:
2327             break;
2328           case GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2329               FromSynthetic:
2330             if (root->IsSynthetic()) {
2331               child_valobj_sp = root->GetNonSyntheticValue();
2332               if (child_valobj_sp.get())
2333                 child_valobj_sp =
2334                     child_valobj_sp->GetChildMemberWithName(child_name, true);
2335             }
2336             break;
2337           case GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2338               ToSynthetic:
2339             if (!root->IsSynthetic()) {
2340               child_valobj_sp = root->GetSyntheticValue();
2341               if (child_valobj_sp.get())
2342                 child_valobj_sp =
2343                     child_valobj_sp->GetChildMemberWithName(child_name, true);
2344             }
2345             break;
2346           case GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2347               Both:
2348             if (root->IsSynthetic()) {
2349               child_valobj_sp = root->GetNonSyntheticValue();
2350               if (child_valobj_sp.get())
2351                 child_valobj_sp =
2352                     child_valobj_sp->GetChildMemberWithName(child_name, true);
2353             } else {
2354               child_valobj_sp = root->GetSyntheticValue();
2355               if (child_valobj_sp.get())
2356                 child_valobj_sp =
2357                     child_valobj_sp->GetChildMemberWithName(child_name, true);
2358             }
2359             break;
2360           }
2361         }
2362 
2363         // if we are here and options.m_no_synthetic_children is true,
2364         // child_valobj_sp is going to be a NULL SP, so we hit the "else"
2365         // branch, and return an error
2366         if (child_valobj_sp.get()) // if it worked, just return
2367         {
2368           *reason_to_stop =
2369               ValueObject::eExpressionPathScanEndReasonEndOfString;
2370           *final_result = ValueObject::eExpressionPathEndResultTypePlain;
2371           return child_valobj_sp;
2372         } else {
2373           *reason_to_stop =
2374               ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2375           *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2376           return nullptr;
2377         }
2378       } else // other layers do expand
2379       {
2380         llvm::StringRef next_separator = temp_expression.substr(next_sep_pos);
2381 
2382         child_name.SetString(temp_expression.slice(0, next_sep_pos));
2383 
2384         ValueObjectSP child_valobj_sp =
2385             root->GetChildMemberWithName(child_name, true);
2386         if (child_valobj_sp.get()) // store the new root and move on
2387         {
2388           root = child_valobj_sp;
2389           remainder = next_separator;
2390           *final_result = ValueObject::eExpressionPathEndResultTypePlain;
2391           continue;
2392         } else {
2393           switch (options.m_synthetic_children_traversal) {
2394           case GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2395               None:
2396             break;
2397           case GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2398               FromSynthetic:
2399             if (root->IsSynthetic()) {
2400               child_valobj_sp = root->GetNonSyntheticValue();
2401               if (child_valobj_sp.get())
2402                 child_valobj_sp =
2403                     child_valobj_sp->GetChildMemberWithName(child_name, true);
2404             }
2405             break;
2406           case GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2407               ToSynthetic:
2408             if (!root->IsSynthetic()) {
2409               child_valobj_sp = root->GetSyntheticValue();
2410               if (child_valobj_sp.get())
2411                 child_valobj_sp =
2412                     child_valobj_sp->GetChildMemberWithName(child_name, true);
2413             }
2414             break;
2415           case GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2416               Both:
2417             if (root->IsSynthetic()) {
2418               child_valobj_sp = root->GetNonSyntheticValue();
2419               if (child_valobj_sp.get())
2420                 child_valobj_sp =
2421                     child_valobj_sp->GetChildMemberWithName(child_name, true);
2422             } else {
2423               child_valobj_sp = root->GetSyntheticValue();
2424               if (child_valobj_sp.get())
2425                 child_valobj_sp =
2426                     child_valobj_sp->GetChildMemberWithName(child_name, true);
2427             }
2428             break;
2429           }
2430         }
2431 
2432         // if we are here and options.m_no_synthetic_children is true,
2433         // child_valobj_sp is going to be a NULL SP, so we hit the "else"
2434         // branch, and return an error
2435         if (child_valobj_sp.get()) // if it worked, move on
2436         {
2437           root = child_valobj_sp;
2438           remainder = next_separator;
2439           *final_result = ValueObject::eExpressionPathEndResultTypePlain;
2440           continue;
2441         } else {
2442           *reason_to_stop =
2443               ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2444           *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2445           return nullptr;
2446         }
2447       }
2448       break;
2449     }
2450     case '[': {
2451       if (!root_compiler_type_info.Test(eTypeIsArray) &&
2452           !root_compiler_type_info.Test(eTypeIsPointer) &&
2453           !root_compiler_type_info.Test(
2454               eTypeIsVector)) // if this is not a T[] nor a T*
2455       {
2456         if (!root_compiler_type_info.Test(
2457                 eTypeIsScalar)) // if this is not even a scalar...
2458         {
2459           if (options.m_synthetic_children_traversal ==
2460               GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2461                   None) // ...only chance left is synthetic
2462           {
2463             *reason_to_stop =
2464                 ValueObject::eExpressionPathScanEndReasonRangeOperatorInvalid;
2465             *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2466             return ValueObjectSP();
2467           }
2468         } else if (!options.m_allow_bitfields_syntax) // if this is a scalar,
2469                                                       // check that we can
2470                                                       // expand bitfields
2471         {
2472           *reason_to_stop =
2473               ValueObject::eExpressionPathScanEndReasonRangeOperatorNotAllowed;
2474           *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2475           return ValueObjectSP();
2476         }
2477       }
2478       if (temp_expression[1] ==
2479           ']') // if this is an unbounded range it only works for arrays
2480       {
2481         if (!root_compiler_type_info.Test(eTypeIsArray)) {
2482           *reason_to_stop =
2483               ValueObject::eExpressionPathScanEndReasonEmptyRangeNotAllowed;
2484           *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2485           return nullptr;
2486         } else // even if something follows, we cannot expand unbounded ranges,
2487                // just let the caller do it
2488         {
2489           *reason_to_stop =
2490               ValueObject::eExpressionPathScanEndReasonArrayRangeOperatorMet;
2491           *final_result =
2492               ValueObject::eExpressionPathEndResultTypeUnboundedRange;
2493           return root;
2494         }
2495       }
2496 
2497       size_t close_bracket_position = temp_expression.find(']', 1);
2498       if (close_bracket_position ==
2499           llvm::StringRef::npos) // if there is no ], this is a syntax error
2500       {
2501         *reason_to_stop =
2502             ValueObject::eExpressionPathScanEndReasonUnexpectedSymbol;
2503         *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2504         return nullptr;
2505       }
2506 
2507       llvm::StringRef bracket_expr =
2508           temp_expression.slice(1, close_bracket_position);
2509 
2510       // If this was an empty expression it would have been caught by the if
2511       // above.
2512       assert(!bracket_expr.empty());
2513 
2514       if (!bracket_expr.contains('-')) {
2515         // if no separator, this is of the form [N].  Note that this cannot be
2516         // an unbounded range of the form [], because that case was handled
2517         // above with an unconditional return.
2518         unsigned long index = 0;
2519         if (bracket_expr.getAsInteger(0, index)) {
2520           *reason_to_stop =
2521               ValueObject::eExpressionPathScanEndReasonUnexpectedSymbol;
2522           *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2523           return nullptr;
2524         }
2525 
2526         // from here on we do have a valid index
2527         if (root_compiler_type_info.Test(eTypeIsArray)) {
2528           ValueObjectSP child_valobj_sp = root->GetChildAtIndex(index, true);
2529           if (!child_valobj_sp)
2530             child_valobj_sp = root->GetSyntheticArrayMember(index, true);
2531           if (!child_valobj_sp)
2532             if (root->HasSyntheticValue() &&
2533                 root->GetSyntheticValue()->GetNumChildren() > index)
2534               child_valobj_sp =
2535                   root->GetSyntheticValue()->GetChildAtIndex(index, true);
2536           if (child_valobj_sp) {
2537             root = child_valobj_sp;
2538             remainder =
2539                 temp_expression.substr(close_bracket_position + 1); // skip ]
2540             *final_result = ValueObject::eExpressionPathEndResultTypePlain;
2541             continue;
2542           } else {
2543             *reason_to_stop =
2544                 ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2545             *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2546             return nullptr;
2547           }
2548         } else if (root_compiler_type_info.Test(eTypeIsPointer)) {
2549           if (*what_next ==
2550                   ValueObject::
2551                       eExpressionPathAftermathDereference && // if this is a
2552                                                              // ptr-to-scalar, I
2553                                                              // am accessing it
2554                                                              // by index and I
2555                                                              // would have
2556                                                              // deref'ed anyway,
2557                                                              // then do it now
2558                                                              // and use this as
2559                                                              // a bitfield
2560               pointee_compiler_type_info.Test(eTypeIsScalar)) {
2561             Status error;
2562             root = root->Dereference(error);
2563             if (error.Fail() || !root) {
2564               *reason_to_stop =
2565                   ValueObject::eExpressionPathScanEndReasonDereferencingFailed;
2566               *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2567               return nullptr;
2568             } else {
2569               *what_next = eExpressionPathAftermathNothing;
2570               continue;
2571             }
2572           } else {
2573             if (root->GetCompilerType().GetMinimumLanguage() ==
2574                     eLanguageTypeObjC &&
2575                 pointee_compiler_type_info.AllClear(eTypeIsPointer) &&
2576                 root->HasSyntheticValue() &&
2577                 (options.m_synthetic_children_traversal ==
2578                      GetValueForExpressionPathOptions::
2579                          SyntheticChildrenTraversal::ToSynthetic ||
2580                  options.m_synthetic_children_traversal ==
2581                      GetValueForExpressionPathOptions::
2582                          SyntheticChildrenTraversal::Both)) {
2583               root = root->GetSyntheticValue()->GetChildAtIndex(index, true);
2584             } else
2585               root = root->GetSyntheticArrayMember(index, true);
2586             if (!root) {
2587               *reason_to_stop =
2588                   ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2589               *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2590               return nullptr;
2591             } else {
2592               remainder =
2593                   temp_expression.substr(close_bracket_position + 1); // skip ]
2594               *final_result = ValueObject::eExpressionPathEndResultTypePlain;
2595               continue;
2596             }
2597           }
2598         } else if (root_compiler_type_info.Test(eTypeIsScalar)) {
2599           root = root->GetSyntheticBitFieldChild(index, index, true);
2600           if (!root) {
2601             *reason_to_stop =
2602                 ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2603             *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2604             return nullptr;
2605           } else // we do not know how to expand members of bitfields, so we
2606                  // just return and let the caller do any further processing
2607           {
2608             *reason_to_stop = ValueObject::
2609                 eExpressionPathScanEndReasonBitfieldRangeOperatorMet;
2610             *final_result = ValueObject::eExpressionPathEndResultTypeBitfield;
2611             return root;
2612           }
2613         } else if (root_compiler_type_info.Test(eTypeIsVector)) {
2614           root = root->GetChildAtIndex(index, true);
2615           if (!root) {
2616             *reason_to_stop =
2617                 ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2618             *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2619             return ValueObjectSP();
2620           } else {
2621             remainder =
2622                 temp_expression.substr(close_bracket_position + 1); // skip ]
2623             *final_result = ValueObject::eExpressionPathEndResultTypePlain;
2624             continue;
2625           }
2626         } else if (options.m_synthetic_children_traversal ==
2627                        GetValueForExpressionPathOptions::
2628                            SyntheticChildrenTraversal::ToSynthetic ||
2629                    options.m_synthetic_children_traversal ==
2630                        GetValueForExpressionPathOptions::
2631                            SyntheticChildrenTraversal::Both) {
2632           if (root->HasSyntheticValue())
2633             root = root->GetSyntheticValue();
2634           else if (!root->IsSynthetic()) {
2635             *reason_to_stop =
2636                 ValueObject::eExpressionPathScanEndReasonSyntheticValueMissing;
2637             *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2638             return nullptr;
2639           }
2640           // if we are here, then root itself is a synthetic VO.. should be
2641           // good to go
2642 
2643           if (!root) {
2644             *reason_to_stop =
2645                 ValueObject::eExpressionPathScanEndReasonSyntheticValueMissing;
2646             *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2647             return nullptr;
2648           }
2649           root = root->GetChildAtIndex(index, true);
2650           if (!root) {
2651             *reason_to_stop =
2652                 ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2653             *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2654             return nullptr;
2655           } else {
2656             remainder =
2657                 temp_expression.substr(close_bracket_position + 1); // skip ]
2658             *final_result = ValueObject::eExpressionPathEndResultTypePlain;
2659             continue;
2660           }
2661         } else {
2662           *reason_to_stop =
2663               ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2664           *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2665           return nullptr;
2666         }
2667       } else {
2668         // we have a low and a high index
2669         llvm::StringRef sleft, sright;
2670         unsigned long low_index, high_index;
2671         std::tie(sleft, sright) = bracket_expr.split('-');
2672         if (sleft.getAsInteger(0, low_index) ||
2673             sright.getAsInteger(0, high_index)) {
2674           *reason_to_stop =
2675               ValueObject::eExpressionPathScanEndReasonUnexpectedSymbol;
2676           *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2677           return nullptr;
2678         }
2679 
2680         if (low_index > high_index) // swap indices if required
2681           std::swap(low_index, high_index);
2682 
2683         if (root_compiler_type_info.Test(
2684                 eTypeIsScalar)) // expansion only works for scalars
2685         {
2686           root = root->GetSyntheticBitFieldChild(low_index, high_index, true);
2687           if (!root) {
2688             *reason_to_stop =
2689                 ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2690             *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2691             return nullptr;
2692           } else {
2693             *reason_to_stop = ValueObject::
2694                 eExpressionPathScanEndReasonBitfieldRangeOperatorMet;
2695             *final_result = ValueObject::eExpressionPathEndResultTypeBitfield;
2696             return root;
2697           }
2698         } else if (root_compiler_type_info.Test(
2699                        eTypeIsPointer) && // if this is a ptr-to-scalar, I am
2700                                           // accessing it by index and I would
2701                                           // have deref'ed anyway, then do it
2702                                           // now and use this as a bitfield
2703                    *what_next ==
2704                        ValueObject::eExpressionPathAftermathDereference &&
2705                    pointee_compiler_type_info.Test(eTypeIsScalar)) {
2706           Status error;
2707           root = root->Dereference(error);
2708           if (error.Fail() || !root) {
2709             *reason_to_stop =
2710                 ValueObject::eExpressionPathScanEndReasonDereferencingFailed;
2711             *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2712             return nullptr;
2713           } else {
2714             *what_next = ValueObject::eExpressionPathAftermathNothing;
2715             continue;
2716           }
2717         } else {
2718           *reason_to_stop =
2719               ValueObject::eExpressionPathScanEndReasonArrayRangeOperatorMet;
2720           *final_result = ValueObject::eExpressionPathEndResultTypeBoundedRange;
2721           return root;
2722         }
2723       }
2724       break;
2725     }
2726     default: // some non-separator is in the way
2727     {
2728       *reason_to_stop =
2729           ValueObject::eExpressionPathScanEndReasonUnexpectedSymbol;
2730       *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2731       return nullptr;
2732     }
2733     }
2734   }
2735 }
2736 
2737 void ValueObject::LogValueObject(Log *log) {
2738   if (log)
2739     return LogValueObject(log, DumpValueObjectOptions(*this));
2740 }
2741 
2742 void ValueObject::LogValueObject(Log *log,
2743                                  const DumpValueObjectOptions &options) {
2744   if (log) {
2745     StreamString s;
2746     Dump(s, options);
2747     if (s.GetSize())
2748       log->PutCString(s.GetData());
2749   }
2750 }
2751 
2752 void ValueObject::Dump(Stream &s) { Dump(s, DumpValueObjectOptions(*this)); }
2753 
2754 void ValueObject::Dump(Stream &s, const DumpValueObjectOptions &options) {
2755   ValueObjectPrinter printer(this, &s, options);
2756   printer.PrintValueObject();
2757 }
2758 
2759 ValueObjectSP ValueObject::CreateConstantValue(ConstString name) {
2760   ValueObjectSP valobj_sp;
2761 
2762   if (UpdateValueIfNeeded(false) && m_error.Success()) {
2763     ExecutionContext exe_ctx(GetExecutionContextRef());
2764 
2765     DataExtractor data;
2766     data.SetByteOrder(m_data.GetByteOrder());
2767     data.SetAddressByteSize(m_data.GetAddressByteSize());
2768 
2769     if (IsBitfield()) {
2770       Value v(Scalar(GetValueAsUnsigned(UINT64_MAX)));
2771       m_error = v.GetValueAsData(&exe_ctx, data, GetModule().get());
2772     } else
2773       m_error = m_value.GetValueAsData(&exe_ctx, data, GetModule().get());
2774 
2775     valobj_sp = ValueObjectConstResult::Create(
2776         exe_ctx.GetBestExecutionContextScope(), GetCompilerType(), name, data,
2777         GetAddressOf());
2778   }
2779 
2780   if (!valobj_sp) {
2781     ExecutionContext exe_ctx(GetExecutionContextRef());
2782     valobj_sp = ValueObjectConstResult::Create(
2783         exe_ctx.GetBestExecutionContextScope(), m_error);
2784   }
2785   return valobj_sp;
2786 }
2787 
2788 ValueObjectSP ValueObject::GetQualifiedRepresentationIfAvailable(
2789     lldb::DynamicValueType dynValue, bool synthValue) {
2790   ValueObjectSP result_sp(GetSP());
2791 
2792   switch (dynValue) {
2793   case lldb::eDynamicCanRunTarget:
2794   case lldb::eDynamicDontRunTarget: {
2795     if (!result_sp->IsDynamic()) {
2796       if (result_sp->GetDynamicValue(dynValue))
2797         result_sp = result_sp->GetDynamicValue(dynValue);
2798     }
2799   } break;
2800   case lldb::eNoDynamicValues: {
2801     if (result_sp->IsDynamic()) {
2802       if (result_sp->GetStaticValue())
2803         result_sp = result_sp->GetStaticValue();
2804     }
2805   } break;
2806   }
2807 
2808   if (synthValue) {
2809     if (!result_sp->IsSynthetic()) {
2810       if (result_sp->GetSyntheticValue())
2811         result_sp = result_sp->GetSyntheticValue();
2812     }
2813   } else {
2814     if (result_sp->IsSynthetic()) {
2815       if (result_sp->GetNonSyntheticValue())
2816         result_sp = result_sp->GetNonSyntheticValue();
2817     }
2818   }
2819 
2820   return result_sp;
2821 }
2822 
2823 ValueObjectSP ValueObject::Dereference(Status &error) {
2824   if (m_deref_valobj)
2825     return m_deref_valobj->GetSP();
2826 
2827   const bool is_pointer_or_reference_type = IsPointerOrReferenceType();
2828   if (is_pointer_or_reference_type) {
2829     bool omit_empty_base_classes = true;
2830     bool ignore_array_bounds = false;
2831 
2832     std::string child_name_str;
2833     uint32_t child_byte_size = 0;
2834     int32_t child_byte_offset = 0;
2835     uint32_t child_bitfield_bit_size = 0;
2836     uint32_t child_bitfield_bit_offset = 0;
2837     bool child_is_base_class = false;
2838     bool child_is_deref_of_parent = false;
2839     const bool transparent_pointers = false;
2840     CompilerType compiler_type = GetCompilerType();
2841     CompilerType child_compiler_type;
2842     uint64_t language_flags;
2843 
2844     ExecutionContext exe_ctx(GetExecutionContextRef());
2845 
2846     child_compiler_type = compiler_type.GetChildCompilerTypeAtIndex(
2847         &exe_ctx, 0, transparent_pointers, omit_empty_base_classes,
2848         ignore_array_bounds, child_name_str, child_byte_size, child_byte_offset,
2849         child_bitfield_bit_size, child_bitfield_bit_offset, child_is_base_class,
2850         child_is_deref_of_parent, this, language_flags);
2851     if (child_compiler_type && child_byte_size) {
2852       ConstString child_name;
2853       if (!child_name_str.empty())
2854         child_name.SetCString(child_name_str.c_str());
2855 
2856       m_deref_valobj = new ValueObjectChild(
2857           *this, child_compiler_type, child_name, child_byte_size,
2858           child_byte_offset, child_bitfield_bit_size, child_bitfield_bit_offset,
2859           child_is_base_class, child_is_deref_of_parent, eAddressTypeInvalid,
2860           language_flags);
2861     }
2862   } else if (HasSyntheticValue()) {
2863     m_deref_valobj =
2864         GetSyntheticValue()
2865             ->GetChildMemberWithName(ConstString("$$dereference$$"), true)
2866             .get();
2867   }
2868 
2869   if (m_deref_valobj) {
2870     error.Clear();
2871     return m_deref_valobj->GetSP();
2872   } else {
2873     StreamString strm;
2874     GetExpressionPath(strm, true);
2875 
2876     if (is_pointer_or_reference_type)
2877       error.SetErrorStringWithFormat("dereference failed: (%s) %s",
2878                                      GetTypeName().AsCString("<invalid type>"),
2879                                      strm.GetData());
2880     else
2881       error.SetErrorStringWithFormat("not a pointer or reference type: (%s) %s",
2882                                      GetTypeName().AsCString("<invalid type>"),
2883                                      strm.GetData());
2884     return ValueObjectSP();
2885   }
2886 }
2887 
2888 ValueObjectSP ValueObject::AddressOf(Status &error) {
2889   if (m_addr_of_valobj_sp)
2890     return m_addr_of_valobj_sp;
2891 
2892   AddressType address_type = eAddressTypeInvalid;
2893   const bool scalar_is_load_address = false;
2894   addr_t addr = GetAddressOf(scalar_is_load_address, &address_type);
2895   error.Clear();
2896   if (addr != LLDB_INVALID_ADDRESS && address_type != eAddressTypeHost) {
2897     switch (address_type) {
2898     case eAddressTypeInvalid: {
2899       StreamString expr_path_strm;
2900       GetExpressionPath(expr_path_strm, true);
2901       error.SetErrorStringWithFormat("'%s' is not in memory",
2902                                      expr_path_strm.GetData());
2903     } break;
2904 
2905     case eAddressTypeFile:
2906     case eAddressTypeLoad: {
2907       CompilerType compiler_type = GetCompilerType();
2908       if (compiler_type) {
2909         std::string name(1, '&');
2910         name.append(m_name.AsCString(""));
2911         ExecutionContext exe_ctx(GetExecutionContextRef());
2912         m_addr_of_valobj_sp = ValueObjectConstResult::Create(
2913             exe_ctx.GetBestExecutionContextScope(),
2914             compiler_type.GetPointerType(), ConstString(name.c_str()), addr,
2915             eAddressTypeInvalid, m_data.GetAddressByteSize());
2916       }
2917     } break;
2918     default:
2919       break;
2920     }
2921   } else {
2922     StreamString expr_path_strm;
2923     GetExpressionPath(expr_path_strm, true);
2924     error.SetErrorStringWithFormat("'%s' doesn't have a valid address",
2925                                    expr_path_strm.GetData());
2926   }
2927 
2928   return m_addr_of_valobj_sp;
2929 }
2930 
2931 ValueObjectSP ValueObject::Cast(const CompilerType &compiler_type) {
2932   return ValueObjectCast::Create(*this, GetName(), compiler_type);
2933 }
2934 
2935 lldb::ValueObjectSP ValueObject::Clone(ConstString new_name) {
2936   return ValueObjectCast::Create(*this, new_name, GetCompilerType());
2937 }
2938 
2939 ValueObjectSP ValueObject::CastPointerType(const char *name,
2940                                            CompilerType &compiler_type) {
2941   ValueObjectSP valobj_sp;
2942   AddressType address_type;
2943   addr_t ptr_value = GetPointerValue(&address_type);
2944 
2945   if (ptr_value != LLDB_INVALID_ADDRESS) {
2946     Address ptr_addr(ptr_value);
2947     ExecutionContext exe_ctx(GetExecutionContextRef());
2948     valobj_sp = ValueObjectMemory::Create(
2949         exe_ctx.GetBestExecutionContextScope(), name, ptr_addr, compiler_type);
2950   }
2951   return valobj_sp;
2952 }
2953 
2954 ValueObjectSP ValueObject::CastPointerType(const char *name, TypeSP &type_sp) {
2955   ValueObjectSP valobj_sp;
2956   AddressType address_type;
2957   addr_t ptr_value = GetPointerValue(&address_type);
2958 
2959   if (ptr_value != LLDB_INVALID_ADDRESS) {
2960     Address ptr_addr(ptr_value);
2961     ExecutionContext exe_ctx(GetExecutionContextRef());
2962     valobj_sp = ValueObjectMemory::Create(
2963         exe_ctx.GetBestExecutionContextScope(), name, ptr_addr, type_sp);
2964   }
2965   return valobj_sp;
2966 }
2967 
2968 ValueObject::EvaluationPoint::EvaluationPoint()
2969     : m_mod_id(), m_exe_ctx_ref(), m_needs_update(true) {}
2970 
2971 ValueObject::EvaluationPoint::EvaluationPoint(ExecutionContextScope *exe_scope,
2972                                               bool use_selected)
2973     : m_mod_id(), m_exe_ctx_ref(), m_needs_update(true) {
2974   ExecutionContext exe_ctx(exe_scope);
2975   TargetSP target_sp(exe_ctx.GetTargetSP());
2976   if (target_sp) {
2977     m_exe_ctx_ref.SetTargetSP(target_sp);
2978     ProcessSP process_sp(exe_ctx.GetProcessSP());
2979     if (!process_sp)
2980       process_sp = target_sp->GetProcessSP();
2981 
2982     if (process_sp) {
2983       m_mod_id = process_sp->GetModID();
2984       m_exe_ctx_ref.SetProcessSP(process_sp);
2985 
2986       ThreadSP thread_sp(exe_ctx.GetThreadSP());
2987 
2988       if (!thread_sp) {
2989         if (use_selected)
2990           thread_sp = process_sp->GetThreadList().GetSelectedThread();
2991       }
2992 
2993       if (thread_sp) {
2994         m_exe_ctx_ref.SetThreadSP(thread_sp);
2995 
2996         StackFrameSP frame_sp(exe_ctx.GetFrameSP());
2997         if (!frame_sp) {
2998           if (use_selected)
2999             frame_sp = thread_sp->GetSelectedFrame();
3000         }
3001         if (frame_sp)
3002           m_exe_ctx_ref.SetFrameSP(frame_sp);
3003       }
3004     }
3005   }
3006 }
3007 
3008 ValueObject::EvaluationPoint::EvaluationPoint(
3009     const ValueObject::EvaluationPoint &rhs)
3010     : m_mod_id(), m_exe_ctx_ref(rhs.m_exe_ctx_ref), m_needs_update(true) {}
3011 
3012 ValueObject::EvaluationPoint::~EvaluationPoint() {}
3013 
3014 // This function checks the EvaluationPoint against the current process state.
3015 // If the current state matches the evaluation point, or the evaluation point
3016 // is already invalid, then we return false, meaning "no change".  If the
3017 // current state is different, we update our state, and return true meaning
3018 // "yes, change".  If we did see a change, we also set m_needs_update to true,
3019 // so future calls to NeedsUpdate will return true. exe_scope will be set to
3020 // the current execution context scope.
3021 
3022 bool ValueObject::EvaluationPoint::SyncWithProcessState(
3023     bool accept_invalid_exe_ctx) {
3024   // Start with the target, if it is NULL, then we're obviously not going to
3025   // get any further:
3026   const bool thread_and_frame_only_if_stopped = true;
3027   ExecutionContext exe_ctx(
3028       m_exe_ctx_ref.Lock(thread_and_frame_only_if_stopped));
3029 
3030   if (exe_ctx.GetTargetPtr() == nullptr)
3031     return false;
3032 
3033   // If we don't have a process nothing can change.
3034   Process *process = exe_ctx.GetProcessPtr();
3035   if (process == nullptr)
3036     return false;
3037 
3038   // If our stop id is the current stop ID, nothing has changed:
3039   ProcessModID current_mod_id = process->GetModID();
3040 
3041   // If the current stop id is 0, either we haven't run yet, or the process
3042   // state has been cleared. In either case, we aren't going to be able to sync
3043   // with the process state.
3044   if (current_mod_id.GetStopID() == 0)
3045     return false;
3046 
3047   bool changed = false;
3048   const bool was_valid = m_mod_id.IsValid();
3049   if (was_valid) {
3050     if (m_mod_id == current_mod_id) {
3051       // Everything is already up to date in this object, no need to update the
3052       // execution context scope.
3053       changed = false;
3054     } else {
3055       m_mod_id = current_mod_id;
3056       m_needs_update = true;
3057       changed = true;
3058     }
3059   }
3060 
3061   // Now re-look up the thread and frame in case the underlying objects have
3062   // gone away & been recreated. That way we'll be sure to return a valid
3063   // exe_scope. If we used to have a thread or a frame but can't find it
3064   // anymore, then mark ourselves as invalid.
3065 
3066   if (!accept_invalid_exe_ctx) {
3067     if (m_exe_ctx_ref.HasThreadRef()) {
3068       ThreadSP thread_sp(m_exe_ctx_ref.GetThreadSP());
3069       if (thread_sp) {
3070         if (m_exe_ctx_ref.HasFrameRef()) {
3071           StackFrameSP frame_sp(m_exe_ctx_ref.GetFrameSP());
3072           if (!frame_sp) {
3073             // We used to have a frame, but now it is gone
3074             SetInvalid();
3075             changed = was_valid;
3076           }
3077         }
3078       } else {
3079         // We used to have a thread, but now it is gone
3080         SetInvalid();
3081         changed = was_valid;
3082       }
3083     }
3084   }
3085 
3086   return changed;
3087 }
3088 
3089 void ValueObject::EvaluationPoint::SetUpdated() {
3090   ProcessSP process_sp(m_exe_ctx_ref.GetProcessSP());
3091   if (process_sp)
3092     m_mod_id = process_sp->GetModID();
3093   m_needs_update = false;
3094 }
3095 
3096 void ValueObject::ClearUserVisibleData(uint32_t clear_mask) {
3097   if ((clear_mask & eClearUserVisibleDataItemsValue) ==
3098       eClearUserVisibleDataItemsValue)
3099     m_value_str.clear();
3100 
3101   if ((clear_mask & eClearUserVisibleDataItemsLocation) ==
3102       eClearUserVisibleDataItemsLocation)
3103     m_location_str.clear();
3104 
3105   if ((clear_mask & eClearUserVisibleDataItemsSummary) ==
3106       eClearUserVisibleDataItemsSummary)
3107     m_summary_str.clear();
3108 
3109   if ((clear_mask & eClearUserVisibleDataItemsDescription) ==
3110       eClearUserVisibleDataItemsDescription)
3111     m_object_desc_str.clear();
3112 
3113   if ((clear_mask & eClearUserVisibleDataItemsSyntheticChildren) ==
3114       eClearUserVisibleDataItemsSyntheticChildren) {
3115     if (m_synthetic_value)
3116       m_synthetic_value = nullptr;
3117   }
3118 
3119   if ((clear_mask & eClearUserVisibleDataItemsValidator) ==
3120       eClearUserVisibleDataItemsValidator)
3121     m_validation_result.reset();
3122 }
3123 
3124 SymbolContextScope *ValueObject::GetSymbolContextScope() {
3125   if (m_parent) {
3126     if (!m_parent->IsPointerOrReferenceType())
3127       return m_parent->GetSymbolContextScope();
3128   }
3129   return nullptr;
3130 }
3131 
3132 lldb::ValueObjectSP
3133 ValueObject::CreateValueObjectFromExpression(llvm::StringRef name,
3134                                              llvm::StringRef expression,
3135                                              const ExecutionContext &exe_ctx) {
3136   return CreateValueObjectFromExpression(name, expression, exe_ctx,
3137                                          EvaluateExpressionOptions());
3138 }
3139 
3140 lldb::ValueObjectSP ValueObject::CreateValueObjectFromExpression(
3141     llvm::StringRef name, llvm::StringRef expression,
3142     const ExecutionContext &exe_ctx, const EvaluateExpressionOptions &options) {
3143   lldb::ValueObjectSP retval_sp;
3144   lldb::TargetSP target_sp(exe_ctx.GetTargetSP());
3145   if (!target_sp)
3146     return retval_sp;
3147   if (expression.empty())
3148     return retval_sp;
3149   target_sp->EvaluateExpression(expression, exe_ctx.GetFrameSP().get(),
3150                                 retval_sp, options);
3151   if (retval_sp && !name.empty())
3152     retval_sp->SetName(ConstString(name));
3153   return retval_sp;
3154 }
3155 
3156 lldb::ValueObjectSP ValueObject::CreateValueObjectFromAddress(
3157     llvm::StringRef name, uint64_t address, const ExecutionContext &exe_ctx,
3158     CompilerType type) {
3159   if (type) {
3160     CompilerType pointer_type(type.GetPointerType());
3161     if (pointer_type) {
3162       lldb::DataBufferSP buffer(
3163           new lldb_private::DataBufferHeap(&address, sizeof(lldb::addr_t)));
3164       lldb::ValueObjectSP ptr_result_valobj_sp(ValueObjectConstResult::Create(
3165           exe_ctx.GetBestExecutionContextScope(), pointer_type,
3166           ConstString(name), buffer, exe_ctx.GetByteOrder(),
3167           exe_ctx.GetAddressByteSize()));
3168       if (ptr_result_valobj_sp) {
3169         ptr_result_valobj_sp->GetValue().SetValueType(
3170             Value::eValueTypeLoadAddress);
3171         Status err;
3172         ptr_result_valobj_sp = ptr_result_valobj_sp->Dereference(err);
3173         if (ptr_result_valobj_sp && !name.empty())
3174           ptr_result_valobj_sp->SetName(ConstString(name));
3175       }
3176       return ptr_result_valobj_sp;
3177     }
3178   }
3179   return lldb::ValueObjectSP();
3180 }
3181 
3182 lldb::ValueObjectSP ValueObject::CreateValueObjectFromData(
3183     llvm::StringRef name, const DataExtractor &data,
3184     const ExecutionContext &exe_ctx, CompilerType type) {
3185   lldb::ValueObjectSP new_value_sp;
3186   new_value_sp = ValueObjectConstResult::Create(
3187       exe_ctx.GetBestExecutionContextScope(), type, ConstString(name), data,
3188       LLDB_INVALID_ADDRESS);
3189   new_value_sp->SetAddressTypeOfChildren(eAddressTypeLoad);
3190   if (new_value_sp && !name.empty())
3191     new_value_sp->SetName(ConstString(name));
3192   return new_value_sp;
3193 }
3194 
3195 ModuleSP ValueObject::GetModule() {
3196   ValueObject *root(GetRoot());
3197   if (root != this)
3198     return root->GetModule();
3199   return lldb::ModuleSP();
3200 }
3201 
3202 ValueObject *ValueObject::GetRoot() {
3203   if (m_root)
3204     return m_root;
3205   return (m_root = FollowParentChain([](ValueObject *vo) -> bool {
3206             return (vo->m_parent != nullptr);
3207           }));
3208 }
3209 
3210 ValueObject *
3211 ValueObject::FollowParentChain(std::function<bool(ValueObject *)> f) {
3212   ValueObject *vo = this;
3213   while (vo) {
3214     if (!f(vo))
3215       break;
3216     vo = vo->m_parent;
3217   }
3218   return vo;
3219 }
3220 
3221 AddressType ValueObject::GetAddressTypeOfChildren() {
3222   if (m_address_type_of_ptr_or_ref_children == eAddressTypeInvalid) {
3223     ValueObject *root(GetRoot());
3224     if (root != this)
3225       return root->GetAddressTypeOfChildren();
3226   }
3227   return m_address_type_of_ptr_or_ref_children;
3228 }
3229 
3230 lldb::DynamicValueType ValueObject::GetDynamicValueType() {
3231   ValueObject *with_dv_info = this;
3232   while (with_dv_info) {
3233     if (with_dv_info->HasDynamicValueTypeInfo())
3234       return with_dv_info->GetDynamicValueTypeImpl();
3235     with_dv_info = with_dv_info->m_parent;
3236   }
3237   return lldb::eNoDynamicValues;
3238 }
3239 
3240 lldb::Format ValueObject::GetFormat() const {
3241   const ValueObject *with_fmt_info = this;
3242   while (with_fmt_info) {
3243     if (with_fmt_info->m_format != lldb::eFormatDefault)
3244       return with_fmt_info->m_format;
3245     with_fmt_info = with_fmt_info->m_parent;
3246   }
3247   return m_format;
3248 }
3249 
3250 lldb::LanguageType ValueObject::GetPreferredDisplayLanguage() {
3251   lldb::LanguageType type = m_preferred_display_language;
3252   if (m_preferred_display_language == lldb::eLanguageTypeUnknown) {
3253     if (GetRoot()) {
3254       if (GetRoot() == this) {
3255         if (StackFrameSP frame_sp = GetFrameSP()) {
3256           const SymbolContext &sc(
3257               frame_sp->GetSymbolContext(eSymbolContextCompUnit));
3258           if (CompileUnit *cu = sc.comp_unit)
3259             type = cu->GetLanguage();
3260         }
3261       } else {
3262         type = GetRoot()->GetPreferredDisplayLanguage();
3263       }
3264     }
3265   }
3266   return (m_preferred_display_language = type); // only compute it once
3267 }
3268 
3269 void ValueObject::SetPreferredDisplayLanguage(lldb::LanguageType lt) {
3270   m_preferred_display_language = lt;
3271 }
3272 
3273 void ValueObject::SetPreferredDisplayLanguageIfNeeded(lldb::LanguageType lt) {
3274   if (m_preferred_display_language == lldb::eLanguageTypeUnknown)
3275     SetPreferredDisplayLanguage(lt);
3276 }
3277 
3278 bool ValueObject::CanProvideValue() {
3279   // we need to support invalid types as providers of values because some bare-
3280   // board debugging scenarios have no notion of types, but still manage to
3281   // have raw numeric values for things like registers. sigh.
3282   const CompilerType &type(GetCompilerType());
3283   return (!type.IsValid()) || (0 != (type.GetTypeInfo() & eTypeHasValue));
3284 }
3285 
3286 bool ValueObject::IsChecksumEmpty() { return m_value_checksum.empty(); }
3287 
3288 ValueObjectSP ValueObject::Persist() {
3289   if (!UpdateValueIfNeeded())
3290     return nullptr;
3291 
3292   TargetSP target_sp(GetTargetSP());
3293   if (!target_sp)
3294     return nullptr;
3295 
3296   PersistentExpressionState *persistent_state =
3297       target_sp->GetPersistentExpressionStateForLanguage(
3298           GetPreferredDisplayLanguage());
3299 
3300   if (!persistent_state)
3301     return nullptr;
3302 
3303   auto prefix = persistent_state->GetPersistentVariablePrefix();
3304   ConstString name =
3305       persistent_state->GetNextPersistentVariableName(*target_sp, prefix);
3306 
3307   ValueObjectSP const_result_sp =
3308       ValueObjectConstResult::Create(target_sp.get(), GetValue(), name);
3309 
3310   ExpressionVariableSP clang_var_sp =
3311       persistent_state->CreatePersistentVariable(const_result_sp);
3312   clang_var_sp->m_live_sp = clang_var_sp->m_frozen_sp;
3313   clang_var_sp->m_flags |= ExpressionVariable::EVIsProgramReference;
3314 
3315   return clang_var_sp->GetValueObject();
3316 }
3317 
3318 bool ValueObject::IsSyntheticChildrenGenerated() {
3319   return m_is_synthetic_children_generated;
3320 }
3321 
3322 void ValueObject::SetSyntheticChildrenGenerated(bool b) {
3323   m_is_synthetic_children_generated = b;
3324 }
3325 
3326 uint64_t ValueObject::GetLanguageFlags() { return m_language_flags; }
3327 
3328 void ValueObject::SetLanguageFlags(uint64_t flags) { m_language_flags = flags; }
3329 
3330 ValueObjectManager::ValueObjectManager(lldb::ValueObjectSP in_valobj_sp,
3331                                        lldb::DynamicValueType use_dynamic,
3332                                        bool use_synthetic) : m_root_valobj_sp(),
3333     m_user_valobj_sp(), m_use_dynamic(use_dynamic), m_stop_id(UINT32_MAX),
3334     m_use_synthetic(use_synthetic) {
3335   if (!in_valobj_sp)
3336     return;
3337   // If the user passes in a value object that is dynamic or synthetic, then
3338   // water it down to the static type.
3339   m_root_valobj_sp = in_valobj_sp->GetQualifiedRepresentationIfAvailable(lldb::eNoDynamicValues, false);
3340 }
3341 
3342 bool ValueObjectManager::IsValid() const {
3343   if (!m_root_valobj_sp)
3344     return false;
3345   lldb::TargetSP target_sp = GetTargetSP();
3346   if (target_sp)
3347     return target_sp->IsValid();
3348   return false;
3349 }
3350 
3351 lldb::ValueObjectSP ValueObjectManager::GetSP() {
3352   lldb::ProcessSP process_sp = GetProcessSP();
3353   if (!process_sp)
3354     return lldb::ValueObjectSP();
3355 
3356   const uint32_t current_stop_id = process_sp->GetLastNaturalStopID();
3357   if (current_stop_id == m_stop_id)
3358     return m_user_valobj_sp;
3359 
3360   m_stop_id = current_stop_id;
3361 
3362   if (!m_root_valobj_sp) {
3363     m_user_valobj_sp.reset();
3364     return m_root_valobj_sp;
3365   }
3366 
3367   m_user_valobj_sp = m_root_valobj_sp;
3368 
3369   if (m_use_dynamic != lldb::eNoDynamicValues) {
3370     lldb::ValueObjectSP dynamic_sp = m_user_valobj_sp->GetDynamicValue(m_use_dynamic);
3371     if (dynamic_sp)
3372       m_user_valobj_sp = dynamic_sp;
3373   }
3374 
3375   if (m_use_synthetic) {
3376     lldb::ValueObjectSP synthetic_sp = m_user_valobj_sp->GetSyntheticValue(m_use_synthetic);
3377     if (synthetic_sp)
3378       m_user_valobj_sp = synthetic_sp;
3379   }
3380 
3381   return m_user_valobj_sp;
3382 }
3383 
3384 void ValueObjectManager::SetUseDynamic(lldb::DynamicValueType use_dynamic) {
3385   if (use_dynamic != m_use_dynamic) {
3386     m_use_dynamic = use_dynamic;
3387     m_user_valobj_sp.reset();
3388     m_stop_id = UINT32_MAX;
3389   }
3390 }
3391 
3392 void ValueObjectManager::SetUseSynthetic(bool use_synthetic) {
3393   if (m_use_synthetic != use_synthetic) {
3394     m_use_synthetic = use_synthetic;
3395     m_user_valobj_sp.reset();
3396     m_stop_id = UINT32_MAX;
3397   }
3398 }
3399 
3400 lldb::TargetSP ValueObjectManager::GetTargetSP() const {
3401   if (!m_root_valobj_sp)
3402     return m_root_valobj_sp->GetTargetSP();
3403   return lldb::TargetSP();
3404 }
3405 
3406 lldb::ProcessSP ValueObjectManager::GetProcessSP() const {
3407   if (m_root_valobj_sp)
3408     return m_root_valobj_sp->GetProcessSP();
3409   return lldb::ProcessSP();
3410 }
3411 
3412 lldb::ThreadSP ValueObjectManager::GetThreadSP() const {
3413   if (m_root_valobj_sp)
3414     return m_root_valobj_sp->GetThreadSP();
3415   return lldb::ThreadSP();
3416 }
3417 
3418 lldb::StackFrameSP ValueObjectManager::GetFrameSP() const {
3419   if (m_root_valobj_sp)
3420     return m_root_valobj_sp->GetFrameSP();
3421   return lldb::StackFrameSP();
3422 }
3423