1 //===-- ValueObject.cpp -----------------------------------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 #include "lldb/Core/ValueObject.h"
11 #include "lldb/Core/Address.h"
12 #include "lldb/Core/Module.h"
13 #include "lldb/Core/ValueObjectCast.h"
14 #include "lldb/Core/ValueObjectChild.h"
15 #include "lldb/Core/ValueObjectConstResult.h"
16 #include "lldb/Core/ValueObjectDynamicValue.h"
17 #include "lldb/Core/ValueObjectMemory.h"
18 #include "lldb/Core/ValueObjectSyntheticFilter.h"
19 #include "lldb/DataFormatters/DataVisualization.h"
20 #include "lldb/DataFormatters/DumpValueObjectOptions.h"
21 #include "lldb/DataFormatters/FormatManager.h"
22 #include "lldb/DataFormatters/StringPrinter.h"
23 #include "lldb/DataFormatters/TypeFormat.h"
24 #include "lldb/DataFormatters/TypeSummary.h"
25 #include "lldb/DataFormatters/TypeValidator.h"
26 #include "lldb/DataFormatters/ValueObjectPrinter.h"
27 #include "lldb/Expression/ExpressionVariable.h"
28 #include "lldb/Symbol/ClangASTContext.h"
29 #include "lldb/Symbol/CompileUnit.h"
30 #include "lldb/Symbol/CompilerType.h"
31 #include "lldb/Symbol/Declaration.h"
32 #include "lldb/Symbol/SymbolContext.h"
33 #include "lldb/Symbol/Type.h"
34 #include "lldb/Symbol/Variable.h"
35 #include "lldb/Target/ExecutionContext.h"
36 #include "lldb/Target/Language.h"
37 #include "lldb/Target/LanguageRuntime.h"
38 #include "lldb/Target/Process.h"
39 #include "lldb/Target/StackFrame.h"
40 #include "lldb/Target/Target.h"
41 #include "lldb/Target/Thread.h"
42 #include "lldb/Target/ThreadList.h"
43 #include "lldb/Utility/DataBuffer.h"
44 #include "lldb/Utility/DataBufferHeap.h"
45 #include "lldb/Utility/Flags.h"
46 #include "lldb/Utility/Log.h"
47 #include "lldb/Utility/Logging.h"
48 #include "lldb/Utility/Scalar.h"
49 #include "lldb/Utility/SharingPtr.h"
50 #include "lldb/Utility/Stream.h"
51 #include "lldb/Utility/StreamString.h"
52 #include "lldb/lldb-private-types.h"
54 #include "llvm/Support/Compiler.h"
67 namespace lldb_private {
68 class ExecutionContextScope;
70 namespace lldb_private {
71 class SymbolContextScope;
75 using namespace lldb_private;
76 using namespace lldb_utility;
78 static user_id_t g_value_obj_uid = 0;
80 // ValueObject constructor
81 ValueObject::ValueObject(ValueObject &parent)
82 : UserID(++g_value_obj_uid), // Unique identifier for every value object
83 m_parent(&parent), m_root(nullptr),
84 m_update_point(parent.GetUpdatePoint()), m_name(), m_data(), m_value(),
85 m_error(), m_value_str(), m_old_value_str(), m_location_str(),
86 m_summary_str(), m_object_desc_str(), m_validation_result(),
87 m_manager(parent.GetManager()), m_children(), m_synthetic_children(),
88 m_dynamic_value(nullptr), m_synthetic_value(nullptr),
89 m_deref_valobj(nullptr), m_format(eFormatDefault),
90 m_last_format(eFormatDefault), m_last_format_mgr_revision(0),
91 m_type_summary_sp(), m_type_format_sp(), m_synthetic_children_sp(),
92 m_type_validator_sp(), m_user_id_of_forced_summary(),
93 m_address_type_of_ptr_or_ref_children(eAddressTypeInvalid),
95 m_preferred_display_language(lldb::eLanguageTypeUnknown),
96 m_language_flags(0), m_value_is_valid(false), m_value_did_change(false),
97 m_children_count_valid(false), m_old_value_valid(false),
98 m_is_deref_of_parent(false), m_is_array_item_for_pointer(false),
99 m_is_bitfield_for_scalar(false), m_is_child_at_offset(false),
100 m_is_getting_summary(false),
101 m_did_calculate_complete_objc_class_type(false),
102 m_is_synthetic_children_generated(
103 parent.m_is_synthetic_children_generated) {
104 m_manager->ManageObject(this);
107 // ValueObject constructor
108 ValueObject::ValueObject(ExecutionContextScope *exe_scope,
109 AddressType child_ptr_or_ref_addr_type)
110 : UserID(++g_value_obj_uid), // Unique identifier for every value object
111 m_parent(nullptr), m_root(nullptr), m_update_point(exe_scope), m_name(),
112 m_data(), m_value(), m_error(), m_value_str(), m_old_value_str(),
113 m_location_str(), m_summary_str(), m_object_desc_str(),
114 m_validation_result(), m_manager(), m_children(), m_synthetic_children(),
115 m_dynamic_value(nullptr), m_synthetic_value(nullptr),
116 m_deref_valobj(nullptr), m_format(eFormatDefault),
117 m_last_format(eFormatDefault), m_last_format_mgr_revision(0),
118 m_type_summary_sp(), m_type_format_sp(), m_synthetic_children_sp(),
119 m_type_validator_sp(), m_user_id_of_forced_summary(),
120 m_address_type_of_ptr_or_ref_children(child_ptr_or_ref_addr_type),
122 m_preferred_display_language(lldb::eLanguageTypeUnknown),
123 m_language_flags(0), m_value_is_valid(false), m_value_did_change(false),
124 m_children_count_valid(false), m_old_value_valid(false),
125 m_is_deref_of_parent(false), m_is_array_item_for_pointer(false),
126 m_is_bitfield_for_scalar(false), m_is_child_at_offset(false),
127 m_is_getting_summary(false),
128 m_did_calculate_complete_objc_class_type(false),
129 m_is_synthetic_children_generated(false) {
130 m_manager = new ValueObjectManager();
131 m_manager->ManageObject(this);
135 ValueObject::~ValueObject() {}
137 bool ValueObject::UpdateValueIfNeeded(bool update_format) {
139 bool did_change_formats = false;
142 did_change_formats = UpdateFormatsIfNeeded();
144 // If this is a constant value, then our success is predicated on whether we
145 // have an error or not
146 if (GetIsConstant()) {
147 // if you are constant, things might still have changed behind your back
148 // (e.g. you are a frozen object and things have changed deeper than you
149 // cared to freeze-dry yourself) in this case, your value has not changed,
150 // but "computed" entries might have, so you might now have a different
151 // summary, or a different object description. clear these so we will
153 if (update_format && !did_change_formats)
154 ClearUserVisibleData(eClearUserVisibleDataItemsSummary |
155 eClearUserVisibleDataItemsDescription);
156 return m_error.Success();
159 bool first_update = IsChecksumEmpty();
161 if (NeedsUpdating()) {
162 m_update_point.SetUpdated();
164 // Save the old value using swap to avoid a string copy which also will
165 // clear our m_value_str
166 if (m_value_str.empty()) {
167 m_old_value_valid = false;
169 m_old_value_valid = true;
170 m_old_value_str.swap(m_value_str);
171 ClearUserVisibleData(eClearUserVisibleDataItemsValue);
174 ClearUserVisibleData();
177 const bool value_was_valid = GetValueIsValid();
178 SetValueDidChange(false);
182 // Call the pure virtual function to update the value
184 bool need_compare_checksums = false;
185 llvm::SmallVector<uint8_t, 16> old_checksum;
187 if (!first_update && CanProvideValue()) {
188 need_compare_checksums = true;
189 old_checksum.resize(m_value_checksum.size());
190 std::copy(m_value_checksum.begin(), m_value_checksum.end(),
191 old_checksum.begin());
194 bool success = UpdateValue();
196 SetValueIsValid(success);
199 const uint64_t max_checksum_size = 128;
200 m_data.Checksum(m_value_checksum, max_checksum_size);
202 need_compare_checksums = false;
203 m_value_checksum.clear();
206 assert(!need_compare_checksums ||
207 (!old_checksum.empty() && !m_value_checksum.empty()));
210 SetValueDidChange(false);
211 else if (!m_value_did_change && !success) {
212 // The value wasn't gotten successfully, so we mark this as changed if
213 // the value used to be valid and now isn't
214 SetValueDidChange(value_was_valid);
215 } else if (need_compare_checksums) {
216 SetValueDidChange(memcmp(&old_checksum[0], &m_value_checksum[0],
217 m_value_checksum.size()));
221 m_error.SetErrorString("out of scope");
224 return m_error.Success();
227 bool ValueObject::UpdateFormatsIfNeeded() {
228 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_DATAFORMATTERS));
230 log->Printf("[%s %p] checking for FormatManager revisions. ValueObject "
231 "rev: %d - Global rev: %d",
232 GetName().GetCString(), static_cast<void *>(this),
233 m_last_format_mgr_revision,
234 DataVisualization::GetCurrentRevision());
236 bool any_change = false;
238 if ((m_last_format_mgr_revision != DataVisualization::GetCurrentRevision())) {
239 m_last_format_mgr_revision = DataVisualization::GetCurrentRevision();
242 SetValueFormat(DataVisualization::GetFormat(*this, eNoDynamicValues));
244 DataVisualization::GetSummaryFormat(*this, GetDynamicValueType()));
245 #ifndef LLDB_DISABLE_PYTHON
246 SetSyntheticChildren(
247 DataVisualization::GetSyntheticChildren(*this, GetDynamicValueType()));
249 SetValidator(DataVisualization::GetValidator(*this, GetDynamicValueType()));
255 void ValueObject::SetNeedsUpdate() {
256 m_update_point.SetNeedsUpdate();
257 // We have to clear the value string here so ConstResult children will notice
258 // if their values are changed by hand (i.e. with SetValueAsCString).
259 ClearUserVisibleData(eClearUserVisibleDataItemsValue);
262 void ValueObject::ClearDynamicTypeInformation() {
263 m_children_count_valid = false;
264 m_did_calculate_complete_objc_class_type = false;
265 m_last_format_mgr_revision = 0;
266 m_override_type = CompilerType();
267 SetValueFormat(lldb::TypeFormatImplSP());
268 SetSummaryFormat(lldb::TypeSummaryImplSP());
269 SetSyntheticChildren(lldb::SyntheticChildrenSP());
272 CompilerType ValueObject::MaybeCalculateCompleteType() {
273 CompilerType compiler_type(GetCompilerTypeImpl());
275 if (m_did_calculate_complete_objc_class_type) {
276 if (m_override_type.IsValid())
277 return m_override_type;
279 return compiler_type;
282 m_did_calculate_complete_objc_class_type = true;
284 ProcessSP process_sp(
285 GetUpdatePoint().GetExecutionContextRef().GetProcessSP());
288 return compiler_type;
291 process_sp->GetLanguageRuntime(GetObjectRuntimeLanguage())) {
292 if (llvm::Optional<CompilerType> complete_type =
293 runtime->GetRuntimeType(compiler_type)) {
294 m_override_type = complete_type.getValue();
295 if (m_override_type.IsValid())
296 return m_override_type;
299 return compiler_type;
302 CompilerType ValueObject::GetCompilerType() {
303 return MaybeCalculateCompleteType();
306 TypeImpl ValueObject::GetTypeImpl() { return TypeImpl(GetCompilerType()); }
308 DataExtractor &ValueObject::GetDataExtractor() {
309 UpdateValueIfNeeded(false);
313 const Status &ValueObject::GetError() {
314 UpdateValueIfNeeded(false);
318 ConstString ValueObject::GetName() const { return m_name; }
320 const char *ValueObject::GetLocationAsCString() {
321 return GetLocationAsCStringImpl(m_value, m_data);
324 const char *ValueObject::GetLocationAsCStringImpl(const Value &value,
325 const DataExtractor &data) {
326 if (UpdateValueIfNeeded(false)) {
327 if (m_location_str.empty()) {
330 Value::ValueType value_type = value.GetValueType();
332 switch (value_type) {
333 case Value::eValueTypeScalar:
334 case Value::eValueTypeVector:
335 if (value.GetContextType() == Value::eContextTypeRegisterInfo) {
336 RegisterInfo *reg_info = value.GetRegisterInfo();
339 m_location_str = reg_info->name;
340 else if (reg_info->alt_name)
341 m_location_str = reg_info->alt_name;
342 if (m_location_str.empty())
343 m_location_str = (reg_info->encoding == lldb::eEncodingVector)
348 if (m_location_str.empty())
350 (value_type == Value::eValueTypeVector) ? "vector" : "scalar";
353 case Value::eValueTypeLoadAddress:
354 case Value::eValueTypeFileAddress:
355 case Value::eValueTypeHostAddress: {
356 uint32_t addr_nibble_size = data.GetAddressByteSize() * 2;
357 sstr.Printf("0x%*.*llx", addr_nibble_size, addr_nibble_size,
358 value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS));
359 m_location_str = sstr.GetString();
364 return m_location_str.c_str();
367 Value &ValueObject::GetValue() { return m_value; }
369 const Value &ValueObject::GetValue() const { return m_value; }
371 bool ValueObject::ResolveValue(Scalar &scalar) {
372 if (UpdateValueIfNeeded(
373 false)) // make sure that you are up to date before returning anything
375 ExecutionContext exe_ctx(GetExecutionContextRef());
376 Value tmp_value(m_value);
377 scalar = tmp_value.ResolveValue(&exe_ctx);
378 if (scalar.IsValid()) {
379 const uint32_t bitfield_bit_size = GetBitfieldBitSize();
380 if (bitfield_bit_size)
381 return scalar.ExtractBitfield(bitfield_bit_size,
382 GetBitfieldBitOffset());
389 bool ValueObject::IsLogicalTrue(Status &error) {
390 if (Language *language = Language::FindPlugin(GetObjectRuntimeLanguage())) {
391 LazyBool is_logical_true = language->IsLogicalTrue(*this, error);
392 switch (is_logical_true) {
395 return (is_logical_true == true);
396 case eLazyBoolCalculate:
403 if (!ResolveValue(scalar_value)) {
404 error.SetErrorString("failed to get a scalar result");
409 ret = scalar_value.ULongLong(1) != 0;
414 bool ValueObject::GetValueIsValid() const { return m_value_is_valid; }
416 void ValueObject::SetValueIsValid(bool b) { m_value_is_valid = b; }
418 bool ValueObject::GetValueDidChange() { return m_value_did_change; }
420 void ValueObject::SetValueDidChange(bool value_changed) {
421 m_value_did_change = value_changed;
424 ValueObjectSP ValueObject::GetChildAtIndex(size_t idx, bool can_create) {
425 ValueObjectSP child_sp;
426 // We may need to update our value if we are dynamic
427 if (IsPossibleDynamicType())
428 UpdateValueIfNeeded(false);
429 if (idx < GetNumChildren()) {
430 // Check if we have already made the child value object?
431 if (can_create && !m_children.HasChildAtIndex(idx)) {
432 // No we haven't created the child at this index, so lets have our
433 // subclass do it and cache the result for quick future access.
434 m_children.SetChildAtIndex(idx, CreateChildAtIndex(idx, false, 0));
437 ValueObject *child = m_children.GetChildAtIndex(idx);
438 if (child != nullptr)
439 return child->GetSP();
445 ValueObject::GetChildAtIndexPath(llvm::ArrayRef<size_t> idxs,
446 size_t *index_of_error) {
447 if (idxs.size() == 0)
449 ValueObjectSP root(GetSP());
450 for (size_t idx : idxs) {
451 root = root->GetChildAtIndex(idx, true);
454 *index_of_error = idx;
461 lldb::ValueObjectSP ValueObject::GetChildAtIndexPath(
462 llvm::ArrayRef<std::pair<size_t, bool>> idxs, size_t *index_of_error) {
463 if (idxs.size() == 0)
465 ValueObjectSP root(GetSP());
466 for (std::pair<size_t, bool> idx : idxs) {
467 root = root->GetChildAtIndex(idx.first, idx.second);
470 *index_of_error = idx.first;
478 ValueObject::GetChildAtNamePath(llvm::ArrayRef<ConstString> names,
479 ConstString *name_of_error) {
480 if (names.size() == 0)
482 ValueObjectSP root(GetSP());
483 for (ConstString name : names) {
484 root = root->GetChildMemberWithName(name, true);
487 *name_of_error = name;
494 lldb::ValueObjectSP ValueObject::GetChildAtNamePath(
495 llvm::ArrayRef<std::pair<ConstString, bool>> names,
496 ConstString *name_of_error) {
497 if (names.size() == 0)
499 ValueObjectSP root(GetSP());
500 for (std::pair<ConstString, bool> name : names) {
501 root = root->GetChildMemberWithName(name.first, name.second);
504 *name_of_error = name.first;
511 size_t ValueObject::GetIndexOfChildWithName(ConstString name) {
512 bool omit_empty_base_classes = true;
513 return GetCompilerType().GetIndexOfChildWithName(name.GetCString(),
514 omit_empty_base_classes);
517 ValueObjectSP ValueObject::GetChildMemberWithName(ConstString name,
519 // when getting a child by name, it could be buried inside some base classes
520 // (which really aren't part of the expression path), so we need a vector of
521 // indexes that can get us down to the correct child
522 ValueObjectSP child_sp;
524 // We may need to update our value if we are dynamic
525 if (IsPossibleDynamicType())
526 UpdateValueIfNeeded(false);
528 std::vector<uint32_t> child_indexes;
529 bool omit_empty_base_classes = true;
530 const size_t num_child_indexes =
531 GetCompilerType().GetIndexOfChildMemberWithName(
532 name.GetCString(), omit_empty_base_classes, child_indexes);
533 if (num_child_indexes > 0) {
534 std::vector<uint32_t>::const_iterator pos = child_indexes.begin();
535 std::vector<uint32_t>::const_iterator end = child_indexes.end();
537 child_sp = GetChildAtIndex(*pos, can_create);
538 for (++pos; pos != end; ++pos) {
540 ValueObjectSP new_child_sp(child_sp->GetChildAtIndex(*pos, can_create));
541 child_sp = new_child_sp;
550 size_t ValueObject::GetNumChildren(uint32_t max) {
551 UpdateValueIfNeeded();
553 if (max < UINT32_MAX) {
554 if (m_children_count_valid) {
555 size_t children_count = m_children.GetChildrenCount();
556 return children_count <= max ? children_count : max;
558 return CalculateNumChildren(max);
561 if (!m_children_count_valid) {
562 SetNumChildren(CalculateNumChildren());
564 return m_children.GetChildrenCount();
567 bool ValueObject::MightHaveChildren() {
568 bool has_children = false;
569 const uint32_t type_info = GetTypeInfo();
571 if (type_info & (eTypeHasChildren | eTypeIsPointer | eTypeIsReference))
574 has_children = GetNumChildren() > 0;
579 // Should only be called by ValueObject::GetNumChildren()
580 void ValueObject::SetNumChildren(size_t num_children) {
581 m_children_count_valid = true;
582 m_children.SetChildrenCount(num_children);
585 void ValueObject::SetName(ConstString name) { m_name = name; }
587 ValueObject *ValueObject::CreateChildAtIndex(size_t idx,
588 bool synthetic_array_member,
589 int32_t synthetic_index) {
590 ValueObject *valobj = nullptr;
592 bool omit_empty_base_classes = true;
593 bool ignore_array_bounds = synthetic_array_member;
594 std::string child_name_str;
595 uint32_t child_byte_size = 0;
596 int32_t child_byte_offset = 0;
597 uint32_t child_bitfield_bit_size = 0;
598 uint32_t child_bitfield_bit_offset = 0;
599 bool child_is_base_class = false;
600 bool child_is_deref_of_parent = false;
601 uint64_t language_flags = 0;
603 const bool transparent_pointers = !synthetic_array_member;
604 CompilerType child_compiler_type;
606 ExecutionContext exe_ctx(GetExecutionContextRef());
608 child_compiler_type = GetCompilerType().GetChildCompilerTypeAtIndex(
609 &exe_ctx, idx, transparent_pointers, omit_empty_base_classes,
610 ignore_array_bounds, child_name_str, child_byte_size, child_byte_offset,
611 child_bitfield_bit_size, child_bitfield_bit_offset, child_is_base_class,
612 child_is_deref_of_parent, this, language_flags);
613 if (child_compiler_type) {
615 child_byte_offset += child_byte_size * synthetic_index;
617 ConstString child_name;
618 if (!child_name_str.empty())
619 child_name.SetCString(child_name_str.c_str());
621 valobj = new ValueObjectChild(
622 *this, child_compiler_type, child_name, child_byte_size,
623 child_byte_offset, child_bitfield_bit_size, child_bitfield_bit_offset,
624 child_is_base_class, child_is_deref_of_parent, eAddressTypeInvalid,
631 bool ValueObject::GetSummaryAsCString(TypeSummaryImpl *summary_ptr,
632 std::string &destination,
633 lldb::LanguageType lang) {
634 return GetSummaryAsCString(summary_ptr, destination,
635 TypeSummaryOptions().SetLanguage(lang));
638 bool ValueObject::GetSummaryAsCString(TypeSummaryImpl *summary_ptr,
639 std::string &destination,
640 const TypeSummaryOptions &options) {
643 // ideally we would like to bail out if passing NULL, but if we do so we end
644 // up not providing the summary for function pointers anymore
645 if (/*summary_ptr == NULL ||*/ m_is_getting_summary)
648 m_is_getting_summary = true;
650 TypeSummaryOptions actual_options(options);
652 if (actual_options.GetLanguage() == lldb::eLanguageTypeUnknown)
653 actual_options.SetLanguage(GetPreferredDisplayLanguage());
655 // this is a hot path in code and we prefer to avoid setting this string all
656 // too often also clearing out other information that we might care to see in
657 // a crash log. might be useful in very specific situations though.
658 /*Host::SetCrashDescriptionWithFormat("Trying to fetch a summary for %s %s.
659 Summary provider's description is %s",
660 GetTypeName().GetCString(),
661 GetName().GetCString(),
662 summary_ptr->GetDescription().c_str());*/
664 if (UpdateValueIfNeeded(false) && summary_ptr) {
665 if (HasSyntheticValue())
666 m_synthetic_value->UpdateValueIfNeeded(); // the summary might depend on
667 // the synthetic children being
668 // up-to-date (e.g. ${svar%#})
669 summary_ptr->FormatObject(this, destination, actual_options);
671 m_is_getting_summary = false;
672 return !destination.empty();
675 const char *ValueObject::GetSummaryAsCString(lldb::LanguageType lang) {
676 if (UpdateValueIfNeeded(true) && m_summary_str.empty()) {
677 TypeSummaryOptions summary_options;
678 summary_options.SetLanguage(lang);
679 GetSummaryAsCString(GetSummaryFormat().get(), m_summary_str,
682 if (m_summary_str.empty())
684 return m_summary_str.c_str();
687 bool ValueObject::GetSummaryAsCString(std::string &destination,
688 const TypeSummaryOptions &options) {
689 return GetSummaryAsCString(GetSummaryFormat().get(), destination, options);
692 bool ValueObject::IsCStringContainer(bool check_pointer) {
693 CompilerType pointee_or_element_compiler_type;
694 const Flags type_flags(GetTypeInfo(&pointee_or_element_compiler_type));
695 bool is_char_arr_ptr(type_flags.AnySet(eTypeIsArray | eTypeIsPointer) &&
696 pointee_or_element_compiler_type.IsCharType());
697 if (!is_char_arr_ptr)
701 if (type_flags.Test(eTypeIsArray))
703 addr_t cstr_address = LLDB_INVALID_ADDRESS;
704 AddressType cstr_address_type = eAddressTypeInvalid;
705 cstr_address = GetAddressOf(true, &cstr_address_type);
706 return (cstr_address != LLDB_INVALID_ADDRESS);
709 size_t ValueObject::GetPointeeData(DataExtractor &data, uint32_t item_idx,
710 uint32_t item_count) {
711 CompilerType pointee_or_element_compiler_type;
712 const uint32_t type_info = GetTypeInfo(&pointee_or_element_compiler_type);
713 const bool is_pointer_type = type_info & eTypeIsPointer;
714 const bool is_array_type = type_info & eTypeIsArray;
715 if (!(is_pointer_type || is_array_type))
721 ExecutionContext exe_ctx(GetExecutionContextRef());
723 llvm::Optional<uint64_t> item_type_size =
724 pointee_or_element_compiler_type.GetByteSize(
725 exe_ctx.GetBestExecutionContextScope());
728 const uint64_t bytes = item_count * *item_type_size;
729 const uint64_t offset = item_idx * *item_type_size;
731 if (item_idx == 0 && item_count == 1) // simply a deref
733 if (is_pointer_type) {
735 ValueObjectSP pointee_sp = Dereference(error);
736 if (error.Fail() || pointee_sp.get() == nullptr)
738 return pointee_sp->GetData(data, error);
740 ValueObjectSP child_sp = GetChildAtIndex(0, true);
741 if (child_sp.get() == nullptr)
744 return child_sp->GetData(data, error);
747 } else /* (items > 1) */
750 lldb_private::DataBufferHeap *heap_buf_ptr = nullptr;
751 lldb::DataBufferSP data_sp(heap_buf_ptr =
752 new lldb_private::DataBufferHeap());
754 AddressType addr_type;
755 lldb::addr_t addr = is_pointer_type ? GetPointerValue(&addr_type)
756 : GetAddressOf(true, &addr_type);
759 case eAddressTypeFile: {
760 ModuleSP module_sp(GetModule());
762 addr = addr + offset;
764 module_sp->ResolveFileAddress(addr, so_addr);
765 ExecutionContext exe_ctx(GetExecutionContextRef());
766 Target *target = exe_ctx.GetTargetPtr();
768 heap_buf_ptr->SetByteSize(bytes);
769 size_t bytes_read = target->ReadMemory(
770 so_addr, false, heap_buf_ptr->GetBytes(), bytes, error);
771 if (error.Success()) {
772 data.SetData(data_sp);
778 case eAddressTypeLoad: {
779 ExecutionContext exe_ctx(GetExecutionContextRef());
780 Process *process = exe_ctx.GetProcessPtr();
782 heap_buf_ptr->SetByteSize(bytes);
783 size_t bytes_read = process->ReadMemory(
784 addr + offset, heap_buf_ptr->GetBytes(), bytes, error);
785 if (error.Success() || bytes_read > 0) {
786 data.SetData(data_sp);
791 case eAddressTypeHost: {
793 GetCompilerType().GetByteSize(exe_ctx.GetBestExecutionContextScope());
794 if (max_bytes && *max_bytes > offset) {
795 size_t bytes_read = std::min<uint64_t>(*max_bytes - offset, bytes);
796 addr = m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
797 if (addr == 0 || addr == LLDB_INVALID_ADDRESS)
799 heap_buf_ptr->CopyData((uint8_t *)(addr + offset), bytes_read);
800 data.SetData(data_sp);
804 case eAddressTypeInvalid:
811 uint64_t ValueObject::GetData(DataExtractor &data, Status &error) {
812 UpdateValueIfNeeded(false);
813 ExecutionContext exe_ctx(GetExecutionContextRef());
814 error = m_value.GetValueAsData(&exe_ctx, data, 0, GetModule().get());
816 if (m_data.GetByteSize()) {
819 return data.GetByteSize();
824 data.SetAddressByteSize(m_data.GetAddressByteSize());
825 data.SetByteOrder(m_data.GetByteOrder());
826 return data.GetByteSize();
829 bool ValueObject::SetData(DataExtractor &data, Status &error) {
831 // Make sure our value is up to date first so that our location and location
833 if (!UpdateValueIfNeeded(false)) {
834 error.SetErrorString("unable to read value");
839 const Encoding encoding = GetCompilerType().GetEncoding(count);
841 const size_t byte_size = GetByteSize();
843 Value::ValueType value_type = m_value.GetValueType();
845 switch (value_type) {
846 case Value::eValueTypeScalar: {
848 m_value.GetScalar().SetValueFromData(data, encoding, byte_size);
850 if (!set_error.Success()) {
851 error.SetErrorStringWithFormat("unable to set scalar value: %s",
852 set_error.AsCString());
856 case Value::eValueTypeLoadAddress: {
857 // If it is a load address, then the scalar value is the storage location
858 // of the data, and we have to shove this value down to that load location.
859 ExecutionContext exe_ctx(GetExecutionContextRef());
860 Process *process = exe_ctx.GetProcessPtr();
862 addr_t target_addr = m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
863 size_t bytes_written = process->WriteMemory(
864 target_addr, data.GetDataStart(), byte_size, error);
865 if (!error.Success())
867 if (bytes_written != byte_size) {
868 error.SetErrorString("unable to write value to memory");
873 case Value::eValueTypeHostAddress: {
874 // If it is a host address, then we stuff the scalar as a DataBuffer into
876 DataBufferSP buffer_sp(new DataBufferHeap(byte_size, 0));
877 m_data.SetData(buffer_sp, 0);
878 data.CopyByteOrderedData(0, byte_size,
879 const_cast<uint8_t *>(m_data.GetDataStart()),
880 byte_size, m_data.GetByteOrder());
881 m_value.GetScalar() = (uintptr_t)m_data.GetDataStart();
883 case Value::eValueTypeFileAddress:
884 case Value::eValueTypeVector:
888 // If we have reached this point, then we have successfully changed the
894 static bool CopyStringDataToBufferSP(const StreamString &source,
895 lldb::DataBufferSP &destination) {
896 destination = std::make_shared<DataBufferHeap>(source.GetSize() + 1, 0);
897 memcpy(destination->GetBytes(), source.GetString().data(), source.GetSize());
901 std::pair<size_t, bool>
902 ValueObject::ReadPointedString(lldb::DataBufferSP &buffer_sp, Status &error,
903 uint32_t max_length, bool honor_array,
904 Format item_format) {
905 bool was_capped = false;
907 ExecutionContext exe_ctx(GetExecutionContextRef());
908 Target *target = exe_ctx.GetTargetPtr();
911 s << "<no target to read from>";
912 error.SetErrorString("no target to read from");
913 CopyStringDataToBufferSP(s, buffer_sp);
914 return {0, was_capped};
918 max_length = target->GetMaximumSizeOfStringSummary();
920 size_t bytes_read = 0;
921 size_t total_bytes_read = 0;
923 CompilerType compiler_type = GetCompilerType();
924 CompilerType elem_or_pointee_compiler_type;
925 const Flags type_flags(GetTypeInfo(&elem_or_pointee_compiler_type));
926 if (type_flags.AnySet(eTypeIsArray | eTypeIsPointer) &&
927 elem_or_pointee_compiler_type.IsCharType()) {
928 addr_t cstr_address = LLDB_INVALID_ADDRESS;
929 AddressType cstr_address_type = eAddressTypeInvalid;
932 bool capped_data = false;
933 const bool is_array = type_flags.Test(eTypeIsArray);
936 uint64_t array_size = 0;
937 if (compiler_type.IsArrayType(nullptr, &array_size, nullptr)) {
938 cstr_len = array_size;
939 if (cstr_len > max_length) {
941 cstr_len = max_length;
944 cstr_address = GetAddressOf(true, &cstr_address_type);
947 cstr_address = GetPointerValue(&cstr_address_type);
950 if (cstr_address == 0 || cstr_address == LLDB_INVALID_ADDRESS) {
951 if (cstr_address_type == eAddressTypeHost && is_array) {
952 const char *cstr = GetDataExtractor().PeekCStr(0);
953 if (cstr == nullptr) {
954 s << "<invalid address>";
955 error.SetErrorString("invalid address");
956 CopyStringDataToBufferSP(s, buffer_sp);
957 return {0, was_capped};
959 buffer_sp = std::make_shared<DataBufferHeap>(cstr_len, 0);
960 memcpy(buffer_sp->GetBytes(), cstr, cstr_len);
961 return {cstr_len, was_capped};
963 s << "<invalid address>";
964 error.SetErrorString("invalid address");
965 CopyStringDataToBufferSP(s, buffer_sp);
966 return {0, was_capped};
970 Address cstr_so_addr(cstr_address);
972 if (cstr_len > 0 && honor_array) {
973 // I am using GetPointeeData() here to abstract the fact that some
974 // ValueObjects are actually frozen pointers in the host but the pointed-
975 // to data lives in the debuggee, and GetPointeeData() automatically
976 // takes care of this
977 GetPointeeData(data, 0, cstr_len);
979 if ((bytes_read = data.GetByteSize()) > 0) {
980 total_bytes_read = bytes_read;
981 for (size_t offset = 0; offset < bytes_read; offset++)
982 s.Printf("%c", *data.PeekData(offset, 1));
987 cstr_len = max_length;
988 const size_t k_max_buf_size = 64;
992 int cstr_len_displayed = -1;
993 bool capped_cstr = false;
994 // I am using GetPointeeData() here to abstract the fact that some
995 // ValueObjects are actually frozen pointers in the host but the pointed-
996 // to data lives in the debuggee, and GetPointeeData() automatically
997 // takes care of this
998 while ((bytes_read = GetPointeeData(data, offset, k_max_buf_size)) > 0) {
999 total_bytes_read += bytes_read;
1000 const char *cstr = data.PeekCStr(0);
1001 size_t len = strnlen(cstr, k_max_buf_size);
1002 if (cstr_len_displayed < 0)
1003 cstr_len_displayed = len;
1007 cstr_len_displayed += len;
1008 if (len > bytes_read)
1013 for (size_t offset = 0; offset < bytes_read; offset++)
1014 s.Printf("%c", *data.PeekData(offset, 1));
1016 if (len < k_max_buf_size)
1019 if (len >= cstr_len) {
1028 if (cstr_len_displayed >= 0) {
1034 error.SetErrorString("not a string object");
1035 s << "<not a string object>";
1037 CopyStringDataToBufferSP(s, buffer_sp);
1038 return {total_bytes_read, was_capped};
1041 std::pair<TypeValidatorResult, std::string> ValueObject::GetValidationStatus() {
1042 if (!UpdateValueIfNeeded(true))
1043 return {TypeValidatorResult::Success,
1044 ""}; // not the validator's job to discuss update problems
1046 if (m_validation_result.hasValue())
1047 return m_validation_result.getValue();
1049 if (!m_type_validator_sp)
1050 return {TypeValidatorResult::Success, ""}; // no validator no failure
1052 auto outcome = m_type_validator_sp->FormatObject(this);
1054 return (m_validation_result = {outcome.m_result, outcome.m_message})
1058 const char *ValueObject::GetObjectDescription() {
1059 if (!UpdateValueIfNeeded(true))
1062 // Return cached value.
1063 if (!m_object_desc_str.empty())
1064 return m_object_desc_str.c_str();
1066 ExecutionContext exe_ctx(GetExecutionContextRef());
1067 Process *process = exe_ctx.GetProcessPtr();
1071 // Returns the object description produced by one language runtime.
1072 auto get_object_description = [&](LanguageType language) -> const char * {
1073 if (LanguageRuntime *runtime = process->GetLanguageRuntime(language)) {
1075 if (runtime->GetObjectDescription(s, *this)) {
1076 m_object_desc_str.append(s.GetString());
1077 return m_object_desc_str.c_str();
1083 // Try the native language runtime first.
1084 LanguageType native_language = GetObjectRuntimeLanguage();
1085 if (const char *desc = get_object_description(native_language))
1088 // Try the Objective-C language runtime. This fallback is necessary
1089 // for Objective-C++ and mixed Objective-C / C++ programs.
1090 if (Language::LanguageIsCFamily(native_language))
1091 return get_object_description(eLanguageTypeObjC);
1095 bool ValueObject::GetValueAsCString(const lldb_private::TypeFormatImpl &format,
1096 std::string &destination) {
1097 if (UpdateValueIfNeeded(false))
1098 return format.FormatObject(this, destination);
1103 bool ValueObject::GetValueAsCString(lldb::Format format,
1104 std::string &destination) {
1105 return GetValueAsCString(TypeFormatImpl_Format(format), destination);
1108 const char *ValueObject::GetValueAsCString() {
1109 if (UpdateValueIfNeeded(true)) {
1110 lldb::TypeFormatImplSP format_sp;
1111 lldb::Format my_format = GetFormat();
1112 if (my_format == lldb::eFormatDefault) {
1113 if (m_type_format_sp)
1114 format_sp = m_type_format_sp;
1116 if (m_is_bitfield_for_scalar)
1117 my_format = eFormatUnsigned;
1119 if (m_value.GetContextType() == Value::eContextTypeRegisterInfo) {
1120 const RegisterInfo *reg_info = m_value.GetRegisterInfo();
1122 my_format = reg_info->format;
1124 my_format = GetValue().GetCompilerType().GetFormat();
1129 if (my_format != m_last_format || m_value_str.empty()) {
1130 m_last_format = my_format;
1132 format_sp = std::make_shared<TypeFormatImpl_Format>(my_format);
1133 if (GetValueAsCString(*format_sp.get(), m_value_str)) {
1134 if (!m_value_did_change && m_old_value_valid) {
1135 // The value was gotten successfully, so we consider the value as
1136 // changed if the value string differs
1137 SetValueDidChange(m_old_value_str != m_value_str);
1142 if (m_value_str.empty())
1144 return m_value_str.c_str();
1147 // if > 8bytes, 0 is returned. this method should mostly be used to read
1148 // address values out of pointers
1149 uint64_t ValueObject::GetValueAsUnsigned(uint64_t fail_value, bool *success) {
1150 // If our byte size is zero this is an aggregate type that has children
1151 if (CanProvideValue()) {
1153 if (ResolveValue(scalar)) {
1156 return scalar.ULongLong(fail_value);
1158 // fallthrough, otherwise...
1166 int64_t ValueObject::GetValueAsSigned(int64_t fail_value, bool *success) {
1167 // If our byte size is zero this is an aggregate type that has children
1168 if (CanProvideValue()) {
1170 if (ResolveValue(scalar)) {
1173 return scalar.SLongLong(fail_value);
1175 // fallthrough, otherwise...
1183 // if any more "special cases" are added to
1184 // ValueObject::DumpPrintableRepresentation() please keep this call up to date
1185 // by returning true for your new special cases. We will eventually move to
1186 // checking this call result before trying to display special cases
1187 bool ValueObject::HasSpecialPrintableRepresentation(
1188 ValueObjectRepresentationStyle val_obj_display, Format custom_format) {
1189 Flags flags(GetTypeInfo());
1190 if (flags.AnySet(eTypeIsArray | eTypeIsPointer) &&
1191 val_obj_display == ValueObject::eValueObjectRepresentationStyleValue) {
1192 if (IsCStringContainer(true) &&
1193 (custom_format == eFormatCString || custom_format == eFormatCharArray ||
1194 custom_format == eFormatChar || custom_format == eFormatVectorOfChar))
1197 if (flags.Test(eTypeIsArray)) {
1198 if ((custom_format == eFormatBytes) ||
1199 (custom_format == eFormatBytesWithASCII))
1202 if ((custom_format == eFormatVectorOfChar) ||
1203 (custom_format == eFormatVectorOfFloat32) ||
1204 (custom_format == eFormatVectorOfFloat64) ||
1205 (custom_format == eFormatVectorOfSInt16) ||
1206 (custom_format == eFormatVectorOfSInt32) ||
1207 (custom_format == eFormatVectorOfSInt64) ||
1208 (custom_format == eFormatVectorOfSInt8) ||
1209 (custom_format == eFormatVectorOfUInt128) ||
1210 (custom_format == eFormatVectorOfUInt16) ||
1211 (custom_format == eFormatVectorOfUInt32) ||
1212 (custom_format == eFormatVectorOfUInt64) ||
1213 (custom_format == eFormatVectorOfUInt8))
1220 bool ValueObject::DumpPrintableRepresentation(
1221 Stream &s, ValueObjectRepresentationStyle val_obj_display,
1222 Format custom_format, PrintableRepresentationSpecialCases special,
1223 bool do_dump_error) {
1225 Flags flags(GetTypeInfo());
1227 bool allow_special =
1228 (special == ValueObject::PrintableRepresentationSpecialCases::eAllow);
1229 const bool only_special = false;
1231 if (allow_special) {
1232 if (flags.AnySet(eTypeIsArray | eTypeIsPointer) &&
1233 val_obj_display == ValueObject::eValueObjectRepresentationStyleValue) {
1234 // when being asked to get a printable display an array or pointer type
1235 // directly, try to "do the right thing"
1237 if (IsCStringContainer(true) &&
1238 (custom_format == eFormatCString ||
1239 custom_format == eFormatCharArray || custom_format == eFormatChar ||
1241 eFormatVectorOfChar)) // print char[] & char* directly
1244 lldb::DataBufferSP buffer_sp;
1245 std::pair<size_t, bool> read_string = ReadPointedString(
1246 buffer_sp, error, 0, (custom_format == eFormatVectorOfChar) ||
1247 (custom_format == eFormatCharArray));
1248 lldb_private::formatters::StringPrinter::
1249 ReadBufferAndDumpToStreamOptions options(*this);
1250 options.SetData(DataExtractor(
1251 buffer_sp, lldb::eByteOrderInvalid,
1252 8)); // none of this matters for a string - pass some defaults
1253 options.SetStream(&s);
1254 options.SetPrefixToken(nullptr);
1255 options.SetQuote('"');
1256 options.SetSourceSize(buffer_sp->GetByteSize());
1257 options.SetIsTruncated(read_string.second);
1258 formatters::StringPrinter::ReadBufferAndDumpToStream<
1259 lldb_private::formatters::StringPrinter::StringElementType::ASCII>(
1261 return !error.Fail();
1264 if (custom_format == eFormatEnum)
1267 // this only works for arrays, because I have no way to know when the
1268 // pointed memory ends, and no special \0 end of data marker
1269 if (flags.Test(eTypeIsArray)) {
1270 if ((custom_format == eFormatBytes) ||
1271 (custom_format == eFormatBytesWithASCII)) {
1272 const size_t count = GetNumChildren();
1275 for (size_t low = 0; low < count; low++) {
1280 ValueObjectSP child = GetChildAtIndex(low, true);
1282 s << "<invalid child>";
1285 child->DumpPrintableRepresentation(
1286 s, ValueObject::eValueObjectRepresentationStyleValue,
1295 if ((custom_format == eFormatVectorOfChar) ||
1296 (custom_format == eFormatVectorOfFloat32) ||
1297 (custom_format == eFormatVectorOfFloat64) ||
1298 (custom_format == eFormatVectorOfSInt16) ||
1299 (custom_format == eFormatVectorOfSInt32) ||
1300 (custom_format == eFormatVectorOfSInt64) ||
1301 (custom_format == eFormatVectorOfSInt8) ||
1302 (custom_format == eFormatVectorOfUInt128) ||
1303 (custom_format == eFormatVectorOfUInt16) ||
1304 (custom_format == eFormatVectorOfUInt32) ||
1305 (custom_format == eFormatVectorOfUInt64) ||
1306 (custom_format == eFormatVectorOfUInt8)) // arrays of bytes, bytes
1307 // with ASCII or any vector
1308 // format should be printed
1311 const size_t count = GetNumChildren();
1313 Format format = FormatManager::GetSingleItemFormat(custom_format);
1316 for (size_t low = 0; low < count; low++) {
1321 ValueObjectSP child = GetChildAtIndex(low, true);
1323 s << "<invalid child>";
1326 child->DumpPrintableRepresentation(
1327 s, ValueObject::eValueObjectRepresentationStyleValue, format);
1336 if ((custom_format == eFormatBoolean) ||
1337 (custom_format == eFormatBinary) || (custom_format == eFormatChar) ||
1338 (custom_format == eFormatCharPrintable) ||
1339 (custom_format == eFormatComplexFloat) ||
1340 (custom_format == eFormatDecimal) || (custom_format == eFormatHex) ||
1341 (custom_format == eFormatHexUppercase) ||
1342 (custom_format == eFormatFloat) || (custom_format == eFormatOctal) ||
1343 (custom_format == eFormatOSType) ||
1344 (custom_format == eFormatUnicode16) ||
1345 (custom_format == eFormatUnicode32) ||
1346 (custom_format == eFormatUnsigned) ||
1347 (custom_format == eFormatPointer) ||
1348 (custom_format == eFormatComplexInteger) ||
1349 (custom_format == eFormatComplex) ||
1350 (custom_format == eFormatDefault)) // use the [] operator
1358 bool var_success = false;
1361 llvm::StringRef str;
1363 // this is a local stream that we are using to ensure that the data pointed
1364 // to by cstr survives long enough for us to copy it to its destination -
1365 // it is necessary to have this temporary storage area for cases where our
1366 // desired output is not backed by some other longer-term storage
1369 if (custom_format != eFormatInvalid)
1370 SetFormat(custom_format);
1372 switch (val_obj_display) {
1373 case eValueObjectRepresentationStyleValue:
1374 str = GetValueAsCString();
1377 case eValueObjectRepresentationStyleSummary:
1378 str = GetSummaryAsCString();
1381 case eValueObjectRepresentationStyleLanguageSpecific:
1382 str = GetObjectDescription();
1385 case eValueObjectRepresentationStyleLocation:
1386 str = GetLocationAsCString();
1389 case eValueObjectRepresentationStyleChildrenCount:
1390 strm.Printf("%" PRIu64 "", (uint64_t)GetNumChildren());
1391 str = strm.GetString();
1394 case eValueObjectRepresentationStyleType:
1395 str = GetTypeName().GetStringRef();
1398 case eValueObjectRepresentationStyleName:
1399 str = GetName().GetStringRef();
1402 case eValueObjectRepresentationStyleExpressionPath:
1403 GetExpressionPath(strm, false);
1404 str = strm.GetString();
1409 if (val_obj_display == eValueObjectRepresentationStyleValue)
1410 str = GetSummaryAsCString();
1411 else if (val_obj_display == eValueObjectRepresentationStyleSummary) {
1412 if (!CanProvideValue()) {
1413 strm.Printf("%s @ %s", GetTypeName().AsCString(),
1414 GetLocationAsCString());
1415 str = strm.GetString();
1417 str = GetValueAsCString();
1424 if (m_error.Fail()) {
1426 s.Printf("<%s>", m_error.AsCString());
1429 } else if (val_obj_display == eValueObjectRepresentationStyleSummary)
1430 s.PutCString("<no summary available>");
1431 else if (val_obj_display == eValueObjectRepresentationStyleValue)
1432 s.PutCString("<no value available>");
1433 else if (val_obj_display ==
1434 eValueObjectRepresentationStyleLanguageSpecific)
1435 s.PutCString("<not a valid Objective-C object>"); // edit this if we
1436 // have other runtimes
1440 s.PutCString("<no printable representation>");
1443 // we should only return false here if we could not do *anything* even if
1444 // we have an error message as output, that's a success from our callers'
1445 // perspective, so return true
1448 if (custom_format != eFormatInvalid)
1449 SetFormat(eFormatDefault);
1455 addr_t ValueObject::GetAddressOf(bool scalar_is_load_address,
1456 AddressType *address_type) {
1457 // Can't take address of a bitfield
1459 return LLDB_INVALID_ADDRESS;
1461 if (!UpdateValueIfNeeded(false))
1462 return LLDB_INVALID_ADDRESS;
1464 switch (m_value.GetValueType()) {
1465 case Value::eValueTypeScalar:
1466 case Value::eValueTypeVector:
1467 if (scalar_is_load_address) {
1469 *address_type = eAddressTypeLoad;
1470 return m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
1474 case Value::eValueTypeLoadAddress:
1475 case Value::eValueTypeFileAddress: {
1477 *address_type = m_value.GetValueAddressType();
1478 return m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
1480 case Value::eValueTypeHostAddress: {
1482 *address_type = m_value.GetValueAddressType();
1483 return LLDB_INVALID_ADDRESS;
1487 *address_type = eAddressTypeInvalid;
1488 return LLDB_INVALID_ADDRESS;
1491 addr_t ValueObject::GetPointerValue(AddressType *address_type) {
1492 addr_t address = LLDB_INVALID_ADDRESS;
1494 *address_type = eAddressTypeInvalid;
1496 if (!UpdateValueIfNeeded(false))
1499 switch (m_value.GetValueType()) {
1500 case Value::eValueTypeScalar:
1501 case Value::eValueTypeVector:
1502 address = m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
1505 case Value::eValueTypeHostAddress:
1506 case Value::eValueTypeLoadAddress:
1507 case Value::eValueTypeFileAddress: {
1508 lldb::offset_t data_offset = 0;
1509 address = m_data.GetPointer(&data_offset);
1514 *address_type = GetAddressTypeOfChildren();
1519 bool ValueObject::SetValueFromCString(const char *value_str, Status &error) {
1521 // Make sure our value is up to date first so that our location and location
1523 if (!UpdateValueIfNeeded(false)) {
1524 error.SetErrorString("unable to read value");
1529 const Encoding encoding = GetCompilerType().GetEncoding(count);
1531 const size_t byte_size = GetByteSize();
1533 Value::ValueType value_type = m_value.GetValueType();
1535 if (value_type == Value::eValueTypeScalar) {
1536 // If the value is already a scalar, then let the scalar change itself:
1537 m_value.GetScalar().SetValueFromCString(value_str, encoding, byte_size);
1538 } else if (byte_size <= 16) {
1539 // If the value fits in a scalar, then make a new scalar and again let the
1540 // scalar code do the conversion, then figure out where to put the new
1543 error = new_scalar.SetValueFromCString(value_str, encoding, byte_size);
1544 if (error.Success()) {
1545 switch (value_type) {
1546 case Value::eValueTypeLoadAddress: {
1547 // If it is a load address, then the scalar value is the storage
1548 // location of the data, and we have to shove this value down to that
1550 ExecutionContext exe_ctx(GetExecutionContextRef());
1551 Process *process = exe_ctx.GetProcessPtr();
1553 addr_t target_addr =
1554 m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
1555 size_t bytes_written = process->WriteScalarToMemory(
1556 target_addr, new_scalar, byte_size, error);
1557 if (!error.Success())
1559 if (bytes_written != byte_size) {
1560 error.SetErrorString("unable to write value to memory");
1565 case Value::eValueTypeHostAddress: {
1566 // If it is a host address, then we stuff the scalar as a DataBuffer
1567 // into the Value's data.
1568 DataExtractor new_data;
1569 new_data.SetByteOrder(m_data.GetByteOrder());
1571 DataBufferSP buffer_sp(new DataBufferHeap(byte_size, 0));
1572 m_data.SetData(buffer_sp, 0);
1573 bool success = new_scalar.GetData(new_data);
1575 new_data.CopyByteOrderedData(
1576 0, byte_size, const_cast<uint8_t *>(m_data.GetDataStart()),
1577 byte_size, m_data.GetByteOrder());
1579 m_value.GetScalar() = (uintptr_t)m_data.GetDataStart();
1582 case Value::eValueTypeFileAddress:
1583 case Value::eValueTypeScalar:
1584 case Value::eValueTypeVector:
1591 // We don't support setting things bigger than a scalar at present.
1592 error.SetErrorString("unable to write aggregate data type");
1596 // If we have reached this point, then we have successfully changed the
1602 bool ValueObject::GetDeclaration(Declaration &decl) {
1607 ConstString ValueObject::GetTypeName() {
1608 return GetCompilerType().GetConstTypeName();
1611 ConstString ValueObject::GetDisplayTypeName() { return GetTypeName(); }
1613 ConstString ValueObject::GetQualifiedTypeName() {
1614 return GetCompilerType().GetConstQualifiedTypeName();
1617 LanguageType ValueObject::GetObjectRuntimeLanguage() {
1618 return GetCompilerType().GetMinimumLanguage();
1621 void ValueObject::AddSyntheticChild(ConstString key,
1622 ValueObject *valobj) {
1623 m_synthetic_children[key] = valobj;
1626 ValueObjectSP ValueObject::GetSyntheticChild(ConstString key) const {
1627 ValueObjectSP synthetic_child_sp;
1628 std::map<ConstString, ValueObject *>::const_iterator pos =
1629 m_synthetic_children.find(key);
1630 if (pos != m_synthetic_children.end())
1631 synthetic_child_sp = pos->second->GetSP();
1632 return synthetic_child_sp;
1636 ValueObject::GetTypeInfo(CompilerType *pointee_or_element_compiler_type) {
1637 return GetCompilerType().GetTypeInfo(pointee_or_element_compiler_type);
1640 bool ValueObject::IsPointerType() { return GetCompilerType().IsPointerType(); }
1642 bool ValueObject::IsArrayType() {
1643 return GetCompilerType().IsArrayType(nullptr, nullptr, nullptr);
1646 bool ValueObject::IsScalarType() { return GetCompilerType().IsScalarType(); }
1648 bool ValueObject::IsIntegerType(bool &is_signed) {
1649 return GetCompilerType().IsIntegerType(is_signed);
1652 bool ValueObject::IsPointerOrReferenceType() {
1653 return GetCompilerType().IsPointerOrReferenceType();
1656 bool ValueObject::IsPossibleDynamicType() {
1657 ExecutionContext exe_ctx(GetExecutionContextRef());
1658 Process *process = exe_ctx.GetProcessPtr();
1660 return process->IsPossibleDynamicValue(*this);
1662 return GetCompilerType().IsPossibleDynamicType(nullptr, true, true);
1665 bool ValueObject::IsRuntimeSupportValue() {
1666 Process *process(GetProcessSP().get());
1670 // We trust the the compiler did the right thing and marked runtime support
1671 // values as artificial.
1672 if (!GetVariable() || !GetVariable()->IsArtificial())
1675 LanguageType lang = eLanguageTypeUnknown;
1676 if (auto *sym_ctx_scope = GetSymbolContextScope()) {
1677 if (auto *func = sym_ctx_scope->CalculateSymbolContextFunction())
1678 lang = func->GetLanguage();
1679 else if (auto *comp_unit =
1680 sym_ctx_scope->CalculateSymbolContextCompileUnit())
1681 lang = comp_unit->GetLanguage();
1684 if (auto *runtime = process->GetLanguageRuntime(lang))
1685 if (runtime->IsWhitelistedRuntimeValue(GetName()))
1691 bool ValueObject::IsNilReference() {
1692 if (Language *language = Language::FindPlugin(GetObjectRuntimeLanguage())) {
1693 return language->IsNilReference(*this);
1698 bool ValueObject::IsUninitializedReference() {
1699 if (Language *language = Language::FindPlugin(GetObjectRuntimeLanguage())) {
1700 return language->IsUninitializedReference(*this);
1705 // This allows you to create an array member using and index that doesn't not
1706 // fall in the normal bounds of the array. Many times structure can be defined
1707 // as: struct Collection {
1708 // uint32_t item_count;
1709 // Item item_array[0];
1711 // The size of the "item_array" is 1, but many times in practice there are more
1712 // items in "item_array".
1714 ValueObjectSP ValueObject::GetSyntheticArrayMember(size_t index,
1716 ValueObjectSP synthetic_child_sp;
1717 if (IsPointerType() || IsArrayType()) {
1719 snprintf(index_str, sizeof(index_str), "[%" PRIu64 "]", (uint64_t)index);
1720 ConstString index_const_str(index_str);
1721 // Check if we have already created a synthetic array member in this valid
1722 // object. If we have we will re-use it.
1723 synthetic_child_sp = GetSyntheticChild(index_const_str);
1724 if (!synthetic_child_sp) {
1725 ValueObject *synthetic_child;
1726 // We haven't made a synthetic array member for INDEX yet, so lets make
1727 // one and cache it for any future reference.
1728 synthetic_child = CreateChildAtIndex(0, true, index);
1730 // Cache the value if we got one back...
1731 if (synthetic_child) {
1732 AddSyntheticChild(index_const_str, synthetic_child);
1733 synthetic_child_sp = synthetic_child->GetSP();
1734 synthetic_child_sp->SetName(ConstString(index_str));
1735 synthetic_child_sp->m_is_array_item_for_pointer = true;
1739 return synthetic_child_sp;
1742 ValueObjectSP ValueObject::GetSyntheticBitFieldChild(uint32_t from, uint32_t to,
1744 ValueObjectSP synthetic_child_sp;
1745 if (IsScalarType()) {
1747 snprintf(index_str, sizeof(index_str), "[%i-%i]", from, to);
1748 ConstString index_const_str(index_str);
1749 // Check if we have already created a synthetic array member in this valid
1750 // object. If we have we will re-use it.
1751 synthetic_child_sp = GetSyntheticChild(index_const_str);
1752 if (!synthetic_child_sp) {
1753 uint32_t bit_field_size = to - from + 1;
1754 uint32_t bit_field_offset = from;
1755 if (GetDataExtractor().GetByteOrder() == eByteOrderBig)
1757 GetByteSize() * 8 - bit_field_size - bit_field_offset;
1758 // We haven't made a synthetic array member for INDEX yet, so lets make
1759 // one and cache it for any future reference.
1760 ValueObjectChild *synthetic_child = new ValueObjectChild(
1761 *this, GetCompilerType(), index_const_str, GetByteSize(), 0,
1762 bit_field_size, bit_field_offset, false, false, eAddressTypeInvalid,
1765 // Cache the value if we got one back...
1766 if (synthetic_child) {
1767 AddSyntheticChild(index_const_str, synthetic_child);
1768 synthetic_child_sp = synthetic_child->GetSP();
1769 synthetic_child_sp->SetName(ConstString(index_str));
1770 synthetic_child_sp->m_is_bitfield_for_scalar = true;
1774 return synthetic_child_sp;
1777 ValueObjectSP ValueObject::GetSyntheticChildAtOffset(
1778 uint32_t offset, const CompilerType &type, bool can_create,
1779 ConstString name_const_str) {
1781 ValueObjectSP synthetic_child_sp;
1783 if (name_const_str.IsEmpty()) {
1785 snprintf(name_str, sizeof(name_str), "@%i", offset);
1786 name_const_str.SetCString(name_str);
1789 // Check if we have already created a synthetic array member in this valid
1790 // object. If we have we will re-use it.
1791 synthetic_child_sp = GetSyntheticChild(name_const_str);
1793 if (synthetic_child_sp.get())
1794 return synthetic_child_sp;
1799 ExecutionContext exe_ctx(GetExecutionContextRef());
1800 llvm::Optional<uint64_t> size =
1801 type.GetByteSize(exe_ctx.GetBestExecutionContextScope());
1804 ValueObjectChild *synthetic_child =
1805 new ValueObjectChild(*this, type, name_const_str, *size, offset, 0, 0,
1806 false, false, eAddressTypeInvalid, 0);
1807 if (synthetic_child) {
1808 AddSyntheticChild(name_const_str, synthetic_child);
1809 synthetic_child_sp = synthetic_child->GetSP();
1810 synthetic_child_sp->SetName(name_const_str);
1811 synthetic_child_sp->m_is_child_at_offset = true;
1813 return synthetic_child_sp;
1816 ValueObjectSP ValueObject::GetSyntheticBase(uint32_t offset,
1817 const CompilerType &type,
1819 ConstString name_const_str) {
1820 ValueObjectSP synthetic_child_sp;
1822 if (name_const_str.IsEmpty()) {
1824 snprintf(name_str, sizeof(name_str), "base%s@%i",
1825 type.GetTypeName().AsCString("<unknown>"), offset);
1826 name_const_str.SetCString(name_str);
1829 // Check if we have already created a synthetic array member in this valid
1830 // object. If we have we will re-use it.
1831 synthetic_child_sp = GetSyntheticChild(name_const_str);
1833 if (synthetic_child_sp.get())
1834 return synthetic_child_sp;
1839 const bool is_base_class = true;
1841 ExecutionContext exe_ctx(GetExecutionContextRef());
1842 llvm::Optional<uint64_t> size =
1843 type.GetByteSize(exe_ctx.GetBestExecutionContextScope());
1846 ValueObjectChild *synthetic_child =
1847 new ValueObjectChild(*this, type, name_const_str, *size, offset, 0, 0,
1848 is_base_class, false, eAddressTypeInvalid, 0);
1849 if (synthetic_child) {
1850 AddSyntheticChild(name_const_str, synthetic_child);
1851 synthetic_child_sp = synthetic_child->GetSP();
1852 synthetic_child_sp->SetName(name_const_str);
1854 return synthetic_child_sp;
1857 // your expression path needs to have a leading . or -> (unless it somehow
1858 // "looks like" an array, in which case it has a leading [ symbol). while the [
1859 // is meaningful and should be shown to the user, . and -> are just parser
1860 // design, but by no means added information for the user.. strip them off
1861 static const char *SkipLeadingExpressionPathSeparators(const char *expression) {
1862 if (!expression || !expression[0])
1864 if (expression[0] == '.')
1865 return expression + 1;
1866 if (expression[0] == '-' && expression[1] == '>')
1867 return expression + 2;
1872 ValueObject::GetSyntheticExpressionPathChild(const char *expression,
1874 ValueObjectSP synthetic_child_sp;
1875 ConstString name_const_string(expression);
1876 // Check if we have already created a synthetic array member in this valid
1877 // object. If we have we will re-use it.
1878 synthetic_child_sp = GetSyntheticChild(name_const_string);
1879 if (!synthetic_child_sp) {
1880 // We haven't made a synthetic array member for expression yet, so lets
1881 // make one and cache it for any future reference.
1882 synthetic_child_sp = GetValueForExpressionPath(
1883 expression, nullptr, nullptr,
1884 GetValueForExpressionPathOptions().SetSyntheticChildrenTraversal(
1885 GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
1888 // Cache the value if we got one back...
1889 if (synthetic_child_sp.get()) {
1890 // FIXME: this causes a "real" child to end up with its name changed to
1891 // the contents of expression
1892 AddSyntheticChild(name_const_string, synthetic_child_sp.get());
1893 synthetic_child_sp->SetName(
1894 ConstString(SkipLeadingExpressionPathSeparators(expression)));
1897 return synthetic_child_sp;
1900 void ValueObject::CalculateSyntheticValue(bool use_synthetic) {
1904 TargetSP target_sp(GetTargetSP());
1905 if (target_sp && !target_sp->GetEnableSyntheticValue()) {
1906 m_synthetic_value = nullptr;
1910 lldb::SyntheticChildrenSP current_synth_sp(m_synthetic_children_sp);
1912 if (!UpdateFormatsIfNeeded() && m_synthetic_value)
1915 if (m_synthetic_children_sp.get() == nullptr)
1918 if (current_synth_sp == m_synthetic_children_sp && m_synthetic_value)
1921 m_synthetic_value = new ValueObjectSynthetic(*this, m_synthetic_children_sp);
1924 void ValueObject::CalculateDynamicValue(DynamicValueType use_dynamic) {
1925 if (use_dynamic == eNoDynamicValues)
1928 if (!m_dynamic_value && !IsDynamic()) {
1929 ExecutionContext exe_ctx(GetExecutionContextRef());
1930 Process *process = exe_ctx.GetProcessPtr();
1931 if (process && process->IsPossibleDynamicValue(*this)) {
1932 ClearDynamicTypeInformation();
1933 m_dynamic_value = new ValueObjectDynamicValue(*this, use_dynamic);
1938 ValueObjectSP ValueObject::GetDynamicValue(DynamicValueType use_dynamic) {
1939 if (use_dynamic == eNoDynamicValues)
1940 return ValueObjectSP();
1942 if (!IsDynamic() && m_dynamic_value == nullptr) {
1943 CalculateDynamicValue(use_dynamic);
1945 if (m_dynamic_value)
1946 return m_dynamic_value->GetSP();
1948 return ValueObjectSP();
1951 ValueObjectSP ValueObject::GetStaticValue() { return GetSP(); }
1953 lldb::ValueObjectSP ValueObject::GetNonSyntheticValue() { return GetSP(); }
1955 ValueObjectSP ValueObject::GetSyntheticValue(bool use_synthetic) {
1957 return ValueObjectSP();
1959 CalculateSyntheticValue(use_synthetic);
1961 if (m_synthetic_value)
1962 return m_synthetic_value->GetSP();
1964 return ValueObjectSP();
1967 bool ValueObject::HasSyntheticValue() {
1968 UpdateFormatsIfNeeded();
1970 if (m_synthetic_children_sp.get() == nullptr)
1973 CalculateSyntheticValue(true);
1975 return m_synthetic_value != nullptr;
1978 bool ValueObject::GetBaseClassPath(Stream &s) {
1979 if (IsBaseClass()) {
1980 bool parent_had_base_class =
1981 GetParent() && GetParent()->GetBaseClassPath(s);
1982 CompilerType compiler_type = GetCompilerType();
1983 std::string cxx_class_name;
1984 bool this_had_base_class =
1985 ClangASTContext::GetCXXClassName(compiler_type, cxx_class_name);
1986 if (this_had_base_class) {
1987 if (parent_had_base_class)
1989 s.PutCString(cxx_class_name);
1991 return parent_had_base_class || this_had_base_class;
1996 ValueObject *ValueObject::GetNonBaseClassParent() {
1998 if (GetParent()->IsBaseClass())
1999 return GetParent()->GetNonBaseClassParent();
2006 bool ValueObject::IsBaseClass(uint32_t &depth) {
2007 if (!IsBaseClass()) {
2012 GetParent()->IsBaseClass(depth);
2016 // TODO: a base of no parent? weird..
2021 void ValueObject::GetExpressionPath(Stream &s, bool qualify_cxx_base_classes,
2022 GetExpressionPathFormat epformat) {
2023 // synthetic children do not actually "exist" as part of the hierarchy, and
2024 // sometimes they are consed up in ways that don't make sense from an
2025 // underlying language/API standpoint. So, use a special code path here to
2026 // return something that can hopefully be used in expression
2027 if (m_is_synthetic_children_generated) {
2028 UpdateValueIfNeeded();
2030 if (m_value.GetValueType() == Value::eValueTypeLoadAddress) {
2031 if (IsPointerOrReferenceType()) {
2032 s.Printf("((%s)0x%" PRIx64 ")", GetTypeName().AsCString("void"),
2033 GetValueAsUnsigned(0));
2036 uint64_t load_addr =
2037 m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
2038 if (load_addr != LLDB_INVALID_ADDRESS) {
2039 s.Printf("(*( (%s *)0x%" PRIx64 "))", GetTypeName().AsCString("void"),
2046 if (CanProvideValue()) {
2047 s.Printf("((%s)%s)", GetTypeName().AsCString("void"),
2048 GetValueAsCString());
2055 const bool is_deref_of_parent = IsDereferenceOfParent();
2057 if (is_deref_of_parent &&
2058 epformat == eGetExpressionPathFormatDereferencePointers) {
2059 // this is the original format of GetExpressionPath() producing code like
2060 // *(a_ptr).memberName, which is entirely fine, until you put this into
2061 // StackFrame::GetValueForVariableExpressionPath() which prefers to see
2062 // a_ptr->memberName. the eHonorPointers mode is meant to produce strings
2063 // in this latter format
2067 ValueObject *parent = GetParent();
2070 parent->GetExpressionPath(s, qualify_cxx_base_classes, epformat);
2072 // if we are a deref_of_parent just because we are synthetic array members
2073 // made up to allow ptr[%d] syntax to work in variable printing, then add our
2074 // name ([%d]) to the expression path
2075 if (m_is_array_item_for_pointer &&
2076 epformat == eGetExpressionPathFormatHonorPointers)
2077 s.PutCString(m_name.AsCString());
2079 if (!IsBaseClass()) {
2080 if (!is_deref_of_parent) {
2081 ValueObject *non_base_class_parent = GetNonBaseClassParent();
2082 if (non_base_class_parent &&
2083 !non_base_class_parent->GetName().IsEmpty()) {
2084 CompilerType non_base_class_parent_compiler_type =
2085 non_base_class_parent->GetCompilerType();
2086 if (non_base_class_parent_compiler_type) {
2087 if (parent && parent->IsDereferenceOfParent() &&
2088 epformat == eGetExpressionPathFormatHonorPointers) {
2091 const uint32_t non_base_class_parent_type_info =
2092 non_base_class_parent_compiler_type.GetTypeInfo();
2094 if (non_base_class_parent_type_info & eTypeIsPointer) {
2096 } else if ((non_base_class_parent_type_info & eTypeHasChildren) &&
2097 !(non_base_class_parent_type_info & eTypeIsArray)) {
2104 const char *name = GetName().GetCString();
2106 if (qualify_cxx_base_classes) {
2107 if (GetBaseClassPath(s))
2115 if (is_deref_of_parent &&
2116 epformat == eGetExpressionPathFormatDereferencePointers) {
2121 ValueObjectSP ValueObject::GetValueForExpressionPath(
2122 llvm::StringRef expression, ExpressionPathScanEndReason *reason_to_stop,
2123 ExpressionPathEndResultType *final_value_type,
2124 const GetValueForExpressionPathOptions &options,
2125 ExpressionPathAftermath *final_task_on_target) {
2127 ExpressionPathScanEndReason dummy_reason_to_stop =
2128 ValueObject::eExpressionPathScanEndReasonUnknown;
2129 ExpressionPathEndResultType dummy_final_value_type =
2130 ValueObject::eExpressionPathEndResultTypeInvalid;
2131 ExpressionPathAftermath dummy_final_task_on_target =
2132 ValueObject::eExpressionPathAftermathNothing;
2134 ValueObjectSP ret_val = GetValueForExpressionPath_Impl(
2135 expression, reason_to_stop ? reason_to_stop : &dummy_reason_to_stop,
2136 final_value_type ? final_value_type : &dummy_final_value_type, options,
2137 final_task_on_target ? final_task_on_target
2138 : &dummy_final_task_on_target);
2140 if (!final_task_on_target ||
2141 *final_task_on_target == ValueObject::eExpressionPathAftermathNothing)
2144 if (ret_val.get() &&
2145 ((final_value_type ? *final_value_type : dummy_final_value_type) ==
2146 eExpressionPathEndResultTypePlain)) // I can only deref and takeaddress
2149 if ((final_task_on_target ? *final_task_on_target
2150 : dummy_final_task_on_target) ==
2151 ValueObject::eExpressionPathAftermathDereference) {
2153 ValueObjectSP final_value = ret_val->Dereference(error);
2154 if (error.Fail() || !final_value.get()) {
2157 ValueObject::eExpressionPathScanEndReasonDereferencingFailed;
2158 if (final_value_type)
2159 *final_value_type = ValueObject::eExpressionPathEndResultTypeInvalid;
2160 return ValueObjectSP();
2162 if (final_task_on_target)
2163 *final_task_on_target = ValueObject::eExpressionPathAftermathNothing;
2167 if (*final_task_on_target ==
2168 ValueObject::eExpressionPathAftermathTakeAddress) {
2170 ValueObjectSP final_value = ret_val->AddressOf(error);
2171 if (error.Fail() || !final_value.get()) {
2174 ValueObject::eExpressionPathScanEndReasonTakingAddressFailed;
2175 if (final_value_type)
2176 *final_value_type = ValueObject::eExpressionPathEndResultTypeInvalid;
2177 return ValueObjectSP();
2179 if (final_task_on_target)
2180 *final_task_on_target = ValueObject::eExpressionPathAftermathNothing;
2185 return ret_val; // final_task_on_target will still have its original value, so
2186 // you know I did not do it
2189 ValueObjectSP ValueObject::GetValueForExpressionPath_Impl(
2190 llvm::StringRef expression, ExpressionPathScanEndReason *reason_to_stop,
2191 ExpressionPathEndResultType *final_result,
2192 const GetValueForExpressionPathOptions &options,
2193 ExpressionPathAftermath *what_next) {
2194 ValueObjectSP root = GetSP();
2199 llvm::StringRef remainder = expression;
2202 llvm::StringRef temp_expression = remainder;
2204 CompilerType root_compiler_type = root->GetCompilerType();
2205 CompilerType pointee_compiler_type;
2206 Flags pointee_compiler_type_info;
2208 Flags root_compiler_type_info(
2209 root_compiler_type.GetTypeInfo(&pointee_compiler_type));
2210 if (pointee_compiler_type)
2211 pointee_compiler_type_info.Reset(pointee_compiler_type.GetTypeInfo());
2213 if (temp_expression.empty()) {
2214 *reason_to_stop = ValueObject::eExpressionPathScanEndReasonEndOfString;
2218 switch (temp_expression.front()) {
2220 temp_expression = temp_expression.drop_front();
2221 if (options.m_check_dot_vs_arrow_syntax &&
2222 root_compiler_type_info.Test(eTypeIsPointer)) // if you are trying to
2224 // non-pointer and I
2225 // must catch the error
2228 ValueObject::eExpressionPathScanEndReasonArrowInsteadOfDot;
2229 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2230 return ValueObjectSP();
2232 if (root_compiler_type_info.Test(eTypeIsObjC) && // if yo are trying to
2233 // extract an ObjC IVar
2234 // when this is forbidden
2235 root_compiler_type_info.Test(eTypeIsPointer) &&
2236 options.m_no_fragile_ivar) {
2238 ValueObject::eExpressionPathScanEndReasonFragileIVarNotAllowed;
2239 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2240 return ValueObjectSP();
2242 if (!temp_expression.startswith(">")) {
2244 ValueObject::eExpressionPathScanEndReasonUnexpectedSymbol;
2245 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2246 return ValueObjectSP();
2250 case '.': // or fallthrough from ->
2252 if (options.m_check_dot_vs_arrow_syntax &&
2253 temp_expression.front() == '.' &&
2254 root_compiler_type_info.Test(eTypeIsPointer)) // if you are trying to
2255 // use . on a pointer
2256 // and I must catch the
2260 ValueObject::eExpressionPathScanEndReasonDotInsteadOfArrow;
2261 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2264 temp_expression = temp_expression.drop_front(); // skip . or >
2266 size_t next_sep_pos = temp_expression.find_first_of("-.[", 1);
2267 ConstString child_name;
2268 if (next_sep_pos == llvm::StringRef::npos) // if no other separator just
2269 // expand this last layer
2271 child_name.SetString(temp_expression);
2272 ValueObjectSP child_valobj_sp =
2273 root->GetChildMemberWithName(child_name, true);
2275 if (child_valobj_sp.get()) // we know we are done, so just return
2278 ValueObject::eExpressionPathScanEndReasonEndOfString;
2279 *final_result = ValueObject::eExpressionPathEndResultTypePlain;
2280 return child_valobj_sp;
2282 switch (options.m_synthetic_children_traversal) {
2283 case GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2286 case GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2288 if (root->IsSynthetic()) {
2289 child_valobj_sp = root->GetNonSyntheticValue();
2290 if (child_valobj_sp.get())
2292 child_valobj_sp->GetChildMemberWithName(child_name, true);
2295 case GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2297 if (!root->IsSynthetic()) {
2298 child_valobj_sp = root->GetSyntheticValue();
2299 if (child_valobj_sp.get())
2301 child_valobj_sp->GetChildMemberWithName(child_name, true);
2304 case GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2306 if (root->IsSynthetic()) {
2307 child_valobj_sp = root->GetNonSyntheticValue();
2308 if (child_valobj_sp.get())
2310 child_valobj_sp->GetChildMemberWithName(child_name, true);
2312 child_valobj_sp = root->GetSyntheticValue();
2313 if (child_valobj_sp.get())
2315 child_valobj_sp->GetChildMemberWithName(child_name, true);
2321 // if we are here and options.m_no_synthetic_children is true,
2322 // child_valobj_sp is going to be a NULL SP, so we hit the "else"
2323 // branch, and return an error
2324 if (child_valobj_sp.get()) // if it worked, just return
2327 ValueObject::eExpressionPathScanEndReasonEndOfString;
2328 *final_result = ValueObject::eExpressionPathEndResultTypePlain;
2329 return child_valobj_sp;
2332 ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2333 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2336 } else // other layers do expand
2338 llvm::StringRef next_separator = temp_expression.substr(next_sep_pos);
2340 child_name.SetString(temp_expression.slice(0, next_sep_pos));
2342 ValueObjectSP child_valobj_sp =
2343 root->GetChildMemberWithName(child_name, true);
2344 if (child_valobj_sp.get()) // store the new root and move on
2346 root = child_valobj_sp;
2347 remainder = next_separator;
2348 *final_result = ValueObject::eExpressionPathEndResultTypePlain;
2351 switch (options.m_synthetic_children_traversal) {
2352 case GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2355 case GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2357 if (root->IsSynthetic()) {
2358 child_valobj_sp = root->GetNonSyntheticValue();
2359 if (child_valobj_sp.get())
2361 child_valobj_sp->GetChildMemberWithName(child_name, true);
2364 case GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2366 if (!root->IsSynthetic()) {
2367 child_valobj_sp = root->GetSyntheticValue();
2368 if (child_valobj_sp.get())
2370 child_valobj_sp->GetChildMemberWithName(child_name, true);
2373 case GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2375 if (root->IsSynthetic()) {
2376 child_valobj_sp = root->GetNonSyntheticValue();
2377 if (child_valobj_sp.get())
2379 child_valobj_sp->GetChildMemberWithName(child_name, true);
2381 child_valobj_sp = root->GetSyntheticValue();
2382 if (child_valobj_sp.get())
2384 child_valobj_sp->GetChildMemberWithName(child_name, true);
2390 // if we are here and options.m_no_synthetic_children is true,
2391 // child_valobj_sp is going to be a NULL SP, so we hit the "else"
2392 // branch, and return an error
2393 if (child_valobj_sp.get()) // if it worked, move on
2395 root = child_valobj_sp;
2396 remainder = next_separator;
2397 *final_result = ValueObject::eExpressionPathEndResultTypePlain;
2401 ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2402 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2409 if (!root_compiler_type_info.Test(eTypeIsArray) &&
2410 !root_compiler_type_info.Test(eTypeIsPointer) &&
2411 !root_compiler_type_info.Test(
2412 eTypeIsVector)) // if this is not a T[] nor a T*
2414 if (!root_compiler_type_info.Test(
2415 eTypeIsScalar)) // if this is not even a scalar...
2417 if (options.m_synthetic_children_traversal ==
2418 GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2419 None) // ...only chance left is synthetic
2422 ValueObject::eExpressionPathScanEndReasonRangeOperatorInvalid;
2423 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2424 return ValueObjectSP();
2426 } else if (!options.m_allow_bitfields_syntax) // if this is a scalar,
2427 // check that we can
2431 ValueObject::eExpressionPathScanEndReasonRangeOperatorNotAllowed;
2432 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2433 return ValueObjectSP();
2436 if (temp_expression[1] ==
2437 ']') // if this is an unbounded range it only works for arrays
2439 if (!root_compiler_type_info.Test(eTypeIsArray)) {
2441 ValueObject::eExpressionPathScanEndReasonEmptyRangeNotAllowed;
2442 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2444 } else // even if something follows, we cannot expand unbounded ranges,
2445 // just let the caller do it
2448 ValueObject::eExpressionPathScanEndReasonArrayRangeOperatorMet;
2450 ValueObject::eExpressionPathEndResultTypeUnboundedRange;
2455 size_t close_bracket_position = temp_expression.find(']', 1);
2456 if (close_bracket_position ==
2457 llvm::StringRef::npos) // if there is no ], this is a syntax error
2460 ValueObject::eExpressionPathScanEndReasonUnexpectedSymbol;
2461 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2465 llvm::StringRef bracket_expr =
2466 temp_expression.slice(1, close_bracket_position);
2468 // If this was an empty expression it would have been caught by the if
2470 assert(!bracket_expr.empty());
2472 if (!bracket_expr.contains('-')) {
2473 // if no separator, this is of the form [N]. Note that this cannot be
2474 // an unbounded range of the form [], because that case was handled
2475 // above with an unconditional return.
2476 unsigned long index = 0;
2477 if (bracket_expr.getAsInteger(0, index)) {
2479 ValueObject::eExpressionPathScanEndReasonUnexpectedSymbol;
2480 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2484 // from here on we do have a valid index
2485 if (root_compiler_type_info.Test(eTypeIsArray)) {
2486 ValueObjectSP child_valobj_sp = root->GetChildAtIndex(index, true);
2487 if (!child_valobj_sp)
2488 child_valobj_sp = root->GetSyntheticArrayMember(index, true);
2489 if (!child_valobj_sp)
2490 if (root->HasSyntheticValue() &&
2491 root->GetSyntheticValue()->GetNumChildren() > index)
2493 root->GetSyntheticValue()->GetChildAtIndex(index, true);
2494 if (child_valobj_sp) {
2495 root = child_valobj_sp;
2497 temp_expression.substr(close_bracket_position + 1); // skip ]
2498 *final_result = ValueObject::eExpressionPathEndResultTypePlain;
2502 ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2503 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2506 } else if (root_compiler_type_info.Test(eTypeIsPointer)) {
2509 eExpressionPathAftermathDereference && // if this is a
2518 pointee_compiler_type_info.Test(eTypeIsScalar)) {
2520 root = root->Dereference(error);
2521 if (error.Fail() || !root) {
2523 ValueObject::eExpressionPathScanEndReasonDereferencingFailed;
2524 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2527 *what_next = eExpressionPathAftermathNothing;
2531 if (root->GetCompilerType().GetMinimumLanguage() ==
2532 eLanguageTypeObjC &&
2533 pointee_compiler_type_info.AllClear(eTypeIsPointer) &&
2534 root->HasSyntheticValue() &&
2535 (options.m_synthetic_children_traversal ==
2536 GetValueForExpressionPathOptions::
2537 SyntheticChildrenTraversal::ToSynthetic ||
2538 options.m_synthetic_children_traversal ==
2539 GetValueForExpressionPathOptions::
2540 SyntheticChildrenTraversal::Both)) {
2541 root = root->GetSyntheticValue()->GetChildAtIndex(index, true);
2543 root = root->GetSyntheticArrayMember(index, true);
2546 ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2547 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2551 temp_expression.substr(close_bracket_position + 1); // skip ]
2552 *final_result = ValueObject::eExpressionPathEndResultTypePlain;
2556 } else if (root_compiler_type_info.Test(eTypeIsScalar)) {
2557 root = root->GetSyntheticBitFieldChild(index, index, true);
2560 ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2561 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2563 } else // we do not know how to expand members of bitfields, so we
2564 // just return and let the caller do any further processing
2566 *reason_to_stop = ValueObject::
2567 eExpressionPathScanEndReasonBitfieldRangeOperatorMet;
2568 *final_result = ValueObject::eExpressionPathEndResultTypeBitfield;
2571 } else if (root_compiler_type_info.Test(eTypeIsVector)) {
2572 root = root->GetChildAtIndex(index, true);
2575 ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2576 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2577 return ValueObjectSP();
2580 temp_expression.substr(close_bracket_position + 1); // skip ]
2581 *final_result = ValueObject::eExpressionPathEndResultTypePlain;
2584 } else if (options.m_synthetic_children_traversal ==
2585 GetValueForExpressionPathOptions::
2586 SyntheticChildrenTraversal::ToSynthetic ||
2587 options.m_synthetic_children_traversal ==
2588 GetValueForExpressionPathOptions::
2589 SyntheticChildrenTraversal::Both) {
2590 if (root->HasSyntheticValue())
2591 root = root->GetSyntheticValue();
2592 else if (!root->IsSynthetic()) {
2594 ValueObject::eExpressionPathScanEndReasonSyntheticValueMissing;
2595 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2598 // if we are here, then root itself is a synthetic VO.. should be
2603 ValueObject::eExpressionPathScanEndReasonSyntheticValueMissing;
2604 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2607 root = root->GetChildAtIndex(index, true);
2610 ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2611 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2615 temp_expression.substr(close_bracket_position + 1); // skip ]
2616 *final_result = ValueObject::eExpressionPathEndResultTypePlain;
2621 ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2622 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2626 // we have a low and a high index
2627 llvm::StringRef sleft, sright;
2628 unsigned long low_index, high_index;
2629 std::tie(sleft, sright) = bracket_expr.split('-');
2630 if (sleft.getAsInteger(0, low_index) ||
2631 sright.getAsInteger(0, high_index)) {
2633 ValueObject::eExpressionPathScanEndReasonUnexpectedSymbol;
2634 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2638 if (low_index > high_index) // swap indices if required
2639 std::swap(low_index, high_index);
2641 if (root_compiler_type_info.Test(
2642 eTypeIsScalar)) // expansion only works for scalars
2644 root = root->GetSyntheticBitFieldChild(low_index, high_index, true);
2647 ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2648 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2651 *reason_to_stop = ValueObject::
2652 eExpressionPathScanEndReasonBitfieldRangeOperatorMet;
2653 *final_result = ValueObject::eExpressionPathEndResultTypeBitfield;
2656 } else if (root_compiler_type_info.Test(
2657 eTypeIsPointer) && // if this is a ptr-to-scalar, I am
2658 // accessing it by index and I would
2659 // have deref'ed anyway, then do it
2660 // now and use this as a bitfield
2662 ValueObject::eExpressionPathAftermathDereference &&
2663 pointee_compiler_type_info.Test(eTypeIsScalar)) {
2665 root = root->Dereference(error);
2666 if (error.Fail() || !root) {
2668 ValueObject::eExpressionPathScanEndReasonDereferencingFailed;
2669 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2672 *what_next = ValueObject::eExpressionPathAftermathNothing;
2677 ValueObject::eExpressionPathScanEndReasonArrayRangeOperatorMet;
2678 *final_result = ValueObject::eExpressionPathEndResultTypeBoundedRange;
2684 default: // some non-separator is in the way
2687 ValueObject::eExpressionPathScanEndReasonUnexpectedSymbol;
2688 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2695 void ValueObject::LogValueObject(Log *log) {
2697 return LogValueObject(log, DumpValueObjectOptions(*this));
2700 void ValueObject::LogValueObject(Log *log,
2701 const DumpValueObjectOptions &options) {
2706 log->PutCString(s.GetData());
2710 void ValueObject::Dump(Stream &s) { Dump(s, DumpValueObjectOptions(*this)); }
2712 void ValueObject::Dump(Stream &s, const DumpValueObjectOptions &options) {
2713 ValueObjectPrinter printer(this, &s, options);
2714 printer.PrintValueObject();
2717 ValueObjectSP ValueObject::CreateConstantValue(ConstString name) {
2718 ValueObjectSP valobj_sp;
2720 if (UpdateValueIfNeeded(false) && m_error.Success()) {
2721 ExecutionContext exe_ctx(GetExecutionContextRef());
2724 data.SetByteOrder(m_data.GetByteOrder());
2725 data.SetAddressByteSize(m_data.GetAddressByteSize());
2728 Value v(Scalar(GetValueAsUnsigned(UINT64_MAX)));
2729 m_error = v.GetValueAsData(&exe_ctx, data, 0, GetModule().get());
2731 m_error = m_value.GetValueAsData(&exe_ctx, data, 0, GetModule().get());
2733 valobj_sp = ValueObjectConstResult::Create(
2734 exe_ctx.GetBestExecutionContextScope(), GetCompilerType(), name, data,
2739 ExecutionContext exe_ctx(GetExecutionContextRef());
2740 valobj_sp = ValueObjectConstResult::Create(
2741 exe_ctx.GetBestExecutionContextScope(), m_error);
2746 ValueObjectSP ValueObject::GetQualifiedRepresentationIfAvailable(
2747 lldb::DynamicValueType dynValue, bool synthValue) {
2748 ValueObjectSP result_sp(GetSP());
2751 case lldb::eDynamicCanRunTarget:
2752 case lldb::eDynamicDontRunTarget: {
2753 if (!result_sp->IsDynamic()) {
2754 if (result_sp->GetDynamicValue(dynValue))
2755 result_sp = result_sp->GetDynamicValue(dynValue);
2758 case lldb::eNoDynamicValues: {
2759 if (result_sp->IsDynamic()) {
2760 if (result_sp->GetStaticValue())
2761 result_sp = result_sp->GetStaticValue();
2767 if (!result_sp->IsSynthetic()) {
2768 if (result_sp->GetSyntheticValue())
2769 result_sp = result_sp->GetSyntheticValue();
2772 if (result_sp->IsSynthetic()) {
2773 if (result_sp->GetNonSyntheticValue())
2774 result_sp = result_sp->GetNonSyntheticValue();
2781 ValueObjectSP ValueObject::Dereference(Status &error) {
2783 return m_deref_valobj->GetSP();
2785 const bool is_pointer_or_reference_type = IsPointerOrReferenceType();
2786 if (is_pointer_or_reference_type) {
2787 bool omit_empty_base_classes = true;
2788 bool ignore_array_bounds = false;
2790 std::string child_name_str;
2791 uint32_t child_byte_size = 0;
2792 int32_t child_byte_offset = 0;
2793 uint32_t child_bitfield_bit_size = 0;
2794 uint32_t child_bitfield_bit_offset = 0;
2795 bool child_is_base_class = false;
2796 bool child_is_deref_of_parent = false;
2797 const bool transparent_pointers = false;
2798 CompilerType compiler_type = GetCompilerType();
2799 CompilerType child_compiler_type;
2800 uint64_t language_flags;
2802 ExecutionContext exe_ctx(GetExecutionContextRef());
2804 child_compiler_type = compiler_type.GetChildCompilerTypeAtIndex(
2805 &exe_ctx, 0, transparent_pointers, omit_empty_base_classes,
2806 ignore_array_bounds, child_name_str, child_byte_size, child_byte_offset,
2807 child_bitfield_bit_size, child_bitfield_bit_offset, child_is_base_class,
2808 child_is_deref_of_parent, this, language_flags);
2809 if (child_compiler_type && child_byte_size) {
2810 ConstString child_name;
2811 if (!child_name_str.empty())
2812 child_name.SetCString(child_name_str.c_str());
2814 m_deref_valobj = new ValueObjectChild(
2815 *this, child_compiler_type, child_name, child_byte_size,
2816 child_byte_offset, child_bitfield_bit_size, child_bitfield_bit_offset,
2817 child_is_base_class, child_is_deref_of_parent, eAddressTypeInvalid,
2820 } else if (HasSyntheticValue()) {
2823 ->GetChildMemberWithName(ConstString("$$dereference$$"), true)
2827 if (m_deref_valobj) {
2829 return m_deref_valobj->GetSP();
2832 GetExpressionPath(strm, true);
2834 if (is_pointer_or_reference_type)
2835 error.SetErrorStringWithFormat("dereference failed: (%s) %s",
2836 GetTypeName().AsCString("<invalid type>"),
2839 error.SetErrorStringWithFormat("not a pointer or reference type: (%s) %s",
2840 GetTypeName().AsCString("<invalid type>"),
2842 return ValueObjectSP();
2846 ValueObjectSP ValueObject::AddressOf(Status &error) {
2847 if (m_addr_of_valobj_sp)
2848 return m_addr_of_valobj_sp;
2850 AddressType address_type = eAddressTypeInvalid;
2851 const bool scalar_is_load_address = false;
2852 addr_t addr = GetAddressOf(scalar_is_load_address, &address_type);
2854 if (addr != LLDB_INVALID_ADDRESS && address_type != eAddressTypeHost) {
2855 switch (address_type) {
2856 case eAddressTypeInvalid: {
2857 StreamString expr_path_strm;
2858 GetExpressionPath(expr_path_strm, true);
2859 error.SetErrorStringWithFormat("'%s' is not in memory",
2860 expr_path_strm.GetData());
2863 case eAddressTypeFile:
2864 case eAddressTypeLoad: {
2865 CompilerType compiler_type = GetCompilerType();
2866 if (compiler_type) {
2867 std::string name(1, '&');
2868 name.append(m_name.AsCString(""));
2869 ExecutionContext exe_ctx(GetExecutionContextRef());
2870 m_addr_of_valobj_sp = ValueObjectConstResult::Create(
2871 exe_ctx.GetBestExecutionContextScope(),
2872 compiler_type.GetPointerType(), ConstString(name.c_str()), addr,
2873 eAddressTypeInvalid, m_data.GetAddressByteSize());
2880 StreamString expr_path_strm;
2881 GetExpressionPath(expr_path_strm, true);
2882 error.SetErrorStringWithFormat("'%s' doesn't have a valid address",
2883 expr_path_strm.GetData());
2886 return m_addr_of_valobj_sp;
2889 ValueObjectSP ValueObject::Cast(const CompilerType &compiler_type) {
2890 return ValueObjectCast::Create(*this, GetName(), compiler_type);
2893 lldb::ValueObjectSP ValueObject::Clone(ConstString new_name) {
2894 return ValueObjectCast::Create(*this, new_name, GetCompilerType());
2897 ValueObjectSP ValueObject::CastPointerType(const char *name,
2898 CompilerType &compiler_type) {
2899 ValueObjectSP valobj_sp;
2900 AddressType address_type;
2901 addr_t ptr_value = GetPointerValue(&address_type);
2903 if (ptr_value != LLDB_INVALID_ADDRESS) {
2904 Address ptr_addr(ptr_value);
2905 ExecutionContext exe_ctx(GetExecutionContextRef());
2906 valobj_sp = ValueObjectMemory::Create(
2907 exe_ctx.GetBestExecutionContextScope(), name, ptr_addr, compiler_type);
2912 ValueObjectSP ValueObject::CastPointerType(const char *name, TypeSP &type_sp) {
2913 ValueObjectSP valobj_sp;
2914 AddressType address_type;
2915 addr_t ptr_value = GetPointerValue(&address_type);
2917 if (ptr_value != LLDB_INVALID_ADDRESS) {
2918 Address ptr_addr(ptr_value);
2919 ExecutionContext exe_ctx(GetExecutionContextRef());
2920 valobj_sp = ValueObjectMemory::Create(
2921 exe_ctx.GetBestExecutionContextScope(), name, ptr_addr, type_sp);
2926 ValueObject::EvaluationPoint::EvaluationPoint()
2927 : m_mod_id(), m_exe_ctx_ref(), m_needs_update(true) {}
2929 ValueObject::EvaluationPoint::EvaluationPoint(ExecutionContextScope *exe_scope,
2931 : m_mod_id(), m_exe_ctx_ref(), m_needs_update(true) {
2932 ExecutionContext exe_ctx(exe_scope);
2933 TargetSP target_sp(exe_ctx.GetTargetSP());
2935 m_exe_ctx_ref.SetTargetSP(target_sp);
2936 ProcessSP process_sp(exe_ctx.GetProcessSP());
2938 process_sp = target_sp->GetProcessSP();
2941 m_mod_id = process_sp->GetModID();
2942 m_exe_ctx_ref.SetProcessSP(process_sp);
2944 ThreadSP thread_sp(exe_ctx.GetThreadSP());
2948 thread_sp = process_sp->GetThreadList().GetSelectedThread();
2952 m_exe_ctx_ref.SetThreadSP(thread_sp);
2954 StackFrameSP frame_sp(exe_ctx.GetFrameSP());
2957 frame_sp = thread_sp->GetSelectedFrame();
2960 m_exe_ctx_ref.SetFrameSP(frame_sp);
2966 ValueObject::EvaluationPoint::EvaluationPoint(
2967 const ValueObject::EvaluationPoint &rhs)
2968 : m_mod_id(), m_exe_ctx_ref(rhs.m_exe_ctx_ref), m_needs_update(true) {}
2970 ValueObject::EvaluationPoint::~EvaluationPoint() {}
2972 // This function checks the EvaluationPoint against the current process state.
2973 // If the current state matches the evaluation point, or the evaluation point
2974 // is already invalid, then we return false, meaning "no change". If the
2975 // current state is different, we update our state, and return true meaning
2976 // "yes, change". If we did see a change, we also set m_needs_update to true,
2977 // so future calls to NeedsUpdate will return true. exe_scope will be set to
2978 // the current execution context scope.
2980 bool ValueObject::EvaluationPoint::SyncWithProcessState(
2981 bool accept_invalid_exe_ctx) {
2982 // Start with the target, if it is NULL, then we're obviously not going to
2984 const bool thread_and_frame_only_if_stopped = true;
2985 ExecutionContext exe_ctx(
2986 m_exe_ctx_ref.Lock(thread_and_frame_only_if_stopped));
2988 if (exe_ctx.GetTargetPtr() == nullptr)
2991 // If we don't have a process nothing can change.
2992 Process *process = exe_ctx.GetProcessPtr();
2993 if (process == nullptr)
2996 // If our stop id is the current stop ID, nothing has changed:
2997 ProcessModID current_mod_id = process->GetModID();
2999 // If the current stop id is 0, either we haven't run yet, or the process
3000 // state has been cleared. In either case, we aren't going to be able to sync
3001 // with the process state.
3002 if (current_mod_id.GetStopID() == 0)
3005 bool changed = false;
3006 const bool was_valid = m_mod_id.IsValid();
3008 if (m_mod_id == current_mod_id) {
3009 // Everything is already up to date in this object, no need to update the
3010 // execution context scope.
3013 m_mod_id = current_mod_id;
3014 m_needs_update = true;
3019 // Now re-look up the thread and frame in case the underlying objects have
3020 // gone away & been recreated. That way we'll be sure to return a valid
3021 // exe_scope. If we used to have a thread or a frame but can't find it
3022 // anymore, then mark ourselves as invalid.
3024 if (!accept_invalid_exe_ctx) {
3025 if (m_exe_ctx_ref.HasThreadRef()) {
3026 ThreadSP thread_sp(m_exe_ctx_ref.GetThreadSP());
3028 if (m_exe_ctx_ref.HasFrameRef()) {
3029 StackFrameSP frame_sp(m_exe_ctx_ref.GetFrameSP());
3031 // We used to have a frame, but now it is gone
3033 changed = was_valid;
3037 // We used to have a thread, but now it is gone
3039 changed = was_valid;
3047 void ValueObject::EvaluationPoint::SetUpdated() {
3048 ProcessSP process_sp(m_exe_ctx_ref.GetProcessSP());
3050 m_mod_id = process_sp->GetModID();
3051 m_needs_update = false;
3054 void ValueObject::ClearUserVisibleData(uint32_t clear_mask) {
3055 if ((clear_mask & eClearUserVisibleDataItemsValue) ==
3056 eClearUserVisibleDataItemsValue)
3057 m_value_str.clear();
3059 if ((clear_mask & eClearUserVisibleDataItemsLocation) ==
3060 eClearUserVisibleDataItemsLocation)
3061 m_location_str.clear();
3063 if ((clear_mask & eClearUserVisibleDataItemsSummary) ==
3064 eClearUserVisibleDataItemsSummary)
3065 m_summary_str.clear();
3067 if ((clear_mask & eClearUserVisibleDataItemsDescription) ==
3068 eClearUserVisibleDataItemsDescription)
3069 m_object_desc_str.clear();
3071 if ((clear_mask & eClearUserVisibleDataItemsSyntheticChildren) ==
3072 eClearUserVisibleDataItemsSyntheticChildren) {
3073 if (m_synthetic_value)
3074 m_synthetic_value = nullptr;
3077 if ((clear_mask & eClearUserVisibleDataItemsValidator) ==
3078 eClearUserVisibleDataItemsValidator)
3079 m_validation_result.reset();
3082 SymbolContextScope *ValueObject::GetSymbolContextScope() {
3084 if (!m_parent->IsPointerOrReferenceType())
3085 return m_parent->GetSymbolContextScope();
3091 ValueObject::CreateValueObjectFromExpression(llvm::StringRef name,
3092 llvm::StringRef expression,
3093 const ExecutionContext &exe_ctx) {
3094 return CreateValueObjectFromExpression(name, expression, exe_ctx,
3095 EvaluateExpressionOptions());
3098 lldb::ValueObjectSP ValueObject::CreateValueObjectFromExpression(
3099 llvm::StringRef name, llvm::StringRef expression,
3100 const ExecutionContext &exe_ctx, const EvaluateExpressionOptions &options) {
3101 lldb::ValueObjectSP retval_sp;
3102 lldb::TargetSP target_sp(exe_ctx.GetTargetSP());
3105 if (expression.empty())
3107 target_sp->EvaluateExpression(expression, exe_ctx.GetFrameSP().get(),
3108 retval_sp, options);
3109 if (retval_sp && !name.empty())
3110 retval_sp->SetName(ConstString(name));
3114 lldb::ValueObjectSP ValueObject::CreateValueObjectFromAddress(
3115 llvm::StringRef name, uint64_t address, const ExecutionContext &exe_ctx,
3116 CompilerType type) {
3118 CompilerType pointer_type(type.GetPointerType());
3120 lldb::DataBufferSP buffer(
3121 new lldb_private::DataBufferHeap(&address, sizeof(lldb::addr_t)));
3122 lldb::ValueObjectSP ptr_result_valobj_sp(ValueObjectConstResult::Create(
3123 exe_ctx.GetBestExecutionContextScope(), pointer_type,
3124 ConstString(name), buffer, exe_ctx.GetByteOrder(),
3125 exe_ctx.GetAddressByteSize()));
3126 if (ptr_result_valobj_sp) {
3127 ptr_result_valobj_sp->GetValue().SetValueType(
3128 Value::eValueTypeLoadAddress);
3130 ptr_result_valobj_sp = ptr_result_valobj_sp->Dereference(err);
3131 if (ptr_result_valobj_sp && !name.empty())
3132 ptr_result_valobj_sp->SetName(ConstString(name));
3134 return ptr_result_valobj_sp;
3137 return lldb::ValueObjectSP();
3140 lldb::ValueObjectSP ValueObject::CreateValueObjectFromData(
3141 llvm::StringRef name, const DataExtractor &data,
3142 const ExecutionContext &exe_ctx, CompilerType type) {
3143 lldb::ValueObjectSP new_value_sp;
3144 new_value_sp = ValueObjectConstResult::Create(
3145 exe_ctx.GetBestExecutionContextScope(), type, ConstString(name), data,
3146 LLDB_INVALID_ADDRESS);
3147 new_value_sp->SetAddressTypeOfChildren(eAddressTypeLoad);
3148 if (new_value_sp && !name.empty())
3149 new_value_sp->SetName(ConstString(name));
3150 return new_value_sp;
3153 ModuleSP ValueObject::GetModule() {
3154 ValueObject *root(GetRoot());
3156 return root->GetModule();
3157 return lldb::ModuleSP();
3160 ValueObject *ValueObject::GetRoot() {
3163 return (m_root = FollowParentChain([](ValueObject *vo) -> bool {
3164 return (vo->m_parent != nullptr);
3169 ValueObject::FollowParentChain(std::function<bool(ValueObject *)> f) {
3170 ValueObject *vo = this;
3179 AddressType ValueObject::GetAddressTypeOfChildren() {
3180 if (m_address_type_of_ptr_or_ref_children == eAddressTypeInvalid) {
3181 ValueObject *root(GetRoot());
3183 return root->GetAddressTypeOfChildren();
3185 return m_address_type_of_ptr_or_ref_children;
3188 lldb::DynamicValueType ValueObject::GetDynamicValueType() {
3189 ValueObject *with_dv_info = this;
3190 while (with_dv_info) {
3191 if (with_dv_info->HasDynamicValueTypeInfo())
3192 return with_dv_info->GetDynamicValueTypeImpl();
3193 with_dv_info = with_dv_info->m_parent;
3195 return lldb::eNoDynamicValues;
3198 lldb::Format ValueObject::GetFormat() const {
3199 const ValueObject *with_fmt_info = this;
3200 while (with_fmt_info) {
3201 if (with_fmt_info->m_format != lldb::eFormatDefault)
3202 return with_fmt_info->m_format;
3203 with_fmt_info = with_fmt_info->m_parent;
3208 lldb::LanguageType ValueObject::GetPreferredDisplayLanguage() {
3209 lldb::LanguageType type = m_preferred_display_language;
3210 if (m_preferred_display_language == lldb::eLanguageTypeUnknown) {
3212 if (GetRoot() == this) {
3213 if (StackFrameSP frame_sp = GetFrameSP()) {
3214 const SymbolContext &sc(
3215 frame_sp->GetSymbolContext(eSymbolContextCompUnit));
3216 if (CompileUnit *cu = sc.comp_unit)
3217 type = cu->GetLanguage();
3220 type = GetRoot()->GetPreferredDisplayLanguage();
3224 return (m_preferred_display_language = type); // only compute it once
3227 void ValueObject::SetPreferredDisplayLanguage(lldb::LanguageType lt) {
3228 m_preferred_display_language = lt;
3231 void ValueObject::SetPreferredDisplayLanguageIfNeeded(lldb::LanguageType lt) {
3232 if (m_preferred_display_language == lldb::eLanguageTypeUnknown)
3233 SetPreferredDisplayLanguage(lt);
3236 bool ValueObject::CanProvideValue() {
3237 // we need to support invalid types as providers of values because some bare-
3238 // board debugging scenarios have no notion of types, but still manage to
3239 // have raw numeric values for things like registers. sigh.
3240 const CompilerType &type(GetCompilerType());
3241 return (!type.IsValid()) || (0 != (type.GetTypeInfo() & eTypeHasValue));
3244 bool ValueObject::IsChecksumEmpty() { return m_value_checksum.empty(); }
3246 ValueObjectSP ValueObject::Persist() {
3247 if (!UpdateValueIfNeeded())
3250 TargetSP target_sp(GetTargetSP());
3254 PersistentExpressionState *persistent_state =
3255 target_sp->GetPersistentExpressionStateForLanguage(
3256 GetPreferredDisplayLanguage());
3258 if (!persistent_state)
3261 auto prefix = persistent_state->GetPersistentVariablePrefix();
3263 persistent_state->GetNextPersistentVariableName(*target_sp, prefix);
3265 ValueObjectSP const_result_sp =
3266 ValueObjectConstResult::Create(target_sp.get(), GetValue(), name);
3268 ExpressionVariableSP clang_var_sp =
3269 persistent_state->CreatePersistentVariable(const_result_sp);
3270 clang_var_sp->m_live_sp = clang_var_sp->m_frozen_sp;
3271 clang_var_sp->m_flags |= ExpressionVariable::EVIsProgramReference;
3273 return clang_var_sp->GetValueObject();
3276 bool ValueObject::IsSyntheticChildrenGenerated() {
3277 return m_is_synthetic_children_generated;
3280 void ValueObject::SetSyntheticChildrenGenerated(bool b) {
3281 m_is_synthetic_children_generated = b;
3284 uint64_t ValueObject::GetLanguageFlags() { return m_language_flags; }
3286 void ValueObject::SetLanguageFlags(uint64_t flags) { m_language_flags = flags; }
3288 ValueObjectManager::ValueObjectManager(lldb::ValueObjectSP in_valobj_sp,
3289 lldb::DynamicValueType use_dynamic,
3290 bool use_synthetic) : m_root_valobj_sp(),
3291 m_user_valobj_sp(), m_use_dynamic(use_dynamic), m_stop_id(UINT32_MAX),
3292 m_use_synthetic(use_synthetic) {
3295 // If the user passes in a value object that is dynamic or synthetic, then
3296 // water it down to the static type.
3297 m_root_valobj_sp = in_valobj_sp->GetQualifiedRepresentationIfAvailable(lldb::eNoDynamicValues, false);
3300 bool ValueObjectManager::IsValid() const {
3301 if (!m_root_valobj_sp)
3303 lldb::TargetSP target_sp = GetTargetSP();
3305 return target_sp->IsValid();
3309 lldb::ValueObjectSP ValueObjectManager::GetSP() {
3310 lldb::ProcessSP process_sp = GetProcessSP();
3312 return lldb::ValueObjectSP();
3314 const uint32_t current_stop_id = process_sp->GetLastNaturalStopID();
3315 if (current_stop_id == m_stop_id)
3316 return m_user_valobj_sp;
3318 m_stop_id = current_stop_id;
3320 if (!m_root_valobj_sp) {
3321 m_user_valobj_sp.reset();
3322 return m_root_valobj_sp;
3325 m_user_valobj_sp = m_root_valobj_sp;
3327 if (m_use_dynamic != lldb::eNoDynamicValues) {
3328 lldb::ValueObjectSP dynamic_sp = m_user_valobj_sp->GetDynamicValue(m_use_dynamic);
3330 m_user_valobj_sp = dynamic_sp;
3333 if (m_use_synthetic) {
3334 lldb::ValueObjectSP synthetic_sp = m_user_valobj_sp->GetSyntheticValue(m_use_synthetic);
3336 m_user_valobj_sp = synthetic_sp;
3339 return m_user_valobj_sp;
3342 void ValueObjectManager::SetUseDynamic(lldb::DynamicValueType use_dynamic) {
3343 if (use_dynamic != m_use_dynamic) {
3344 m_use_dynamic = use_dynamic;
3345 m_user_valobj_sp.reset();
3346 m_stop_id = UINT32_MAX;
3350 void ValueObjectManager::SetUseSynthetic(bool use_synthetic) {
3351 if (m_use_synthetic != use_synthetic) {
3352 m_use_synthetic = use_synthetic;
3353 m_user_valobj_sp.reset();
3354 m_stop_id = UINT32_MAX;
3358 lldb::TargetSP ValueObjectManager::GetTargetSP() const {
3359 if (!m_root_valobj_sp)
3360 return m_root_valobj_sp->GetTargetSP();
3361 return lldb::TargetSP();
3364 lldb::ProcessSP ValueObjectManager::GetProcessSP() const {
3365 if (m_root_valobj_sp)
3366 return m_root_valobj_sp->GetProcessSP();
3367 return lldb::ProcessSP();
3370 lldb::ThreadSP ValueObjectManager::GetThreadSP() const {
3371 if (m_root_valobj_sp)
3372 return m_root_valobj_sp->GetThreadSP();
3373 return lldb::ThreadSP();
3376 lldb::StackFrameSP ValueObjectManager::GetFrameSP() const {
3377 if (m_root_valobj_sp)
3378 return m_root_valobj_sp->GetFrameSP();
3379 return lldb::StackFrameSP();