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