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