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