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