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