[Go to site: main page, start]

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