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