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 <cstdint>
58#include <cstdlib>
59#include <memory>
60#include <optional>
61#include <tuple>
62
63#include <cassert>
64#include <cinttypes>
65#include <cstdio>
66#include <cstring>
67
68namespace lldb_private {
70}
71namespace lldb_private {
73}
74
75using namespace lldb;
76using namespace lldb_private;
77
79
80// FIXME: this will return true for vector types whose elements
81// are floats. Audit all usages of this function and call
82// IsFloatingPointType() instead if vectors of floats aren't intended
83// to be supported.
85 return ct.GetTypeInfo() & eTypeIsFloat;
86}
87
88// ValueObject constructor
90 : m_parent(&parent), m_update_point(parent.GetUpdatePoint()),
92 m_flags.m_is_synthetic_children_generated =
94 m_data.SetByteOrder(parent.GetDataExtractor().GetByteOrder());
95 m_data.SetAddressByteSize(parent.GetDataExtractor().GetAddressByteSize());
96 m_manager->ManageObject(this);
97}
98
99// ValueObject constructor
101 ValueObjectManager &manager,
102 AddressType child_ptr_or_ref_addr_type)
103 : m_update_point(exe_scope), m_manager(&manager),
104 m_address_type_of_ptr_or_ref_children(child_ptr_or_ref_addr_type),
106 if (exe_scope) {
107 TargetSP target_sp(exe_scope->CalculateTarget());
108 if (target_sp) {
109 const ArchSpec &arch = target_sp->GetArchitecture();
110 m_data.SetByteOrder(arch.GetByteOrder());
111 m_data.SetAddressByteSize(arch.GetAddressByteSize());
112 }
113 }
114 m_manager->ManageObject(this);
115}
116
117// Destructor
118ValueObject::~ValueObject() = default;
119
120bool ValueObject::UpdateValueIfNeeded(bool update_format) {
121
122 bool did_change_formats = false;
123
124 if (update_format)
125 did_change_formats = UpdateFormatsIfNeeded();
126
127 // If this is a constant value, then our success is predicated on whether we
128 // have an error or not
129 if (GetIsConstant()) {
130 // if you are constant, things might still have changed behind your back
131 // (e.g. you are a frozen object and things have changed deeper than you
132 // cared to freeze-dry yourself) in this case, your value has not changed,
133 // but "computed" entries might have, so you might now have a different
134 // summary, or a different object description. clear these so we will
135 // recompute them
136 if (update_format && !did_change_formats)
139 return m_error.Success();
140 }
141
142 bool first_update = IsChecksumEmpty();
143
144 if (NeedsUpdating()) {
145 m_update_point.SetUpdated();
146
147 // Save the old value using swap to avoid a string copy which also will
148 // clear our m_value_str
149 if (m_value_str.empty()) {
150 m_flags.m_old_value_valid = false;
151 } else {
152 m_flags.m_old_value_valid = true;
155 }
156
158
159 if (IsInScope()) {
160 const bool value_was_valid = GetValueIsValid();
161 SetValueDidChange(false);
162
163 m_error.Clear();
164
165 // Call the pure virtual function to update the value
166
167 bool need_compare_checksums = false;
168 llvm::SmallVector<uint8_t, 16> old_checksum;
169
170 if (!first_update && CanProvideValue()) {
171 need_compare_checksums = true;
172 old_checksum.resize(m_value_checksum.size());
173 std::copy(m_value_checksum.begin(), m_value_checksum.end(),
174 old_checksum.begin());
175 }
176
177 bool success = UpdateValue();
178
179 SetValueIsValid(success);
180
181 if (success) {
183 const uint64_t max_checksum_size = 128;
184 m_data.Checksum(m_value_checksum, max_checksum_size);
185 } else {
186 need_compare_checksums = false;
187 m_value_checksum.clear();
188 }
189
190 assert(!need_compare_checksums ||
191 (!old_checksum.empty() && !m_value_checksum.empty()));
192
193 if (first_update)
194 SetValueDidChange(false);
195 else if (!m_flags.m_value_did_change && !success) {
196 // The value wasn't gotten successfully, so we mark this as changed if
197 // the value used to be valid and now isn't
198 SetValueDidChange(value_was_valid);
199 } else if (need_compare_checksums) {
200 SetValueDidChange(memcmp(&old_checksum[0], &m_value_checksum[0],
201 m_value_checksum.size()));
202 }
203
204 } else {
205 m_error = Status::FromErrorString("out of scope");
206 }
207 }
208 return m_error.Success();
209}
210
213 LLDB_LOGF(log,
214 "[%s %p] checking for FormatManager revisions. ValueObject "
215 "rev: %d - Global rev: %d",
216 GetName().GetCString(), static_cast<void *>(this),
219
220 bool any_change = false;
221
224 any_change = true;
225
231 }
232
233 return any_change;
234}
235
237 m_update_point.SetNeedsUpdate();
238 // We have to clear the value string here so ConstResult children will notice
239 // if their values are changed by hand (i.e. with SetValueAsCString).
241}
242
244 m_flags.m_children_count_valid = false;
245 m_flags.m_did_calculate_complete_objc_class_type = false;
251}
252
254 CompilerType compiler_type(GetCompilerTypeImpl());
255
256 if (m_flags.m_did_calculate_complete_objc_class_type) {
257 if (m_override_type.IsValid())
258 return m_override_type;
259 else
260 return compiler_type;
261 }
262
263 m_flags.m_did_calculate_complete_objc_class_type = true;
264
265 ProcessSP process_sp(
267
268 if (!process_sp)
269 return compiler_type;
270
271 if (auto *runtime =
272 process_sp->GetLanguageRuntime(GetObjectRuntimeLanguage())) {
273 if (std::optional<CompilerType> complete_type =
274 runtime->GetRuntimeType(compiler_type)) {
275 m_override_type = *complete_type;
276 if (m_override_type.IsValid())
277 return m_override_type;
278 }
279 }
280 return compiler_type;
281}
282
287
289 UpdateValueIfNeeded(false);
290 return m_error;
291}
292
294 const DataExtractor &data) {
295 if (UpdateValueIfNeeded(false)) {
296 if (m_location_str.empty()) {
297 StreamString sstr;
298
299 Value::ValueType value_type = value.GetValueType();
300
301 switch (value_type) {
303 m_location_str = "invalid";
304 break;
307 RegisterInfo *reg_info = value.GetRegisterInfo();
308 if (reg_info) {
309 if (reg_info->name)
310 m_location_str = reg_info->name;
311 else if (reg_info->alt_name)
312 m_location_str = reg_info->alt_name;
313 if (m_location_str.empty())
315 ? "vector"
316 : "scalar";
317 }
318 }
319 if (m_location_str.empty())
320 m_location_str = "scalar";
321 break;
322
326 uint32_t addr_nibble_size = data.GetAddressByteSize() * 2;
327 sstr.Printf("0x%*.*llx", addr_nibble_size, addr_nibble_size,
329 m_location_str = std::string(sstr.GetString());
330 } break;
331 }
332 }
333 }
334 return m_location_str.c_str();
335}
336
339 false)) // make sure that you are up to date before returning anything
340 {
342 Value tmp_value(m_value);
343 scalar = tmp_value.ResolveValue(&exe_ctx, GetModule().get());
344 if (scalar.IsValid()) {
345 const uint32_t bitfield_bit_size = GetBitfieldBitSize();
346 if (bitfield_bit_size)
347 return scalar.ExtractBitfield(bitfield_bit_size,
349 return true;
350 }
351 }
352 return false;
353}
354
357 LazyBool is_logical_true = language->IsLogicalTrue(*this, error);
358 switch (is_logical_true) {
359 case eLazyBoolYes:
360 case eLazyBoolNo:
361 return (is_logical_true == true);
363 break;
364 }
365 }
366
367 Scalar scalar_value;
368
369 if (!ResolveValue(scalar_value)) {
370 error = Status::FromErrorString("failed to get a scalar result");
371 return false;
372 }
373
374 bool ret;
375 ret = scalar_value.ULongLong(1) != 0;
376 error.Clear();
377 return ret;
378}
379
381 Target *target_ptr = GetTargetSP().get();
382 if (!target_ptr)
383 return {};
384
385 if (target_ptr->GetCheckValueObjectOwnership()) {
386 // Child value objects should always be owned by their parent's manager.
387 if (child && (child->GetManager() != GetManager())) {
389 "ValueObject: '{0}' not owned by its parent: '{1}'", child->GetName(),
390 GetName());
391 return ValueObjectConstResult::Create(target_ptr, std::move(error),
392 this->GetManager());
393 }
394 }
395 return {};
396}
397
398ValueObjectSP ValueObject::GetChildAtIndex(uint32_t idx, bool can_create) {
399 ValueObjectSP child_sp;
400 // We may need to update our value if we are dynamic
402 UpdateValueIfNeeded(false);
403 if (idx < GetNumChildrenIgnoringErrors()) {
404 // Check if we have already made the child value object?
405 if (can_create && !m_children.HasChildAtIndex(idx)) {
406 // No we haven't created the child at this index, so lets have our
407 // subclass do it and cache the result for quick future access.
408 m_children.SetChildAtIndex(idx, CreateChildAtIndex(idx));
409 }
410
411 ValueObject *child = m_children.GetChildAtIndex(idx);
412 if (child != nullptr)
413 return child->GetSP();
414 }
415 return child_sp;
416}
417
419ValueObject::GetChildAtNamePath(llvm::ArrayRef<llvm::StringRef> names) {
420 if (names.size() == 0)
421 return GetSP();
422 ValueObjectSP root(GetSP());
423 for (llvm::StringRef name : names) {
424 root = root->GetChildMemberWithName(name);
425 if (!root) {
426 return root;
427 }
428 }
429 return root;
430}
431
432llvm::Expected<size_t>
434 bool omit_empty_base_classes = true;
436 omit_empty_base_classes);
437}
438
440 bool can_create) {
441 // We may need to update our value if we are dynamic.
443 UpdateValueIfNeeded(false);
444
445 // When getting a child by name, it could be buried inside some base classes
446 // (which really aren't part of the expression path), so we need a vector of
447 // indexes that can get us down to the correct child.
448 std::vector<uint32_t> child_indexes;
449 bool omit_empty_base_classes = true;
450
451 if (!GetCompilerType().IsValid())
452 return ValueObjectSP();
453
454 const size_t num_child_indexes =
456 name, omit_empty_base_classes, child_indexes);
457 if (num_child_indexes == 0)
458 return nullptr;
459
460 ValueObjectSP child_sp = GetSP();
461 for (uint32_t idx : child_indexes)
462 if (child_sp)
463 child_sp = child_sp->GetChildAtIndex(idx, can_create);
464 return child_sp;
465}
466
467llvm::Expected<uint32_t> ValueObject::GetNumChildren(uint32_t max) {
469
470 if (max < UINT32_MAX) {
471 if (m_flags.m_children_count_valid) {
472 size_t children_count = m_children.GetChildrenCount();
473 return children_count <= max ? children_count : max;
474 } else
475 return CalculateNumChildren(max);
476 }
477
478 if (!m_flags.m_children_count_valid) {
479 auto num_children_or_err = CalculateNumChildren();
480 if (num_children_or_err)
481 SetNumChildren(*num_children_or_err);
482 else
483 return num_children_or_err;
484 }
485 return m_children.GetChildrenCount();
486}
487
489 auto value_or_err = GetNumChildren(max);
490 if (value_or_err)
491 return *value_or_err;
492 LLDB_LOG_ERRORV(GetLog(LLDBLog::DataFormatters), value_or_err.takeError(),
493 "{0}");
494 return 0;
495}
496
498 bool has_children = false;
499 const uint32_t type_info = GetTypeInfo();
500 if (type_info) {
501 if (type_info & (eTypeHasChildren | eTypeIsPointer | eTypeIsReference))
502 has_children = true;
503 } else {
504 has_children = GetNumChildrenIgnoringErrors() > 0;
505 }
506 return has_children;
507}
508
509// Should only be called by ValueObject::GetNumChildren()
510void ValueObject::SetNumChildren(uint32_t num_children) {
511 m_flags.m_children_count_valid = true;
512 m_children.SetChildrenCount(num_children);
513}
514
516 bool omit_empty_base_classes = true;
517 bool ignore_array_bounds = false;
518 std::string child_name;
519 uint32_t child_byte_size = 0;
520 int32_t child_byte_offset = 0;
521 uint32_t child_bitfield_bit_size = 0;
522 uint32_t child_bitfield_bit_offset = 0;
523 bool child_is_base_class = false;
524 bool child_is_deref_of_parent = false;
525 uint64_t language_flags = 0;
526 const bool transparent_pointers = true;
527
529
530 auto child_compiler_type_or_err =
532 &exe_ctx, idx, transparent_pointers, omit_empty_base_classes,
533 ignore_array_bounds, child_name, child_byte_size, child_byte_offset,
534 child_bitfield_bit_size, child_bitfield_bit_offset,
535 child_is_base_class, child_is_deref_of_parent, this, language_flags);
536 if (!child_compiler_type_or_err || !child_compiler_type_or_err->IsValid()) {
538 child_compiler_type_or_err.takeError(),
539 "could not find child: {0}");
540 return nullptr;
541 }
542
543 return new ValueObjectChild(
544 *this, *child_compiler_type_or_err, ConstString(child_name),
545 child_byte_size, child_byte_offset, child_bitfield_bit_size,
546 child_bitfield_bit_offset, child_is_base_class, child_is_deref_of_parent,
547 eAddressTypeInvalid, language_flags);
548}
549
551 bool omit_empty_base_classes = true;
552 bool ignore_array_bounds = true;
553 std::string child_name;
554 uint32_t child_byte_size = 0;
555 int32_t child_byte_offset = 0;
556 uint32_t child_bitfield_bit_size = 0;
557 uint32_t child_bitfield_bit_offset = 0;
558 bool child_is_base_class = false;
559 bool child_is_deref_of_parent = false;
560 uint64_t language_flags = 0;
561 const bool transparent_pointers = false;
562
564
565 auto child_compiler_type_or_err =
567 &exe_ctx, 0, transparent_pointers, omit_empty_base_classes,
568 ignore_array_bounds, child_name, child_byte_size, child_byte_offset,
569 child_bitfield_bit_size, child_bitfield_bit_offset,
570 child_is_base_class, child_is_deref_of_parent, this, language_flags);
571 if (!child_compiler_type_or_err) {
573 child_compiler_type_or_err.takeError(),
574 "could not find child: {0}");
575 return nullptr;
576 }
577
578 if (child_compiler_type_or_err->IsValid()) {
579 child_byte_offset += child_byte_size * idx;
580
581 return new ValueObjectChild(
582 *this, *child_compiler_type_or_err, ConstString(child_name),
583 child_byte_size, child_byte_offset, child_bitfield_bit_size,
584 child_bitfield_bit_offset, child_is_base_class,
585 child_is_deref_of_parent, eAddressTypeInvalid, language_flags);
586 }
587
588 // In case of an incomplete type, try to use the ValueObject's
589 // synthetic value to create the child ValueObject.
590 if (ValueObjectSP synth_valobj_sp = GetSyntheticValue())
591 return synth_valobj_sp->GetChildAtIndex(idx, /*can_create=*/true).get();
592
593 return nullptr;
594}
595
597 std::string &destination,
598 lldb::LanguageType lang) {
599 return GetSummaryAsCString(summary_ptr, destination,
600 TypeSummaryOptions().SetLanguage(lang));
601}
602
604 std::string &destination,
605 const TypeSummaryOptions &options) {
606 destination.clear();
607
608 // If we have a forcefully completed type, don't try and show a summary from
609 // a valid summary string or function because the type is not complete and
610 // no member variables or member functions will be available.
611 if (GetCompilerType().IsForcefullyCompleted()) {
612 destination = "<incomplete type>";
613 return true;
614 }
615
616 // ideally we would like to bail out if passing NULL, but if we do so we end
617 // up not providing the summary for function pointers anymore
618 if (/*summary_ptr == NULL ||*/ m_flags.m_is_getting_summary)
619 return false;
620
621 m_flags.m_is_getting_summary = true;
622
623 TypeSummaryOptions actual_options(options);
624
625 if (actual_options.GetLanguage() == lldb::eLanguageTypeUnknown)
627
628 // this is a hot path in code and we prefer to avoid setting this string all
629 // too often also clearing out other information that we might care to see in
630 // a crash log. might be useful in very specific situations though.
631 /*Host::SetCrashDescriptionWithFormat("Trying to fetch a summary for %s %s.
632 Summary provider's description is %s",
633 GetTypeName().GetCString(),
634 GetName().GetCString(),
635 summary_ptr->GetDescription().c_str());*/
636
637 if (UpdateValueIfNeeded(false) && summary_ptr) {
638 if (HasSyntheticValue())
639 m_synthetic_value->UpdateValueIfNeeded(); // the summary might depend on
640 // the synthetic children being
641 // up-to-date (e.g. ${svar%#})
642
643 if (TargetSP target_sp = GetExecutionContextRef().GetTargetSP()) {
644 SummaryStatisticsSP stats_sp =
645 target_sp->GetSummaryStatisticsCache()
646 .GetSummaryStatisticsForProvider(*summary_ptr);
647
648 // Construct RAII types to time and collect data on summary creation.
649 SummaryStatistics::SummaryInvocation invocation(stats_sp);
650 summary_ptr->FormatObject(this, destination, actual_options);
651 } else
652 summary_ptr->FormatObject(this, destination, actual_options);
653 }
654 m_flags.m_is_getting_summary = false;
655 return !destination.empty();
656}
657
659 if (UpdateValueIfNeeded(true) && m_summary_str.empty()) {
660 TypeSummaryOptions summary_options;
661 summary_options.SetLanguage(lang);
663 summary_options);
664 }
665 if (m_summary_str.empty())
666 return nullptr;
667 return m_summary_str.c_str();
668}
669
670bool ValueObject::GetSummaryAsCString(std::string &destination,
671 const TypeSummaryOptions &options) {
672 return GetSummaryAsCString(GetSummaryFormat().get(), destination, options);
673}
674
675bool ValueObject::IsCStringContainer(bool check_pointer) {
676 CompilerType pointee_or_element_compiler_type;
677 const Flags type_flags(GetTypeInfo(&pointee_or_element_compiler_type));
678 bool is_char_arr_ptr(type_flags.AnySet(eTypeIsArray | eTypeIsPointer) &&
679 pointee_or_element_compiler_type.IsCharType());
680 if (!is_char_arr_ptr)
681 return false;
682 if (!check_pointer)
683 return true;
684 if (type_flags.Test(eTypeIsArray))
685 return true;
686 addr_t cstr_address = GetPointerValue().address;
687 return (cstr_address != LLDB_INVALID_ADDRESS);
688}
689
690size_t ValueObject::GetPointeeData(DataExtractor &data, uint32_t item_idx,
691 uint32_t item_count) {
692 CompilerType pointee_or_element_compiler_type;
693 const uint32_t type_info = GetTypeInfo(&pointee_or_element_compiler_type);
694 const bool is_pointer_type = type_info & eTypeIsPointer;
695 const bool is_array_type = type_info & eTypeIsArray;
696 if (!(is_pointer_type || is_array_type))
697 return 0;
698
699 if (item_count == 0)
700 return 0;
701
703
704 std::optional<uint64_t> item_type_size =
705 llvm::expectedToOptional(pointee_or_element_compiler_type.GetByteSize(
707 if (!item_type_size)
708 return 0;
709 const uint64_t bytes = item_count * *item_type_size;
710 const uint64_t offset = item_idx * *item_type_size;
711
712 if (item_idx == 0 && item_count == 1) // simply a deref
713 {
714 if (is_pointer_type) {
716 ValueObjectSP pointee_sp = Dereference(error);
717 if (error.Fail() || pointee_sp.get() == nullptr)
718 return 0;
719 return pointee_sp->GetData(data, error);
720 } else {
721 ValueObjectSP child_sp = GetChildAtIndex(0);
722 if (child_sp.get() == nullptr)
723 return 0;
725 return child_sp->GetData(data, error);
726 }
727 return 0;
728 } else /* (items > 1) */
729 {
731 lldb_private::DataBufferHeap *heap_buf_ptr = nullptr;
732 lldb::DataBufferSP data_sp(heap_buf_ptr =
734
735 auto [addr, addr_type] =
736 is_pointer_type ? GetPointerValue() : GetAddressOf(true);
737
738 switch (addr_type) {
739 case eAddressTypeFile: {
740 ModuleSP module_sp(GetModule());
741 if (module_sp) {
742 addr = addr + offset;
743 Address so_addr;
744 module_sp->ResolveFileAddress(addr, so_addr);
746 Target *target = exe_ctx.GetTargetPtr();
747 if (target) {
748 heap_buf_ptr->SetByteSize(bytes);
749 size_t bytes_read = target->ReadMemory(
750 so_addr, heap_buf_ptr->GetBytes(), bytes, error, true);
751 if (error.Success()) {
752 data.SetData(data_sp);
753 return bytes_read;
754 }
755 }
756 }
757 } break;
758 case eAddressTypeLoad: {
760 if (Target *target = exe_ctx.GetTargetPtr()) {
761 heap_buf_ptr->SetByteSize(bytes);
762 Address target_addr;
763 target_addr.SetLoadAddress(addr + offset, target);
764 size_t bytes_read =
765 target->ReadMemory(target_addr, heap_buf_ptr->GetBytes(), bytes,
766 error, /*force_live_memory=*/true);
767 if (error.Success() || bytes_read > 0) {
768 data.SetData(data_sp);
769 return bytes_read;
770 }
771 }
772 } break;
773 case eAddressTypeHost: {
774 auto max_bytes = llvm::expectedToOptional(GetCompilerType().GetByteSize(
776 if (max_bytes && *max_bytes > offset) {
777 size_t bytes_read = std::min<uint64_t>(*max_bytes - offset, bytes);
778 addr = m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
779 if (addr == 0 || addr == LLDB_INVALID_ADDRESS)
780 break;
781 heap_buf_ptr->CopyData((uint8_t *)(addr + offset), bytes_read);
782 data.SetData(data_sp);
783 return bytes_read;
784 }
785 } break;
787 break;
788 }
789 }
790 return 0;
791}
792
794 UpdateValueIfNeeded(false);
796 error = m_value.GetValueAsData(&exe_ctx, data, GetModule().get());
797 if (error.Fail()) {
798 if (m_data.GetByteSize()) {
799 data = m_data;
800 error.Clear();
801 return data.GetByteSize();
802 } else {
803 return 0;
804 }
805 }
806 data.SetAddressByteSize(m_data.GetAddressByteSize());
807 data.SetByteOrder(m_data.GetByteOrder());
808 return data.GetByteSize();
809}
810
812 error.Clear();
813 // Make sure our value is up to date first so that our location and location
814 // type is valid.
815 if (!UpdateValueIfNeeded(false)) {
816 error = Status::FromErrorString("unable to read value");
817 return false;
818 }
819
820 const Encoding encoding = GetCompilerType().GetEncoding();
821
822 const size_t byte_size = llvm::expectedToOptional(GetByteSize()).value_or(0);
823
824 Value::ValueType value_type = m_value.GetValueType();
825
826 switch (value_type) {
828 error = Status::FromErrorString("invalid location");
829 return false;
831 Status set_error =
832 m_value.GetScalar().SetValueFromData(data, encoding, byte_size);
833
834 if (!set_error.Success()) {
836 "unable to set scalar value: %s", set_error.AsCString());
837 return false;
838 }
839 } break;
841 // If it is a load address, then the scalar value is the storage location
842 // of the data, and we have to shove this value down to that load location.
844 Process *process = exe_ctx.GetProcessPtr();
845 if (process) {
846 addr_t target_addr = m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
847 size_t bytes_written = process->WriteMemory(
848 target_addr, data.GetDataStart(), byte_size, error);
849 if (!error.Success())
850 return false;
851 if (bytes_written != byte_size) {
852 error = Status::FromErrorString("unable to write value to memory");
853 return false;
854 }
855 }
856 } break;
858 // If it is a host address, then we stuff the scalar as a DataBuffer into
859 // the Value's data.
860 DataBufferSP buffer_sp(new DataBufferHeap(byte_size, 0));
861 m_data.SetData(buffer_sp, 0);
862 data.CopyByteOrderedData(0, byte_size,
863 const_cast<uint8_t *>(m_data.GetDataStart()),
864 byte_size, m_data.GetByteOrder());
865 m_value.GetScalar() = (uintptr_t)m_data.GetDataStart();
866 } break;
868 break;
869 }
870
871 // If we have reached this point, then we have successfully changed the
872 // value.
874 return true;
875}
876
877llvm::ArrayRef<uint8_t> ValueObject::GetLocalBuffer() const {
878 if (m_value.GetValueType() != Value::ValueType::HostAddress)
879 return {};
880 auto start = m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
881 if (start == LLDB_INVALID_ADDRESS)
882 return {};
883 // Does our pointer point to this value object's m_data buffer?
884 if ((uint64_t)m_data.GetDataStart() == start)
885 return m_data.GetData();
886 // Does our pointer point to the value's buffer?
887 if ((uint64_t)m_value.GetBuffer().GetBytes() == start)
888 return m_value.GetBuffer().GetData();
889 // Our pointer points to something else. We can't know what the size is.
890 return {};
891}
892
893static bool CopyStringDataToBufferSP(const StreamString &source,
894 lldb::WritableDataBufferSP &destination) {
895 llvm::StringRef src = source.GetString();
896 src = src.rtrim('\0');
897 destination = std::make_shared<DataBufferHeap>(src.size(), 0);
898 memcpy(destination->GetBytes(), src.data(), src.size());
899 return true;
900}
901
902std::pair<size_t, bool>
904 Status &error, bool honor_array) {
905 bool was_capped = false;
906 StreamString s;
908 Target *target = exe_ctx.GetTargetPtr();
909
910 if (!target) {
911 s << "<no target to read from>";
912 error = Status::FromErrorString("no target to read from");
913 CopyStringDataToBufferSP(s, buffer_sp);
914 return {0, was_capped};
915 }
916
917 const auto max_length = target->GetMaximumSizeOfStringSummary();
918
919 size_t bytes_read = 0;
920 size_t total_bytes_read = 0;
921
922 CompilerType compiler_type = GetCompilerType();
923 CompilerType elem_or_pointee_compiler_type;
924 const Flags type_flags(GetTypeInfo(&elem_or_pointee_compiler_type));
925 if (type_flags.AnySet(eTypeIsArray | eTypeIsPointer) &&
926 elem_or_pointee_compiler_type.IsCharType()) {
927 AddrAndType cstr_address;
928
929 size_t cstr_len = 0;
930 bool capped_data = false;
931 const bool is_array = type_flags.Test(eTypeIsArray);
932 if (is_array) {
933 // We have an array
934 uint64_t array_size = 0;
935 if (compiler_type.IsArrayType(nullptr, &array_size)) {
936 cstr_len = array_size;
937 if (cstr_len > max_length) {
938 capped_data = true;
939 cstr_len = max_length;
940 }
941 }
942 cstr_address = GetAddressOf(true);
943 } else {
944 // We have a pointer
945 cstr_address = GetPointerValue();
946 }
947
948 if (cstr_address.address == 0 ||
949 cstr_address.address == LLDB_INVALID_ADDRESS) {
950 if (cstr_address.type == eAddressTypeHost && is_array) {
951 const char *cstr = GetDataExtractor().PeekCStr(0);
952 if (cstr == nullptr) {
953 s << "<invalid address>";
954 error = Status::FromErrorString("invalid address");
955 CopyStringDataToBufferSP(s, buffer_sp);
956 return {0, was_capped};
957 }
958 s << llvm::StringRef(cstr, cstr_len);
959 CopyStringDataToBufferSP(s, buffer_sp);
960 return {cstr_len, was_capped};
961 } else {
962 s << "<invalid address>";
963 error = Status::FromErrorString("invalid address");
964 CopyStringDataToBufferSP(s, buffer_sp);
965 return {0, was_capped};
966 }
967 }
968
969 Address cstr_so_addr(cstr_address.address);
970 DataExtractor data;
971 if (cstr_len > 0 && honor_array) {
972 // I am using GetPointeeData() here to abstract the fact that some
973 // ValueObjects are actually frozen pointers in the host but the pointed-
974 // to data lives in the debuggee, and GetPointeeData() automatically
975 // takes care of this
976 GetPointeeData(data, 0, cstr_len);
977
978 if ((bytes_read = data.GetByteSize()) > 0) {
979 total_bytes_read = bytes_read;
980 for (size_t offset = 0; offset < bytes_read; offset++)
981 s.Printf("%c", *data.PeekData(offset, 1));
982 if (capped_data)
983 was_capped = true;
984 }
985 } else {
986 cstr_len = max_length;
987 const size_t k_max_buf_size = 64;
988
989 size_t offset = 0;
990
991 int cstr_len_displayed = -1;
992 bool capped_cstr = false;
993 // I am using GetPointeeData() here to abstract the fact that some
994 // ValueObjects are actually frozen pointers in the host but the pointed-
995 // to data lives in the debuggee, and GetPointeeData() automatically
996 // takes care of this
997 while ((bytes_read = GetPointeeData(data, offset, k_max_buf_size)) > 0) {
998 total_bytes_read += bytes_read;
999 const char *cstr = data.PeekCStr(0);
1000 size_t len = strnlen(cstr, k_max_buf_size);
1001 if (cstr_len_displayed < 0)
1002 cstr_len_displayed = len;
1003
1004 if (len == 0)
1005 break;
1006 cstr_len_displayed += len;
1007 if (len > bytes_read)
1008 len = bytes_read;
1009 if (len > cstr_len)
1010 len = cstr_len;
1011
1012 for (size_t offset = 0; offset < bytes_read; offset++)
1013 s.Printf("%c", *data.PeekData(offset, 1));
1014
1015 if (len < k_max_buf_size)
1016 break;
1017
1018 if (len >= cstr_len) {
1019 capped_cstr = true;
1020 break;
1021 }
1022
1023 cstr_len -= len;
1024 offset += len;
1025 }
1026
1027 if (cstr_len_displayed >= 0) {
1028 if (capped_cstr)
1029 was_capped = true;
1030 }
1031 }
1032 } else {
1033 error = Status::FromErrorString("not a string object");
1034 s << "<not a string object>";
1035 }
1036 CopyStringDataToBufferSP(s, buffer_sp);
1037 return {total_bytes_read, was_capped};
1038}
1039
1040llvm::Expected<std::string> ValueObject::GetObjectDescription() {
1041 if (!UpdateValueIfNeeded(true))
1042 return llvm::createStringError("could not update value");
1043
1044 // Return cached value.
1045 if (!m_object_desc_str.empty())
1046 return m_object_desc_str;
1047
1049 Process *process = exe_ctx.GetProcessPtr();
1050 if (!process)
1051 return llvm::createStringError("no process");
1052
1053 // Returns the object description produced by one language runtime.
1054 auto get_object_description =
1055 [&](LanguageType language) -> llvm::Expected<std::string> {
1056 if (LanguageRuntime *runtime = process->GetLanguageRuntime(language)) {
1057 StreamString s;
1058 if (llvm::Error error = runtime->GetObjectDescription(s, *this))
1059 return error;
1061 return m_object_desc_str;
1062 }
1063 return llvm::createStringError("no native language runtime");
1064 };
1065
1066 // Try the native language runtime first.
1067 LanguageType native_language = GetObjectRuntimeLanguage();
1068 llvm::Expected<std::string> desc = get_object_description(native_language);
1069 if (desc)
1070 return desc;
1071
1072 // Try the Objective-C language runtime. This fallback is necessary
1073 // for Objective-C++ and mixed Objective-C / C++ programs.
1074 if (Language::LanguageIsCFamily(native_language)) {
1075 // We're going to try again, so let's drop the first error.
1076 llvm::consumeError(desc.takeError());
1077 return get_object_description(eLanguageTypeObjC);
1078 }
1079 return desc;
1080}
1081
1083 std::string &destination) {
1084 if (UpdateValueIfNeeded(false))
1085 return format.FormatObject(this, destination);
1086 else
1087 return false;
1088}
1089
1091 std::string &destination) {
1092 return GetValueAsCString(TypeFormatImpl_Format(format), destination);
1093}
1094
1096 if (UpdateValueIfNeeded(true)) {
1097 lldb::TypeFormatImplSP format_sp;
1098 lldb::Format my_format = GetFormat();
1099 if (my_format == lldb::eFormatDefault) {
1100 if (m_type_format_sp)
1101 format_sp = m_type_format_sp;
1102 else {
1103 if (m_flags.m_is_bitfield_for_scalar)
1104 my_format = eFormatUnsigned;
1105 else {
1106 if (m_value.GetContextType() == Value::ContextType::RegisterInfo) {
1107 const RegisterInfo *reg_info = m_value.GetRegisterInfo();
1108 if (reg_info)
1109 my_format = reg_info->format;
1110 } else {
1111 my_format = GetValue().GetCompilerType().GetFormat();
1112 }
1113 }
1114 }
1115 }
1116 if (my_format != m_last_format || m_value_str.empty()) {
1117 m_last_format = my_format;
1118 if (!format_sp)
1119 format_sp = std::make_shared<TypeFormatImpl_Format>(my_format);
1120 if (GetValueAsCString(*format_sp.get(), m_value_str)) {
1121 if (!m_flags.m_value_did_change && m_flags.m_old_value_valid) {
1122 // The value was gotten successfully, so we consider the value as
1123 // changed if the value string differs
1125 }
1126 }
1127 }
1128 }
1129 if (m_value_str.empty())
1130 return nullptr;
1131 return m_value_str.c_str();
1132}
1133
1134// if > 8bytes, 0 is returned. this method should mostly be used to read
1135// address values out of pointers
1136uint64_t ValueObject::GetValueAsUnsigned(uint64_t fail_value, bool *success) {
1137 // If our byte size is zero this is an aggregate type that has children
1138 if (CanProvideValue()) {
1139 Scalar scalar;
1140 if (ResolveValue(scalar)) {
1141 if (success)
1142 *success = true;
1143 scalar.MakeUnsigned();
1144 return scalar.ULongLong(fail_value);
1145 }
1146 // fallthrough, otherwise...
1147 }
1148
1149 if (success)
1150 *success = false;
1151 return fail_value;
1152}
1153
1154int64_t ValueObject::GetValueAsSigned(int64_t fail_value, bool *success) {
1155 // If our byte size is zero this is an aggregate type that has children
1156 if (CanProvideValue()) {
1157 Scalar scalar;
1158 if (ResolveValue(scalar)) {
1159 if (success)
1160 *success = true;
1161 scalar.MakeSigned();
1162 return scalar.SLongLong(fail_value);
1163 }
1164 // fallthrough, otherwise...
1165 }
1166
1167 if (success)
1168 *success = false;
1169 return fail_value;
1170}
1171
1172llvm::Expected<llvm::APSInt> ValueObject::GetValueAsAPSInt() {
1173 // Make sure the type can be converted to an APSInt.
1174 if (!GetCompilerType().IsInteger() &&
1175 !GetCompilerType().IsScopedEnumerationType() &&
1176 !GetCompilerType().IsEnumerationType() &&
1178 !GetCompilerType().IsNullPtrType() &&
1179 !GetCompilerType().IsReferenceType() && !GetCompilerType().IsBoolean())
1180 return llvm::createStringError("type cannot be converted to APSInt");
1181
1182 if (CanProvideValue()) {
1183 Scalar scalar;
1184 if (ResolveValue(scalar))
1185 return scalar.GetAPSInt();
1186 }
1187
1188 return llvm::createStringError("error occurred; unable to convert to APSInt");
1189}
1190
1191llvm::Expected<llvm::APFloat> ValueObject::GetValueAsAPFloat() {
1193 return llvm::createStringError("type cannot be converted to APFloat");
1194
1195 if (CanProvideValue()) {
1196 Scalar scalar;
1197 if (ResolveValue(scalar))
1198 return scalar.GetAPFloat();
1199 }
1200
1201 return llvm::createStringError(
1202 "error occurred; unable to convert to APFloat");
1203}
1204
1205llvm::Expected<bool> ValueObject::GetValueAsBool() {
1206 CompilerType val_type = GetCompilerType();
1207 if (val_type.IsInteger() || val_type.IsUnscopedEnumerationType() ||
1208 val_type.IsPointerType()) {
1209 auto value_or_err = GetValueAsAPSInt();
1210 if (value_or_err)
1211 return value_or_err->getBoolValue();
1212 else
1213 LLDB_LOG_ERROR(GetLog(LLDBLog::Types), value_or_err.takeError(),
1214 "GetValueAsAPSInt failed: {0}");
1215 }
1216 if (HasFloatingRepresentation(val_type)) {
1217 auto value_or_err = GetValueAsAPFloat();
1218 if (value_or_err)
1219 return value_or_err->isNonZero();
1220 else
1221 LLDB_LOG_ERROR(GetLog(LLDBLog::Types), value_or_err.takeError(),
1222 "GetValueAsAPFloat failed: {0}");
1223 }
1224 if (val_type.IsArrayType())
1225 return GetAddressOf().address != 0;
1226
1227 return llvm::createStringError("type cannot be converted to bool");
1228}
1229
1230void ValueObject::SetValueFromInteger(const llvm::APInt &value, Status &error,
1231 bool can_update_var) {
1232 // Verify the current object is an integer object
1233 CompilerType val_type = GetCompilerType();
1234 if (!val_type.IsInteger() && !val_type.IsUnscopedEnumerationType() &&
1235 !HasFloatingRepresentation(val_type) && !val_type.IsPointerType() &&
1236 !val_type.IsScalarType()) {
1237 error =
1238 Status::FromErrorString("current value object is not an scalar object");
1239 return;
1240 }
1241
1242 // Verify, if current object is associated with a program variable, that
1243 // we are allowing updating program variables in this case.
1244 if (GetVariable() && !can_update_var) {
1246 "Not allowed to update program variables in this case.");
1247 return;
1248 }
1249
1250 // Verify the proposed new value is the right size.
1251 lldb::TargetSP target = GetTargetSP();
1252 uint64_t byte_size = 0;
1253 if (auto temp =
1254 llvm::expectedToOptional(GetCompilerType().GetByteSize(target.get())))
1255 byte_size = temp.value();
1256 if (value.getBitWidth() != byte_size * CHAR_BIT) {
1258 "illegal argument: new value should be of the same size");
1259 return;
1260 }
1261
1262 lldb::DataExtractorSP data_sp = std::make_shared<DataExtractor>(
1263 reinterpret_cast<const void *>(value.getRawData()), byte_size,
1264 target->GetArchitecture().GetByteOrder(),
1265 static_cast<uint8_t>(target->GetArchitecture().GetAddressByteSize()));
1266 SetData(*data_sp, error);
1267}
1268
1270 Status &error, bool can_update_var) {
1271 // Verify the current object is an integer object
1272 CompilerType val_type = GetCompilerType();
1273 if (!val_type.IsInteger() && !val_type.IsUnscopedEnumerationType() &&
1274 !HasFloatingRepresentation(val_type) && !val_type.IsPointerType() &&
1275 !val_type.IsScalarType()) {
1276 error =
1277 Status::FromErrorString("current value object is not an scalar object");
1278 return;
1279 }
1280
1281 // Verify, if current object is associated with a program variable, that
1282 // we are allowing updating program variables in this case.
1283 if (GetVariable() && !can_update_var) {
1285 "Not allowed to update program variables in this case.");
1286 return;
1287 }
1288
1289 // Verify the proposed new value is the right type.
1290 CompilerType new_val_type = new_val_sp->GetCompilerType();
1291 if (!new_val_type.IsInteger() && !HasFloatingRepresentation(new_val_type) &&
1292 !new_val_type.IsPointerType()) {
1294 "illegal argument: new value should be of the same size");
1295 return;
1296 }
1297
1298 if (new_val_type.IsInteger()) {
1299 auto value_or_err = new_val_sp->GetValueAsAPSInt();
1300 if (value_or_err)
1301 SetValueFromInteger(*value_or_err, error, can_update_var);
1302 else
1303 error = Status::FromError(value_or_err.takeError());
1304 } else if (HasFloatingRepresentation(new_val_type)) {
1305 auto value_or_err = new_val_sp->GetValueAsAPFloat();
1306 if (value_or_err)
1307 SetValueFromInteger(value_or_err->bitcastToAPInt(), error,
1308 can_update_var);
1309 else
1310 error = Status::FromError(value_or_err.takeError());
1311 } else if (new_val_type.IsPointerType()) {
1312 bool success = true;
1313 uint64_t int_val = new_val_sp->GetValueAsUnsigned(0, &success);
1314 if (success) {
1315 lldb::TargetSP target = GetTargetSP();
1316 uint64_t num_bits = 0;
1317 if (auto temp = llvm::expectedToOptional(
1318 new_val_sp->GetCompilerType().GetBitSize(target.get())))
1319 num_bits = temp.value();
1320 SetValueFromInteger(llvm::APInt(num_bits, int_val), error,
1321 can_update_var);
1322 } else
1323 error = Status::FromErrorString("error converting new_val_sp to integer");
1324 }
1325}
1326
1327// if any more "special cases" are added to
1328// ValueObject::DumpPrintableRepresentation() please keep this call up to date
1329// by returning true for your new special cases. We will eventually move to
1330// checking this call result before trying to display special cases
1332 ValueObjectRepresentationStyle val_obj_display, Format custom_format) {
1333 Flags flags(GetTypeInfo());
1334 if (flags.AnySet(eTypeIsArray | eTypeIsPointer) &&
1336 if (IsCStringContainer(true) &&
1337 (custom_format == eFormatCString || custom_format == eFormatCharArray ||
1338 custom_format == eFormatChar || custom_format == eFormatVectorOfChar))
1339 return true;
1340
1341 if (flags.Test(eTypeIsArray)) {
1342 if ((custom_format == eFormatBytes) ||
1343 (custom_format == eFormatBytesWithASCII))
1344 return true;
1345
1346 if ((custom_format == eFormatVectorOfChar) ||
1347 (custom_format == eFormatVectorOfFloat32) ||
1348 (custom_format == eFormatVectorOfFloat64) ||
1349 (custom_format == eFormatVectorOfSInt16) ||
1350 (custom_format == eFormatVectorOfSInt32) ||
1351 (custom_format == eFormatVectorOfSInt64) ||
1352 (custom_format == eFormatVectorOfSInt8) ||
1353 (custom_format == eFormatVectorOfUInt128) ||
1354 (custom_format == eFormatVectorOfUInt16) ||
1355 (custom_format == eFormatVectorOfUInt32) ||
1356 (custom_format == eFormatVectorOfUInt64) ||
1357 (custom_format == eFormatVectorOfUInt8))
1358 return true;
1359 }
1360 }
1361 return false;
1362}
1363
1365 Stream &s, ValueObjectRepresentationStyle val_obj_display,
1366 Format custom_format, PrintableRepresentationSpecialCases special,
1367 bool do_dump_error) {
1368
1369 // If the ValueObject has an error, we might end up dumping the type, which
1370 // is useful, but if we don't even have a type, then don't examine the object
1371 // further as that's not meaningful, only the error is.
1372 if (m_error.Fail() && !GetCompilerType().IsValid()) {
1373 if (do_dump_error)
1374 s.Printf("<%s>", m_error.AsCString());
1375 return false;
1376 }
1377
1378 Flags flags(GetTypeInfo());
1379
1380 bool allow_special =
1382 const bool only_special = false;
1383
1384 if (allow_special) {
1385 if (flags.AnySet(eTypeIsArray | eTypeIsPointer) &&
1387 // when being asked to get a printable display an array or pointer type
1388 // directly, try to "do the right thing"
1389
1390 if (IsCStringContainer(true) &&
1391 (custom_format == eFormatCString ||
1392 custom_format == eFormatCharArray || custom_format == eFormatChar ||
1393 custom_format ==
1394 eFormatVectorOfChar)) // print char[] & char* directly
1395 {
1396 Status error;
1398 std::pair<size_t, bool> read_string =
1399 ReadPointedString(buffer_sp, error,
1400 (custom_format == eFormatVectorOfChar) ||
1401 (custom_format == eFormatCharArray));
1402 lldb_private::formatters::StringPrinter::
1403 ReadBufferAndDumpToStreamOptions options(*this);
1404 options.SetData(DataExtractor(
1405 buffer_sp, lldb::eByteOrderInvalid,
1406 8)); // none of this matters for a string - pass some defaults
1407 options.SetStream(&s);
1408 options.SetPrefixToken(nullptr);
1409 options.SetQuote('"');
1410 options.SetSourceSize(buffer_sp->GetByteSize());
1411 options.SetIsTruncated(read_string.second);
1412 if (custom_format == eFormatVectorOfChar) {
1413 options.SetZeroTermination(
1415 } else {
1416 options.SetZeroTermination(
1418 }
1420 lldb_private::formatters::StringPrinter::StringElementType::ASCII>(
1421 options);
1422 return !error.Fail();
1423 }
1424
1425 if (custom_format == eFormatEnum)
1426 return false;
1427
1428 // this only works for arrays, because I have no way to know when the
1429 // pointed memory ends, and no special \0 end of data marker
1430 if (flags.Test(eTypeIsArray)) {
1431 if ((custom_format == eFormatBytes) ||
1432 (custom_format == eFormatBytesWithASCII)) {
1433 const size_t count = GetNumChildrenIgnoringErrors();
1434
1435 s << '[';
1436 for (size_t low = 0; low < count; low++) {
1437
1438 if (low)
1439 s << ',';
1440
1441 ValueObjectSP child = GetChildAtIndex(low);
1442 if (!child.get()) {
1443 s << "<invalid child>";
1444 continue;
1445 }
1446 child->DumpPrintableRepresentation(
1448 custom_format);
1449 }
1450
1451 s << ']';
1452
1453 return true;
1454 }
1455
1456 if ((custom_format == eFormatVectorOfChar) ||
1457 (custom_format == eFormatVectorOfFloat32) ||
1458 (custom_format == eFormatVectorOfFloat64) ||
1459 (custom_format == eFormatVectorOfSInt16) ||
1460 (custom_format == eFormatVectorOfSInt32) ||
1461 (custom_format == eFormatVectorOfSInt64) ||
1462 (custom_format == eFormatVectorOfSInt8) ||
1463 (custom_format == eFormatVectorOfUInt128) ||
1464 (custom_format == eFormatVectorOfUInt16) ||
1465 (custom_format == eFormatVectorOfUInt32) ||
1466 (custom_format == eFormatVectorOfUInt64) ||
1467 (custom_format == eFormatVectorOfUInt8)) // arrays of bytes, bytes
1468 // with ASCII or any vector
1469 // format should be printed
1470 // directly
1471 {
1472 const size_t count = GetNumChildrenIgnoringErrors();
1473
1474 Format format = FormatManager::GetSingleItemFormat(custom_format);
1475
1476 s << '[';
1477 for (size_t low = 0; low < count; low++) {
1478
1479 if (low)
1480 s << ',';
1481
1482 ValueObjectSP child = GetChildAtIndex(low);
1483 if (!child.get()) {
1484 s << "<invalid child>";
1485 continue;
1486 }
1487 child->DumpPrintableRepresentation(
1489 }
1490
1491 s << ']';
1492
1493 return true;
1494 }
1495 }
1496
1497 if ((custom_format == eFormatBoolean) ||
1498 (custom_format == eFormatBinary) || (custom_format == eFormatChar) ||
1499 (custom_format == eFormatCharPrintable) ||
1500 (custom_format == eFormatComplexFloat) ||
1501 (custom_format == eFormatDecimal) || (custom_format == eFormatHex) ||
1502 (custom_format == eFormatHexUppercase) ||
1503 (custom_format == eFormatFloat) ||
1504 (custom_format == eFormatFloat128) ||
1505 (custom_format == eFormatOctal) || (custom_format == eFormatOSType) ||
1506 (custom_format == eFormatUnicode16) ||
1507 (custom_format == eFormatUnicode32) ||
1508 (custom_format == eFormatUnsigned) ||
1509 (custom_format == eFormatPointer) ||
1510 (custom_format == eFormatComplexInteger) ||
1511 (custom_format == eFormatComplex) ||
1512 (custom_format == eFormatDefault)) // use the [] operator
1513 return false;
1514 }
1515 }
1516
1517 if (only_special)
1518 return false;
1519
1520 bool var_success = false;
1521
1522 {
1523 llvm::StringRef str;
1524
1525 // this is a local stream that we are using to ensure that the data pointed
1526 // to by cstr survives long enough for us to copy it to its destination -
1527 // it is necessary to have this temporary storage area for cases where our
1528 // desired output is not backed by some other longer-term storage
1529 StreamString strm;
1530
1531 if (custom_format != eFormatInvalid)
1532 SetFormat(custom_format);
1533
1534 switch (val_obj_display) {
1536 str = GetValueAsCString();
1537 break;
1538
1540 str = GetSummaryAsCString();
1541 break;
1542
1544 llvm::Expected<std::string> desc = GetObjectDescription();
1545 if (!desc) {
1546 strm << "error: " << toString(desc.takeError());
1547 str = strm.GetString();
1548 } else {
1549 strm << *desc;
1550 str = strm.GetString();
1551 }
1552 } break;
1553
1555 str = GetLocationAsCString();
1556 break;
1557
1559 if (auto err = GetNumChildren()) {
1560 strm.Printf("%" PRIu32, *err);
1561 str = strm.GetString();
1562 } else {
1563 strm << "error: " << toString(err.takeError());
1564 str = strm.GetString();
1565 }
1566 break;
1567 }
1568
1570 str = GetTypeName().GetStringRef();
1571 break;
1572
1574 str = GetName().GetStringRef();
1575 break;
1576
1578 GetExpressionPath(strm);
1579 str = strm.GetString();
1580 break;
1581 }
1582
1583 // If the requested display style produced no output, try falling back to
1584 // alternative presentations.
1585 if (str.empty()) {
1586 if (val_obj_display == eValueObjectRepresentationStyleValue)
1587 str = GetSummaryAsCString();
1588 else if (val_obj_display == eValueObjectRepresentationStyleSummary) {
1589 if (!CanProvideValue()) {
1590 strm.Format("{0} @ {1}", GetTypeName(), GetLocationAsCString());
1591 str = strm.GetString();
1592 } else
1593 str = GetValueAsCString();
1594 }
1595 }
1596
1597 if (!str.empty())
1598 s << str;
1599 else {
1600 // We checked for errors at the start, but do it again here in case
1601 // realizing the value for dumping produced an error.
1602 if (m_error.Fail()) {
1603 if (do_dump_error)
1604 s.Printf("<%s>", m_error.AsCString());
1605 else
1606 return false;
1607 } else if (val_obj_display == eValueObjectRepresentationStyleSummary)
1608 s.PutCString("<no summary available>");
1609 else if (val_obj_display == eValueObjectRepresentationStyleValue)
1610 s.PutCString("<no value available>");
1611 else if (val_obj_display ==
1613 s.PutCString("<not a valid Objective-C object>"); // edit this if we
1614 // have other runtimes
1615 // that support a
1616 // description
1617 else
1618 s.PutCString("<no printable representation>");
1619 }
1620
1621 // we should only return false here if we could not do *anything* even if
1622 // we have an error message as output, that's a success from our callers'
1623 // perspective, so return true
1624 var_success = true;
1625
1626 if (custom_format != eFormatInvalid)
1628 }
1629
1630 return var_success;
1631}
1632
1634ValueObject::GetAddressOf(bool scalar_is_load_address) {
1635 // Can't take address of a bitfield
1636 if (IsBitfield())
1637 return {};
1638
1639 if (!UpdateValueIfNeeded(false))
1640 return {};
1641
1642 switch (m_value.GetValueType()) {
1644 return {};
1646 if (scalar_is_load_address) {
1647 return {m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS),
1649 }
1650 return {};
1651
1654 return {m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS),
1655 m_value.GetValueAddressType()};
1657 return {LLDB_INVALID_ADDRESS, m_value.GetValueAddressType()};
1658 }
1659 llvm_unreachable("Unhandled value type!");
1660}
1661
1662std::optional<addr_t> ValueObject::GetStrippedPointerValue(addr_t address) {
1663 if (GetCompilerType().HasPointerAuthQualifier()) {
1665 if (Process *process = exe_ctx.GetProcessPtr())
1666 if (ABISP abi_sp = process->GetABI())
1667 return abi_sp->FixCodeAddress(address);
1668 }
1669 return std::nullopt;
1670}
1671
1673 if (!UpdateValueIfNeeded(false))
1674 return {};
1675
1676 switch (m_value.GetValueType()) {
1678 return {};
1680 return {m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS),
1682
1686 lldb::offset_t data_offset = 0;
1687 return {m_data.GetAddress(&data_offset), GetAddressTypeOfChildren()};
1688 }
1689 }
1690
1691 llvm_unreachable("Unhandled value type!");
1692}
1693
1694static const char *ConvertBoolean(lldb::LanguageType language_type,
1695 const char *value_str) {
1696 if (Language *language = Language::FindPlugin(language_type))
1697 if (auto boolean = language->GetBooleanFromString(value_str))
1698 return *boolean ? "1" : "0";
1699
1700 return llvm::StringSwitch<const char *>(value_str)
1701 .Case("true", "1")
1702 .Case("false", "0")
1703 .Default(value_str);
1704}
1705
1706bool ValueObject::SetValueFromCString(const char *value_str, Status &error) {
1707 error.Clear();
1708 // Make sure our value is up to date first so that our location and location
1709 // type is valid.
1710 if (!UpdateValueIfNeeded(false)) {
1711 error = Status::FromErrorString("unable to read value");
1712 return false;
1713 }
1714
1715 const Encoding encoding = GetCompilerType().GetEncoding();
1716
1717 const size_t byte_size = llvm::expectedToOptional(GetByteSize()).value_or(0);
1718
1719 Value::ValueType value_type = m_value.GetValueType();
1720
1721 if (value_type == Value::ValueType::Scalar) {
1722 // If the value is already a scalar, then let the scalar change itself:
1723 m_value.GetScalar().SetValueFromCString(value_str, encoding, byte_size);
1724 } else if (byte_size <= 16) {
1725 if (GetCompilerType().IsBoolean())
1726 value_str = ConvertBoolean(GetObjectRuntimeLanguage(), value_str);
1727
1728 // If the value fits in a scalar, then make a new scalar and again let the
1729 // scalar code do the conversion, then figure out where to put the new
1730 // value.
1731 Scalar new_scalar;
1732 error = new_scalar.SetValueFromCString(value_str, encoding, byte_size);
1733 if (error.Success()) {
1734 switch (value_type) {
1736 // If it is a load address, then the scalar value is the storage
1737 // location of the data, and we have to shove this value down to that
1738 // load location.
1740 Process *process = exe_ctx.GetProcessPtr();
1741 if (process) {
1742 addr_t target_addr =
1743 m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
1744 size_t bytes_written = process->WriteScalarToMemory(
1745 target_addr, new_scalar, byte_size, error);
1746 if (!error.Success())
1747 return false;
1748 if (bytes_written != byte_size) {
1749 error = Status::FromErrorString("unable to write value to memory");
1750 return false;
1751 }
1752 }
1753 } break;
1755 // If it is a host address, then we stuff the scalar as a DataBuffer
1756 // into the Value's data.
1757 DataExtractor new_data;
1758 new_data.SetByteOrder(m_data.GetByteOrder());
1759
1760 DataBufferSP buffer_sp(new DataBufferHeap(byte_size, 0));
1761 m_data.SetData(buffer_sp, 0);
1762 bool success = new_scalar.GetData(new_data);
1763 if (success) {
1764 new_data.CopyByteOrderedData(
1765 0, byte_size, const_cast<uint8_t *>(m_data.GetDataStart()),
1766 byte_size, m_data.GetByteOrder());
1767 }
1768 m_value.GetScalar() = (uintptr_t)m_data.GetDataStart();
1769
1770 } break;
1772 error = Status::FromErrorString("invalid location");
1773 return false;
1776 break;
1777 }
1778 } else {
1779 return false;
1780 }
1781 } else {
1782 // We don't support setting things bigger than a scalar at present.
1783 error = Status::FromErrorString("unable to write aggregate data type");
1784 return false;
1785 }
1786
1787 // If we have reached this point, then we have successfully changed the
1788 // value.
1790 return true;
1791}
1792
1794 decl.Clear();
1795 return false;
1796}
1797
1801
1803 ValueObjectSP synthetic_child_sp;
1804 std::map<ConstString, ValueObject *>::const_iterator pos =
1805 m_synthetic_children.find(key);
1806 if (pos != m_synthetic_children.end())
1807 synthetic_child_sp = pos->second->GetSP();
1808 return synthetic_child_sp;
1809}
1810
1813 Process *process = exe_ctx.GetProcessPtr();
1814 if (process)
1815 return process->IsPossibleDynamicValue(*this);
1816 else
1817 return GetCompilerType().IsPossibleDynamicType(nullptr, true, true);
1818}
1819
1821 Process *process(GetProcessSP().get());
1822 if (!process)
1823 return false;
1824
1825 // We trust that the compiler did the right thing and marked runtime support
1826 // values as artificial.
1827 if (!GetVariable() || !GetVariable()->IsArtificial())
1828 return false;
1829
1830 if (auto *runtime = process->GetLanguageRuntime(GetVariable()->GetLanguage()))
1831 if (runtime->IsAllowedRuntimeValue(GetName()))
1832 return false;
1833
1834 return true;
1835}
1836
1839 return language->IsNilReference(*this);
1840 }
1841 return false;
1842}
1843
1846 return language->IsUninitializedReference(*this);
1847 }
1848 return false;
1849}
1850
1851// This allows you to create an array member using and index that doesn't not
1852// fall in the normal bounds of the array. Many times structure can be defined
1853// as: struct Collection {
1854// uint32_t item_count;
1855// Item item_array[0];
1856// };
1857// The size of the "item_array" is 1, but many times in practice there are more
1858// items in "item_array".
1859
1861 bool can_create) {
1862 ValueObjectSP synthetic_child_sp;
1863 if (IsPointerType() || IsArrayType()) {
1864 std::string index_str = llvm::formatv("[{0}]", index);
1865 ConstString index_const_str(index_str);
1866 // Check if we have already created a synthetic array member in this valid
1867 // object. If we have we will re-use it.
1868 synthetic_child_sp = GetSyntheticChild(index_const_str);
1869 if (!synthetic_child_sp) {
1870 ValueObject *synthetic_child;
1871 // We haven't made a synthetic array member for INDEX yet, so lets make
1872 // one and cache it for any future reference.
1873 synthetic_child = CreateSyntheticArrayMember(index);
1874
1875 // Cache the value if we got one back...
1876 if (synthetic_child) {
1877 AddSyntheticChild(index_const_str, synthetic_child);
1878 synthetic_child_sp = synthetic_child->GetSP();
1879 synthetic_child_sp->SetName(ConstString(index_str));
1880 synthetic_child_sp->m_flags.m_is_array_item_for_pointer = true;
1881 }
1882 }
1883 }
1884 return synthetic_child_sp;
1885}
1886
1888 bool can_create) {
1889 ValueObjectSP synthetic_child_sp;
1890 if (IsScalarType()) {
1891 std::string index_str = llvm::formatv("[{0}-{1}]", from, to);
1892 ConstString index_const_str(index_str);
1893 // Check if we have already created a synthetic array member in this valid
1894 // object. If we have we will re-use it.
1895 synthetic_child_sp = GetSyntheticChild(index_const_str);
1896 if (!synthetic_child_sp) {
1897 uint32_t bit_field_size = to - from + 1;
1898 uint32_t bit_field_offset = from;
1899 if (GetDataExtractor().GetByteOrder() == eByteOrderBig)
1900 bit_field_offset =
1901 llvm::expectedToOptional(GetByteSize()).value_or(0) * 8 -
1902 bit_field_size - bit_field_offset;
1903 // We haven't made a synthetic array member for INDEX yet, so lets make
1904 // one and cache it for any future reference.
1905 ValueObjectChild *synthetic_child = new ValueObjectChild(
1906 *this, GetCompilerType(), index_const_str,
1907 llvm::expectedToOptional(GetByteSize()).value_or(0), 0,
1908 bit_field_size, bit_field_offset, false, false, eAddressTypeInvalid,
1909 0);
1910
1911 // Cache the value if we got one back...
1912 if (synthetic_child) {
1913 AddSyntheticChild(index_const_str, synthetic_child);
1914 synthetic_child_sp = synthetic_child->GetSP();
1915 synthetic_child_sp->SetName(ConstString(index_str));
1916 synthetic_child_sp->m_flags.m_is_bitfield_for_scalar = true;
1917 }
1918 }
1919 }
1920 return synthetic_child_sp;
1921}
1922
1924 uint32_t offset, const CompilerType &type, bool can_create,
1925 ConstString name_const_str) {
1926
1927 ValueObjectSP synthetic_child_sp;
1928
1929 if (name_const_str.IsEmpty()) {
1930 name_const_str.SetString("@" + std::to_string(offset));
1931 }
1932
1933 // Check if we have already created a synthetic array member in this valid
1934 // object. If we have we will re-use it.
1935 synthetic_child_sp = GetSyntheticChild(name_const_str);
1936
1937 if (synthetic_child_sp.get())
1938 return synthetic_child_sp;
1939
1940 if (!can_create)
1941 return {};
1942
1944 std::optional<uint64_t> size = llvm::expectedToOptional(
1946 if (!size)
1947 return {};
1948 ValueObjectChild *synthetic_child =
1949 new ValueObjectChild(*this, type, name_const_str, *size, offset, 0, 0,
1950 false, false, eAddressTypeInvalid, 0);
1951 if (synthetic_child) {
1952 AddSyntheticChild(name_const_str, synthetic_child);
1953 synthetic_child_sp = synthetic_child->GetSP();
1954 synthetic_child_sp->SetName(name_const_str);
1955 synthetic_child_sp->m_flags.m_is_child_at_offset = true;
1956 }
1957 return synthetic_child_sp;
1958}
1959
1961 const CompilerType &type,
1962 bool can_create,
1963 ConstString name_const_str) {
1964 ValueObjectSP synthetic_child_sp;
1965
1966 if (name_const_str.IsEmpty()) {
1967 char name_str[128];
1968 snprintf(name_str, sizeof(name_str), "base%s@%i",
1969 type.GetTypeName().AsCString("<unknown>"), offset);
1970 name_const_str.SetCString(name_str);
1971 }
1972
1973 // Check if we have already created a synthetic array member in this valid
1974 // object. If we have we will re-use it.
1975 synthetic_child_sp = GetSyntheticChild(name_const_str);
1976
1977 if (synthetic_child_sp.get())
1978 return synthetic_child_sp;
1979
1980 if (!can_create)
1981 return {};
1982
1983 const bool is_base_class = true;
1984
1986 std::optional<uint64_t> size = llvm::expectedToOptional(
1988 if (!size)
1989 return {};
1990 ValueObjectChild *synthetic_child =
1991 new ValueObjectChild(*this, type, name_const_str, *size, offset, 0, 0,
1992 is_base_class, false, eAddressTypeInvalid, 0);
1993 if (synthetic_child) {
1994 AddSyntheticChild(name_const_str, synthetic_child);
1995 synthetic_child_sp = synthetic_child->GetSP();
1996 synthetic_child_sp->SetName(name_const_str);
1997 }
1998 return synthetic_child_sp;
1999}
2000
2001// your expression path needs to have a leading . or -> (unless it somehow
2002// "looks like" an array, in which case it has a leading [ symbol). while the [
2003// is meaningful and should be shown to the user, . and -> are just parser
2004// design, but by no means added information for the user.. strip them off
2005static const char *SkipLeadingExpressionPathSeparators(const char *expression) {
2006 if (!expression || !expression[0])
2007 return expression;
2008 if (expression[0] == '.')
2009 return expression + 1;
2010 if (expression[0] == '-' && expression[1] == '>')
2011 return expression + 2;
2012 return expression;
2013}
2014
2017 bool can_create) {
2018 ValueObjectSP synthetic_child_sp;
2019 ConstString name_const_string(expression);
2020 // Check if we have already created a synthetic array member in this valid
2021 // object. If we have we will re-use it.
2022 synthetic_child_sp = GetSyntheticChild(name_const_string);
2023 if (!synthetic_child_sp) {
2024 // We haven't made a synthetic array member for expression yet, so lets
2025 // make one and cache it for any future reference.
2026 synthetic_child_sp = GetValueForExpressionPath(
2027 expression, nullptr, nullptr,
2028 GetValueForExpressionPathOptions().SetSyntheticChildrenTraversal(
2030 None));
2031
2032 // Cache the value if we got one back...
2033 if (synthetic_child_sp.get()) {
2034 // FIXME: this causes a "real" child to end up with its name changed to
2035 // the contents of expression
2036 AddSyntheticChild(name_const_string, synthetic_child_sp.get());
2037 synthetic_child_sp->SetName(
2039 }
2040 }
2041 return synthetic_child_sp;
2042}
2043
2045 TargetSP target_sp(GetTargetSP());
2046 if (target_sp && !target_sp->GetEnableSyntheticValue()) {
2047 m_synthetic_value = nullptr;
2048 return;
2049 }
2050
2052
2054 return;
2055
2056 if (m_synthetic_children_sp.get() == nullptr)
2057 return;
2058
2059 if (current_synth_sp == m_synthetic_children_sp && m_synthetic_value)
2060 return;
2061
2063}
2064
2066 if (use_dynamic == eNoDynamicValues)
2067 return;
2068
2069 if (!m_dynamic_value && !IsDynamic()) {
2071 Process *process = exe_ctx.GetProcessPtr();
2072 if (process && process->IsPossibleDynamicValue(*this)) {
2074 m_dynamic_value = new ValueObjectDynamicValue(*this, use_dynamic);
2075 }
2076 }
2077}
2078
2080 if (use_dynamic == eNoDynamicValues)
2081 return ValueObjectSP();
2082
2083 if (!IsDynamic() && m_dynamic_value == nullptr) {
2084 CalculateDynamicValue(use_dynamic);
2085 }
2086 if (m_dynamic_value && m_dynamic_value->GetError().Success())
2087 return m_dynamic_value->GetSP();
2088 else
2089 return ValueObjectSP();
2090}
2091
2094
2096 return m_synthetic_value->GetSP();
2097 else
2098 return ValueObjectSP();
2099}
2100
2103
2104 if (m_synthetic_children_sp.get() == nullptr)
2105 return false;
2106
2108
2109 return m_synthetic_value != nullptr;
2110}
2111
2113 if (GetParent()) {
2114 if (GetParent()->IsBaseClass())
2115 return GetParent()->GetNonBaseClassParent();
2116 else
2117 return GetParent();
2118 }
2119 return nullptr;
2120}
2121
2123 GetExpressionPathFormat epformat) {
2124 // synthetic children do not actually "exist" as part of the hierarchy, and
2125 // sometimes they are consed up in ways that don't make sense from an
2126 // underlying language/API standpoint. So, use a special code path here to
2127 // return something that can hopefully be used in expression
2128 if (m_flags.m_is_synthetic_children_generated) {
2130
2131 if (m_value.GetValueType() == Value::ValueType::LoadAddress) {
2133 s.Printf("((%s)0x%" PRIx64 ")", GetTypeName().AsCString("void"),
2135 return;
2136 } else {
2137 uint64_t load_addr =
2138 m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
2139 if (load_addr != LLDB_INVALID_ADDRESS) {
2140 s.Printf("(*( (%s *)0x%" PRIx64 "))", GetTypeName().AsCString("void"),
2141 load_addr);
2142 return;
2143 }
2144 }
2145 }
2146
2147 if (CanProvideValue()) {
2148 s.Printf("((%s)%s)", GetTypeName().AsCString("void"),
2150 return;
2151 }
2152
2153 return;
2154 }
2155
2156 const bool is_deref_of_parent = IsDereferenceOfParent();
2157
2158 if (is_deref_of_parent &&
2160 // this is the original format of GetExpressionPath() producing code like
2161 // *(a_ptr).memberName, which is entirely fine, until you put this into
2162 // StackFrame::GetValueForVariableExpressionPath() which prefers to see
2163 // a_ptr->memberName. the eHonorPointers mode is meant to produce strings
2164 // in this latter format
2165 s.PutCString("*(");
2166 }
2167
2168 ValueObject *parent = GetParent();
2169
2170 if (parent) {
2171 parent->GetExpressionPath(s, epformat);
2172 const CompilerType parentType = parent->GetCompilerType();
2173 if (parentType.IsPointerType() &&
2174 parentType.GetPointeeType().IsArrayType(nullptr, nullptr, nullptr)) {
2175 // When the parent is a pointer to an array, then we have to:
2176 // - follow the expression path of the parent with "[0]"
2177 // (that will indicate dereferencing the pointer to the array)
2178 // - and then follow that with this ValueObject's name
2179 // (which will be something like "[i]" to indicate
2180 // the i-th element of the array)
2181 s.PutCString("[0]");
2182 s.PutCString(GetName().GetCString());
2183 return;
2184 }
2185 }
2186
2187 // if we are a deref_of_parent just because we are synthetic array members
2188 // made up to allow ptr[%d] syntax to work in variable printing, then add our
2189 // name ([%d]) to the expression path
2190 if (m_flags.m_is_array_item_for_pointer &&
2192 s.PutCString(m_name.GetStringRef());
2193
2194 if (!IsBaseClass()) {
2195 if (!is_deref_of_parent) {
2196 ValueObject *non_base_class_parent = GetNonBaseClassParent();
2197 if (non_base_class_parent &&
2198 !non_base_class_parent->GetName().IsEmpty()) {
2199 CompilerType non_base_class_parent_compiler_type =
2200 non_base_class_parent->GetCompilerType();
2201 if (non_base_class_parent_compiler_type) {
2202 if (parent && parent->IsDereferenceOfParent() &&
2204 s.PutCString("->");
2205 } else {
2206 const uint32_t non_base_class_parent_type_info =
2207 non_base_class_parent_compiler_type.GetTypeInfo();
2208
2209 if (non_base_class_parent_type_info & eTypeIsPointer) {
2210 s.PutCString("->");
2211 } else if ((non_base_class_parent_type_info & eTypeHasChildren) &&
2212 !(non_base_class_parent_type_info & eTypeIsArray)) {
2213 s.PutChar('.');
2214 }
2215 }
2216 }
2217 }
2218
2219 const char *name = GetName().GetCString();
2220 if (name)
2221 s.PutCString(name);
2222 }
2223 }
2224
2225 if (is_deref_of_parent &&
2227 s.PutChar(')');
2228 }
2229}
2230
2231// Return the alternate value (synthetic if the input object is non-synthetic
2232// and otherwise) this is permitted by the expression path options.
2234 ValueObject &valobj,
2236 synth_traversal) {
2237 using SynthTraversal =
2239
2240 if (valobj.IsSynthetic()) {
2241 if (synth_traversal == SynthTraversal::FromSynthetic ||
2242 synth_traversal == SynthTraversal::Both)
2243 return valobj.GetNonSyntheticValue();
2244 } else {
2245 if (synth_traversal == SynthTraversal::ToSynthetic ||
2246 synth_traversal == SynthTraversal::Both)
2247 return valobj.GetSyntheticValue();
2248 }
2249 return nullptr;
2250}
2251
2252// Dereference the provided object or the alternate value, if permitted by the
2253// expression path options.
2255 ValueObject &valobj,
2257 synth_traversal,
2258 Status &error) {
2259 error.Clear();
2260 ValueObjectSP result = valobj.Dereference(error);
2261 if (!result || error.Fail()) {
2262 if (ValueObjectSP alt_obj = GetAlternateValue(valobj, synth_traversal)) {
2263 error.Clear();
2264 result = alt_obj->Dereference(error);
2265 }
2266 }
2267 return result;
2268}
2269
2271 llvm::StringRef expression, ExpressionPathScanEndReason *reason_to_stop,
2272 ExpressionPathEndResultType *final_value_type,
2273 const GetValueForExpressionPathOptions &options,
2274 ExpressionPathAftermath *final_task_on_target) {
2275
2276 ExpressionPathScanEndReason dummy_reason_to_stop =
2278 ExpressionPathEndResultType dummy_final_value_type =
2280 ExpressionPathAftermath dummy_final_task_on_target =
2282
2284 expression, reason_to_stop ? reason_to_stop : &dummy_reason_to_stop,
2285 final_value_type ? final_value_type : &dummy_final_value_type, options,
2286 final_task_on_target ? final_task_on_target
2287 : &dummy_final_task_on_target);
2288
2289 if (!final_task_on_target ||
2290 *final_task_on_target == ValueObject::eExpressionPathAftermathNothing)
2291 return ret_val;
2292
2293 if (ret_val.get() &&
2294 ((final_value_type ? *final_value_type : dummy_final_value_type) ==
2295 eExpressionPathEndResultTypePlain)) // I can only deref and takeaddress
2296 // of plain objects
2297 {
2298 if ((final_task_on_target ? *final_task_on_target
2299 : dummy_final_task_on_target) ==
2301 Status error;
2303 *ret_val, options.m_synthetic_children_traversal, error);
2304 if (error.Fail() || !final_value.get()) {
2305 if (reason_to_stop)
2306 *reason_to_stop =
2308 if (final_value_type)
2310 return ValueObjectSP();
2311 } else {
2312 if (final_task_on_target)
2313 *final_task_on_target = ValueObject::eExpressionPathAftermathNothing;
2314 return final_value;
2315 }
2316 }
2317 if (*final_task_on_target ==
2319 Status error;
2320 ValueObjectSP final_value = ret_val->AddressOf(error);
2321 if (error.Fail() || !final_value.get()) {
2322 if (reason_to_stop)
2323 *reason_to_stop =
2325 if (final_value_type)
2327 return ValueObjectSP();
2328 } else {
2329 if (final_task_on_target)
2330 *final_task_on_target = ValueObject::eExpressionPathAftermathNothing;
2331 return final_value;
2332 }
2333 }
2334 }
2335 return ret_val; // final_task_on_target will still have its original value, so
2336 // you know I did not do it
2337}
2338
2340 llvm::StringRef expression, ExpressionPathScanEndReason *reason_to_stop,
2341 ExpressionPathEndResultType *final_result,
2342 const GetValueForExpressionPathOptions &options,
2343 ExpressionPathAftermath *what_next) {
2344 ValueObjectSP root = GetSP();
2345
2346 if (!root)
2347 return nullptr;
2348
2349 llvm::StringRef remainder = expression;
2350
2351 while (true) {
2352 llvm::StringRef temp_expression = remainder;
2353
2354 CompilerType root_compiler_type = root->GetCompilerType();
2355 CompilerType pointee_compiler_type;
2356 Flags pointee_compiler_type_info;
2357
2358 Flags root_compiler_type_info(
2359 root_compiler_type.GetTypeInfo(&pointee_compiler_type));
2360 if (pointee_compiler_type)
2361 pointee_compiler_type_info.Reset(pointee_compiler_type.GetTypeInfo());
2362
2363 if (temp_expression.empty()) {
2365 return root;
2366 }
2367
2368 switch (temp_expression.front()) {
2369 case '-': {
2370 temp_expression = temp_expression.drop_front();
2371 if (options.m_check_dot_vs_arrow_syntax &&
2372 root_compiler_type_info.Test(eTypeIsPointer)) // if you are trying to
2373 // use -> on a
2374 // non-pointer and I
2375 // must catch the error
2376 {
2377 *reason_to_stop =
2380 return ValueObjectSP();
2381 }
2382 if (root_compiler_type_info.Test(eTypeIsObjC) && // if yo are trying to
2383 // extract an ObjC IVar
2384 // when this is forbidden
2385 root_compiler_type_info.Test(eTypeIsPointer) &&
2386 options.m_no_fragile_ivar) {
2387 *reason_to_stop =
2390 return ValueObjectSP();
2391 }
2392 if (!temp_expression.starts_with(">")) {
2393 *reason_to_stop =
2396 return ValueObjectSP();
2397 }
2398 }
2399 [[fallthrough]];
2400 case '.': // or fallthrough from ->
2401 {
2402 if (options.m_check_dot_vs_arrow_syntax &&
2403 temp_expression.front() == '.' &&
2404 root_compiler_type_info.Test(eTypeIsPointer)) // if you are trying to
2405 // use . on a pointer
2406 // and I must catch the
2407 // error
2408 {
2409 *reason_to_stop =
2412 return nullptr;
2413 }
2414 temp_expression = temp_expression.drop_front(); // skip . or >
2415
2416 size_t next_sep_pos = temp_expression.find_first_of("-.[", 1);
2417 if (next_sep_pos == llvm::StringRef::npos) {
2418 // if no other separator just expand this last layer
2419 llvm::StringRef child_name = temp_expression;
2420 ValueObjectSP child_valobj_sp =
2421 root->GetChildMemberWithName(child_name);
2422 if (!child_valobj_sp) {
2423 if (ValueObjectSP altroot = GetAlternateValue(
2424 *root, options.m_synthetic_children_traversal))
2425 child_valobj_sp = altroot->GetChildMemberWithName(child_name);
2426 }
2427 if (child_valobj_sp) {
2428 *reason_to_stop =
2431 return child_valobj_sp;
2432 }
2435 return nullptr;
2436 }
2437
2438 llvm::StringRef next_separator = temp_expression.substr(next_sep_pos);
2439 llvm::StringRef child_name = temp_expression.slice(0, next_sep_pos);
2440
2441 ValueObjectSP child_valobj_sp = root->GetChildMemberWithName(child_name);
2442 if (!child_valobj_sp) {
2443 if (ValueObjectSP altroot = GetAlternateValue(
2444 *root, options.m_synthetic_children_traversal))
2445 child_valobj_sp = altroot->GetChildMemberWithName(child_name);
2446 }
2447 if (child_valobj_sp) {
2448 root = child_valobj_sp;
2449 remainder = next_separator;
2451 continue;
2452 }
2455 return nullptr;
2456 }
2457 case '[': {
2458 if (!root_compiler_type_info.Test(eTypeIsArray) &&
2459 !root_compiler_type_info.Test(eTypeIsPointer) &&
2460 !root_compiler_type_info.Test(
2461 eTypeIsVector)) // if this is not a T[] nor a T*
2462 {
2463 if (!root_compiler_type_info.Test(
2464 eTypeIsScalar)) // if this is not even a scalar...
2465 {
2466 if (options.m_synthetic_children_traversal ==
2468 None) // ...only chance left is synthetic
2469 {
2470 *reason_to_stop =
2473 return ValueObjectSP();
2474 }
2475 } else if (!options.m_allow_bitfields_syntax) // if this is a scalar,
2476 // check that we can
2477 // expand bitfields
2478 {
2479 *reason_to_stop =
2482 return ValueObjectSP();
2483 }
2484 }
2485 if (temp_expression[1] ==
2486 ']') // if this is an unbounded range it only works for arrays
2487 {
2488 if (!root_compiler_type_info.Test(eTypeIsArray)) {
2489 *reason_to_stop =
2492 return nullptr;
2493 } else // even if something follows, we cannot expand unbounded ranges,
2494 // just let the caller do it
2495 {
2496 *reason_to_stop =
2498 *final_result =
2500 return root;
2501 }
2502 }
2503
2504 size_t close_bracket_position = temp_expression.find(']', 1);
2505 if (close_bracket_position ==
2506 llvm::StringRef::npos) // if there is no ], this is a syntax error
2507 {
2508 *reason_to_stop =
2511 return nullptr;
2512 }
2513
2514 llvm::StringRef bracket_expr =
2515 temp_expression.slice(1, close_bracket_position);
2516
2517 // If this was an empty expression it would have been caught by the if
2518 // above.
2519 assert(!bracket_expr.empty());
2520
2521 if (!bracket_expr.contains('-')) {
2522 // if no separator, this is of the form [N]. Note that this cannot be
2523 // an unbounded range of the form [], because that case was handled
2524 // above with an unconditional return.
2525 unsigned long index = 0;
2526 if (bracket_expr.getAsInteger(0, index)) {
2527 *reason_to_stop =
2530 return nullptr;
2531 }
2532
2533 // from here on we do have a valid index
2534 if (root_compiler_type_info.Test(eTypeIsArray)) {
2535 ValueObjectSP child_valobj_sp = root->GetChildAtIndex(index);
2536 if (!child_valobj_sp)
2537 child_valobj_sp = root->GetSyntheticArrayMember(index, true);
2538 if (!child_valobj_sp)
2539 if (root->HasSyntheticValue() &&
2540 llvm::expectedToOptional(
2541 root->GetSyntheticValue()->GetNumChildren())
2542 .value_or(0) > index)
2543 child_valobj_sp =
2544 root->GetSyntheticValue()->GetChildAtIndex(index);
2545 if (child_valobj_sp) {
2546 root = child_valobj_sp;
2547 remainder =
2548 temp_expression.substr(close_bracket_position + 1); // skip ]
2550 continue;
2551 } else {
2552 *reason_to_stop =
2555 return nullptr;
2556 }
2557 } else if (root_compiler_type_info.Test(eTypeIsPointer)) {
2558 if (*what_next ==
2559 ValueObject::
2560 eExpressionPathAftermathDereference && // if this is a
2561 // ptr-to-scalar, I
2562 // am accessing it
2563 // by index and I
2564 // would have
2565 // deref'ed anyway,
2566 // then do it now
2567 // and use this as
2568 // a bitfield
2569 pointee_compiler_type_info.Test(eTypeIsScalar)) {
2570 Status error;
2572 *root, options.m_synthetic_children_traversal, error);
2573 if (error.Fail() || !root) {
2574 *reason_to_stop =
2577 return nullptr;
2578 } else {
2580 continue;
2581 }
2582 } else {
2583 if (root->GetCompilerType().GetMinimumLanguage() ==
2585 pointee_compiler_type_info.AllClear(eTypeIsPointer) &&
2586 root->HasSyntheticValue() &&
2589 SyntheticChildrenTraversal::ToSynthetic ||
2592 SyntheticChildrenTraversal::Both)) {
2593 root = root->GetSyntheticValue()->GetChildAtIndex(index);
2594 } else
2595 root = root->GetSyntheticArrayMember(index, true);
2596 if (!root) {
2597 *reason_to_stop =
2600 return nullptr;
2601 } else {
2602 remainder =
2603 temp_expression.substr(close_bracket_position + 1); // skip ]
2605 continue;
2606 }
2607 }
2608 } else if (root_compiler_type_info.Test(eTypeIsScalar)) {
2609 root = root->GetSyntheticBitFieldChild(index, index, true);
2610 if (!root) {
2611 *reason_to_stop =
2614 return nullptr;
2615 } else // we do not know how to expand members of bitfields, so we
2616 // just return and let the caller do any further processing
2617 {
2618 *reason_to_stop = ValueObject::
2619 eExpressionPathScanEndReasonBitfieldRangeOperatorMet;
2621 return root;
2622 }
2623 } else if (root_compiler_type_info.Test(eTypeIsVector)) {
2624 root = root->GetChildAtIndex(index);
2625 if (!root) {
2626 *reason_to_stop =
2629 return ValueObjectSP();
2630 } else {
2631 remainder =
2632 temp_expression.substr(close_bracket_position + 1); // skip ]
2634 continue;
2635 }
2636 } else if (options.m_synthetic_children_traversal ==
2638 SyntheticChildrenTraversal::ToSynthetic ||
2641 SyntheticChildrenTraversal::Both) {
2642 if (root->HasSyntheticValue())
2643 root = root->GetSyntheticValue();
2644 else if (!root->IsSynthetic()) {
2645 *reason_to_stop =
2648 return nullptr;
2649 }
2650 // if we are here, then root itself is a synthetic VO.. should be
2651 // good to go
2652
2653 if (!root) {
2654 *reason_to_stop =
2657 return nullptr;
2658 }
2659 root = root->GetChildAtIndex(index);
2660 if (!root) {
2661 *reason_to_stop =
2664 return nullptr;
2665 } else {
2666 remainder =
2667 temp_expression.substr(close_bracket_position + 1); // skip ]
2669 continue;
2670 }
2671 } else {
2672 *reason_to_stop =
2675 return nullptr;
2676 }
2677 } else {
2678 // we have a low and a high index
2679 llvm::StringRef sleft, sright;
2680 unsigned long low_index, high_index;
2681 std::tie(sleft, sright) = bracket_expr.split('-');
2682 if (sleft.getAsInteger(0, low_index) ||
2683 sright.getAsInteger(0, high_index)) {
2684 *reason_to_stop =
2687 return nullptr;
2688 }
2689
2690 if (low_index > high_index) // swap indices if required
2691 std::swap(low_index, high_index);
2692
2693 if (root_compiler_type_info.Test(
2694 eTypeIsScalar)) // expansion only works for scalars
2695 {
2696 root = root->GetSyntheticBitFieldChild(low_index, high_index, true);
2697 if (!root) {
2698 *reason_to_stop =
2701 return nullptr;
2702 } else {
2703 *reason_to_stop = ValueObject::
2704 eExpressionPathScanEndReasonBitfieldRangeOperatorMet;
2706 return root;
2707 }
2708 } else if (root_compiler_type_info.Test(
2709 eTypeIsPointer) && // if this is a ptr-to-scalar, I am
2710 // accessing it by index and I would
2711 // have deref'ed anyway, then do it
2712 // now and use this as a bitfield
2713 *what_next ==
2715 pointee_compiler_type_info.Test(eTypeIsScalar)) {
2716 Status error;
2718 *root, options.m_synthetic_children_traversal, error);
2719 if (error.Fail() || !root) {
2720 *reason_to_stop =
2723 return nullptr;
2724 } else {
2726 continue;
2727 }
2728 } else {
2729 *reason_to_stop =
2732 return root;
2733 }
2734 }
2735 break;
2736 }
2737 default: // some non-separator is in the way
2738 {
2739 *reason_to_stop =
2742 return nullptr;
2743 }
2744 }
2745 }
2746}
2747
2748llvm::Error ValueObject::Dump(Stream &s) {
2749 return Dump(s, DumpValueObjectOptions(*this));
2750}
2751
2753 const DumpValueObjectOptions &options) {
2754 ValueObjectPrinter printer(*this, &s, options);
2755 return printer.PrintValueObject();
2756}
2757
2759 ValueObjectSP valobj_sp;
2760
2761 if (UpdateValueIfNeeded(false) && m_error.Success()) {
2763
2764 DataExtractor data;
2765 data.SetByteOrder(m_data.GetByteOrder());
2766 data.SetAddressByteSize(m_data.GetAddressByteSize());
2767
2768 if (IsBitfield()) {
2770 m_error = v.GetValueAsData(&exe_ctx, data, GetModule().get());
2771 } else
2772 m_error = m_value.GetValueAsData(&exe_ctx, data, GetModule().get());
2773
2775 exe_ctx.GetBestExecutionContextScope(), GetCompilerType(), name, data,
2776 GetAddressOf().address);
2777 }
2778
2779 if (!valobj_sp) {
2782 exe_ctx.GetBestExecutionContextScope(), m_error.Clone());
2783 }
2784 return valobj_sp;
2785}
2786
2788 lldb::DynamicValueType dynValue, bool synthValue) {
2789 ValueObjectSP result_sp;
2790 switch (dynValue) {
2793 if (!IsDynamic())
2794 result_sp = GetDynamicValue(dynValue);
2795 } break;
2797 if (IsDynamic())
2798 result_sp = GetStaticValue();
2799 } break;
2800 }
2801 if (!result_sp)
2802 result_sp = GetSP();
2803 assert(result_sp);
2804
2805 bool is_synthetic = result_sp->IsSynthetic();
2806 if (synthValue && !is_synthetic) {
2807 if (auto synth_sp = result_sp->GetSyntheticValue())
2808 return synth_sp;
2809 }
2810 if (!synthValue && is_synthetic) {
2811 if (auto non_synth_sp = result_sp->GetNonSyntheticValue())
2812 return non_synth_sp;
2813 }
2814
2815 return result_sp;
2816}
2817
2819 if (m_deref_valobj)
2820 return m_deref_valobj->GetSP();
2821
2822 std::string deref_name_str;
2823 uint32_t deref_byte_size = 0;
2824 int32_t deref_byte_offset = 0;
2825 CompilerType compiler_type = GetCompilerType();
2826 uint64_t language_flags = 0;
2827
2829
2830 CompilerType deref_compiler_type;
2831 auto deref_compiler_type_or_err = compiler_type.GetDereferencedType(
2832 &exe_ctx, deref_name_str, deref_byte_size, deref_byte_offset, this,
2833 language_flags);
2834
2835 std::string deref_error;
2836 if (deref_compiler_type_or_err) {
2837 deref_compiler_type = *deref_compiler_type_or_err;
2838 } else {
2839 deref_error = llvm::toString(deref_compiler_type_or_err.takeError());
2840 LLDB_LOG(GetLog(LLDBLog::Types), "could not find child: {0}", deref_error);
2841 }
2842
2843 if (deref_compiler_type && deref_byte_size) {
2844 ConstString deref_name;
2845 if (!deref_name_str.empty())
2846 deref_name.SetCString(deref_name_str.c_str());
2847
2849 new ValueObjectChild(*this, deref_compiler_type, deref_name,
2850 deref_byte_size, deref_byte_offset, 0, 0, false,
2851 true, eAddressTypeInvalid, language_flags);
2852 }
2853
2854 // In case of incomplete deref compiler type, use the pointee type and try
2855 // to recreate a new ValueObjectChild using it.
2856 if (!m_deref_valobj) {
2857 // FIXME(#59012): C++ stdlib formatters break with incomplete types (e.g.
2858 // `std::vector<int> &`). Remove ObjC restriction once that's resolved.
2861 deref_compiler_type = compiler_type.GetPointeeType();
2862
2863 if (deref_compiler_type) {
2864 ConstString deref_name;
2865 if (!deref_name_str.empty())
2866 deref_name.SetCString(deref_name_str.c_str());
2867
2869 *this, deref_compiler_type, deref_name, deref_byte_size,
2870 deref_byte_offset, 0, 0, false, true, eAddressTypeInvalid,
2871 language_flags);
2872 }
2873 }
2874 }
2875
2876 if (!m_deref_valobj && IsSynthetic())
2877 m_deref_valobj = GetChildMemberWithName("$$dereference$$").get();
2878
2879 if (m_deref_valobj) {
2880 error.Clear();
2881 return m_deref_valobj->GetSP();
2882 } else {
2883 StreamString strm;
2884 GetExpressionPath(strm);
2885
2886 if (deref_error.empty())
2888 "dereference failed: (%s) %s",
2889 GetTypeName().AsCString("<invalid type>"), strm.GetData());
2890 else
2892 "dereference failed: %s: (%s) %s", deref_error.c_str(),
2893 GetTypeName().AsCString("<invalid type>"), strm.GetData());
2894 return ValueObjectSP();
2895 }
2896}
2897
2900 return m_addr_of_valobj_sp;
2901
2902 auto [addr, address_type] = GetAddressOf(/*scalar_is_load_address=*/false);
2903 error.Clear();
2904 if (addr != LLDB_INVALID_ADDRESS && address_type != eAddressTypeHost) {
2905 switch (address_type) {
2906 case eAddressTypeInvalid: {
2907 StreamString expr_path_strm;
2908 GetExpressionPath(expr_path_strm);
2909 error = Status::FromErrorStringWithFormat("'%s' is not in memory",
2910 expr_path_strm.GetData());
2911 } break;
2912
2913 case eAddressTypeFile:
2914 case eAddressTypeLoad: {
2915 CompilerType compiler_type = GetCompilerType();
2916 if (compiler_type) {
2917 std::string name(1, '&');
2918 name.append(m_name.AsCString(""));
2920
2921 lldb::DataBufferSP buffer(
2922 new lldb_private::DataBufferHeap(&addr, sizeof(lldb::addr_t)));
2925 compiler_type.GetPointerType(), ConstString(name.c_str()), buffer,
2927 LLDB_INVALID_ADDRESS, this->GetManager());
2928 }
2929 } break;
2930 default:
2931 break;
2932 }
2933 } else {
2934 StreamString expr_path_strm;
2935 GetExpressionPath(expr_path_strm);
2937 "'%s' doesn't have a valid address", expr_path_strm.GetData());
2938 }
2939
2940 return m_addr_of_valobj_sp;
2941}
2942
2944 return ValueObjectCast::Create(*this, GetName(), compiler_type);
2945}
2946
2948 // Only allow casts if the original type is equal or larger than the cast
2949 // type, unless we know this is a load address. Getting the size wrong for
2950 // a host side storage could leak lldb memory, so we absolutely want to
2951 // prevent that. We may not always get the right value, for instance if we
2952 // have an expression result value that's copied into a storage location in
2953 // the target may not have copied enough memory. I'm not trying to fix that
2954 // here, I'm just making Cast from a smaller to a larger possible in all the
2955 // cases where that doesn't risk making a Value out of random lldb memory.
2956 // You have to check the ValueObject's Value for the address types, since
2957 // ValueObjects that use live addresses will tell you they fetch data from the
2958 // live address, but once they are made, they actually don't.
2959 // FIXME: Can we make ValueObject's with a live address fetch "more data" from
2960 // the live address if it is still valid?
2961
2962 Status error;
2963 CompilerType my_type = GetCompilerType();
2964
2965 ExecutionContextScope *exe_scope =
2967 if (llvm::expectedToOptional(compiler_type.GetByteSize(exe_scope))
2968 .value_or(0) <=
2969 llvm::expectedToOptional(GetCompilerType().GetByteSize(exe_scope))
2970 .value_or(0) ||
2971 m_value.GetValueType() == Value::ValueType::LoadAddress)
2972 return DoCast(compiler_type);
2973
2975 "Can only cast to a type that is equal to or smaller "
2976 "than the orignal type.");
2977
2979 ExecutionContext(GetExecutionContextRef()).GetBestExecutionContextScope(),
2980 std::move(error));
2981}
2982
2986
2988 CompilerType &compiler_type) {
2989 ValueObjectSP valobj_sp;
2990 addr_t ptr_value = GetPointerValue().address;
2991
2992 if (ptr_value != LLDB_INVALID_ADDRESS) {
2993 Address ptr_addr(ptr_value);
2995 valobj_sp = ValueObjectMemory::Create(
2996 exe_ctx.GetBestExecutionContextScope(), name, ptr_addr, compiler_type);
2997 }
2998 return valobj_sp;
2999}
3000
3002 ValueObjectSP valobj_sp;
3003 addr_t ptr_value = GetPointerValue().address;
3004
3005 if (ptr_value != LLDB_INVALID_ADDRESS) {
3006 Address ptr_addr(ptr_value);
3008 valobj_sp = ValueObjectMemory::Create(
3009 exe_ctx.GetBestExecutionContextScope(), name, ptr_addr, type_sp);
3010 }
3011 return valobj_sp;
3012}
3013
3015 if (auto target_sp = GetTargetSP()) {
3016 const bool scalar_is_load_address = true;
3017 auto [addr_value, addr_type] = GetAddressOf(scalar_is_load_address);
3018 if (addr_type == eAddressTypeFile) {
3019 lldb::ModuleSP module_sp(GetModule());
3020 if (!module_sp)
3021 addr_value = LLDB_INVALID_ADDRESS;
3022 else {
3023 Address tmp_addr;
3024 module_sp->ResolveFileAddress(addr_value, tmp_addr);
3025 addr_value = tmp_addr.GetLoadAddress(target_sp.get());
3026 }
3027 } else if (addr_type == eAddressTypeHost ||
3028 addr_type == eAddressTypeInvalid)
3029 addr_value = LLDB_INVALID_ADDRESS;
3030 return addr_value;
3031 }
3032 return LLDB_INVALID_ADDRESS;
3033}
3034
3035llvm::Expected<lldb::ValueObjectSP> ValueObject::CastDerivedToBaseType(
3036 CompilerType type, const llvm::ArrayRef<uint32_t> &base_type_indices) {
3037 // Make sure the starting type and the target type are both valid for this
3038 // type of cast; otherwise return the shared pointer to the original
3039 // (unchanged) ValueObject.
3040 if (!type.IsPointerType() && !type.IsReferenceType())
3041 return llvm::createStringError(
3042 "Invalid target type: should be a pointer or a reference");
3043
3044 CompilerType start_type = GetCompilerType();
3045 if (start_type.IsReferenceType())
3046 start_type = start_type.GetNonReferenceType();
3047
3048 auto target_record_type =
3049 type.IsPointerType() ? type.GetPointeeType() : type.GetNonReferenceType();
3050 auto start_record_type =
3051 start_type.IsPointerType() ? start_type.GetPointeeType() : start_type;
3052
3053 if (!target_record_type.IsRecordType() || !start_record_type.IsRecordType())
3054 return llvm::createStringError(
3055 "Underlying start & target types should be record types");
3056
3057 if (target_record_type.CompareTypes(start_record_type))
3058 return llvm::createStringError(
3059 "Underlying start & target types should be different");
3060
3061 if (base_type_indices.empty())
3062 return llvm::createStringError("children sequence must be non-empty");
3063
3064 // Both the starting & target types are valid for the cast, and the list of
3065 // base class indices is non-empty, so we can proceed with the cast.
3066
3067 lldb::TargetSP target = GetTargetSP();
3068 // The `value` can be a pointer, but GetChildAtIndex works for pointers too.
3069 lldb::ValueObjectSP inner_value = GetSP();
3070
3071 for (const uint32_t i : base_type_indices)
3072 // Create synthetic value if needed.
3073 inner_value =
3074 inner_value->GetChildAtIndex(i, /*can_create_synthetic*/ true);
3075
3076 // At this point type of `inner_value` should be the dereferenced target
3077 // type.
3078 CompilerType inner_value_type = inner_value->GetCompilerType();
3079 if (type.IsPointerType()) {
3080 if (!inner_value_type.CompareTypes(type.GetPointeeType()))
3081 return llvm::createStringError(
3082 "casted value doesn't match the desired type");
3083
3084 uintptr_t addr = inner_value->GetLoadAddress();
3085 llvm::StringRef name = "";
3086 ExecutionContext exe_ctx(target.get(), false);
3087 return ValueObject::CreateValueObjectFromAddress(name, addr, exe_ctx, type,
3088 /* do deref */ false);
3089 }
3090
3091 // At this point the target type should be a reference.
3092 if (!inner_value_type.CompareTypes(type.GetNonReferenceType()))
3093 return llvm::createStringError(
3094 "casted value doesn't match the desired type");
3095
3096 return lldb::ValueObjectSP(inner_value->Cast(type.GetNonReferenceType()));
3097}
3098
3099llvm::Expected<lldb::ValueObjectSP>
3101 // Make sure the starting type and the target type are both valid for this
3102 // type of cast; otherwise return the shared pointer to the original
3103 // (unchanged) ValueObject.
3104 if (!type.IsPointerType() && !type.IsReferenceType())
3105 return llvm::createStringError(
3106 "Invalid target type: should be a pointer or a reference");
3107
3108 CompilerType start_type = GetCompilerType();
3109 if (start_type.IsReferenceType())
3110 start_type = start_type.GetNonReferenceType();
3111
3112 auto target_record_type =
3113 type.IsPointerType() ? type.GetPointeeType() : type.GetNonReferenceType();
3114 auto start_record_type =
3115 start_type.IsPointerType() ? start_type.GetPointeeType() : start_type;
3116
3117 if (!target_record_type.IsRecordType() || !start_record_type.IsRecordType())
3118 return llvm::createStringError(
3119 "Underlying start & target types should be record types");
3120
3121 if (target_record_type.CompareTypes(start_record_type))
3122 return llvm::createStringError(
3123 "Underlying start & target types should be different");
3124
3125 CompilerType virtual_base;
3126 if (target_record_type.IsVirtualBase(start_record_type, &virtual_base)) {
3127 if (!virtual_base.IsValid())
3128 return llvm::createStringError("virtual base should be valid");
3129 return llvm::createStringError(
3130 llvm::Twine("cannot cast " + start_type.TypeDescription() + " to " +
3131 type.TypeDescription() + " via virtual base " +
3132 virtual_base.TypeDescription())
3133 .str());
3134 }
3135
3136 // Both the starting & target types are valid for the cast, so we can
3137 // proceed with the cast.
3138
3139 lldb::TargetSP target = GetTargetSP();
3140 auto pointer_type =
3141 type.IsPointerType() ? type : type.GetNonReferenceType().GetPointerType();
3142
3143 uintptr_t addr =
3145
3146 llvm::StringRef name = "";
3147 ExecutionContext exe_ctx(target.get(), false);
3149 name, addr - offset, exe_ctx, pointer_type, /* do_deref */ false);
3150
3151 if (type.IsPointerType())
3152 return value;
3153
3154 // At this point the target type is a reference. Since `value` is a pointer,
3155 // it has to be dereferenced.
3156 Status error;
3157 return value->Dereference(error);
3158}
3159
3161 bool is_scalar = GetCompilerType().IsScalarType();
3162 bool is_enum = GetCompilerType().IsEnumerationType();
3163 bool is_pointer =
3165 bool is_float = HasFloatingRepresentation(GetCompilerType());
3166 bool is_integer = GetCompilerType().IsInteger();
3168
3169 if (!type.IsScalarType())
3172 Status::FromErrorString("target type must be a scalar"));
3173
3174 if (!is_scalar && !is_enum && !is_pointer)
3177 Status::FromErrorString("argument must be a scalar, enum, or pointer"));
3178
3179 lldb::TargetSP target = GetTargetSP();
3180 uint64_t type_byte_size = 0;
3181 uint64_t val_byte_size = 0;
3182 if (auto temp = llvm::expectedToOptional(type.GetByteSize(target.get())))
3183 type_byte_size = temp.value();
3184 if (auto temp =
3185 llvm::expectedToOptional(GetCompilerType().GetByteSize(target.get())))
3186 val_byte_size = temp.value();
3187
3188 if (is_pointer) {
3189 if (!type.IsInteger() && !type.IsBoolean())
3192 Status::FromErrorString("target type must be an integer or boolean"));
3193 if (!type.IsBoolean() && type_byte_size < val_byte_size)
3197 "target type cannot be smaller than the pointer type"));
3198 }
3199
3200 if (type.IsBoolean()) {
3201 if (!is_scalar || is_integer)
3203 exe_ctx, type.GetTypeSystem().GetSharedPointer(),
3204 GetValueAsUnsigned(0) != 0, "result");
3205 else if (is_scalar && is_float) {
3206 auto float_value_or_err = GetValueAsAPFloat();
3207 if (float_value_or_err)
3209 exe_ctx, type.GetTypeSystem().GetSharedPointer(),
3210 !float_value_or_err->isZero(), "result");
3211 else
3215 "cannot get value as APFloat: %s",
3216 llvm::toString(float_value_or_err.takeError()).c_str()));
3217 }
3218 }
3219
3220 if (type.IsInteger()) {
3221 if (!is_scalar || is_integer) {
3222 auto int_value_or_err = GetValueAsAPSInt();
3223 if (int_value_or_err) {
3224 // Get the value as APSInt and extend or truncate it to the requested
3225 // size.
3226 llvm::APSInt ext =
3227 int_value_or_err->extOrTrunc(type_byte_size * CHAR_BIT);
3228 return ValueObject::CreateValueObjectFromAPInt(exe_ctx, ext, type,
3229 "result");
3230 } else
3234 "cannot get value as APSInt: %s",
3235 llvm::toString(int_value_or_err.takeError()).c_str()));
3236 } else if (is_scalar && is_float) {
3237 llvm::APSInt integer(type_byte_size * CHAR_BIT, !type.IsSigned());
3238 bool is_exact;
3239 auto float_value_or_err = GetValueAsAPFloat();
3240 if (float_value_or_err) {
3241 llvm::APFloatBase::opStatus status =
3242 float_value_or_err->convertToInteger(
3243 integer, llvm::APFloat::rmTowardZero, &is_exact);
3244
3245 // Casting floating point values that are out of bounds of the target
3246 // type is undefined behaviour.
3247 if (status & llvm::APFloatBase::opInvalidOp)
3251 "invalid type cast detected: %s",
3252 llvm::toString(float_value_or_err.takeError()).c_str()));
3254 "result");
3255 }
3256 }
3257 }
3258
3259 if (HasFloatingRepresentation(type)) {
3260 if (!is_scalar) {
3261 auto int_value_or_err = GetValueAsAPSInt();
3262 if (int_value_or_err) {
3263 llvm::APSInt ext =
3264 int_value_or_err->extOrTrunc(type_byte_size * CHAR_BIT);
3265 Scalar scalar_int(ext);
3266 llvm::APFloat f =
3268 return ValueObject::CreateValueObjectFromAPFloat(exe_ctx, f, type,
3269 "result");
3270 } else {
3274 "cannot get value as APSInt: %s",
3275 llvm::toString(int_value_or_err.takeError()).c_str()));
3276 }
3277 } else {
3278 if (is_integer) {
3279 auto int_value_or_err = GetValueAsAPSInt();
3280 if (int_value_or_err) {
3281 Scalar scalar_int(*int_value_or_err);
3282 llvm::APFloat f = scalar_int.CreateAPFloatFromAPSInt(
3284 return ValueObject::CreateValueObjectFromAPFloat(exe_ctx, f, type,
3285 "result");
3286 } else {
3290 "cannot get value as APSInt: %s",
3291 llvm::toString(int_value_or_err.takeError()).c_str()));
3292 }
3293 }
3294 if (is_float) {
3295 auto float_value_or_err = GetValueAsAPFloat();
3296 if (float_value_or_err) {
3297 Scalar scalar_float(*float_value_or_err);
3298 llvm::APFloat f = scalar_float.CreateAPFloatFromAPFloat(
3300 return ValueObject::CreateValueObjectFromAPFloat(exe_ctx, f, type,
3301 "result");
3302 } else {
3306 "cannot get value as APFloat: %s",
3307 llvm::toString(float_value_or_err.takeError()).c_str()));
3308 }
3309 }
3310 }
3311 }
3312
3315 Status::FromErrorString("Unable to perform requested cast"));
3316}
3317
3319 bool is_enum = GetCompilerType().IsEnumerationType();
3320 bool is_integer = GetCompilerType().IsInteger();
3321 bool is_float = HasFloatingRepresentation(GetCompilerType());
3323
3324 if (!is_enum && !is_integer && !is_float)
3328 "argument must be an integer, a float, or an enum"));
3329
3330 if (!type.IsEnumerationType())
3333 Status::FromErrorString("target type must be an enum"));
3334
3335 lldb::TargetSP target = GetTargetSP();
3336 uint64_t byte_size = 0;
3337 if (auto temp = llvm::expectedToOptional(type.GetByteSize(target.get())))
3338 byte_size = temp.value();
3339
3340 if (is_float) {
3341 llvm::APSInt integer(byte_size * CHAR_BIT, !type.IsSigned());
3342 bool is_exact;
3343 auto value_or_err = GetValueAsAPFloat();
3344 if (value_or_err) {
3345 llvm::APFloatBase::opStatus status = value_or_err->convertToInteger(
3346 integer, llvm::APFloat::rmTowardZero, &is_exact);
3347
3348 // Casting floating point values that are out of bounds of the target
3349 // type is undefined behaviour.
3350 if (status & llvm::APFloatBase::opInvalidOp)
3354 "invalid type cast detected: %s",
3355 llvm::toString(value_or_err.takeError()).c_str()));
3357 "result");
3358 } else
3361 Status::FromErrorString("cannot get value as APFloat"));
3362 } else {
3363 // Get the value as APSInt and extend or truncate it to the requested size.
3364 auto value_or_err = GetValueAsAPSInt();
3365 if (value_or_err) {
3366 llvm::APSInt ext = value_or_err->extOrTrunc(byte_size * CHAR_BIT);
3367 return ValueObject::CreateValueObjectFromAPInt(exe_ctx, ext, type,
3368 "result");
3369 } else
3373 "cannot get value as APSInt: %s",
3374 llvm::toString(value_or_err.takeError()).c_str()));
3375 }
3378 Status::FromErrorString("Cannot perform requested cast"));
3379}
3380
3382
3384 bool use_selected)
3385 : m_mod_id(), m_exe_ctx_ref() {
3386 ExecutionContext exe_ctx(exe_scope);
3387 TargetSP target_sp(exe_ctx.GetTargetSP());
3388 if (target_sp) {
3389 m_exe_ctx_ref.SetTargetSP(target_sp);
3390 ProcessSP process_sp(exe_ctx.GetProcessSP());
3391 if (!process_sp)
3392 process_sp = target_sp->GetProcessSP();
3393
3394 if (process_sp) {
3395 m_mod_id = process_sp->GetModID();
3396 m_exe_ctx_ref.SetProcessSP(process_sp);
3397
3398 ThreadSP thread_sp(exe_ctx.GetThreadSP());
3399
3400 if (!thread_sp) {
3401 if (use_selected)
3402 thread_sp = process_sp->GetThreadList().GetSelectedThread();
3403 }
3404
3405 if (thread_sp) {
3406 m_exe_ctx_ref.SetThreadSP(thread_sp);
3407
3408 StackFrameSP frame_sp(exe_ctx.GetFrameSP());
3409 if (!frame_sp) {
3410 if (use_selected)
3411 frame_sp = thread_sp->GetSelectedFrame(DoNoSelectMostRelevantFrame);
3412 }
3413 if (frame_sp)
3414 m_exe_ctx_ref.SetFrameSP(frame_sp);
3415 }
3416 }
3417 }
3418}
3419
3423
3425
3426// This function checks the EvaluationPoint against the current process state.
3427// If the current state matches the evaluation point, or the evaluation point
3428// is already invalid, then we return false, meaning "no change". If the
3429// current state is different, we update our state, and return true meaning
3430// "yes, change". If we did see a change, we also set m_needs_update to true,
3431// so future calls to NeedsUpdate will return true. exe_scope will be set to
3432// the current execution context scope.
3433
3435 bool accept_invalid_exe_ctx) {
3436 // Start with the target, if it is NULL, then we're obviously not going to
3437 // get any further:
3438 const bool thread_and_frame_only_if_stopped = true;
3439 ExecutionContext exe_ctx(
3440 m_exe_ctx_ref.Lock(thread_and_frame_only_if_stopped));
3441
3442 if (exe_ctx.GetTargetPtr() == nullptr)
3443 return false;
3444
3445 // If we don't have a process nothing can change.
3446 Process *process = exe_ctx.GetProcessPtr();
3447 if (process == nullptr)
3448 return false;
3449
3450 // If our stop id is the current stop ID, nothing has changed:
3451 ProcessModID current_mod_id = process->GetModID();
3452
3453 // If the current stop id is 0, either we haven't run yet, or the process
3454 // state has been cleared. In either case, we aren't going to be able to sync
3455 // with the process state.
3456 if (current_mod_id.GetStopID() == 0)
3457 return false;
3458
3459 bool changed = false;
3460 const bool was_valid = m_mod_id.IsValid();
3461 if (was_valid) {
3462 if (m_mod_id == current_mod_id) {
3463 // Everything is already up to date in this object, no need to update the
3464 // execution context scope.
3465 changed = false;
3466 } else {
3467 m_mod_id = current_mod_id;
3468 m_needs_update = true;
3469 changed = true;
3470 }
3471 }
3472
3473 // Now re-look up the thread and frame in case the underlying objects have
3474 // gone away & been recreated. That way we'll be sure to return a valid
3475 // exe_scope. If we used to have a thread or a frame but can't find it
3476 // anymore, then mark ourselves as invalid.
3477
3478 if (!accept_invalid_exe_ctx) {
3479 if (m_exe_ctx_ref.HasThreadRef()) {
3480 ThreadSP thread_sp(m_exe_ctx_ref.GetThreadSP());
3481 if (thread_sp) {
3482 if (m_exe_ctx_ref.HasFrameRef()) {
3483 StackFrameSP frame_sp(m_exe_ctx_ref.GetFrameSP());
3484 if (!frame_sp) {
3485 // We used to have a frame, but now it is gone
3486 SetInvalid();
3487 changed = was_valid;
3488 }
3489 }
3490 } else {
3491 // We used to have a thread, but now it is gone
3492 SetInvalid();
3493 changed = was_valid;
3494 }
3495 }
3496 }
3497
3498 return changed;
3499}
3500
3502 ProcessSP process_sp(m_exe_ctx_ref.GetProcessSP());
3503 if (process_sp)
3504 m_mod_id = process_sp->GetModID();
3505 m_needs_update = false;
3506}
3507
3508void ValueObject::ClearUserVisibleData(uint32_t clear_mask) {
3509 if ((clear_mask & eClearUserVisibleDataItemsValue) ==
3511 m_value_str.clear();
3512
3513 if ((clear_mask & eClearUserVisibleDataItemsLocation) ==
3515 m_location_str.clear();
3516
3517 if ((clear_mask & eClearUserVisibleDataItemsSummary) ==
3519 m_summary_str.clear();
3520
3521 if ((clear_mask & eClearUserVisibleDataItemsDescription) ==
3523 m_object_desc_str.clear();
3524
3528 m_synthetic_value = nullptr;
3529 }
3530}
3531
3533 if (m_parent) {
3534 if (!m_parent->IsPointerOrReferenceType())
3535 return m_parent->GetSymbolContextScope();
3536 }
3537 return nullptr;
3538}
3539
3541 llvm::StringRef name, llvm::StringRef expression,
3542 const ExecutionContext &exe_ctx, ValueObject *parent) {
3543 return CreateValueObjectFromExpression(name, expression, exe_ctx,
3544 EvaluateExpressionOptions(), parent);
3545}
3546
3548 llvm::StringRef name, llvm::StringRef expression,
3549 const ExecutionContext &exe_ctx, const EvaluateExpressionOptions &options,
3550 ValueObject *parent) {
3551 // FIXME: I haven't handled parent in this case yet. That is a WHOLE lot of
3552 // plumbing.
3553
3554 lldb::ValueObjectSP retval_sp;
3555 lldb::TargetSP target_sp(exe_ctx.GetTargetSP());
3556 if (!target_sp)
3557 return retval_sp;
3558 if (expression.empty())
3559 return retval_sp;
3560
3561 target_sp->EvaluateExpression(expression, exe_ctx.GetFrameSP().get(),
3562 retval_sp, options);
3563 if (retval_sp && !name.empty())
3564 retval_sp->SetName(ConstString(name));
3565 return retval_sp;
3566}
3567
3569 llvm::StringRef name, uint64_t address, const ExecutionContext &exe_ctx,
3570 CompilerType type, bool do_deref, ValueObject *parent) {
3571 if (type) {
3572 CompilerType pointer_type(type.GetPointerType());
3573 if (!do_deref)
3574 pointer_type = type;
3575 if (pointer_type) {
3576 lldb::DataBufferSP buffer(
3577 new lldb_private::DataBufferHeap(&address, sizeof(lldb::addr_t)));
3579 exe_ctx.GetBestExecutionContextScope(), pointer_type,
3580 ConstString(name), buffer, exe_ctx.GetByteOrder(),
3581 exe_ctx.GetAddressByteSize(), /*address=*/LLDB_INVALID_ADDRESS,
3582 parent ? parent->GetManager() : nullptr));
3583 if (ptr_result_valobj_sp) {
3584 if (do_deref)
3585 ptr_result_valobj_sp->GetValue().SetValueType(
3587 Status err;
3588 if (do_deref)
3589 ptr_result_valobj_sp = ptr_result_valobj_sp->Dereference(err);
3590 if (ptr_result_valobj_sp && !name.empty())
3591 ptr_result_valobj_sp->SetName(ConstString(name));
3592 }
3593 return ptr_result_valobj_sp;
3594 }
3595 }
3596 return lldb::ValueObjectSP();
3597}
3598
3600 llvm::StringRef name, const DataExtractor &data,
3601 const ExecutionContext &exe_ctx, CompilerType type, ValueObject *parent) {
3602 lldb::ValueObjectSP new_value_sp;
3603 new_value_sp = ValueObjectConstResult::Create(
3604 exe_ctx.GetBestExecutionContextScope(), type, ConstString(name), data,
3605 LLDB_INVALID_ADDRESS, parent ? parent->GetManager() : nullptr);
3606 new_value_sp->SetAddressTypeOfChildren(eAddressTypeLoad);
3607 if (new_value_sp && !name.empty())
3608 new_value_sp->SetName(ConstString(name));
3609 return new_value_sp;
3610}
3611
3613 const ExecutionContext &exe_ctx, const llvm::APInt &v, CompilerType type,
3614 llvm::StringRef name, ValueObject *parent) {
3615 uint64_t byte_size =
3616 llvm::expectedToOptional(
3618 .value_or(0);
3619 lldb::DataExtractorSP data_sp = std::make_shared<DataExtractor>(
3620 reinterpret_cast<const void *>(v.getRawData()), byte_size,
3621 exe_ctx.GetByteOrder(), exe_ctx.GetAddressByteSize());
3622 return ValueObject::CreateValueObjectFromData(name, *data_sp, exe_ctx, type,
3623 parent);
3624}
3625
3627 const ExecutionContext &exe_ctx, const llvm::APFloat &v, CompilerType type,
3628 llvm::StringRef name, ValueObject *parent) {
3629 return CreateValueObjectFromAPInt(exe_ctx, v.bitcastToAPInt(), type, name,
3630 parent);
3631}
3632
3634 const ExecutionContext &exe_ctx, Scalar &s, CompilerType type,
3635 llvm::StringRef name, ValueObject *parent) {
3637 exe_ctx.GetBestExecutionContextScope(), type, s, ConstString(name),
3638 /*module_ptr=*/nullptr, parent ? parent->GetManager() : nullptr);
3639}
3640
3642 const ExecutionContext &exe_ctx, TypeSystemSP typesystem_sp, bool value,
3643 llvm::StringRef name, ValueObject *parent) {
3644 CompilerType type = typesystem_sp->GetBasicTypeFromAST(lldb::eBasicTypeBool);
3646 uint64_t byte_size =
3647 llvm::expectedToOptional(type.GetByteSize(exe_scope)).value_or(0);
3648 lldb::DataExtractorSP data_sp = std::make_shared<DataExtractor>(
3649 reinterpret_cast<const void *>(&value), byte_size, exe_ctx.GetByteOrder(),
3650 exe_ctx.GetAddressByteSize());
3651 return ValueObject::CreateValueObjectFromData(name, *data_sp, exe_ctx, type,
3652 parent);
3653}
3654
3656 const ExecutionContext &exe_ctx, CompilerType type, llvm::StringRef name,
3657 ValueObject *parent) {
3658 if (!type.IsNullPtrType()) {
3659 lldb::ValueObjectSP ret_val;
3660 return ret_val;
3661 }
3662 uintptr_t zero = 0;
3663 uint64_t byte_size = 0;
3664 if (auto temp = llvm::expectedToOptional(
3666 byte_size = temp.value();
3667 lldb::DataExtractorSP data_sp = std::make_shared<DataExtractor>(
3668 reinterpret_cast<const void *>(zero), byte_size, exe_ctx.GetByteOrder(),
3669 exe_ctx.GetAddressByteSize());
3670 return ValueObject::CreateValueObjectFromData(name, *data_sp, exe_ctx, type,
3671 parent);
3672}
3673
3675 ValueObject *root(GetRoot());
3676 if (root != this)
3677 return root->GetModule();
3678 return lldb::ModuleSP();
3679}
3680
3682 if (m_root)
3683 return m_root;
3684 return (m_root = FollowParentChain([](ValueObject *vo) -> bool {
3685 return (vo->m_parent != nullptr);
3686 }));
3687}
3688
3691 ValueObject *vo = this;
3692 while (vo) {
3693 if (!f(vo))
3694 break;
3695 vo = vo->m_parent;
3696 }
3697 return vo;
3698}
3699
3708
3710 ValueObject *with_dv_info = this;
3711 while (with_dv_info) {
3712 if (with_dv_info->HasDynamicValueTypeInfo())
3713 return with_dv_info->GetDynamicValueTypeImpl();
3714 with_dv_info = with_dv_info->m_parent;
3715 }
3717}
3718
3720 const ValueObject *with_fmt_info = this;
3721 while (with_fmt_info) {
3722 if (with_fmt_info->m_format != lldb::eFormatDefault)
3723 return with_fmt_info->m_format;
3724 with_fmt_info = with_fmt_info->m_parent;
3725 }
3726 return m_format;
3727}
3728
3732 if (GetRoot()) {
3733 if (GetRoot() == this) {
3734 if (StackFrameSP frame_sp = GetFrameSP()) {
3735 const SymbolContext &sc(
3736 frame_sp->GetSymbolContext(eSymbolContextCompUnit));
3737 if (CompileUnit *cu = sc.comp_unit)
3738 type = cu->GetLanguage();
3739 }
3740 } else {
3742 }
3743 }
3744 }
3745 return (m_preferred_display_language = type); // only compute it once
3746}
3747
3752
3754 // we need to support invalid types as providers of values because some bare-
3755 // board debugging scenarios have no notion of types, but still manage to
3756 // have raw numeric values for things like registers. sigh.
3758 return (!type.IsValid()) || (0 != (type.GetTypeInfo() & eTypeHasValue));
3759}
3760
3762 if (!UpdateValueIfNeeded())
3763 return nullptr;
3764
3765 TargetSP target_sp(GetTargetSP());
3766 if (!target_sp)
3767 return nullptr;
3768
3769 PersistentExpressionState *persistent_state =
3770 target_sp->GetPersistentExpressionStateForLanguage(
3772
3773 if (!persistent_state)
3774 return nullptr;
3775
3776 ConstString name = persistent_state->GetNextPersistentVariableName();
3777
3778 ValueObjectSP const_result_sp =
3779 ValueObjectConstResult::Create(target_sp.get(), GetValue(), name);
3780
3781 ExpressionVariableSP persistent_var_sp =
3782 persistent_state->CreatePersistentVariable(const_result_sp);
3783 persistent_var_sp->m_live_sp = persistent_var_sp->m_frozen_sp;
3784 persistent_var_sp->m_flags |= ExpressionVariable::EVIsProgramReference;
3785
3786 return persistent_var_sp->GetValueObject();
3787}
3788
3792
3794 lldb::DynamicValueType use_dynamic, bool use_synthetic,
3795 const char *name)
3796 : m_use_dynamic(use_dynamic), m_use_synthetic(use_synthetic), m_name(name) {
3797 if (in_valobj_sp) {
3798 if ((m_valobj_sp = in_valobj_sp->GetQualifiedRepresentationIfAvailable(
3799 lldb::eNoDynamicValues, false))) {
3800 if (!m_name.IsEmpty())
3801 m_valobj_sp->SetName(m_name);
3802 }
3803 }
3804}
3805
3807 if (this != &rhs) {
3811 m_name = rhs.m_name;
3812 }
3813 return *this;
3814}
3815
3817 if (m_valobj_sp.get() == nullptr)
3818 return false;
3819
3820 // FIXME: This check is necessary but not sufficient. We for sure don't
3821 // want to touch SBValues whose owning
3822 // targets have gone away. This check is a little weak in that it
3823 // enforces that restriction when you call IsValid, but since IsValid
3824 // doesn't lock the target, you have no guarantee that the SBValue won't
3825 // go invalid after you call this... Also, an SBValue could depend on
3826 // data from one of the modules in the target, and those could go away
3827 // independently of the target, for instance if a module is unloaded.
3828 // But right now, neither SBValues nor ValueObjects know which modules
3829 // they depend on. So I have no good way to make that check without
3830 // tracking that in all the ValueObject subclasses.
3831 TargetSP target_sp = m_valobj_sp->GetTargetSP();
3832 return target_sp && target_sp->IsValid();
3833}
3834
3837 std::unique_lock<std::recursive_mutex> &lock, Status &error) {
3838 if (!m_valobj_sp) {
3839 error = Status::FromErrorString("invalid value object");
3840 return m_valobj_sp;
3841 }
3842
3844
3845 Target *target = value_sp->GetTargetSP().get();
3846 // If this ValueObject holds an error, then it is valuable for that.
3847 if (value_sp->GetError().Fail())
3848 return value_sp;
3849
3850 if (!target)
3851 return ValueObjectSP();
3852
3853 lock = std::unique_lock<std::recursive_mutex>(target->GetAPIMutex());
3854
3855 ProcessSP process_sp(value_sp->GetProcessSP());
3856 if (process_sp && !stop_locker.TryLock(&process_sp->GetRunLock())) {
3857 // We don't allow people to play around with ValueObject if the process
3858 // is running. If you want to look at values, pause the process, then
3859 // look.
3860 error = Status::FromErrorString("process must be stopped.");
3861 return ValueObjectSP();
3862 }
3863
3865 ValueObjectSP dynamic_sp = value_sp->GetDynamicValue(m_use_dynamic);
3866 if (dynamic_sp)
3867 value_sp = dynamic_sp;
3868 }
3869
3870 if (m_use_synthetic) {
3871 ValueObjectSP synthetic_sp = value_sp->GetSyntheticValue();
3872 if (synthetic_sp)
3873 value_sp = synthetic_sp;
3874 }
3875
3876 if (!value_sp)
3877 error = Status::FromErrorString("invalid value object");
3878 if (!m_name.IsEmpty())
3879 value_sp->SetName(m_name);
3880
3881 return value_sp;
3882}
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:364
#define LLDB_LOG_ERRORV(log, error,...)
Definition Log.h:410
#define LLDB_LOGF(log,...)
Definition Log.h:378
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:394
static user_id_t g_value_obj_uid
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 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:301
bool SetLoadAddress(lldb::addr_t load_addr, Target *target, bool allow_section_end=false)
Set the address to represent load_addr.
Definition Address.cpp:1034
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:690
lldb::ByteOrder GetByteOrder() const
Returns the byte order for the architecture specification.
Definition ArchSpec.cpp:739
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 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...
const char * PeekCStr(lldb::offset_t offset) const
Peek at a C string at offset.
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:252
A plug-in interface definition class for debugging a process.
Definition Process.h:356
ProcessModID GetModID() const
Get the Modification ID of the process.
Definition Process.h:1486
ProcessRunLock::ProcessRunLocker StopLocker
Definition Process.h:395
bool IsPossibleDynamicValue(ValueObject &in_value)
Definition Process.cpp:1536
LanguageRuntime * GetLanguageRuntime(lldb::LanguageType language)
Definition Process.cpp:1508
size_t WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size, Status &error)
Write memory to a process.
Definition Process.cpp:2535
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:2616
llvm::APFloat CreateAPFloatFromAPFloat(lldb::BasicType basic_type)
Definition Scalar.cpp:850
llvm::APFloat CreateAPFloatFromAPSInt(lldb::BasicType basic_type)
Definition Scalar.cpp:830
unsigned long long ULongLong(unsigned long long fail_value=0) const
Definition Scalar.cpp:365
llvm::APFloat GetAPFloat() const
Definition Scalar.h:190
long long SLongLong(long long fail_value=0) const
Definition Scalar.cpp:361
bool ExtractBitfield(uint32_t bit_size, uint32_t bit_offset)
Definition Scalar.cpp:813
Status SetValueFromCString(const char *s, lldb::Encoding encoding, size_t byte_size)
Definition Scalar.cpp:648
bool GetData(DataExtractor &data) const
Get data with a byte size of GetByteSize().
Definition Scalar.cpp:85
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.
uint32_t GetMaximumSizeOfStringSummary() const
Definition Target.cpp:5561
bool GetCheckValueObjectOwnership() const
Definition Target.cpp:5853
std::recursive_mutex & GetAPIMutex()
Definition Target.cpp:5957
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:2062
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 m_valobj_sp
lldb::DynamicValueType m_use_dynamic
lldb::ValueObjectSP GetSP(Process::StopLocker &stop_locker, std::unique_lock< std::recursive_mutex > &lock, Status &error)
ValueImpl & operator=(const ValueImpl &rhs)
static lldb::ValueObjectSP Create(ValueObject &parent, ConstString 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)
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()
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)
void SetValueFromInteger(const llvm::APInt &value, Status &error, bool can_update_var=true)
Update an existing integer ValueObject with a new integer value.
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::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
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)
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.
virtual lldb::ValueObjectSP Clone(ConstString new_name)
Creates a copy of the ValueObject with a new name and setting the current ValueObject as its parent.
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
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:113
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:41
@ HostAddress
A host address value (for memory in the process that < A is using liblldb).
Definition Value.h:52
@ FileAddress
A file address value.
Definition Value.h:47
@ LoadAddress
A load address value.
Definition Value.h:49
@ Scalar
A raw scalar value.
Definition Value.h:45
ValueType GetValueType() const
Definition Value.cpp:111
Scalar & ResolveValue(ExecutionContext *exe_ctx, Module *module=nullptr)
Definition Value.cpp:589
@ RegisterInfo
RegisterInfo * (can be a scalar or a vector register).
Definition Value.h:61
ContextType GetContextType() const
Definition Value.h:87
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:327
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:85
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
uint64_t user_id_t
Definition lldb-types.h:82
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.