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