LLDB mainline
ValueObject.cpp
Go to the documentation of this file.
1//===-- ValueObject.cpp ---------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10
11#include "lldb/Core/Address.h"
13#include "lldb/Core/Module.h"
22#include "lldb/Host/Config.h"
26#include "lldb/Symbol/Type.h"
28#include "lldb/Target/ABI.h"
32#include "lldb/Target/Process.h"
34#include "lldb/Target/Target.h"
35#include "lldb/Target/Thread.h"
39#include "lldb/Utility/Flags.h"
41#include "lldb/Utility/Log.h"
42#include "lldb/Utility/Scalar.h"
43#include "lldb/Utility/Stream.h"
53
54#include "llvm/Support/Compiler.h"
55
56#include <algorithm>
57#include <atomic>
58#include <cstdint>
59#include <cstdlib>
60#include <memory>
61#include <optional>
62#include <tuple>
63
64#include <cassert>
65#include <cinttypes>
66#include <cstdio>
67#include <cstring>
68
69namespace lldb_private {
71}
72namespace lldb_private {
74}
75
76using namespace lldb;
77using namespace lldb_private;
78
79static std::atomic<user_id_t> g_value_obj_uid{0};
80
81// FIXME: this will return true for vector types whose elements
82// are floats. Audit all usages of this function and call
83// IsFloatingPointType() instead if vectors of floats aren't intended
84// to be supported.
86 return ct.GetTypeInfo() & eTypeIsFloat;
87}
88
89// ValueObject constructor
91 : m_parent(&parent), m_update_point(parent.GetUpdatePoint()),
93 m_flags.m_is_synthetic_children_generated =
95 m_data.SetByteOrder(parent.GetDataExtractor().GetByteOrder());
96 m_data.SetAddressByteSize(parent.GetDataExtractor().GetAddressByteSize());
97 m_manager->ManageObject(this);
98}
99
100// ValueObject constructor
102 ValueObjectManager &manager,
103 AddressType child_ptr_or_ref_addr_type)
104 : m_update_point(exe_scope), m_manager(&manager),
105 m_address_type_of_ptr_or_ref_children(child_ptr_or_ref_addr_type),
107 if (exe_scope) {
108 TargetSP target_sp(exe_scope->CalculateTarget());
109 if (target_sp) {
110 const ArchSpec &arch = target_sp->GetArchitecture();
111 m_data.SetByteOrder(arch.GetByteOrder());
112 m_data.SetAddressByteSize(arch.GetAddressByteSize());
113 }
114 }
115 m_manager->ManageObject(this);
116}
117
118// Destructor
119ValueObject::~ValueObject() = default;
120
121bool ValueObject::UpdateValueIfNeeded(bool update_format) {
122
123 bool did_change_formats = false;
124
125 if (update_format)
126 did_change_formats = UpdateFormatsIfNeeded();
127
128 // If this is a constant value, then our success is predicated on whether we
129 // have an error or not
130 if (GetIsConstant()) {
131 // if you are constant, things might still have changed behind your back
132 // (e.g. you are a frozen object and things have changed deeper than you
133 // cared to freeze-dry yourself) in this case, your value has not changed,
134 // but "computed" entries might have, so you might now have a different
135 // summary, or a different object description. clear these so we will
136 // recompute them
137 if (update_format && !did_change_formats)
140 return m_error.Success();
141 }
142
143 bool first_update = IsChecksumEmpty();
144
145 if (NeedsUpdating()) {
146 m_update_point.SetUpdated();
147
148 // Save the old value using swap to avoid a string copy which also will
149 // clear our m_value_str
150 if (m_value_str.empty()) {
151 m_flags.m_old_value_valid = false;
152 } else {
153 m_flags.m_old_value_valid = true;
156 }
157
159
160 if (IsInScope()) {
161 const bool value_was_valid = GetValueIsValid();
162 SetValueDidChange(false);
163
164 m_error.Clear();
165
166 // Call the pure virtual function to update the value
167
168 bool need_compare_checksums = false;
169 llvm::SmallVector<uint8_t, 16> old_checksum;
170
171 if (!first_update && CanProvideValue()) {
172 need_compare_checksums = true;
173 old_checksum.resize(m_value_checksum.size());
174 std::copy(m_value_checksum.begin(), m_value_checksum.end(),
175 old_checksum.begin());
176 }
177
178 bool success = UpdateValue();
179
180 SetValueIsValid(success);
181
182 if (success) {
184 const uint64_t max_checksum_size = 128;
185 m_data.Checksum(m_value_checksum, max_checksum_size);
186 } else {
187 need_compare_checksums = false;
188 m_value_checksum.clear();
189 }
190
191 assert(!need_compare_checksums ||
192 (!old_checksum.empty() && !m_value_checksum.empty()));
193
194 if (first_update)
195 SetValueDidChange(false);
196 else if (!m_flags.m_value_did_change && !success) {
197 // The value wasn't gotten successfully, so we mark this as changed if
198 // the value used to be valid and now isn't
199 SetValueDidChange(value_was_valid);
200 } else if (need_compare_checksums) {
201 SetValueDidChange(memcmp(&old_checksum[0], &m_value_checksum[0],
202 m_value_checksum.size()));
203 }
204
205 } else {
206 m_error = Status::FromErrorString("out of scope");
207 }
208 }
209 return m_error.Success();
210}
211
214 LLDB_LOGF(log,
215 "[%s %p] checking for FormatManager revisions. ValueObject "
216 "rev: %d - Global rev: %d",
217 GetName().GetCString(), static_cast<void *>(this),
220
221 bool any_change = false;
222
225 any_change = true;
226
232 }
233
234 return any_change;
235}
236
238 m_update_point.SetNeedsUpdate();
239 // We have to clear the value string here so ConstResult children will notice
240 // if their values are changed by hand (i.e. with SetValueAsCString).
242}
243
245 m_flags.m_children_count_valid = false;
246 m_flags.m_did_calculate_complete_objc_class_type = false;
252}
253
255 CompilerType compiler_type(GetCompilerTypeImpl());
256
257 if (m_flags.m_did_calculate_complete_objc_class_type) {
258 if (m_override_type.IsValid())
259 return m_override_type;
260 else
261 return compiler_type;
262 }
263
264 m_flags.m_did_calculate_complete_objc_class_type = true;
265
266 ProcessSP process_sp(
268
269 if (!process_sp)
270 return compiler_type;
271
272 if (auto *runtime =
273 process_sp->GetLanguageRuntime(GetObjectRuntimeLanguage())) {
274 if (std::optional<CompilerType> complete_type =
275 runtime->GetRuntimeType(compiler_type)) {
276 m_override_type = *complete_type;
277 if (m_override_type.IsValid())
278 return m_override_type;
279 }
280 }
281 return compiler_type;
282}
283
288
290 UpdateValueIfNeeded(false);
291 return m_error;
292}
293
295 const DataExtractor &data) {
296 if (UpdateValueIfNeeded(false)) {
297 if (m_location_str.empty()) {
298 StreamString sstr;
299
300 Value::ValueType value_type = value.GetValueType();
301
302 switch (value_type) {
304 m_location_str = "invalid";
305 break;
308 RegisterInfo *reg_info = value.GetRegisterInfo();
309 if (reg_info) {
310 if (reg_info->name)
311 m_location_str = reg_info->name;
312 else if (reg_info->alt_name)
313 m_location_str = reg_info->alt_name;
314 if (m_location_str.empty())
316 ? "vector"
317 : "scalar";
318 }
319 }
320 if (m_location_str.empty())
321 m_location_str = "scalar";
322 break;
323
327 uint32_t addr_nibble_size = data.GetAddressByteSize() * 2;
328 sstr.Printf("0x%*.*llx", addr_nibble_size, addr_nibble_size,
330 m_location_str = std::string(sstr.GetString());
331 } break;
332 }
333 }
334 }
335 return m_location_str.c_str();
336}
337
340 false)) // make sure that you are up to date before returning anything
341 {
343 Value tmp_value(m_value);
344 scalar = tmp_value.ResolveValue(&exe_ctx, GetModule().get());
345 if (scalar.IsValid()) {
346 const uint32_t bitfield_bit_size = GetBitfieldBitSize();
347 if (bitfield_bit_size)
348 return scalar.ExtractBitfield(bitfield_bit_size,
350 return true;
351 }
352 }
353 return false;
354}
355
358 LazyBool is_logical_true = language->IsLogicalTrue(*this, error);
359 switch (is_logical_true) {
360 case eLazyBoolYes:
361 case eLazyBoolNo:
362 return (is_logical_true == true);
364 break;
365 }
366 }
367
368 Scalar scalar_value;
369
370 if (!ResolveValue(scalar_value)) {
371 error = Status::FromErrorString("failed to get a scalar result");
372 return false;
373 }
374
375 bool ret;
376 ret = scalar_value.ULongLong(1) != 0;
377 error.Clear();
378 return ret;
379}
380
382 Target *target_ptr = GetTargetSP().get();
383 if (!target_ptr)
384 return {};
385
386 if (target_ptr->GetCheckValueObjectOwnership()) {
387 // Child value objects should always be owned by their parent's manager.
388 if (child && (child->GetManager() != GetManager())) {
390 "ValueObject: '{0}' not owned by its parent: '{1}'", child->GetName(),
391 GetName());
392 return ValueObjectConstResult::Create(target_ptr, std::move(error),
393 this->GetManager());
394 }
395 }
396 return {};
397}
398
399ValueObjectSP ValueObject::GetChildAtIndex(uint32_t idx, bool can_create) {
400 ValueObjectSP child_sp;
401 // We may need to update our value if we are dynamic
403 UpdateValueIfNeeded(false);
404 if (idx < GetNumChildrenIgnoringErrors()) {
405 // Check if we have already made the child value object?
406 if (can_create && !m_children.HasChildAtIndex(idx)) {
407 // No we haven't created the child at this index, so lets have our
408 // subclass do it and cache the result for quick future access.
409 m_children.SetChildAtIndex(idx, CreateChildAtIndex(idx));
410 }
411
412 ValueObject *child = m_children.GetChildAtIndex(idx);
413 if (child != nullptr)
414 return child->GetSP();
415 }
416 return child_sp;
417}
418
420ValueObject::GetChildAtNamePath(llvm::ArrayRef<llvm::StringRef> names) {
421 if (names.size() == 0)
422 return GetSP();
423 ValueObjectSP root(GetSP());
424 for (llvm::StringRef name : names) {
425 root = root->GetChildMemberWithName(name);
426 if (!root) {
427 return root;
428 }
429 }
430 return root;
431}
432
433llvm::Expected<size_t>
435 bool omit_empty_base_classes = true;
437 omit_empty_base_classes);
438}
439
441 bool can_create) {
442 // We may need to update our value if we are dynamic.
444 UpdateValueIfNeeded(false);
445
446 // When getting a child by name, it could be buried inside some base classes
447 // (which really aren't part of the expression path), so we need a vector of
448 // indexes that can get us down to the correct child.
449 std::vector<uint32_t> child_indexes;
450 bool omit_empty_base_classes = true;
451
452 if (!GetCompilerType().IsValid())
453 return ValueObjectSP();
454
455 const size_t num_child_indexes =
457 name, omit_empty_base_classes, child_indexes);
458 if (num_child_indexes == 0)
459 return nullptr;
460
461 ValueObjectSP child_sp = GetSP();
462 for (uint32_t idx : child_indexes)
463 if (child_sp)
464 child_sp = child_sp->GetChildAtIndex(idx, can_create);
465 return child_sp;
466}
467
468llvm::Expected<uint32_t> ValueObject::GetNumChildren(uint32_t max) {
470
471 if (max < UINT32_MAX) {
472 if (m_flags.m_children_count_valid) {
473 size_t children_count = m_children.GetChildrenCount();
474 return children_count <= max ? children_count : max;
475 } else
476 return CalculateNumChildren(max);
477 }
478
479 if (!m_flags.m_children_count_valid) {
480 auto num_children_or_err = CalculateNumChildren();
481 if (num_children_or_err)
482 SetNumChildren(*num_children_or_err);
483 else
484 return num_children_or_err;
485 }
486 return m_children.GetChildrenCount();
487}
488
490 auto value_or_err = GetNumChildren(max);
491 if (value_or_err)
492 return *value_or_err;
493 LLDB_LOG_ERRORV(GetLog(LLDBLog::DataFormatters), value_or_err.takeError(),
494 "{0}");
495 return 0;
496}
497
499 bool has_children = false;
500 const uint32_t type_info = GetTypeInfo();
501 if (type_info) {
502 if (type_info & (eTypeHasChildren | eTypeIsPointer | eTypeIsReference))
503 has_children = true;
504 } else {
505 has_children = GetNumChildrenIgnoringErrors() > 0;
506 }
507 return has_children;
508}
509
510// Should only be called by ValueObject::GetNumChildren()
511void ValueObject::SetNumChildren(uint32_t num_children) {
512 m_flags.m_children_count_valid = true;
513 m_children.SetChildrenCount(num_children);
514}
515
517 bool omit_empty_base_classes = true;
518 bool ignore_array_bounds = false;
519 std::string child_name;
520 uint32_t child_byte_size = 0;
521 int32_t child_byte_offset = 0;
522 uint32_t child_bitfield_bit_size = 0;
523 uint32_t child_bitfield_bit_offset = 0;
524 bool child_is_base_class = false;
525 bool child_is_deref_of_parent = false;
526 uint64_t language_flags = 0;
527 const bool transparent_pointers = true;
528
530
531 auto child_compiler_type_or_err =
533 &exe_ctx, idx, transparent_pointers, omit_empty_base_classes,
534 ignore_array_bounds, child_name, child_byte_size, child_byte_offset,
535 child_bitfield_bit_size, child_bitfield_bit_offset,
536 child_is_base_class, child_is_deref_of_parent, this, language_flags);
537 if (!child_compiler_type_or_err || !child_compiler_type_or_err->IsValid()) {
539 child_compiler_type_or_err.takeError(),
540 "could not find child: {0}");
541 return nullptr;
542 }
543
544 return new ValueObjectChild(
545 *this, *child_compiler_type_or_err, ConstString(child_name),
546 child_byte_size, child_byte_offset, child_bitfield_bit_size,
547 child_bitfield_bit_offset, child_is_base_class, child_is_deref_of_parent,
548 eAddressTypeInvalid, language_flags);
549}
550
552 bool omit_empty_base_classes = true;
553 bool ignore_array_bounds = true;
554 std::string child_name;
555 uint32_t child_byte_size = 0;
556 int32_t child_byte_offset = 0;
557 uint32_t child_bitfield_bit_size = 0;
558 uint32_t child_bitfield_bit_offset = 0;
559 bool child_is_base_class = false;
560 bool child_is_deref_of_parent = false;
561 uint64_t language_flags = 0;
562 const bool transparent_pointers = false;
563
565
566 auto child_compiler_type_or_err =
568 &exe_ctx, 0, transparent_pointers, omit_empty_base_classes,
569 ignore_array_bounds, child_name, child_byte_size, child_byte_offset,
570 child_bitfield_bit_size, child_bitfield_bit_offset,
571 child_is_base_class, child_is_deref_of_parent, this, language_flags);
572 if (!child_compiler_type_or_err) {
574 child_compiler_type_or_err.takeError(),
575 "could not find child: {0}");
576 return nullptr;
577 }
578
579 if (child_compiler_type_or_err->IsValid()) {
580 child_byte_offset += child_byte_size * idx;
581
582 return new ValueObjectChild(
583 *this, *child_compiler_type_or_err, ConstString(child_name),
584 child_byte_size, child_byte_offset, child_bitfield_bit_size,
585 child_bitfield_bit_offset, child_is_base_class,
586 child_is_deref_of_parent, eAddressTypeInvalid, language_flags);
587 }
588
589 // In case of an incomplete type, try to use the ValueObject's
590 // synthetic value to create the child ValueObject.
591 if (ValueObjectSP synth_valobj_sp = GetSyntheticValue())
592 return synth_valobj_sp->GetChildAtIndex(idx, /*can_create=*/true).get();
593
594 return nullptr;
595}
596
598 std::string &destination,
599 lldb::LanguageType lang) {
600 return GetSummaryAsCString(summary_ptr, destination,
601 TypeSummaryOptions().SetLanguage(lang));
602}
603
605 std::string &destination,
606 const TypeSummaryOptions &options) {
607 destination.clear();
608
609 // If we have a forcefully completed type, don't try and show a summary from
610 // a valid summary string or function because the type is not complete and
611 // no member variables or member functions will be available.
612 if (GetCompilerType().IsForcefullyCompleted()) {
613 destination = "<incomplete type>";
614 return true;
615 }
616
617 // ideally we would like to bail out if passing NULL, but if we do so we end
618 // up not providing the summary for function pointers anymore
619 if (/*summary_ptr == NULL ||*/ m_flags.m_is_getting_summary)
620 return false;
621
622 m_flags.m_is_getting_summary = true;
623
624 TypeSummaryOptions actual_options(options);
625
626 if (actual_options.GetLanguage() == lldb::eLanguageTypeUnknown)
628
629 // this is a hot path in code and we prefer to avoid setting this string all
630 // too often also clearing out other information that we might care to see in
631 // a crash log. might be useful in very specific situations though.
632 /*Host::SetCrashDescriptionWithFormat("Trying to fetch a summary for %s %s.
633 Summary provider's description is %s",
634 GetTypeName().GetCString(),
635 GetName().GetCString(),
636 summary_ptr->GetDescription().c_str());*/
637
638 if (UpdateValueIfNeeded(false) && summary_ptr) {
639 if (HasSyntheticValue())
640 m_synthetic_value->UpdateValueIfNeeded(); // the summary might depend on
641 // the synthetic children being
642 // up-to-date (e.g. ${svar%#})
643
644 if (TargetSP target_sp = GetExecutionContextRef().GetTargetSP()) {
645 SummaryStatisticsSP stats_sp =
646 target_sp->GetSummaryStatisticsCache()
647 .GetSummaryStatisticsForProvider(*summary_ptr);
648
649 // Construct RAII types to time and collect data on summary creation.
650 SummaryStatistics::SummaryInvocation invocation(stats_sp);
651 summary_ptr->FormatObject(this, destination, actual_options);
652 } else
653 summary_ptr->FormatObject(this, destination, actual_options);
654 }
655 m_flags.m_is_getting_summary = false;
656 return !destination.empty();
657}
658
660 if (UpdateValueIfNeeded(true) && m_summary_str.empty()) {
661 TypeSummaryOptions summary_options;
662 summary_options.SetLanguage(lang);
664 summary_options);
665 }
666 if (m_summary_str.empty())
667 return nullptr;
668 return m_summary_str.c_str();
669}
670
671bool ValueObject::GetSummaryAsCString(std::string &destination,
672 const TypeSummaryOptions &options) {
673 return GetSummaryAsCString(GetSummaryFormat().get(), destination, options);
674}
675
676bool ValueObject::IsCStringContainer(bool check_pointer) {
677 CompilerType pointee_or_element_compiler_type;
678 const Flags type_flags(GetTypeInfo(&pointee_or_element_compiler_type));
679 bool is_char_arr_ptr(type_flags.AnySet(eTypeIsArray | eTypeIsPointer) &&
680 pointee_or_element_compiler_type.IsCharType());
681 if (!is_char_arr_ptr)
682 return false;
683 if (!check_pointer)
684 return true;
685 if (type_flags.Test(eTypeIsArray))
686 return true;
687 addr_t cstr_address = GetPointerValue().address;
688 return (cstr_address != LLDB_INVALID_ADDRESS);
689}
690
691size_t ValueObject::GetPointeeData(DataExtractor &data, uint32_t item_idx,
692 uint32_t item_count) {
693 CompilerType pointee_or_element_compiler_type;
694 const uint32_t type_info = GetTypeInfo(&pointee_or_element_compiler_type);
695 const bool is_pointer_type = type_info & eTypeIsPointer;
696 const bool is_array_type = type_info & eTypeIsArray;
697 if (!(is_pointer_type || is_array_type))
698 return 0;
699
700 if (item_count == 0)
701 return 0;
702
704
705 std::optional<uint64_t> item_type_size =
706 llvm::expectedToOptional(pointee_or_element_compiler_type.GetByteSize(
708 if (!item_type_size)
709 return 0;
710 const uint64_t bytes = item_count * *item_type_size;
711 const uint64_t offset = item_idx * *item_type_size;
712
713 if (item_idx == 0 && item_count == 1) // simply a deref
714 {
715 if (is_pointer_type) {
717 ValueObjectSP pointee_sp = Dereference(error);
718 if (error.Fail() || pointee_sp.get() == nullptr)
719 return 0;
720 return pointee_sp->GetData(data, error);
721 } else {
722 ValueObjectSP child_sp = GetChildAtIndex(0);
723 if (child_sp.get() == nullptr)
724 return 0;
726 return child_sp->GetData(data, error);
727 }
728 return 0;
729 } else /* (items > 1) */
730 {
732 lldb_private::DataBufferHeap *heap_buf_ptr = nullptr;
733 lldb::DataBufferSP data_sp(heap_buf_ptr =
735
736 auto [addr, addr_type] =
737 is_pointer_type ? GetPointerValue() : GetAddressOf(true);
738
739 switch (addr_type) {
740 case eAddressTypeFile: {
741 ModuleSP module_sp(GetModule());
742 if (module_sp) {
743 addr = addr + offset;
744 Address so_addr;
745 module_sp->ResolveFileAddress(addr, so_addr);
747 Target *target = exe_ctx.GetTargetPtr();
748 if (target) {
749 heap_buf_ptr->SetByteSize(bytes);
750 size_t bytes_read = target->ReadMemory(
751 so_addr, heap_buf_ptr->GetBytes(), bytes, error, true);
752 if (error.Success()) {
753 data.SetData(data_sp);
754 return bytes_read;
755 }
756 }
757 }
758 } break;
759 case eAddressTypeLoad: {
761 if (Target *target = exe_ctx.GetTargetPtr()) {
762 heap_buf_ptr->SetByteSize(bytes);
763 Address target_addr;
764 target_addr.SetLoadAddress(addr + offset, target);
765 size_t bytes_read =
766 target->ReadMemory(target_addr, heap_buf_ptr->GetBytes(), bytes,
767 error, /*force_live_memory=*/true);
768 if (!error.Success()) {
769 // The live read failed. Fall back to the object file's read-only
770 // sections, but keep the live-memory error to report if the fallback
771 // fails too.
772 Status file_error;
773 size_t file_bytes_read =
774 target->ReadMemory(target_addr, heap_buf_ptr->GetBytes(), bytes,
775 file_error, /*force_live_memory=*/false);
776 if (file_error.Success() || file_bytes_read > 0) {
777 bytes_read = file_bytes_read;
778 error = std::move(file_error);
779 }
780 }
781 if (error.Success() || bytes_read > 0) {
782 data.SetData(data_sp);
783 return bytes_read;
784 }
785 }
786 } break;
787 case eAddressTypeHost: {
788 auto max_bytes = llvm::expectedToOptional(GetCompilerType().GetByteSize(
790 if (max_bytes && *max_bytes > offset) {
791 size_t bytes_read = std::min<uint64_t>(*max_bytes - offset, bytes);
792 addr = m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
793 if (addr == 0 || addr == LLDB_INVALID_ADDRESS)
794 break;
795 heap_buf_ptr->CopyData((uint8_t *)(addr + offset), bytes_read);
796 data.SetData(data_sp);
797 return bytes_read;
798 }
799 } break;
801 break;
802 }
803 }
804 return 0;
805}
806
808 UpdateValueIfNeeded(false);
810 error = m_value.GetValueAsData(&exe_ctx, data, GetModule().get());
811 if (error.Fail()) {
812 if (m_data.GetByteSize()) {
813 data = m_data;
814 error.Clear();
815 return data.GetByteSize();
816 } else {
817 return 0;
818 }
819 }
820 data.SetAddressByteSize(m_data.GetAddressByteSize());
821 data.SetByteOrder(m_data.GetByteOrder());
822 return data.GetByteSize();
823}
824
826 error.Clear();
827 if (llvm::Error err = CanSetValue()) {
828 error = Status::FromError(std::move(err));
829 return false;
830 }
831 // Make sure our value is up to date first so that our location and location
832 // type is valid.
833 if (!UpdateValueIfNeeded(false)) {
834 error = Status::FromErrorString("unable to read value");
835 return false;
836 }
837
838 const Encoding encoding = GetCompilerType().GetEncoding();
839
840 const size_t byte_size = llvm::expectedToOptional(GetByteSize()).value_or(0);
841
842 Value::ValueType value_type = m_value.GetValueType();
843
844 switch (value_type) {
846 error = Status::FromErrorString("invalid location");
847 return false;
849 Status set_error =
850 m_value.GetScalar().SetValueFromData(data, encoding, byte_size);
851
852 if (!set_error.Success()) {
854 "unable to set scalar value: %s", set_error.AsCString());
855 return false;
856 }
857 } break;
859 // If it is a load address, then the scalar value is the storage location
860 // of the data, and we have to shove this value down to that load location.
862 Process *process = exe_ctx.GetProcessPtr();
863 if (process) {
864 addr_t target_addr = m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
865 size_t bytes_written = process->WriteMemory(
866 target_addr, data.GetDataStart(), byte_size, error);
867 if (!error.Success())
868 return false;
869 if (bytes_written != byte_size) {
870 error = Status::FromErrorString("unable to write value to memory");
871 return false;
872 }
873 }
874 } break;
876 // If it is a host address, then we stuff the scalar as a DataBuffer into
877 // the Value's data.
878 DataBufferSP buffer_sp(new DataBufferHeap(byte_size, 0));
879 m_data.SetData(buffer_sp, 0);
880 data.CopyByteOrderedData(0, byte_size,
881 const_cast<uint8_t *>(m_data.GetDataStart()),
882 byte_size, m_data.GetByteOrder());
883 m_value.GetScalar() = (uintptr_t)m_data.GetDataStart();
884 } break;
886 break;
887 }
888
889 // If we have reached this point, then we have successfully changed the
890 // value.
892 return true;
893}
894
895llvm::ArrayRef<uint8_t> ValueObject::GetLocalBuffer() const {
896 if (m_value.GetValueType() != Value::ValueType::HostAddress)
897 return {};
898 auto start = m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
899 if (start == LLDB_INVALID_ADDRESS)
900 return {};
901 // Does our pointer point to this value object's m_data buffer?
902 if ((uint64_t)m_data.GetDataStart() == start)
903 return m_data.GetData();
904 // Does our pointer point to the value's buffer?
905 if ((uint64_t)m_value.GetBuffer().GetBytes() == start)
906 return m_value.GetBuffer().GetData();
907 // Our pointer points to something else. We can't know what the size is.
908 return {};
909}
910
911static bool CopyStringDataToBufferSP(const StreamString &source,
912 lldb::WritableDataBufferSP &destination) {
913 llvm::StringRef src = source.GetString();
914 src = src.rtrim('\0');
915 destination = std::make_shared<DataBufferHeap>(src.size(), 0);
916 memcpy(destination->GetBytes(), src.data(), src.size());
917 return true;
918}
919
920std::pair<size_t, bool>
922 Status &error, bool honor_array) {
923 bool was_capped = false;
924 StreamString s;
926 Target *target = exe_ctx.GetTargetPtr();
927
928 if (!target) {
929 s << "<no target to read from>";
930 error = Status::FromErrorString("no target to read from");
931 CopyStringDataToBufferSP(s, buffer_sp);
932 return {0, was_capped};
933 }
934
935 const auto max_length = target->GetMaximumSizeOfStringSummary();
936
937 size_t bytes_read = 0;
938 size_t total_bytes_read = 0;
939
940 CompilerType compiler_type = GetCompilerType();
941 CompilerType elem_or_pointee_compiler_type;
942 const Flags type_flags(GetTypeInfo(&elem_or_pointee_compiler_type));
943 if (type_flags.AnySet(eTypeIsArray | eTypeIsPointer) &&
944 elem_or_pointee_compiler_type.IsCharType()) {
945 AddrAndType cstr_address;
946
947 size_t cstr_len = 0;
948 bool capped_data = false;
949 const bool is_array = type_flags.Test(eTypeIsArray);
950 if (is_array) {
951 // We have an array
952 uint64_t array_size = 0;
953 if (compiler_type.IsArrayType(nullptr, &array_size)) {
954 cstr_len = array_size;
955 if (cstr_len > max_length) {
956 capped_data = true;
957 cstr_len = max_length;
958 }
959 }
960 cstr_address = GetAddressOf(true);
961 } else {
962 // We have a pointer
963 cstr_address = GetPointerValue();
964 }
965
966 if (cstr_address.address == 0 ||
967 cstr_address.address == LLDB_INVALID_ADDRESS) {
968 if (cstr_address.type == eAddressTypeHost && is_array) {
969 // The array is not required to be null-terminated, so ask for the
970 // bytes rather than for a C string. Its data can also be shorter than
971 // the array type, as for a DW_AT_const_value string, so clamp the
972 // length to what is really there.
974 const uint8_t *cstr = data.PeekData(0, 1);
975 if (cstr == nullptr) {
976 s << "<invalid address>";
977 error = Status::FromErrorString("invalid address");
978 CopyStringDataToBufferSP(s, buffer_sp);
979 return {0, was_capped};
980 }
981 cstr_len = std::min<uint64_t>(cstr_len, data.GetByteSize());
982 s << llvm::StringRef(reinterpret_cast<const char *>(cstr), cstr_len);
983 CopyStringDataToBufferSP(s, buffer_sp);
984 return {cstr_len, was_capped};
985 } else {
986 s << "<invalid address>";
987 error = Status::FromErrorString("invalid address");
988 CopyStringDataToBufferSP(s, buffer_sp);
989 return {0, was_capped};
990 }
991 }
992
993 Address cstr_so_addr(cstr_address.address);
994 DataExtractor data;
995 if (cstr_len > 0 && honor_array) {
996 // I am using GetPointeeData() here to abstract the fact that some
997 // ValueObjects are actually frozen pointers in the host but the pointed-
998 // to data lives in the debuggee, and GetPointeeData() automatically
999 // takes care of this
1000 GetPointeeData(data, 0, cstr_len);
1001
1002 if ((bytes_read = data.GetByteSize()) > 0) {
1003 total_bytes_read = bytes_read;
1004 for (size_t offset = 0; offset < bytes_read; offset++)
1005 s.PutChar(*data.PeekData(offset, 1));
1006 if (capped_data)
1007 was_capped = true;
1008 }
1009 } else {
1010 cstr_len = max_length;
1011 const size_t k_max_buf_size = 64;
1012
1013 size_t offset = 0;
1014
1015 int cstr_len_displayed = -1;
1016 bool capped_cstr = false;
1017 // I am using GetPointeeData() here to abstract the fact that some
1018 // ValueObjects are actually frozen pointers in the host but the pointed-
1019 // to data lives in the debuggee, and GetPointeeData() automatically
1020 // takes care of this
1021 while ((bytes_read = GetPointeeData(data, offset, k_max_buf_size)) > 0) {
1022 total_bytes_read += bytes_read;
1023 // The chunk holds the middle of a string as often as its end, so scan
1024 // for a terminator instead of requiring one.
1025 const uint8_t *bytes = data.PeekData(0, bytes_read);
1026 if (bytes == nullptr)
1027 break;
1028 size_t len = strnlen(reinterpret_cast<const char *>(bytes), bytes_read);
1029 if (cstr_len_displayed < 0)
1030 cstr_len_displayed = len;
1031
1032 if (len == 0)
1033 break;
1034 cstr_len_displayed += len;
1035 if (len > bytes_read)
1036 len = bytes_read;
1037 if (len > cstr_len)
1038 len = cstr_len;
1039
1040 for (size_t offset = 0; offset < bytes_read; offset++)
1041 s.PutChar(*data.PeekData(offset, 1));
1042
1043 if (len < k_max_buf_size)
1044 break;
1045
1046 if (len >= cstr_len) {
1047 capped_cstr = true;
1048 break;
1049 }
1050
1051 cstr_len -= len;
1052 offset += len;
1053 }
1054
1055 if (cstr_len_displayed >= 0) {
1056 if (capped_cstr)
1057 was_capped = true;
1058 }
1059 }
1060 } else {
1061 error = Status::FromErrorString("not a string object");
1062 s << "<not a string object>";
1063 }
1064 CopyStringDataToBufferSP(s, buffer_sp);
1065 return {total_bytes_read, was_capped};
1066}
1067
1068llvm::Expected<std::string> ValueObject::GetObjectDescription() {
1069 if (!UpdateValueIfNeeded(true))
1070 return llvm::createStringError("could not update value");
1071
1072 // Return cached value.
1073 if (!m_object_desc_str.empty())
1074 return m_object_desc_str;
1075
1077 Process *process = exe_ctx.GetProcessPtr();
1078 if (!process)
1079 return llvm::createStringError("no process");
1080
1081 // Returns the object description produced by one language runtime.
1082 auto get_object_description =
1083 [&](LanguageType language) -> llvm::Expected<std::string> {
1084 if (LanguageRuntime *runtime = process->GetLanguageRuntime(language)) {
1085 StreamString s;
1086 if (llvm::Error error = runtime->GetObjectDescription(s, *this))
1087 return error;
1089 return m_object_desc_str;
1090 }
1091 return llvm::createStringError("no native language runtime");
1092 };
1093
1094 // Try the native language runtime first.
1095 LanguageType native_language = GetObjectRuntimeLanguage();
1096 llvm::Expected<std::string> desc = get_object_description(native_language);
1097 if (desc)
1098 return desc;
1099
1100 // Try the Objective-C language runtime. This fallback is necessary
1101 // for Objective-C++ and mixed Objective-C / C++ programs.
1102 if (Language::LanguageIsCFamily(native_language)) {
1103 // We're going to try again, so let's drop the first error.
1104 llvm::consumeError(desc.takeError());
1105 return get_object_description(eLanguageTypeObjC);
1106 }
1107 return desc;
1108}
1109
1111 std::string &destination) {
1112 if (UpdateValueIfNeeded(false))
1113 return format.FormatObject(this, destination);
1114 else
1115 return false;
1116}
1117
1119 std::string &destination) {
1120 return GetValueAsCString(TypeFormatImpl_Format(format), destination);
1121}
1122
1124 if (UpdateValueIfNeeded(true)) {
1125 lldb::TypeFormatImplSP format_sp;
1126 lldb::Format my_format = GetFormat();
1127 if (my_format == lldb::eFormatDefault) {
1128 if (m_type_format_sp)
1129 format_sp = m_type_format_sp;
1130 else {
1131 if (m_flags.m_is_bitfield_for_scalar)
1132 my_format = eFormatUnsigned;
1133 else {
1134 if (m_value.GetContextType() == Value::ContextType::RegisterInfo) {
1135 const RegisterInfo *reg_info = m_value.GetRegisterInfo();
1136 if (reg_info)
1137 my_format = reg_info->format;
1138 } else {
1139 my_format = GetValue().GetCompilerType().GetFormat();
1140 }
1141 }
1142 }
1143 }
1144 if (my_format != m_last_format || m_value_str.empty()) {
1145 m_last_format = my_format;
1146 if (!format_sp)
1147 format_sp = std::make_shared<TypeFormatImpl_Format>(my_format);
1148 if (GetValueAsCString(*format_sp.get(), m_value_str)) {
1149 if (!m_flags.m_value_did_change && m_flags.m_old_value_valid) {
1150 // The value was gotten successfully, so we consider the value as
1151 // changed if the value string differs
1153 }
1154 }
1155 }
1156 }
1157 if (m_value_str.empty())
1158 return nullptr;
1159 return m_value_str.c_str();
1160}
1161
1162// if > 8bytes, 0 is returned. this method should mostly be used to read
1163// address values out of pointers
1164uint64_t ValueObject::GetValueAsUnsigned(uint64_t fail_value, bool *success) {
1165 // If our byte size is zero this is an aggregate type that has children
1166 if (CanProvideValue()) {
1167 Scalar scalar;
1168 if (ResolveValue(scalar)) {
1169 if (success)
1170 *success = true;
1171 scalar.MakeUnsigned();
1172 return scalar.ULongLong(fail_value);
1173 }
1174 // fallthrough, otherwise...
1175 }
1176
1177 if (success)
1178 *success = false;
1179 return fail_value;
1180}
1181
1182int64_t ValueObject::GetValueAsSigned(int64_t fail_value, bool *success) {
1183 // If our byte size is zero this is an aggregate type that has children
1184 if (CanProvideValue()) {
1185 Scalar scalar;
1186 if (ResolveValue(scalar)) {
1187 if (success)
1188 *success = true;
1189 scalar.MakeSigned();
1190 return scalar.SLongLong(fail_value);
1191 }
1192 // fallthrough, otherwise...
1193 }
1194
1195 if (success)
1196 *success = false;
1197 return fail_value;
1198}
1199
1200llvm::Expected<llvm::APSInt> ValueObject::GetValueAsAPSInt() {
1201 // Make sure the type can be converted to an APSInt.
1202 if (!GetCompilerType().IsInteger() &&
1203 !GetCompilerType().IsScopedEnumerationType() &&
1204 !GetCompilerType().IsEnumerationType() &&
1206 !GetCompilerType().IsNullPtrType() &&
1207 !GetCompilerType().IsReferenceType() && !GetCompilerType().IsBoolean())
1208 return llvm::createStringError("type cannot be converted to APSInt");
1209
1210 if (CanProvideValue()) {
1211 Scalar scalar;
1212 if (ResolveValue(scalar))
1213 return scalar.GetAPSInt();
1214 }
1215
1216 return llvm::createStringError("error occurred; unable to convert to APSInt");
1217}
1218
1219llvm::Expected<llvm::APFloat> ValueObject::GetValueAsAPFloat() {
1221 return llvm::createStringError("type cannot be converted to APFloat");
1222
1223 if (CanProvideValue()) {
1224 Scalar scalar;
1225 if (ResolveValue(scalar))
1226 return scalar.GetAPFloat();
1227 }
1228
1229 return llvm::createStringError(
1230 "error occurred; unable to convert to APFloat");
1231}
1232
1233llvm::Expected<bool> ValueObject::GetValueAsBool() {
1234 CompilerType val_type = GetCompilerType();
1235 if (val_type.IsInteger() || val_type.IsUnscopedEnumerationType() ||
1236 val_type.IsPointerType()) {
1237 auto value_or_err = GetValueAsAPSInt();
1238 if (value_or_err)
1239 return value_or_err->getBoolValue();
1240 else
1241 LLDB_LOG_ERROR(GetLog(LLDBLog::Types), value_or_err.takeError(),
1242 "GetValueAsAPSInt failed: {0}");
1243 }
1244 if (HasFloatingRepresentation(val_type)) {
1245 auto value_or_err = GetValueAsAPFloat();
1246 if (value_or_err)
1247 return value_or_err->isNonZero();
1248 else
1249 LLDB_LOG_ERROR(GetLog(LLDBLog::Types), value_or_err.takeError(),
1250 "GetValueAsAPFloat failed: {0}");
1251 }
1252 if (val_type.IsArrayType())
1253 return GetAddressOf().address != 0;
1254 if (val_type.IsNullPtrType())
1255 return false;
1256
1257 return llvm::createStringError("type cannot be converted to bool");
1258}
1259
1260llvm::Error ValueObject::SetValueFromInteger(const llvm::APInt &value,
1261 bool can_update_var) {
1262 // Verify the current object is an integer object
1263 CompilerType val_type = GetCompilerType();
1264 if (!val_type.IsInteger() && !val_type.IsUnscopedEnumerationType() &&
1265 !HasFloatingRepresentation(val_type) && !val_type.IsPointerType() &&
1266 !val_type.IsScalarType())
1267 return llvm::createStringError(
1268 "Not allowed to change the value of a non-scalar object");
1269
1270 // Verify, if current object is associated with a program variable, that
1271 // we are allowing updating program variables in this case.
1272 if (GetVariable() && !can_update_var)
1273 return llvm::createStringError(
1274 "Not allowed to update program variables in this case");
1275
1276 // Make sure we're not trying to assign to a constant.
1277 if (GetIsConstant())
1278 return llvm::createStringError(
1279 "Not allowed to change the value of a constant");
1280
1281 // Verify the proposed new value is the right size.
1282 lldb::TargetSP target = GetTargetSP();
1283 uint64_t byte_size = 0;
1284 // Exclude size check when assigning an integer 1 or 0 to a boolean.
1285 if (!val_type.IsBoolean() || (!value.isOne() && !value.isZero())) {
1286 byte_size = llvm::expectedToOptional(GetByteSize()).value_or(0);
1287 // Check that the value is representable in the destination type.
1288 unsigned dest_bits = byte_size * CHAR_BIT;
1289 unsigned needed_bits = val_type.IsSigned() ? value.getSignificantBits()
1290 : value.getActiveBits();
1291 if (needed_bits > dest_bits)
1292 return llvm::createStringError("Illegal argument: new value is too big");
1293 }
1294
1295 // The DataExtractor below reads exactly byte_size bytes from the APInt's raw
1296 // storage. If the incoming value has fewer bits than the destination type,
1297 // reading byte_size bytes could run past the APInt's backing store and pull
1298 // in garbage (an out-of-bounds read). Extend the value so its storage always
1299 // covers the full read, preserving the sign so that negative values keep
1300 // their value in the wider destination.
1301 llvm::APInt sized_value = value;
1302 if (sized_value.getBitWidth() < byte_size * CHAR_BIT)
1303 sized_value = sized_value.sext(byte_size * CHAR_BIT);
1304
1305 Status error;
1306 lldb::DataExtractorSP data_sp = std::make_shared<DataExtractor>(
1307 reinterpret_cast<const void *>(sized_value.getRawData()), byte_size,
1308 target->GetArchitecture().GetByteOrder(),
1309 static_cast<uint8_t>(target->GetArchitecture().GetAddressByteSize()));
1310 SetData(*data_sp, error);
1311 return error.takeError();
1312}
1313
1315 bool can_update_var) {
1316 // Verify the current object is an integer object
1317 CompilerType val_type = GetCompilerType();
1318 if (!val_type.IsInteger() && !val_type.IsUnscopedEnumerationType() &&
1319 !HasFloatingRepresentation(val_type) && !val_type.IsPointerType() &&
1320 !val_type.IsScalarType())
1321 return llvm::createStringError("Not allowed to update a non-scalar object");
1322
1323 // Verify, if current object is associated with a program variable, that
1324 // we are allowing updating program variables in this case.
1325 if (GetVariable() && !can_update_var)
1326 return llvm::createStringError(
1327 "Not allowed to update program variables in this case");
1328
1329 // Verify the proposed new value is the right type.
1330 CompilerType new_val_type = new_val_sp->GetCompilerType();
1331 if (!new_val_type.IsInteger() && !new_val_type.IsUnscopedEnumerationType() &&
1332 !HasFloatingRepresentation(new_val_type) && !new_val_type.IsPointerType())
1333 return llvm::createStringError(
1334 "Illegal argument: new value is not a scalar object");
1335
1336 if (new_val_type.IsInteger() || new_val_type.IsUnscopedEnumerationType()) {
1337 auto value_or_err = new_val_sp->GetValueAsAPSInt();
1338 if (value_or_err)
1339 return SetValueFromInteger(*value_or_err, can_update_var);
1340 } else if (HasFloatingRepresentation(new_val_type)) {
1341 auto value_or_err = new_val_sp->GetValueAsAPFloat();
1342 if (value_or_err)
1343 return SetValueFromInteger(value_or_err->bitcastToAPInt(),
1344 can_update_var);
1345 } else if (new_val_type.IsPointerType()) {
1346 bool success = true;
1347 uint64_t int_val = new_val_sp->GetValueAsUnsigned(0, &success);
1348 if (success) {
1349 lldb::TargetSP target = GetTargetSP();
1350 uint64_t num_bits = 0;
1351 if (auto temp = llvm::expectedToOptional(
1352 new_val_sp->GetCompilerType().GetBitSize(target.get())))
1353 num_bits = temp.value();
1354 return SetValueFromInteger(llvm::APInt(num_bits, int_val),
1355 can_update_var);
1356 } else
1357 return llvm::createStringError("Error converting new_val_sp to integer");
1358 }
1359 llvm_unreachable("Unrecognized type for RHS of assignment");
1360}
1361
1362// if any more "special cases" are added to
1363// ValueObject::DumpPrintableRepresentation() please keep this call up to date
1364// by returning true for your new special cases. We will eventually move to
1365// checking this call result before trying to display special cases
1367 ValueObjectRepresentationStyle val_obj_display, Format custom_format) {
1368 Flags flags(GetTypeInfo());
1369 if (flags.AnySet(eTypeIsArray | eTypeIsPointer) &&
1371 if (IsCStringContainer(true) &&
1372 (custom_format == eFormatCString || custom_format == eFormatCharArray ||
1373 custom_format == eFormatChar || custom_format == eFormatVectorOfChar))
1374 return true;
1375
1376 if (flags.Test(eTypeIsArray)) {
1377 if ((custom_format == eFormatBytes) ||
1378 (custom_format == eFormatBytesWithASCII))
1379 return true;
1380
1381 if ((custom_format == eFormatVectorOfChar) ||
1382 (custom_format == eFormatVectorOfFloat32) ||
1383 (custom_format == eFormatVectorOfFloat64) ||
1384 (custom_format == eFormatVectorOfSInt16) ||
1385 (custom_format == eFormatVectorOfSInt32) ||
1386 (custom_format == eFormatVectorOfSInt64) ||
1387 (custom_format == eFormatVectorOfSInt8) ||
1388 (custom_format == eFormatVectorOfUInt128) ||
1389 (custom_format == eFormatVectorOfUInt16) ||
1390 (custom_format == eFormatVectorOfUInt32) ||
1391 (custom_format == eFormatVectorOfUInt64) ||
1392 (custom_format == eFormatVectorOfUInt8))
1393 return true;
1394 }
1395 }
1396 return false;
1397}
1398
1400 Stream &s, ValueObjectRepresentationStyle val_obj_display,
1401 Format custom_format, PrintableRepresentationSpecialCases special,
1402 bool do_dump_error) {
1403
1404 // If the ValueObject has an error, we might end up dumping the type, which
1405 // is useful, but if we don't even have a type, then don't examine the object
1406 // further as that's not meaningful, only the error is.
1407 if (m_error.Fail() && !GetCompilerType().IsValid()) {
1408 if (do_dump_error)
1409 s.Printf("<%s>", m_error.AsCString());
1410 return false;
1411 }
1412
1413 Flags flags(GetTypeInfo());
1414
1415 bool allow_special =
1417 const bool only_special = false;
1418
1419 if (allow_special) {
1420 if (flags.AnySet(eTypeIsArray | eTypeIsPointer) &&
1422 // when being asked to get a printable display an array or pointer type
1423 // directly, try to "do the right thing"
1424
1425 if (IsCStringContainer(true) &&
1426 (custom_format == eFormatCString ||
1427 custom_format == eFormatCharArray || custom_format == eFormatChar ||
1428 custom_format ==
1429 eFormatVectorOfChar)) // print char[] & char* directly
1430 {
1431 Status error;
1433 std::pair<size_t, bool> read_string =
1434 ReadPointedString(buffer_sp, error,
1435 (custom_format == eFormatVectorOfChar) ||
1436 (custom_format == eFormatCharArray));
1437 lldb_private::formatters::StringPrinter::
1438 ReadBufferAndDumpToStreamOptions options(*this);
1439 options.SetData(DataExtractor(
1440 buffer_sp, lldb::eByteOrderInvalid,
1441 8)); // none of this matters for a string - pass some defaults
1442 options.SetStream(&s);
1443 options.SetPrefixToken(nullptr);
1444 options.SetQuote('"');
1445 options.SetSourceSize(buffer_sp->GetByteSize());
1446 options.SetIsTruncated(read_string.second);
1447 if (custom_format == eFormatVectorOfChar) {
1448 options.SetZeroTermination(
1450 } else {
1451 options.SetZeroTermination(
1453 }
1455 lldb_private::formatters::StringPrinter::StringElementType::ASCII>(
1456 options);
1457 return !error.Fail();
1458 }
1459
1460 if (custom_format == eFormatEnum)
1461 return false;
1462
1463 // this only works for arrays, because I have no way to know when the
1464 // pointed memory ends, and no special \0 end of data marker
1465 if (flags.Test(eTypeIsArray)) {
1466 if ((custom_format == eFormatBytes) ||
1467 (custom_format == eFormatBytesWithASCII)) {
1468 const size_t count = GetNumChildrenIgnoringErrors();
1469
1470 s << '[';
1471 for (size_t low = 0; low < count; low++) {
1472
1473 if (low)
1474 s << ',';
1475
1476 ValueObjectSP child = GetChildAtIndex(low);
1477 if (!child.get()) {
1478 s << "<invalid child>";
1479 continue;
1480 }
1481 child->DumpPrintableRepresentation(
1483 custom_format);
1484 }
1485
1486 s << ']';
1487
1488 return true;
1489 }
1490
1491 if ((custom_format == eFormatVectorOfChar) ||
1492 (custom_format == eFormatVectorOfFloat32) ||
1493 (custom_format == eFormatVectorOfFloat64) ||
1494 (custom_format == eFormatVectorOfSInt16) ||
1495 (custom_format == eFormatVectorOfSInt32) ||
1496 (custom_format == eFormatVectorOfSInt64) ||
1497 (custom_format == eFormatVectorOfSInt8) ||
1498 (custom_format == eFormatVectorOfUInt128) ||
1499 (custom_format == eFormatVectorOfUInt16) ||
1500 (custom_format == eFormatVectorOfUInt32) ||
1501 (custom_format == eFormatVectorOfUInt64) ||
1502 (custom_format == eFormatVectorOfUInt8)) // arrays of bytes, bytes
1503 // with ASCII or any vector
1504 // format should be printed
1505 // directly
1506 {
1507 const size_t count = GetNumChildrenIgnoringErrors();
1508
1509 Format format = FormatManager::GetSingleItemFormat(custom_format);
1510
1511 s << '[';
1512 for (size_t low = 0; low < count; low++) {
1513
1514 if (low)
1515 s << ',';
1516
1517 ValueObjectSP child = GetChildAtIndex(low);
1518 if (!child.get()) {
1519 s << "<invalid child>";
1520 continue;
1521 }
1522 child->DumpPrintableRepresentation(
1524 }
1525
1526 s << ']';
1527
1528 return true;
1529 }
1530 }
1531
1532 if ((custom_format == eFormatBoolean) ||
1533 (custom_format == eFormatBinary) || (custom_format == eFormatChar) ||
1534 (custom_format == eFormatCharPrintable) ||
1535 (custom_format == eFormatComplexFloat) ||
1536 (custom_format == eFormatDecimal) || (custom_format == eFormatHex) ||
1537 (custom_format == eFormatHexUppercase) ||
1538 (custom_format == eFormatFloat) ||
1539 (custom_format == eFormatFloat128) ||
1540 (custom_format == eFormatOctal) || (custom_format == eFormatOSType) ||
1541 (custom_format == eFormatUnicode16) ||
1542 (custom_format == eFormatUnicode32) ||
1543 (custom_format == eFormatUnsigned) ||
1544 (custom_format == eFormatPointer) ||
1545 (custom_format == eFormatComplexInteger) ||
1546 (custom_format == eFormatComplex) ||
1547 (custom_format == eFormatDefault)) // use the [] operator
1548 return false;
1549 }
1550 }
1551
1552 if (only_special)
1553 return false;
1554
1555 bool var_success = false;
1556
1557 {
1558 llvm::StringRef str;
1559
1560 // this is a local stream that we are using to ensure that the data pointed
1561 // to by cstr survives long enough for us to copy it to its destination -
1562 // it is necessary to have this temporary storage area for cases where our
1563 // desired output is not backed by some other longer-term storage
1564 StreamString strm;
1565
1566 if (custom_format != eFormatInvalid)
1567 SetFormat(custom_format);
1568
1569 switch (val_obj_display) {
1571 str = GetValueAsCString();
1572 break;
1573
1575 str = GetSummaryAsCString();
1576 break;
1577
1579 llvm::Expected<std::string> desc = GetObjectDescription();
1580 if (!desc) {
1581 strm << "error: " << toString(desc.takeError());
1582 str = strm.GetString();
1583 } else {
1584 strm << *desc;
1585 str = strm.GetString();
1586 }
1587 } break;
1588
1590 str = GetLocationAsCString();
1591 break;
1592
1594 if (auto err = GetNumChildren()) {
1595 strm.Printf("%" PRIu32, *err);
1596 str = strm.GetString();
1597 } else {
1598 strm << "error: " << toString(err.takeError());
1599 str = strm.GetString();
1600 }
1601 break;
1602 }
1603
1605 str = GetTypeName().GetStringRef();
1606 break;
1607
1609 str = GetName().GetStringRef();
1610 break;
1611
1613 GetExpressionPath(strm);
1614 str = strm.GetString();
1615 break;
1616 }
1617
1618 // If the requested display style produced no output, try falling back to
1619 // alternative presentations.
1620 if (str.empty()) {
1621 if (val_obj_display == eValueObjectRepresentationStyleValue)
1622 str = GetSummaryAsCString();
1623 else if (val_obj_display == eValueObjectRepresentationStyleSummary) {
1624 if (!CanProvideValue()) {
1625 strm.Format("{0} @ {1}", GetTypeName(), GetLocationAsCString());
1626 str = strm.GetString();
1627 } else
1628 str = GetValueAsCString();
1629 }
1630 }
1631
1632 if (!str.empty())
1633 s << str;
1634 else {
1635 // We checked for errors at the start, but do it again here in case
1636 // realizing the value for dumping produced an error.
1637 if (m_error.Fail()) {
1638 if (do_dump_error)
1639 s.Printf("<%s>", m_error.AsCString());
1640 else
1641 return false;
1642 } else if (val_obj_display == eValueObjectRepresentationStyleSummary)
1643 s.PutCString("<no summary available>");
1644 else if (val_obj_display == eValueObjectRepresentationStyleValue)
1645 s.PutCString("<no value available>");
1646 else if (val_obj_display ==
1648 s.PutCString("<not a valid Objective-C object>"); // edit this if we
1649 // have other runtimes
1650 // that support a
1651 // description
1652 else
1653 s.PutCString("<no printable representation>");
1654 }
1655
1656 // we should only return false here if we could not do *anything* even if
1657 // we have an error message as output, that's a success from our callers'
1658 // perspective, so return true
1659 var_success = true;
1660
1661 if (custom_format != eFormatInvalid)
1663 }
1664
1665 return var_success;
1666}
1667
1669ValueObject::GetAddressOf(bool scalar_is_load_address) {
1670 // Can't take address of a bitfield
1671 if (IsBitfield())
1672 return {};
1673
1674 if (!UpdateValueIfNeeded(false))
1675 return {};
1676
1677 switch (m_value.GetValueType()) {
1679 return {};
1681 if (scalar_is_load_address) {
1682 return {m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS),
1684 }
1685 return {};
1686
1689 return {m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS),
1690 m_value.GetValueAddressType()};
1692 return {LLDB_INVALID_ADDRESS, m_value.GetValueAddressType()};
1693 }
1694 llvm_unreachable("Unhandled value type!");
1695}
1696
1697std::optional<addr_t> ValueObject::GetStrippedPointerValue(addr_t address) {
1698 if (GetCompilerType().HasPointerAuthQualifier()) {
1700 if (Process *process = exe_ctx.GetProcessPtr())
1701 if (ABISP abi_sp = process->GetABI())
1702 return abi_sp->FixCodeAddress(address);
1703 }
1704 return std::nullopt;
1705}
1706
1708 if (!UpdateValueIfNeeded(false))
1709 return {};
1710
1711 switch (m_value.GetValueType()) {
1713 return {};
1715 return {m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS),
1717
1721 lldb::offset_t data_offset = 0;
1722 return {m_data.GetAddress(&data_offset), GetAddressTypeOfChildren()};
1723 }
1724 }
1725
1726 llvm_unreachable("Unhandled value type!");
1727}
1728
1729static const char *ConvertBoolean(lldb::LanguageType language_type,
1730 const char *value_str) {
1731 if (Language *language = Language::FindPlugin(language_type))
1732 if (auto boolean = language->GetBooleanFromString(value_str))
1733 return *boolean ? "1" : "0";
1734
1735 return llvm::StringSwitch<const char *>(value_str)
1736 .Case("true", "1")
1737 .Case("false", "0")
1738 .Default(value_str);
1739}
1740
1741bool ValueObject::SetValueFromCString(const char *value_str, Status &error) {
1742 error.Clear();
1743 if (llvm::Error err = CanSetValue()) {
1744 error = Status::FromError(std::move(err));
1745 return false;
1746 }
1747 // Make sure our value is up to date first so that our location and location
1748 // type is valid.
1749 if (!UpdateValueIfNeeded(false)) {
1750 error = Status::FromErrorString("unable to read value");
1751 return false;
1752 }
1753
1754 const Encoding encoding = GetCompilerType().GetEncoding();
1755
1756 const size_t byte_size = llvm::expectedToOptional(GetByteSize()).value_or(0);
1757
1758 Value::ValueType value_type = m_value.GetValueType();
1759
1760 if (value_type == Value::ValueType::Scalar) {
1761 // If the value is already a scalar, then let the scalar change itself:
1762 m_value.GetScalar().SetValueFromCString(value_str, encoding, byte_size);
1763 } else if (byte_size <= 16) {
1764 if (GetCompilerType().IsBoolean())
1765 value_str = ConvertBoolean(GetObjectRuntimeLanguage(), value_str);
1766
1767 // If the value fits in a scalar, then make a new scalar and again let the
1768 // scalar code do the conversion, then figure out where to put the new
1769 // value.
1770 Scalar new_scalar;
1771 error = new_scalar.SetValueFromCString(value_str, encoding, byte_size);
1772 if (error.Success()) {
1773 switch (value_type) {
1775 // If it is a load address, then the scalar value is the storage
1776 // location of the data, and we have to shove this value down to that
1777 // load location.
1779 Process *process = exe_ctx.GetProcessPtr();
1780 if (process) {
1781 addr_t target_addr =
1782 m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
1783 size_t bytes_written = process->WriteScalarToMemory(
1784 target_addr, new_scalar, byte_size, error);
1785 if (!error.Success())
1786 return false;
1787 if (bytes_written != byte_size) {
1788 error = Status::FromErrorString("unable to write value to memory");
1789 return false;
1790 }
1791 }
1792 } break;
1794 // If it is a host address, then we stuff the scalar as a DataBuffer
1795 // into the Value's data.
1796 DataExtractor new_data;
1797 new_data.SetByteOrder(m_data.GetByteOrder());
1798
1799 DataBufferSP buffer_sp(new DataBufferHeap(byte_size, 0));
1800 m_data.SetData(buffer_sp, 0);
1801 bool success = new_scalar.GetData(new_data);
1802 if (success) {
1803 new_data.CopyByteOrderedData(
1804 0, byte_size, const_cast<uint8_t *>(m_data.GetDataStart()),
1805 byte_size, m_data.GetByteOrder());
1806 }
1807 m_value.GetScalar() = (uintptr_t)m_data.GetDataStart();
1808
1809 } break;
1811 error = Status::FromErrorString("invalid location");
1812 return false;
1815 break;
1816 }
1817 } else {
1818 return false;
1819 }
1820 } else {
1821 // We don't support setting things bigger than a scalar at present.
1822 error = Status::FromErrorString("unable to write aggregate data type");
1823 return false;
1824 }
1825
1826 // If we have reached this point, then we have successfully changed the
1827 // value.
1829 return true;
1830}
1831
1833 decl.Clear();
1834 return false;
1835}
1836
1840
1842 ValueObjectSP synthetic_child_sp;
1843 std::map<ConstString, ValueObject *>::const_iterator pos =
1844 m_synthetic_children.find(key);
1845 if (pos != m_synthetic_children.end())
1846 synthetic_child_sp = pos->second->GetSP();
1847 return synthetic_child_sp;
1848}
1849
1852 Process *process = exe_ctx.GetProcessPtr();
1853 if (process)
1854 return process->IsPossibleDynamicValue(*this);
1855 else
1856 return GetCompilerType().IsPossibleDynamicType(nullptr, true, true);
1857}
1858
1860 Process *process(GetProcessSP().get());
1861 if (!process)
1862 return false;
1863
1864 // We trust that the compiler did the right thing and marked runtime support
1865 // values as artificial.
1866 if (!GetVariable() || !GetVariable()->IsArtificial())
1867 return false;
1868
1869 if (auto *runtime = process->GetLanguageRuntime(GetVariable()->GetLanguage()))
1870 if (runtime->IsAllowedRuntimeValue(GetName()))
1871 return false;
1872
1873 return true;
1874}
1875
1878 return language->IsNilReference(*this);
1879 }
1880 return false;
1881}
1882
1885 return language->IsUninitializedReference(*this);
1886 }
1887 return false;
1888}
1889
1890// This allows you to create an array member using and index that doesn't not
1891// fall in the normal bounds of the array. Many times structure can be defined
1892// as: struct Collection {
1893// uint32_t item_count;
1894// Item item_array[0];
1895// };
1896// The size of the "item_array" is 1, but many times in practice there are more
1897// items in "item_array".
1898
1900 bool can_create) {
1901 // Register values use exact-size host buffers. Do not create array children
1902 // that would read beyond the bytes supplied by the register context.
1903 uint64_t array_size = 0;
1905 GetCompilerType().IsArrayType(nullptr, &array_size) &&
1906 index >= array_size)
1907 return {};
1908
1909 ValueObjectSP synthetic_child_sp;
1910 if (IsPointerType() || IsArrayType()) {
1911 std::string index_str = llvm::formatv("[{0}]", index);
1912 ConstString index_const_str(index_str);
1913 // Check if we have already created a synthetic array member in this valid
1914 // object. If we have we will re-use it.
1915 synthetic_child_sp = GetSyntheticChild(index_const_str);
1916 if (!synthetic_child_sp) {
1917 ValueObject *synthetic_child;
1918 // We haven't made a synthetic array member for INDEX yet, so lets make
1919 // one and cache it for any future reference.
1920 synthetic_child = CreateSyntheticArrayMember(index);
1921
1922 // Cache the value if we got one back...
1923 if (synthetic_child) {
1924 AddSyntheticChild(index_const_str, synthetic_child);
1925 synthetic_child_sp = synthetic_child->GetSP();
1926 synthetic_child_sp->SetName(index_str);
1927 synthetic_child_sp->m_flags.m_is_array_item_for_pointer = true;
1928 }
1929 }
1930 }
1931 return synthetic_child_sp;
1932}
1933
1935 bool can_create) {
1936 if (from > to)
1937 return {};
1938 // Register children must stay within the exact bytes supplied by the
1939 // register context.
1941 std::optional<uint64_t> byte_size = llvm::expectedToOptional(GetByteSize());
1942 if (!byte_size || to / 8 >= *byte_size)
1943 return {};
1944 }
1945
1946 ValueObjectSP synthetic_child_sp;
1947 if (IsScalarType()) {
1948 std::string index_str = llvm::formatv("[{0}-{1}]", from, to);
1949 ConstString index_const_str(index_str);
1950 // Check if we have already created a synthetic array member in this valid
1951 // object. If we have we will re-use it.
1952 synthetic_child_sp = GetSyntheticChild(index_const_str);
1953 if (!synthetic_child_sp) {
1954 uint32_t bit_field_size = to - from + 1;
1955 uint32_t bit_field_offset = from;
1956 if (GetDataExtractor().GetByteOrder() == eByteOrderBig)
1957 bit_field_offset =
1958 llvm::expectedToOptional(GetByteSize()).value_or(0) * 8 -
1959 bit_field_size - bit_field_offset;
1960 // We haven't made a synthetic array member for INDEX yet, so lets make
1961 // one and cache it for any future reference.
1962 ValueObjectChild *synthetic_child = new ValueObjectChild(
1963 *this, GetCompilerType(), index_const_str,
1964 llvm::expectedToOptional(GetByteSize()).value_or(0), 0,
1965 bit_field_size, bit_field_offset, false, false, eAddressTypeInvalid,
1966 0);
1967
1968 // Cache the value if we got one back...
1969 if (synthetic_child) {
1970 AddSyntheticChild(index_const_str, synthetic_child);
1971 synthetic_child_sp = synthetic_child->GetSP();
1972 synthetic_child_sp->SetName(index_str);
1973 synthetic_child_sp->m_flags.m_is_bitfield_for_scalar = true;
1974 }
1975 }
1976 }
1977 return synthetic_child_sp;
1978}
1979
1981 uint32_t offset, const CompilerType &type, bool can_create,
1982 ConstString name_const_str) {
1983
1984 ValueObjectSP synthetic_child_sp;
1985
1986 if (name_const_str.IsEmpty()) {
1987 name_const_str.SetString("@" + std::to_string(offset));
1988 }
1989
1990 // Check if we have already created a synthetic array member in this valid
1991 // object. If we have we will re-use it.
1992 synthetic_child_sp = GetSyntheticChild(name_const_str);
1993
1994 if (synthetic_child_sp.get())
1995 return synthetic_child_sp;
1996
1997 if (!can_create)
1998 return {};
1999
2001 std::optional<uint64_t> size = llvm::expectedToOptional(
2003 if (!size)
2004 return {};
2005 ValueObjectChild *synthetic_child =
2006 new ValueObjectChild(*this, type, name_const_str, *size, offset, 0, 0,
2007 false, false, eAddressTypeInvalid, 0);
2008 if (synthetic_child) {
2009 AddSyntheticChild(name_const_str, synthetic_child);
2010 synthetic_child_sp = synthetic_child->GetSP();
2011 synthetic_child_sp->SetName(name_const_str);
2012 synthetic_child_sp->m_flags.m_is_child_at_offset = true;
2013 synthetic_child_sp->SetSyntheticChildrenGenerated(true);
2014 }
2015 return synthetic_child_sp;
2016}
2017
2019 const CompilerType &type,
2020 bool can_create,
2021 ConstString name_const_str) {
2022 ValueObjectSP synthetic_child_sp;
2023
2024 if (name_const_str.IsEmpty()) {
2025 char name_str[128];
2026 snprintf(name_str, sizeof(name_str), "base%s@%i",
2027 type.GetTypeName().AsCString("<unknown>"), offset);
2028 name_const_str.SetCString(name_str);
2029 }
2030
2031 // Check if we have already created a synthetic array member in this valid
2032 // object. If we have we will re-use it.
2033 synthetic_child_sp = GetSyntheticChild(name_const_str);
2034
2035 if (synthetic_child_sp.get())
2036 return synthetic_child_sp;
2037
2038 if (!can_create)
2039 return {};
2040
2041 const bool is_base_class = true;
2042
2044 std::optional<uint64_t> size = llvm::expectedToOptional(
2046 if (!size)
2047 return {};
2048 ValueObjectChild *synthetic_child =
2049 new ValueObjectChild(*this, type, name_const_str, *size, offset, 0, 0,
2050 is_base_class, false, eAddressTypeInvalid, 0);
2051 if (synthetic_child) {
2052 AddSyntheticChild(name_const_str, synthetic_child);
2053 synthetic_child_sp = synthetic_child->GetSP();
2054 synthetic_child_sp->SetName(name_const_str);
2055 }
2056 return synthetic_child_sp;
2057}
2058
2059// your expression path needs to have a leading . or -> (unless it somehow
2060// "looks like" an array, in which case it has a leading [ symbol). while the [
2061// is meaningful and should be shown to the user, . and -> are just parser
2062// design, but by no means added information for the user.. strip them off
2063static llvm::StringRef
2064SkipLeadingExpressionPathSeparators(llvm::StringRef expression) {
2065 if (expression.starts_with('.'))
2066 return expression.drop_front();
2067 if (expression.starts_with("->"))
2068 return expression.drop_front(2);
2069 return expression;
2070}
2071
2074 bool can_create) {
2075 ValueObjectSP synthetic_child_sp;
2076 ConstString name_const_string(expression);
2077 // Check if we have already created a synthetic array member in this valid
2078 // object. If we have we will re-use it.
2079 synthetic_child_sp = GetSyntheticChild(name_const_string);
2080 if (!synthetic_child_sp) {
2081 // We haven't made a synthetic array member for expression yet, so lets
2082 // make one and cache it for any future reference.
2083 synthetic_child_sp = GetValueForExpressionPath(
2084 expression, nullptr, nullptr,
2085 GetValueForExpressionPathOptions().SetSyntheticChildrenTraversal(
2087 None));
2088
2089 // Cache the value if we got one back...
2090 if (synthetic_child_sp.get()) {
2091 // FIXME: this causes a "real" child to end up with its name changed to
2092 // the contents of expression
2093 AddSyntheticChild(name_const_string, synthetic_child_sp.get());
2094 synthetic_child_sp->SetName(
2096 }
2097 }
2098 return synthetic_child_sp;
2099}
2100
2102 TargetSP target_sp(GetTargetSP());
2103 if (target_sp && !target_sp->GetEnableSyntheticValue()) {
2104 m_synthetic_value = nullptr;
2105 return;
2106 }
2107
2109
2111 return;
2112
2114
2115 if (curr_synth_sp.get() == nullptr)
2116 return;
2117
2118 if (curr_synth_sp == prev_synth_sp && m_synthetic_value)
2119 return;
2120
2121 m_synthetic_value = new ValueObjectSynthetic(*this, curr_synth_sp);
2122}
2123
2125 if (use_dynamic == eNoDynamicValues)
2126 return;
2127
2128 if (!m_dynamic_value && !IsDynamic()) {
2130 Process *process = exe_ctx.GetProcessPtr();
2131 if (process && process->IsPossibleDynamicValue(*this)) {
2133 m_dynamic_value = new ValueObjectDynamicValue(*this, use_dynamic);
2134 }
2135 }
2136}
2137
2139 if (use_dynamic == eNoDynamicValues)
2140 return ValueObjectSP();
2141
2142 if (!IsDynamic() && m_dynamic_value == nullptr) {
2143 CalculateDynamicValue(use_dynamic);
2144 }
2145 if (m_dynamic_value && m_dynamic_value->GetError().Success())
2146 return m_dynamic_value->GetSP();
2147 else
2148 return ValueObjectSP();
2149}
2150
2153
2155 return m_synthetic_value->GetSP();
2156 else
2157 return ValueObjectSP();
2158}
2159
2162
2163 if (m_synthetic_children_sp.get() == nullptr)
2164 return false;
2165
2167
2168 return m_synthetic_value != nullptr;
2169}
2170
2172 if (GetParent()) {
2173 if (GetParent()->IsBaseClass())
2174 return GetParent()->GetNonBaseClassParent();
2175 else
2176 return GetParent();
2177 }
2178 return nullptr;
2179}
2180
2182 GetExpressionPathFormat epformat) {
2183 // synthetic children do not actually "exist" as part of the hierarchy, and
2184 // sometimes they are consed up in ways that don't make sense from an
2185 // underlying language/API standpoint. So, use a special code path here to
2186 // return something that can hopefully be used in expression
2187 if (m_flags.m_is_synthetic_children_generated) {
2189
2190 if (m_value.GetValueType() == Value::ValueType::LoadAddress) {
2192 s.Printf("((%s)0x%" PRIx64 ")", GetTypeName().AsCString("void"),
2194 return;
2195 } else {
2196 uint64_t load_addr =
2197 m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
2198 if (load_addr != LLDB_INVALID_ADDRESS) {
2199 s.Printf("(*( (%s *)0x%" PRIx64 "))", GetTypeName().AsCString("void"),
2200 load_addr);
2201 return;
2202 }
2203 }
2204 }
2205
2206 if (CanProvideValue()) {
2207 s.Printf("((%s)%s)", GetTypeName().AsCString("void"),
2209 return;
2210 }
2211
2212 return;
2213 }
2214
2215 const bool is_deref_of_parent = IsDereferenceOfParent();
2216
2217 if (is_deref_of_parent &&
2219 // this is the original format of GetExpressionPath() producing code like
2220 // *(a_ptr).memberName, which is entirely fine, until you put this into
2221 // StackFrame::GetValueForVariableExpressionPath() which prefers to see
2222 // a_ptr->memberName. the eHonorPointers mode is meant to produce strings
2223 // in this latter format
2224 s.PutCString("*(");
2225 }
2226
2227 ValueObject *parent = GetParent();
2228
2229 if (parent) {
2230 parent->GetExpressionPath(s, epformat);
2231 const CompilerType parentType = parent->GetCompilerType();
2232 if (parentType.IsPointerType() &&
2233 parentType.GetPointeeType().IsArrayType(nullptr, nullptr, nullptr)) {
2234 // When the parent is a pointer to an array, then we have to:
2235 // - follow the expression path of the parent with "[0]"
2236 // (that will indicate dereferencing the pointer to the array)
2237 // - and then follow that with this ValueObject's name
2238 // (which will be something like "[i]" to indicate
2239 // the i-th element of the array)
2240 s.PutCString("[0]");
2241 s.PutCString(GetName().GetCString());
2242 return;
2243 }
2244 }
2245
2246 // if we are a deref_of_parent just because we are synthetic array members
2247 // made up to allow ptr[%d] syntax to work in variable printing, then add our
2248 // name ([%d]) to the expression path
2249 if (m_flags.m_is_array_item_for_pointer &&
2251 s.PutCString(m_name.GetStringRef());
2252
2253 if (!IsBaseClass()) {
2254 if (!is_deref_of_parent) {
2255 ValueObject *non_base_class_parent = GetNonBaseClassParent();
2256 if (non_base_class_parent &&
2257 !non_base_class_parent->GetName().IsEmpty()) {
2258 CompilerType non_base_class_parent_compiler_type =
2259 non_base_class_parent->GetCompilerType();
2260 if (non_base_class_parent_compiler_type) {
2261 if (parent && parent->IsDereferenceOfParent() &&
2263 s.PutCString("->");
2264 } else {
2265 const uint32_t non_base_class_parent_type_info =
2266 non_base_class_parent_compiler_type.GetTypeInfo();
2267
2268 if (non_base_class_parent_type_info & eTypeIsPointer) {
2269 s.PutCString("->");
2270 } else if ((non_base_class_parent_type_info & eTypeHasChildren) &&
2271 !(non_base_class_parent_type_info &
2272 (eTypeIsArray | eTypeIsVector))) {
2273 s.PutChar('.');
2274 }
2275 }
2276 }
2277 }
2278
2279 const char *name = GetName().GetCString();
2280 if (name)
2281 s.PutCString(name);
2282 }
2283 }
2284
2285 if (is_deref_of_parent &&
2287 s.PutChar(')');
2288 }
2289}
2290
2291// Return the alternate value (synthetic if the input object is non-synthetic
2292// and otherwise) this is permitted by the expression path options.
2294 ValueObject &valobj,
2296 synth_traversal) {
2297 using SynthTraversal =
2299
2300 if (valobj.IsSynthetic()) {
2301 if (synth_traversal == SynthTraversal::FromSynthetic ||
2302 synth_traversal == SynthTraversal::Both)
2303 return valobj.GetNonSyntheticValue();
2304 } else {
2305 if (synth_traversal == SynthTraversal::ToSynthetic ||
2306 synth_traversal == SynthTraversal::Both)
2307 return valobj.GetSyntheticValue();
2308 }
2309 return nullptr;
2310}
2311
2312// Dereference the provided object or the alternate value, if permitted by the
2313// expression path options.
2315 ValueObject &valobj,
2317 synth_traversal,
2318 Status &error) {
2319 error.Clear();
2320 ValueObjectSP result = valobj.Dereference(error);
2321 if (!result || error.Fail()) {
2322 if (ValueObjectSP alt_obj = GetAlternateValue(valobj, synth_traversal)) {
2323 error.Clear();
2324 result = alt_obj->Dereference(error);
2325 }
2326 }
2327 return result;
2328}
2329
2331 llvm::StringRef expression, ExpressionPathScanEndReason *reason_to_stop,
2332 ExpressionPathEndResultType *final_value_type,
2333 const GetValueForExpressionPathOptions &options,
2334 ExpressionPathAftermath *final_task_on_target) {
2335
2336 ExpressionPathScanEndReason dummy_reason_to_stop =
2338 ExpressionPathEndResultType dummy_final_value_type =
2340 ExpressionPathAftermath dummy_final_task_on_target =
2342
2344 expression, reason_to_stop ? reason_to_stop : &dummy_reason_to_stop,
2345 final_value_type ? final_value_type : &dummy_final_value_type, options,
2346 final_task_on_target ? final_task_on_target
2347 : &dummy_final_task_on_target);
2348
2349 if (!final_task_on_target ||
2350 *final_task_on_target == ValueObject::eExpressionPathAftermathNothing)
2351 return ret_val;
2352
2353 if (ret_val.get() &&
2354 ((final_value_type ? *final_value_type : dummy_final_value_type) ==
2355 eExpressionPathEndResultTypePlain)) // I can only deref and takeaddress
2356 // of plain objects
2357 {
2358 if ((final_task_on_target ? *final_task_on_target
2359 : dummy_final_task_on_target) ==
2361 Status error;
2363 *ret_val, options.m_synthetic_children_traversal, error);
2364 if (error.Fail() || !final_value.get()) {
2365 if (reason_to_stop)
2366 *reason_to_stop =
2368 if (final_value_type)
2370 return ValueObjectSP();
2371 } else {
2372 if (final_task_on_target)
2373 *final_task_on_target = ValueObject::eExpressionPathAftermathNothing;
2374 return final_value;
2375 }
2376 }
2377 if (*final_task_on_target ==
2379 Status error;
2380 ValueObjectSP final_value = ret_val->AddressOf(error);
2381 if (error.Fail() || !final_value.get()) {
2382 if (reason_to_stop)
2383 *reason_to_stop =
2385 if (final_value_type)
2387 return ValueObjectSP();
2388 } else {
2389 if (final_task_on_target)
2390 *final_task_on_target = ValueObject::eExpressionPathAftermathNothing;
2391 return final_value;
2392 }
2393 }
2394 }
2395 return ret_val; // final_task_on_target will still have its original value, so
2396 // you know I did not do it
2397}
2398
2400 llvm::StringRef expression, ExpressionPathScanEndReason *reason_to_stop,
2401 ExpressionPathEndResultType *final_result,
2402 const GetValueForExpressionPathOptions &options,
2403 ExpressionPathAftermath *what_next) {
2404 ValueObjectSP root = GetSP();
2405
2406 if (!root)
2407 return nullptr;
2408
2409 llvm::StringRef remainder = expression;
2410
2411 while (true) {
2412 llvm::StringRef temp_expression = remainder;
2413
2414 CompilerType root_compiler_type = root->GetCompilerType();
2415 CompilerType pointee_compiler_type;
2416 Flags pointee_compiler_type_info;
2417
2418 Flags root_compiler_type_info(
2419 root_compiler_type.GetTypeInfo(&pointee_compiler_type));
2420 if (pointee_compiler_type)
2421 pointee_compiler_type_info.Reset(pointee_compiler_type.GetTypeInfo());
2422
2423 if (temp_expression.empty()) {
2425 return root;
2426 }
2427
2428 switch (temp_expression.front()) {
2429 case '-': {
2430 temp_expression = temp_expression.drop_front();
2431 if (options.m_check_dot_vs_arrow_syntax &&
2432 root_compiler_type_info.Test(eTypeIsPointer)) // if you are trying to
2433 // use -> on a
2434 // non-pointer and I
2435 // must catch the error
2436 {
2437 *reason_to_stop =
2440 return ValueObjectSP();
2441 }
2442 if (root_compiler_type_info.Test(eTypeIsObjC) && // if yo are trying to
2443 // extract an ObjC IVar
2444 // when this is forbidden
2445 root_compiler_type_info.Test(eTypeIsPointer) &&
2446 options.m_no_fragile_ivar) {
2447 *reason_to_stop =
2450 return ValueObjectSP();
2451 }
2452 if (!temp_expression.starts_with(">")) {
2453 *reason_to_stop =
2456 return ValueObjectSP();
2457 }
2458 }
2459 [[fallthrough]];
2460 case '.': // or fallthrough from ->
2461 {
2462 if (options.m_check_dot_vs_arrow_syntax &&
2463 temp_expression.front() == '.' &&
2464 root_compiler_type_info.Test(eTypeIsPointer)) // if you are trying to
2465 // use . on a pointer
2466 // and I must catch the
2467 // error
2468 {
2469 *reason_to_stop =
2472 return nullptr;
2473 }
2474 temp_expression = temp_expression.drop_front(); // skip . or >
2475
2476 size_t next_sep_pos = temp_expression.find_first_of("-.[", 1);
2477 if (next_sep_pos == llvm::StringRef::npos) {
2478 // if no other separator just expand this last layer
2479 llvm::StringRef child_name = temp_expression;
2480 ValueObjectSP child_valobj_sp =
2481 root->GetChildMemberWithName(child_name);
2482 if (!child_valobj_sp) {
2483 if (ValueObjectSP altroot = GetAlternateValue(
2484 *root, options.m_synthetic_children_traversal))
2485 child_valobj_sp = altroot->GetChildMemberWithName(child_name);
2486 }
2487 if (child_valobj_sp) {
2488 *reason_to_stop =
2491 return child_valobj_sp;
2492 }
2495 return nullptr;
2496 }
2497
2498 llvm::StringRef next_separator = temp_expression.substr(next_sep_pos);
2499 llvm::StringRef child_name = temp_expression.slice(0, next_sep_pos);
2500
2501 ValueObjectSP child_valobj_sp = root->GetChildMemberWithName(child_name);
2502 if (!child_valobj_sp) {
2503 if (ValueObjectSP altroot = GetAlternateValue(
2504 *root, options.m_synthetic_children_traversal))
2505 child_valobj_sp = altroot->GetChildMemberWithName(child_name);
2506 }
2507 if (child_valobj_sp) {
2508 root = child_valobj_sp;
2509 remainder = next_separator;
2511 continue;
2512 }
2515 return nullptr;
2516 }
2517 case '[': {
2518 if (!root_compiler_type_info.Test(eTypeIsArray) &&
2519 !root_compiler_type_info.Test(eTypeIsPointer) &&
2520 !root_compiler_type_info.Test(
2521 eTypeIsVector)) // if this is not a T[] nor a T*
2522 {
2523 if (!root_compiler_type_info.Test(
2524 eTypeIsScalar)) // if this is not even a scalar...
2525 {
2526 if (options.m_synthetic_children_traversal ==
2528 None) // ...only chance left is synthetic
2529 {
2530 *reason_to_stop =
2533 return ValueObjectSP();
2534 }
2535 } else if (!options.m_allow_bitfields_syntax) // if this is a scalar,
2536 // check that we can
2537 // expand bitfields
2538 {
2539 *reason_to_stop =
2542 return ValueObjectSP();
2543 }
2544 }
2545 if (temp_expression.size() == 1) {
2546 *reason_to_stop =
2549 return nullptr;
2550 }
2551
2552 if (temp_expression[1] ==
2553 ']') // if this is an unbounded range it only works for arrays
2554 {
2555 if (!root_compiler_type_info.Test(eTypeIsArray)) {
2556 *reason_to_stop =
2559 return nullptr;
2560 } else // even if something follows, we cannot expand unbounded ranges,
2561 // just let the caller do it
2562 {
2563 *reason_to_stop =
2565 *final_result =
2567 return root;
2568 }
2569 }
2570
2571 size_t close_bracket_position = temp_expression.find(']', 1);
2572 if (close_bracket_position ==
2573 llvm::StringRef::npos) // if there is no ], this is a syntax error
2574 {
2575 *reason_to_stop =
2578 return nullptr;
2579 }
2580
2581 llvm::StringRef bracket_expr =
2582 temp_expression.slice(1, close_bracket_position);
2583
2584 // If this was an empty expression it would have been caught by the if
2585 // above.
2586 assert(!bracket_expr.empty());
2587
2588 if (!bracket_expr.contains('-')) {
2589 // if no separator, this is of the form [N]. Note that this cannot be
2590 // an unbounded range of the form [], because that case was handled
2591 // above with an unconditional return.
2592 unsigned long index = 0;
2593 if (bracket_expr.getAsInteger(0, index)) {
2594 *reason_to_stop =
2597 return nullptr;
2598 }
2599 if (root->GetValueType() == eValueTypeRegister &&
2600 !root_compiler_type_info.Test(eTypeIsPointer) &&
2601 index > UINT32_MAX) {
2602 *reason_to_stop =
2605 return nullptr;
2606 }
2607
2608 // from here on we do have a valid index
2609 if (root_compiler_type_info.Test(eTypeIsArray)) {
2610 ValueObjectSP child_valobj_sp = root->GetChildAtIndex(index);
2611 if (!child_valobj_sp)
2612 child_valobj_sp = root->GetSyntheticArrayMember(index, true);
2613 if (!child_valobj_sp)
2614 if (root->HasSyntheticValue() &&
2615 llvm::expectedToOptional(
2616 root->GetSyntheticValue()->GetNumChildren())
2617 .value_or(0) > index)
2618 child_valobj_sp =
2619 root->GetSyntheticValue()->GetChildAtIndex(index);
2620 if (child_valobj_sp) {
2621 root = child_valobj_sp;
2622 remainder =
2623 temp_expression.substr(close_bracket_position + 1); // skip ]
2625 continue;
2626 } else {
2627 *reason_to_stop =
2630 return nullptr;
2631 }
2632 } else if (root_compiler_type_info.Test(eTypeIsPointer)) {
2633 if (*what_next ==
2634 ValueObject::
2635 eExpressionPathAftermathDereference && // if this is a
2636 // ptr-to-scalar, I
2637 // am accessing it
2638 // by index and I
2639 // would have
2640 // deref'ed anyway,
2641 // then do it now
2642 // and use this as
2643 // a bitfield
2644 pointee_compiler_type_info.Test(eTypeIsScalar)) {
2645 Status error;
2647 *root, options.m_synthetic_children_traversal, error);
2648 if (error.Fail() || !root) {
2649 *reason_to_stop =
2652 return nullptr;
2653 } else {
2655 continue;
2656 }
2657 } else {
2658 if (root->GetCompilerType().GetMinimumLanguage() ==
2660 pointee_compiler_type_info.AllClear(eTypeIsPointer) &&
2661 root->HasSyntheticValue() &&
2664 SyntheticChildrenTraversal::ToSynthetic ||
2667 SyntheticChildrenTraversal::Both)) {
2668 root = root->GetSyntheticValue()->GetChildAtIndex(index);
2669 } else
2670 root = root->GetSyntheticArrayMember(index, true);
2671 if (!root) {
2672 *reason_to_stop =
2675 return nullptr;
2676 } else {
2677 remainder =
2678 temp_expression.substr(close_bracket_position + 1); // skip ]
2680 continue;
2681 }
2682 }
2683 } else if (root_compiler_type_info.Test(eTypeIsScalar)) {
2684 root = root->GetSyntheticBitFieldChild(index, index, true);
2685 if (!root) {
2686 *reason_to_stop =
2689 return nullptr;
2690 } else // we do not know how to expand members of bitfields, so we
2691 // just return and let the caller do any further processing
2692 {
2693 *reason_to_stop = ValueObject::
2694 eExpressionPathScanEndReasonBitfieldRangeOperatorMet;
2696 return root;
2697 }
2698 } else if (root_compiler_type_info.Test(eTypeIsVector)) {
2699 root = root->GetChildAtIndex(index);
2700 if (!root) {
2701 *reason_to_stop =
2704 return ValueObjectSP();
2705 } else {
2706 remainder =
2707 temp_expression.substr(close_bracket_position + 1); // skip ]
2709 continue;
2710 }
2711 } else if (options.m_synthetic_children_traversal ==
2713 SyntheticChildrenTraversal::ToSynthetic ||
2716 SyntheticChildrenTraversal::Both) {
2717 if (root->HasSyntheticValue())
2718 root = root->GetSyntheticValue();
2719 else if (!root->IsSynthetic()) {
2720 *reason_to_stop =
2723 return nullptr;
2724 }
2725 // if we are here, then root itself is a synthetic VO.. should be
2726 // good to go
2727
2728 if (!root) {
2729 *reason_to_stop =
2732 return nullptr;
2733 }
2734 root = root->GetChildAtIndex(index);
2735 if (!root) {
2736 *reason_to_stop =
2739 return nullptr;
2740 } else {
2741 remainder =
2742 temp_expression.substr(close_bracket_position + 1); // skip ]
2744 continue;
2745 }
2746 } else {
2747 *reason_to_stop =
2750 return nullptr;
2751 }
2752 } else {
2753 // we have a low and a high index
2754 llvm::StringRef sleft, sright;
2755 unsigned long low_index, high_index;
2756 std::tie(sleft, sright) = bracket_expr.split('-');
2757 if (sleft.getAsInteger(0, low_index) ||
2758 sright.getAsInteger(0, high_index)) {
2759 *reason_to_stop =
2762 return nullptr;
2763 }
2764
2765 if (low_index > high_index) // swap indices if required
2766 std::swap(low_index, high_index);
2767
2768 if (root->GetValueType() == eValueTypeRegister &&
2769 high_index > UINT32_MAX) {
2770 *reason_to_stop =
2773 return nullptr;
2774 }
2775
2776 if (root_compiler_type_info.Test(
2777 eTypeIsScalar)) // expansion only works for scalars
2778 {
2779 root = root->GetSyntheticBitFieldChild(low_index, high_index, true);
2780 if (!root) {
2781 *reason_to_stop =
2784 return nullptr;
2785 } else {
2786 *reason_to_stop = ValueObject::
2787 eExpressionPathScanEndReasonBitfieldRangeOperatorMet;
2789 return root;
2790 }
2791 } else if (root_compiler_type_info.Test(
2792 eTypeIsPointer) && // if this is a ptr-to-scalar, I am
2793 // accessing it by index and I would
2794 // have deref'ed anyway, then do it
2795 // now and use this as a bitfield
2796 *what_next ==
2798 pointee_compiler_type_info.Test(eTypeIsScalar)) {
2799 Status error;
2801 *root, options.m_synthetic_children_traversal, error);
2802 if (error.Fail() || !root) {
2803 *reason_to_stop =
2806 return nullptr;
2807 } else {
2809 continue;
2810 }
2811 } else {
2812 *reason_to_stop =
2815 return root;
2816 }
2817 }
2818 break;
2819 }
2820 default: // some non-separator is in the way
2821 {
2822 *reason_to_stop =
2825 return nullptr;
2826 }
2827 }
2828 }
2829}
2830
2831llvm::Error ValueObject::Dump(Stream &s) {
2832 return Dump(s, DumpValueObjectOptions(*this));
2833}
2834
2836 const DumpValueObjectOptions &options) {
2837 ValueObjectPrinter printer(*this, &s, options);
2838 return printer.PrintValueObject();
2839}
2840
2842 ValueObjectSP valobj_sp;
2843
2844 if (UpdateValueIfNeeded(false) && m_error.Success()) {
2846
2847 DataExtractor data;
2848 data.SetByteOrder(m_data.GetByteOrder());
2849 data.SetAddressByteSize(m_data.GetAddressByteSize());
2850
2851 if (IsBitfield()) {
2853 m_error = v.GetValueAsData(&exe_ctx, data, GetModule().get());
2854 } else
2855 m_error = m_value.GetValueAsData(&exe_ctx, data, GetModule().get());
2856
2858 exe_ctx.GetBestExecutionContextScope(), GetCompilerType(), name, data,
2859 GetAddressOf().address);
2860 }
2861
2862 if (!valobj_sp) {
2865 exe_ctx.GetBestExecutionContextScope(), m_error.Clone());
2866 }
2867 return valobj_sp;
2868}
2869
2871 lldb::DynamicValueType dynValue, bool synthValue) {
2872 ValueObjectSP result_sp;
2873 switch (dynValue) {
2876 if (!IsDynamic())
2877 result_sp = GetDynamicValue(dynValue);
2878 } break;
2880 if (IsDynamic())
2881 result_sp = GetStaticValue();
2882 } break;
2883 }
2884 if (!result_sp)
2885 result_sp = GetSP();
2886 assert(result_sp);
2887
2888 bool is_synthetic = result_sp->IsSynthetic();
2889 if (synthValue && !is_synthetic) {
2890 if (auto synth_sp = result_sp->GetSyntheticValue())
2891 return synth_sp;
2892 }
2893 if (!synthValue && is_synthetic) {
2894 if (auto non_synth_sp = result_sp->GetNonSyntheticValue())
2895 return non_synth_sp;
2896 }
2897
2898 return result_sp;
2899}
2900
2902 if (m_deref_valobj)
2903 return m_deref_valobj->GetSP();
2904
2905 std::string deref_name_str;
2906 uint32_t deref_byte_size = 0;
2907 int32_t deref_byte_offset = 0;
2908 CompilerType compiler_type = GetCompilerType();
2909 uint64_t language_flags = 0;
2910
2912
2913 CompilerType deref_compiler_type;
2914 auto deref_compiler_type_or_err = compiler_type.GetDereferencedType(
2915 &exe_ctx, deref_name_str, deref_byte_size, deref_byte_offset, this,
2916 language_flags);
2917
2918 std::string deref_error;
2919 if (deref_compiler_type_or_err) {
2920 deref_compiler_type = *deref_compiler_type_or_err;
2921 } else {
2922 deref_error = llvm::toString(deref_compiler_type_or_err.takeError());
2923 LLDB_LOG(GetLog(LLDBLog::Types), "could not find child: {0}", deref_error);
2924 }
2925
2926 if (deref_compiler_type && deref_byte_size) {
2927 ConstString deref_name;
2928 if (!deref_name_str.empty())
2929 deref_name.SetCString(deref_name_str.c_str());
2930
2932 new ValueObjectChild(*this, deref_compiler_type, deref_name,
2933 deref_byte_size, deref_byte_offset, 0, 0, false,
2934 true, eAddressTypeInvalid, language_flags);
2935 }
2936
2937 // In case of incomplete deref compiler type, use the pointee type and try
2938 // to recreate a new ValueObjectChild using it.
2939 if (!m_deref_valobj) {
2940 // FIXME(#59012): C++ stdlib formatters break with incomplete types (e.g.
2941 // `std::vector<int> &`). Remove ObjC restriction once that's resolved.
2944 deref_compiler_type = compiler_type.GetPointeeType();
2945
2946 if (deref_compiler_type) {
2947 ConstString deref_name;
2948 if (!deref_name_str.empty())
2949 deref_name.SetCString(deref_name_str.c_str());
2950
2952 *this, deref_compiler_type, deref_name, deref_byte_size,
2953 deref_byte_offset, 0, 0, false, true, eAddressTypeInvalid,
2954 language_flags);
2955 }
2956 }
2957 }
2958
2959 if (!m_deref_valobj && IsSynthetic())
2960 m_deref_valobj = GetChildMemberWithName("$$dereference$$").get();
2961
2962 if (m_deref_valobj) {
2963 error.Clear();
2964 return m_deref_valobj->GetSP();
2965 } else {
2966 StreamString strm;
2967 GetExpressionPath(strm);
2968
2969 if (deref_error.empty())
2971 "dereference failed: (%s) %s",
2972 GetTypeName().AsCString("<invalid type>"), strm.GetData());
2973 else
2975 "dereference failed: %s: (%s) %s", deref_error.c_str(),
2976 GetTypeName().AsCString("<invalid type>"), strm.GetData());
2977 return ValueObjectSP();
2978 }
2979}
2980
2982 auto [addr, address_type] = GetAddressOf(/*scalar_is_load_address=*/false);
2983 error.Clear();
2984 if (addr != LLDB_INVALID_ADDRESS && address_type != eAddressTypeHost) {
2985 switch (address_type) {
2986 case eAddressTypeInvalid: {
2987 StreamString expr_path_strm;
2988 GetExpressionPath(expr_path_strm);
2989 error = Status::FromErrorStringWithFormat("'%s' is not in memory",
2990 expr_path_strm.GetData());
2991 } break;
2992
2993 case eAddressTypeFile:
2994 case eAddressTypeLoad: {
2995 if (m_addr_of_valobj_sp &&
2996 m_addr_of_valobj_sp->GetValueAsUnsigned(LLDB_INVALID_ADDRESS) == addr)
2997 return m_addr_of_valobj_sp;
2998 m_addr_of_valobj_sp.reset();
2999 CompilerType compiler_type = GetCompilerType();
3000 if (compiler_type) {
3001 std::string name(1, '&');
3002 name.append(m_name.AsCString(""));
3004
3005 lldb::DataBufferSP buffer(
3006 new lldb_private::DataBufferHeap(&addr, sizeof(lldb::addr_t)));
3009 compiler_type.GetPointerType(), ConstString(name), buffer,
3011 LLDB_INVALID_ADDRESS, this->GetManager());
3012 }
3013 } break;
3014 default:
3015 break;
3016 }
3017 } else {
3018 StreamString expr_path_strm;
3019 GetExpressionPath(expr_path_strm);
3021 "'%s' doesn't have a valid address", expr_path_strm.GetData());
3022 }
3023
3024 return m_addr_of_valobj_sp;
3025}
3026
3028 return ValueObjectCast::Create(*this, GetName(), compiler_type);
3029}
3030
3032 // Only allow casts if the original type is equal or larger than the cast
3033 // type, unless we know this is a load address. Getting the size wrong for
3034 // a host side storage could leak lldb memory, so we absolutely want to
3035 // prevent that. We may not always get the right value, for instance if we
3036 // have an expression result value that's copied into a storage location in
3037 // the target may not have copied enough memory. I'm not trying to fix that
3038 // here, I'm just making Cast from a smaller to a larger possible in all the
3039 // cases where that doesn't risk making a Value out of random lldb memory.
3040 // You have to check the ValueObject's Value for the address types, since
3041 // ValueObjects that use live addresses will tell you they fetch data from the
3042 // live address, but once they are made, they actually don't.
3043 // FIXME: Can we make ValueObject's with a live address fetch "more data" from
3044 // the live address if it is still valid?
3045
3046 Status error;
3047 CompilerType my_type = GetCompilerType();
3048
3049 ExecutionContextScope *exe_scope =
3051 if (llvm::expectedToOptional(compiler_type.GetByteSize(exe_scope))
3052 .value_or(0) <=
3053 llvm::expectedToOptional(GetCompilerType().GetByteSize(exe_scope))
3054 .value_or(0) ||
3055 m_value.GetValueType() == Value::ValueType::LoadAddress)
3056 return DoCast(compiler_type);
3057
3059 "Can only cast to a type that is equal to or smaller "
3060 "than the orignal type.");
3061
3063 ExecutionContext(GetExecutionContextRef()).GetBestExecutionContextScope(),
3064 std::move(error));
3065}
3066
3067lldb::ValueObjectSP ValueObject::Clone(llvm::StringRef new_name) {
3068 return ValueObjectCast::Create(*this, new_name, GetCompilerType());
3069}
3070
3072 CompilerType &compiler_type) {
3073 ValueObjectSP valobj_sp;
3074 addr_t ptr_value = GetPointerValue().address;
3075
3076 if (ptr_value != LLDB_INVALID_ADDRESS) {
3077 Address ptr_addr(ptr_value);
3079 valobj_sp = ValueObjectMemory::Create(
3080 exe_ctx.GetBestExecutionContextScope(), name, ptr_addr, compiler_type);
3081 }
3082 return valobj_sp;
3083}
3084
3086 ValueObjectSP valobj_sp;
3087 addr_t ptr_value = GetPointerValue().address;
3088
3089 if (ptr_value != LLDB_INVALID_ADDRESS) {
3090 Address ptr_addr(ptr_value);
3092 valobj_sp = ValueObjectMemory::Create(
3093 exe_ctx.GetBestExecutionContextScope(), name, ptr_addr, type_sp);
3094 }
3095 return valobj_sp;
3096}
3097
3099 if (auto target_sp = GetTargetSP()) {
3100 const bool scalar_is_load_address = true;
3101 auto [addr_value, addr_type] = GetAddressOf(scalar_is_load_address);
3102 if (addr_type == eAddressTypeFile) {
3103 lldb::ModuleSP module_sp(GetModule());
3104 if (!module_sp)
3105 addr_value = LLDB_INVALID_ADDRESS;
3106 else {
3107 Address tmp_addr;
3108 module_sp->ResolveFileAddress(addr_value, tmp_addr);
3109 addr_value = tmp_addr.GetLoadAddress(target_sp.get());
3110 }
3111 } else if (addr_type == eAddressTypeHost ||
3112 addr_type == eAddressTypeInvalid)
3113 addr_value = LLDB_INVALID_ADDRESS;
3114 return addr_value;
3115 }
3116 return LLDB_INVALID_ADDRESS;
3117}
3118
3119llvm::Expected<lldb::ValueObjectSP> ValueObject::CastDerivedToBaseType(
3120 CompilerType type, const llvm::ArrayRef<uint32_t> &base_type_indices) {
3121 // Make sure the starting type and the target type are both valid for this
3122 // type of cast; otherwise return the shared pointer to the original
3123 // (unchanged) ValueObject.
3124 if (!type.IsPointerType() && !type.IsReferenceType())
3125 return llvm::createStringError(
3126 "Invalid target type: should be a pointer or a reference");
3127
3128 CompilerType start_type = GetCompilerType();
3129 if (start_type.IsReferenceType())
3130 start_type = start_type.GetNonReferenceType();
3131
3132 auto target_record_type =
3133 type.IsPointerType() ? type.GetPointeeType() : type.GetNonReferenceType();
3134 auto start_record_type =
3135 start_type.IsPointerType() ? start_type.GetPointeeType() : start_type;
3136
3137 if (!target_record_type.IsRecordType() || !start_record_type.IsRecordType())
3138 return llvm::createStringError(
3139 "Underlying start & target types should be record types");
3140
3141 if (target_record_type.CompareTypes(start_record_type))
3142 return llvm::createStringError(
3143 "Underlying start & target types should be different");
3144
3145 if (base_type_indices.empty())
3146 return llvm::createStringError("children sequence must be non-empty");
3147
3148 // Both the starting & target types are valid for the cast, and the list of
3149 // base class indices is non-empty, so we can proceed with the cast.
3150
3151 lldb::TargetSP target = GetTargetSP();
3152 // The `value` can be a pointer, but GetChildAtIndex works for pointers too.
3153 lldb::ValueObjectSP inner_value = GetSP();
3154
3155 for (const uint32_t i : base_type_indices)
3156 // Create synthetic value if needed.
3157 inner_value =
3158 inner_value->GetChildAtIndex(i, /*can_create_synthetic*/ true);
3159
3160 // At this point type of `inner_value` should be the dereferenced target
3161 // type.
3162 CompilerType inner_value_type = inner_value->GetCompilerType();
3163 if (type.IsPointerType()) {
3164 if (!inner_value_type.CompareTypes(type.GetPointeeType()))
3165 return llvm::createStringError(
3166 "casted value doesn't match the desired type");
3167
3168 uintptr_t addr = inner_value->GetLoadAddress();
3169 llvm::StringRef name = "";
3170 ExecutionContext exe_ctx(target.get(), false);
3171 return ValueObject::CreateValueObjectFromAddress(name, addr, exe_ctx, type,
3172 /* do deref */ false);
3173 }
3174
3175 // At this point the target type should be a reference.
3176 if (!inner_value_type.CompareTypes(type.GetNonReferenceType()))
3177 return llvm::createStringError(
3178 "casted value doesn't match the desired type");
3179
3180 return lldb::ValueObjectSP(inner_value->Cast(type.GetNonReferenceType()));
3181}
3182
3183llvm::Expected<lldb::ValueObjectSP>
3185 // Make sure the starting type and the target type are both valid for this
3186 // type of cast; otherwise return the shared pointer to the original
3187 // (unchanged) ValueObject.
3188 if (!type.IsPointerType() && !type.IsReferenceType())
3189 return llvm::createStringError(
3190 "Invalid target type: should be a pointer or a reference");
3191
3192 CompilerType start_type = GetCompilerType();
3193 if (start_type.IsReferenceType())
3194 start_type = start_type.GetNonReferenceType();
3195
3196 auto target_record_type =
3197 type.IsPointerType() ? type.GetPointeeType() : type.GetNonReferenceType();
3198 auto start_record_type =
3199 start_type.IsPointerType() ? start_type.GetPointeeType() : start_type;
3200
3201 if (!target_record_type.IsRecordType() || !start_record_type.IsRecordType())
3202 return llvm::createStringError(
3203 "Underlying start & target types should be record types");
3204
3205 if (target_record_type.CompareTypes(start_record_type))
3206 return llvm::createStringError(
3207 "Underlying start & target types should be different");
3208
3209 CompilerType virtual_base;
3210 if (target_record_type.IsVirtualBase(start_record_type, &virtual_base)) {
3211 if (!virtual_base.IsValid())
3212 return llvm::createStringError("virtual base should be valid");
3213 return llvm::createStringError(
3214 llvm::Twine("cannot cast " + start_type.TypeDescription() + " to " +
3215 type.TypeDescription() + " via virtual base " +
3216 virtual_base.TypeDescription())
3217 .str());
3218 }
3219
3220 // Both the starting & target types are valid for the cast, so we can
3221 // proceed with the cast.
3222
3223 lldb::TargetSP target = GetTargetSP();
3224 auto pointer_type =
3225 type.IsPointerType() ? type : type.GetNonReferenceType().GetPointerType();
3226
3227 uintptr_t addr =
3229
3230 llvm::StringRef name = "";
3231 ExecutionContext exe_ctx(target.get(), false);
3233 name, addr - offset, exe_ctx, pointer_type, /* do_deref */ false);
3234
3235 if (type.IsPointerType())
3236 return value;
3237
3238 // At this point the target type is a reference. Since `value` is a pointer,
3239 // it has to be dereferenced.
3240 Status error;
3241 return value->Dereference(error);
3242}
3243
3245 bool is_scalar = GetCompilerType().IsScalarType();
3246 bool is_enum = GetCompilerType().IsEnumerationType();
3247 bool is_pointer =
3249 bool is_float = HasFloatingRepresentation(GetCompilerType());
3250 bool is_integer = GetCompilerType().IsInteger();
3252
3253 if (!type.IsScalarType())
3256 Status::FromErrorString("target type must be a scalar"));
3257
3258 if (!is_scalar && !is_enum && !is_pointer)
3261 Status::FromErrorString("argument must be a scalar, enum, or pointer"));
3262
3263 lldb::TargetSP target = GetTargetSP();
3264 uint64_t type_byte_size = 0;
3265 uint64_t val_byte_size = 0;
3266 if (auto temp = llvm::expectedToOptional(type.GetByteSize(target.get())))
3267 type_byte_size = temp.value();
3268 if (auto temp =
3269 llvm::expectedToOptional(GetCompilerType().GetByteSize(target.get())))
3270 val_byte_size = temp.value();
3271
3272 if (is_pointer) {
3273 if (!type.IsInteger() && !type.IsBoolean())
3276 Status::FromErrorString("target type must be an integer or boolean"));
3277 if (!type.IsBoolean() && type_byte_size < val_byte_size)
3281 "target type cannot be smaller than the pointer type"));
3282 }
3283
3284 if (type.IsBoolean()) {
3285 if (!is_scalar || is_integer)
3287 exe_ctx, type.GetTypeSystem().GetSharedPointer(),
3288 GetValueAsUnsigned(0) != 0, "result");
3289 else if (is_scalar && is_float) {
3290 auto float_value_or_err = GetValueAsAPFloat();
3291 if (float_value_or_err)
3293 exe_ctx, type.GetTypeSystem().GetSharedPointer(),
3294 !float_value_or_err->isZero(), "result");
3295 else
3299 "cannot get value as APFloat: %s",
3300 llvm::toString(float_value_or_err.takeError()).c_str()));
3301 }
3302 }
3303
3304 if (type.IsInteger()) {
3305 if (!is_scalar || is_integer) {
3306 auto int_value_or_err = GetValueAsAPSInt();
3307 if (int_value_or_err) {
3308 // Get the value as APSInt and extend or truncate it to the requested
3309 // size.
3310 llvm::APSInt ext =
3311 int_value_or_err->extOrTrunc(type_byte_size * CHAR_BIT);
3312 return ValueObject::CreateValueObjectFromAPInt(exe_ctx, ext, type,
3313 "result");
3314 } else
3318 "cannot get value as APSInt: %s",
3319 llvm::toString(int_value_or_err.takeError()).c_str()));
3320 } else if (is_scalar && is_float) {
3321 llvm::APSInt integer(type_byte_size * CHAR_BIT, !type.IsSigned());
3322 bool is_exact;
3323 auto float_value_or_err = GetValueAsAPFloat();
3324 if (float_value_or_err) {
3325 llvm::APFloatBase::opStatus status =
3326 float_value_or_err->convertToInteger(
3327 integer, llvm::APFloat::rmTowardZero, &is_exact);
3328
3329 // Casting floating point values that are out of bounds of the target
3330 // type is undefined behaviour.
3331 if (status & llvm::APFloatBase::opInvalidOp)
3335 "invalid cast from float to integer"));
3337 "result");
3338 } else {
3342 "cannot get value as APFloat: %s",
3343 llvm::toString(float_value_or_err.takeError()).c_str()));
3344 }
3345 }
3346 }
3347
3348 if (HasFloatingRepresentation(type)) {
3349 if (!is_scalar) {
3350 auto int_value_or_err = GetValueAsAPSInt();
3351 if (int_value_or_err) {
3352 llvm::APSInt ext =
3353 int_value_or_err->extOrTrunc(type_byte_size * CHAR_BIT);
3354 Scalar scalar_int(ext);
3355 llvm::APFloat f =
3357 return ValueObject::CreateValueObjectFromAPFloat(exe_ctx, f, type,
3358 "result");
3359 } else {
3363 "cannot get value as APSInt: %s",
3364 llvm::toString(int_value_or_err.takeError()).c_str()));
3365 }
3366 } else {
3367 if (is_integer) {
3368 auto int_value_or_err = GetValueAsAPSInt();
3369 if (int_value_or_err) {
3370 Scalar scalar_int(*int_value_or_err);
3371 llvm::APFloat f = scalar_int.CreateAPFloatFromAPSInt(
3373 return ValueObject::CreateValueObjectFromAPFloat(exe_ctx, f, type,
3374 "result");
3375 } else {
3379 "cannot get value as APSInt: %s",
3380 llvm::toString(int_value_or_err.takeError()).c_str()));
3381 }
3382 }
3383 if (is_float) {
3384 auto float_value_or_err = GetValueAsAPFloat();
3385 if (float_value_or_err) {
3386 Scalar scalar_float(*float_value_or_err);
3387 llvm::APFloat f = scalar_float.CreateAPFloatFromAPFloat(
3389 return ValueObject::CreateValueObjectFromAPFloat(exe_ctx, f, type,
3390 "result");
3391 } else {
3395 "cannot get value as APFloat: %s",
3396 llvm::toString(float_value_or_err.takeError()).c_str()));
3397 }
3398 }
3399 }
3400 }
3401
3404 Status::FromErrorString("Unable to perform requested cast"));
3405}
3406
3408 bool is_enum = GetCompilerType().IsEnumerationType();
3409 bool is_integer = GetCompilerType().IsInteger();
3410 bool is_float = HasFloatingRepresentation(GetCompilerType());
3412
3413 if (!is_enum && !is_integer && !is_float)
3417 "argument must be an integer, a float, or an enum"));
3418
3419 if (!type.IsEnumerationType())
3422 Status::FromErrorString("target type must be an enum"));
3423
3424 lldb::TargetSP target = GetTargetSP();
3425 uint64_t byte_size = 0;
3426 if (auto temp = llvm::expectedToOptional(type.GetByteSize(target.get())))
3427 byte_size = temp.value();
3428
3429 if (is_float) {
3430 llvm::APSInt integer(byte_size * CHAR_BIT,
3432 bool is_exact;
3433 auto value_or_err = GetValueAsAPFloat();
3434 if (value_or_err) {
3435 llvm::APFloatBase::opStatus status = value_or_err->convertToInteger(
3436 integer, llvm::APFloat::rmTowardZero, &is_exact);
3437
3438 // Casting floating point values that are out of bounds of the target
3439 // type is undefined behaviour.
3440 if (status & llvm::APFloatBase::opInvalidOp)
3443 Status::FromErrorString("invalid cast from float to integer"));
3445 "result");
3446 } else
3450 "cannot get value as APFloat: {0}",
3451 llvm::toString(value_or_err.takeError())));
3452 } else {
3453 // Get the value as APSInt and extend or truncate it to the requested size.
3454 auto value_or_err = GetValueAsAPSInt();
3455 if (value_or_err) {
3456 llvm::APSInt ext = value_or_err->extOrTrunc(byte_size * CHAR_BIT);
3457 return ValueObject::CreateValueObjectFromAPInt(exe_ctx, ext, type,
3458 "result");
3459 } else
3463 "cannot get value as APSInt: %s",
3464 llvm::toString(value_or_err.takeError()).c_str()));
3465 }
3468 Status::FromErrorString("Cannot perform requested cast"));
3469}
3470
3472
3474 bool use_selected)
3475 : m_mod_id(), m_exe_ctx_ref() {
3476 ExecutionContext exe_ctx(exe_scope);
3477 TargetSP target_sp(exe_ctx.GetTargetSP());
3478 if (target_sp) {
3479 m_exe_ctx_ref.SetTargetSP(target_sp);
3480 ProcessSP process_sp(exe_ctx.GetProcessSP());
3481 if (!process_sp)
3482 process_sp = target_sp->GetProcessSP();
3483
3484 if (process_sp) {
3485 m_mod_id = process_sp->GetModID();
3486 m_exe_ctx_ref.SetProcessSP(process_sp);
3487
3488 ThreadSP thread_sp(exe_ctx.GetThreadSP());
3489
3490 if (!thread_sp) {
3491 if (use_selected)
3492 thread_sp = process_sp->GetThreadList().GetSelectedThread();
3493 }
3494
3495 if (thread_sp) {
3496 m_exe_ctx_ref.SetThreadSP(thread_sp);
3497
3498 StackFrameSP frame_sp(exe_ctx.GetFrameSP());
3499 if (!frame_sp) {
3500 if (use_selected)
3501 frame_sp = thread_sp->GetSelectedFrame(DoNoSelectMostRelevantFrame);
3502 }
3503 if (frame_sp)
3504 m_exe_ctx_ref.SetFrameSP(frame_sp);
3505 }
3506 }
3507 }
3508}
3509
3513
3515
3516// This function checks the EvaluationPoint against the current process state.
3517// If the current state matches the evaluation point, or the evaluation point
3518// is already invalid, then we return false, meaning "no change". If the
3519// current state is different, we update our state, and return true meaning
3520// "yes, change". If we did see a change, we also set m_needs_update to true,
3521// so future calls to NeedsUpdate will return true. exe_scope will be set to
3522// the current execution context scope.
3523
3525 bool accept_invalid_exe_ctx) {
3526 // Start with the target, if it is NULL, then we're obviously not going to
3527 // get any further:
3528 const bool thread_and_frame_only_if_stopped = true;
3529 ExecutionContext exe_ctx(
3530 m_exe_ctx_ref.Lock(thread_and_frame_only_if_stopped));
3531
3532 if (exe_ctx.GetTargetPtr() == nullptr)
3533 return false;
3534
3535 // If we don't have a process nothing can change.
3536 Process *process = exe_ctx.GetProcessPtr();
3537 if (process == nullptr)
3538 return false;
3539
3540 // If our stop id is the current stop ID, nothing has changed:
3541 ProcessModID current_mod_id = process->GetModID();
3542
3543 // If the current stop id is 0, either we haven't run yet, or the process
3544 // state has been cleared. In either case, we aren't going to be able to sync
3545 // with the process state.
3546 if (current_mod_id.GetStopID() == 0)
3547 return false;
3548
3549 bool changed = false;
3550 const bool was_valid = m_mod_id.IsValid();
3551 if (was_valid) {
3552 if (m_mod_id == current_mod_id) {
3553 // Everything is already up to date in this object, no need to update the
3554 // execution context scope.
3555 changed = false;
3556 } else {
3557 m_mod_id = current_mod_id;
3558 m_needs_update = true;
3559 changed = true;
3560 }
3561 }
3562
3563 // Now re-look up the thread and frame in case the underlying objects have
3564 // gone away & been recreated. That way we'll be sure to return a valid
3565 // exe_scope. If we used to have a thread or a frame but can't find it
3566 // anymore, then mark ourselves as invalid.
3567
3568 if (!accept_invalid_exe_ctx) {
3569 if (m_exe_ctx_ref.HasThreadRef()) {
3570 ThreadSP thread_sp(m_exe_ctx_ref.GetThreadSP());
3571 if (thread_sp) {
3572 if (m_exe_ctx_ref.HasFrameRef()) {
3573 StackFrameSP frame_sp(m_exe_ctx_ref.GetFrameSP());
3574 if (!frame_sp) {
3575 // We used to have a frame, but now it is gone
3576 SetInvalid();
3577 changed = was_valid;
3578 }
3579 }
3580 } else {
3581 // We used to have a thread, but now it is gone
3582 SetInvalid();
3583 changed = was_valid;
3584 }
3585 }
3586 }
3587
3588 return changed;
3589}
3590
3592 ProcessSP process_sp(m_exe_ctx_ref.GetProcessSP());
3593 if (process_sp)
3594 m_mod_id = process_sp->GetModID();
3595 m_needs_update = false;
3596}
3597
3598void ValueObject::ClearUserVisibleData(uint32_t clear_mask) {
3599 if ((clear_mask & eClearUserVisibleDataItemsValue) ==
3601 m_value_str.clear();
3602
3603 if ((clear_mask & eClearUserVisibleDataItemsLocation) ==
3605 m_location_str.clear();
3606
3607 if ((clear_mask & eClearUserVisibleDataItemsSummary) ==
3609 m_summary_str.clear();
3610
3611 if ((clear_mask & eClearUserVisibleDataItemsDescription) ==
3613 m_object_desc_str.clear();
3614
3618 m_synthetic_value = nullptr;
3619 }
3620}
3621
3623 if (m_parent) {
3624 if (!m_parent->IsPointerOrReferenceType())
3625 return m_parent->GetSymbolContextScope();
3626 }
3627 return nullptr;
3628}
3629
3631 llvm::StringRef name, llvm::StringRef expression,
3632 const ExecutionContext &exe_ctx, ValueObject *parent) {
3633 return CreateValueObjectFromExpression(name, expression, exe_ctx,
3634 EvaluateExpressionOptions(), parent);
3635}
3636
3638 llvm::StringRef name, llvm::StringRef expression,
3639 const ExecutionContext &exe_ctx, const EvaluateExpressionOptions &options,
3640 ValueObject *parent) {
3641 // FIXME: I haven't handled parent in this case yet. That is a WHOLE lot of
3642 // plumbing.
3643
3644 lldb::ValueObjectSP retval_sp;
3645 lldb::TargetSP target_sp(exe_ctx.GetTargetSP());
3646 if (!target_sp)
3647 return retval_sp;
3648 if (expression.empty())
3649 return retval_sp;
3650
3651 target_sp->EvaluateExpression(expression, exe_ctx.GetFrameSP().get(),
3652 retval_sp, options);
3653 if (retval_sp && !name.empty())
3654 retval_sp->SetName(name);
3655 return retval_sp;
3656}
3657
3659 llvm::StringRef name, uint64_t address, const ExecutionContext &exe_ctx,
3660 CompilerType type, bool do_deref, ValueObject *parent) {
3661 if (type) {
3662 CompilerType pointer_type(type.GetPointerType());
3663 if (!do_deref)
3664 pointer_type = type;
3665 if (pointer_type) {
3666 lldb::DataBufferSP buffer(
3667 new lldb_private::DataBufferHeap(&address, sizeof(lldb::addr_t)));
3669 exe_ctx.GetBestExecutionContextScope(), pointer_type,
3670 ConstString(name), buffer, exe_ctx.GetByteOrder(),
3671 exe_ctx.GetAddressByteSize(), /*address=*/LLDB_INVALID_ADDRESS,
3672 parent ? parent->GetManager() : nullptr));
3673 if (ptr_result_valobj_sp) {
3674 if (do_deref)
3675 ptr_result_valobj_sp->GetValue().SetValueType(
3677 Status err;
3678 if (do_deref)
3679 ptr_result_valobj_sp = ptr_result_valobj_sp->Dereference(err);
3680 if (ptr_result_valobj_sp && !name.empty())
3681 ptr_result_valobj_sp->SetName(name);
3682 }
3683 return ptr_result_valobj_sp;
3684 }
3685 }
3686 return lldb::ValueObjectSP();
3687}
3688
3690 llvm::StringRef name, const DataExtractor &data,
3691 const ExecutionContext &exe_ctx, CompilerType type, ValueObject *parent) {
3692 lldb::ValueObjectSP new_value_sp;
3693 new_value_sp = ValueObjectConstResult::Create(
3694 exe_ctx.GetBestExecutionContextScope(), type, ConstString(name), data,
3695 LLDB_INVALID_ADDRESS, parent ? parent->GetManager() : nullptr);
3696 new_value_sp->SetAddressTypeOfChildren(eAddressTypeLoad);
3697 if (new_value_sp && !name.empty())
3698 new_value_sp->SetName(name);
3699 return new_value_sp;
3700}
3701
3703 const ExecutionContext &exe_ctx, const llvm::APInt &v, CompilerType type,
3704 llvm::StringRef name, ValueObject *parent) {
3705 uint64_t byte_size =
3706 llvm::expectedToOptional(
3708 .value_or(0);
3709 lldb::DataExtractorSP data_sp = std::make_shared<DataExtractor>(
3710 reinterpret_cast<const void *>(v.getRawData()), byte_size,
3711 exe_ctx.GetByteOrder(), exe_ctx.GetAddressByteSize());
3712 return ValueObject::CreateValueObjectFromData(name, *data_sp, exe_ctx, type,
3713 parent);
3714}
3715
3717 const ExecutionContext &exe_ctx, const llvm::APFloat &v, CompilerType type,
3718 llvm::StringRef name, ValueObject *parent) {
3719 return CreateValueObjectFromAPInt(exe_ctx, v.bitcastToAPInt(), type, name,
3720 parent);
3721}
3722
3724 const ExecutionContext &exe_ctx, Scalar &s, CompilerType type,
3725 llvm::StringRef name, ValueObject *parent) {
3727 exe_ctx.GetBestExecutionContextScope(), type, s, ConstString(name),
3728 /*module_ptr=*/nullptr, parent ? parent->GetManager() : nullptr);
3729}
3730
3732 const ExecutionContext &exe_ctx, TypeSystemSP typesystem_sp, bool value,
3733 llvm::StringRef name, ValueObject *parent) {
3734 CompilerType type = typesystem_sp->GetBasicTypeFromAST(lldb::eBasicTypeBool);
3736 uint64_t byte_size =
3737 llvm::expectedToOptional(type.GetByteSize(exe_scope)).value_or(0);
3738 lldb::DataExtractorSP data_sp = std::make_shared<DataExtractor>(
3739 reinterpret_cast<const void *>(&value), byte_size, exe_ctx.GetByteOrder(),
3740 exe_ctx.GetAddressByteSize());
3741 return ValueObject::CreateValueObjectFromData(name, *data_sp, exe_ctx, type,
3742 parent);
3743}
3744
3746 const ExecutionContext &exe_ctx, CompilerType type, llvm::StringRef name,
3747 ValueObject *parent) {
3748 if (!type.IsNullPtrType()) {
3749 lldb::ValueObjectSP ret_val;
3750 return ret_val;
3751 }
3752 uintptr_t zero = 0;
3753 uint64_t byte_size = 0;
3754 if (auto temp = llvm::expectedToOptional(
3756 byte_size = temp.value();
3757 lldb::DataExtractorSP data_sp = std::make_shared<DataExtractor>(
3758 reinterpret_cast<const void *>(zero), byte_size, exe_ctx.GetByteOrder(),
3759 exe_ctx.GetAddressByteSize());
3760 return ValueObject::CreateValueObjectFromData(name, *data_sp, exe_ctx, type,
3761 parent);
3762}
3763
3765 ValueObject *root(GetRoot());
3766 if (root != this)
3767 return root->GetModule();
3768 return lldb::ModuleSP();
3769}
3770
3772 if (m_root)
3773 return m_root;
3774 return (m_root = FollowParentChain([](ValueObject *vo) -> bool {
3775 return (vo->m_parent != nullptr);
3776 }));
3777}
3778
3781 ValueObject *vo = this;
3782 while (vo) {
3783 if (!f(vo))
3784 break;
3785 vo = vo->m_parent;
3786 }
3787 return vo;
3788}
3789
3798
3800 ValueObject *with_dv_info = this;
3801 while (with_dv_info) {
3802 if (with_dv_info->HasDynamicValueTypeInfo())
3803 return with_dv_info->GetDynamicValueTypeImpl();
3804 with_dv_info = with_dv_info->m_parent;
3805 }
3807}
3808
3810 const ValueObject *with_fmt_info = this;
3811 while (with_fmt_info) {
3812 if (with_fmt_info->m_format != lldb::eFormatDefault)
3813 return with_fmt_info->m_format;
3814 with_fmt_info = with_fmt_info->m_parent;
3815 }
3816 return m_format;
3817}
3818
3822 if (GetRoot()) {
3823 if (GetRoot() == this) {
3824 if (StackFrameSP frame_sp = GetFrameSP()) {
3825 const SymbolContext &sc(
3826 frame_sp->GetSymbolContext(eSymbolContextCompUnit));
3827 if (CompileUnit *cu = sc.comp_unit)
3828 type = cu->GetLanguage();
3829 }
3830 } else {
3832 }
3833 }
3834 }
3835 return (m_preferred_display_language = type); // only compute it once
3836}
3837
3842
3844 // we need to support invalid types as providers of values because some bare-
3845 // board debugging scenarios have no notion of types, but still manage to
3846 // have raw numeric values for things like registers. sigh.
3848 return (!type.IsValid()) || (0 != (type.GetTypeInfo() & eTypeHasValue));
3849}
3850
3852 if (!UpdateValueIfNeeded())
3853 return nullptr;
3854
3855 TargetSP target_sp(GetTargetSP());
3856 if (!target_sp)
3857 return nullptr;
3858
3859 PersistentExpressionState *persistent_state =
3860 target_sp->GetPersistentExpressionStateForLanguage(
3862
3863 if (!persistent_state)
3864 return nullptr;
3865
3866 ConstString name = persistent_state->GetNextPersistentVariableName();
3867
3868 ValueObjectSP const_result_sp =
3869 ValueObjectConstResult::Create(target_sp.get(), GetValue(), name);
3870
3871 ExpressionVariableSP persistent_var_sp =
3872 persistent_state->CreatePersistentVariable(const_result_sp);
3873 persistent_var_sp->m_live_sp = persistent_var_sp->m_frozen_sp;
3874 persistent_var_sp->m_flags |= ExpressionVariable::EVIsProgramReference;
3875
3876 return persistent_var_sp->GetValueObject();
3877}
3878
3882
3884 lldb::DynamicValueType use_dynamic, bool use_synthetic,
3885 const char *name)
3886 : m_use_dynamic(use_dynamic), m_use_synthetic(use_synthetic), m_name(name) {
3887 if (in_valobj_sp) {
3888 if ((m_valobj_sp = in_valobj_sp->GetQualifiedRepresentationIfAvailable(
3889 lldb::eNoDynamicValues, false))) {
3890 if (!m_name.IsEmpty())
3891 m_valobj_sp->SetName(m_name);
3892 }
3893 }
3894}
3895
3897 if (this != &rhs) {
3901 m_name = rhs.m_name;
3902 }
3903 return *this;
3904}
3905
3907 if (m_valobj_sp.get() == nullptr)
3908 return false;
3909
3910 // FIXME: This check is necessary but not sufficient. We for sure don't
3911 // want to touch SBValues whose owning
3912 // targets have gone away. This check is a little weak in that it
3913 // enforces that restriction when you call IsValid, but since IsValid
3914 // doesn't lock the target, you have no guarantee that the SBValue won't
3915 // go invalid after you call this... Also, an SBValue could depend on
3916 // data from one of the modules in the target, and those could go away
3917 // independently of the target, for instance if a module is unloaded.
3918 // But right now, neither SBValues nor ValueObjects know which modules
3919 // they depend on. So I have no good way to make that check without
3920 // tracking that in all the ValueObject subclasses.
3921 TargetSP target_sp = m_valobj_sp->GetTargetSP();
3922 return target_sp && target_sp->IsValid();
3923}
3924
3926 TargetAPIMutex &api_mutex,
3927 std::unique_lock<TargetAPIMutex> &lock,
3928 Status &error) {
3929 if (!m_valobj_sp) {
3930 error = Status::FromErrorString("invalid value object");
3931 return m_valobj_sp;
3932 }
3933
3935
3936 Target *target = value_sp->GetTargetSP().get();
3937 // If this ValueObject holds an error, then it is valuable for that.
3938 if (value_sp->GetError().Fail())
3939 return value_sp;
3940
3941 if (!target)
3942 return ValueObjectSP();
3943
3944 api_mutex = target->GetAPIMutex();
3945 lock = std::unique_lock<TargetAPIMutex>(api_mutex);
3946
3947 ProcessSP process_sp(value_sp->GetProcessSP());
3948 if (process_sp && !stop_locker.TryLock(&process_sp->GetRunLock())) {
3949 // We don't allow people to play around with ValueObject if the process
3950 // is running. If you want to look at values, pause the process, then
3951 // look.
3952 error = Status::FromErrorString("process must be stopped.");
3953 return ValueObjectSP();
3954 }
3955
3957 ValueObjectSP dynamic_sp = value_sp->GetDynamicValue(m_use_dynamic);
3958 if (dynamic_sp)
3959 value_sp = dynamic_sp;
3960 }
3961
3962 if (m_use_synthetic) {
3963 ValueObjectSP synthetic_sp = value_sp->GetSyntheticValue();
3964 if (synthetic_sp)
3965 value_sp = synthetic_sp;
3966 }
3967
3968 if (!value_sp)
3969 error = Status::FromErrorString("invalid value object");
3970 if (!m_name.IsEmpty())
3971 value_sp->SetName(m_name);
3972
3973 return value_sp;
3974}
static llvm::raw_ostream & error(Stream &strm)
#define integer
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:375
#define LLDB_LOG_ERRORV(log, error,...)
Definition Log.h:421
#define LLDB_LOGF(log,...)
Definition Log.h:389
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:405
static const char * ConvertBoolean(lldb::LanguageType language_type, const char *value_str)
static llvm::StringRef SkipLeadingExpressionPathSeparators(llvm::StringRef expression)
static bool CopyStringDataToBufferSP(const StreamString &source, lldb::WritableDataBufferSP &destination)
static ValueObjectSP DereferenceValueOrAlternate(ValueObject &valobj, ValueObject::GetValueForExpressionPathOptions::SyntheticChildrenTraversal synth_traversal, Status &error)
static bool HasFloatingRepresentation(CompilerType ct)
static ValueObjectSP GetAlternateValue(ValueObject &valobj, ValueObject::GetValueForExpressionPathOptions::SyntheticChildrenTraversal synth_traversal)
static std::atomic< user_id_t > g_value_obj_uid
A section + offset based address class.
Definition Address.h:62
lldb::addr_t GetLoadAddress(Target *target) const
Get the load address.
Definition Address.cpp:303
bool SetLoadAddress(lldb::addr_t load_addr, Target *target, bool allow_section_end=false)
Set the address to represent load_addr.
Definition Address.cpp:1029
An architecture specification class.
Definition ArchSpec.h:32
uint32_t GetAddressByteSize() const
Returns the size in bytes of an address of the current architecture.
Definition ArchSpec.cpp:894
lldb::ByteOrder GetByteOrder() const
Returns the byte order for the architecture specification.
Definition ArchSpec.cpp:943
A class that describes a compilation unit.
Definition CompileUnit.h:43
Generic representation of a type in a programming language.
bool IsEnumerationType(bool &is_signed) const
lldb::BasicType GetBasicTypeEnumeration() const
TypeSystemSPWrapper GetTypeSystem() const
Accessors.
bool IsPossibleDynamicType(CompilerType *target_type, bool check_cplusplus, bool check_objc) const
bool IsArrayType(CompilerType *element_type=nullptr, uint64_t *size=nullptr, bool *is_incomplete=nullptr) const
size_t GetIndexOfChildMemberWithName(llvm::StringRef name, bool omit_empty_base_classes, std::vector< uint32_t > &child_indexes) const
Lookup a child member given a name.
CompilerType GetPointerType() const
Return a new CompilerType that is a pointer to this type.
llvm::Expected< uint64_t > GetByteSize(ExecutionContextScope *exe_scope) const
Return the size of the type in bytes.
lldb::Encoding GetEncoding() const
CompilerType GetNonReferenceType() const
If this type is a reference to a type (L value or R value reference), return a new type with the refe...
ConstString GetTypeName(bool BaseOnly=false) const
bool IsEnumerationIntegerTypeSigned() const
bool IsReferenceType(CompilerType *pointee_type=nullptr, bool *is_rvalue=nullptr) const
bool IsInteger() const
This is used when you don't care about the signedness of the integer.
llvm::Expected< CompilerType > GetDereferencedType(ExecutionContext *exe_ctx, std::string &deref_name, uint32_t &deref_byte_size, int32_t &deref_byte_offset, ValueObject *valobj, uint64_t &language_flags) const
lldb::Format GetFormat() const
llvm::Expected< CompilerType > GetChildCompilerTypeAtIndex(ExecutionContext *exe_ctx, size_t idx, bool transparent_pointers, bool omit_empty_base_classes, bool ignore_array_bounds, std::string &child_name, uint32_t &child_byte_size, int32_t &child_byte_offset, uint32_t &child_bitfield_bit_size, uint32_t &child_bitfield_bit_offset, bool &child_is_base_class, bool &child_is_deref_of_parent, ValueObject *valobj, uint64_t &language_flags) const
CompilerType GetPointeeType() const
If this type is a pointer type, return the type that the pointer points to, else return an invalid ty...
bool IsUnscopedEnumerationType() const
uint32_t GetTypeInfo(CompilerType *pointee_or_element_compiler_type=nullptr) const
llvm::Expected< uint32_t > GetIndexOfChildWithName(llvm::StringRef name, bool omit_empty_base_classes) const
Lookup a child given a name.
bool CompareTypes(CompilerType rhs) const
bool IsPointerType(CompilerType *pointee_type=nullptr) const
A uniqued constant string class.
Definition ConstString.h:40
void SetCString(const char *cstr)
Set the C string value.
bool IsEmpty() const
Test for empty string.
llvm::StringRef GetStringRef() const
Get the string value as a llvm::StringRef.
void SetString(llvm::StringRef s)
const char * GetCString() const
Get the string value as a C string.
const char * AsCString(const char *value_if_empty) const
Get the string value as a C string.
A subclass of DataBuffer that stores a data buffer on the heap.
lldb::offset_t SetByteSize(lldb::offset_t byte_size)
Set the number of bytes in the data buffer.
void CopyData(const void *src, lldb::offset_t src_len)
Makes a copy of the src_len bytes in src.
An data extractor class.
virtual const uint8_t * PeekData(lldb::offset_t offset, lldb::offset_t length) const
Peek at a bytes at offset.
virtual uint64_t GetByteSize() const
Get the number of bytes contained in this object.
void SetByteOrder(lldb::ByteOrder byte_order)
Set the byte_order value.
const uint8_t * GetDataStart() const
Get the data start pointer.
virtual lldb::offset_t SetData(const void *bytes, lldb::offset_t length, lldb::ByteOrder byte_order)
Set data with a buffer that is caller owned.
uint32_t GetAddressByteSize() const
Get the current address size.
lldb::ByteOrder GetByteOrder() const
Get the current byte order value.
void SetAddressByteSize(uint32_t addr_size)
Set the address byte size.
lldb::offset_t CopyByteOrderedData(lldb::offset_t src_offset, lldb::offset_t src_len, void *dst, lldb::offset_t dst_len, lldb::ByteOrder dst_byte_order) const
Copy dst_len bytes from *offset_ptr and ensure the copied data is treated as a value that can be swap...
static lldb::TypeSummaryImplSP GetSummaryFormat(ValueObject &valobj, lldb::DynamicValueType use_dynamic)
static lldb::TypeFormatImplSP GetFormat(ValueObject &valobj, lldb::DynamicValueType use_dynamic)
static lldb::SyntheticChildrenSP GetSyntheticChildren(ValueObject &valobj, lldb::DynamicValueType use_dynamic)
A class that describes the declaration location of a lldb object.
Definition Declaration.h:24
void Clear()
Clear the object's state.
Definition Declaration.h:57
"lldb/Target/ExecutionContextScope.h" Inherit from this if your object can reconstruct its execution ...
virtual lldb::TargetSP CalculateTarget()=0
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
ExecutionContextScope * GetBestExecutionContextScope() const
const lldb::TargetSP & GetTargetSP() const
Get accessor to get the target shared pointer.
const lldb::ProcessSP & GetProcessSP() const
Get accessor to get the process shared pointer.
lldb::ByteOrder GetByteOrder() const
const lldb::StackFrameSP & GetFrameSP() const
Get accessor to get the frame shared pointer.
Target * GetTargetPtr() const
Returns a pointer to the target object.
const lldb::ThreadSP & GetThreadSP() const
Get accessor to get the thread shared pointer.
Process * GetProcessPtr() const
Returns a pointer to the process object.
@ EVIsProgramReference
This variable is a reference to a (possibly invalid) area managed by the target program.
A class to manage flags.
Definition Flags.h:22
bool AllClear(ValueType mask) const
Test if all bits in mask are clear.
Definition Flags.h:103
void Reset(ValueType flags)
Set accessor for all flags.
Definition Flags.h:52
bool Test(ValueType bit) const
Test a single flag bit.
Definition Flags.h:96
bool AnySet(ValueType mask) const
Test one or more flags.
Definition Flags.h:90
static lldb::Format GetSingleItemFormat(lldb::Format vector_format)
static Language * FindPlugin(lldb::LanguageType language)
Definition Language.cpp:86
static bool LanguageIsCFamily(lldb::LanguageType language)
Equivalent to LanguageIsC||LanguageIsObjC||LanguageIsCPlusPlus.
Definition Language.cpp:408
static bool LanguageIsObjC(lldb::LanguageType language)
Definition Language.cpp:386
virtual lldb::ExpressionVariableSP CreatePersistentVariable(const lldb::ValueObjectSP &valobj_sp)=0
virtual ConstString GetNextPersistentVariableName(bool is_error=false)=0
Return a new persistent variable name with the specified prefix.
uint32_t GetStopID() const
Definition Process.h:265
bool TryLock(ProcessRunLock *lock)
Try to acquire the read lock.
A plug-in interface definition class for debugging a process.
Definition Process.h:369
ProcessModID GetModID() const
Get the Modification ID of the process.
Definition Process.h:1513
ProcessRunLock::ProcessRunLocker StopLocker
Definition Process.h:410
bool IsPossibleDynamicValue(ValueObject &in_value)
Definition Process.cpp:1583
LanguageRuntime * GetLanguageRuntime(lldb::LanguageType language)
Definition Process.cpp:1555
size_t WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size, Status &error)
Write memory to a process.
Definition Process.cpp:2599
size_t WriteScalarToMemory(lldb::addr_t vm_addr, const Scalar &scalar, size_t size, Status &error)
Write all or part of a scalar value to memory.
Definition Process.cpp:2676
llvm::APFloat CreateAPFloatFromAPFloat(lldb::BasicType basic_type)
Definition Scalar.cpp:854
llvm::APFloat CreateAPFloatFromAPSInt(lldb::BasicType basic_type)
Definition Scalar.cpp:834
unsigned long long ULongLong(unsigned long long fail_value=0) const
Definition Scalar.cpp:366
llvm::APFloat GetAPFloat() const
Definition Scalar.h:190
long long SLongLong(long long fail_value=0) const
Definition Scalar.cpp:362
bool ExtractBitfield(uint32_t bit_size, uint32_t bit_offset)
Definition Scalar.cpp:816
Status SetValueFromCString(const char *s, lldb::Encoding encoding, size_t byte_size)
Definition Scalar.cpp:651
bool GetData(DataExtractor &data) const
Get data with a byte size of GetByteSize().
Definition Scalar.cpp:86
bool IsValid() const
Definition Scalar.h:111
llvm::APSInt GetAPSInt() const
Definition Scalar.h:188
An error handling class.
Definition Status.h:118
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Definition Status.cpp:106
static Status FromErrorString(const char *str)
Definition Status.h:141
const char * AsCString(const char *default_error_str="unknown error") const
Get the error string associated with the current error.
Definition Status.cpp:194
static Status static Status FromErrorStringWithFormatv(const char *format, Args &&...args)
Definition Status.h:151
static Status FromError(llvm::Error error)
Avoid using this in new code. Migrate APIs to llvm::Expected instead.
Definition Status.cpp:136
bool Success() const
Test for success condition.
Definition Status.cpp:303
const char * GetData() const
llvm::StringRef GetString() const
A stream class that can stream formatted output to a file.
Definition Stream.h:28
void Format(const char *format, Args &&... args)
Forwards the arguments to llvm::formatv and writes to the stream.
Definition Stream.h:370
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:134
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition Stream.cpp:63
size_t PutChar(char ch)
Definition Stream.cpp:131
Basic RAII class to increment the summary count when the call is complete.
Definition Statistics.h:253
"lldb/Symbol/SymbolContextScope.h" Inherit from this if your object is part of a symbol context and c...
Defines a symbol context baton that can be handed other debug core functions.
CompileUnit * comp_unit
The CompileUnit for a given query.
A Lockable handle over a Target's API mutex, returned by Target::GetAPIMutex() and backing the public...
uint32_t GetMaximumSizeOfStringSummary() const
Definition Target.cpp:5711
bool GetCheckValueObjectOwnership() const
Definition Target.cpp:6010
TargetAPIMutex GetAPIMutex()
Returns a handle resolved to the mutex to serialize on before touching the target through the SB API.
Definition Target.cpp:6114
virtual size_t ReadMemory(const Address &addr, void *dst, size_t dst_len, Status &error, bool force_live_memory=false, lldb::addr_t *load_addr_ptr=nullptr, bool *did_read_live_memory=nullptr)
Definition Target.cpp:2126
virtual bool FormatObject(ValueObject *valobj, std::string &dest) const =0
virtual bool FormatObject(ValueObject *valobj, std::string &dest, const TypeSummaryOptions &options)=0
lldb::LanguageType GetLanguage() const
TypeSummaryOptions & SetLanguage(lldb::LanguageType)
lldb::ValueObjectSP GetSP(Process::StopLocker &stop_locker, TargetAPIMutex &api_mutex, std::unique_lock< TargetAPIMutex > &lock, Status &error)
lldb::ValueObjectSP m_valobj_sp
lldb::DynamicValueType m_use_dynamic
ValueImpl & operator=(const ValueImpl &rhs)
static lldb::ValueObjectSP Create(ValueObject &parent, llvm::StringRef name, const CompilerType &cast_type)
static lldb::ValueObjectSP Create(ExecutionContextScope *exe_scope, lldb::ByteOrder byte_order, uint32_t addr_byte_size, lldb::addr_t address=LLDB_INVALID_ADDRESS, ValueObjectManager *manager=nullptr)
These routines create ValueObjectConstResult ValueObjects from various data sources.
A ValueObject that represents memory at a given address, viewed as some set lldb type.
static lldb::ValueObjectSP Create(ExecutionContextScope *exe_scope, llvm::StringRef name, const Address &address, lldb::TypeSP &type_sp, ValueObject *parent=nullptr)
static lldb::ValueObjectSP Create(ValueObject &parent)
bool SyncWithProcessState(bool accept_invalid_exe_ctx)
AddressType m_address_type_of_ptr_or_ref_children
void SetValueIsValid(bool valid)
EvaluationPoint m_update_point
Stores both the stop id and the full context at which this value was last updated.
lldb::TypeSummaryImplSP GetSummaryFormat()
lldb::ValueObjectSP CheckValueObjectOwnership(ValueObject *child)
llvm::SmallVector< uint8_t, 16 > m_value_checksum
static lldb::ValueObjectSP CreateValueObjectFromNullptr(const ExecutionContext &exe_ctx, CompilerType type, llvm::StringRef name, ValueObject *parent=nullptr)
Create a nullptr value object with the specified type (must be a nullptr type).
llvm::Expected< llvm::APFloat > GetValueAsAPFloat()
If the current ValueObject is of an appropriate type, convert the value to an APFloat and return that...
virtual uint32_t GetBitfieldBitSize()
void ClearUserVisibleData(uint32_t items=ValueObject::eClearUserVisibleDataItemsAllStrings)
ValueObject * FollowParentChain(std::function< bool(ValueObject *)>)
Given a ValueObject, loop over itself and its parent, and its parent's parent, .
CompilerType m_override_type
If the type of the value object should be overridden, the type to impose.
lldb::ValueObjectSP Cast(const CompilerType &compiler_type)
const EvaluationPoint & GetUpdatePoint() const
void AddSyntheticChild(ConstString key, ValueObject *valobj)
virtual uint64_t GetData(DataExtractor &data, Status &error)
friend class ValueObjectSynthetic
bool DumpPrintableRepresentation(Stream &s, ValueObjectRepresentationStyle val_obj_display=eValueObjectRepresentationStyleSummary, lldb::Format custom_format=lldb::eFormatInvalid, PrintableRepresentationSpecialCases special=PrintableRepresentationSpecialCases::eAllow, bool do_dump_error=true)
virtual lldb::ValueObjectSP GetChildAtIndex(uint32_t idx, bool can_create=true)
virtual lldb::DynamicValueType GetDynamicValueTypeImpl()
virtual bool GetIsConstant() const
virtual bool MightHaveChildren()
Find out if a ValueObject might have children.
virtual bool IsDereferenceOfParent()
virtual llvm::Expected< size_t > GetIndexOfChildWithName(llvm::StringRef name)
Return the index of the child named name.
static lldb::ValueObjectSP CreateValueObjectFromScalar(const ExecutionContext &exe_ctx, Scalar &s, CompilerType type, llvm::StringRef name, ValueObject *parent=nullptr)
Create a value object containing the given Scalar value.
virtual ValueObject * CreateSyntheticArrayMember(size_t idx)
Should only be called by ValueObject::GetSyntheticArrayMember().
void SetValueFormat(lldb::TypeFormatImplSP format)
virtual void CalculateSyntheticValue()
void SetPreferredDisplayLanguage(lldb::LanguageType lt)
struct lldb_private::ValueObject::Bitflags m_flags
ClusterManager< ValueObject > ValueObjectManager
ValueObject(ExecutionContextScope *exe_scope, ValueObjectManager &manager, AddressType child_ptr_or_ref_addr_type=eAddressTypeLoad)
Use this constructor to create a "root variable object".
std::string m_summary_str
Cached summary string that will get cleared if/when the value is updated.
virtual lldb::ValueObjectSP DoCast(const CompilerType &compiler_type)
lldb::ValueObjectSP GetSP()
virtual llvm::Error CanSetValue()
Check if the value may be writable.
ChildrenManager m_children
virtual lldb::ValueObjectSP CastPointerType(const char *name, CompilerType &ast_type)
Status m_error
An error object that can describe any errors that occur when updating values.
virtual size_t GetPointeeData(DataExtractor &data, uint32_t item_idx=0, uint32_t item_count=1)
lldb::ValueObjectSP GetSyntheticValue()
ValueObjectManager * m_manager
This object is managed by the root object (any ValueObject that gets created without a parent....
lldb::ValueObjectSP GetSyntheticBitFieldChild(uint32_t from, uint32_t to, bool can_create)
lldb::ProcessSP GetProcessSP() const
lldb::ValueObjectSP GetSyntheticChild(ConstString key) const
@ eExpressionPathScanEndReasonArrowInsteadOfDot
-> used when . should be used.
@ eExpressionPathScanEndReasonDereferencingFailed
Impossible to apply * operator.
@ eExpressionPathScanEndReasonNoSuchChild
Child element not found.
@ eExpressionPathScanEndReasonDotInsteadOfArrow
. used when -> should be used.
@ eExpressionPathScanEndReasonEndOfString
Out of data to parse.
@ eExpressionPathScanEndReasonRangeOperatorNotAllowed
[] not allowed by options.
@ eExpressionPathScanEndReasonEmptyRangeNotAllowed
[] only allowed for arrays.
@ eExpressionPathScanEndReasonRangeOperatorInvalid
[] not valid on objects other than scalars, pointers or arrays.
@ eExpressionPathScanEndReasonUnexpectedSymbol
Something is malformed in he expression.
@ eExpressionPathScanEndReasonArrayRangeOperatorMet
[] is good for arrays, but I cannot parse it.
@ eExpressionPathScanEndReasonSyntheticValueMissing
getting the synthetic children failed.
@ eExpressionPathScanEndReasonTakingAddressFailed
Impossible to apply & operator.
@ eExpressionPathScanEndReasonFragileIVarNotAllowed
ObjC ivar expansion not allowed.
virtual bool UpdateValue()=0
lldb::Format GetFormat() const
virtual lldb::VariableSP GetVariable()
@ eExpressionPathAftermathNothing
Just return it.
@ eExpressionPathAftermathDereference
Dereference the target.
@ eExpressionPathAftermathTakeAddress
Take target's address.
lldb::ValueObjectSP CastToBasicType(CompilerType type)
ValueObject * GetNonBaseClassParent()
virtual ValueObject * CreateChildAtIndex(size_t idx)
Should only be called by ValueObject::GetChildAtIndex().
lldb::ValueObjectSP GetValueForExpressionPath(llvm::StringRef expression, ExpressionPathScanEndReason *reason_to_stop=nullptr, ExpressionPathEndResultType *final_value_type=nullptr, const GetValueForExpressionPathOptions &options=GetValueForExpressionPathOptions::DefaultOptions(), ExpressionPathAftermath *final_task_on_target=nullptr)
virtual lldb::ValueObjectSP GetSyntheticChildAtOffset(uint32_t offset, const CompilerType &type, bool can_create, ConstString name_const_str=ConstString())
virtual void CalculateDynamicValue(lldb::DynamicValueType use_dynamic)
DataExtractor m_data
A data extractor that can be used to extract the value.
virtual llvm::Expected< uint64_t > GetByteSize()=0
virtual CompilerType GetCompilerTypeImpl()=0
virtual lldb::ValueObjectSP GetSyntheticBase(uint32_t offset, const CompilerType &type, bool can_create, ConstString name_const_str=ConstString())
virtual uint64_t GetValueAsUnsigned(uint64_t fail_value, bool *success=nullptr)
virtual lldb::ValueObjectSP GetChildMemberWithName(llvm::StringRef name, bool can_create=true)
lldb::ValueObjectSP CastToEnumType(CompilerType type)
llvm::Expected< uint32_t > GetNumChildren(uint32_t max=UINT32_MAX)
virtual lldb::ValueType GetValueType() const =0
virtual void GetExpressionPath(Stream &s, GetExpressionPathFormat=eGetExpressionPathFormatDereferencePointers)
virtual bool HasSyntheticValue()
lldb::StackFrameSP GetFrameSP() const
lldb::ValueObjectSP GetChildAtNamePath(llvm::ArrayRef< llvm::StringRef > names)
void SetSummaryFormat(lldb::TypeSummaryImplSP format)
virtual bool IsRuntimeSupportValue()
virtual ConstString GetTypeName()
DataExtractor & GetDataExtractor()
void SetValueDidChange(bool value_changed)
static lldb::ValueObjectSP CreateValueObjectFromBool(const ExecutionContext &exe_ctx, lldb::TypeSystemSP typesystem, bool value, llvm::StringRef name, ValueObject *parent=nullptr)
Create a value object containing the given boolean value.
ValueObjectManager * GetManager()
ValueObject * m_root
The root of the hierarchy for this ValueObject (or nullptr if never calculated).
lldb::addr_t GetLoadAddress()
Return the target load address associated with this value object.
virtual lldb::ModuleSP GetModule()
Return the module associated with this value object in case the value is from an executable file and ...
virtual lldb::ValueObjectSP GetDynamicValue(lldb::DynamicValueType valueType)
llvm::Expected< lldb::ValueObjectSP > CastDerivedToBaseType(CompilerType type, const llvm::ArrayRef< uint32_t > &base_type_indices)
Take a ValueObject whose type is an inherited class, and cast it to 'type', which should be one of it...
virtual lldb::ValueObjectSP AddressOf(Status &error)
lldb::DynamicValueType GetDynamicValueType()
llvm::Expected< lldb::ValueObjectSP > CastBaseToDerivedType(CompilerType type, uint64_t offset)
Take a ValueObject whose type is a base class, and cast it to 'type', which should be one of its deri...
lldb::SyntheticChildrenSP GetSyntheticChildren()
lldb::LanguageType m_preferred_display_language
uint32_t GetTypeInfo(CompilerType *pointee_or_element_compiler_type=nullptr)
virtual llvm::Expected< uint32_t > CalculateNumChildren(uint32_t max=UINT32_MAX)=0
Should only be called by ValueObject::GetNumChildren().
lldb::LanguageType GetObjectRuntimeLanguage()
virtual lldb::ValueObjectSP CreateConstantValue(ConstString name)
lldb::ValueObjectSP GetSyntheticExpressionPathChild(llvm::StringRef expression, bool can_create)
virtual bool IsLogicalTrue(Status &error)
virtual SymbolContextScope * GetSymbolContextScope()
virtual bool HasDynamicValueTypeInfo()
ValueObject * m_synthetic_value
virtual lldb::ValueObjectSP Clone(llvm::StringRef new_name)
Creates a copy of the ValueObject with a new name and setting the current ValueObject as its parent.
void SetNumChildren(uint32_t num_children)
ValueObject * m_parent
The parent value object, or nullptr if this has no parent.
static lldb::ValueObjectSP CreateValueObjectFromAPInt(const ExecutionContext &exe_ctx, const llvm::APInt &v, CompilerType type, llvm::StringRef name, ValueObject *parent=nullptr)
Create a value object containing the given APInt value.
virtual bool IsBaseClass()
llvm::Expected< bool > GetValueAsBool()
If the current ValueObject is of an appropriate type, convert the value to a boolean and return that.
virtual bool GetDeclaration(Declaration &decl)
llvm::Error SetValueFromInteger(const llvm::APInt &value, bool can_update_var=true)
Update an existing integer ValueObject with a new integer value.
static lldb::ValueObjectSP CreateValueObjectFromExpression(llvm::StringRef name, llvm::StringRef expression, const ExecutionContext &exe_ctx, ValueObject *parent=nullptr)
The following static routines create "Root" ValueObjects if parent is null.
lldb::ValueObjectSP GetQualifiedRepresentationIfAvailable(lldb::DynamicValueType dynValue, bool synthValue)
lldb::ValueObjectSP m_addr_of_valobj_sp
We have to hold onto a shared pointer to this one because it is created as an independent ValueObject...
std::pair< size_t, bool > ReadPointedString(lldb::WritableDataBufferSP &buffer_sp, Status &error, bool honor_array)
llvm::Error Dump(Stream &s)
bool UpdateValueIfNeeded(bool update_format=true)
AddressType GetAddressTypeOfChildren()
const Status & GetError()
lldb::TypeFormatImplSP m_type_format_sp
lldb::TargetSP GetTargetSP() const
@ eExpressionPathEndResultTypePlain
Anything but...
@ eExpressionPathEndResultTypeBoundedRange
A range [low-high].
@ eExpressionPathEndResultTypeBitfield
A bitfield.
@ eExpressionPathEndResultTypeUnboundedRange
A range [].
virtual lldb::ValueObjectSP Dereference(Status &error)
CompilerType GetCompilerType()
void SetPreferredDisplayLanguageIfNeeded(lldb::LanguageType)
virtual const char * GetValueAsCString()
bool HasSpecialPrintableRepresentation(ValueObjectRepresentationStyle val_obj_display, lldb::Format custom_format)
virtual const char * GetLocationAsCString()
ConstString GetName() const
std::string m_location_str
Cached location string that will get cleared if/when the value is updated.
lldb::ValueObjectSP GetVTable()
If this object represents a C++ class with a vtable, return an object that represents the virtual fun...
virtual bool SetValueFromCString(const char *value_str, Status &error)
virtual lldb::ValueObjectSP GetStaticValue()
lldb::ValueObjectSP Persist()
std::string m_object_desc_str
Cached result of the "object printer".
virtual ValueObject * GetParent()
static lldb::ValueObjectSP CreateValueObjectFromData(llvm::StringRef name, const DataExtractor &data, const ExecutionContext &exe_ctx, CompilerType type, ValueObject *parent=nullptr)
lldb::SyntheticChildrenSP m_synthetic_children_sp
As determined by DataVisualization - may be overridden.
static lldb::ValueObjectSP CreateValueObjectFromAPFloat(const ExecutionContext &exe_ctx, const llvm::APFloat &v, CompilerType type, llvm::StringRef name, ValueObject *parent=nullptr)
Create a value object containing the given APFloat value.
virtual uint32_t GetBitfieldBitOffset()
llvm::Expected< std::string > GetObjectDescription()
std::string m_old_value_str
Cached old value string from the last time the value was gotten.
virtual lldb::ValueObjectSP GetNonSyntheticValue()
virtual bool SetData(DataExtractor &data, Status &error)
virtual int64_t GetValueAsSigned(int64_t fail_value, bool *success=nullptr)
const char * GetSummaryAsCString(lldb::LanguageType lang=lldb::eLanguageTypeUnknown)
std::string m_value_str
Cached value string that will get cleared if/when the value is updated.
lldb::ValueObjectSP GetSyntheticArrayMember(size_t index, bool can_create)
virtual bool ResolveValue(Scalar &scalar)
llvm::Expected< llvm::APSInt > GetValueAsAPSInt()
If the current ValueObject is of an appropriate type, convert the value to an APSInt and return that.
void SetSyntheticChildren(const lldb::SyntheticChildrenSP &synth_sp)
ConstString m_name
The name of this object.
const char * GetLocationAsCStringImpl(const Value &value, const DataExtractor &data)
virtual void SetFormat(lldb::Format format)
ValueObject * m_dynamic_value
bool IsCStringContainer(bool check_pointer=false)
Returns true if this is a char* or a char[] if it is a char* and check_pointer is true,...
virtual bool IsSynthetic()
std::map< ConstString, ValueObject * > m_synthetic_children
llvm::ArrayRef< uint8_t > GetLocalBuffer() const
Returns the local buffer that this ValueObject points to if it's available.
std::optional< lldb::addr_t > GetStrippedPointerValue(lldb::addr_t address)
Remove ptrauth bits from address if the type has a ptrauth qualifier.
const ExecutionContextRef & GetExecutionContextRef() const
virtual AddrAndType GetAddressOf(bool scalar_is_load_address=true)
uint32_t GetNumChildrenIgnoringErrors(uint32_t max=UINT32_MAX)
Like GetNumChildren but returns 0 on error.
UserID m_id
Unique identifier for every value object.
const Value & GetValue() const
virtual lldb::LanguageType GetPreferredDisplayLanguage()
lldb::ValueObjectSP GetValueForExpressionPath_Impl(llvm::StringRef expression_cstr, ExpressionPathScanEndReason *reason_to_stop, ExpressionPathEndResultType *final_value_type, const GetValueForExpressionPathOptions &options, ExpressionPathAftermath *final_task_on_target)
static lldb::ValueObjectSP CreateValueObjectFromAddress(llvm::StringRef name, uint64_t address, const ExecutionContext &exe_ctx, CompilerType type, bool do_deref=true, ValueObject *parent=nullptr)
Given an address either create a value object containing the value at that address,...
const Scalar & GetScalar() const
See comment on m_scalar to understand what GetScalar returns.
Definition Value.h:114
Status GetValueAsData(ExecutionContext *exe_ctx, DataExtractor &data, Module *module)
Definition Value.cpp:324
RegisterInfo * GetRegisterInfo() const
Definition Value.cpp:143
ValueType
Type that describes Value::m_value.
Definition Value.h:42
@ HostAddress
A host address value (for memory in the process that < A is using liblldb).
Definition Value.h:53
@ FileAddress
A file address value.
Definition Value.h:48
@ LoadAddress
A load address value.
Definition Value.h:50
@ Scalar
A raw scalar value.
Definition Value.h:46
ValueType GetValueType() const
Definition Value.cpp:112
Scalar & ResolveValue(ExecutionContext *exe_ctx, Module *module=nullptr)
Definition Value.cpp:594
@ RegisterInfo
RegisterInfo * (can be a scalar or a vector register).
Definition Value.h:62
ContextType GetContextType() const
Definition Value.h:88
const CompilerType & GetCompilerType()
Definition Value.cpp:248
uint8_t * GetBytes()
Get a pointer to the data.
Definition DataBuffer.h:108
static bool ReadBufferAndDumpToStream(const ReadBufferAndDumpToStreamOptions &options)
@ ZeroTerminate
Stop printing at the first zero terminator.
@ Ignore
Don't look for a terminator - print the whole buffer.
#define UINT64_MAX
#define LLDB_INVALID_ADDRESS
#define UINT32_MAX
@ DoNoSelectMostRelevantFrame
lldb::ByteOrder InlHostByteOrder()
Definition Endian.h:25
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:338
std::shared_ptr< SummaryStatistics > SummaryStatisticsSP
Definition Statistics.h:33
@ eAddressTypeFile
Address is an address as found in an object or symbol file.
@ eAddressTypeLoad
Address is an address as in the current target inferior process.
@ eAddressTypeHost
Address is an address in the process that is running this code.
std::string toString(FormatterBytecode::OpCodes op)
std::shared_ptr< lldb_private::TypeSystem > TypeSystemSP
std::shared_ptr< lldb_private::ABI > ABISP
std::shared_ptr< lldb_private::StackFrame > StackFrameSP
std::shared_ptr< lldb_private::TypeSummaryImpl > TypeSummaryImplSP
std::shared_ptr< lldb_private::Thread > ThreadSP
std::shared_ptr< lldb_private::TypeFormatImpl > TypeFormatImplSP
std::shared_ptr< lldb_private::ValueObject > ValueObjectSP
std::shared_ptr< lldb_private::ExpressionVariable > ExpressionVariableSP
Format
Display format definitions.
@ eFormatCString
Null-terminated C strings.
@ eFormatCharArray
Print characters with no single quotes, used for character arrays that can contain non printable char...
@ eFormatVectorOfChar
@ eFormatVectorOfUInt64
@ eFormatVectorOfSInt64
@ eFormatComplex
Floating point complex type.
@ eFormatBytesWithASCII
@ eFormatOSType
OS character codes encoded into an integer 'PICT' 'text' etc...
@ eFormatVectorOfUInt128
@ eFormatVectorOfUInt8
@ eFormatComplexFloat
@ eFormatVectorOfFloat32
@ eFormatVectorOfSInt32
@ eFormatVectorOfSInt8
@ eFormatVectorOfUInt16
@ eFormatHexUppercase
@ eFormatVectorOfFloat64
@ eFormatCharPrintable
Only printable characters, '.' if not printable.
@ eFormatComplexInteger
Integer complex type.
@ eFormatVectorOfSInt16
@ eFormatFloat128
Disambiguate between 128-bit long double (which uses eFormatFloat) and __float128 (which uses eFormat...
@ eFormatVectorOfUInt32
uint64_t offset_t
Definition lldb-types.h:86
LanguageType
Programming language type.
@ eLanguageTypeUnknown
Unknown or invalid language value.
@ eLanguageTypeObjC
Objective-C.
std::shared_ptr< lldb_private::Type > TypeSP
std::shared_ptr< lldb_private::Process > ProcessSP
Encoding
Register encoding definitions.
@ eEncodingVector
vector registers
@ eValueTypeRegister
stack frame register value
std::shared_ptr< lldb_private::SyntheticChildren > SyntheticChildrenSP
std::shared_ptr< lldb_private::DataBuffer > DataBufferSP
std::shared_ptr< lldb_private::WritableDataBuffer > WritableDataBufferSP
uint64_t addr_t
Definition lldb-types.h:80
std::shared_ptr< lldb_private::Target > TargetSP
@ eDynamicDontRunTarget
@ eDynamicCanRunTarget
std::shared_ptr< lldb_private::DataExtractor > DataExtractorSP
std::shared_ptr< lldb_private::Module > ModuleSP
Every register is described in detail including its name, alternate name (optional),...
lldb::Encoding encoding
Encoding of the register bits.
const char * alt_name
Alternate name of this register, can be NULL.
const char * name
Name of this register, can't be NULL.
lldb::Format format
Default display format.