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