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