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