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