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