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