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