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