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