[Go to site: main page, start]

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