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
9#include "lldb/Core/ValueObject.h"
10
11#include "lldb/Core/Address.h"
12#include "lldb/Core/Declaration.h"
13#include "lldb/Core/Module.h"
14#include "lldb/Core/ValueObjectCast.h"
15#include "lldb/Core/ValueObjectChild.h"
16#include "lldb/Core/ValueObjectConstResult.h"
17#include "lldb/Core/ValueObjectDynamicValue.h"
18#include "lldb/Core/ValueObjectMemory.h"
19#include "lldb/Core/ValueObjectSyntheticFilter.h"
20#include "lldb/DataFormatters/DataVisualization.h"
21#include "lldb/DataFormatters/DumpValueObjectOptions.h"
22#include "lldb/DataFormatters/FormatManager.h"
23#include "lldb/DataFormatters/StringPrinter.h"
24#include "lldb/DataFormatters/TypeFormat.h"
25#include "lldb/DataFormatters/TypeSummary.h"
26#include "lldb/DataFormatters/ValueObjectPrinter.h"
27#include "lldb/Expression/ExpressionVariable.h"
28#include "lldb/Host/Config.h"
29#include "lldb/Symbol/CompileUnit.h"
30#include "lldb/Symbol/CompilerType.h"
31#include "lldb/Symbol/SymbolContext.h"
32#include "lldb/Symbol/Type.h"
33#include "lldb/Symbol/Variable.h"
34#include "lldb/Target/ExecutionContext.h"
35#include "lldb/Target/Language.h"
36#include "lldb/Target/LanguageRuntime.h"
37#include "lldb/Target/Process.h"
38#include "lldb/Target/StackFrame.h"
39#include "lldb/Target/Target.h"
40#include "lldb/Target/Thread.h"
41#include "lldb/Target/ThreadList.h"
42#include "lldb/Utility/DataBuffer.h"
43#include "lldb/Utility/DataBufferHeap.h"
44#include "lldb/Utility/Flags.h"
45#include "lldb/Utility/Log.h"
46#include "lldb/Utility/Logging.h"
47#include "lldb/Utility/Scalar.h"
48#include "lldb/Utility/Stream.h"
49#include "lldb/Utility/StreamString.h"
50#include "lldb/lldb-private-types.h"
51
52#include "llvm/Support/Compiler.h"
53
54#include <algorithm>
55#include <cstdint>
56#include <cstdlib>
57#include <memory>
58#include <tuple>
59
60#include <assert.h>
61#include <inttypes.h>
62#include <stdio.h>
63#include <string.h>
64
65#include <lldb/Core/ValueObject.h>
66
67namespace lldb_private {
68class ExecutionContextScope;
69}
70namespace lldb_private {
71class SymbolContextScope;
72}
73
74using namespace lldb;
75using namespace lldb_private;
76
77static user_id_t g_value_obj_uid = 0;
78
79// ValueObject constructor
80ValueObject::ValueObject(ValueObject &parent)
81 : m_parent(&parent), m_update_point(parent.GetUpdatePoint()),
82 m_manager(parent.GetManager()), m_id(++g_value_obj_uid) {
83 m_flags.m_is_synthetic_children_generated =
84 parent.m_flags.m_is_synthetic_children_generated;
85 m_data.SetByteOrder(parent.GetDataExtractor().GetByteOrder());
86 m_data.SetAddressByteSize(parent.GetDataExtractor().GetAddressByteSize());
87 m_manager->ManageObject(this);
88}
89
90// ValueObject constructor
91ValueObject::ValueObject(ExecutionContextScope *exe_scope,
92 ValueObjectManager &manager,
93 AddressType child_ptr_or_ref_addr_type)
94 : m_update_point(exe_scope), m_manager(&manager),
95 m_address_type_of_ptr_or_ref_children(child_ptr_or_ref_addr_type),
96 m_id(++g_value_obj_uid) {
97 if (exe_scope) {
98 TargetSP target_sp(exe_scope->CalculateTarget());
99 if (target_sp) {
100 const ArchSpec &arch = target_sp->GetArchitecture();
101 m_data.SetByteOrder(arch.GetByteOrder());
102 m_data.SetAddressByteSize(arch.GetAddressByteSize());
103 }
104 }
105 m_manager->ManageObject(this);
106}
107
108// Destructor
109ValueObject::~ValueObject() {}
110
111bool ValueObject::UpdateValueIfNeeded(bool update_format) {
112
113 bool did_change_formats = false;
114
115 if (update_format)
116 did_change_formats = UpdateFormatsIfNeeded();
117
118 // If this is a constant value, then our success is predicated on whether we
119 // have an error or not
120 if (GetIsConstant()) {
121 // if you are constant, things might still have changed behind your back
122 // (e.g. you are a frozen object and things have changed deeper than you
123 // cared to freeze-dry yourself) in this case, your value has not changed,
124 // but "computed" entries might have, so you might now have a different
125 // summary, or a different object description. clear these so we will
126 // recompute them
127 if (update_format && !did_change_formats)
128 ClearUserVisibleData(eClearUserVisibleDataItemsSummary |
129 eClearUserVisibleDataItemsDescription);
130 return m_error.Success();
131 }
132
133 bool first_update = IsChecksumEmpty();
134
135 if (NeedsUpdating()) {
136 m_update_point.SetUpdated();
137
138 // Save the old value using swap to avoid a string copy which also will
139 // clear our m_value_str
140 if (m_value_str.empty()) {
141 m_flags.m_old_value_valid = false;
142 } else {
143 m_flags.m_old_value_valid = true;
144 m_old_value_str.swap(m_value_str);
145 ClearUserVisibleData(eClearUserVisibleDataItemsValue);
146 }
147
148 ClearUserVisibleData();
149
150 if (IsInScope()) {
151 const bool value_was_valid = GetValueIsValid();
152 SetValueDidChange(false);
153
154 m_error.Clear();
155
156 // Call the pure virtual function to update the value
157
158 bool need_compare_checksums = false;
159 llvm::SmallVector<uint8_t, 16> old_checksum;
160
161 if (!first_update && CanProvideValue()) {
162 need_compare_checksums = true;
163 old_checksum.resize(m_value_checksum.size());
164 std::copy(m_value_checksum.begin(), m_value_checksum.end(),
165 old_checksum.begin());
166 }
167
168 bool success = UpdateValue();
169
170 SetValueIsValid(success);
171
172 if (success) {
173 UpdateChildrenAddressType();
174 const uint64_t max_checksum_size = 128;
175 m_data.Checksum(m_value_checksum, max_checksum_size);
176 } else {
177 need_compare_checksums = false;
178 m_value_checksum.clear();
179 }
180
181 assert(!need_compare_checksums ||
182 (!old_checksum.empty() && !m_value_checksum.empty()));
183
184 if (first_update)
185 SetValueDidChange(false);
186 else if (!m_flags.m_value_did_change && !success) {
187 // The value wasn't gotten successfully, so we mark this as changed if
188 // the value used to be valid and now isn't
189 SetValueDidChange(value_was_valid);
190 } else if (need_compare_checksums) {
191 SetValueDidChange(memcmp(&old_checksum[0], &m_value_checksum[0],
192 m_value_checksum.size()));
193 }
194
195 } else {
196 m_error.SetErrorString("out of scope");
197 }
198 }
199 return m_error.Success();
200}
201
202bool ValueObject::UpdateFormatsIfNeeded() {
203 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_DATAFORMATTERS));
204 LLDB_LOGF(log,
205 "[%s %p] checking for FormatManager revisions. ValueObject "
206 "rev: %d - Global rev: %d",
207 GetName().GetCString(), static_cast<void *>(this),
208 m_last_format_mgr_revision,
209 DataVisualization::GetCurrentRevision());
210
211 bool any_change = false;
212
213 if ((m_last_format_mgr_revision != DataVisualization::GetCurrentRevision())) {
214 m_last_format_mgr_revision = DataVisualization::GetCurrentRevision();
215 any_change = true;
216
217 SetValueFormat(DataVisualization::GetFormat(*this, eNoDynamicValues));
218 SetSummaryFormat(
219 DataVisualization::GetSummaryFormat(*this, GetDynamicValueType()));
220#if LLDB_ENABLE_PYTHON
221 SetSyntheticChildren(
222 DataVisualization::GetSyntheticChildren(*this, GetDynamicValueType()));
223#endif
224 }
225
226 return any_change;
227}
228
229void ValueObject::SetNeedsUpdate() {
230 m_update_point.SetNeedsUpdate();
231 // We have to clear the value string here so ConstResult children will notice
232 // if their values are changed by hand (i.e. with SetValueAsCString).
233 ClearUserVisibleData(eClearUserVisibleDataItemsValue);
234}
235
236void ValueObject::ClearDynamicTypeInformation() {
237 m_flags.m_children_count_valid = false;
238 m_flags.m_did_calculate_complete_objc_class_type = false;
239 m_last_format_mgr_revision = 0;
240 m_override_type = CompilerType();
241 SetValueFormat(lldb::TypeFormatImplSP());
242 SetSummaryFormat(lldb::TypeSummaryImplSP());
243 SetSyntheticChildren(lldb::SyntheticChildrenSP());
244}
245
246CompilerType ValueObject::MaybeCalculateCompleteType() {
247 CompilerType compiler_type(GetCompilerTypeImpl());
248
249 if (m_flags.m_did_calculate_complete_objc_class_type) {
250 if (m_override_type.IsValid())
251 return m_override_type;
252 else
253 return compiler_type;
254 }
255
256 m_flags.m_did_calculate_complete_objc_class_type = true;
257
258 ProcessSP process_sp(
259 GetUpdatePoint().GetExecutionContextRef().GetProcessSP());
260
261 if (!process_sp)
262 return compiler_type;
263
264 if (auto *runtime =
265 process_sp->GetLanguageRuntime(GetObjectRuntimeLanguage())) {
266 if (llvm::Optional<CompilerType> complete_type =
267 runtime->GetRuntimeType(compiler_type)) {
268 m_override_type = complete_type.getValue();
269 if (m_override_type.IsValid())
270 return m_override_type;
271 }
272 }
273 return compiler_type;
274}
275
276
277
278DataExtractor &ValueObject::GetDataExtractor() {
279 UpdateValueIfNeeded(false);
280 return m_data;
281}
282
283const Status &ValueObject::GetError() {
284 UpdateValueIfNeeded(false);
285 return m_error;
286}
287
288const char *ValueObject::GetLocationAsCStringImpl(const Value &value,
289 const DataExtractor &data) {
290 if (UpdateValueIfNeeded(false)) {
291 if (m_location_str.empty()) {
292 StreamString sstr;
293
294 Value::ValueType value_type = value.GetValueType();
295
296 switch (value_type) {
297 case Value::ValueType::Invalid:
298 m_location_str = "invalid";
299 break;
300 case Value::ValueType::Scalar:
301 if (value.GetContextType() == Value::ContextType::RegisterInfo) {
302 RegisterInfo *reg_info = value.GetRegisterInfo();
303 if (reg_info) {
304 if (reg_info->name)
305 m_location_str = reg_info->name;
306 else if (reg_info->alt_name)
307 m_location_str = reg_info->alt_name;
308 if (m_location_str.empty())
309 m_location_str = (reg_info->encoding == lldb::eEncodingVector)
310 ? "vector"
311 : "scalar";
312 }
313 }
314 if (m_location_str.empty())
315 m_location_str = "scalar";
316 break;
317
318 case Value::ValueType::LoadAddress:
319 case Value::ValueType::FileAddress:
320 case Value::ValueType::HostAddress: {
321 uint32_t addr_nibble_size = data.GetAddressByteSize() * 2;
322 sstr.Printf("0x%*.*llx", addr_nibble_size, addr_nibble_size,
323 value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS));
324 m_location_str = std::string(sstr.GetString());
325 } break;
326 }
327 }
328 }
329 return m_location_str.c_str();
330}
331
332bool ValueObject::ResolveValue(Scalar &scalar) {
333 if (UpdateValueIfNeeded(
334 false)) // make sure that you are up to date before returning anything
335 {
336 ExecutionContext exe_ctx(GetExecutionContextRef());
337 Value tmp_value(m_value);
338 scalar = tmp_value.ResolveValue(&exe_ctx);
339 if (scalar.IsValid()) {
340 const uint32_t bitfield_bit_size = GetBitfieldBitSize();
341 if (bitfield_bit_size)
342 return scalar.ExtractBitfield(bitfield_bit_size,
343 GetBitfieldBitOffset());
344 return true;
345 }
346 }
347 return false;
348}
349
350bool ValueObject::IsLogicalTrue(Status &error) {
351 if (Language *language = Language::FindPlugin(GetObjectRuntimeLanguage())) {
352 LazyBool is_logical_true = language->IsLogicalTrue(*this, error);
353 switch (is_logical_true) {
354 case eLazyBoolYes:
355 case eLazyBoolNo:
356 return (is_logical_true == true);
357 case eLazyBoolCalculate:
358 break;
359 }
360 }
361
362 Scalar scalar_value;
363
364 if (!ResolveValue(scalar_value)) {
365 error.SetErrorString("failed to get a scalar result");
366 return false;
367 }
368
369 bool ret;
370 ret = scalar_value.ULongLong(1) != 0;
371 error.Clear();
372 return ret;
373}
374
375ValueObjectSP ValueObject::GetChildAtIndex(size_t idx, bool can_create) {
376 ValueObjectSP child_sp;
377 // We may need to update our value if we are dynamic
378 if (IsPossibleDynamicType())
379 UpdateValueIfNeeded(false);
380 if (idx < GetNumChildren()) {
381 // Check if we have already made the child value object?
382 if (can_create && !m_children.HasChildAtIndex(idx)) {
383 // No we haven't created the child at this index, so lets have our
384 // subclass do it and cache the result for quick future access.
385 m_children.SetChildAtIndex(idx, CreateChildAtIndex(idx, false, 0));
386 }
387
388 ValueObject *child = m_children.GetChildAtIndex(idx);
389 if (child != nullptr)
390 return child->GetSP();
391 }
392 return child_sp;
393}
394
395lldb::ValueObjectSP
396ValueObject::GetChildAtIndexPath(llvm::ArrayRef<size_t> idxs,
397 size_t *index_of_error) {
398 if (idxs.size() == 0)
399 return GetSP();
400 ValueObjectSP root(GetSP());
401 for (size_t idx : idxs) {
402 root = root->GetChildAtIndex(idx, true);
403 if (!root) {
404 if (index_of_error)
405 *index_of_error = idx;
406 return root;
407 }
408 }
409 return root;
410}
411
412lldb::ValueObjectSP ValueObject::GetChildAtIndexPath(
413 llvm::ArrayRef<std::pair<size_t, bool>> idxs, size_t *index_of_error) {
414 if (idxs.size() == 0)
415 return GetSP();
416 ValueObjectSP root(GetSP());
417 for (std::pair<size_t, bool> idx : idxs) {
418 root = root->GetChildAtIndex(idx.first, idx.second);
419 if (!root) {
420 if (index_of_error)
421 *index_of_error = idx.first;
422 return root;
423 }
424 }
425 return root;
426}
427
428lldb::ValueObjectSP
429ValueObject::GetChildAtNamePath(llvm::ArrayRef<ConstString> names,
430 ConstString *name_of_error) {
431 if (names.size() == 0)
432 return GetSP();
433 ValueObjectSP root(GetSP());
434 for (ConstString name : names) {
435 root = root->GetChildMemberWithName(name, true);
436 if (!root) {
437 if (name_of_error)
438 *name_of_error = name;
439 return root;
440 }
441 }
442 return root;
443}
444
445lldb::ValueObjectSP ValueObject::GetChildAtNamePath(
446 llvm::ArrayRef<std::pair<ConstString, bool>> names,
447 ConstString *name_of_error) {
448 if (names.size() == 0)
449 return GetSP();
450 ValueObjectSP root(GetSP());
451 for (std::pair<ConstString, bool> name : names) {
452 root = root->GetChildMemberWithName(name.first, name.second);
453 if (!root) {
454 if (name_of_error)
455 *name_of_error = name.first;
456 return root;
457 }
458 }
459 return root;
460}
461
462size_t ValueObject::GetIndexOfChildWithName(ConstString name) {
463 bool omit_empty_base_classes = true;
464 return GetCompilerType().GetIndexOfChildWithName(name.GetCString(),
465 omit_empty_base_classes);
466}
467
468ValueObjectSP ValueObject::GetChildMemberWithName(ConstString name,
469 bool can_create) {
470 // We may need to update our value if we are dynamic.
471 if (IsPossibleDynamicType())
472 UpdateValueIfNeeded(false);
473
474 // When getting a child by name, it could be buried inside some base classes
475 // (which really aren't part of the expression path), so we need a vector of
476 // indexes that can get us down to the correct child.
477 std::vector<uint32_t> child_indexes;
478 bool omit_empty_base_classes = true;
479
480 if (!GetCompilerType().IsValid())
481 return ValueObjectSP();
482
483 const size_t num_child_indexes =
484 GetCompilerType().GetIndexOfChildMemberWithName(
485 name.GetCString(), omit_empty_base_classes, child_indexes);
486 if (num_child_indexes == 0)
487 return nullptr;
488
489 ValueObjectSP child_sp = GetSP();
490 for (uint32_t idx : child_indexes)
491 if (child_sp)
492 child_sp = child_sp->GetChildAtIndex(idx, can_create);
493 return child_sp;
494}
495
496size_t ValueObject::GetNumChildren(uint32_t max) {
497 UpdateValueIfNeeded();
498
499 if (max < UINT32_MAX) {
500 if (m_flags.m_children_count_valid) {
501 size_t children_count = m_children.GetChildrenCount();
502 return children_count <= max ? children_count : max;
503 } else
504 return CalculateNumChildren(max);
505 }
506
507 if (!m_flags.m_children_count_valid) {
508 SetNumChildren(CalculateNumChildren());
509 }
510 return m_children.GetChildrenCount();
511}
512
513bool ValueObject::MightHaveChildren() {
514 bool has_children = false;
515 const uint32_t type_info = GetTypeInfo();
516 if (type_info) {
517 if (type_info & (eTypeHasChildren | eTypeIsPointer | eTypeIsReference))
518 has_children = true;
519 } else {
520 has_children = GetNumChildren() > 0;
521 }
522 return has_children;
523}
524
525// Should only be called by ValueObject::GetNumChildren()
526void ValueObject::SetNumChildren(size_t num_children) {
527 m_flags.m_children_count_valid = true;
528 m_children.SetChildrenCount(num_children);
529}
530
531ValueObject *ValueObject::CreateChildAtIndex(size_t idx,
532 bool synthetic_array_member,
533 int32_t synthetic_index) {
534 ValueObject *valobj = nullptr;
535
536 bool omit_empty_base_classes = true;
537 bool ignore_array_bounds = synthetic_array_member;
538 std::string child_name_str;
539 uint32_t child_byte_size = 0;
540 int32_t child_byte_offset = 0;
541 uint32_t child_bitfield_bit_size = 0;
542 uint32_t child_bitfield_bit_offset = 0;
543 bool child_is_base_class = false;
544 bool child_is_deref_of_parent = false;
545 uint64_t language_flags = 0;
546
547 const bool transparent_pointers = !synthetic_array_member;
548 CompilerType child_compiler_type;
549
550 ExecutionContext exe_ctx(GetExecutionContextRef());
551
552 child_compiler_type = GetCompilerType().GetChildCompilerTypeAtIndex(
553 &exe_ctx, idx, transparent_pointers, omit_empty_base_classes,
554 ignore_array_bounds, child_name_str, child_byte_size, child_byte_offset,
555 child_bitfield_bit_size, child_bitfield_bit_offset, child_is_base_class,
556 child_is_deref_of_parent, this, language_flags);
557 if (child_compiler_type) {
558 if (synthetic_index)
559 child_byte_offset += child_byte_size * synthetic_index;
560
561 ConstString child_name;
562 if (!child_name_str.empty())
563 child_name.SetCString(child_name_str.c_str());
564
565 valobj = new ValueObjectChild(
566 *this, child_compiler_type, child_name, child_byte_size,
567 child_byte_offset, child_bitfield_bit_size, child_bitfield_bit_offset,
568 child_is_base_class, child_is_deref_of_parent, eAddressTypeInvalid,
569 language_flags);
570 }
571
572 // In case of an incomplete type, try to use the ValueObject's
573 // synthetic value to create the child ValueObject.
574 if (!valobj && synthetic_array_member) {
575 if (ValueObjectSP synth_valobj_sp = GetSyntheticValue()) {
576 valobj = synth_valobj_sp
577 ->GetChildAtIndex(synthetic_index, synthetic_array_member)
578 .get();
579 }
580 }
581
582 return valobj;
583}
584
585bool ValueObject::GetSummaryAsCString(TypeSummaryImpl *summary_ptr,
586 std::string &destination,
587 lldb::LanguageType lang) {
588 return GetSummaryAsCString(summary_ptr, destination,
589 TypeSummaryOptions().SetLanguage(lang));
590}
591
592bool ValueObject::GetSummaryAsCString(TypeSummaryImpl *summary_ptr,
593 std::string &destination,
594 const TypeSummaryOptions &options) {
595 destination.clear();
596
597 // ideally we would like to bail out if passing NULL, but if we do so we end
598 // up not providing the summary for function pointers anymore
599 if (/*summary_ptr == NULL ||*/ m_flags.m_is_getting_summary)
600 return false;
601
602 m_flags.m_is_getting_summary = true;
603
604 TypeSummaryOptions actual_options(options);
605
606 if (actual_options.GetLanguage() == lldb::eLanguageTypeUnknown)
607 actual_options.SetLanguage(GetPreferredDisplayLanguage());
608
609 // this is a hot path in code and we prefer to avoid setting this string all
610 // too often also clearing out other information that we might care to see in
611 // a crash log. might be useful in very specific situations though.
612 /*Host::SetCrashDescriptionWithFormat("Trying to fetch a summary for %s %s.
613 Summary provider's description is %s",
614 GetTypeName().GetCString(),
615 GetName().GetCString(),
616 summary_ptr->GetDescription().c_str());*/
617
618 if (UpdateValueIfNeeded(false) && summary_ptr) {
619 if (HasSyntheticValue())
620 m_synthetic_value->UpdateValueIfNeeded(); // the summary might depend on
621 // the synthetic children being
622 // up-to-date (e.g. ${svar%#})
623 summary_ptr->FormatObject(this, destination, actual_options);
624 }
625 m_flags.m_is_getting_summary = false;
626 return !destination.empty();
627}
628
629const char *ValueObject::GetSummaryAsCString(lldb::LanguageType lang) {
630 if (UpdateValueIfNeeded(true) && m_summary_str.empty()) {
631 TypeSummaryOptions summary_options;
632 summary_options.SetLanguage(lang);
633 GetSummaryAsCString(GetSummaryFormat().get(), m_summary_str,
634 summary_options);
635 }
636 if (m_summary_str.empty())
637 return nullptr;
638 return m_summary_str.c_str();
639}
640
641bool ValueObject::GetSummaryAsCString(std::string &destination,
642 const TypeSummaryOptions &options) {
643 return GetSummaryAsCString(GetSummaryFormat().get(), destination, options);
644}
645
646bool ValueObject::IsCStringContainer(bool check_pointer) {
647 CompilerType pointee_or_element_compiler_type;
648 const Flags type_flags(GetTypeInfo(&pointee_or_element_compiler_type));
649 bool is_char_arr_ptr(type_flags.AnySet(eTypeIsArray | eTypeIsPointer) &&
650 pointee_or_element_compiler_type.IsCharType());
651 if (!is_char_arr_ptr)
652 return false;
653 if (!check_pointer)
654 return true;
655 if (type_flags.Test(eTypeIsArray))
656 return true;
657 addr_t cstr_address = LLDB_INVALID_ADDRESS;
658 AddressType cstr_address_type = eAddressTypeInvalid;
659 cstr_address = GetPointerValue(&cstr_address_type);
660 return (cstr_address != LLDB_INVALID_ADDRESS);
661}
662
663size_t ValueObject::GetPointeeData(DataExtractor &data, uint32_t item_idx,
664 uint32_t item_count) {
665 CompilerType pointee_or_element_compiler_type;
666 const uint32_t type_info = GetTypeInfo(&pointee_or_element_compiler_type);
667 const bool is_pointer_type = type_info & eTypeIsPointer;
668 const bool is_array_type = type_info & eTypeIsArray;
669 if (!(is_pointer_type || is_array_type))
670 return 0;
671
672 if (item_count == 0)
673 return 0;
674
675 ExecutionContext exe_ctx(GetExecutionContextRef());
676
677 llvm::Optional<uint64_t> item_type_size =
678 pointee_or_element_compiler_type.GetByteSize(
679 exe_ctx.GetBestExecutionContextScope());
680 if (!item_type_size)
681 return 0;
682 const uint64_t bytes = item_count * *item_type_size;
683 const uint64_t offset = item_idx * *item_type_size;
684
685 if (item_idx == 0 && item_count == 1) // simply a deref
686 {
687 if (is_pointer_type) {
688 Status error;
689 ValueObjectSP pointee_sp = Dereference(error);
690 if (error.Fail() || pointee_sp.get() == nullptr)
691 return 0;
692 return pointee_sp->GetData(data, error);
693 } else {
694 ValueObjectSP child_sp = GetChildAtIndex(0, true);
695 if (child_sp.get() == nullptr)
696 return 0;
697 Status error;
698 return child_sp->GetData(data, error);
699 }
700 return true;
701 } else /* (items > 1) */
702 {
703 Status error;
704 lldb_private::DataBufferHeap *heap_buf_ptr = nullptr;
705 lldb::DataBufferSP data_sp(heap_buf_ptr =
706 new lldb_private::DataBufferHeap());
707
708 AddressType addr_type;
709 lldb::addr_t addr = is_pointer_type ? GetPointerValue(&addr_type)
710 : GetAddressOf(true, &addr_type);
711
712 switch (addr_type) {
713 case eAddressTypeFile: {
714 ModuleSP module_sp(GetModule());
715 if (module_sp) {
716 addr = addr + offset;
717 Address so_addr;
718 module_sp->ResolveFileAddress(addr, so_addr);
719 ExecutionContext exe_ctx(GetExecutionContextRef());
720 Target *target = exe_ctx.GetTargetPtr();
721 if (target) {
722 heap_buf_ptr->SetByteSize(bytes);
723 size_t bytes_read = target->ReadMemory(
724 so_addr, heap_buf_ptr->GetBytes(), bytes, error, true);
725 if (error.Success()) {
726 data.SetData(data_sp);
727 return bytes_read;
728 }
729 }
730 }
731 } break;
732 case eAddressTypeLoad: {
733 ExecutionContext exe_ctx(GetExecutionContextRef());
734 Process *process = exe_ctx.GetProcessPtr();
735 if (process) {
736 heap_buf_ptr->SetByteSize(bytes);
737 size_t bytes_read = process->ReadMemory(
738 addr + offset, heap_buf_ptr->GetBytes(), bytes, error);
739 if (error.Success() || bytes_read > 0) {
740 data.SetData(data_sp);
741 return bytes_read;
742 }
743 }
744 } break;
745 case eAddressTypeHost: {
746 auto max_bytes =
747 GetCompilerType().GetByteSize(exe_ctx.GetBestExecutionContextScope());
748 if (max_bytes && *max_bytes > offset) {
749 size_t bytes_read = std::min<uint64_t>(*max_bytes - offset, bytes);
750 addr = m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
751 if (addr == 0 || addr == LLDB_INVALID_ADDRESS)
752 break;
753 heap_buf_ptr->CopyData((uint8_t *)(addr + offset), bytes_read);
754 data.SetData(data_sp);
755 return bytes_read;
756 }
757 } break;
758 case eAddressTypeInvalid:
759 break;
760 }
761 }
762 return 0;
763}
764
765uint64_t ValueObject::GetData(DataExtractor &data, Status &error) {
766 UpdateValueIfNeeded(false);
767 ExecutionContext exe_ctx(GetExecutionContextRef());
768 error = m_value.GetValueAsData(&exe_ctx, data, GetModule().get());
769 if (error.Fail()) {
770 if (m_data.GetByteSize()) {
771 data = m_data;
772 error.Clear();
773 return data.GetByteSize();
774 } else {
775 return 0;
776 }
777 }
778 data.SetAddressByteSize(m_data.GetAddressByteSize());
779 data.SetByteOrder(m_data.GetByteOrder());
780 return data.GetByteSize();
781}
782
783bool ValueObject::SetData(DataExtractor &data, Status &error) {
784 error.Clear();
785 // Make sure our value is up to date first so that our location and location
786 // type is valid.
787 if (!UpdateValueIfNeeded(false)) {
788 error.SetErrorString("unable to read value");
789 return false;
790 }
791
792 uint64_t count = 0;
793 const Encoding encoding = GetCompilerType().GetEncoding(count);
794
795 const size_t byte_size = GetByteSize().getValueOr(0);
796
797 Value::ValueType value_type = m_value.GetValueType();
798
799 switch (value_type) {
800 case Value::ValueType::Invalid:
801 error.SetErrorString("invalid location");
802 return false;
803 case Value::ValueType::Scalar: {
804 Status set_error =
805 m_value.GetScalar().SetValueFromData(data, encoding, byte_size);
806
807 if (!set_error.Success()) {
808 error.SetErrorStringWithFormat("unable to set scalar value: %s",
809 set_error.AsCString());
810 return false;
811 }
812 } break;
813 case Value::ValueType::LoadAddress: {
814 // If it is a load address, then the scalar value is the storage location
815 // of the data, and we have to shove this value down to that load location.
816 ExecutionContext exe_ctx(GetExecutionContextRef());
817 Process *process = exe_ctx.GetProcessPtr();
818 if (process) {
819 addr_t target_addr = m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
820 size_t bytes_written = process->WriteMemory(
821 target_addr, data.GetDataStart(), byte_size, error);
822 if (!error.Success())
823 return false;
824 if (bytes_written != byte_size) {
825 error.SetErrorString("unable to write value to memory");
826 return false;
827 }
828 }
829 } break;
830 case Value::ValueType::HostAddress: {
831 // If it is a host address, then we stuff the scalar as a DataBuffer into
832 // the Value's data.
833 DataBufferSP buffer_sp(new DataBufferHeap(byte_size, 0));
834 m_data.SetData(buffer_sp, 0);
835 data.CopyByteOrderedData(0, byte_size,
836 const_cast<uint8_t *>(m_data.GetDataStart()),
837 byte_size, m_data.GetByteOrder());
838 m_value.GetScalar() = (uintptr_t)m_data.GetDataStart();
839 } break;
840 case Value::ValueType::FileAddress:
841 break;
842 }
843
844 // If we have reached this point, then we have successfully changed the
845 // value.
846 SetNeedsUpdate();
847 return true;
848}
849
850static bool CopyStringDataToBufferSP(const StreamString &source,
851 lldb::DataBufferSP &destination) {
852 destination = std::make_shared<DataBufferHeap>(source.GetSize() + 1, 0);
853 memcpy(destination->GetBytes(), source.GetString().data(), source.GetSize());
854 return true;
855}
856
857std::pair<size_t, bool>
858ValueObject::ReadPointedString(lldb::DataBufferSP &buffer_sp, Status &error,
859 uint32_t max_length, bool honor_array,
860 Format item_format) {
861 bool was_capped = false;
862 StreamString s;
863 ExecutionContext exe_ctx(GetExecutionContextRef());
864 Target *target = exe_ctx.GetTargetPtr();
865
866 if (!target) {
867 s << "<no target to read from>";
868 error.SetErrorString("no target to read from");
869 CopyStringDataToBufferSP(s, buffer_sp);
870 return {0, was_capped};
871 }
872
873 if (max_length == 0)
874 max_length = target->GetMaximumSizeOfStringSummary();
875
876 size_t bytes_read = 0;
877 size_t total_bytes_read = 0;
878
879 CompilerType compiler_type = GetCompilerType();
880 CompilerType elem_or_pointee_compiler_type;
881 const Flags type_flags(GetTypeInfo(&elem_or_pointee_compiler_type));
882 if (type_flags.AnySet(eTypeIsArray | eTypeIsPointer) &&
883 elem_or_pointee_compiler_type.IsCharType()) {
884 addr_t cstr_address = LLDB_INVALID_ADDRESS;
885 AddressType cstr_address_type = eAddressTypeInvalid;
886
887 size_t cstr_len = 0;
888 bool capped_data = false;
889 const bool is_array = type_flags.Test(eTypeIsArray);
890 if (is_array) {
891 // We have an array
892 uint64_t array_size = 0;
893 if (compiler_type.IsArrayType(nullptr, &array_size)) {
894 cstr_len = array_size;
895 if (cstr_len > max_length) {
896 capped_data = true;
897 cstr_len = max_length;
898 }
899 }
900 cstr_address = GetAddressOf(true, &cstr_address_type);
901 } else {
902 // We have a pointer
903 cstr_address = GetPointerValue(&cstr_address_type);
904 }
905
906 if (cstr_address == 0 || cstr_address == LLDB_INVALID_ADDRESS) {
907 if (cstr_address_type == eAddressTypeHost && is_array) {
908 const char *cstr = GetDataExtractor().PeekCStr(0);
909 if (cstr == nullptr) {
910 s << "<invalid address>";
911 error.SetErrorString("invalid address");
912 CopyStringDataToBufferSP(s, buffer_sp);
913 return {0, was_capped};
914 }
915 buffer_sp = std::make_shared<DataBufferHeap>(cstr_len, 0);
916 memcpy(buffer_sp->GetBytes(), cstr, cstr_len);
917 return {cstr_len, was_capped};
918 } else {
919 s << "<invalid address>";
920 error.SetErrorString("invalid address");
921 CopyStringDataToBufferSP(s, buffer_sp);
922 return {0, was_capped};
923 }
924 }
925
926 Address cstr_so_addr(cstr_address);
927 DataExtractor data;
928 if (cstr_len > 0 && honor_array) {
929 // I am using GetPointeeData() here to abstract the fact that some
930 // ValueObjects are actually frozen pointers in the host but the pointed-
931 // to data lives in the debuggee, and GetPointeeData() automatically
932 // takes care of this
933 GetPointeeData(data, 0, cstr_len);
934
935 if ((bytes_read = data.GetByteSize()) > 0) {
936 total_bytes_read = bytes_read;
937 for (size_t offset = 0; offset < bytes_read; offset++)
938 s.Printf("%c", *data.PeekData(offset, 1));
939 if (capped_data)
940 was_capped = true;
941 }
942 } else {
943 cstr_len = max_length;
944 const size_t k_max_buf_size = 64;
945
946 size_t offset = 0;
947
948 int cstr_len_displayed = -1;
949 bool capped_cstr = false;
950 // I am using GetPointeeData() here to abstract the fact that some
951 // ValueObjects are actually frozen pointers in the host but the pointed-
952 // to data lives in the debuggee, and GetPointeeData() automatically
953 // takes care of this
954 while ((bytes_read = GetPointeeData(data, offset, k_max_buf_size)) > 0) {
955 total_bytes_read += bytes_read;
956 const char *cstr = data.PeekCStr(0);
957 size_t len = strnlen(cstr, k_max_buf_size);
958 if (cstr_len_displayed < 0)
959 cstr_len_displayed = len;
960
961 if (len == 0)
962 break;
963 cstr_len_displayed += len;
964 if (len > bytes_read)
965 len = bytes_read;
966 if (len > cstr_len)
967 len = cstr_len;
968
969 for (size_t offset = 0; offset < bytes_read; offset++)
970 s.Printf("%c", *data.PeekData(offset, 1));
971
972 if (len < k_max_buf_size)
973 break;
974
975 if (len >= cstr_len) {
976 capped_cstr = true;
977 break;
978 }
979
980 cstr_len -= len;
981 offset += len;
982 }
983
984 if (cstr_len_displayed >= 0) {
985 if (capped_cstr)
986 was_capped = true;
987 }
988 }
989 } else {
990 error.SetErrorString("not a string object");
991 s << "<not a string object>";
992 }
993 CopyStringDataToBufferSP(s, buffer_sp);
994 return {total_bytes_read, was_capped};
995}
996
997const char *ValueObject::GetObjectDescription() {
998 if (!UpdateValueIfNeeded(true))
999 return nullptr;
1000
1001 // Return cached value.
1002 if (!m_object_desc_str.empty())
1003 return m_object_desc_str.c_str();
1004
1005 ExecutionContext exe_ctx(GetExecutionContextRef());
1006 Process *process = exe_ctx.GetProcessPtr();
1007 if (!process)
1008 return nullptr;
1009
1010 // Returns the object description produced by one language runtime.
1011 auto get_object_description = [&](LanguageType language) -> const char * {
1012 if (LanguageRuntime *runtime = process->GetLanguageRuntime(language)) {
1013 StreamString s;
1014 if (runtime->GetObjectDescription(s, *this)) {
1015 m_object_desc_str.append(std::string(s.GetString()));
1016 return m_object_desc_str.c_str();
1017 }
1018 }
1019 return nullptr;
1020 };
1021
1022 // Try the native language runtime first.
1023 LanguageType native_language = GetObjectRuntimeLanguage();
1024 if (const char *desc = get_object_description(native_language))
1025 return desc;
1026
1027 // Try the Objective-C language runtime. This fallback is necessary
1028 // for Objective-C++ and mixed Objective-C / C++ programs.
1029 if (Language::LanguageIsCFamily(native_language))
1030 return get_object_description(eLanguageTypeObjC);
1031 return nullptr;
1032}
1033
1034bool ValueObject::GetValueAsCString(const lldb_private::TypeFormatImpl &format,
1035 std::string &destination) {
1036 if (UpdateValueIfNeeded(false))
1037 return format.FormatObject(this, destination);
1038 else
1039 return false;
1040}
1041
1042bool ValueObject::GetValueAsCString(lldb::Format format,
1043 std::string &destination) {
1044 return GetValueAsCString(TypeFormatImpl_Format(format), destination);
1045}
1046
1047const char *ValueObject::GetValueAsCString() {
1048 if (UpdateValueIfNeeded(true)) {
1049 lldb::TypeFormatImplSP format_sp;
1050 lldb::Format my_format = GetFormat();
1051 if (my_format == lldb::eFormatDefault) {
1052 if (m_type_format_sp)
1053 format_sp = m_type_format_sp;
1054 else {
1055 if (m_flags.m_is_bitfield_for_scalar)
1056 my_format = eFormatUnsigned;
1057 else {
1058 if (m_value.GetContextType() == Value::ContextType::RegisterInfo) {
1059 const RegisterInfo *reg_info = m_value.GetRegisterInfo();
1060 if (reg_info)
1061 my_format = reg_info->format;
1062 } else {
1063 my_format = GetValue().GetCompilerType().GetFormat();
1064 }
1065 }
1066 }
1067 }
1068 if (my_format != m_last_format || m_value_str.empty()) {
1069 m_last_format = my_format;
1070 if (!format_sp)
1071 format_sp = std::make_shared<TypeFormatImpl_Format>(my_format);
1072 if (GetValueAsCString(*format_sp.get(), m_value_str)) {
1073 if (!m_flags.m_value_did_change && m_flags.m_old_value_valid) {
1074 // The value was gotten successfully, so we consider the value as
1075 // changed if the value string differs
1076 SetValueDidChange(m_old_value_str != m_value_str);
1077 }
1078 }
1079 }
1080 }
1081 if (m_value_str.empty())
1082 return nullptr;
1083 return m_value_str.c_str();
1084}
1085
1086// if > 8bytes, 0 is returned. this method should mostly be used to read
1087// address values out of pointers
1088uint64_t ValueObject::GetValueAsUnsigned(uint64_t fail_value, bool *success) {
1089 // If our byte size is zero this is an aggregate type that has children
1090 if (CanProvideValue()) {
1091 Scalar scalar;
1092 if (ResolveValue(scalar)) {
1093 if (success)
1094 *success = true;
1095 scalar.MakeUnsigned();
1096 return scalar.ULongLong(fail_value);
1097 }
1098 // fallthrough, otherwise...
1099 }
1100
1101 if (success)
1102 *success = false;
1103 return fail_value;
1104}
1105
1106int64_t ValueObject::GetValueAsSigned(int64_t fail_value, bool *success) {
1107 // If our byte size is zero this is an aggregate type that has children
1108 if (CanProvideValue()) {
1109 Scalar scalar;
1110 if (ResolveValue(scalar)) {
1111 if (success)
1112 *success = true;
1113 scalar.MakeSigned();
1114 return scalar.SLongLong(fail_value);
1115 }
1116 // fallthrough, otherwise...
1117 }
1118
1119 if (success)
1120 *success = false;
1121 return fail_value;
1122}
1123
1124// if any more "special cases" are added to
1125// ValueObject::DumpPrintableRepresentation() please keep this call up to date
1126// by returning true for your new special cases. We will eventually move to
1127// checking this call result before trying to display special cases
1128bool ValueObject::HasSpecialPrintableRepresentation(
1129 ValueObjectRepresentationStyle val_obj_display, Format custom_format) {
1130 Flags flags(GetTypeInfo());
1131 if (flags.AnySet(eTypeIsArray | eTypeIsPointer) &&
1132 val_obj_display == ValueObject::eValueObjectRepresentationStyleValue) {
1133 if (IsCStringContainer(true) &&
1134 (custom_format == eFormatCString || custom_format == eFormatCharArray ||
1135 custom_format == eFormatChar || custom_format == eFormatVectorOfChar))
1136 return true;
1137
1138 if (flags.Test(eTypeIsArray)) {
1139 if ((custom_format == eFormatBytes) ||
1140 (custom_format == eFormatBytesWithASCII))
1141 return true;
1142
1143 if ((custom_format == eFormatVectorOfChar) ||
1144 (custom_format == eFormatVectorOfFloat32) ||
1145 (custom_format == eFormatVectorOfFloat64) ||
1146 (custom_format == eFormatVectorOfSInt16) ||
1147 (custom_format == eFormatVectorOfSInt32) ||
1148 (custom_format == eFormatVectorOfSInt64) ||
1149 (custom_format == eFormatVectorOfSInt8) ||
1150 (custom_format == eFormatVectorOfUInt128) ||
1151 (custom_format == eFormatVectorOfUInt16) ||
1152 (custom_format == eFormatVectorOfUInt32) ||
1153 (custom_format == eFormatVectorOfUInt64) ||
1154 (custom_format == eFormatVectorOfUInt8))
1155 return true;
1156 }
1157 }
1158 return false;
1159}
1160
1161bool ValueObject::DumpPrintableRepresentation(
1162 Stream &s, ValueObjectRepresentationStyle val_obj_display,
1163 Format custom_format, PrintableRepresentationSpecialCases special,
1164 bool do_dump_error) {
1165
1166 Flags flags(GetTypeInfo());
1167
1168 bool allow_special =
1169 (special == ValueObject::PrintableRepresentationSpecialCases::eAllow);
1170 const bool only_special = false;
1171
1172 if (allow_special) {
1173 if (flags.AnySet(eTypeIsArray | eTypeIsPointer) &&
1174 val_obj_display == ValueObject::eValueObjectRepresentationStyleValue) {
1175 // when being asked to get a printable display an array or pointer type
1176 // directly, try to "do the right thing"
1177
1178 if (IsCStringContainer(true) &&
1179 (custom_format == eFormatCString ||
1180 custom_format == eFormatCharArray || custom_format == eFormatChar ||
1181 custom_format ==
1182 eFormatVectorOfChar)) // print char[] & char* directly
1183 {
1184 Status error;
1185 lldb::DataBufferSP buffer_sp;
1186 std::pair<size_t, bool> read_string = ReadPointedString(
1187 buffer_sp, error, 0, (custom_format == eFormatVectorOfChar) ||
1188 (custom_format == eFormatCharArray));
1189 lldb_private::formatters::StringPrinter::
1190 ReadBufferAndDumpToStreamOptions options(*this);
1191 options.SetData(DataExtractor(
1192 buffer_sp, lldb::eByteOrderInvalid,
1193 8)); // none of this matters for a string - pass some defaults
1194 options.SetStream(&s);
1195 options.SetPrefixToken(nullptr);
1196 options.SetQuote('"');
1197 options.SetSourceSize(buffer_sp->GetByteSize());
1198 options.SetIsTruncated(read_string.second);
1199 formatters::StringPrinter::ReadBufferAndDumpToStream<
1200 lldb_private::formatters::StringPrinter::StringElementType::ASCII>(
1201 options);
1202 return !error.Fail();
1203 }
1204
1205 if (custom_format == eFormatEnum)
1206 return false;
1207
1208 // this only works for arrays, because I have no way to know when the
1209 // pointed memory ends, and no special \0 end of data marker
1210 if (flags.Test(eTypeIsArray)) {
1211 if ((custom_format == eFormatBytes) ||
1212 (custom_format == eFormatBytesWithASCII)) {
1213 const size_t count = GetNumChildren();
1214
1215 s << '[';
1216 for (size_t low = 0; low < count; low++) {
1217
1218 if (low)
1219 s << ',';
1220
1221 ValueObjectSP child = GetChildAtIndex(low, true);
1222 if (!child.get()) {
1223 s << "<invalid child>";
1224 continue;
1225 }
1226 child->DumpPrintableRepresentation(
1227 s, ValueObject::eValueObjectRepresentationStyleValue,
1228 custom_format);
1229 }
1230
1231 s << ']';
1232
1233 return true;
1234 }
1235
1236 if ((custom_format == eFormatVectorOfChar) ||
1237 (custom_format == eFormatVectorOfFloat32) ||
1238 (custom_format == eFormatVectorOfFloat64) ||
1239 (custom_format == eFormatVectorOfSInt16) ||
1240 (custom_format == eFormatVectorOfSInt32) ||
1241 (custom_format == eFormatVectorOfSInt64) ||
1242 (custom_format == eFormatVectorOfSInt8) ||
1243 (custom_format == eFormatVectorOfUInt128) ||
1244 (custom_format == eFormatVectorOfUInt16) ||
1245 (custom_format == eFormatVectorOfUInt32) ||
1246 (custom_format == eFormatVectorOfUInt64) ||
1247 (custom_format == eFormatVectorOfUInt8)) // arrays of bytes, bytes
1248 // with ASCII or any vector
1249 // format should be printed
1250 // directly
1251 {
1252 const size_t count = GetNumChildren();
1253
1254 Format format = FormatManager::GetSingleItemFormat(custom_format);
1255
1256 s << '[';
1257 for (size_t low = 0; low < count; low++) {
1258
1259 if (low)
1260 s << ',';
1261
1262 ValueObjectSP child = GetChildAtIndex(low, true);
1263 if (!child.get()) {
1264 s << "<invalid child>";
1265 continue;
1266 }
1267 child->DumpPrintableRepresentation(
1268 s, ValueObject::eValueObjectRepresentationStyleValue, format);
1269 }
1270
1271 s << ']';
1272
1273 return true;
1274 }
1275 }
1276
1277 if ((custom_format == eFormatBoolean) ||
1278 (custom_format == eFormatBinary) || (custom_format == eFormatChar) ||
1279 (custom_format == eFormatCharPrintable) ||
1280 (custom_format == eFormatComplexFloat) ||
1281 (custom_format == eFormatDecimal) || (custom_format == eFormatHex) ||
1282 (custom_format == eFormatHexUppercase) ||
1283 (custom_format == eFormatFloat) || (custom_format == eFormatOctal) ||
1284 (custom_format == eFormatOSType) ||
1285 (custom_format == eFormatUnicode16) ||
1286 (custom_format == eFormatUnicode32) ||
1287 (custom_format == eFormatUnsigned) ||
1288 (custom_format == eFormatPointer) ||
1289 (custom_format == eFormatComplexInteger) ||
1290 (custom_format == eFormatComplex) ||
1291 (custom_format == eFormatDefault)) // use the [] operator
1292 return false;
1293 }
1294 }
1295
1296 if (only_special)
1297 return false;
1298
1299 bool var_success = false;
1300
1301 {
1302 llvm::StringRef str;
1303
1304 // this is a local stream that we are using to ensure that the data pointed
1305 // to by cstr survives long enough for us to copy it to its destination -
1306 // it is necessary to have this temporary storage area for cases where our
1307 // desired output is not backed by some other longer-term storage
1308 StreamString strm;
1309
1310 if (custom_format != eFormatInvalid)
1311 SetFormat(custom_format);
1312
1313 switch (val_obj_display) {
1314 case eValueObjectRepresentationStyleValue:
1315 str = GetValueAsCString();
1316 break;
1317
1318 case eValueObjectRepresentationStyleSummary:
1319 str = GetSummaryAsCString();
1320 break;
1321
1322 case eValueObjectRepresentationStyleLanguageSpecific:
1323 str = GetObjectDescription();
1324 break;
1325
1326 case eValueObjectRepresentationStyleLocation:
1327 str = GetLocationAsCString();
1328 break;
1329
1330 case eValueObjectRepresentationStyleChildrenCount:
1331 strm.Printf("%" PRIu64 "", (uint64_t)GetNumChildren());
1332 str = strm.GetString();
1333 break;
1334
1335 case eValueObjectRepresentationStyleType:
1336 str = GetTypeName().GetStringRef();
1337 break;
1338
1339 case eValueObjectRepresentationStyleName:
1340 str = GetName().GetStringRef();
1341 break;
1342
1343 case eValueObjectRepresentationStyleExpressionPath:
1344 GetExpressionPath(strm);
1345 str = strm.GetString();
1346 break;
1347 }
1348
1349 if (str.empty()) {
1350 if (val_obj_display == eValueObjectRepresentationStyleValue)
1351 str = GetSummaryAsCString();
1352 else if (val_obj_display == eValueObjectRepresentationStyleSummary) {
1353 if (!CanProvideValue()) {
1354 strm.Printf("%s @ %s", GetTypeName().AsCString(),
1355 GetLocationAsCString());
1356 str = strm.GetString();
1357 } else
1358 str = GetValueAsCString();
1359 }
1360 }
1361
1362 if (!str.empty())
1363 s << str;
1364 else {
1365 if (m_error.Fail()) {
1366 if (do_dump_error)
1367 s.Printf("<%s>", m_error.AsCString());
1368 else
1369 return false;
1370 } else if (val_obj_display == eValueObjectRepresentationStyleSummary)
1371 s.PutCString("<no summary available>");
1372 else if (val_obj_display == eValueObjectRepresentationStyleValue)
1373 s.PutCString("<no value available>");
1374 else if (val_obj_display ==
1375 eValueObjectRepresentationStyleLanguageSpecific)
1376 s.PutCString("<not a valid Objective-C object>"); // edit this if we
1377 // have other runtimes
1378 // that support a
1379 // description
1380 else
1381 s.PutCString("<no printable representation>");
1382 }
1383
1384 // we should only return false here if we could not do *anything* even if
1385 // we have an error message as output, that's a success from our callers'
1386 // perspective, so return true
1387 var_success = true;
1388
1389 if (custom_format != eFormatInvalid)
1390 SetFormat(eFormatDefault);
1391 }
1392
1393 return var_success;
1394}
1395
1396addr_t ValueObject::GetAddressOf(bool scalar_is_load_address,
1397 AddressType *address_type) {
1398 // Can't take address of a bitfield
1399 if (IsBitfield())
1400 return LLDB_INVALID_ADDRESS;
1401
1402 if (!UpdateValueIfNeeded(false))
1403 return LLDB_INVALID_ADDRESS;
1404
1405 switch (m_value.GetValueType()) {
1406 case Value::ValueType::Invalid:
1407 return LLDB_INVALID_ADDRESS;
1408 case Value::ValueType::Scalar:
1409 if (scalar_is_load_address) {
1410 if (address_type)
1411 *address_type = eAddressTypeLoad;
1412 return m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
1413 }
1414 break;
1415
1416 case Value::ValueType::LoadAddress:
1417 case Value::ValueType::FileAddress: {
1418 if (address_type)
1419 *address_type = m_value.GetValueAddressType();
1420 return m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
1421 } break;
1422 case Value::ValueType::HostAddress: {
1423 if (address_type)
1424 *address_type = m_value.GetValueAddressType();
1425 return LLDB_INVALID_ADDRESS;
1426 } break;
1427 }
1428 if (address_type)
1429 *address_type = eAddressTypeInvalid;
1430 return LLDB_INVALID_ADDRESS;
1431}
1432
1433addr_t ValueObject::GetPointerValue(AddressType *address_type) {
1434 addr_t address = LLDB_INVALID_ADDRESS;
1435 if (address_type)
1436 *address_type = eAddressTypeInvalid;
1437
1438 if (!UpdateValueIfNeeded(false))
1439 return address;
1440
1441 switch (m_value.GetValueType()) {
1442 case Value::ValueType::Invalid:
1443 return LLDB_INVALID_ADDRESS;
1444 case Value::ValueType::Scalar:
1445 address = m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
1446 break;
1447
1448 case Value::ValueType::HostAddress:
1449 case Value::ValueType::LoadAddress:
1450 case Value::ValueType::FileAddress: {
1451 lldb::offset_t data_offset = 0;
1452 address = m_data.GetAddress(&data_offset);
1453 } break;
1454 }
1455
1456 if (address_type)
1457 *address_type = GetAddressTypeOfChildren();
1458
1459 return address;
1460}
1461
1462bool ValueObject::SetValueFromCString(const char *value_str, Status &error) {
1463 error.Clear();
1464 // Make sure our value is up to date first so that our location and location
1465 // type is valid.
1466 if (!UpdateValueIfNeeded(false)) {
1467 error.SetErrorString("unable to read value");
1468 return false;
1469 }
1470
1471 uint64_t count = 0;
1472 const Encoding encoding = GetCompilerType().GetEncoding(count);
1473
1474 const size_t byte_size = GetByteSize().getValueOr(0);
1475
1476 Value::ValueType value_type = m_value.GetValueType();
1477
1478 if (value_type == Value::ValueType::Scalar) {
1479 // If the value is already a scalar, then let the scalar change itself:
1480 m_value.GetScalar().SetValueFromCString(value_str, encoding, byte_size);
1481 } else if (byte_size <= 16) {
1482 // If the value fits in a scalar, then make a new scalar and again let the
1483 // scalar code do the conversion, then figure out where to put the new
1484 // value.
1485 Scalar new_scalar;
1486 error = new_scalar.SetValueFromCString(value_str, encoding, byte_size);
1487 if (error.Success()) {
1488 switch (value_type) {
1489 case Value::ValueType::LoadAddress: {
1490 // If it is a load address, then the scalar value is the storage
1491 // location of the data, and we have to shove this value down to that
1492 // load location.
1493 ExecutionContext exe_ctx(GetExecutionContextRef());
1494 Process *process = exe_ctx.GetProcessPtr();
1495 if (process) {
1496 addr_t target_addr =
1497 m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
1498 size_t bytes_written = process->WriteScalarToMemory(
1499 target_addr, new_scalar, byte_size, error);
1500 if (!error.Success())
1501 return false;
1502 if (bytes_written != byte_size) {
1503 error.SetErrorString("unable to write value to memory");
1504 return false;
1505 }
1506 }
1507 } break;
1508 case Value::ValueType::HostAddress: {
1509 // If it is a host address, then we stuff the scalar as a DataBuffer
1510 // into the Value's data.
1511 DataExtractor new_data;
1512 new_data.SetByteOrder(m_data.GetByteOrder());
1513
1514 DataBufferSP buffer_sp(new DataBufferHeap(byte_size, 0));
1515 m_data.SetData(buffer_sp, 0);
1516 bool success = new_scalar.GetData(new_data);
1517 if (success) {
1518 new_data.CopyByteOrderedData(
1519 0, byte_size, const_cast<uint8_t *>(m_data.GetDataStart()),
1520 byte_size, m_data.GetByteOrder());
1521 }
1522 m_value.GetScalar() = (uintptr_t)m_data.GetDataStart();
1523
1524 } break;
1525 case Value::ValueType::Invalid:
1526 error.SetErrorString("invalid location");
1527 return false;
1528 case Value::ValueType::FileAddress:
1529 case Value::ValueType::Scalar:
1530 break;
1531 }
1532 } else {
1533 return false;
1534 }
1535 } else {
1536 // We don't support setting things bigger than a scalar at present.
1537 error.SetErrorString("unable to write aggregate data type");
1538 return false;
1539 }
1540
1541 // If we have reached this point, then we have successfully changed the
1542 // value.
1543 SetNeedsUpdate();
1544 return true;
1545}
1546
1547bool ValueObject::GetDeclaration(Declaration &decl) {
1548 decl.Clear();
1549 return false;
1550}
1551
1552void ValueObject::AddSyntheticChild(ConstString key,
1553 ValueObject *valobj) {
1554 m_synthetic_children[key] = valobj;
1555}
1556
1557ValueObjectSP ValueObject::GetSyntheticChild(ConstString key) const {
1558 ValueObjectSP synthetic_child_sp;
1559 std::map<ConstString, ValueObject *>::const_iterator pos =
1560 m_synthetic_children.find(key);
1561 if (pos != m_synthetic_children.end())
1562 synthetic_child_sp = pos->second->GetSP();
1563 return synthetic_child_sp;
1564}
1565
1566bool ValueObject::IsPossibleDynamicType() {
1567 ExecutionContext exe_ctx(GetExecutionContextRef());
1568 Process *process = exe_ctx.GetProcessPtr();
1569 if (process)
1570 return process->IsPossibleDynamicValue(*this);
1571 else
1572 return GetCompilerType().IsPossibleDynamicType(nullptr, true, true);
1573}
1574
1575bool ValueObject::IsRuntimeSupportValue() {
1576 Process *process(GetProcessSP().get());
1577 if (!process)
1578 return false;
1579
1580 // We trust the the compiler did the right thing and marked runtime support
1581 // values as artificial.
1582 if (!GetVariable() || !GetVariable()->IsArtificial())
1583 return false;
1584
1585 if (auto *runtime = process->GetLanguageRuntime(GetVariable()->GetLanguage()))
1586 if (runtime->IsAllowedRuntimeValue(GetName()))
1587 return false;
1588
1589 return true;
1590}
1591
1592bool ValueObject::IsNilReference() {
1593 if (Language *language = Language::FindPlugin(GetObjectRuntimeLanguage())) {
1594 return language->IsNilReference(*this);
1595 }
1596 return false;
1597}
1598
1599bool ValueObject::IsUninitializedReference() {
1600 if (Language *language = Language::FindPlugin(GetObjectRuntimeLanguage())) {
1601 return language->IsUninitializedReference(*this);
1602 }
1603 return false;
1604}
1605
1606// This allows you to create an array member using and index that doesn't not
1607// fall in the normal bounds of the array. Many times structure can be defined
1608// as: struct Collection {
1609// uint32_t item_count;
1610// Item item_array[0];
1611// };
1612// The size of the "item_array" is 1, but many times in practice there are more
1613// items in "item_array".
1614
1615ValueObjectSP ValueObject::GetSyntheticArrayMember(size_t index,
1616 bool can_create) {
1617 ValueObjectSP synthetic_child_sp;
1618 if (IsPointerType() || IsArrayType()) {
1619 std::string index_str = llvm::formatv("[{0}]", index);
1620 ConstString index_const_str(index_str);
1621 // Check if we have already created a synthetic array member in this valid
1622 // object. If we have we will re-use it.
1623 synthetic_child_sp = GetSyntheticChild(index_const_str);
1624 if (!synthetic_child_sp) {
1625 ValueObject *synthetic_child;
1626 // We haven't made a synthetic array member for INDEX yet, so lets make
1627 // one and cache it for any future reference.
1628 synthetic_child = CreateChildAtIndex(0, true, index);
1629
1630 // Cache the value if we got one back...
1631 if (synthetic_child) {
1632 AddSyntheticChild(index_const_str, synthetic_child);
1633 synthetic_child_sp = synthetic_child->GetSP();
1634 synthetic_child_sp->SetName(ConstString(index_str));
1635 synthetic_child_sp->m_flags.m_is_array_item_for_pointer = true;
1636 }
1637 }
1638 }
1639 return synthetic_child_sp;
1640}
1641
1642ValueObjectSP ValueObject::GetSyntheticBitFieldChild(uint32_t from, uint32_t to,
1643 bool can_create) {
1644 ValueObjectSP synthetic_child_sp;
1645 if (IsScalarType()) {
1646 std::string index_str = llvm::formatv("[{0}-{1}]", from, to);
1647 ConstString index_const_str(index_str);
1648 // Check if we have already created a synthetic array member in this valid
1649 // object. If we have we will re-use it.
1650 synthetic_child_sp = GetSyntheticChild(index_const_str);
1651 if (!synthetic_child_sp) {
1652 uint32_t bit_field_size = to - from + 1;
1653 uint32_t bit_field_offset = from;
1654 if (GetDataExtractor().GetByteOrder() == eByteOrderBig)
1655 bit_field_offset =
1656 GetByteSize().getValueOr(0) * 8 - bit_field_size - bit_field_offset;
1657 // We haven't made a synthetic array member for INDEX yet, so lets make
1658 // one and cache it for any future reference.
1659 ValueObjectChild *synthetic_child = new ValueObjectChild(
1660 *this, GetCompilerType(), index_const_str,
1661 GetByteSize().getValueOr(0), 0, bit_field_size, bit_field_offset,
1662 false, false, eAddressTypeInvalid, 0);
1663
1664 // Cache the value if we got one back...
1665 if (synthetic_child) {
1666 AddSyntheticChild(index_const_str, synthetic_child);
1667 synthetic_child_sp = synthetic_child->GetSP();
1668 synthetic_child_sp->SetName(ConstString(index_str));
1669 synthetic_child_sp->m_flags.m_is_bitfield_for_scalar = true;
1670 }
1671 }
1672 }
1673 return synthetic_child_sp;
1674}
1675
1676ValueObjectSP ValueObject::GetSyntheticChildAtOffset(
1677 uint32_t offset, const CompilerType &type, bool can_create,
1678 ConstString name_const_str) {
1679
1680 ValueObjectSP synthetic_child_sp;
1681
1682 if (name_const_str.IsEmpty()) {
1683 name_const_str.SetString("@" + std::to_string(offset));
1684 }
1685
1686 // Check if we have already created a synthetic array member in this valid
1687 // object. If we have we will re-use it.
1688 synthetic_child_sp = GetSyntheticChild(name_const_str);
1689
1690 if (synthetic_child_sp.get())
1691 return synthetic_child_sp;
1692
1693 if (!can_create)
1694 return {};
1695
1696 ExecutionContext exe_ctx(GetExecutionContextRef());
1697 llvm::Optional<uint64_t> size =
1698 type.GetByteSize(exe_ctx.GetBestExecutionContextScope());
1699 if (!size)
1700 return {};
1701 ValueObjectChild *synthetic_child =
1702 new ValueObjectChild(*this, type, name_const_str, *size, offset, 0, 0,
1703 false, false, eAddressTypeInvalid, 0);
1704 if (synthetic_child) {
1705 AddSyntheticChild(name_const_str, synthetic_child);
1706 synthetic_child_sp = synthetic_child->GetSP();
1707 synthetic_child_sp->SetName(name_const_str);
1708 synthetic_child_sp->m_flags.m_is_child_at_offset = true;
1709 }
1710 return synthetic_child_sp;
1711}
1712
1713ValueObjectSP ValueObject::GetSyntheticBase(uint32_t offset,
1714 const CompilerType &type,
1715 bool can_create,
1716 ConstString name_const_str) {
1717 ValueObjectSP synthetic_child_sp;
1718
1719 if (name_const_str.IsEmpty()) {
1720 char name_str[128];
1721 snprintf(name_str, sizeof(name_str), "base%s@%i",
1722 type.GetTypeName().AsCString("<unknown>"), offset);
1723 name_const_str.SetCString(name_str);
1724 }
1725
1726 // Check if we have already created a synthetic array member in this valid
1727 // object. If we have we will re-use it.
1728 synthetic_child_sp = GetSyntheticChild(name_const_str);
1729
1730 if (synthetic_child_sp.get())
1731 return synthetic_child_sp;
1732
1733 if (!can_create)
1734 return {};
1735
1736 const bool is_base_class = true;
1737
1738 ExecutionContext exe_ctx(GetExecutionContextRef());
1739 llvm::Optional<uint64_t> size =
1740 type.GetByteSize(exe_ctx.GetBestExecutionContextScope());
1741 if (!size)
1742 return {};
1743 ValueObjectChild *synthetic_child =
1744 new ValueObjectChild(*this, type, name_const_str, *size, offset, 0, 0,
1745 is_base_class, false, eAddressTypeInvalid, 0);
1746 if (synthetic_child) {
1747 AddSyntheticChild(name_const_str, synthetic_child);
1748 synthetic_child_sp = synthetic_child->GetSP();
1749 synthetic_child_sp->SetName(name_const_str);
1750 }
1751 return synthetic_child_sp;
1752}
1753
1754// your expression path needs to have a leading . or -> (unless it somehow
1755// "looks like" an array, in which case it has a leading [ symbol). while the [
1756// is meaningful and should be shown to the user, . and -> are just parser
1757// design, but by no means added information for the user.. strip them off
1758static const char *SkipLeadingExpressionPathSeparators(const char *expression) {
1759 if (!expression || !expression[0])
1760 return expression;
1761 if (expression[0] == '.')
1762 return expression + 1;
1763 if (expression[0] == '-' && expression[1] == '>')
1764 return expression + 2;
1765 return expression;
1766}
1767
1768ValueObjectSP
1769ValueObject::GetSyntheticExpressionPathChild(const char *expression,
1770 bool can_create) {
1771 ValueObjectSP synthetic_child_sp;
1772 ConstString name_const_string(expression);
1773 // Check if we have already created a synthetic array member in this valid
1774 // object. If we have we will re-use it.
1775 synthetic_child_sp = GetSyntheticChild(name_const_string);
1776 if (!synthetic_child_sp) {
1777 // We haven't made a synthetic array member for expression yet, so lets
1778 // make one and cache it for any future reference.
1779 synthetic_child_sp = GetValueForExpressionPath(
1780 expression, nullptr, nullptr,
1781 GetValueForExpressionPathOptions().SetSyntheticChildrenTraversal(
1782 GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
1783 None));
1784
1785 // Cache the value if we got one back...
1786 if (synthetic_child_sp.get()) {
1787 // FIXME: this causes a "real" child to end up with its name changed to
1788 // the contents of expression
1789 AddSyntheticChild(name_const_string, synthetic_child_sp.get());
1790 synthetic_child_sp->SetName(
1791 ConstString(SkipLeadingExpressionPathSeparators(expression)));
1792 }
1793 }
1794 return synthetic_child_sp;
1795}
1796
1797void ValueObject::CalculateSyntheticValue() {
1798 TargetSP target_sp(GetTargetSP());
1799 if (target_sp && !target_sp->GetEnableSyntheticValue()) {
1800 m_synthetic_value = nullptr;
1801 return;
1802 }
1803
1804 lldb::SyntheticChildrenSP current_synth_sp(m_synthetic_children_sp);
1805
1806 if (!UpdateFormatsIfNeeded() && m_synthetic_value)
1807 return;
1808
1809 if (m_synthetic_children_sp.get() == nullptr)
1810 return;
1811
1812 if (current_synth_sp == m_synthetic_children_sp && m_synthetic_value)
1813 return;
1814
1815 m_synthetic_value = new ValueObjectSynthetic(*this, m_synthetic_children_sp);
1816}
1817
1818void ValueObject::CalculateDynamicValue(DynamicValueType use_dynamic) {
1819 if (use_dynamic == eNoDynamicValues)
1820 return;
1821
1822 if (!m_dynamic_value && !IsDynamic()) {
1823 ExecutionContext exe_ctx(GetExecutionContextRef());
1824 Process *process = exe_ctx.GetProcessPtr();
1825 if (process && process->IsPossibleDynamicValue(*this)) {
1826 ClearDynamicTypeInformation();
1827 m_dynamic_value = new ValueObjectDynamicValue(*this, use_dynamic);
1828 }
1829 }
1830}
1831
1832ValueObjectSP ValueObject::GetDynamicValue(DynamicValueType use_dynamic) {
1833 if (use_dynamic == eNoDynamicValues)
1834 return ValueObjectSP();
1835
1836 if (!IsDynamic() && m_dynamic_value == nullptr) {
1837 CalculateDynamicValue(use_dynamic);
1838 }
1839 if (m_dynamic_value)
1840 return m_dynamic_value->GetSP();
1841 else
1842 return ValueObjectSP();
1843}
1844
1845ValueObjectSP ValueObject::GetSyntheticValue() {
1846 CalculateSyntheticValue();
1847
1848 if (m_synthetic_value)
1849 return m_synthetic_value->GetSP();
1850 else
1851 return ValueObjectSP();
1852}
1853
1854bool ValueObject::HasSyntheticValue() {
1855 UpdateFormatsIfNeeded();
1856
1857 if (m_synthetic_children_sp.get() == nullptr)
1858 return false;
1859
1860 CalculateSyntheticValue();
1861
1862 return m_synthetic_value != nullptr;
1863}
1864
1865ValueObject *ValueObject::GetNonBaseClassParent() {
1866 if (GetParent()) {
1867 if (GetParent()->IsBaseClass())
1868 return GetParent()->GetNonBaseClassParent();
1869 else
1870 return GetParent();
1871 }
1872 return nullptr;
1873}
1874
1875bool ValueObject::IsBaseClass(uint32_t &depth) {
1876 if (!IsBaseClass()) {
1877 depth = 0;
1878 return false;
1879 }
1880 if (GetParent()) {
1881 GetParent()->IsBaseClass(depth);
1882 depth = depth + 1;
1883 return true;
1884 }
1885 // TODO: a base of no parent? weird..
1886 depth = 1;
1887 return true;
1888}
1889
1890void ValueObject::GetExpressionPath(Stream &s,
1891 GetExpressionPathFormat epformat) {
1892 // synthetic children do not actually "exist" as part of the hierarchy, and
1893 // sometimes they are consed up in ways that don't make sense from an
1894 // underlying language/API standpoint. So, use a special code path here to
1895 // return something that can hopefully be used in expression
1896 if (m_flags.m_is_synthetic_children_generated) {
1897 UpdateValueIfNeeded();
1898
1899 if (m_value.GetValueType() == Value::ValueType::LoadAddress) {
1900 if (IsPointerOrReferenceType()) {
1901 s.Printf("((%s)0x%" PRIx64 ")", GetTypeName().AsCString("void"),
1902 GetValueAsUnsigned(0));
1903 return;
1904 } else {
1905 uint64_t load_addr =
1906 m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
1907 if (load_addr != LLDB_INVALID_ADDRESS) {
1908 s.Printf("(*( (%s *)0x%" PRIx64 "))", GetTypeName().AsCString("void"),
1909 load_addr);
1910 return;
1911 }
1912 }
1913 }
1914
1915 if (CanProvideValue()) {
1916 s.Printf("((%s)%s)", GetTypeName().AsCString("void"),
1917 GetValueAsCString());
1918 return;
1919 }
1920
1921 return;
1922 }
1923
1924 const bool is_deref_of_parent = IsDereferenceOfParent();
1925
1926 if (is_deref_of_parent &&
1927 epformat == eGetExpressionPathFormatDereferencePointers) {
1928 // this is the original format of GetExpressionPath() producing code like
1929 // *(a_ptr).memberName, which is entirely fine, until you put this into
1930 // StackFrame::GetValueForVariableExpressionPath() which prefers to see
1931 // a_ptr->memberName. the eHonorPointers mode is meant to produce strings
1932 // in this latter format
1933 s.PutCString("*(");
1934 }
1935
1936 ValueObject *parent = GetParent();
1937
1938 if (parent)
1939 parent->GetExpressionPath(s, epformat);
1940
1941 // if we are a deref_of_parent just because we are synthetic array members
1942 // made up to allow ptr[%d] syntax to work in variable printing, then add our
1943 // name ([%d]) to the expression path
1944 if (m_flags.m_is_array_item_for_pointer &&
1945 epformat == eGetExpressionPathFormatHonorPointers)
1946 s.PutCString(m_name.GetStringRef());
1947
1948 if (!IsBaseClass()) {
1949 if (!is_deref_of_parent) {
1950 ValueObject *non_base_class_parent = GetNonBaseClassParent();
1951 if (non_base_class_parent &&
1952 !non_base_class_parent->GetName().IsEmpty()) {
1953 CompilerType non_base_class_parent_compiler_type =
1954 non_base_class_parent->GetCompilerType();
1955 if (non_base_class_parent_compiler_type) {
1956 if (parent && parent->IsDereferenceOfParent() &&
1957 epformat == eGetExpressionPathFormatHonorPointers) {
1958 s.PutCString("->");
1959 } else {
1960 const uint32_t non_base_class_parent_type_info =
1961 non_base_class_parent_compiler_type.GetTypeInfo();
1962
1963 if (non_base_class_parent_type_info & eTypeIsPointer) {
1964 s.PutCString("->");
1965 } else if ((non_base_class_parent_type_info & eTypeHasChildren) &&
1966 !(non_base_class_parent_type_info & eTypeIsArray)) {
1967 s.PutChar('.');
1968 }
1969 }
1970 }
1971 }
1972
1973 const char *name = GetName().GetCString();
1974 if (name)
1975 s.PutCString(name);
1976 }
1977 }
1978
1979 if (is_deref_of_parent &&
1980 epformat == eGetExpressionPathFormatDereferencePointers) {
1981 s.PutChar(')');
1982 }
1983}
1984
1985ValueObjectSP ValueObject::GetValueForExpressionPath(
1986 llvm::StringRef expression, ExpressionPathScanEndReason *reason_to_stop,
1987 ExpressionPathEndResultType *final_value_type,
1988 const GetValueForExpressionPathOptions &options,
1989 ExpressionPathAftermath *final_task_on_target) {
1990
1991 ExpressionPathScanEndReason dummy_reason_to_stop =
1992 ValueObject::eExpressionPathScanEndReasonUnknown;
1993 ExpressionPathEndResultType dummy_final_value_type =
1994 ValueObject::eExpressionPathEndResultTypeInvalid;
1995 ExpressionPathAftermath dummy_final_task_on_target =
1996 ValueObject::eExpressionPathAftermathNothing;
1997
1998 ValueObjectSP ret_val = GetValueForExpressionPath_Impl(
1999 expression, reason_to_stop ? reason_to_stop : &dummy_reason_to_stop,
2000 final_value_type ? final_value_type : &dummy_final_value_type, options,
2001 final_task_on_target ? final_task_on_target
2002 : &dummy_final_task_on_target);
2003
2004 if (!final_task_on_target ||
2005 *final_task_on_target == ValueObject::eExpressionPathAftermathNothing)
2006 return ret_val;
2007
2008 if (ret_val.get() &&
2009 ((final_value_type ? *final_value_type : dummy_final_value_type) ==
2010 eExpressionPathEndResultTypePlain)) // I can only deref and takeaddress
2011 // of plain objects
2012 {
2013 if ((final_task_on_target ? *final_task_on_target
2014 : dummy_final_task_on_target) ==
2015 ValueObject::eExpressionPathAftermathDereference) {
2016 Status error;
2017 ValueObjectSP final_value = ret_val->Dereference(error);
2018 if (error.Fail() || !final_value.get()) {
2019 if (reason_to_stop)
2020 *reason_to_stop =
2021 ValueObject::eExpressionPathScanEndReasonDereferencingFailed;
2022 if (final_value_type)
2023 *final_value_type = ValueObject::eExpressionPathEndResultTypeInvalid;
2024 return ValueObjectSP();
2025 } else {
2026 if (final_task_on_target)
2027 *final_task_on_target = ValueObject::eExpressionPathAftermathNothing;
2028 return final_value;
2029 }
2030 }
2031 if (*final_task_on_target ==
2032 ValueObject::eExpressionPathAftermathTakeAddress) {
2033 Status error;
2034 ValueObjectSP final_value = ret_val->AddressOf(error);
2035 if (error.Fail() || !final_value.get()) {
2036 if (reason_to_stop)
2037 *reason_to_stop =
2038 ValueObject::eExpressionPathScanEndReasonTakingAddressFailed;
2039 if (final_value_type)
2040 *final_value_type = ValueObject::eExpressionPathEndResultTypeInvalid;
2041 return ValueObjectSP();
2042 } else {
2043 if (final_task_on_target)
2044 *final_task_on_target = ValueObject::eExpressionPathAftermathNothing;
2045 return final_value;
2046 }
2047 }
2048 }
2049 return ret_val; // final_task_on_target will still have its original value, so
2050 // you know I did not do it
2051}
2052
2053ValueObjectSP ValueObject::GetValueForExpressionPath_Impl(
2054 llvm::StringRef expression, ExpressionPathScanEndReason *reason_to_stop,
2055 ExpressionPathEndResultType *final_result,
2056 const GetValueForExpressionPathOptions &options,
2057 ExpressionPathAftermath *what_next) {
2058 ValueObjectSP root = GetSP();
2059
2060 if (!root)
2061 return nullptr;
2062
2063 llvm::StringRef remainder = expression;
2064
2065 while (true) {
2066 llvm::StringRef temp_expression = remainder;
2067
2068 CompilerType root_compiler_type = root->GetCompilerType();
2069 CompilerType pointee_compiler_type;
2070 Flags pointee_compiler_type_info;
2071
2072 Flags root_compiler_type_info(
2073 root_compiler_type.GetTypeInfo(&pointee_compiler_type));
2074 if (pointee_compiler_type)
2075 pointee_compiler_type_info.Reset(pointee_compiler_type.GetTypeInfo());
2076
2077 if (temp_expression.empty()) {
2078 *reason_to_stop = ValueObject::eExpressionPathScanEndReasonEndOfString;
2079 return root;
2080 }
2081
2082 switch (temp_expression.front()) {
2083 case '-': {
2084 temp_expression = temp_expression.drop_front();
2085 if (options.m_check_dot_vs_arrow_syntax &&
2086 root_compiler_type_info.Test(eTypeIsPointer)) // if you are trying to
2087 // use -> on a
2088 // non-pointer and I
2089 // must catch the error
2090 {
2091 *reason_to_stop =
2092 ValueObject::eExpressionPathScanEndReasonArrowInsteadOfDot;
2093 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2094 return ValueObjectSP();
2095 }
2096 if (root_compiler_type_info.Test(eTypeIsObjC) && // if yo are trying to
2097 // extract an ObjC IVar
2098 // when this is forbidden
2099 root_compiler_type_info.Test(eTypeIsPointer) &&
2100 options.m_no_fragile_ivar) {
2101 *reason_to_stop =
2102 ValueObject::eExpressionPathScanEndReasonFragileIVarNotAllowed;
2103 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2104 return ValueObjectSP();
2105 }
2106 if (!temp_expression.startswith(">")) {
2107 *reason_to_stop =
2108 ValueObject::eExpressionPathScanEndReasonUnexpectedSymbol;
2109 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2110 return ValueObjectSP();
2111 }
2112 }
2113 LLVM_FALLTHROUGH;
2114 case '.': // or fallthrough from ->
2115 {
2116 if (options.m_check_dot_vs_arrow_syntax &&
2117 temp_expression.front() == '.' &&
2118 root_compiler_type_info.Test(eTypeIsPointer)) // if you are trying to
2119 // use . on a pointer
2120 // and I must catch the
2121 // error
2122 {
2123 *reason_to_stop =
2124 ValueObject::eExpressionPathScanEndReasonDotInsteadOfArrow;
2125 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2126 return nullptr;
2127 }
2128 temp_expression = temp_expression.drop_front(); // skip . or >
2129
2130 size_t next_sep_pos = temp_expression.find_first_of("-.[", 1);
2131 ConstString child_name;
2132 if (next_sep_pos == llvm::StringRef::npos) // if no other separator just
2133 // expand this last layer
2134 {
2135 child_name.SetString(temp_expression);
2136 ValueObjectSP child_valobj_sp =
2137 root->GetChildMemberWithName(child_name, true);
2138
2139 if (child_valobj_sp.get()) // we know we are done, so just return
2140 {
2141 *reason_to_stop =
2142 ValueObject::eExpressionPathScanEndReasonEndOfString;
2143 *final_result = ValueObject::eExpressionPathEndResultTypePlain;
2144 return child_valobj_sp;
2145 } else {
2146 switch (options.m_synthetic_children_traversal) {
2147 case GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2148 None:
2149 break;
2150 case GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2151 FromSynthetic:
2152 if (root->IsSynthetic()) {
2153 child_valobj_sp = root->GetNonSyntheticValue();
2154 if (child_valobj_sp.get())
2155 child_valobj_sp =
2156 child_valobj_sp->GetChildMemberWithName(child_name, true);
2157 }
2158 break;
2159 case GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2160 ToSynthetic:
2161 if (!root->IsSynthetic()) {
2162 child_valobj_sp = root->GetSyntheticValue();
2163 if (child_valobj_sp.get())
2164 child_valobj_sp =
2165 child_valobj_sp->GetChildMemberWithName(child_name, true);
2166 }
2167 break;
2168 case GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2169 Both:
2170 if (root->IsSynthetic()) {
2171 child_valobj_sp = root->GetNonSyntheticValue();
2172 if (child_valobj_sp.get())
2173 child_valobj_sp =
2174 child_valobj_sp->GetChildMemberWithName(child_name, true);
2175 } else {
2176 child_valobj_sp = root->GetSyntheticValue();
2177 if (child_valobj_sp.get())
2178 child_valobj_sp =
2179 child_valobj_sp->GetChildMemberWithName(child_name, true);
2180 }
2181 break;
2182 }
2183 }
2184
2185 // if we are here and options.m_no_synthetic_children is true,
2186 // child_valobj_sp is going to be a NULL SP, so we hit the "else"
2187 // branch, and return an error
2188 if (child_valobj_sp.get()) // if it worked, just return
2189 {
2190 *reason_to_stop =
2191 ValueObject::eExpressionPathScanEndReasonEndOfString;
2192 *final_result = ValueObject::eExpressionPathEndResultTypePlain;
2193 return child_valobj_sp;
2194 } else {
2195 *reason_to_stop =
2196 ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2197 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2198 return nullptr;
2199 }
2200 } else // other layers do expand
2201 {
2202 llvm::StringRef next_separator = temp_expression.substr(next_sep_pos);
2203
2204 child_name.SetString(temp_expression.slice(0, next_sep_pos));
2205
2206 ValueObjectSP child_valobj_sp =
2207 root->GetChildMemberWithName(child_name, true);
2208 if (child_valobj_sp.get()) // store the new root and move on
2209 {
2210 root = child_valobj_sp;
2211 remainder = next_separator;
2212 *final_result = ValueObject::eExpressionPathEndResultTypePlain;
2213 continue;
2214 } else {
2215 switch (options.m_synthetic_children_traversal) {
2216 case GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2217 None:
2218 break;
2219 case GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2220 FromSynthetic:
2221 if (root->IsSynthetic()) {
2222 child_valobj_sp = root->GetNonSyntheticValue();
2223 if (child_valobj_sp.get())
2224 child_valobj_sp =
2225 child_valobj_sp->GetChildMemberWithName(child_name, true);
2226 }
2227 break;
2228 case GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2229 ToSynthetic:
2230 if (!root->IsSynthetic()) {
2231 child_valobj_sp = root->GetSyntheticValue();
2232 if (child_valobj_sp.get())
2233 child_valobj_sp =
2234 child_valobj_sp->GetChildMemberWithName(child_name, true);
2235 }
2236 break;
2237 case GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2238 Both:
2239 if (root->IsSynthetic()) {
2240 child_valobj_sp = root->GetNonSyntheticValue();
2241 if (child_valobj_sp.get())
2242 child_valobj_sp =
2243 child_valobj_sp->GetChildMemberWithName(child_name, true);
2244 } else {
2245 child_valobj_sp = root->GetSyntheticValue();
2246 if (child_valobj_sp.get())
2247 child_valobj_sp =
2248 child_valobj_sp->GetChildMemberWithName(child_name, true);
2249 }
2250 break;
2251 }
2252 }
2253
2254 // if we are here and options.m_no_synthetic_children is true,
2255 // child_valobj_sp is going to be a NULL SP, so we hit the "else"
2256 // branch, and return an error
2257 if (child_valobj_sp.get()) // if it worked, move on
2258 {
2259 root = child_valobj_sp;
2260 remainder = next_separator;
2261 *final_result = ValueObject::eExpressionPathEndResultTypePlain;
2262 continue;
2263 } else {
2264 *reason_to_stop =
2265 ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2266 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2267 return nullptr;
2268 }
2269 }
2270 break;
2271 }
2272 case '[': {
2273 if (!root_compiler_type_info.Test(eTypeIsArray) &&
2274 !root_compiler_type_info.Test(eTypeIsPointer) &&
2275 !root_compiler_type_info.Test(
2276 eTypeIsVector)) // if this is not a T[] nor a T*
2277 {
2278 if (!root_compiler_type_info.Test(
2279 eTypeIsScalar)) // if this is not even a scalar...
2280 {
2281 if (options.m_synthetic_children_traversal ==
2282 GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2283 None) // ...only chance left is synthetic
2284 {
2285 *reason_to_stop =
2286 ValueObject::eExpressionPathScanEndReasonRangeOperatorInvalid;
2287 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2288 return ValueObjectSP();
2289 }
2290 } else if (!options.m_allow_bitfields_syntax) // if this is a scalar,
2291 // check that we can
2292 // expand bitfields
2293 {
2294 *reason_to_stop =
2295 ValueObject::eExpressionPathScanEndReasonRangeOperatorNotAllowed;
2296 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2297 return ValueObjectSP();
2298 }
2299 }
2300 if (temp_expression[1] ==
2301 ']') // if this is an unbounded range it only works for arrays
2302 {
2303 if (!root_compiler_type_info.Test(eTypeIsArray)) {
2304 *reason_to_stop =
2305 ValueObject::eExpressionPathScanEndReasonEmptyRangeNotAllowed;
2306 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2307 return nullptr;
2308 } else // even if something follows, we cannot expand unbounded ranges,
2309 // just let the caller do it
2310 {
2311 *reason_to_stop =
2312 ValueObject::eExpressionPathScanEndReasonArrayRangeOperatorMet;
2313 *final_result =
2314 ValueObject::eExpressionPathEndResultTypeUnboundedRange;
2315 return root;
2316 }
2317 }
2318
2319 size_t close_bracket_position = temp_expression.find(']', 1);
2320 if (close_bracket_position ==
2321 llvm::StringRef::npos) // if there is no ], this is a syntax error
2322 {
2323 *reason_to_stop =
2324 ValueObject::eExpressionPathScanEndReasonUnexpectedSymbol;
2325 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2326 return nullptr;
2327 }
2328
2329 llvm::StringRef bracket_expr =
2330 temp_expression.slice(1, close_bracket_position);
2331
2332 // If this was an empty expression it would have been caught by the if
2333 // above.
2334 assert(!bracket_expr.empty());
2335
2336 if (!bracket_expr.contains('-')) {
2337 // if no separator, this is of the form [N]. Note that this cannot be
2338 // an unbounded range of the form [], because that case was handled
2339 // above with an unconditional return.
2340 unsigned long index = 0;
2341 if (bracket_expr.getAsInteger(0, index)) {
2342 *reason_to_stop =
2343 ValueObject::eExpressionPathScanEndReasonUnexpectedSymbol;
2344 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2345 return nullptr;
2346 }
2347
2348 // from here on we do have a valid index
2349 if (root_compiler_type_info.Test(eTypeIsArray)) {
2350 ValueObjectSP child_valobj_sp = root->GetChildAtIndex(index, true);
2351 if (!child_valobj_sp)
2352 child_valobj_sp = root->GetSyntheticArrayMember(index, true);
2353 if (!child_valobj_sp)
2354 if (root->HasSyntheticValue() &&
2355 root->GetSyntheticValue()->GetNumChildren() > index)
2356 child_valobj_sp =
2357 root->GetSyntheticValue()->GetChildAtIndex(index, true);
2358 if (child_valobj_sp) {
2359 root = child_valobj_sp;
2360 remainder =
2361 temp_expression.substr(close_bracket_position + 1); // skip ]
2362 *final_result = ValueObject::eExpressionPathEndResultTypePlain;
2363 continue;
2364 } else {
2365 *reason_to_stop =
2366 ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2367 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2368 return nullptr;
2369 }
2370 } else if (root_compiler_type_info.Test(eTypeIsPointer)) {
2371 if (*what_next ==
2372 ValueObject::
2373 eExpressionPathAftermathDereference && // if this is a
2374 // ptr-to-scalar, I
2375 // am accessing it
2376 // by index and I
2377 // would have
2378 // deref'ed anyway,
2379 // then do it now
2380 // and use this as
2381 // a bitfield
2382 pointee_compiler_type_info.Test(eTypeIsScalar)) {
2383 Status error;
2384 root = root->Dereference(error);
2385 if (error.Fail() || !root) {
2386 *reason_to_stop =
2387 ValueObject::eExpressionPathScanEndReasonDereferencingFailed;
2388 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2389 return nullptr;
2390 } else {
2391 *what_next = eExpressionPathAftermathNothing;
2392 continue;
2393 }
2394 } else {
2395 if (root->GetCompilerType().GetMinimumLanguage() ==
2396 eLanguageTypeObjC &&
2397 pointee_compiler_type_info.AllClear(eTypeIsPointer) &&
2398 root->HasSyntheticValue() &&
2399 (options.m_synthetic_children_traversal ==
2400 GetValueForExpressionPathOptions::
2401 SyntheticChildrenTraversal::ToSynthetic ||
2402 options.m_synthetic_children_traversal ==
2403 GetValueForExpressionPathOptions::
2404 SyntheticChildrenTraversal::Both)) {
2405 root = root->GetSyntheticValue()->GetChildAtIndex(index, true);
2406 } else
2407 root = root->GetSyntheticArrayMember(index, true);
2408 if (!root) {
2409 *reason_to_stop =
2410 ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2411 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2412 return nullptr;
2413 } else {
2414 remainder =
2415 temp_expression.substr(close_bracket_position + 1); // skip ]
2416 *final_result = ValueObject::eExpressionPathEndResultTypePlain;
2417 continue;
2418 }
2419 }
2420 } else if (root_compiler_type_info.Test(eTypeIsScalar)) {
2421 root = root->GetSyntheticBitFieldChild(index, index, true);
2422 if (!root) {
2423 *reason_to_stop =
2424 ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2425 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2426 return nullptr;
2427 } else // we do not know how to expand members of bitfields, so we
2428 // just return and let the caller do any further processing
2429 {
2430 *reason_to_stop = ValueObject::
2431 eExpressionPathScanEndReasonBitfieldRangeOperatorMet;
2432 *final_result = ValueObject::eExpressionPathEndResultTypeBitfield;
2433 return root;
2434 }
2435 } else if (root_compiler_type_info.Test(eTypeIsVector)) {
2436 root = root->GetChildAtIndex(index, true);
2437 if (!root) {
2438 *reason_to_stop =
2439 ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2440 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2441 return ValueObjectSP();
2442 } else {
2443 remainder =
2444 temp_expression.substr(close_bracket_position + 1); // skip ]
2445 *final_result = ValueObject::eExpressionPathEndResultTypePlain;
2446 continue;
2447 }
2448 } else if (options.m_synthetic_children_traversal ==
2449 GetValueForExpressionPathOptions::
2450 SyntheticChildrenTraversal::ToSynthetic ||
2451 options.m_synthetic_children_traversal ==
2452 GetValueForExpressionPathOptions::
2453 SyntheticChildrenTraversal::Both) {
2454 if (root->HasSyntheticValue())
2455 root = root->GetSyntheticValue();
2456 else if (!root->IsSynthetic()) {
2457 *reason_to_stop =
2458 ValueObject::eExpressionPathScanEndReasonSyntheticValueMissing;
2459 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2460 return nullptr;
2461 }
2462 // if we are here, then root itself is a synthetic VO.. should be
2463 // good to go
2464
2465 if (!root) {
2466 *reason_to_stop =
2467 ValueObject::eExpressionPathScanEndReasonSyntheticValueMissing;
2468 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2469 return nullptr;
2470 }
2471 root = root->GetChildAtIndex(index, true);
2472 if (!root) {
2473 *reason_to_stop =
2474 ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2475 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2476 return nullptr;
2477 } else {
2478 remainder =
2479 temp_expression.substr(close_bracket_position + 1); // skip ]
2480 *final_result = ValueObject::eExpressionPathEndResultTypePlain;
2481 continue;
2482 }
2483 } else {<