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 ValueObjectSP synthetic_child_sp;
1902 if (IsPointerType() || IsArrayType()) {
1903 std::string index_str = llvm::formatv("[{0}]", index);
1904 ConstString index_const_str(index_str);
1905 // Check if we have already created a synthetic array member in this valid
1906 // object. If we have we will re-use it.
1907 synthetic_child_sp = GetSyntheticChild(index_const_str);
1908 if (!synthetic_child_sp) {
1909 ValueObject *synthetic_child;
1910 // We haven't made a synthetic array member for INDEX yet, so lets make
1911 // one and cache it for any future reference.
1912 synthetic_child = CreateSyntheticArrayMember(index);
1913
1914 // Cache the value if we got one back...
1915 if (synthetic_child) {
1916 AddSyntheticChild(index_const_str, synthetic_child);
1917 synthetic_child_sp = synthetic_child->GetSP();
1918 synthetic_child_sp->SetName(index_str);
1919 synthetic_child_sp->m_flags.m_is_array_item_for_pointer = true;
1920 }
1921 }
1922 }
1923 return synthetic_child_sp;
1924}
1925
1927 bool can_create) {
1928 ValueObjectSP synthetic_child_sp;
1929 if (IsScalarType()) {
1930 std::string index_str = llvm::formatv("[{0}-{1}]", from, to);
1931 ConstString index_const_str(index_str);
1932 // Check if we have already created a synthetic array member in this valid
1933 // object. If we have we will re-use it.
1934 synthetic_child_sp = GetSyntheticChild(index_const_str);
1935 if (!synthetic_child_sp) {
1936 uint32_t bit_field_size = to - from + 1;
1937 uint32_t bit_field_offset = from;
1938 if (GetDataExtractor().GetByteOrder() == eByteOrderBig)
1939 bit_field_offset =
1940 llvm::expectedToOptional(GetByteSize()).value_or(0) * 8 -
1941 bit_field_size - bit_field_offset;
1942 // We haven't made a synthetic array member for INDEX yet, so lets make
1943 // one and cache it for any future reference.
1944 ValueObjectChild *synthetic_child = new ValueObjectChild(
1945 *this, GetCompilerType(), index_const_str,
1946 llvm::expectedToOptional(GetByteSize()).value_or(0), 0,
1947 bit_field_size, bit_field_offset, false, false, eAddressTypeInvalid,
1948 0);
1949
1950 // Cache the value if we got one back...
1951 if (synthetic_child) {
1952 AddSyntheticChild(index_const_str, synthetic_child);
1953 synthetic_child_sp = synthetic_child->GetSP();
1954 synthetic_child_sp->SetName(index_str);
1955 synthetic_child_sp->m_flags.m_is_bitfield_for_scalar = true;
1956 }
1957 }
1958 }
1959 return synthetic_child_sp;
1960}
1961
1963 uint32_t offset, const CompilerType &type, bool can_create,
1964 ConstString name_const_str) {
1965
1966 ValueObjectSP synthetic_child_sp;
1967
1968 if (name_const_str.IsEmpty()) {
1969 name_const_str.SetString("@" + std::to_string(offset));
1970 }
1971
1972 // Check if we have already created a synthetic array member in this valid
1973 // object. If we have we will re-use it.
1974 synthetic_child_sp = GetSyntheticChild(name_const_str);
1975
1976 if (synthetic_child_sp.get())
1977 return synthetic_child_sp;
1978
1979 if (!can_create)
1980 return {};
1981
1983 std::optional<uint64_t> size = llvm::expectedToOptional(
1985 if (!size)
1986 return {};
1987 ValueObjectChild *synthetic_child =
1988 new ValueObjectChild(*this, type, name_const_str, *size, offset, 0, 0,
1989 false, false, eAddressTypeInvalid, 0);
1990 if (synthetic_child) {
1991 AddSyntheticChild(name_const_str, synthetic_child);
1992 synthetic_child_sp = synthetic_child->GetSP();
1993 synthetic_child_sp->SetName(name_const_str);
1994 synthetic_child_sp->m_flags.m_is_child_at_offset = true;
1995 synthetic_child_sp->SetSyntheticChildrenGenerated(true);
1996 }
1997 return synthetic_child_sp;
1998}
1999
2001 const CompilerType &type,
2002 bool can_create,
2003 ConstString name_const_str) {
2004 ValueObjectSP synthetic_child_sp;
2005
2006 if (name_const_str.IsEmpty()) {
2007 char name_str[128];
2008 snprintf(name_str, sizeof(name_str), "base%s@%i",
2009 type.GetTypeName().AsCString("<unknown>"), offset);
2010 name_const_str.SetCString(name_str);
2011 }
2012
2013 // Check if we have already created a synthetic array member in this valid
2014 // object. If we have we will re-use it.
2015 synthetic_child_sp = GetSyntheticChild(name_const_str);
2016
2017 if (synthetic_child_sp.get())
2018 return synthetic_child_sp;
2019
2020 if (!can_create)
2021 return {};
2022
2023 const bool is_base_class = true;
2024
2026 std::optional<uint64_t> size = llvm::expectedToOptional(
2028 if (!size)
2029 return {};
2030 ValueObjectChild *synthetic_child =
2031 new ValueObjectChild(*this, type, name_const_str, *size, offset, 0, 0,
2032 is_base_class, false, eAddressTypeInvalid, 0);
2033 if (synthetic_child) {
2034 AddSyntheticChild(name_const_str, synthetic_child);
2035 synthetic_child_sp = synthetic_child->GetSP();
2036 synthetic_child_sp->SetName(name_const_str);
2037 }
2038 return synthetic_child_sp;
2039}
2040
2041// your expression path needs to have a leading . or -> (unless it somehow
2042// "looks like" an array, in which case it has a leading [ symbol). while the [
2043// is meaningful and should be shown to the user, . and -> are just parser
2044// design, but by no means added information for the user.. strip them off
2045static const char *SkipLeadingExpressionPathSeparators(const char *expression) {
2046 if (!expression || !expression[0])
2047 return expression;
2048 if (expression[0] == '.')
2049 return expression + 1;
2050 if (expression[0] == '-' && expression[1] == '>')
2051 return expression + 2;
2052 return expression;
2053}
2054
2057 bool can_create) {
2058 ValueObjectSP synthetic_child_sp;
2059 ConstString name_const_string(expression);
2060 // Check if we have already created a synthetic array member in this valid
2061 // object. If we have we will re-use it.
2062 synthetic_child_sp = GetSyntheticChild(name_const_string);
2063 if (!synthetic_child_sp) {
2064 // We haven't made a synthetic array member for expression yet, so lets
2065 // make one and cache it for any future reference.
2066 synthetic_child_sp = GetValueForExpressionPath(
2067 expression, nullptr, nullptr,
2068 GetValueForExpressionPathOptions().SetSyntheticChildrenTraversal(
2070 None));
2071
2072 // Cache the value if we got one back...
2073 if (synthetic_child_sp.get()) {
2074 // FIXME: this causes a "real" child to end up with its name changed to
2075 // the contents of expression
2076 AddSyntheticChild(name_const_string, synthetic_child_sp.get());
2077 synthetic_child_sp->SetName(
2079 }
2080 }
2081 return synthetic_child_sp;
2082}
2083
2085 TargetSP target_sp(GetTargetSP());
2086 if (target_sp && !target_sp->GetEnableSyntheticValue()) {
2087 m_synthetic_value = nullptr;
2088 return;
2089 }
2090
2092
2094 return;
2095
2097
2098 if (curr_synth_sp.get() == nullptr)
2099 return;
2100
2101 if (curr_synth_sp == prev_synth_sp && m_synthetic_value)
2102 return;
2103
2104 m_synthetic_value = new ValueObjectSynthetic(*this, curr_synth_sp);
2105}
2106
2108 if (use_dynamic == eNoDynamicValues)
2109 return;
2110
2111 if (!m_dynamic_value && !IsDynamic()) {
2113 Process *process = exe_ctx.GetProcessPtr();
2114 if (process && process->IsPossibleDynamicValue(*this)) {
2116 m_dynamic_value = new ValueObjectDynamicValue(*this, use_dynamic);
2117 }
2118 }
2119}
2120
2122 if (use_dynamic == eNoDynamicValues)
2123 return ValueObjectSP();
2124
2125 if (!IsDynamic() && m_dynamic_value == nullptr) {
2126 CalculateDynamicValue(use_dynamic);
2127 }
2128 if (m_dynamic_value && m_dynamic_value->GetError().Success())
2129 return m_dynamic_value->GetSP();
2130 else
2131 return ValueObjectSP();
2132}
2133
2136
2138 return m_synthetic_value->GetSP();
2139 else
2140 return ValueObjectSP();
2141}
2142
2145
2146 if (m_synthetic_children_sp.get() == nullptr)
2147 return false;
2148
2150
2151 return m_synthetic_value != nullptr;
2152}
2153
2155 if (GetParent()) {
2156 if (GetParent()->IsBaseClass())
2157 return GetParent()->GetNonBaseClassParent();
2158 else
2159 return GetParent();
2160 }
2161 return nullptr;
2162}
2163
2165 GetExpressionPathFormat epformat) {
2166 // synthetic children do not actually "exist" as part of the hierarchy, and
2167 // sometimes they are consed up in ways that don't make sense from an
2168 // underlying language/API standpoint. So, use a special code path here to
2169 // return something that can hopefully be used in expression
2170 if (m_flags.m_is_synthetic_children_generated) {
2172
2173 if (m_value.GetValueType() == Value::ValueType::LoadAddress) {
2175 s.Printf("((%s)0x%" PRIx64 ")", GetTypeName().AsCString("void"),
2177 return;
2178 } else {
2179 uint64_t load_addr =
2180 m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
2181 if (load_addr != LLDB_INVALID_ADDRESS) {
2182 s.Printf("(*( (%s *)0x%" PRIx64 "))", GetTypeName().AsCString("void"),
2183 load_addr);
2184 return;
2185 }
2186 }
2187 }
2188
2189 if (CanProvideValue()) {
2190 s.Printf("((%s)%s)", GetTypeName().AsCString("void"),
2192 return;
2193 }
2194
2195 return;
2196 }
2197
2198 const bool is_deref_of_parent = IsDereferenceOfParent();
2199
2200 if (is_deref_of_parent &&
2202 // this is the original format of GetExpressionPath() producing code like
2203 // *(a_ptr).memberName, which is entirely fine, until you put this into
2204 // StackFrame::GetValueForVariableExpressionPath() which prefers to see
2205 // a_ptr->memberName. the eHonorPointers mode is meant to produce strings
2206 // in this latter format
2207 s.PutCString("*(");
2208 }
2209
2210 ValueObject *parent = GetParent();
2211
2212 if (parent) {
2213 parent->GetExpressionPath(s, epformat);
2214 const CompilerType parentType = parent->GetCompilerType();
2215 if (parentType.IsPointerType() &&
2216 parentType.GetPointeeType().IsArrayType(nullptr, nullptr, nullptr)) {
2217 // When the parent is a pointer to an array, then we have to:
2218 // - follow the expression path of the parent with "[0]"
2219 // (that will indicate dereferencing the pointer to the array)
2220 // - and then follow that with this ValueObject's name
2221 // (which will be something like "[i]" to indicate
2222 // the i-th element of the array)
2223 s.PutCString("[0]");
2224 s.PutCString(GetName().GetCString());
2225 return;
2226 }
2227 }
2228
2229 // if we are a deref_of_parent just because we are synthetic array members
2230 // made up to allow ptr[%d] syntax to work in variable printing, then add our
2231 // name ([%d]) to the expression path
2232 if (m_flags.m_is_array_item_for_pointer &&
2234 s.PutCString(m_name.GetStringRef());
2235
2236 if (!IsBaseClass()) {
2237 if (!is_deref_of_parent) {
2238 ValueObject *non_base_class_parent = GetNonBaseClassParent();
2239 if (non_base_class_parent &&
2240 !non_base_class_parent->GetName().IsEmpty()) {
2241 CompilerType non_base_class_parent_compiler_type =
2242 non_base_class_parent->GetCompilerType();
2243 if (non_base_class_parent_compiler_type) {
2244 if (parent && parent->IsDereferenceOfParent() &&
2246 s.PutCString("->");
2247 } else {
2248 const uint32_t non_base_class_parent_type_info =
2249 non_base_class_parent_compiler_type.GetTypeInfo();
2250
2251 if (non_base_class_parent_type_info & eTypeIsPointer) {
2252 s.PutCString("->");
2253 } else if ((non_base_class_parent_type_info & eTypeHasChildren) &&
2254 !(non_base_class_parent_type_info & eTypeIsArray)) {
2255 s.PutChar('.');
2256 }
2257 }
2258 }
2259 }
2260
2261 const char *name = GetName().GetCString();
2262 if (name)
2263 s.PutCString(name);
2264 }
2265 }
2266
2267 if (is_deref_of_parent &&
2269 s.PutChar(')');
2270 }
2271}
2272
2273// Return the alternate value (synthetic if the input object is non-synthetic
2274// and otherwise) this is permitted by the expression path options.
2276 ValueObject &valobj,
2278 synth_traversal) {
2279 using SynthTraversal =
2281
2282 if (valobj.IsSynthetic()) {
2283 if (synth_traversal == SynthTraversal::FromSynthetic ||
2284 synth_traversal == SynthTraversal::Both)
2285 return valobj.GetNonSyntheticValue();
2286 } else {
2287 if (synth_traversal == SynthTraversal::ToSynthetic ||
2288 synth_traversal == SynthTraversal::Both)
2289 return valobj.GetSyntheticValue();
2290 }
2291 return nullptr;
2292}
2293
2294// Dereference the provided object or the alternate value, if permitted by the
2295// expression path options.
2297 ValueObject &valobj,
2299 synth_traversal,
2300 Status &error) {
2301 error.Clear();
2302 ValueObjectSP result = valobj.Dereference(error);
2303 if (!result || error.Fail()) {
2304 if (ValueObjectSP alt_obj = GetAlternateValue(valobj, synth_traversal)) {
2305 error.Clear();
2306 result = alt_obj->Dereference(error);
2307 }
2308 }
2309 return result;
2310}
2311
2313 llvm::StringRef expression, ExpressionPathScanEndReason *reason_to_stop,
2314 ExpressionPathEndResultType *final_value_type,
2315 const GetValueForExpressionPathOptions &options,
2316 ExpressionPathAftermath *final_task_on_target) {
2317
2318 ExpressionPathScanEndReason dummy_reason_to_stop =
2320 ExpressionPathEndResultType dummy_final_value_type =
2322 ExpressionPathAftermath dummy_final_task_on_target =
2324
2326 expression, reason_to_stop ? reason_to_stop : &dummy_reason_to_stop,
2327 final_value_type ? final_value_type : &dummy_final_value_type, options,
2328 final_task_on_target ? final_task_on_target
2329 : &dummy_final_task_on_target);
2330
2331 if (!final_task_on_target ||
2332 *final_task_on_target == ValueObject::eExpressionPathAftermathNothing)
2333 return ret_val;
2334
2335 if (ret_val.get() &&
2336 ((final_value_type ? *final_value_type : dummy_final_value_type) ==
2337 eExpressionPathEndResultTypePlain)) // I can only deref and takeaddress
2338 // of plain objects
2339 {
2340 if ((final_task_on_target ? *final_task_on_target
2341 : dummy_final_task_on_target) ==
2343 Status error;
2345 *ret_val, options.m_synthetic_children_traversal, error);
2346 if (error.Fail() || !final_value.get()) {
2347 if (reason_to_stop)
2348 *reason_to_stop =
2350 if (final_value_type)
2352 return ValueObjectSP();
2353 } else {
2354 if (final_task_on_target)
2355 *final_task_on_target = ValueObject::eExpressionPathAftermathNothing;
2356 return final_value;
2357 }
2358 }
2359 if (*final_task_on_target ==
2361 Status error;
2362 ValueObjectSP final_value = ret_val->AddressOf(error);
2363 if (error.Fail() || !final_value.get()) {
2364 if (reason_to_stop)
2365 *reason_to_stop =
2367 if (final_value_type)
2369 return ValueObjectSP();
2370 } else {
2371 if (final_task_on_target)
2372 *final_task_on_target = ValueObject::eExpressionPathAftermathNothing;
2373 return final_value;
2374 }
2375 }
2376 }
2377 return ret_val; // final_task_on_target will still have its original value, so
2378 // you know I did not do it
2379}
2380
2382 llvm::StringRef expression, ExpressionPathScanEndReason *reason_to_stop,
2383 ExpressionPathEndResultType *final_result,
2384 const GetValueForExpressionPathOptions &options,
2385 ExpressionPathAftermath *what_next) {
2386 ValueObjectSP root = GetSP();
2387
2388 if (!root)
2389 return nullptr;
2390
2391 llvm::StringRef remainder = expression;
2392
2393 while (true) {
2394 llvm::StringRef temp_expression = remainder;
2395
2396 CompilerType root_compiler_type = root->GetCompilerType();
2397 CompilerType pointee_compiler_type;
2398 Flags pointee_compiler_type_info;
2399
2400 Flags root_compiler_type_info(
2401 root_compiler_type.GetTypeInfo(&pointee_compiler_type));
2402 if (pointee_compiler_type)
2403 pointee_compiler_type_info.Reset(pointee_compiler_type.GetTypeInfo());
2404
2405 if (temp_expression.empty()) {
2407 return root;
2408 }
2409
2410 switch (temp_expression.front()) {
2411 case '-': {
2412 temp_expression = temp_expression.drop_front();
2413 if (options.m_check_dot_vs_arrow_syntax &&
2414 root_compiler_type_info.Test(eTypeIsPointer)) // if you are trying to
2415 // use -> on a
2416 // non-pointer and I
2417 // must catch the error
2418 {
2419 *reason_to_stop =
2422 return ValueObjectSP();
2423 }
2424 if (root_compiler_type_info.Test(eTypeIsObjC) && // if yo are trying to
2425 // extract an ObjC IVar
2426 // when this is forbidden
2427 root_compiler_type_info.Test(eTypeIsPointer) &&
2428 options.m_no_fragile_ivar) {
2429 *reason_to_stop =
2432 return ValueObjectSP();
2433 }
2434 if (!temp_expression.starts_with(">")) {
2435 *reason_to_stop =
2438 return ValueObjectSP();
2439 }
2440 }
2441 [[fallthrough]];
2442 case '.': // or fallthrough from ->
2443 {
2444 if (options.m_check_dot_vs_arrow_syntax &&
2445 temp_expression.front() == '.' &&
2446 root_compiler_type_info.Test(eTypeIsPointer)) // if you are trying to
2447 // use . on a pointer
2448 // and I must catch the
2449 // error
2450 {
2451 *reason_to_stop =
2454 return nullptr;
2455 }
2456 temp_expression = temp_expression.drop_front(); // skip . or >
2457
2458 size_t next_sep_pos = temp_expression.find_first_of("-.[", 1);
2459 if (next_sep_pos == llvm::StringRef::npos) {
2460 // if no other separator just expand this last layer
2461 llvm::StringRef child_name = temp_expression;
2462 ValueObjectSP child_valobj_sp =
2463 root->GetChildMemberWithName(child_name);
2464 if (!child_valobj_sp) {
2465 if (ValueObjectSP altroot = GetAlternateValue(
2466 *root, options.m_synthetic_children_traversal))
2467 child_valobj_sp = altroot->GetChildMemberWithName(child_name);
2468 }
2469 if (child_valobj_sp) {
2470 *reason_to_stop =
2473 return child_valobj_sp;
2474 }
2477 return nullptr;
2478 }
2479
2480 llvm::StringRef next_separator = temp_expression.substr(next_sep_pos);
2481 llvm::StringRef child_name = temp_expression.slice(0, next_sep_pos);
2482
2483 ValueObjectSP child_valobj_sp = root->GetChildMemberWithName(child_name);
2484 if (!child_valobj_sp) {
2485 if (ValueObjectSP altroot = GetAlternateValue(
2486 *root, options.m_synthetic_children_traversal))
2487 child_valobj_sp = altroot->GetChildMemberWithName(child_name);
2488 }
2489 if (child_valobj_sp) {
2490 root = child_valobj_sp;
2491 remainder = next_separator;
2493 continue;
2494 }
2497 return nullptr;
2498 }
2499 case '[': {
2500 if (!root_compiler_type_info.Test(eTypeIsArray) &&
2501 !root_compiler_type_info.Test(eTypeIsPointer) &&
2502 !root_compiler_type_info.Test(
2503 eTypeIsVector)) // if this is not a T[] nor a T*
2504 {
2505 if (!root_compiler_type_info.Test(
2506 eTypeIsScalar)) // if this is not even a scalar...
2507 {
2508 if (options.m_synthetic_children_traversal ==
2510 None) // ...only chance left is synthetic
2511 {
2512 *reason_to_stop =
2515 return ValueObjectSP();
2516 }
2517 } else if (!options.m_allow_bitfields_syntax) // if this is a scalar,
2518 // check that we can
2519 // expand bitfields
2520 {
2521 *reason_to_stop =
2524 return ValueObjectSP();
2525 }
2526 }
2527 if (temp_expression[1] ==
2528 ']') // if this is an unbounded range it only works for arrays
2529 {
2530 if (!root_compiler_type_info.Test(eTypeIsArray)) {
2531 *reason_to_stop =
2534 return nullptr;
2535 } else // even if something follows, we cannot expand unbounded ranges,
2536 // just let the caller do it
2537 {
2538 *reason_to_stop =
2540 *final_result =
2542 return root;
2543 }
2544 }
2545
2546 size_t close_bracket_position = temp_expression.find(']', 1);
2547 if (close_bracket_position ==
2548 llvm::StringRef::npos) // if there is no ], this is a syntax error
2549 {
2550 *reason_to_stop =
2553 return nullptr;
2554 }
2555
2556 llvm::StringRef bracket_expr =
2557 temp_expression.slice(1, close_bracket_position);
2558
2559 // If this was an empty expression it would have been caught by the if
2560 // above.
2561 assert(!bracket_expr.empty());
2562
2563 if (!bracket_expr.contains('-')) {
2564 // if no separator, this is of the form [N]. Note that this cannot be
2565 // an unbounded range of the form [], because that case was handled
2566 // above with an unconditional return.
2567 unsigned long index = 0;
2568 if (bracket_expr.getAsInteger(0, index)) {
2569 *reason_to_stop =
2572 return nullptr;
2573 }
2574
2575 // from here on we do have a valid index
2576 if (root_compiler_type_info.Test(eTypeIsArray)) {
2577 ValueObjectSP child_valobj_sp = root->GetChildAtIndex(index);
2578 if (!child_valobj_sp)
2579 child_valobj_sp = root->GetSyntheticArrayMember(index, true);
2580 if (!child_valobj_sp)
2581 if (root->HasSyntheticValue() &&
2582 llvm::expectedToOptional(
2583 root->GetSyntheticValue()->GetNumChildren())
2584 .value_or(0) > index)
2585 child_valobj_sp =
2586 root->GetSyntheticValue()->GetChildAtIndex(index);
2587 if (child_valobj_sp) {
2588 root = child_valobj_sp;
2589 remainder =
2590 temp_expression.substr(close_bracket_position + 1); // skip ]
2592 continue;
2593 } else {
2594 *reason_to_stop =
2597 return nullptr;
2598 }
2599 } else if (root_compiler_type_info.Test(eTypeIsPointer)) {
2600 if (*what_next ==
2601 ValueObject::
2602 eExpressionPathAftermathDereference && // if this is a
2603 // ptr-to-scalar, I
2604 // am accessing it
2605 // by index and I
2606 // would have
2607 // deref'ed anyway,
2608 // then do it now
2609 // and use this as
2610 // a bitfield
2611 pointee_compiler_type_info.Test(eTypeIsScalar)) {
2612 Status error;
2614 *root, options.m_synthetic_children_traversal, error);
2615 if (error.Fail() || !root) {
2616 *reason_to_stop =
2619 return nullptr;
2620 } else {
2622 continue;
2623 }
2624 } else {
2625 if (root->GetCompilerType().GetMinimumLanguage() ==
2627 pointee_compiler_type_info.AllClear(eTypeIsPointer) &&
2628 root->HasSyntheticValue() &&
2631 SyntheticChildrenTraversal::ToSynthetic ||
2634 SyntheticChildrenTraversal::Both)) {
2635 root = root->GetSyntheticValue()->GetChildAtIndex(index);
2636 } else
2637 root = root->GetSyntheticArrayMember(index, true);
2638 if (!root) {
2639 *reason_to_stop =
2642 return nullptr;
2643 } else {
2644 remainder =
2645 temp_expression.substr(close_bracket_position + 1); // skip ]
2647 continue;
2648 }
2649 }
2650 } else if (root_compiler_type_info.Test(eTypeIsScalar)) {
2651 root = root->GetSyntheticBitFieldChild(index, index, true);
2652 if (!root) {
2653 *reason_to_stop =
2656 return nullptr;
2657 } else // we do not know how to expand members of bitfields, so we
2658 // just return and let the caller do any further processing
2659 {
2660 *reason_to_stop = ValueObject::
2661 eExpressionPathScanEndReasonBitfieldRangeOperatorMet;
2663 return root;
2664 }
2665 } else if (root_compiler_type_info.Test(eTypeIsVector)) {
2666 root = root->GetChildAtIndex(index);
2667 if (!root) {
2668 *reason_to_stop =
2671 return ValueObjectSP();
2672 } else {
2673 remainder =
2674 temp_expression.substr(close_bracket_position + 1); // skip ]
2676 continue;
2677 }
2678 } else if (options.m_synthetic_children_traversal ==
2680 SyntheticChildrenTraversal::ToSynthetic ||
2683 SyntheticChildrenTraversal::Both) {
2684 if (root->HasSyntheticValue())
2685 root = root->GetSyntheticValue();
2686 else if (!root->IsSynthetic()) {
2687 *reason_to_stop =
2690 return nullptr;
2691 }
2692 // if we are here, then root itself is a synthetic VO.. should be
2693 // good to go
2694
2695 if (!root) {
2696 *reason_to_stop =
2699 return nullptr;
2700 }
2701 root = root->GetChildAtIndex(index);
2702 if (!root) {
2703 *reason_to_stop =
2706 return nullptr;
2707 } else {
2708 remainder =
2709 temp_expression.substr(close_bracket_position + 1); // skip ]
2711 continue;
2712 }
2713 } else {
2714 *reason_to_stop =
2717 return nullptr;
2718 }
2719 } else {
2720 // we have a low and a high index
2721 llvm::StringRef sleft, sright;
2722 unsigned long low_index, high_index;
2723 std::tie(sleft, sright) = bracket_expr.split('-');
2724 if (sleft.getAsInteger(0, low_index) ||
2725 sright.getAsInteger(0, high_index)) {
2726 *reason_to_stop =
2729 return nullptr;
2730 }
2731
2732 if (low_index > high_index) // swap indices if required
2733 std::swap(low_index, high_index);
2734
2735 if (root_compiler_type_info.Test(
2736 eTypeIsScalar)) // expansion only works for scalars
2737 {
2738 root = root->GetSyntheticBitFieldChild(low_index, high_index, true);
2739 if (!root) {
2740 *reason_to_stop =
2743 return nullptr;
2744 } else {
2745 *reason_to_stop = ValueObject::
2746 eExpressionPathScanEndReasonBitfieldRangeOperatorMet;
2748 return root;
2749 }
2750 } else if (root_compiler_type_info.Test(
2751 eTypeIsPointer) && // if this is a ptr-to-scalar, I am
2752 // accessing it by index and I would
2753 // have deref'ed anyway, then do it
2754 // now and use this as a bitfield
2755 *what_next ==
2757 pointee_compiler_type_info.Test(eTypeIsScalar)) {
2758 Status error;
2760 *root, options.m_synthetic_children_traversal, error);
2761 if (error.Fail() || !root) {
2762 *reason_to_stop =
2765 return nullptr;
2766 } else {
2768 continue;
2769 }
2770 } else {
2771 *reason_to_stop =
2774 return root;
2775 }
2776 }
2777 break;
2778 }
2779 default: // some non-separator is in the way
2780 {
2781 *reason_to_stop =
2784 return nullptr;
2785 }
2786 }
2787 }
2788}
2789
2790llvm::Error ValueObject::Dump(Stream &s) {
2791 return Dump(s, DumpValueObjectOptions(*this));
2792}
2793
2795 const DumpValueObjectOptions &options) {
2796 ValueObjectPrinter printer(*this, &s, options);
2797 return printer.PrintValueObject();
2798}
2799
2801 ValueObjectSP valobj_sp;
2802
2803 if (UpdateValueIfNeeded(false) && m_error.Success()) {
2805
2806 DataExtractor data;
2807 data.SetByteOrder(m_data.GetByteOrder());
2808 data.SetAddressByteSize(m_data.GetAddressByteSize());
2809
2810 if (IsBitfield()) {
2812 m_error = v.GetValueAsData(&exe_ctx, data, GetModule().get());
2813 } else
2814 m_error = m_value.GetValueAsData(&exe_ctx, data, GetModule().get());
2815
2817 exe_ctx.GetBestExecutionContextScope(), GetCompilerType(), name, data,
2818 GetAddressOf().address);
2819 }
2820
2821 if (!valobj_sp) {
2824 exe_ctx.GetBestExecutionContextScope(), m_error.Clone());
2825 }
2826 return valobj_sp;
2827}
2828
2830 lldb::DynamicValueType dynValue, bool synthValue) {
2831 ValueObjectSP result_sp;
2832 switch (dynValue) {
2835 if (!IsDynamic())
2836 result_sp = GetDynamicValue(dynValue);
2837 } break;
2839 if (IsDynamic())
2840 result_sp = GetStaticValue();
2841 } break;
2842 }
2843 if (!result_sp)
2844 result_sp = GetSP();
2845 assert(result_sp);
2846
2847 bool is_synthetic = result_sp->IsSynthetic();
2848 if (synthValue && !is_synthetic) {
2849 if (auto synth_sp = result_sp->GetSyntheticValue())
2850 return synth_sp;
2851 }
2852 if (!synthValue && is_synthetic) {
2853 if (auto non_synth_sp = result_sp->GetNonSyntheticValue())
2854 return non_synth_sp;
2855 }
2856
2857 return result_sp;
2858}
2859
2861 if (m_deref_valobj)
2862 return m_deref_valobj->GetSP();
2863
2864 std::string deref_name_str;
2865 uint32_t deref_byte_size = 0;
2866 int32_t deref_byte_offset = 0;
2867 CompilerType compiler_type = GetCompilerType();
2868 uint64_t language_flags = 0;
2869
2871
2872 CompilerType deref_compiler_type;
2873 auto deref_compiler_type_or_err = compiler_type.GetDereferencedType(
2874 &exe_ctx, deref_name_str, deref_byte_size, deref_byte_offset, this,
2875 language_flags);
2876
2877 std::string deref_error;
2878 if (deref_compiler_type_or_err) {
2879 deref_compiler_type = *deref_compiler_type_or_err;
2880 } else {
2881 deref_error = llvm::toString(deref_compiler_type_or_err.takeError());
2882 LLDB_LOG(GetLog(LLDBLog::Types), "could not find child: {0}", deref_error);
2883 }
2884
2885 if (deref_compiler_type && deref_byte_size) {
2886 ConstString deref_name;
2887 if (!deref_name_str.empty())
2888 deref_name.SetCString(deref_name_str.c_str());
2889
2891 new ValueObjectChild(*this, deref_compiler_type, deref_name,
2892 deref_byte_size, deref_byte_offset, 0, 0, false,
2893 true, eAddressTypeInvalid, language_flags);
2894 }
2895
2896 // In case of incomplete deref compiler type, use the pointee type and try
2897 // to recreate a new ValueObjectChild using it.
2898 if (!m_deref_valobj) {
2899 // FIXME(#59012): C++ stdlib formatters break with incomplete types (e.g.
2900 // `std::vector<int> &`). Remove ObjC restriction once that's resolved.
2903 deref_compiler_type = compiler_type.GetPointeeType();
2904
2905 if (deref_compiler_type) {
2906 ConstString deref_name;
2907 if (!deref_name_str.empty())
2908 deref_name.SetCString(deref_name_str.c_str());
2909
2911 *this, deref_compiler_type, deref_name, deref_byte_size,
2912 deref_byte_offset, 0, 0, false, true, eAddressTypeInvalid,
2913 language_flags);
2914 }
2915 }
2916 }
2917
2918 if (!m_deref_valobj && IsSynthetic())
2919 m_deref_valobj = GetChildMemberWithName("$$dereference$$").get();
2920
2921 if (m_deref_valobj) {
2922 error.Clear();
2923 return m_deref_valobj->GetSP();
2924 } else {
2925 StreamString strm;
2926 GetExpressionPath(strm);
2927
2928 if (deref_error.empty())
2930 "dereference failed: (%s) %s",
2931 GetTypeName().AsCString("<invalid type>"), strm.GetData());
2932 else
2934 "dereference failed: %s: (%s) %s", deref_error.c_str(),
2935 GetTypeName().AsCString("<invalid type>"), strm.GetData());
2936 return ValueObjectSP();
2937 }
2938}
2939
2941 auto [addr, address_type] = GetAddressOf(/*scalar_is_load_address=*/false);
2942 error.Clear();
2943 if (addr != LLDB_INVALID_ADDRESS && address_type != eAddressTypeHost) {
2944 switch (address_type) {
2945 case eAddressTypeInvalid: {
2946 StreamString expr_path_strm;
2947 GetExpressionPath(expr_path_strm);
2948 error = Status::FromErrorStringWithFormat("'%s' is not in memory",
2949 expr_path_strm.GetData());
2950 } break;
2951
2952 case eAddressTypeFile:
2953 case eAddressTypeLoad: {
2954 if (m_addr_of_valobj_sp &&
2955 m_addr_of_valobj_sp->GetValueAsUnsigned(LLDB_INVALID_ADDRESS) == addr)
2956 return m_addr_of_valobj_sp;
2957 m_addr_of_valobj_sp.reset();
2958 CompilerType compiler_type = GetCompilerType();
2959 if (compiler_type) {
2960 std::string name(1, '&');
2961 name.append(m_name.AsCString(""));
2963
2964 lldb::DataBufferSP buffer(
2965 new lldb_private::DataBufferHeap(&addr, sizeof(lldb::addr_t)));
2968 compiler_type.GetPointerType(), ConstString(name), buffer,
2970 LLDB_INVALID_ADDRESS, this->GetManager());
2971 }
2972 } break;
2973 default:
2974 break;
2975 }
2976 } else {
2977 StreamString expr_path_strm;
2978 GetExpressionPath(expr_path_strm);
2980 "'%s' doesn't have a valid address", expr_path_strm.GetData());
2981 }
2982
2983 return m_addr_of_valobj_sp;
2984}
2985
2987 return ValueObjectCast::Create(*this, GetName(), compiler_type);
2988}
2989
2991 // Only allow casts if the original type is equal or larger than the cast
2992 // type, unless we know this is a load address. Getting the size wrong for
2993 // a host side storage could leak lldb memory, so we absolutely want to
2994 // prevent that. We may not always get the right value, for instance if we
2995 // have an expression result value that's copied into a storage location in
2996 // the target may not have copied enough memory. I'm not trying to fix that
2997 // here, I'm just making Cast from a smaller to a larger possible in all the
2998 // cases where that doesn't risk making a Value out of random lldb memory.
2999 // You have to check the ValueObject's Value for the address types, since
3000 // ValueObjects that use live addresses will tell you they fetch data from the
3001 // live address, but once they are made, they actually don't.
3002 // FIXME: Can we make ValueObject's with a live address fetch "more data" from
3003 // the live address if it is still valid?
3004
3005 Status error;
3006 CompilerType my_type = GetCompilerType();
3007
3008 ExecutionContextScope *exe_scope =
3010 if (llvm::expectedToOptional(compiler_type.GetByteSize(exe_scope))
3011 .value_or(0) <=
3012 llvm::expectedToOptional(GetCompilerType().GetByteSize(exe_scope))
3013 .value_or(0) ||
3014 m_value.GetValueType() == Value::ValueType::LoadAddress)
3015 return DoCast(compiler_type);
3016
3018 "Can only cast to a type that is equal to or smaller "
3019 "than the orignal type.");
3020
3022 ExecutionContext(GetExecutionContextRef()).GetBestExecutionContextScope(),
3023 std::move(error));
3024}
3025
3026lldb::ValueObjectSP ValueObject::Clone(llvm::StringRef new_name) {
3027 return ValueObjectCast::Create(*this, new_name, GetCompilerType());
3028}
3029
3031 CompilerType &compiler_type) {
3032 ValueObjectSP valobj_sp;
3033 addr_t ptr_value = GetPointerValue().address;
3034
3035 if (ptr_value != LLDB_INVALID_ADDRESS) {
3036 Address ptr_addr(ptr_value);
3038 valobj_sp = ValueObjectMemory::Create(
3039 exe_ctx.GetBestExecutionContextScope(), name, ptr_addr, compiler_type);
3040 }
3041 return valobj_sp;
3042}
3043
3045 ValueObjectSP valobj_sp;
3046 addr_t ptr_value = GetPointerValue().address;
3047
3048 if (ptr_value != LLDB_INVALID_ADDRESS) {
3049 Address ptr_addr(ptr_value);
3051 valobj_sp = ValueObjectMemory::Create(
3052 exe_ctx.GetBestExecutionContextScope(), name, ptr_addr, type_sp);
3053 }
3054 return valobj_sp;
3055}
3056
3058 if (auto target_sp = GetTargetSP()) {
3059 const bool scalar_is_load_address = true;
3060 auto [addr_value, addr_type] = GetAddressOf(scalar_is_load_address);
3061 if (addr_type == eAddressTypeFile) {
3062 lldb::ModuleSP module_sp(GetModule());
3063 if (!module_sp)
3064 addr_value = LLDB_INVALID_ADDRESS;
3065 else {
3066 Address tmp_addr;
3067 module_sp->ResolveFileAddress(addr_value, tmp_addr);
3068 addr_value = tmp_addr.GetLoadAddress(target_sp.get());
3069 }
3070 } else if (addr_type == eAddressTypeHost ||
3071 addr_type == eAddressTypeInvalid)
3072 addr_value = LLDB_INVALID_ADDRESS;
3073 return addr_value;
3074 }
3075 return LLDB_INVALID_ADDRESS;
3076}
3077
3078llvm::Expected<lldb::ValueObjectSP> ValueObject::CastDerivedToBaseType(
3079 CompilerType type, const llvm::ArrayRef<uint32_t> &base_type_indices) {
3080 // Make sure the starting type and the target type are both valid for this
3081 // type of cast; otherwise return the shared pointer to the original
3082 // (unchanged) ValueObject.
3083 if (!type.IsPointerType() && !type.IsReferenceType())
3084 return llvm::createStringError(
3085 "Invalid target type: should be a pointer or a reference");
3086
3087 CompilerType start_type = GetCompilerType();
3088 if (start_type.IsReferenceType())
3089 start_type = start_type.GetNonReferenceType();
3090
3091 auto target_record_type =
3092 type.IsPointerType() ? type.GetPointeeType() : type.GetNonReferenceType();
3093 auto start_record_type =
3094 start_type.IsPointerType() ? start_type.GetPointeeType() : start_type;
3095
3096 if (!target_record_type.IsRecordType() || !start_record_type.IsRecordType())
3097 return llvm::createStringError(
3098 "Underlying start & target types should be record types");
3099
3100 if (target_record_type.CompareTypes(start_record_type))
3101 return llvm::createStringError(
3102 "Underlying start & target types should be different");
3103
3104 if (base_type_indices.empty())
3105 return llvm::createStringError("children sequence must be non-empty");
3106
3107 // Both the starting & target types are valid for the cast, and the list of
3108 // base class indices is non-empty, so we can proceed with the cast.
3109
3110 lldb::TargetSP target = GetTargetSP();
3111 // The `value` can be a pointer, but GetChildAtIndex works for pointers too.
3112 lldb::ValueObjectSP inner_value = GetSP();
3113
3114 for (const uint32_t i : base_type_indices)
3115 // Create synthetic value if needed.
3116 inner_value =
3117 inner_value->GetChildAtIndex(i, /*can_create_synthetic*/ true);
3118
3119 // At this point type of `inner_value` should be the dereferenced target
3120 // type.
3121 CompilerType inner_value_type = inner_value->GetCompilerType();
3122 if (type.IsPointerType()) {
3123 if (!inner_value_type.CompareTypes(type.GetPointeeType()))
3124 return llvm::createStringError(
3125 "casted value doesn't match the desired type");
3126
3127 uintptr_t addr = inner_value->GetLoadAddress();
3128 llvm::StringRef name = "";
3129 ExecutionContext exe_ctx(target.get(), false);
3130 return ValueObject::CreateValueObjectFromAddress(name, addr, exe_ctx, type,
3131 /* do deref */ false);
3132 }
3133
3134 // At this point the target type should be a reference.
3135 if (!inner_value_type.CompareTypes(type.GetNonReferenceType()))
3136 return llvm::createStringError(
3137 "casted value doesn't match the desired type");
3138
3139 return lldb::ValueObjectSP(inner_value->Cast(type.GetNonReferenceType()));
3140}
3141
3142llvm::Expected<lldb::ValueObjectSP>
3144 // Make sure the starting type and the target type are both valid for this
3145 // type of cast; otherwise return the shared pointer to the original
3146 // (unchanged) ValueObject.
3147 if (!type.IsPointerType() && !type.IsReferenceType())
3148 return llvm::createStringError(
3149 "Invalid target type: should be a pointer or a reference");
3150
3151 CompilerType start_type = GetCompilerType();
3152 if (start_type.IsReferenceType())
3153 start_type = start_type.GetNonReferenceType();
3154
3155 auto target_record_type =
3156 type.IsPointerType() ? type.GetPointeeType() : type.GetNonReferenceType();
3157 auto start_record_type =
3158 start_type.IsPointerType() ? start_type.GetPointeeType() : start_type;
3159
3160 if (!target_record_type.IsRecordType() || !start_record_type.IsRecordType())
3161 return llvm::createStringError(
3162 "Underlying start & target types should be record types");
3163
3164 if (target_record_type.CompareTypes(start_record_type))
3165 return llvm::createStringError(
3166 "Underlying start & target types should be different");
3167
3168 CompilerType virtual_base;
3169 if (target_record_type.IsVirtualBase(start_record_type, &virtual_base)) {
3170 if (!virtual_base.IsValid())
3171 return llvm::createStringError("virtual base should be valid");
3172 return llvm::createStringError(
3173 llvm::Twine("cannot cast " + start_type.TypeDescription() + " to " +
3174 type.TypeDescription() + " via virtual base " +
3175 virtual_base.TypeDescription())
3176 .str());
3177 }
3178
3179 // Both the starting & target types are valid for the cast, so we can
3180 // proceed with the cast.
3181
3182 lldb::TargetSP target = GetTargetSP();
3183 auto pointer_type =
3184 type.IsPointerType() ? type : type.GetNonReferenceType().GetPointerType();
3185
3186 uintptr_t addr =
3188
3189 llvm::StringRef name = "";
3190 ExecutionContext exe_ctx(target.get(), false);
3192 name, addr - offset, exe_ctx, pointer_type, /* do_deref */ false);
3193
3194 if (type.IsPointerType())
3195 return value;
3196
3197 // At this point the target type is a reference. Since `value` is a pointer,
3198 // it has to be dereferenced.
3199 Status error;
3200 return value->Dereference(error);
3201}
3202
3204 bool is_scalar = GetCompilerType().IsScalarType();
3205 bool is_enum = GetCompilerType().IsEnumerationType();
3206 bool is_pointer =
3208 bool is_float = HasFloatingRepresentation(GetCompilerType());
3209 bool is_integer = GetCompilerType().IsInteger();
3211
3212 if (!type.IsScalarType())
3215 Status::FromErrorString("target type must be a scalar"));
3216
3217 if (!is_scalar && !is_enum && !is_pointer)
3220 Status::FromErrorString("argument must be a scalar, enum, or pointer"));
3221
3222 lldb::TargetSP target = GetTargetSP();
3223 uint64_t type_byte_size = 0;
3224 uint64_t val_byte_size = 0;
3225 if (auto temp = llvm::expectedToOptional(type.GetByteSize(target.get())))
3226 type_byte_size = temp.value();
3227 if (auto temp =
3228 llvm::expectedToOptional(GetCompilerType().GetByteSize(target.get())))
3229 val_byte_size = temp.value();
3230
3231 if (is_pointer) {
3232 if (!type.IsInteger() && !type.IsBoolean())
3235 Status::FromErrorString("target type must be an integer or boolean"));
3236 if (!type.IsBoolean() && type_byte_size < val_byte_size)
3240 "target type cannot be smaller than the pointer type"));
3241 }
3242
3243 if (type.IsBoolean()) {
3244 if (!is_scalar || is_integer)
3246 exe_ctx, type.GetTypeSystem().GetSharedPointer(),
3247 GetValueAsUnsigned(0) != 0, "result");
3248 else if (is_scalar && is_float) {
3249 auto float_value_or_err = GetValueAsAPFloat();
3250 if (float_value_or_err)
3252 exe_ctx, type.GetTypeSystem().GetSharedPointer(),
3253 !float_value_or_err->isZero(), "result");
3254 else
3258 "cannot get value as APFloat: %s",
3259 llvm::toString(float_value_or_err.takeError()).c_str()));
3260 }
3261 }
3262
3263 if (type.IsInteger()) {
3264 if (!is_scalar || is_integer) {
3265 auto int_value_or_err = GetValueAsAPSInt();
3266 if (int_value_or_err) {
3267 // Get the value as APSInt and extend or truncate it to the requested
3268 // size.
3269 llvm::APSInt ext =
3270 int_value_or_err->extOrTrunc(type_byte_size * CHAR_BIT);
3271 return ValueObject::CreateValueObjectFromAPInt(exe_ctx, ext, type,
3272 "result");
3273 } else
3277 "cannot get value as APSInt: %s",
3278 llvm::toString(int_value_or_err.takeError()).c_str()));
3279 } else if (is_scalar && is_float) {
3280 llvm::APSInt integer(type_byte_size * CHAR_BIT, !type.IsSigned());
3281 bool is_exact;
3282 auto float_value_or_err = GetValueAsAPFloat();
3283 if (float_value_or_err) {
3284 llvm::APFloatBase::opStatus status =
3285 float_value_or_err->convertToInteger(
3286 integer, llvm::APFloat::rmTowardZero, &is_exact);
3287
3288 // Casting floating point values that are out of bounds of the target
3289 // type is undefined behaviour.
3290 if (status & llvm::APFloatBase::opInvalidOp)
3294 "invalid cast from float to integer"));
3296 "result");
3297 } else {
3301 "cannot get value as APFloat: %s",
3302 llvm::toString(float_value_or_err.takeError()).c_str()));
3303 }
3304 }
3305 }
3306
3307 if (HasFloatingRepresentation(type)) {
3308 if (!is_scalar) {
3309 auto int_value_or_err = GetValueAsAPSInt();
3310 if (int_value_or_err) {
3311 llvm::APSInt ext =
3312 int_value_or_err->extOrTrunc(type_byte_size * CHAR_BIT);
3313 Scalar scalar_int(ext);
3314 llvm::APFloat f =
3316 return ValueObject::CreateValueObjectFromAPFloat(exe_ctx, f, type,
3317 "result");
3318 } else {
3322 "cannot get value as APSInt: %s",
3323 llvm::toString(int_value_or_err.takeError()).c_str()));
3324 }
3325 } else {
3326 if (is_integer) {
3327 auto int_value_or_err = GetValueAsAPSInt();
3328 if (int_value_or_err) {
3329 Scalar scalar_int(*int_value_or_err);
3330 llvm::APFloat f = scalar_int.CreateAPFloatFromAPSInt(
3332 return ValueObject::CreateValueObjectFromAPFloat(exe_ctx, f, type,
3333 "result");
3334 } else {
3338 "cannot get value as APSInt: %s",
3339 llvm::toString(int_value_or_err.takeError()).c_str()));
3340 }
3341 }
3342 if (is_float) {
3343 auto float_value_or_err = GetValueAsAPFloat();
3344 if (float_value_or_err) {
3345 Scalar scalar_float(*float_value_or_err);
3346 llvm::APFloat f = scalar_float.CreateAPFloatFromAPFloat(
3348 return ValueObject::CreateValueObjectFromAPFloat(exe_ctx, f, type,
3349 "result");
3350 } else {
3354 "cannot get value as APFloat: %s",
3355 llvm::toString(float_value_or_err.takeError()).c_str()));
3356 }
3357 }
3358 }
3359 }
3360
3363 Status::FromErrorString("Unable to perform requested cast"));
3364}
3365
3367 bool is_enum = GetCompilerType().IsEnumerationType();
3368 bool is_integer = GetCompilerType().IsInteger();
3369 bool is_float = HasFloatingRepresentation(GetCompilerType());
3371
3372 if (!is_enum && !is_integer && !is_float)
3376 "argument must be an integer, a float, or an enum"));
3377
3378 if (!type.IsEnumerationType())
3381 Status::FromErrorString("target type must be an enum"));
3382
3383 lldb::TargetSP target = GetTargetSP();
3384 uint64_t byte_size = 0;
3385 if (auto temp = llvm::expectedToOptional(type.GetByteSize(target.get())))
3386 byte_size = temp.value();
3387
3388 if (is_float) {
3389 llvm::APSInt integer(byte_size * CHAR_BIT,
3391 bool is_exact;
3392 auto value_or_err = GetValueAsAPFloat();
3393 if (value_or_err) {
3394 llvm::APFloatBase::opStatus status = value_or_err->convertToInteger(
3395 integer, llvm::APFloat::rmTowardZero, &is_exact);
3396
3397 // Casting floating point values that are out of bounds of the target
3398 // type is undefined behaviour.
3399 if (status & llvm::APFloatBase::opInvalidOp)
3402 Status::FromErrorString("invalid cast from float to integer"));
3404 "result");
3405 } else
3409 "cannot get value as APFloat: {0}",
3410 llvm::toString(value_or_err.takeError())));
3411 } else {
3412 // Get the value as APSInt and extend or truncate it to the requested size.
3413 auto value_or_err = GetValueAsAPSInt();
3414 if (value_or_err) {
3415 llvm::APSInt ext = value_or_err->extOrTrunc(byte_size * CHAR_BIT);
3416 return ValueObject::CreateValueObjectFromAPInt(exe_ctx, ext, type,
3417 "result");
3418 } else
3422 "cannot get value as APSInt: %s",
3423 llvm::toString(value_or_err.takeError()).c_str()));
3424 }
3427 Status::FromErrorString("Cannot perform requested cast"));
3428}
3429
3431
3433 bool use_selected)
3434 : m_mod_id(), m_exe_ctx_ref() {
3435 ExecutionContext exe_ctx(exe_scope);
3436 TargetSP target_sp(exe_ctx.GetTargetSP());
3437 if (target_sp) {
3438 m_exe_ctx_ref.SetTargetSP(target_sp);
3439 ProcessSP process_sp(exe_ctx.GetProcessSP());
3440 if (!process_sp)
3441 process_sp = target_sp->GetProcessSP();
3442
3443 if (process_sp) {
3444 m_mod_id = process_sp->GetModID();
3445 m_exe_ctx_ref.SetProcessSP(process_sp);
3446
3447 ThreadSP thread_sp(exe_ctx.GetThreadSP());
3448
3449 if (!thread_sp) {
3450 if (use_selected)
3451 thread_sp = process_sp->GetThreadList().GetSelectedThread();
3452 }
3453
3454 if (thread_sp) {
3455 m_exe_ctx_ref.SetThreadSP(thread_sp);
3456
3457 StackFrameSP frame_sp(exe_ctx.GetFrameSP());
3458 if (!frame_sp) {
3459 if (use_selected)
3460 frame_sp = thread_sp->GetSelectedFrame(DoNoSelectMostRelevantFrame);
3461 }
3462 if (frame_sp)
3463 m_exe_ctx_ref.SetFrameSP(frame_sp);
3464 }
3465 }
3466 }
3467}
3468
3472
3474
3475// This function checks the EvaluationPoint against the current process state.
3476// If the current state matches the evaluation point, or the evaluation point
3477// is already invalid, then we return false, meaning "no change". If the
3478// current state is different, we update our state, and return true meaning
3479// "yes, change". If we did see a change, we also set m_needs_update to true,
3480// so future calls to NeedsUpdate will return true. exe_scope will be set to
3481// the current execution context scope.
3482
3484 bool accept_invalid_exe_ctx) {
3485 // Start with the target, if it is NULL, then we're obviously not going to
3486 // get any further:
3487 const bool thread_and_frame_only_if_stopped = true;
3488 ExecutionContext exe_ctx(
3489 m_exe_ctx_ref.Lock(thread_and_frame_only_if_stopped));
3490
3491 if (exe_ctx.GetTargetPtr() == nullptr)
3492 return false;
3493
3494 // If we don't have a process nothing can change.
3495 Process *process = exe_ctx.GetProcessPtr();
3496 if (process == nullptr)
3497 return false;
3498
3499 // If our stop id is the current stop ID, nothing has changed:
3500 ProcessModID current_mod_id = process->GetModID();
3501
3502 // If the current stop id is 0, either we haven't run yet, or the process
3503 // state has been cleared. In either case, we aren't going to be able to sync
3504 // with the process state.
3505 if (current_mod_id.GetStopID() == 0)
3506 return false;
3507
3508 bool changed = false;
3509 const bool was_valid = m_mod_id.IsValid();
3510 if (was_valid) {
3511 if (m_mod_id == current_mod_id) {
3512 // Everything is already up to date in this object, no need to update the
3513 // execution context scope.
3514 changed = false;
3515 } else {
3516 m_mod_id = current_mod_id;
3517 m_needs_update = true;
3518 changed = true;
3519 }
3520 }
3521
3522 // Now re-look up the thread and frame in case the underlying objects have
3523 // gone away & been recreated. That way we'll be sure to return a valid
3524 // exe_scope. If we used to have a thread or a frame but can't find it
3525 // anymore, then mark ourselves as invalid.
3526
3527 if (!accept_invalid_exe_ctx) {
3528 if (m_exe_ctx_ref.HasThreadRef()) {
3529 ThreadSP thread_sp(m_exe_ctx_ref.GetThreadSP());
3530 if (thread_sp) {
3531 if (m_exe_ctx_ref.HasFrameRef()) {
3532 StackFrameSP frame_sp(m_exe_ctx_ref.GetFrameSP());
3533 if (!frame_sp) {
3534 // We used to have a frame, but now it is gone
3535 SetInvalid();
3536 changed = was_valid;
3537 }
3538 }
3539 } else {
3540 // We used to have a thread, but now it is gone
3541 SetInvalid();
3542 changed = was_valid;
3543 }
3544 }
3545 }
3546
3547 return changed;
3548}
3549
3551 ProcessSP process_sp(m_exe_ctx_ref.GetProcessSP());
3552 if (process_sp)
3553 m_mod_id = process_sp->GetModID();
3554 m_needs_update = false;
3555}
3556
3557void ValueObject::ClearUserVisibleData(uint32_t clear_mask) {
3558 if ((clear_mask & eClearUserVisibleDataItemsValue) ==
3560 m_value_str.clear();
3561
3562 if ((clear_mask & eClearUserVisibleDataItemsLocation) ==
3564 m_location_str.clear();
3565
3566 if ((clear_mask & eClearUserVisibleDataItemsSummary) ==
3568 m_summary_str.clear();
3569
3570 if ((clear_mask & eClearUserVisibleDataItemsDescription) ==
3572 m_object_desc_str.clear();
3573
3577 m_synthetic_value = nullptr;
3578 }
3579}
3580
3582 if (m_parent) {
3583 if (!m_parent->IsPointerOrReferenceType())
3584 return m_parent->GetSymbolContextScope();
3585 }
3586 return nullptr;
3587}
3588
3590 llvm::StringRef name, llvm::StringRef expression,
3591 const ExecutionContext &exe_ctx, ValueObject *parent) {
3592 return CreateValueObjectFromExpression(name, expression, exe_ctx,
3593 EvaluateExpressionOptions(), parent);
3594}
3595
3597 llvm::StringRef name, llvm::StringRef expression,
3598 const ExecutionContext &exe_ctx, const EvaluateExpressionOptions &options,
3599 ValueObject *parent) {
3600 // FIXME: I haven't handled parent in this case yet. That is a WHOLE lot of
3601 // plumbing.
3602
3603 lldb::ValueObjectSP retval_sp;
3604 lldb::TargetSP target_sp(exe_ctx.GetTargetSP());
3605 if (!target_sp)
3606 return retval_sp;
3607 if (expression.empty())
3608 return retval_sp;
3609
3610 target_sp->EvaluateExpression(expression, exe_ctx.GetFrameSP().get(),
3611 retval_sp, options);
3612 if (retval_sp && !name.empty())
3613 retval_sp->SetName(name);
3614 return retval_sp;
3615}
3616
3618 llvm::StringRef name, uint64_t address, const ExecutionContext &exe_ctx,
3619 CompilerType type, bool do_deref, ValueObject *parent) {
3620 if (type) {
3621 CompilerType pointer_type(type.GetPointerType());
3622 if (!do_deref)
3623 pointer_type = type;
3624 if (pointer_type) {
3625 lldb::DataBufferSP buffer(
3626 new lldb_private::DataBufferHeap(&address, sizeof(lldb::addr_t)));
3628 exe_ctx.GetBestExecutionContextScope(), pointer_type,
3629 ConstString(name), buffer, exe_ctx.GetByteOrder(),
3630 exe_ctx.GetAddressByteSize(), /*address=*/LLDB_INVALID_ADDRESS,
3631 parent ? parent->GetManager() : nullptr));
3632 if (ptr_result_valobj_sp) {
3633 if (do_deref)
3634 ptr_result_valobj_sp->GetValue().SetValueType(
3636 Status err;
3637 if (do_deref)
3638 ptr_result_valobj_sp = ptr_result_valobj_sp->Dereference(err);
3639 if (ptr_result_valobj_sp && !name.empty())
3640 ptr_result_valobj_sp->SetName(name);
3641 }
3642 return ptr_result_valobj_sp;
3643 }
3644 }
3645 return lldb::ValueObjectSP();
3646}
3647
3649 llvm::StringRef name, const DataExtractor &data,
3650 const ExecutionContext &exe_ctx, CompilerType type, ValueObject *parent) {
3651 lldb::ValueObjectSP new_value_sp;
3652 new_value_sp = ValueObjectConstResult::Create(
3653 exe_ctx.GetBestExecutionContextScope(), type, ConstString(name), data,
3654 LLDB_INVALID_ADDRESS, parent ? parent->GetManager() : nullptr);
3655 new_value_sp->SetAddressTypeOfChildren(eAddressTypeLoad);
3656 if (new_value_sp && !name.empty())
3657 new_value_sp->SetName(name);
3658 return new_value_sp;
3659}
3660
3662 const ExecutionContext &exe_ctx, const llvm::APInt &v, CompilerType type,
3663 llvm::StringRef name, ValueObject *parent) {
3664 uint64_t byte_size =
3665 llvm::expectedToOptional(
3667 .value_or(0);
3668 lldb::DataExtractorSP data_sp = std::make_shared<DataExtractor>(
3669 reinterpret_cast<const void *>(v.getRawData()), byte_size,
3670 exe_ctx.GetByteOrder(), exe_ctx.GetAddressByteSize());
3671 return ValueObject::CreateValueObjectFromData(name, *data_sp, exe_ctx, type,
3672 parent);
3673}
3674
3676 const ExecutionContext &exe_ctx, const llvm::APFloat &v, CompilerType type,
3677 llvm::StringRef name, ValueObject *parent) {
3678 return CreateValueObjectFromAPInt(exe_ctx, v.bitcastToAPInt(), type, name,
3679 parent);
3680}
3681
3683 const ExecutionContext &exe_ctx, Scalar &s, CompilerType type,
3684 llvm::StringRef name, ValueObject *parent) {
3686 exe_ctx.GetBestExecutionContextScope(), type, s, ConstString(name),
3687 /*module_ptr=*/nullptr, parent ? parent->GetManager() : nullptr);
3688}
3689
3691 const ExecutionContext &exe_ctx, TypeSystemSP typesystem_sp, bool value,
3692 llvm::StringRef name, ValueObject *parent) {
3693 CompilerType type = typesystem_sp->GetBasicTypeFromAST(lldb::eBasicTypeBool);
3695 uint64_t byte_size =
3696 llvm::expectedToOptional(type.GetByteSize(exe_scope)).value_or(0);
3697 lldb::DataExtractorSP data_sp = std::make_shared<DataExtractor>(
3698 reinterpret_cast<const void *>(&value), byte_size, exe_ctx.GetByteOrder(),
3699 exe_ctx.GetAddressByteSize());
3700 return ValueObject::CreateValueObjectFromData(name, *data_sp, exe_ctx, type,
3701 parent);
3702}
3703
3705 const ExecutionContext &exe_ctx, CompilerType type, llvm::StringRef name,
3706 ValueObject *parent) {
3707 if (!type.IsNullPtrType()) {
3708 lldb::ValueObjectSP ret_val;
3709 return ret_val;
3710 }
3711 uintptr_t zero = 0;
3712 uint64_t byte_size = 0;
3713 if (auto temp = llvm::expectedToOptional(
3715 byte_size = temp.value();
3716 lldb::DataExtractorSP data_sp = std::make_shared<DataExtractor>(
3717 reinterpret_cast<const void *>(zero), byte_size, exe_ctx.GetByteOrder(),
3718 exe_ctx.GetAddressByteSize());
3719 return ValueObject::CreateValueObjectFromData(name, *data_sp, exe_ctx, type,
3720 parent);
3721}
3722
3724 ValueObject *root(GetRoot());
3725 if (root != this)
3726 return root->GetModule();
3727 return lldb::ModuleSP();
3728}
3729
3731 if (m_root)
3732 return m_root;
3733 return (m_root = FollowParentChain([](ValueObject *vo) -> bool {
3734 return (vo->m_parent != nullptr);
3735 }));
3736}
3737
3740 ValueObject *vo = this;
3741 while (vo) {
3742 if (!f(vo))
3743 break;
3744 vo = vo->m_parent;
3745 }
3746 return vo;
3747}
3748
3757
3759 ValueObject *with_dv_info = this;
3760 while (with_dv_info) {
3761 if (with_dv_info->HasDynamicValueTypeInfo())
3762 return with_dv_info->GetDynamicValueTypeImpl();
3763 with_dv_info = with_dv_info->m_parent;
3764 }
3766}
3767
3769 const ValueObject *with_fmt_info = this;
3770 while (with_fmt_info) {
3771 if (with_fmt_info->m_format != lldb::eFormatDefault)
3772 return with_fmt_info->m_format;
3773 with_fmt_info = with_fmt_info->m_parent;
3774 }
3775 return m_format;
3776}
3777
3781 if (GetRoot()) {
3782 if (GetRoot() == this) {
3783 if (StackFrameSP frame_sp = GetFrameSP()) {
3784 const SymbolContext &sc(
3785 frame_sp->GetSymbolContext(eSymbolContextCompUnit));
3786 if (CompileUnit *cu = sc.comp_unit)
3787 type = cu->GetLanguage();
3788 }
3789 } else {
3791 }
3792 }
3793 }
3794 return (m_preferred_display_language = type); // only compute it once
3795}
3796
3801
3803 // we need to support invalid types as providers of values because some bare-
3804 // board debugging scenarios have no notion of types, but still manage to
3805 // have raw numeric values for things like registers. sigh.
3807 return (!type.IsValid()) || (0 != (type.GetTypeInfo() & eTypeHasValue));
3808}
3809
3811 if (!UpdateValueIfNeeded())
3812 return nullptr;
3813
3814 TargetSP target_sp(GetTargetSP());
3815 if (!target_sp)
3816 return nullptr;
3817
3818 PersistentExpressionState *persistent_state =
3819 target_sp->GetPersistentExpressionStateForLanguage(
3821
3822 if (!persistent_state)
3823 return nullptr;
3824
3825 ConstString name = persistent_state->GetNextPersistentVariableName();
3826
3827 ValueObjectSP const_result_sp =
3828 ValueObjectConstResult::Create(target_sp.get(), GetValue(), name);
3829
3830 ExpressionVariableSP persistent_var_sp =
3831 persistent_state->CreatePersistentVariable(const_result_sp);
3832 persistent_var_sp->m_live_sp = persistent_var_sp->m_frozen_sp;
3833 persistent_var_sp->m_flags |= ExpressionVariable::EVIsProgramReference;
3834
3835 return persistent_var_sp->GetValueObject();
3836}
3837
3841
3843 lldb::DynamicValueType use_dynamic, bool use_synthetic,
3844 const char *name)
3845 : m_use_dynamic(use_dynamic), m_use_synthetic(use_synthetic), m_name(name) {
3846 if (in_valobj_sp) {
3847 if ((m_valobj_sp = in_valobj_sp->GetQualifiedRepresentationIfAvailable(
3848 lldb::eNoDynamicValues, false))) {
3849 if (!m_name.IsEmpty())
3850 m_valobj_sp->SetName(m_name);
3851 }
3852 }
3853}
3854
3856 if (this != &rhs) {
3860 m_name = rhs.m_name;
3861 }
3862 return *this;
3863}
3864
3866 if (m_valobj_sp.get() == nullptr)
3867 return false;
3868
3869 // FIXME: This check is necessary but not sufficient. We for sure don't
3870 // want to touch SBValues whose owning
3871 // targets have gone away. This check is a little weak in that it
3872 // enforces that restriction when you call IsValid, but since IsValid
3873 // doesn't lock the target, you have no guarantee that the SBValue won't
3874 // go invalid after you call this... Also, an SBValue could depend on
3875 // data from one of the modules in the target, and those could go away
3876 // independently of the target, for instance if a module is unloaded.
3877 // But right now, neither SBValues nor ValueObjects know which modules
3878 // they depend on. So I have no good way to make that check without
3879 // tracking that in all the ValueObject subclasses.
3880 TargetSP target_sp = m_valobj_sp->GetTargetSP();
3881 return target_sp && target_sp->IsValid();
3882}
3883
3885 TargetAPIMutex &api_mutex,
3886 std::unique_lock<TargetAPIMutex> &lock,
3887 Status &error) {
3888 if (!m_valobj_sp) {
3889 error = Status::FromErrorString("invalid value object");
3890 return m_valobj_sp;
3891 }
3892
3894
3895 Target *target = value_sp->GetTargetSP().get();
3896 // If this ValueObject holds an error, then it is valuable for that.
3897 if (value_sp->GetError().Fail())
3898 return value_sp;
3899
3900 if (!target)
3901 return ValueObjectSP();
3902
3903 api_mutex = target->GetAPIMutex();
3904 lock = std::unique_lock<TargetAPIMutex>(api_mutex);
3905
3906 ProcessSP process_sp(value_sp->GetProcessSP());
3907 if (process_sp && !stop_locker.TryLock(&process_sp->GetRunLock())) {
3908 // We don't allow people to play around with ValueObject if the process
3909 // is running. If you want to look at values, pause the process, then
3910 // look.
3911 error = Status::FromErrorString("process must be stopped.");
3912 return ValueObjectSP();
3913 }
3914
3916 ValueObjectSP dynamic_sp = value_sp->GetDynamicValue(m_use_dynamic);
3917 if (dynamic_sp)
3918 value_sp = dynamic_sp;
3919 }
3920
3921 if (m_use_synthetic) {
3922 ValueObjectSP synthetic_sp = value_sp->GetSyntheticValue();
3923 if (synthetic_sp)
3924 value_sp = synthetic_sp;
3925 }
3926
3927 if (!value_sp)
3928 error = Status::FromErrorString("invalid value object");
3929 if (!m_name.IsEmpty())
3930 value_sp->SetName(m_name);
3931
3932 return value_sp;
3933}
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 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
static const char * SkipLeadingExpressionPathSeparators(const char *expression)
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:891
lldb::ByteOrder GetByteOrder() const
Returns the byte order for the architecture specification.
Definition ArchSpec.cpp:940
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:84
static bool LanguageIsCFamily(lldb::LanguageType language)
Equivalent to LanguageIsC||LanguageIsObjC||LanguageIsCPlusPlus.
Definition Language.cpp:379
static bool LanguageIsObjC(lldb::LanguageType language)
Definition Language.cpp:357
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:264
bool TryLock(ProcessRunLock *lock)
Try to acquire the read lock.
A plug-in interface definition class for debugging a process.
Definition Process.h:368
ProcessModID GetModID() const
Get the Modification ID of the process.
Definition Process.h:1510
ProcessRunLock::ProcessRunLocker StopLocker
Definition Process.h:408
bool IsPossibleDynamicValue(ValueObject &in_value)
Definition Process.cpp:1579
LanguageRuntime * GetLanguageRuntime(lldb::LanguageType language)
Definition Process.cpp:1551
size_t WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size, Status &error)
Write memory to a process.
Definition Process.cpp:2595
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:2672
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:5695
bool GetCheckValueObjectOwnership() const
Definition Target.cpp:5994
TargetAPIMutex GetAPIMutex()
Returns a handle resolved to the mutex to serialize on before touching the target through the SB API.
Definition Target.cpp:6098
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:2112
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 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)
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()
lldb::ValueObjectSP GetSyntheticExpressionPathChild(const char *expression, bool can_create)
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:323
RegisterInfo * GetRegisterInfo() const
Definition Value.cpp:142
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:111
Scalar & ResolveValue(ExecutionContext *exe_ctx, Module *module=nullptr)
Definition Value.cpp:593
@ 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:247
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
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.