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