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