1 //===-- ValueObject.cpp -----------------------------------------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "lldb/Core/ValueObject.h"
11
12 #include "lldb/Core/Address.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/TypeValidator.h"
27 #include "lldb/DataFormatters/ValueObjectPrinter.h"
28 #include "lldb/Expression/ExpressionVariable.h"
29 #include "lldb/Symbol/ClangASTContext.h"
30 #include "lldb/Symbol/CompileUnit.h"
31 #include "lldb/Symbol/CompilerType.h"
32 #include "lldb/Symbol/Declaration.h"
33 #include "lldb/Symbol/SymbolContext.h"
34 #include "lldb/Symbol/Type.h"
35 #include "lldb/Target/ExecutionContext.h"
36 #include "lldb/Target/Language.h"
37 #include "lldb/Target/LanguageRuntime.h"
38 #include "lldb/Target/ObjCLanguageRuntime.h"
39 #include "lldb/Target/Process.h"
40 #include "lldb/Target/StackFrame.h"
41 #include "lldb/Target/Target.h"
42 #include "lldb/Target/Thread.h"
43 #include "lldb/Target/ThreadList.h"
44 #include "lldb/Utility/DataBuffer.h"
45 #include "lldb/Utility/DataBufferHeap.h"
46 #include "lldb/Utility/Flags.h"
47 #include "lldb/Utility/Log.h"
48 #include "lldb/Utility/Logging.h"
49 #include "lldb/Utility/Scalar.h"
50 #include "lldb/Utility/SharingPtr.h"
51 #include "lldb/Utility/Stream.h"
52 #include "lldb/Utility/StreamString.h"
53 #include "lldb/lldb-private-types.h"
54
55 #include "llvm/Support/Compiler.h"
56
57 #include <algorithm>
58 #include <cstdint>
59 #include <cstdlib>
60 #include <memory>
61 #include <tuple>
62
63 #include <assert.h>
64 #include <inttypes.h>
65 #include <stdio.h>
66 #include <string.h>
67
68 namespace lldb_private {
69 class ExecutionContextScope;
70 }
71 namespace lldb_private {
72 class SymbolContextScope;
73 }
74
75 using namespace lldb;
76 using namespace lldb_private;
77 using namespace lldb_utility;
78
79 static user_id_t g_value_obj_uid = 0;
80
81 //----------------------------------------------------------------------
82 // ValueObject constructor
83 //----------------------------------------------------------------------
ValueObject(ValueObject & parent)84 ValueObject::ValueObject(ValueObject &parent)
85 : UserID(++g_value_obj_uid), // Unique identifier for every value object
86 m_parent(&parent), m_root(NULL), m_update_point(parent.GetUpdatePoint()),
87 m_name(), m_data(), m_value(), m_error(), m_value_str(),
88 m_old_value_str(), m_location_str(), m_summary_str(), m_object_desc_str(),
89 m_validation_result(), m_manager(parent.GetManager()), m_children(),
90 m_synthetic_children(), m_dynamic_value(NULL), m_synthetic_value(NULL),
91 m_deref_valobj(NULL), m_format(eFormatDefault),
92 m_last_format(eFormatDefault), m_last_format_mgr_revision(0),
93 m_type_summary_sp(), m_type_format_sp(), m_synthetic_children_sp(),
94 m_type_validator_sp(), m_user_id_of_forced_summary(),
95 m_address_type_of_ptr_or_ref_children(eAddressTypeInvalid),
96 m_value_checksum(),
97 m_preferred_display_language(lldb::eLanguageTypeUnknown),
98 m_language_flags(0), m_value_is_valid(false), m_value_did_change(false),
99 m_children_count_valid(false), m_old_value_valid(false),
100 m_is_deref_of_parent(false), m_is_array_item_for_pointer(false),
101 m_is_bitfield_for_scalar(false), m_is_child_at_offset(false),
102 m_is_getting_summary(false),
103 m_did_calculate_complete_objc_class_type(false),
104 m_is_synthetic_children_generated(
105 parent.m_is_synthetic_children_generated) {
106 m_manager->ManageObject(this);
107 }
108
109 //----------------------------------------------------------------------
110 // ValueObject constructor
111 //----------------------------------------------------------------------
ValueObject(ExecutionContextScope * exe_scope,AddressType child_ptr_or_ref_addr_type)112 ValueObject::ValueObject(ExecutionContextScope *exe_scope,
113 AddressType child_ptr_or_ref_addr_type)
114 : UserID(++g_value_obj_uid), // Unique identifier for every value object
115 m_parent(NULL), m_root(NULL), m_update_point(exe_scope), m_name(),
116 m_data(), m_value(), m_error(), m_value_str(), m_old_value_str(),
117 m_location_str(), m_summary_str(), m_object_desc_str(),
118 m_validation_result(), m_manager(), m_children(), m_synthetic_children(),
119 m_dynamic_value(NULL), m_synthetic_value(NULL), m_deref_valobj(NULL),
120 m_format(eFormatDefault), m_last_format(eFormatDefault),
121 m_last_format_mgr_revision(0), m_type_summary_sp(), m_type_format_sp(),
122 m_synthetic_children_sp(), m_type_validator_sp(),
123 m_user_id_of_forced_summary(),
124 m_address_type_of_ptr_or_ref_children(child_ptr_or_ref_addr_type),
125 m_value_checksum(),
126 m_preferred_display_language(lldb::eLanguageTypeUnknown),
127 m_language_flags(0), m_value_is_valid(false), m_value_did_change(false),
128 m_children_count_valid(false), m_old_value_valid(false),
129 m_is_deref_of_parent(false), m_is_array_item_for_pointer(false),
130 m_is_bitfield_for_scalar(false), m_is_child_at_offset(false),
131 m_is_getting_summary(false),
132 m_did_calculate_complete_objc_class_type(false),
133 m_is_synthetic_children_generated(false) {
134 m_manager = new ValueObjectManager();
135 m_manager->ManageObject(this);
136 }
137
138 //----------------------------------------------------------------------
139 // Destructor
140 //----------------------------------------------------------------------
~ValueObject()141 ValueObject::~ValueObject() {}
142
UpdateValueIfNeeded(bool update_format)143 bool ValueObject::UpdateValueIfNeeded(bool update_format) {
144
145 bool did_change_formats = false;
146
147 if (update_format)
148 did_change_formats = UpdateFormatsIfNeeded();
149
150 // If this is a constant value, then our success is predicated on whether we
151 // have an error or not
152 if (GetIsConstant()) {
153 // if you are constant, things might still have changed behind your back
154 // (e.g. you are a frozen object and things have changed deeper than you
155 // cared to freeze-dry yourself) in this case, your value has not changed,
156 // but "computed" entries might have, so you might now have a different
157 // summary, or a different object description. clear these so we will
158 // recompute them
159 if (update_format && !did_change_formats)
160 ClearUserVisibleData(eClearUserVisibleDataItemsSummary |
161 eClearUserVisibleDataItemsDescription);
162 return m_error.Success();
163 }
164
165 bool first_update = IsChecksumEmpty();
166
167 if (NeedsUpdating()) {
168 m_update_point.SetUpdated();
169
170 // Save the old value using swap to avoid a string copy which also will
171 // clear our m_value_str
172 if (m_value_str.empty()) {
173 m_old_value_valid = false;
174 } else {
175 m_old_value_valid = true;
176 m_old_value_str.swap(m_value_str);
177 ClearUserVisibleData(eClearUserVisibleDataItemsValue);
178 }
179
180 ClearUserVisibleData();
181
182 if (IsInScope()) {
183 const bool value_was_valid = GetValueIsValid();
184 SetValueDidChange(false);
185
186 m_error.Clear();
187
188 // Call the pure virtual function to update the value
189
190 bool need_compare_checksums = false;
191 llvm::SmallVector<uint8_t, 16> old_checksum;
192
193 if (!first_update && CanProvideValue()) {
194 need_compare_checksums = true;
195 old_checksum.resize(m_value_checksum.size());
196 std::copy(m_value_checksum.begin(), m_value_checksum.end(),
197 old_checksum.begin());
198 }
199
200 bool success = UpdateValue();
201
202 SetValueIsValid(success);
203
204 if (success) {
205 const uint64_t max_checksum_size = 128;
206 m_data.Checksum(m_value_checksum, max_checksum_size);
207 } else {
208 need_compare_checksums = false;
209 m_value_checksum.clear();
210 }
211
212 assert(!need_compare_checksums ||
213 (!old_checksum.empty() && !m_value_checksum.empty()));
214
215 if (first_update)
216 SetValueDidChange(false);
217 else if (!m_value_did_change && !success) {
218 // The value wasn't gotten successfully, so we mark this as changed if
219 // the value used to be valid and now isn't
220 SetValueDidChange(value_was_valid);
221 } else if (need_compare_checksums) {
222 SetValueDidChange(memcmp(&old_checksum[0], &m_value_checksum[0],
223 m_value_checksum.size()));
224 }
225
226 } else {
227 m_error.SetErrorString("out of scope");
228 }
229 }
230 return m_error.Success();
231 }
232
UpdateFormatsIfNeeded()233 bool ValueObject::UpdateFormatsIfNeeded() {
234 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_DATAFORMATTERS));
235 if (log)
236 log->Printf("[%s %p] checking for FormatManager revisions. ValueObject "
237 "rev: %d - Global rev: %d",
238 GetName().GetCString(), static_cast<void *>(this),
239 m_last_format_mgr_revision,
240 DataVisualization::GetCurrentRevision());
241
242 bool any_change = false;
243
244 if ((m_last_format_mgr_revision != DataVisualization::GetCurrentRevision())) {
245 m_last_format_mgr_revision = DataVisualization::GetCurrentRevision();
246 any_change = true;
247
248 SetValueFormat(DataVisualization::GetFormat(*this, eNoDynamicValues));
249 SetSummaryFormat(
250 DataVisualization::GetSummaryFormat(*this, GetDynamicValueType()));
251 #ifndef LLDB_DISABLE_PYTHON
252 SetSyntheticChildren(
253 DataVisualization::GetSyntheticChildren(*this, GetDynamicValueType()));
254 #endif
255 SetValidator(DataVisualization::GetValidator(*this, GetDynamicValueType()));
256 }
257
258 return any_change;
259 }
260
SetNeedsUpdate()261 void ValueObject::SetNeedsUpdate() {
262 m_update_point.SetNeedsUpdate();
263 // We have to clear the value string here so ConstResult children will notice
264 // if their values are changed by hand (i.e. with SetValueAsCString).
265 ClearUserVisibleData(eClearUserVisibleDataItemsValue);
266 }
267
ClearDynamicTypeInformation()268 void ValueObject::ClearDynamicTypeInformation() {
269 m_children_count_valid = false;
270 m_did_calculate_complete_objc_class_type = false;
271 m_last_format_mgr_revision = 0;
272 m_override_type = CompilerType();
273 SetValueFormat(lldb::TypeFormatImplSP());
274 SetSummaryFormat(lldb::TypeSummaryImplSP());
275 SetSyntheticChildren(lldb::SyntheticChildrenSP());
276 }
277
MaybeCalculateCompleteType()278 CompilerType ValueObject::MaybeCalculateCompleteType() {
279 CompilerType compiler_type(GetCompilerTypeImpl());
280
281 if (m_did_calculate_complete_objc_class_type) {
282 if (m_override_type.IsValid())
283 return m_override_type;
284 else
285 return compiler_type;
286 }
287
288 CompilerType class_type;
289 bool is_pointer_type = false;
290
291 if (ClangASTContext::IsObjCObjectPointerType(compiler_type, &class_type)) {
292 is_pointer_type = true;
293 } else if (ClangASTContext::IsObjCObjectOrInterfaceType(compiler_type)) {
294 class_type = compiler_type;
295 } else {
296 return compiler_type;
297 }
298
299 m_did_calculate_complete_objc_class_type = true;
300
301 if (class_type) {
302 ConstString class_name(class_type.GetConstTypeName());
303
304 if (class_name) {
305 ProcessSP process_sp(
306 GetUpdatePoint().GetExecutionContextRef().GetProcessSP());
307
308 if (process_sp) {
309 ObjCLanguageRuntime *objc_language_runtime(
310 process_sp->GetObjCLanguageRuntime());
311
312 if (objc_language_runtime) {
313 TypeSP complete_objc_class_type_sp =
314 objc_language_runtime->LookupInCompleteClassCache(class_name);
315
316 if (complete_objc_class_type_sp) {
317 CompilerType complete_class(
318 complete_objc_class_type_sp->GetFullCompilerType());
319
320 if (complete_class.GetCompleteType()) {
321 if (is_pointer_type) {
322 m_override_type = complete_class.GetPointerType();
323 } else {
324 m_override_type = complete_class;
325 }
326
327 if (m_override_type.IsValid())
328 return m_override_type;
329 }
330 }
331 }
332 }
333 }
334 }
335 return compiler_type;
336 }
337
GetCompilerType()338 CompilerType ValueObject::GetCompilerType() {
339 return MaybeCalculateCompleteType();
340 }
341
GetTypeImpl()342 TypeImpl ValueObject::GetTypeImpl() { return TypeImpl(GetCompilerType()); }
343
GetDataExtractor()344 DataExtractor &ValueObject::GetDataExtractor() {
345 UpdateValueIfNeeded(false);
346 return m_data;
347 }
348
GetError()349 const Status &ValueObject::GetError() {
350 UpdateValueIfNeeded(false);
351 return m_error;
352 }
353
GetName() const354 const ConstString &ValueObject::GetName() const { return m_name; }
355
GetLocationAsCString()356 const char *ValueObject::GetLocationAsCString() {
357 return GetLocationAsCStringImpl(m_value, m_data);
358 }
359
GetLocationAsCStringImpl(const Value & value,const DataExtractor & data)360 const char *ValueObject::GetLocationAsCStringImpl(const Value &value,
361 const DataExtractor &data) {
362 if (UpdateValueIfNeeded(false)) {
363 if (m_location_str.empty()) {
364 StreamString sstr;
365
366 Value::ValueType value_type = value.GetValueType();
367
368 switch (value_type) {
369 case Value::eValueTypeScalar:
370 case Value::eValueTypeVector:
371 if (value.GetContextType() == Value::eContextTypeRegisterInfo) {
372 RegisterInfo *reg_info = value.GetRegisterInfo();
373 if (reg_info) {
374 if (reg_info->name)
375 m_location_str = reg_info->name;
376 else if (reg_info->alt_name)
377 m_location_str = reg_info->alt_name;
378 if (m_location_str.empty())
379 m_location_str = (reg_info->encoding == lldb::eEncodingVector)
380 ? "vector"
381 : "scalar";
382 }
383 }
384 if (m_location_str.empty())
385 m_location_str =
386 (value_type == Value::eValueTypeVector) ? "vector" : "scalar";
387 break;
388
389 case Value::eValueTypeLoadAddress:
390 case Value::eValueTypeFileAddress:
391 case Value::eValueTypeHostAddress: {
392 uint32_t addr_nibble_size = data.GetAddressByteSize() * 2;
393 sstr.Printf("0x%*.*llx", addr_nibble_size, addr_nibble_size,
394 value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS));
395 m_location_str = sstr.GetString();
396 } break;
397 }
398 }
399 }
400 return m_location_str.c_str();
401 }
402
GetValue()403 Value &ValueObject::GetValue() { return m_value; }
404
GetValue() const405 const Value &ValueObject::GetValue() const { return m_value; }
406
ResolveValue(Scalar & scalar)407 bool ValueObject::ResolveValue(Scalar &scalar) {
408 if (UpdateValueIfNeeded(
409 false)) // make sure that you are up to date before returning anything
410 {
411 ExecutionContext exe_ctx(GetExecutionContextRef());
412 Value tmp_value(m_value);
413 scalar = tmp_value.ResolveValue(&exe_ctx);
414 if (scalar.IsValid()) {
415 const uint32_t bitfield_bit_size = GetBitfieldBitSize();
416 if (bitfield_bit_size)
417 return scalar.ExtractBitfield(bitfield_bit_size,
418 GetBitfieldBitOffset());
419 return true;
420 }
421 }
422 return false;
423 }
424
IsLogicalTrue(Status & error)425 bool ValueObject::IsLogicalTrue(Status &error) {
426 if (Language *language = Language::FindPlugin(GetObjectRuntimeLanguage())) {
427 LazyBool is_logical_true = language->IsLogicalTrue(*this, error);
428 switch (is_logical_true) {
429 case eLazyBoolYes:
430 case eLazyBoolNo:
431 return (is_logical_true == true);
432 case eLazyBoolCalculate:
433 break;
434 }
435 }
436
437 Scalar scalar_value;
438
439 if (!ResolveValue(scalar_value)) {
440 error.SetErrorString("failed to get a scalar result");
441 return false;
442 }
443
444 bool ret;
445 ret = scalar_value.ULongLong(1) != 0;
446 error.Clear();
447 return ret;
448 }
449
GetValueIsValid() const450 bool ValueObject::GetValueIsValid() const { return m_value_is_valid; }
451
SetValueIsValid(bool b)452 void ValueObject::SetValueIsValid(bool b) { m_value_is_valid = b; }
453
GetValueDidChange()454 bool ValueObject::GetValueDidChange() { return m_value_did_change; }
455
SetValueDidChange(bool value_changed)456 void ValueObject::SetValueDidChange(bool value_changed) {
457 m_value_did_change = value_changed;
458 }
459
GetChildAtIndex(size_t idx,bool can_create)460 ValueObjectSP ValueObject::GetChildAtIndex(size_t idx, bool can_create) {
461 ValueObjectSP child_sp;
462 // We may need to update our value if we are dynamic
463 if (IsPossibleDynamicType())
464 UpdateValueIfNeeded(false);
465 if (idx < GetNumChildren()) {
466 // Check if we have already made the child value object?
467 if (can_create && !m_children.HasChildAtIndex(idx)) {
468 // No we haven't created the child at this index, so lets have our
469 // subclass do it and cache the result for quick future access.
470 m_children.SetChildAtIndex(idx, CreateChildAtIndex(idx, false, 0));
471 }
472
473 ValueObject *child = m_children.GetChildAtIndex(idx);
474 if (child != NULL)
475 return child->GetSP();
476 }
477 return child_sp;
478 }
479
480 lldb::ValueObjectSP
GetChildAtIndexPath(llvm::ArrayRef<size_t> idxs,size_t * index_of_error)481 ValueObject::GetChildAtIndexPath(llvm::ArrayRef<size_t> idxs,
482 size_t *index_of_error) {
483 if (idxs.size() == 0)
484 return GetSP();
485 ValueObjectSP root(GetSP());
486 for (size_t idx : idxs) {
487 root = root->GetChildAtIndex(idx, true);
488 if (!root) {
489 if (index_of_error)
490 *index_of_error = idx;
491 return root;
492 }
493 }
494 return root;
495 }
496
GetChildAtIndexPath(llvm::ArrayRef<std::pair<size_t,bool>> idxs,size_t * index_of_error)497 lldb::ValueObjectSP ValueObject::GetChildAtIndexPath(
498 llvm::ArrayRef<std::pair<size_t, bool>> idxs, size_t *index_of_error) {
499 if (idxs.size() == 0)
500 return GetSP();
501 ValueObjectSP root(GetSP());
502 for (std::pair<size_t, bool> idx : idxs) {
503 root = root->GetChildAtIndex(idx.first, idx.second);
504 if (!root) {
505 if (index_of_error)
506 *index_of_error = idx.first;
507 return root;
508 }
509 }
510 return root;
511 }
512
513 lldb::ValueObjectSP
GetChildAtNamePath(llvm::ArrayRef<ConstString> names,ConstString * name_of_error)514 ValueObject::GetChildAtNamePath(llvm::ArrayRef<ConstString> names,
515 ConstString *name_of_error) {
516 if (names.size() == 0)
517 return GetSP();
518 ValueObjectSP root(GetSP());
519 for (ConstString name : names) {
520 root = root->GetChildMemberWithName(name, true);
521 if (!root) {
522 if (name_of_error)
523 *name_of_error = name;
524 return root;
525 }
526 }
527 return root;
528 }
529
GetChildAtNamePath(llvm::ArrayRef<std::pair<ConstString,bool>> names,ConstString * name_of_error)530 lldb::ValueObjectSP ValueObject::GetChildAtNamePath(
531 llvm::ArrayRef<std::pair<ConstString, bool>> names,
532 ConstString *name_of_error) {
533 if (names.size() == 0)
534 return GetSP();
535 ValueObjectSP root(GetSP());
536 for (std::pair<ConstString, bool> name : names) {
537 root = root->GetChildMemberWithName(name.first, name.second);
538 if (!root) {
539 if (name_of_error)
540 *name_of_error = name.first;
541 return root;
542 }
543 }
544 return root;
545 }
546
GetIndexOfChildWithName(const ConstString & name)547 size_t ValueObject::GetIndexOfChildWithName(const ConstString &name) {
548 bool omit_empty_base_classes = true;
549 return GetCompilerType().GetIndexOfChildWithName(name.GetCString(),
550 omit_empty_base_classes);
551 }
552
GetChildMemberWithName(const ConstString & name,bool can_create)553 ValueObjectSP ValueObject::GetChildMemberWithName(const ConstString &name,
554 bool can_create) {
555 // when getting a child by name, it could be buried inside some base classes
556 // (which really aren't part of the expression path), so we need a vector of
557 // indexes that can get us down to the correct child
558 ValueObjectSP child_sp;
559
560 // We may need to update our value if we are dynamic
561 if (IsPossibleDynamicType())
562 UpdateValueIfNeeded(false);
563
564 std::vector<uint32_t> child_indexes;
565 bool omit_empty_base_classes = true;
566 const size_t num_child_indexes =
567 GetCompilerType().GetIndexOfChildMemberWithName(
568 name.GetCString(), omit_empty_base_classes, child_indexes);
569 if (num_child_indexes > 0) {
570 std::vector<uint32_t>::const_iterator pos = child_indexes.begin();
571 std::vector<uint32_t>::const_iterator end = child_indexes.end();
572
573 child_sp = GetChildAtIndex(*pos, can_create);
574 for (++pos; pos != end; ++pos) {
575 if (child_sp) {
576 ValueObjectSP new_child_sp(child_sp->GetChildAtIndex(*pos, can_create));
577 child_sp = new_child_sp;
578 } else {
579 child_sp.reset();
580 }
581 }
582 }
583 return child_sp;
584 }
585
GetNumChildren(uint32_t max)586 size_t ValueObject::GetNumChildren(uint32_t max) {
587 UpdateValueIfNeeded();
588
589 if (max < UINT32_MAX) {
590 if (m_children_count_valid) {
591 size_t children_count = m_children.GetChildrenCount();
592 return children_count <= max ? children_count : max;
593 } else
594 return CalculateNumChildren(max);
595 }
596
597 if (!m_children_count_valid) {
598 SetNumChildren(CalculateNumChildren());
599 }
600 return m_children.GetChildrenCount();
601 }
602
MightHaveChildren()603 bool ValueObject::MightHaveChildren() {
604 bool has_children = false;
605 const uint32_t type_info = GetTypeInfo();
606 if (type_info) {
607 if (type_info & (eTypeHasChildren | eTypeIsPointer | eTypeIsReference))
608 has_children = true;
609 } else {
610 has_children = GetNumChildren() > 0;
611 }
612 return has_children;
613 }
614
615 // Should only be called by ValueObject::GetNumChildren()
SetNumChildren(size_t num_children)616 void ValueObject::SetNumChildren(size_t num_children) {
617 m_children_count_valid = true;
618 m_children.SetChildrenCount(num_children);
619 }
620
SetName(const ConstString & name)621 void ValueObject::SetName(const ConstString &name) { m_name = name; }
622
CreateChildAtIndex(size_t idx,bool synthetic_array_member,int32_t synthetic_index)623 ValueObject *ValueObject::CreateChildAtIndex(size_t idx,
624 bool synthetic_array_member,
625 int32_t synthetic_index) {
626 ValueObject *valobj = NULL;
627
628 bool omit_empty_base_classes = true;
629 bool ignore_array_bounds = synthetic_array_member;
630 std::string child_name_str;
631 uint32_t child_byte_size = 0;
632 int32_t child_byte_offset = 0;
633 uint32_t child_bitfield_bit_size = 0;
634 uint32_t child_bitfield_bit_offset = 0;
635 bool child_is_base_class = false;
636 bool child_is_deref_of_parent = false;
637 uint64_t language_flags = 0;
638
639 const bool transparent_pointers = !synthetic_array_member;
640 CompilerType child_compiler_type;
641
642 ExecutionContext exe_ctx(GetExecutionContextRef());
643
644 child_compiler_type = GetCompilerType().GetChildCompilerTypeAtIndex(
645 &exe_ctx, idx, transparent_pointers, omit_empty_base_classes,
646 ignore_array_bounds, child_name_str, child_byte_size, child_byte_offset,
647 child_bitfield_bit_size, child_bitfield_bit_offset, child_is_base_class,
648 child_is_deref_of_parent, this, language_flags);
649 if (child_compiler_type) {
650 if (synthetic_index)
651 child_byte_offset += child_byte_size * synthetic_index;
652
653 ConstString child_name;
654 if (!child_name_str.empty())
655 child_name.SetCString(child_name_str.c_str());
656
657 valobj = new ValueObjectChild(
658 *this, child_compiler_type, child_name, child_byte_size,
659 child_byte_offset, child_bitfield_bit_size, child_bitfield_bit_offset,
660 child_is_base_class, child_is_deref_of_parent, eAddressTypeInvalid,
661 language_flags);
662 }
663
664 return valobj;
665 }
666
GetSummaryAsCString(TypeSummaryImpl * summary_ptr,std::string & destination,lldb::LanguageType lang)667 bool ValueObject::GetSummaryAsCString(TypeSummaryImpl *summary_ptr,
668 std::string &destination,
669 lldb::LanguageType lang) {
670 return GetSummaryAsCString(summary_ptr, destination,
671 TypeSummaryOptions().SetLanguage(lang));
672 }
673
GetSummaryAsCString(TypeSummaryImpl * summary_ptr,std::string & destination,const TypeSummaryOptions & options)674 bool ValueObject::GetSummaryAsCString(TypeSummaryImpl *summary_ptr,
675 std::string &destination,
676 const TypeSummaryOptions &options) {
677 destination.clear();
678
679 // ideally we would like to bail out if passing NULL, but if we do so we end
680 // up not providing the summary for function pointers anymore
681 if (/*summary_ptr == NULL ||*/ m_is_getting_summary)
682 return false;
683
684 m_is_getting_summary = true;
685
686 TypeSummaryOptions actual_options(options);
687
688 if (actual_options.GetLanguage() == lldb::eLanguageTypeUnknown)
689 actual_options.SetLanguage(GetPreferredDisplayLanguage());
690
691 // this is a hot path in code and we prefer to avoid setting this string all
692 // too often also clearing out other information that we might care to see in
693 // a crash log. might be useful in very specific situations though.
694 /*Host::SetCrashDescriptionWithFormat("Trying to fetch a summary for %s %s.
695 Summary provider's description is %s",
696 GetTypeName().GetCString(),
697 GetName().GetCString(),
698 summary_ptr->GetDescription().c_str());*/
699
700 if (UpdateValueIfNeeded(false) && summary_ptr) {
701 if (HasSyntheticValue())
702 m_synthetic_value->UpdateValueIfNeeded(); // the summary might depend on
703 // the synthetic children being
704 // up-to-date (e.g. ${svar%#})
705 summary_ptr->FormatObject(this, destination, actual_options);
706 }
707 m_is_getting_summary = false;
708 return !destination.empty();
709 }
710
GetSummaryAsCString(lldb::LanguageType lang)711 const char *ValueObject::GetSummaryAsCString(lldb::LanguageType lang) {
712 if (UpdateValueIfNeeded(true) && m_summary_str.empty()) {
713 TypeSummaryOptions summary_options;
714 summary_options.SetLanguage(lang);
715 GetSummaryAsCString(GetSummaryFormat().get(), m_summary_str,
716 summary_options);
717 }
718 if (m_summary_str.empty())
719 return NULL;
720 return m_summary_str.c_str();
721 }
722
GetSummaryAsCString(std::string & destination,const TypeSummaryOptions & options)723 bool ValueObject::GetSummaryAsCString(std::string &destination,
724 const TypeSummaryOptions &options) {
725 return GetSummaryAsCString(GetSummaryFormat().get(), destination, options);
726 }
727
IsCStringContainer(bool check_pointer)728 bool ValueObject::IsCStringContainer(bool check_pointer) {
729 CompilerType pointee_or_element_compiler_type;
730 const Flags type_flags(GetTypeInfo(&pointee_or_element_compiler_type));
731 bool is_char_arr_ptr(type_flags.AnySet(eTypeIsArray | eTypeIsPointer) &&
732 pointee_or_element_compiler_type.IsCharType());
733 if (!is_char_arr_ptr)
734 return false;
735 if (!check_pointer)
736 return true;
737 if (type_flags.Test(eTypeIsArray))
738 return true;
739 addr_t cstr_address = LLDB_INVALID_ADDRESS;
740 AddressType cstr_address_type = eAddressTypeInvalid;
741 cstr_address = GetAddressOf(true, &cstr_address_type);
742 return (cstr_address != LLDB_INVALID_ADDRESS);
743 }
744
GetPointeeData(DataExtractor & data,uint32_t item_idx,uint32_t item_count)745 size_t ValueObject::GetPointeeData(DataExtractor &data, uint32_t item_idx,
746 uint32_t item_count) {
747 CompilerType pointee_or_element_compiler_type;
748 const uint32_t type_info = GetTypeInfo(&pointee_or_element_compiler_type);
749 const bool is_pointer_type = type_info & eTypeIsPointer;
750 const bool is_array_type = type_info & eTypeIsArray;
751 if (!(is_pointer_type || is_array_type))
752 return 0;
753
754 if (item_count == 0)
755 return 0;
756
757 ExecutionContext exe_ctx(GetExecutionContextRef());
758
759 llvm::Optional<uint64_t> item_type_size =
760 pointee_or_element_compiler_type.GetByteSize(
761 exe_ctx.GetBestExecutionContextScope());
762 if (!item_type_size)
763 return 0;
764 const uint64_t bytes = item_count * *item_type_size;
765 const uint64_t offset = item_idx * *item_type_size;
766
767 if (item_idx == 0 && item_count == 1) // simply a deref
768 {
769 if (is_pointer_type) {
770 Status error;
771 ValueObjectSP pointee_sp = Dereference(error);
772 if (error.Fail() || pointee_sp.get() == NULL)
773 return 0;
774 return pointee_sp->GetData(data, error);
775 } else {
776 ValueObjectSP child_sp = GetChildAtIndex(0, true);
777 if (child_sp.get() == NULL)
778 return 0;
779 Status error;
780 return child_sp->GetData(data, error);
781 }
782 return true;
783 } else /* (items > 1) */
784 {
785 Status error;
786 lldb_private::DataBufferHeap *heap_buf_ptr = NULL;
787 lldb::DataBufferSP data_sp(heap_buf_ptr =
788 new lldb_private::DataBufferHeap());
789
790 AddressType addr_type;
791 lldb::addr_t addr = is_pointer_type ? GetPointerValue(&addr_type)
792 : GetAddressOf(true, &addr_type);
793
794 switch (addr_type) {
795 case eAddressTypeFile: {
796 ModuleSP module_sp(GetModule());
797 if (module_sp) {
798 addr = addr + offset;
799 Address so_addr;
800 module_sp->ResolveFileAddress(addr, so_addr);
801 ExecutionContext exe_ctx(GetExecutionContextRef());
802 Target *target = exe_ctx.GetTargetPtr();
803 if (target) {
804 heap_buf_ptr->SetByteSize(bytes);
805 size_t bytes_read = target->ReadMemory(
806 so_addr, false, heap_buf_ptr->GetBytes(), bytes, error);
807 if (error.Success()) {
808 data.SetData(data_sp);
809 return bytes_read;
810 }
811 }
812 }
813 } break;
814 case eAddressTypeLoad: {
815 ExecutionContext exe_ctx(GetExecutionContextRef());
816 Process *process = exe_ctx.GetProcessPtr();
817 if (process) {
818 heap_buf_ptr->SetByteSize(bytes);
819 size_t bytes_read = process->ReadMemory(
820 addr + offset, heap_buf_ptr->GetBytes(), bytes, error);
821 if (error.Success() || bytes_read > 0) {
822 data.SetData(data_sp);
823 return bytes_read;
824 }
825 }
826 } break;
827 case eAddressTypeHost: {
828 auto max_bytes =
829 GetCompilerType().GetByteSize(exe_ctx.GetBestExecutionContextScope());
830 if (max_bytes && *max_bytes > offset) {
831 size_t bytes_read = std::min<uint64_t>(*max_bytes - offset, bytes);
832 addr = m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
833 if (addr == 0 || addr == LLDB_INVALID_ADDRESS)
834 break;
835 heap_buf_ptr->CopyData((uint8_t *)(addr + offset), bytes_read);
836 data.SetData(data_sp);
837 return bytes_read;
838 }
839 } break;
840 case eAddressTypeInvalid:
841 break;
842 }
843 }
844 return 0;
845 }
846
GetData(DataExtractor & data,Status & error)847 uint64_t ValueObject::GetData(DataExtractor &data, Status &error) {
848 UpdateValueIfNeeded(false);
849 ExecutionContext exe_ctx(GetExecutionContextRef());
850 error = m_value.GetValueAsData(&exe_ctx, data, 0, GetModule().get());
851 if (error.Fail()) {
852 if (m_data.GetByteSize()) {
853 data = m_data;
854 error.Clear();
855 return data.GetByteSize();
856 } else {
857 return 0;
858 }
859 }
860 data.SetAddressByteSize(m_data.GetAddressByteSize());
861 data.SetByteOrder(m_data.GetByteOrder());
862 return data.GetByteSize();
863 }
864
SetData(DataExtractor & data,Status & error)865 bool ValueObject::SetData(DataExtractor &data, Status &error) {
866 error.Clear();
867 // Make sure our value is up to date first so that our location and location
868 // type is valid.
869 if (!UpdateValueIfNeeded(false)) {
870 error.SetErrorString("unable to read value");
871 return false;
872 }
873
874 uint64_t count = 0;
875 const Encoding encoding = GetCompilerType().GetEncoding(count);
876
877 const size_t byte_size = GetByteSize();
878
879 Value::ValueType value_type = m_value.GetValueType();
880
881 switch (value_type) {
882 case Value::eValueTypeScalar: {
883 Status set_error =
884 m_value.GetScalar().SetValueFromData(data, encoding, byte_size);
885
886 if (!set_error.Success()) {
887 error.SetErrorStringWithFormat("unable to set scalar value: %s",
888 set_error.AsCString());
889 return false;
890 }
891 } break;
892 case Value::eValueTypeLoadAddress: {
893 // If it is a load address, then the scalar value is the storage location
894 // of the data, and we have to shove this value down to that load location.
895 ExecutionContext exe_ctx(GetExecutionContextRef());
896 Process *process = exe_ctx.GetProcessPtr();
897 if (process) {
898 addr_t target_addr = m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
899 size_t bytes_written = process->WriteMemory(
900 target_addr, data.GetDataStart(), byte_size, error);
901 if (!error.Success())
902 return false;
903 if (bytes_written != byte_size) {
904 error.SetErrorString("unable to write value to memory");
905 return false;
906 }
907 }
908 } break;
909 case Value::eValueTypeHostAddress: {
910 // If it is a host address, then we stuff the scalar as a DataBuffer into
911 // the Value's data.
912 DataBufferSP buffer_sp(new DataBufferHeap(byte_size, 0));
913 m_data.SetData(buffer_sp, 0);
914 data.CopyByteOrderedData(0, byte_size,
915 const_cast<uint8_t *>(m_data.GetDataStart()),
916 byte_size, m_data.GetByteOrder());
917 m_value.GetScalar() = (uintptr_t)m_data.GetDataStart();
918 } break;
919 case Value::eValueTypeFileAddress:
920 case Value::eValueTypeVector:
921 break;
922 }
923
924 // If we have reached this point, then we have successfully changed the
925 // value.
926 SetNeedsUpdate();
927 return true;
928 }
929
CopyStringDataToBufferSP(const StreamString & source,lldb::DataBufferSP & destination)930 static bool CopyStringDataToBufferSP(const StreamString &source,
931 lldb::DataBufferSP &destination) {
932 destination.reset(new DataBufferHeap(source.GetSize() + 1, 0));
933 memcpy(destination->GetBytes(), source.GetString().data(), source.GetSize());
934 return true;
935 }
936
937 std::pair<size_t, bool>
ReadPointedString(lldb::DataBufferSP & buffer_sp,Status & error,uint32_t max_length,bool honor_array,Format item_format)938 ValueObject::ReadPointedString(lldb::DataBufferSP &buffer_sp, Status &error,
939 uint32_t max_length, bool honor_array,
940 Format item_format) {
941 bool was_capped = false;
942 StreamString s;
943 ExecutionContext exe_ctx(GetExecutionContextRef());
944 Target *target = exe_ctx.GetTargetPtr();
945
946 if (!target) {
947 s << "<no target to read from>";
948 error.SetErrorString("no target to read from");
949 CopyStringDataToBufferSP(s, buffer_sp);
950 return {0, was_capped};
951 }
952
953 if (max_length == 0)
954 max_length = target->GetMaximumSizeOfStringSummary();
955
956 size_t bytes_read = 0;
957 size_t total_bytes_read = 0;
958
959 CompilerType compiler_type = GetCompilerType();
960 CompilerType elem_or_pointee_compiler_type;
961 const Flags type_flags(GetTypeInfo(&elem_or_pointee_compiler_type));
962 if (type_flags.AnySet(eTypeIsArray | eTypeIsPointer) &&
963 elem_or_pointee_compiler_type.IsCharType()) {
964 addr_t cstr_address = LLDB_INVALID_ADDRESS;
965 AddressType cstr_address_type = eAddressTypeInvalid;
966
967 size_t cstr_len = 0;
968 bool capped_data = false;
969 const bool is_array = type_flags.Test(eTypeIsArray);
970 if (is_array) {
971 // We have an array
972 uint64_t array_size = 0;
973 if (compiler_type.IsArrayType(NULL, &array_size, NULL)) {
974 cstr_len = array_size;
975 if (cstr_len > max_length) {
976 capped_data = true;
977 cstr_len = max_length;
978 }
979 }
980 cstr_address = GetAddressOf(true, &cstr_address_type);
981 } else {
982 // We have a pointer
983 cstr_address = GetPointerValue(&cstr_address_type);
984 }
985
986 if (cstr_address == 0 || cstr_address == LLDB_INVALID_ADDRESS) {
987 if (cstr_address_type == eAddressTypeHost && is_array) {
988 const char *cstr = GetDataExtractor().PeekCStr(0);
989 if (cstr == nullptr) {
990 s << "<invalid address>";
991 error.SetErrorString("invalid address");
992 CopyStringDataToBufferSP(s, buffer_sp);
993 return {0, was_capped};
994 }
995 buffer_sp.reset(new DataBufferHeap(cstr_len, 0));
996 memcpy(buffer_sp->GetBytes(), cstr, cstr_len);
997 return {cstr_len, was_capped};
998 } else {
999 s << "<invalid address>";
1000 error.SetErrorString("invalid address");
1001 CopyStringDataToBufferSP(s, buffer_sp);
1002 return {0, was_capped};
1003 }
1004 }
1005
1006 Address cstr_so_addr(cstr_address);
1007 DataExtractor data;
1008 if (cstr_len > 0 && honor_array) {
1009 // I am using GetPointeeData() here to abstract the fact that some
1010 // ValueObjects are actually frozen pointers in the host but the pointed-
1011 // to data lives in the debuggee, and GetPointeeData() automatically
1012 // takes care of this
1013 GetPointeeData(data, 0, cstr_len);
1014
1015 if ((bytes_read = data.GetByteSize()) > 0) {
1016 total_bytes_read = bytes_read;
1017 for (size_t offset = 0; offset < bytes_read; offset++)
1018 s.Printf("%c", *data.PeekData(offset, 1));
1019 if (capped_data)
1020 was_capped = true;
1021 }
1022 } else {
1023 cstr_len = max_length;
1024 const size_t k_max_buf_size = 64;
1025
1026 size_t offset = 0;
1027
1028 int cstr_len_displayed = -1;
1029 bool capped_cstr = false;
1030 // I am using GetPointeeData() here to abstract the fact that some
1031 // ValueObjects are actually frozen pointers in the host but the pointed-
1032 // to data lives in the debuggee, and GetPointeeData() automatically
1033 // takes care of this
1034 while ((bytes_read = GetPointeeData(data, offset, k_max_buf_size)) > 0) {
1035 total_bytes_read += bytes_read;
1036 const char *cstr = data.PeekCStr(0);
1037 size_t len = strnlen(cstr, k_max_buf_size);
1038 if (cstr_len_displayed < 0)
1039 cstr_len_displayed = len;
1040
1041 if (len == 0)
1042 break;
1043 cstr_len_displayed += len;
1044 if (len > bytes_read)
1045 len = bytes_read;
1046 if (len > cstr_len)
1047 len = cstr_len;
1048
1049 for (size_t offset = 0; offset < bytes_read; offset++)
1050 s.Printf("%c", *data.PeekData(offset, 1));
1051
1052 if (len < k_max_buf_size)
1053 break;
1054
1055 if (len >= cstr_len) {
1056 capped_cstr = true;
1057 break;
1058 }
1059
1060 cstr_len -= len;
1061 offset += len;
1062 }
1063
1064 if (cstr_len_displayed >= 0) {
1065 if (capped_cstr)
1066 was_capped = true;
1067 }
1068 }
1069 } else {
1070 error.SetErrorString("not a string object");
1071 s << "<not a string object>";
1072 }
1073 CopyStringDataToBufferSP(s, buffer_sp);
1074 return {total_bytes_read, was_capped};
1075 }
1076
GetValidationStatus()1077 std::pair<TypeValidatorResult, std::string> ValueObject::GetValidationStatus() {
1078 if (!UpdateValueIfNeeded(true))
1079 return {TypeValidatorResult::Success,
1080 ""}; // not the validator's job to discuss update problems
1081
1082 if (m_validation_result.hasValue())
1083 return m_validation_result.getValue();
1084
1085 if (!m_type_validator_sp)
1086 return {TypeValidatorResult::Success, ""}; // no validator no failure
1087
1088 auto outcome = m_type_validator_sp->FormatObject(this);
1089
1090 return (m_validation_result = {outcome.m_result, outcome.m_message})
1091 .getValue();
1092 }
1093
GetObjectDescription()1094 const char *ValueObject::GetObjectDescription() {
1095
1096 if (!UpdateValueIfNeeded(true))
1097 return NULL;
1098
1099 if (!m_object_desc_str.empty())
1100 return m_object_desc_str.c_str();
1101
1102 ExecutionContext exe_ctx(GetExecutionContextRef());
1103 Process *process = exe_ctx.GetProcessPtr();
1104 if (process == NULL)
1105 return NULL;
1106
1107 StreamString s;
1108
1109 LanguageType language = GetObjectRuntimeLanguage();
1110 LanguageRuntime *runtime = process->GetLanguageRuntime(language);
1111
1112 if (runtime == NULL) {
1113 // Aw, hell, if the things a pointer, or even just an integer, let's try
1114 // ObjC anyway...
1115 CompilerType compiler_type = GetCompilerType();
1116 if (compiler_type) {
1117 bool is_signed;
1118 if (compiler_type.IsIntegerType(is_signed) ||
1119 compiler_type.IsPointerType()) {
1120 runtime = process->GetLanguageRuntime(eLanguageTypeObjC);
1121 }
1122 }
1123 }
1124
1125 if (runtime && runtime->GetObjectDescription(s, *this)) {
1126 m_object_desc_str.append(s.GetString());
1127 }
1128
1129 if (m_object_desc_str.empty())
1130 return NULL;
1131 else
1132 return m_object_desc_str.c_str();
1133 }
1134
GetValueAsCString(const lldb_private::TypeFormatImpl & format,std::string & destination)1135 bool ValueObject::GetValueAsCString(const lldb_private::TypeFormatImpl &format,
1136 std::string &destination) {
1137 if (UpdateValueIfNeeded(false))
1138 return format.FormatObject(this, destination);
1139 else
1140 return false;
1141 }
1142
GetValueAsCString(lldb::Format format,std::string & destination)1143 bool ValueObject::GetValueAsCString(lldb::Format format,
1144 std::string &destination) {
1145 return GetValueAsCString(TypeFormatImpl_Format(format), destination);
1146 }
1147
GetValueAsCString()1148 const char *ValueObject::GetValueAsCString() {
1149 if (UpdateValueIfNeeded(true)) {
1150 lldb::TypeFormatImplSP format_sp;
1151 lldb::Format my_format = GetFormat();
1152 if (my_format == lldb::eFormatDefault) {
1153 if (m_type_format_sp)
1154 format_sp = m_type_format_sp;
1155 else {
1156 if (m_is_bitfield_for_scalar)
1157 my_format = eFormatUnsigned;
1158 else {
1159 if (m_value.GetContextType() == Value::eContextTypeRegisterInfo) {
1160 const RegisterInfo *reg_info = m_value.GetRegisterInfo();
1161 if (reg_info)
1162 my_format = reg_info->format;
1163 } else {
1164 my_format = GetValue().GetCompilerType().GetFormat();
1165 }
1166 }
1167 }
1168 }
1169 if (my_format != m_last_format || m_value_str.empty()) {
1170 m_last_format = my_format;
1171 if (!format_sp)
1172 format_sp.reset(new TypeFormatImpl_Format(my_format));
1173 if (GetValueAsCString(*format_sp.get(), m_value_str)) {
1174 if (!m_value_did_change && m_old_value_valid) {
1175 // The value was gotten successfully, so we consider the value as
1176 // changed if the value string differs
1177 SetValueDidChange(m_old_value_str != m_value_str);
1178 }
1179 }
1180 }
1181 }
1182 if (m_value_str.empty())
1183 return NULL;
1184 return m_value_str.c_str();
1185 }
1186
1187 // if > 8bytes, 0 is returned. this method should mostly be used to read
1188 // address values out of pointers
GetValueAsUnsigned(uint64_t fail_value,bool * success)1189 uint64_t ValueObject::GetValueAsUnsigned(uint64_t fail_value, bool *success) {
1190 // If our byte size is zero this is an aggregate type that has children
1191 if (CanProvideValue()) {
1192 Scalar scalar;
1193 if (ResolveValue(scalar)) {
1194 if (success)
1195 *success = true;
1196 return scalar.ULongLong(fail_value);
1197 }
1198 // fallthrough, otherwise...
1199 }
1200
1201 if (success)
1202 *success = false;
1203 return fail_value;
1204 }
1205
GetValueAsSigned(int64_t fail_value,bool * success)1206 int64_t ValueObject::GetValueAsSigned(int64_t fail_value, bool *success) {
1207 // If our byte size is zero this is an aggregate type that has children
1208 if (CanProvideValue()) {
1209 Scalar scalar;
1210 if (ResolveValue(scalar)) {
1211 if (success)
1212 *success = true;
1213 return scalar.SLongLong(fail_value);
1214 }
1215 // fallthrough, otherwise...
1216 }
1217
1218 if (success)
1219 *success = false;
1220 return fail_value;
1221 }
1222
1223 // if any more "special cases" are added to
1224 // ValueObject::DumpPrintableRepresentation() please keep this call up to date
1225 // by returning true for your new special cases. We will eventually move to
1226 // checking this call result before trying to display special cases
HasSpecialPrintableRepresentation(ValueObjectRepresentationStyle val_obj_display,Format custom_format)1227 bool ValueObject::HasSpecialPrintableRepresentation(
1228 ValueObjectRepresentationStyle val_obj_display, Format custom_format) {
1229 Flags flags(GetTypeInfo());
1230 if (flags.AnySet(eTypeIsArray | eTypeIsPointer) &&
1231 val_obj_display == ValueObject::eValueObjectRepresentationStyleValue) {
1232 if (IsCStringContainer(true) &&
1233 (custom_format == eFormatCString || custom_format == eFormatCharArray ||
1234 custom_format == eFormatChar || custom_format == eFormatVectorOfChar))
1235 return true;
1236
1237 if (flags.Test(eTypeIsArray)) {
1238 if ((custom_format == eFormatBytes) ||
1239 (custom_format == eFormatBytesWithASCII))
1240 return true;
1241
1242 if ((custom_format == eFormatVectorOfChar) ||
1243 (custom_format == eFormatVectorOfFloat32) ||
1244 (custom_format == eFormatVectorOfFloat64) ||
1245 (custom_format == eFormatVectorOfSInt16) ||
1246 (custom_format == eFormatVectorOfSInt32) ||
1247 (custom_format == eFormatVectorOfSInt64) ||
1248 (custom_format == eFormatVectorOfSInt8) ||
1249 (custom_format == eFormatVectorOfUInt128) ||
1250 (custom_format == eFormatVectorOfUInt16) ||
1251 (custom_format == eFormatVectorOfUInt32) ||
1252 (custom_format == eFormatVectorOfUInt64) ||
1253 (custom_format == eFormatVectorOfUInt8))
1254 return true;
1255 }
1256 }
1257 return false;
1258 }
1259
DumpPrintableRepresentation(Stream & s,ValueObjectRepresentationStyle val_obj_display,Format custom_format,PrintableRepresentationSpecialCases special,bool do_dump_error)1260 bool ValueObject::DumpPrintableRepresentation(
1261 Stream &s, ValueObjectRepresentationStyle val_obj_display,
1262 Format custom_format, PrintableRepresentationSpecialCases special,
1263 bool do_dump_error) {
1264
1265 Flags flags(GetTypeInfo());
1266
1267 bool allow_special =
1268 (special == ValueObject::PrintableRepresentationSpecialCases::eAllow);
1269 const bool only_special = false;
1270
1271 if (allow_special) {
1272 if (flags.AnySet(eTypeIsArray | eTypeIsPointer) &&
1273 val_obj_display == ValueObject::eValueObjectRepresentationStyleValue) {
1274 // when being asked to get a printable display an array or pointer type
1275 // directly, try to "do the right thing"
1276
1277 if (IsCStringContainer(true) &&
1278 (custom_format == eFormatCString ||
1279 custom_format == eFormatCharArray || custom_format == eFormatChar ||
1280 custom_format ==
1281 eFormatVectorOfChar)) // print char[] & char* directly
1282 {
1283 Status error;
1284 lldb::DataBufferSP buffer_sp;
1285 std::pair<size_t, bool> read_string = ReadPointedString(
1286 buffer_sp, error, 0, (custom_format == eFormatVectorOfChar) ||
1287 (custom_format == eFormatCharArray));
1288 lldb_private::formatters::StringPrinter::
1289 ReadBufferAndDumpToStreamOptions options(*this);
1290 options.SetData(DataExtractor(
1291 buffer_sp, lldb::eByteOrderInvalid,
1292 8)); // none of this matters for a string - pass some defaults
1293 options.SetStream(&s);
1294 options.SetPrefixToken(0);
1295 options.SetQuote('"');
1296 options.SetSourceSize(buffer_sp->GetByteSize());
1297 options.SetIsTruncated(read_string.second);
1298 formatters::StringPrinter::ReadBufferAndDumpToStream<
1299 lldb_private::formatters::StringPrinter::StringElementType::ASCII>(
1300 options);
1301 return !error.Fail();
1302 }
1303
1304 if (custom_format == eFormatEnum)
1305 return false;
1306
1307 // this only works for arrays, because I have no way to know when the
1308 // pointed memory ends, and no special \0 end of data marker
1309 if (flags.Test(eTypeIsArray)) {
1310 if ((custom_format == eFormatBytes) ||
1311 (custom_format == eFormatBytesWithASCII)) {
1312 const size_t count = GetNumChildren();
1313
1314 s << '[';
1315 for (size_t low = 0; low < count; low++) {
1316
1317 if (low)
1318 s << ',';
1319
1320 ValueObjectSP child = GetChildAtIndex(low, true);
1321 if (!child.get()) {
1322 s << "<invalid child>";
1323 continue;
1324 }
1325 child->DumpPrintableRepresentation(
1326 s, ValueObject::eValueObjectRepresentationStyleValue,
1327 custom_format);
1328 }
1329
1330 s << ']';
1331
1332 return true;
1333 }
1334
1335 if ((custom_format == eFormatVectorOfChar) ||
1336 (custom_format == eFormatVectorOfFloat32) ||
1337 (custom_format == eFormatVectorOfFloat64) ||
1338 (custom_format == eFormatVectorOfSInt16) ||
1339 (custom_format == eFormatVectorOfSInt32) ||
1340 (custom_format == eFormatVectorOfSInt64) ||
1341 (custom_format == eFormatVectorOfSInt8) ||
1342 (custom_format == eFormatVectorOfUInt128) ||
1343 (custom_format == eFormatVectorOfUInt16) ||
1344 (custom_format == eFormatVectorOfUInt32) ||
1345 (custom_format == eFormatVectorOfUInt64) ||
1346 (custom_format == eFormatVectorOfUInt8)) // arrays of bytes, bytes
1347 // with ASCII or any vector
1348 // format should be printed
1349 // directly
1350 {
1351 const size_t count = GetNumChildren();
1352
1353 Format format = FormatManager::GetSingleItemFormat(custom_format);
1354
1355 s << '[';
1356 for (size_t low = 0; low < count; low++) {
1357
1358 if (low)
1359 s << ',';
1360
1361 ValueObjectSP child = GetChildAtIndex(low, true);
1362 if (!child.get()) {
1363 s << "<invalid child>";
1364 continue;
1365 }
1366 child->DumpPrintableRepresentation(
1367 s, ValueObject::eValueObjectRepresentationStyleValue, format);
1368 }
1369
1370 s << ']';
1371
1372 return true;
1373 }
1374 }
1375
1376 if ((custom_format == eFormatBoolean) ||
1377 (custom_format == eFormatBinary) || (custom_format == eFormatChar) ||
1378 (custom_format == eFormatCharPrintable) ||
1379 (custom_format == eFormatComplexFloat) ||
1380 (custom_format == eFormatDecimal) || (custom_format == eFormatHex) ||
1381 (custom_format == eFormatHexUppercase) ||
1382 (custom_format == eFormatFloat) || (custom_format == eFormatOctal) ||
1383 (custom_format == eFormatOSType) ||
1384 (custom_format == eFormatUnicode16) ||
1385 (custom_format == eFormatUnicode32) ||
1386 (custom_format == eFormatUnsigned) ||
1387 (custom_format == eFormatPointer) ||
1388 (custom_format == eFormatComplexInteger) ||
1389 (custom_format == eFormatComplex) ||
1390 (custom_format == eFormatDefault)) // use the [] operator
1391 return false;
1392 }
1393 }
1394
1395 if (only_special)
1396 return false;
1397
1398 bool var_success = false;
1399
1400 {
1401 llvm::StringRef str;
1402
1403 // this is a local stream that we are using to ensure that the data pointed
1404 // to by cstr survives long enough for us to copy it to its destination -
1405 // it is necessary to have this temporary storage area for cases where our
1406 // desired output is not backed by some other longer-term storage
1407 StreamString strm;
1408
1409 if (custom_format != eFormatInvalid)
1410 SetFormat(custom_format);
1411
1412 switch (val_obj_display) {
1413 case eValueObjectRepresentationStyleValue:
1414 str = GetValueAsCString();
1415 break;
1416
1417 case eValueObjectRepresentationStyleSummary:
1418 str = GetSummaryAsCString();
1419 break;
1420
1421 case eValueObjectRepresentationStyleLanguageSpecific:
1422 str = GetObjectDescription();
1423 break;
1424
1425 case eValueObjectRepresentationStyleLocation:
1426 str = GetLocationAsCString();
1427 break;
1428
1429 case eValueObjectRepresentationStyleChildrenCount:
1430 strm.Printf("%" PRIu64 "", (uint64_t)GetNumChildren());
1431 str = strm.GetString();
1432 break;
1433
1434 case eValueObjectRepresentationStyleType:
1435 str = GetTypeName().GetStringRef();
1436 break;
1437
1438 case eValueObjectRepresentationStyleName:
1439 str = GetName().GetStringRef();
1440 break;
1441
1442 case eValueObjectRepresentationStyleExpressionPath:
1443 GetExpressionPath(strm, false);
1444 str = strm.GetString();
1445 break;
1446 }
1447
1448 if (str.empty()) {
1449 if (val_obj_display == eValueObjectRepresentationStyleValue)
1450 str = GetSummaryAsCString();
1451 else if (val_obj_display == eValueObjectRepresentationStyleSummary) {
1452 if (!CanProvideValue()) {
1453 strm.Printf("%s @ %s", GetTypeName().AsCString(),
1454 GetLocationAsCString());
1455 str = strm.GetString();
1456 } else
1457 str = GetValueAsCString();
1458 }
1459 }
1460
1461 if (!str.empty())
1462 s << str;
1463 else {
1464 if (m_error.Fail()) {
1465 if (do_dump_error)
1466 s.Printf("<%s>", m_error.AsCString());
1467 else
1468 return false;
1469 } else if (val_obj_display == eValueObjectRepresentationStyleSummary)
1470 s.PutCString("<no summary available>");
1471 else if (val_obj_display == eValueObjectRepresentationStyleValue)
1472 s.PutCString("<no value available>");
1473 else if (val_obj_display ==
1474 eValueObjectRepresentationStyleLanguageSpecific)
1475 s.PutCString("<not a valid Objective-C object>"); // edit this if we
1476 // have other runtimes
1477 // that support a
1478 // description
1479 else
1480 s.PutCString("<no printable representation>");
1481 }
1482
1483 // we should only return false here if we could not do *anything* even if
1484 // we have an error message as output, that's a success from our callers'
1485 // perspective, so return true
1486 var_success = true;
1487
1488 if (custom_format != eFormatInvalid)
1489 SetFormat(eFormatDefault);
1490 }
1491
1492 return var_success;
1493 }
1494
GetAddressOf(bool scalar_is_load_address,AddressType * address_type)1495 addr_t ValueObject::GetAddressOf(bool scalar_is_load_address,
1496 AddressType *address_type) {
1497 // Can't take address of a bitfield
1498 if (IsBitfield())
1499 return LLDB_INVALID_ADDRESS;
1500
1501 if (!UpdateValueIfNeeded(false))
1502 return LLDB_INVALID_ADDRESS;
1503
1504 switch (m_value.GetValueType()) {
1505 case Value::eValueTypeScalar:
1506 case Value::eValueTypeVector:
1507 if (scalar_is_load_address) {
1508 if (address_type)
1509 *address_type = eAddressTypeLoad;
1510 return m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
1511 }
1512 break;
1513
1514 case Value::eValueTypeLoadAddress:
1515 case Value::eValueTypeFileAddress: {
1516 if (address_type)
1517 *address_type = m_value.GetValueAddressType();
1518 return m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
1519 } break;
1520 case Value::eValueTypeHostAddress: {
1521 if (address_type)
1522 *address_type = m_value.GetValueAddressType();
1523 return LLDB_INVALID_ADDRESS;
1524 } break;
1525 }
1526 if (address_type)
1527 *address_type = eAddressTypeInvalid;
1528 return LLDB_INVALID_ADDRESS;
1529 }
1530
GetPointerValue(AddressType * address_type)1531 addr_t ValueObject::GetPointerValue(AddressType *address_type) {
1532 addr_t address = LLDB_INVALID_ADDRESS;
1533 if (address_type)
1534 *address_type = eAddressTypeInvalid;
1535
1536 if (!UpdateValueIfNeeded(false))
1537 return address;
1538
1539 switch (m_value.GetValueType()) {
1540 case Value::eValueTypeScalar:
1541 case Value::eValueTypeVector:
1542 address = m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
1543 break;
1544
1545 case Value::eValueTypeHostAddress:
1546 case Value::eValueTypeLoadAddress:
1547 case Value::eValueTypeFileAddress: {
1548 lldb::offset_t data_offset = 0;
1549 address = m_data.GetPointer(&data_offset);
1550 } break;
1551 }
1552
1553 if (address_type)
1554 *address_type = GetAddressTypeOfChildren();
1555
1556 return address;
1557 }
1558
SetValueFromCString(const char * value_str,Status & error)1559 bool ValueObject::SetValueFromCString(const char *value_str, Status &error) {
1560 error.Clear();
1561 // Make sure our value is up to date first so that our location and location
1562 // type is valid.
1563 if (!UpdateValueIfNeeded(false)) {
1564 error.SetErrorString("unable to read value");
1565 return false;
1566 }
1567
1568 uint64_t count = 0;
1569 const Encoding encoding = GetCompilerType().GetEncoding(count);
1570
1571 const size_t byte_size = GetByteSize();
1572
1573 Value::ValueType value_type = m_value.GetValueType();
1574
1575 if (value_type == Value::eValueTypeScalar) {
1576 // If the value is already a scalar, then let the scalar change itself:
1577 m_value.GetScalar().SetValueFromCString(value_str, encoding, byte_size);
1578 } else if (byte_size <= 16) {
1579 // If the value fits in a scalar, then make a new scalar and again let the
1580 // scalar code do the conversion, then figure out where to put the new
1581 // value.
1582 Scalar new_scalar;
1583 error = new_scalar.SetValueFromCString(value_str, encoding, byte_size);
1584 if (error.Success()) {
1585 switch (value_type) {
1586 case Value::eValueTypeLoadAddress: {
1587 // If it is a load address, then the scalar value is the storage
1588 // location of the data, and we have to shove this value down to that
1589 // load location.
1590 ExecutionContext exe_ctx(GetExecutionContextRef());
1591 Process *process = exe_ctx.GetProcessPtr();
1592 if (process) {
1593 addr_t target_addr =
1594 m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
1595 size_t bytes_written = process->WriteScalarToMemory(
1596 target_addr, new_scalar, byte_size, error);
1597 if (!error.Success())
1598 return false;
1599 if (bytes_written != byte_size) {
1600 error.SetErrorString("unable to write value to memory");
1601 return false;
1602 }
1603 }
1604 } break;
1605 case Value::eValueTypeHostAddress: {
1606 // If it is a host address, then we stuff the scalar as a DataBuffer
1607 // into the Value's data.
1608 DataExtractor new_data;
1609 new_data.SetByteOrder(m_data.GetByteOrder());
1610
1611 DataBufferSP buffer_sp(new DataBufferHeap(byte_size, 0));
1612 m_data.SetData(buffer_sp, 0);
1613 bool success = new_scalar.GetData(new_data);
1614 if (success) {
1615 new_data.CopyByteOrderedData(
1616 0, byte_size, const_cast<uint8_t *>(m_data.GetDataStart()),
1617 byte_size, m_data.GetByteOrder());
1618 }
1619 m_value.GetScalar() = (uintptr_t)m_data.GetDataStart();
1620
1621 } break;
1622 case Value::eValueTypeFileAddress:
1623 case Value::eValueTypeScalar:
1624 case Value::eValueTypeVector:
1625 break;
1626 }
1627 } else {
1628 return false;
1629 }
1630 } else {
1631 // We don't support setting things bigger than a scalar at present.
1632 error.SetErrorString("unable to write aggregate data type");
1633 return false;
1634 }
1635
1636 // If we have reached this point, then we have successfully changed the
1637 // value.
1638 SetNeedsUpdate();
1639 return true;
1640 }
1641
GetDeclaration(Declaration & decl)1642 bool ValueObject::GetDeclaration(Declaration &decl) {
1643 decl.Clear();
1644 return false;
1645 }
1646
GetTypeName()1647 ConstString ValueObject::GetTypeName() {
1648 return GetCompilerType().GetConstTypeName();
1649 }
1650
GetDisplayTypeName()1651 ConstString ValueObject::GetDisplayTypeName() { return GetTypeName(); }
1652
GetQualifiedTypeName()1653 ConstString ValueObject::GetQualifiedTypeName() {
1654 return GetCompilerType().GetConstQualifiedTypeName();
1655 }
1656
GetObjectRuntimeLanguage()1657 LanguageType ValueObject::GetObjectRuntimeLanguage() {
1658 return GetCompilerType().GetMinimumLanguage();
1659 }
1660
AddSyntheticChild(const ConstString & key,ValueObject * valobj)1661 void ValueObject::AddSyntheticChild(const ConstString &key,
1662 ValueObject *valobj) {
1663 m_synthetic_children[key] = valobj;
1664 }
1665
GetSyntheticChild(const ConstString & key) const1666 ValueObjectSP ValueObject::GetSyntheticChild(const ConstString &key) const {
1667 ValueObjectSP synthetic_child_sp;
1668 std::map<ConstString, ValueObject *>::const_iterator pos =
1669 m_synthetic_children.find(key);
1670 if (pos != m_synthetic_children.end())
1671 synthetic_child_sp = pos->second->GetSP();
1672 return synthetic_child_sp;
1673 }
1674
1675 uint32_t
GetTypeInfo(CompilerType * pointee_or_element_compiler_type)1676 ValueObject::GetTypeInfo(CompilerType *pointee_or_element_compiler_type) {
1677 return GetCompilerType().GetTypeInfo(pointee_or_element_compiler_type);
1678 }
1679
IsPointerType()1680 bool ValueObject::IsPointerType() { return GetCompilerType().IsPointerType(); }
1681
IsArrayType()1682 bool ValueObject::IsArrayType() {
1683 return GetCompilerType().IsArrayType(NULL, NULL, NULL);
1684 }
1685
IsScalarType()1686 bool ValueObject::IsScalarType() { return GetCompilerType().IsScalarType(); }
1687
IsIntegerType(bool & is_signed)1688 bool ValueObject::IsIntegerType(bool &is_signed) {
1689 return GetCompilerType().IsIntegerType(is_signed);
1690 }
1691
IsPointerOrReferenceType()1692 bool ValueObject::IsPointerOrReferenceType() {
1693 return GetCompilerType().IsPointerOrReferenceType();
1694 }
1695
IsPossibleDynamicType()1696 bool ValueObject::IsPossibleDynamicType() {
1697 ExecutionContext exe_ctx(GetExecutionContextRef());
1698 Process *process = exe_ctx.GetProcessPtr();
1699 if (process)
1700 return process->IsPossibleDynamicValue(*this);
1701 else
1702 return GetCompilerType().IsPossibleDynamicType(NULL, true, true);
1703 }
1704
IsRuntimeSupportValue()1705 bool ValueObject::IsRuntimeSupportValue() {
1706 Process *process(GetProcessSP().get());
1707 if (process) {
1708 LanguageRuntime *runtime =
1709 process->GetLanguageRuntime(GetObjectRuntimeLanguage());
1710 if (!runtime)
1711 runtime = process->GetObjCLanguageRuntime();
1712 if (runtime)
1713 return runtime->IsRuntimeSupportValue(*this);
1714 }
1715 return false;
1716 }
1717
IsNilReference()1718 bool ValueObject::IsNilReference() {
1719 if (Language *language = Language::FindPlugin(GetObjectRuntimeLanguage())) {
1720 return language->IsNilReference(*this);
1721 }
1722 return false;
1723 }
1724
IsUninitializedReference()1725 bool ValueObject::IsUninitializedReference() {
1726 if (Language *language = Language::FindPlugin(GetObjectRuntimeLanguage())) {
1727 return language->IsUninitializedReference(*this);
1728 }
1729 return false;
1730 }
1731
1732 // This allows you to create an array member using and index that doesn't not
1733 // fall in the normal bounds of the array. Many times structure can be defined
1734 // as: struct Collection {
1735 // uint32_t item_count;
1736 // Item item_array[0];
1737 // };
1738 // The size of the "item_array" is 1, but many times in practice there are more
1739 // items in "item_array".
1740
GetSyntheticArrayMember(size_t index,bool can_create)1741 ValueObjectSP ValueObject::GetSyntheticArrayMember(size_t index,
1742 bool can_create) {
1743 ValueObjectSP synthetic_child_sp;
1744 if (IsPointerType() || IsArrayType()) {
1745 char index_str[64];
1746 snprintf(index_str, sizeof(index_str), "[%" PRIu64 "]", (uint64_t)index);
1747 ConstString index_const_str(index_str);
1748 // Check if we have already created a synthetic array member in this valid
1749 // object. If we have we will re-use it.
1750 synthetic_child_sp = GetSyntheticChild(index_const_str);
1751 if (!synthetic_child_sp) {
1752 ValueObject *synthetic_child;
1753 // We haven't made a synthetic array member for INDEX yet, so lets make
1754 // one and cache it for any future reference.
1755 synthetic_child = CreateChildAtIndex(0, true, index);
1756
1757 // Cache the value if we got one back...
1758 if (synthetic_child) {
1759 AddSyntheticChild(index_const_str, synthetic_child);
1760 synthetic_child_sp = synthetic_child->GetSP();
1761 synthetic_child_sp->SetName(ConstString(index_str));
1762 synthetic_child_sp->m_is_array_item_for_pointer = true;
1763 }
1764 }
1765 }
1766 return synthetic_child_sp;
1767 }
1768
GetSyntheticBitFieldChild(uint32_t from,uint32_t to,bool can_create)1769 ValueObjectSP ValueObject::GetSyntheticBitFieldChild(uint32_t from, uint32_t to,
1770 bool can_create) {
1771 ValueObjectSP synthetic_child_sp;
1772 if (IsScalarType()) {
1773 char index_str[64];
1774 snprintf(index_str, sizeof(index_str), "[%i-%i]", from, to);
1775 ConstString index_const_str(index_str);
1776 // Check if we have already created a synthetic array member in this valid
1777 // object. If we have we will re-use it.
1778 synthetic_child_sp = GetSyntheticChild(index_const_str);
1779 if (!synthetic_child_sp) {
1780 uint32_t bit_field_size = to - from + 1;
1781 uint32_t bit_field_offset = from;
1782 if (GetDataExtractor().GetByteOrder() == eByteOrderBig)
1783 bit_field_offset =
1784 GetByteSize() * 8 - bit_field_size - bit_field_offset;
1785 // We haven't made a synthetic array member for INDEX yet, so lets make
1786 // one and cache it for any future reference.
1787 ValueObjectChild *synthetic_child = new ValueObjectChild(
1788 *this, GetCompilerType(), index_const_str, GetByteSize(), 0,
1789 bit_field_size, bit_field_offset, false, false, eAddressTypeInvalid,
1790 0);
1791
1792 // Cache the value if we got one back...
1793 if (synthetic_child) {
1794 AddSyntheticChild(index_const_str, synthetic_child);
1795 synthetic_child_sp = synthetic_child->GetSP();
1796 synthetic_child_sp->SetName(ConstString(index_str));
1797 synthetic_child_sp->m_is_bitfield_for_scalar = true;
1798 }
1799 }
1800 }
1801 return synthetic_child_sp;
1802 }
1803
GetSyntheticChildAtOffset(uint32_t offset,const CompilerType & type,bool can_create,ConstString name_const_str)1804 ValueObjectSP ValueObject::GetSyntheticChildAtOffset(
1805 uint32_t offset, const CompilerType &type, bool can_create,
1806 ConstString name_const_str) {
1807
1808 ValueObjectSP synthetic_child_sp;
1809
1810 if (name_const_str.IsEmpty()) {
1811 char name_str[64];
1812 snprintf(name_str, sizeof(name_str), "@%i", offset);
1813 name_const_str.SetCString(name_str);
1814 }
1815
1816 // Check if we have already created a synthetic array member in this valid
1817 // object. If we have we will re-use it.
1818 synthetic_child_sp = GetSyntheticChild(name_const_str);
1819
1820 if (synthetic_child_sp.get())
1821 return synthetic_child_sp;
1822
1823 if (!can_create)
1824 return {};
1825
1826 ExecutionContext exe_ctx(GetExecutionContextRef());
1827 llvm::Optional<uint64_t> size =
1828 type.GetByteSize(exe_ctx.GetBestExecutionContextScope());
1829 if (!size)
1830 return {};
1831 ValueObjectChild *synthetic_child =
1832 new ValueObjectChild(*this, type, name_const_str, *size, offset, 0, 0,
1833 false, false, eAddressTypeInvalid, 0);
1834 if (synthetic_child) {
1835 AddSyntheticChild(name_const_str, synthetic_child);
1836 synthetic_child_sp = synthetic_child->GetSP();
1837 synthetic_child_sp->SetName(name_const_str);
1838 synthetic_child_sp->m_is_child_at_offset = true;
1839 }
1840 return synthetic_child_sp;
1841 }
1842
GetSyntheticBase(uint32_t offset,const CompilerType & type,bool can_create,ConstString name_const_str)1843 ValueObjectSP ValueObject::GetSyntheticBase(uint32_t offset,
1844 const CompilerType &type,
1845 bool can_create,
1846 ConstString name_const_str) {
1847 ValueObjectSP synthetic_child_sp;
1848
1849 if (name_const_str.IsEmpty()) {
1850 char name_str[128];
1851 snprintf(name_str, sizeof(name_str), "base%s@%i",
1852 type.GetTypeName().AsCString("<unknown>"), offset);
1853 name_const_str.SetCString(name_str);
1854 }
1855
1856 // Check if we have already created a synthetic array member in this valid
1857 // object. If we have we will re-use it.
1858 synthetic_child_sp = GetSyntheticChild(name_const_str);
1859
1860 if (synthetic_child_sp.get())
1861 return synthetic_child_sp;
1862
1863 if (!can_create)
1864 return {};
1865
1866 const bool is_base_class = true;
1867
1868 ExecutionContext exe_ctx(GetExecutionContextRef());
1869 llvm::Optional<uint64_t> size =
1870 type.GetByteSize(exe_ctx.GetBestExecutionContextScope());
1871 if (!size)
1872 return {};
1873 ValueObjectChild *synthetic_child =
1874 new ValueObjectChild(*this, type, name_const_str, *size, offset, 0, 0,
1875 is_base_class, false, eAddressTypeInvalid, 0);
1876 if (synthetic_child) {
1877 AddSyntheticChild(name_const_str, synthetic_child);
1878 synthetic_child_sp = synthetic_child->GetSP();
1879 synthetic_child_sp->SetName(name_const_str);
1880 }
1881 return synthetic_child_sp;
1882 }
1883
1884 // your expression path needs to have a leading . or -> (unless it somehow
1885 // "looks like" an array, in which case it has a leading [ symbol). while the [
1886 // is meaningful and should be shown to the user, . and -> are just parser
1887 // design, but by no means added information for the user.. strip them off
SkipLeadingExpressionPathSeparators(const char * expression)1888 static const char *SkipLeadingExpressionPathSeparators(const char *expression) {
1889 if (!expression || !expression[0])
1890 return expression;
1891 if (expression[0] == '.')
1892 return expression + 1;
1893 if (expression[0] == '-' && expression[1] == '>')
1894 return expression + 2;
1895 return expression;
1896 }
1897
1898 ValueObjectSP
GetSyntheticExpressionPathChild(const char * expression,bool can_create)1899 ValueObject::GetSyntheticExpressionPathChild(const char *expression,
1900 bool can_create) {
1901 ValueObjectSP synthetic_child_sp;
1902 ConstString name_const_string(expression);
1903 // Check if we have already created a synthetic array member in this valid
1904 // object. If we have we will re-use it.
1905 synthetic_child_sp = GetSyntheticChild(name_const_string);
1906 if (!synthetic_child_sp) {
1907 // We haven't made a synthetic array member for expression yet, so lets
1908 // make one and cache it for any future reference.
1909 synthetic_child_sp = GetValueForExpressionPath(
1910 expression, NULL, NULL,
1911 GetValueForExpressionPathOptions().SetSyntheticChildrenTraversal(
1912 GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
1913 None));
1914
1915 // Cache the value if we got one back...
1916 if (synthetic_child_sp.get()) {
1917 // FIXME: this causes a "real" child to end up with its name changed to
1918 // the contents of expression
1919 AddSyntheticChild(name_const_string, synthetic_child_sp.get());
1920 synthetic_child_sp->SetName(
1921 ConstString(SkipLeadingExpressionPathSeparators(expression)));
1922 }
1923 }
1924 return synthetic_child_sp;
1925 }
1926
CalculateSyntheticValue(bool use_synthetic)1927 void ValueObject::CalculateSyntheticValue(bool use_synthetic) {
1928 if (!use_synthetic)
1929 return;
1930
1931 TargetSP target_sp(GetTargetSP());
1932 if (target_sp && !target_sp->GetEnableSyntheticValue()) {
1933 m_synthetic_value = NULL;
1934 return;
1935 }
1936
1937 lldb::SyntheticChildrenSP current_synth_sp(m_synthetic_children_sp);
1938
1939 if (!UpdateFormatsIfNeeded() && m_synthetic_value)
1940 return;
1941
1942 if (m_synthetic_children_sp.get() == NULL)
1943 return;
1944
1945 if (current_synth_sp == m_synthetic_children_sp && m_synthetic_value)
1946 return;
1947
1948 m_synthetic_value = new ValueObjectSynthetic(*this, m_synthetic_children_sp);
1949 }
1950
CalculateDynamicValue(DynamicValueType use_dynamic)1951 void ValueObject::CalculateDynamicValue(DynamicValueType use_dynamic) {
1952 if (use_dynamic == eNoDynamicValues)
1953 return;
1954
1955 if (!m_dynamic_value && !IsDynamic()) {
1956 ExecutionContext exe_ctx(GetExecutionContextRef());
1957 Process *process = exe_ctx.GetProcessPtr();
1958 if (process && process->IsPossibleDynamicValue(*this)) {
1959 ClearDynamicTypeInformation();
1960 m_dynamic_value = new ValueObjectDynamicValue(*this, use_dynamic);
1961 }
1962 }
1963 }
1964
GetDynamicValue(DynamicValueType use_dynamic)1965 ValueObjectSP ValueObject::GetDynamicValue(DynamicValueType use_dynamic) {
1966 if (use_dynamic == eNoDynamicValues)
1967 return ValueObjectSP();
1968
1969 if (!IsDynamic() && m_dynamic_value == NULL) {
1970 CalculateDynamicValue(use_dynamic);
1971 }
1972 if (m_dynamic_value)
1973 return m_dynamic_value->GetSP();
1974 else
1975 return ValueObjectSP();
1976 }
1977
GetStaticValue()1978 ValueObjectSP ValueObject::GetStaticValue() { return GetSP(); }
1979
GetNonSyntheticValue()1980 lldb::ValueObjectSP ValueObject::GetNonSyntheticValue() { return GetSP(); }
1981
GetSyntheticValue(bool use_synthetic)1982 ValueObjectSP ValueObject::GetSyntheticValue(bool use_synthetic) {
1983 if (!use_synthetic)
1984 return ValueObjectSP();
1985
1986 CalculateSyntheticValue(use_synthetic);
1987
1988 if (m_synthetic_value)
1989 return m_synthetic_value->GetSP();
1990 else
1991 return ValueObjectSP();
1992 }
1993
HasSyntheticValue()1994 bool ValueObject::HasSyntheticValue() {
1995 UpdateFormatsIfNeeded();
1996
1997 if (m_synthetic_children_sp.get() == NULL)
1998 return false;
1999
2000 CalculateSyntheticValue(true);
2001
2002 return m_synthetic_value != nullptr;
2003 }
2004
GetBaseClassPath(Stream & s)2005 bool ValueObject::GetBaseClassPath(Stream &s) {
2006 if (IsBaseClass()) {
2007 bool parent_had_base_class =
2008 GetParent() && GetParent()->GetBaseClassPath(s);
2009 CompilerType compiler_type = GetCompilerType();
2010 std::string cxx_class_name;
2011 bool this_had_base_class =
2012 ClangASTContext::GetCXXClassName(compiler_type, cxx_class_name);
2013 if (this_had_base_class) {
2014 if (parent_had_base_class)
2015 s.PutCString("::");
2016 s.PutCString(cxx_class_name);
2017 }
2018 return parent_had_base_class || this_had_base_class;
2019 }
2020 return false;
2021 }
2022
GetNonBaseClassParent()2023 ValueObject *ValueObject::GetNonBaseClassParent() {
2024 if (GetParent()) {
2025 if (GetParent()->IsBaseClass())
2026 return GetParent()->GetNonBaseClassParent();
2027 else
2028 return GetParent();
2029 }
2030 return NULL;
2031 }
2032
IsBaseClass(uint32_t & depth)2033 bool ValueObject::IsBaseClass(uint32_t &depth) {
2034 if (!IsBaseClass()) {
2035 depth = 0;
2036 return false;
2037 }
2038 if (GetParent()) {
2039 GetParent()->IsBaseClass(depth);
2040 depth = depth + 1;
2041 return true;
2042 }
2043 // TODO: a base of no parent? weird..
2044 depth = 1;
2045 return true;
2046 }
2047
GetExpressionPath(Stream & s,bool qualify_cxx_base_classes,GetExpressionPathFormat epformat)2048 void ValueObject::GetExpressionPath(Stream &s, bool qualify_cxx_base_classes,
2049 GetExpressionPathFormat epformat) {
2050 // synthetic children do not actually "exist" as part of the hierarchy, and
2051 // sometimes they are consed up in ways that don't make sense from an
2052 // underlying language/API standpoint. So, use a special code path here to
2053 // return something that can hopefully be used in expression
2054 if (m_is_synthetic_children_generated) {
2055 UpdateValueIfNeeded();
2056
2057 if (m_value.GetValueType() == Value::eValueTypeLoadAddress) {
2058 if (IsPointerOrReferenceType()) {
2059 s.Printf("((%s)0x%" PRIx64 ")", GetTypeName().AsCString("void"),
2060 GetValueAsUnsigned(0));
2061 return;
2062 } else {
2063 uint64_t load_addr =
2064 m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
2065 if (load_addr != LLDB_INVALID_ADDRESS) {
2066 s.Printf("(*( (%s *)0x%" PRIx64 "))", GetTypeName().AsCString("void"),
2067 load_addr);
2068 return;
2069 }
2070 }
2071 }
2072
2073 if (CanProvideValue()) {
2074 s.Printf("((%s)%s)", GetTypeName().AsCString("void"),
2075 GetValueAsCString());
2076 return;
2077 }
2078
2079 return;
2080 }
2081
2082 const bool is_deref_of_parent = IsDereferenceOfParent();
2083
2084 if (is_deref_of_parent &&
2085 epformat == eGetExpressionPathFormatDereferencePointers) {
2086 // this is the original format of GetExpressionPath() producing code like
2087 // *(a_ptr).memberName, which is entirely fine, until you put this into
2088 // StackFrame::GetValueForVariableExpressionPath() which prefers to see
2089 // a_ptr->memberName. the eHonorPointers mode is meant to produce strings
2090 // in this latter format
2091 s.PutCString("*(");
2092 }
2093
2094 ValueObject *parent = GetParent();
2095
2096 if (parent)
2097 parent->GetExpressionPath(s, qualify_cxx_base_classes, epformat);
2098
2099 // if we are a deref_of_parent just because we are synthetic array members
2100 // made up to allow ptr[%d] syntax to work in variable printing, then add our
2101 // name ([%d]) to the expression path
2102 if (m_is_array_item_for_pointer &&
2103 epformat == eGetExpressionPathFormatHonorPointers)
2104 s.PutCString(m_name.AsCString());
2105
2106 if (!IsBaseClass()) {
2107 if (!is_deref_of_parent) {
2108 ValueObject *non_base_class_parent = GetNonBaseClassParent();
2109 if (non_base_class_parent &&
2110 !non_base_class_parent->GetName().IsEmpty()) {
2111 CompilerType non_base_class_parent_compiler_type =
2112 non_base_class_parent->GetCompilerType();
2113 if (non_base_class_parent_compiler_type) {
2114 if (parent && parent->IsDereferenceOfParent() &&
2115 epformat == eGetExpressionPathFormatHonorPointers) {
2116 s.PutCString("->");
2117 } else {
2118 const uint32_t non_base_class_parent_type_info =
2119 non_base_class_parent_compiler_type.GetTypeInfo();
2120
2121 if (non_base_class_parent_type_info & eTypeIsPointer) {
2122 s.PutCString("->");
2123 } else if ((non_base_class_parent_type_info & eTypeHasChildren) &&
2124 !(non_base_class_parent_type_info & eTypeIsArray)) {
2125 s.PutChar('.');
2126 }
2127 }
2128 }
2129 }
2130
2131 const char *name = GetName().GetCString();
2132 if (name) {
2133 if (qualify_cxx_base_classes) {
2134 if (GetBaseClassPath(s))
2135 s.PutCString("::");
2136 }
2137 s.PutCString(name);
2138 }
2139 }
2140 }
2141
2142 if (is_deref_of_parent &&
2143 epformat == eGetExpressionPathFormatDereferencePointers) {
2144 s.PutChar(')');
2145 }
2146 }
2147
GetValueForExpressionPath(llvm::StringRef expression,ExpressionPathScanEndReason * reason_to_stop,ExpressionPathEndResultType * final_value_type,const GetValueForExpressionPathOptions & options,ExpressionPathAftermath * final_task_on_target)2148 ValueObjectSP ValueObject::GetValueForExpressionPath(
2149 llvm::StringRef expression, ExpressionPathScanEndReason *reason_to_stop,
2150 ExpressionPathEndResultType *final_value_type,
2151 const GetValueForExpressionPathOptions &options,
2152 ExpressionPathAftermath *final_task_on_target) {
2153
2154 ExpressionPathScanEndReason dummy_reason_to_stop =
2155 ValueObject::eExpressionPathScanEndReasonUnknown;
2156 ExpressionPathEndResultType dummy_final_value_type =
2157 ValueObject::eExpressionPathEndResultTypeInvalid;
2158 ExpressionPathAftermath dummy_final_task_on_target =
2159 ValueObject::eExpressionPathAftermathNothing;
2160
2161 ValueObjectSP ret_val = GetValueForExpressionPath_Impl(
2162 expression, reason_to_stop ? reason_to_stop : &dummy_reason_to_stop,
2163 final_value_type ? final_value_type : &dummy_final_value_type, options,
2164 final_task_on_target ? final_task_on_target
2165 : &dummy_final_task_on_target);
2166
2167 if (!final_task_on_target ||
2168 *final_task_on_target == ValueObject::eExpressionPathAftermathNothing)
2169 return ret_val;
2170
2171 if (ret_val.get() &&
2172 ((final_value_type ? *final_value_type : dummy_final_value_type) ==
2173 eExpressionPathEndResultTypePlain)) // I can only deref and takeaddress
2174 // of plain objects
2175 {
2176 if ((final_task_on_target ? *final_task_on_target
2177 : dummy_final_task_on_target) ==
2178 ValueObject::eExpressionPathAftermathDereference) {
2179 Status error;
2180 ValueObjectSP final_value = ret_val->Dereference(error);
2181 if (error.Fail() || !final_value.get()) {
2182 if (reason_to_stop)
2183 *reason_to_stop =
2184 ValueObject::eExpressionPathScanEndReasonDereferencingFailed;
2185 if (final_value_type)
2186 *final_value_type = ValueObject::eExpressionPathEndResultTypeInvalid;
2187 return ValueObjectSP();
2188 } else {
2189 if (final_task_on_target)
2190 *final_task_on_target = ValueObject::eExpressionPathAftermathNothing;
2191 return final_value;
2192 }
2193 }
2194 if (*final_task_on_target ==
2195 ValueObject::eExpressionPathAftermathTakeAddress) {
2196 Status error;
2197 ValueObjectSP final_value = ret_val->AddressOf(error);
2198 if (error.Fail() || !final_value.get()) {
2199 if (reason_to_stop)
2200 *reason_to_stop =
2201 ValueObject::eExpressionPathScanEndReasonTakingAddressFailed;
2202 if (final_value_type)
2203 *final_value_type = ValueObject::eExpressionPathEndResultTypeInvalid;
2204 return ValueObjectSP();
2205 } else {
2206 if (final_task_on_target)
2207 *final_task_on_target = ValueObject::eExpressionPathAftermathNothing;
2208 return final_value;
2209 }
2210 }
2211 }
2212 return ret_val; // final_task_on_target will still have its original value, so
2213 // you know I did not do it
2214 }
2215
GetValueForExpressionPath_Impl(llvm::StringRef expression,ExpressionPathScanEndReason * reason_to_stop,ExpressionPathEndResultType * final_result,const GetValueForExpressionPathOptions & options,ExpressionPathAftermath * what_next)2216 ValueObjectSP ValueObject::GetValueForExpressionPath_Impl(
2217 llvm::StringRef expression, ExpressionPathScanEndReason *reason_to_stop,
2218 ExpressionPathEndResultType *final_result,
2219 const GetValueForExpressionPathOptions &options,
2220 ExpressionPathAftermath *what_next) {
2221 ValueObjectSP root = GetSP();
2222
2223 if (!root)
2224 return nullptr;
2225
2226 llvm::StringRef remainder = expression;
2227
2228 while (true) {
2229 llvm::StringRef temp_expression = remainder;
2230
2231 CompilerType root_compiler_type = root->GetCompilerType();
2232 CompilerType pointee_compiler_type;
2233 Flags pointee_compiler_type_info;
2234
2235 Flags root_compiler_type_info(
2236 root_compiler_type.GetTypeInfo(&pointee_compiler_type));
2237 if (pointee_compiler_type)
2238 pointee_compiler_type_info.Reset(pointee_compiler_type.GetTypeInfo());
2239
2240 if (temp_expression.empty()) {
2241 *reason_to_stop = ValueObject::eExpressionPathScanEndReasonEndOfString;
2242 return root;
2243 }
2244
2245 switch (temp_expression.front()) {
2246 case '-': {
2247 temp_expression = temp_expression.drop_front();
2248 if (options.m_check_dot_vs_arrow_syntax &&
2249 root_compiler_type_info.Test(eTypeIsPointer)) // if you are trying to
2250 // use -> on a
2251 // non-pointer and I
2252 // must catch the error
2253 {
2254 *reason_to_stop =
2255 ValueObject::eExpressionPathScanEndReasonArrowInsteadOfDot;
2256 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2257 return ValueObjectSP();
2258 }
2259 if (root_compiler_type_info.Test(eTypeIsObjC) && // if yo are trying to
2260 // extract an ObjC IVar
2261 // when this is forbidden
2262 root_compiler_type_info.Test(eTypeIsPointer) &&
2263 options.m_no_fragile_ivar) {
2264 *reason_to_stop =
2265 ValueObject::eExpressionPathScanEndReasonFragileIVarNotAllowed;
2266 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2267 return ValueObjectSP();
2268 }
2269 if (!temp_expression.startswith(">")) {
2270 *reason_to_stop =
2271 ValueObject::eExpressionPathScanEndReasonUnexpectedSymbol;
2272 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2273 return ValueObjectSP();
2274 }
2275 }
2276 LLVM_FALLTHROUGH;
2277 case '.': // or fallthrough from ->
2278 {
2279 if (options.m_check_dot_vs_arrow_syntax &&
2280 temp_expression.front() == '.' &&
2281 root_compiler_type_info.Test(eTypeIsPointer)) // if you are trying to
2282 // use . on a pointer
2283 // and I must catch the
2284 // error
2285 {
2286 *reason_to_stop =
2287 ValueObject::eExpressionPathScanEndReasonDotInsteadOfArrow;
2288 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2289 return nullptr;
2290 }
2291 temp_expression = temp_expression.drop_front(); // skip . or >
2292
2293 size_t next_sep_pos = temp_expression.find_first_of("-.[", 1);
2294 ConstString child_name;
2295 if (next_sep_pos == llvm::StringRef::npos) // if no other separator just
2296 // expand this last layer
2297 {
2298 child_name.SetString(temp_expression);
2299 ValueObjectSP child_valobj_sp =
2300 root->GetChildMemberWithName(child_name, true);
2301
2302 if (child_valobj_sp.get()) // we know we are done, so just return
2303 {
2304 *reason_to_stop =
2305 ValueObject::eExpressionPathScanEndReasonEndOfString;
2306 *final_result = ValueObject::eExpressionPathEndResultTypePlain;
2307 return child_valobj_sp;
2308 } else {
2309 switch (options.m_synthetic_children_traversal) {
2310 case GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2311 None:
2312 break;
2313 case GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2314 FromSynthetic:
2315 if (root->IsSynthetic()) {
2316 child_valobj_sp = root->GetNonSyntheticValue();
2317 if (child_valobj_sp.get())
2318 child_valobj_sp =
2319 child_valobj_sp->GetChildMemberWithName(child_name, true);
2320 }
2321 break;
2322 case GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2323 ToSynthetic:
2324 if (!root->IsSynthetic()) {
2325 child_valobj_sp = root->GetSyntheticValue();
2326 if (child_valobj_sp.get())
2327 child_valobj_sp =
2328 child_valobj_sp->GetChildMemberWithName(child_name, true);
2329 }
2330 break;
2331 case GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2332 Both:
2333 if (root->IsSynthetic()) {
2334 child_valobj_sp = root->GetNonSyntheticValue();
2335 if (child_valobj_sp.get())
2336 child_valobj_sp =
2337 child_valobj_sp->GetChildMemberWithName(child_name, true);
2338 } else {
2339 child_valobj_sp = root->GetSyntheticValue();
2340 if (child_valobj_sp.get())
2341 child_valobj_sp =
2342 child_valobj_sp->GetChildMemberWithName(child_name, true);
2343 }
2344 break;
2345 }
2346 }
2347
2348 // if we are here and options.m_no_synthetic_children is true,
2349 // child_valobj_sp is going to be a NULL SP, so we hit the "else"
2350 // branch, and return an error
2351 if (child_valobj_sp.get()) // if it worked, just return
2352 {
2353 *reason_to_stop =
2354 ValueObject::eExpressionPathScanEndReasonEndOfString;
2355 *final_result = ValueObject::eExpressionPathEndResultTypePlain;
2356 return child_valobj_sp;
2357 } else {
2358 *reason_to_stop =
2359 ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2360 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2361 return nullptr;
2362 }
2363 } else // other layers do expand
2364 {
2365 llvm::StringRef next_separator = temp_expression.substr(next_sep_pos);
2366
2367 child_name.SetString(temp_expression.slice(0, next_sep_pos));
2368
2369 ValueObjectSP child_valobj_sp =
2370 root->GetChildMemberWithName(child_name, true);
2371 if (child_valobj_sp.get()) // store the new root and move on
2372 {
2373 root = child_valobj_sp;
2374 remainder = next_separator;
2375 *final_result = ValueObject::eExpressionPathEndResultTypePlain;
2376 continue;
2377 } else {
2378 switch (options.m_synthetic_children_traversal) {
2379 case GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2380 None:
2381 break;
2382 case GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2383 FromSynthetic:
2384 if (root->IsSynthetic()) {
2385 child_valobj_sp = root->GetNonSyntheticValue();
2386 if (child_valobj_sp.get())
2387 child_valobj_sp =
2388 child_valobj_sp->GetChildMemberWithName(child_name, true);
2389 }
2390 break;
2391 case GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2392 ToSynthetic:
2393 if (!root->IsSynthetic()) {
2394 child_valobj_sp = root->GetSyntheticValue();
2395 if (child_valobj_sp.get())
2396 child_valobj_sp =
2397 child_valobj_sp->GetChildMemberWithName(child_name, true);
2398 }
2399 break;
2400 case GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2401 Both:
2402 if (root->IsSynthetic()) {
2403 child_valobj_sp = root->GetNonSyntheticValue();
2404 if (child_valobj_sp.get())
2405 child_valobj_sp =
2406 child_valobj_sp->GetChildMemberWithName(child_name, true);
2407 } else {
2408 child_valobj_sp = root->GetSyntheticValue();
2409 if (child_valobj_sp.get())
2410 child_valobj_sp =
2411 child_valobj_sp->GetChildMemberWithName(child_name, true);
2412 }
2413 break;
2414 }
2415 }
2416
2417 // if we are here and options.m_no_synthetic_children is true,
2418 // child_valobj_sp is going to be a NULL SP, so we hit the "else"
2419 // branch, and return an error
2420 if (child_valobj_sp.get()) // if it worked, move on
2421 {
2422 root = child_valobj_sp;
2423 remainder = next_separator;
2424 *final_result = ValueObject::eExpressionPathEndResultTypePlain;
2425 continue;
2426 } else {
2427 *reason_to_stop =
2428 ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2429 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2430 return nullptr;
2431 }
2432 }
2433 break;
2434 }
2435 case '[': {
2436 if (!root_compiler_type_info.Test(eTypeIsArray) &&
2437 !root_compiler_type_info.Test(eTypeIsPointer) &&
2438 !root_compiler_type_info.Test(
2439 eTypeIsVector)) // if this is not a T[] nor a T*
2440 {
2441 if (!root_compiler_type_info.Test(
2442 eTypeIsScalar)) // if this is not even a scalar...
2443 {
2444 if (options.m_synthetic_children_traversal ==
2445 GetValueForExpressionPathOptions::SyntheticChildrenTraversal::
2446 None) // ...only chance left is synthetic
2447 {
2448 *reason_to_stop =
2449 ValueObject::eExpressionPathScanEndReasonRangeOperatorInvalid;
2450 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2451 return ValueObjectSP();
2452 }
2453 } else if (!options.m_allow_bitfields_syntax) // if this is a scalar,
2454 // check that we can
2455 // expand bitfields
2456 {
2457 *reason_to_stop =
2458 ValueObject::eExpressionPathScanEndReasonRangeOperatorNotAllowed;
2459 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2460 return ValueObjectSP();
2461 }
2462 }
2463 if (temp_expression[1] ==
2464 ']') // if this is an unbounded range it only works for arrays
2465 {
2466 if (!root_compiler_type_info.Test(eTypeIsArray)) {
2467 *reason_to_stop =
2468 ValueObject::eExpressionPathScanEndReasonEmptyRangeNotAllowed;
2469 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2470 return nullptr;
2471 } else // even if something follows, we cannot expand unbounded ranges,
2472 // just let the caller do it
2473 {
2474 *reason_to_stop =
2475 ValueObject::eExpressionPathScanEndReasonArrayRangeOperatorMet;
2476 *final_result =
2477 ValueObject::eExpressionPathEndResultTypeUnboundedRange;
2478 return root;
2479 }
2480 }
2481
2482 size_t close_bracket_position = temp_expression.find(']', 1);
2483 if (close_bracket_position ==
2484 llvm::StringRef::npos) // if there is no ], this is a syntax error
2485 {
2486 *reason_to_stop =
2487 ValueObject::eExpressionPathScanEndReasonUnexpectedSymbol;
2488 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2489 return nullptr;
2490 }
2491
2492 llvm::StringRef bracket_expr =
2493 temp_expression.slice(1, close_bracket_position);
2494
2495 // If this was an empty expression it would have been caught by the if
2496 // above.
2497 assert(!bracket_expr.empty());
2498
2499 if (!bracket_expr.contains('-')) {
2500 // if no separator, this is of the form [N]. Note that this cannot be
2501 // an unbounded range of the form [], because that case was handled
2502 // above with an unconditional return.
2503 unsigned long index = 0;
2504 if (bracket_expr.getAsInteger(0, index)) {
2505 *reason_to_stop =
2506 ValueObject::eExpressionPathScanEndReasonUnexpectedSymbol;
2507 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2508 return nullptr;
2509 }
2510
2511 // from here on we do have a valid index
2512 if (root_compiler_type_info.Test(eTypeIsArray)) {
2513 ValueObjectSP child_valobj_sp = root->GetChildAtIndex(index, true);
2514 if (!child_valobj_sp)
2515 child_valobj_sp = root->GetSyntheticArrayMember(index, true);
2516 if (!child_valobj_sp)
2517 if (root->HasSyntheticValue() &&
2518 root->GetSyntheticValue()->GetNumChildren() > index)
2519 child_valobj_sp =
2520 root->GetSyntheticValue()->GetChildAtIndex(index, true);
2521 if (child_valobj_sp) {
2522 root = child_valobj_sp;
2523 remainder =
2524 temp_expression.substr(close_bracket_position + 1); // skip ]
2525 *final_result = ValueObject::eExpressionPathEndResultTypePlain;
2526 continue;
2527 } else {
2528 *reason_to_stop =
2529 ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2530 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2531 return nullptr;
2532 }
2533 } else if (root_compiler_type_info.Test(eTypeIsPointer)) {
2534 if (*what_next ==
2535 ValueObject::
2536 eExpressionPathAftermathDereference && // if this is a
2537 // ptr-to-scalar, I
2538 // am accessing it
2539 // by index and I
2540 // would have
2541 // deref'ed anyway,
2542 // then do it now
2543 // and use this as
2544 // a bitfield
2545 pointee_compiler_type_info.Test(eTypeIsScalar)) {
2546 Status error;
2547 root = root->Dereference(error);
2548 if (error.Fail() || !root) {
2549 *reason_to_stop =
2550 ValueObject::eExpressionPathScanEndReasonDereferencingFailed;
2551 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2552 return nullptr;
2553 } else {
2554 *what_next = eExpressionPathAftermathNothing;
2555 continue;
2556 }
2557 } else {
2558 if (root->GetCompilerType().GetMinimumLanguage() ==
2559 eLanguageTypeObjC &&
2560 pointee_compiler_type_info.AllClear(eTypeIsPointer) &&
2561 root->HasSyntheticValue() &&
2562 (options.m_synthetic_children_traversal ==
2563 GetValueForExpressionPathOptions::
2564 SyntheticChildrenTraversal::ToSynthetic ||
2565 options.m_synthetic_children_traversal ==
2566 GetValueForExpressionPathOptions::
2567 SyntheticChildrenTraversal::Both)) {
2568 root = root->GetSyntheticValue()->GetChildAtIndex(index, true);
2569 } else
2570 root = root->GetSyntheticArrayMember(index, true);
2571 if (!root) {
2572 *reason_to_stop =
2573 ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2574 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2575 return nullptr;
2576 } else {
2577 remainder =
2578 temp_expression.substr(close_bracket_position + 1); // skip ]
2579 *final_result = ValueObject::eExpressionPathEndResultTypePlain;
2580 continue;
2581 }
2582 }
2583 } else if (root_compiler_type_info.Test(eTypeIsScalar)) {
2584 root = root->GetSyntheticBitFieldChild(index, index, true);
2585 if (!root) {
2586 *reason_to_stop =
2587 ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2588 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2589 return nullptr;
2590 } else // we do not know how to expand members of bitfields, so we
2591 // just return and let the caller do any further processing
2592 {
2593 *reason_to_stop = ValueObject::
2594 eExpressionPathScanEndReasonBitfieldRangeOperatorMet;
2595 *final_result = ValueObject::eExpressionPathEndResultTypeBitfield;
2596 return root;
2597 }
2598 } else if (root_compiler_type_info.Test(eTypeIsVector)) {
2599 root = root->GetChildAtIndex(index, true);
2600 if (!root) {
2601 *reason_to_stop =
2602 ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2603 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2604 return ValueObjectSP();
2605 } else {
2606 remainder =
2607 temp_expression.substr(close_bracket_position + 1); // skip ]
2608 *final_result = ValueObject::eExpressionPathEndResultTypePlain;
2609 continue;
2610 }
2611 } else if (options.m_synthetic_children_traversal ==
2612 GetValueForExpressionPathOptions::
2613 SyntheticChildrenTraversal::ToSynthetic ||
2614 options.m_synthetic_children_traversal ==
2615 GetValueForExpressionPathOptions::
2616 SyntheticChildrenTraversal::Both) {
2617 if (root->HasSyntheticValue())
2618 root = root->GetSyntheticValue();
2619 else if (!root->IsSynthetic()) {
2620 *reason_to_stop =
2621 ValueObject::eExpressionPathScanEndReasonSyntheticValueMissing;
2622 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2623 return nullptr;
2624 }
2625 // if we are here, then root itself is a synthetic VO.. should be
2626 // good to go
2627
2628 if (!root) {
2629 *reason_to_stop =
2630 ValueObject::eExpressionPathScanEndReasonSyntheticValueMissing;
2631 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2632 return nullptr;
2633 }
2634 root = root->GetChildAtIndex(index, true);
2635 if (!root) {
2636 *reason_to_stop =
2637 ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2638 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2639 return nullptr;
2640 } else {
2641 remainder =
2642 temp_expression.substr(close_bracket_position + 1); // skip ]
2643 *final_result = ValueObject::eExpressionPathEndResultTypePlain;
2644 continue;
2645 }
2646 } else {
2647 *reason_to_stop =
2648 ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2649 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2650 return nullptr;
2651 }
2652 } else {
2653 // we have a low and a high index
2654 llvm::StringRef sleft, sright;
2655 unsigned long low_index, high_index;
2656 std::tie(sleft, sright) = bracket_expr.split('-');
2657 if (sleft.getAsInteger(0, low_index) ||
2658 sright.getAsInteger(0, high_index)) {
2659 *reason_to_stop =
2660 ValueObject::eExpressionPathScanEndReasonUnexpectedSymbol;
2661 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2662 return nullptr;
2663 }
2664
2665 if (low_index > high_index) // swap indices if required
2666 std::swap(low_index, high_index);
2667
2668 if (root_compiler_type_info.Test(
2669 eTypeIsScalar)) // expansion only works for scalars
2670 {
2671 root = root->GetSyntheticBitFieldChild(low_index, high_index, true);
2672 if (!root) {
2673 *reason_to_stop =
2674 ValueObject::eExpressionPathScanEndReasonNoSuchChild;
2675 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2676 return nullptr;
2677 } else {
2678 *reason_to_stop = ValueObject::
2679 eExpressionPathScanEndReasonBitfieldRangeOperatorMet;
2680 *final_result = ValueObject::eExpressionPathEndResultTypeBitfield;
2681 return root;
2682 }
2683 } else if (root_compiler_type_info.Test(
2684 eTypeIsPointer) && // if this is a ptr-to-scalar, I am
2685 // accessing it by index and I would
2686 // have deref'ed anyway, then do it
2687 // now and use this as a bitfield
2688 *what_next ==
2689 ValueObject::eExpressionPathAftermathDereference &&
2690 pointee_compiler_type_info.Test(eTypeIsScalar)) {
2691 Status error;
2692 root = root->Dereference(error);
2693 if (error.Fail() || !root) {
2694 *reason_to_stop =
2695 ValueObject::eExpressionPathScanEndReasonDereferencingFailed;
2696 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2697 return nullptr;
2698 } else {
2699 *what_next = ValueObject::eExpressionPathAftermathNothing;
2700 continue;
2701 }
2702 } else {
2703 *reason_to_stop =
2704 ValueObject::eExpressionPathScanEndReasonArrayRangeOperatorMet;
2705 *final_result = ValueObject::eExpressionPathEndResultTypeBoundedRange;
2706 return root;
2707 }
2708 }
2709 break;
2710 }
2711 default: // some non-separator is in the way
2712 {
2713 *reason_to_stop =
2714 ValueObject::eExpressionPathScanEndReasonUnexpectedSymbol;
2715 *final_result = ValueObject::eExpressionPathEndResultTypeInvalid;
2716 return nullptr;
2717 }
2718 }
2719 }
2720 }
2721
LogValueObject(Log * log)2722 void ValueObject::LogValueObject(Log *log) {
2723 if (log)
2724 return LogValueObject(log, DumpValueObjectOptions(*this));
2725 }
2726
LogValueObject(Log * log,const DumpValueObjectOptions & options)2727 void ValueObject::LogValueObject(Log *log,
2728 const DumpValueObjectOptions &options) {
2729 if (log) {
2730 StreamString s;
2731 Dump(s, options);
2732 if (s.GetSize())
2733 log->PutCString(s.GetData());
2734 }
2735 }
2736
Dump(Stream & s)2737 void ValueObject::Dump(Stream &s) { Dump(s, DumpValueObjectOptions(*this)); }
2738
Dump(Stream & s,const DumpValueObjectOptions & options)2739 void ValueObject::Dump(Stream &s, const DumpValueObjectOptions &options) {
2740 ValueObjectPrinter printer(this, &s, options);
2741 printer.PrintValueObject();
2742 }
2743
CreateConstantValue(const ConstString & name)2744 ValueObjectSP ValueObject::CreateConstantValue(const ConstString &name) {
2745 ValueObjectSP valobj_sp;
2746
2747 if (UpdateValueIfNeeded(false) && m_error.Success()) {
2748 ExecutionContext exe_ctx(GetExecutionContextRef());
2749
2750 DataExtractor data;
2751 data.SetByteOrder(m_data.GetByteOrder());
2752 data.SetAddressByteSize(m_data.GetAddressByteSize());
2753
2754 if (IsBitfield()) {
2755 Value v(Scalar(GetValueAsUnsigned(UINT64_MAX)));
2756 m_error = v.GetValueAsData(&exe_ctx, data, 0, GetModule().get());
2757 } else
2758 m_error = m_value.GetValueAsData(&exe_ctx, data, 0, GetModule().get());
2759
2760 valobj_sp = ValueObjectConstResult::Create(
2761 exe_ctx.GetBestExecutionContextScope(), GetCompilerType(), name, data,
2762 GetAddressOf());
2763 }
2764
2765 if (!valobj_sp) {
2766 ExecutionContext exe_ctx(GetExecutionContextRef());
2767 valobj_sp = ValueObjectConstResult::Create(
2768 exe_ctx.GetBestExecutionContextScope(), m_error);
2769 }
2770 return valobj_sp;
2771 }
2772
GetQualifiedRepresentationIfAvailable(lldb::DynamicValueType dynValue,bool synthValue)2773 ValueObjectSP ValueObject::GetQualifiedRepresentationIfAvailable(
2774 lldb::DynamicValueType dynValue, bool synthValue) {
2775 ValueObjectSP result_sp(GetSP());
2776
2777 switch (dynValue) {
2778 case lldb::eDynamicCanRunTarget:
2779 case lldb::eDynamicDontRunTarget: {
2780 if (!result_sp->IsDynamic()) {
2781 if (result_sp->GetDynamicValue(dynValue))
2782 result_sp = result_sp->GetDynamicValue(dynValue);
2783 }
2784 } break;
2785 case lldb::eNoDynamicValues: {
2786 if (result_sp->IsDynamic()) {
2787 if (result_sp->GetStaticValue())
2788 result_sp = result_sp->GetStaticValue();
2789 }
2790 } break;
2791 }
2792
2793 if (synthValue) {
2794 if (!result_sp->IsSynthetic()) {
2795 if (result_sp->GetSyntheticValue())
2796 result_sp = result_sp->GetSyntheticValue();
2797 }
2798 } else {
2799 if (result_sp->IsSynthetic()) {
2800 if (result_sp->GetNonSyntheticValue())
2801 result_sp = result_sp->GetNonSyntheticValue();
2802 }
2803 }
2804
2805 return result_sp;
2806 }
2807
Dereference(Status & error)2808 ValueObjectSP ValueObject::Dereference(Status &error) {
2809 if (m_deref_valobj)
2810 return m_deref_valobj->GetSP();
2811
2812 const bool is_pointer_or_reference_type = IsPointerOrReferenceType();
2813 if (is_pointer_or_reference_type) {
2814 bool omit_empty_base_classes = true;
2815 bool ignore_array_bounds = false;
2816
2817 std::string child_name_str;
2818 uint32_t child_byte_size = 0;
2819 int32_t child_byte_offset = 0;
2820 uint32_t child_bitfield_bit_size = 0;
2821 uint32_t child_bitfield_bit_offset = 0;
2822 bool child_is_base_class = false;
2823 bool child_is_deref_of_parent = false;
2824 const bool transparent_pointers = false;
2825 CompilerType compiler_type = GetCompilerType();
2826 CompilerType child_compiler_type;
2827 uint64_t language_flags;
2828
2829 ExecutionContext exe_ctx(GetExecutionContextRef());
2830
2831 child_compiler_type = compiler_type.GetChildCompilerTypeAtIndex(
2832 &exe_ctx, 0, transparent_pointers, omit_empty_base_classes,
2833 ignore_array_bounds, child_name_str, child_byte_size, child_byte_offset,
2834 child_bitfield_bit_size, child_bitfield_bit_offset, child_is_base_class,
2835 child_is_deref_of_parent, this, language_flags);
2836 if (child_compiler_type && child_byte_size) {
2837 ConstString child_name;
2838 if (!child_name_str.empty())
2839 child_name.SetCString(child_name_str.c_str());
2840
2841 m_deref_valobj = new ValueObjectChild(
2842 *this, child_compiler_type, child_name, child_byte_size,
2843 child_byte_offset, child_bitfield_bit_size, child_bitfield_bit_offset,
2844 child_is_base_class, child_is_deref_of_parent, eAddressTypeInvalid,
2845 language_flags);
2846 }
2847 } else if (HasSyntheticValue()) {
2848 m_deref_valobj =
2849 GetSyntheticValue()
2850 ->GetChildMemberWithName(ConstString("$$dereference$$"), true)
2851 .get();
2852 }
2853
2854 if (m_deref_valobj) {
2855 error.Clear();
2856 return m_deref_valobj->GetSP();
2857 } else {
2858 StreamString strm;
2859 GetExpressionPath(strm, true);
2860
2861 if (is_pointer_or_reference_type)
2862 error.SetErrorStringWithFormat("dereference failed: (%s) %s",
2863 GetTypeName().AsCString("<invalid type>"),
2864 strm.GetData());
2865 else
2866 error.SetErrorStringWithFormat("not a pointer or reference type: (%s) %s",
2867 GetTypeName().AsCString("<invalid type>"),
2868 strm.GetData());
2869 return ValueObjectSP();
2870 }
2871 }
2872
AddressOf(Status & error)2873 ValueObjectSP ValueObject::AddressOf(Status &error) {
2874 if (m_addr_of_valobj_sp)
2875 return m_addr_of_valobj_sp;
2876
2877 AddressType address_type = eAddressTypeInvalid;
2878 const bool scalar_is_load_address = false;
2879 addr_t addr = GetAddressOf(scalar_is_load_address, &address_type);
2880 error.Clear();
2881 if (addr != LLDB_INVALID_ADDRESS && address_type != eAddressTypeHost) {
2882 switch (address_type) {
2883 case eAddressTypeInvalid: {
2884 StreamString expr_path_strm;
2885 GetExpressionPath(expr_path_strm, true);
2886 error.SetErrorStringWithFormat("'%s' is not in memory",
2887 expr_path_strm.GetData());
2888 } break;
2889
2890 case eAddressTypeFile:
2891 case eAddressTypeLoad: {
2892 CompilerType compiler_type = GetCompilerType();
2893 if (compiler_type) {
2894 std::string name(1, '&');
2895 name.append(m_name.AsCString(""));
2896 ExecutionContext exe_ctx(GetExecutionContextRef());
2897 m_addr_of_valobj_sp = ValueObjectConstResult::Create(
2898 exe_ctx.GetBestExecutionContextScope(),
2899 compiler_type.GetPointerType(), ConstString(name.c_str()), addr,
2900 eAddressTypeInvalid, m_data.GetAddressByteSize());
2901 }
2902 } break;
2903 default:
2904 break;
2905 }
2906 } else {
2907 StreamString expr_path_strm;
2908 GetExpressionPath(expr_path_strm, true);
2909 error.SetErrorStringWithFormat("'%s' doesn't have a valid address",
2910 expr_path_strm.GetData());
2911 }
2912
2913 return m_addr_of_valobj_sp;
2914 }
2915
Cast(const CompilerType & compiler_type)2916 ValueObjectSP ValueObject::Cast(const CompilerType &compiler_type) {
2917 return ValueObjectCast::Create(*this, GetName(), compiler_type);
2918 }
2919
Clone(const ConstString & new_name)2920 lldb::ValueObjectSP ValueObject::Clone(const ConstString &new_name) {
2921 return ValueObjectCast::Create(*this, new_name, GetCompilerType());
2922 }
2923
CastPointerType(const char * name,CompilerType & compiler_type)2924 ValueObjectSP ValueObject::CastPointerType(const char *name,
2925 CompilerType &compiler_type) {
2926 ValueObjectSP valobj_sp;
2927 AddressType address_type;
2928 addr_t ptr_value = GetPointerValue(&address_type);
2929
2930 if (ptr_value != LLDB_INVALID_ADDRESS) {
2931 Address ptr_addr(ptr_value);
2932 ExecutionContext exe_ctx(GetExecutionContextRef());
2933 valobj_sp = ValueObjectMemory::Create(
2934 exe_ctx.GetBestExecutionContextScope(), name, ptr_addr, compiler_type);
2935 }
2936 return valobj_sp;
2937 }
2938
CastPointerType(const char * name,TypeSP & type_sp)2939 ValueObjectSP ValueObject::CastPointerType(const char *name, TypeSP &type_sp) {
2940 ValueObjectSP valobj_sp;
2941 AddressType address_type;
2942 addr_t ptr_value = GetPointerValue(&address_type);
2943
2944 if (ptr_value != LLDB_INVALID_ADDRESS) {
2945 Address ptr_addr(ptr_value);
2946 ExecutionContext exe_ctx(GetExecutionContextRef());
2947 valobj_sp = ValueObjectMemory::Create(
2948 exe_ctx.GetBestExecutionContextScope(), name, ptr_addr, type_sp);
2949 }
2950 return valobj_sp;
2951 }
2952
EvaluationPoint()2953 ValueObject::EvaluationPoint::EvaluationPoint()
2954 : m_mod_id(), m_exe_ctx_ref(), m_needs_update(true) {}
2955
EvaluationPoint(ExecutionContextScope * exe_scope,bool use_selected)2956 ValueObject::EvaluationPoint::EvaluationPoint(ExecutionContextScope *exe_scope,
2957 bool use_selected)
2958 : m_mod_id(), m_exe_ctx_ref(), m_needs_update(true) {
2959 ExecutionContext exe_ctx(exe_scope);
2960 TargetSP target_sp(exe_ctx.GetTargetSP());
2961 if (target_sp) {
2962 m_exe_ctx_ref.SetTargetSP(target_sp);
2963 ProcessSP process_sp(exe_ctx.GetProcessSP());
2964 if (!process_sp)
2965 process_sp = target_sp->GetProcessSP();
2966
2967 if (process_sp) {
2968 m_mod_id = process_sp->GetModID();
2969 m_exe_ctx_ref.SetProcessSP(process_sp);
2970
2971 ThreadSP thread_sp(exe_ctx.GetThreadSP());
2972
2973 if (!thread_sp) {
2974 if (use_selected)
2975 thread_sp = process_sp->GetThreadList().GetSelectedThread();
2976 }
2977
2978 if (thread_sp) {
2979 m_exe_ctx_ref.SetThreadSP(thread_sp);
2980
2981 StackFrameSP frame_sp(exe_ctx.GetFrameSP());
2982 if (!frame_sp) {
2983 if (use_selected)
2984 frame_sp = thread_sp->GetSelectedFrame();
2985 }
2986 if (frame_sp)
2987 m_exe_ctx_ref.SetFrameSP(frame_sp);
2988 }
2989 }
2990 }
2991 }
2992
EvaluationPoint(const ValueObject::EvaluationPoint & rhs)2993 ValueObject::EvaluationPoint::EvaluationPoint(
2994 const ValueObject::EvaluationPoint &rhs)
2995 : m_mod_id(), m_exe_ctx_ref(rhs.m_exe_ctx_ref), m_needs_update(true) {}
2996
~EvaluationPoint()2997 ValueObject::EvaluationPoint::~EvaluationPoint() {}
2998
2999 // This function checks the EvaluationPoint against the current process state.
3000 // If the current state matches the evaluation point, or the evaluation point
3001 // is already invalid, then we return false, meaning "no change". If the
3002 // current state is different, we update our state, and return true meaning
3003 // "yes, change". If we did see a change, we also set m_needs_update to true,
3004 // so future calls to NeedsUpdate will return true. exe_scope will be set to
3005 // the current execution context scope.
3006
SyncWithProcessState(bool accept_invalid_exe_ctx)3007 bool ValueObject::EvaluationPoint::SyncWithProcessState(
3008 bool accept_invalid_exe_ctx) {
3009 // Start with the target, if it is NULL, then we're obviously not going to
3010 // get any further:
3011 const bool thread_and_frame_only_if_stopped = true;
3012 ExecutionContext exe_ctx(
3013 m_exe_ctx_ref.Lock(thread_and_frame_only_if_stopped));
3014
3015 if (exe_ctx.GetTargetPtr() == NULL)
3016 return false;
3017
3018 // If we don't have a process nothing can change.
3019 Process *process = exe_ctx.GetProcessPtr();
3020 if (process == NULL)
3021 return false;
3022
3023 // If our stop id is the current stop ID, nothing has changed:
3024 ProcessModID current_mod_id = process->GetModID();
3025
3026 // If the current stop id is 0, either we haven't run yet, or the process
3027 // state has been cleared. In either case, we aren't going to be able to sync
3028 // with the process state.
3029 if (current_mod_id.GetStopID() == 0)
3030 return false;
3031
3032 bool changed = false;
3033 const bool was_valid = m_mod_id.IsValid();
3034 if (was_valid) {
3035 if (m_mod_id == current_mod_id) {
3036 // Everything is already up to date in this object, no need to update the
3037 // execution context scope.
3038 changed = false;
3039 } else {
3040 m_mod_id = current_mod_id;
3041 m_needs_update = true;
3042 changed = true;
3043 }
3044 }
3045
3046 // Now re-look up the thread and frame in case the underlying objects have
3047 // gone away & been recreated. That way we'll be sure to return a valid
3048 // exe_scope. If we used to have a thread or a frame but can't find it
3049 // anymore, then mark ourselves as invalid.
3050
3051 if (!accept_invalid_exe_ctx) {
3052 if (m_exe_ctx_ref.HasThreadRef()) {
3053 ThreadSP thread_sp(m_exe_ctx_ref.GetThreadSP());
3054 if (thread_sp) {
3055 if (m_exe_ctx_ref.HasFrameRef()) {
3056 StackFrameSP frame_sp(m_exe_ctx_ref.GetFrameSP());
3057 if (!frame_sp) {
3058 // We used to have a frame, but now it is gone
3059 SetInvalid();
3060 changed = was_valid;
3061 }
3062 }
3063 } else {
3064 // We used to have a thread, but now it is gone
3065 SetInvalid();
3066 changed = was_valid;
3067 }
3068 }
3069 }
3070
3071 return changed;
3072 }
3073
SetUpdated()3074 void ValueObject::EvaluationPoint::SetUpdated() {
3075 ProcessSP process_sp(m_exe_ctx_ref.GetProcessSP());
3076 if (process_sp)
3077 m_mod_id = process_sp->GetModID();
3078 m_needs_update = false;
3079 }
3080
ClearUserVisibleData(uint32_t clear_mask)3081 void ValueObject::ClearUserVisibleData(uint32_t clear_mask) {
3082 if ((clear_mask & eClearUserVisibleDataItemsValue) ==
3083 eClearUserVisibleDataItemsValue)
3084 m_value_str.clear();
3085
3086 if ((clear_mask & eClearUserVisibleDataItemsLocation) ==
3087 eClearUserVisibleDataItemsLocation)
3088 m_location_str.clear();
3089
3090 if ((clear_mask & eClearUserVisibleDataItemsSummary) ==
3091 eClearUserVisibleDataItemsSummary)
3092 m_summary_str.clear();
3093
3094 if ((clear_mask & eClearUserVisibleDataItemsDescription) ==
3095 eClearUserVisibleDataItemsDescription)
3096 m_object_desc_str.clear();
3097
3098 if ((clear_mask & eClearUserVisibleDataItemsSyntheticChildren) ==
3099 eClearUserVisibleDataItemsSyntheticChildren) {
3100 if (m_synthetic_value)
3101 m_synthetic_value = NULL;
3102 }
3103
3104 if ((clear_mask & eClearUserVisibleDataItemsValidator) ==
3105 eClearUserVisibleDataItemsValidator)
3106 m_validation_result.reset();
3107 }
3108
GetSymbolContextScope()3109 SymbolContextScope *ValueObject::GetSymbolContextScope() {
3110 if (m_parent) {
3111 if (!m_parent->IsPointerOrReferenceType())
3112 return m_parent->GetSymbolContextScope();
3113 }
3114 return NULL;
3115 }
3116
3117 lldb::ValueObjectSP
CreateValueObjectFromExpression(llvm::StringRef name,llvm::StringRef expression,const ExecutionContext & exe_ctx)3118 ValueObject::CreateValueObjectFromExpression(llvm::StringRef name,
3119 llvm::StringRef expression,
3120 const ExecutionContext &exe_ctx) {
3121 return CreateValueObjectFromExpression(name, expression, exe_ctx,
3122 EvaluateExpressionOptions());
3123 }
3124
CreateValueObjectFromExpression(llvm::StringRef name,llvm::StringRef expression,const ExecutionContext & exe_ctx,const EvaluateExpressionOptions & options)3125 lldb::ValueObjectSP ValueObject::CreateValueObjectFromExpression(
3126 llvm::StringRef name, llvm::StringRef expression,
3127 const ExecutionContext &exe_ctx, const EvaluateExpressionOptions &options) {
3128 lldb::ValueObjectSP retval_sp;
3129 lldb::TargetSP target_sp(exe_ctx.GetTargetSP());
3130 if (!target_sp)
3131 return retval_sp;
3132 if (expression.empty())
3133 return retval_sp;
3134 target_sp->EvaluateExpression(expression, exe_ctx.GetFrameSP().get(),
3135 retval_sp, options);
3136 if (retval_sp && !name.empty())
3137 retval_sp->SetName(ConstString(name));
3138 return retval_sp;
3139 }
3140
CreateValueObjectFromAddress(llvm::StringRef name,uint64_t address,const ExecutionContext & exe_ctx,CompilerType type)3141 lldb::ValueObjectSP ValueObject::CreateValueObjectFromAddress(
3142 llvm::StringRef name, uint64_t address, const ExecutionContext &exe_ctx,
3143 CompilerType type) {
3144 if (type) {
3145 CompilerType pointer_type(type.GetPointerType());
3146 if (pointer_type) {
3147 lldb::DataBufferSP buffer(
3148 new lldb_private::DataBufferHeap(&address, sizeof(lldb::addr_t)));
3149 lldb::ValueObjectSP ptr_result_valobj_sp(ValueObjectConstResult::Create(
3150 exe_ctx.GetBestExecutionContextScope(), pointer_type,
3151 ConstString(name), buffer, exe_ctx.GetByteOrder(),
3152 exe_ctx.GetAddressByteSize()));
3153 if (ptr_result_valobj_sp) {
3154 ptr_result_valobj_sp->GetValue().SetValueType(
3155 Value::eValueTypeLoadAddress);
3156 Status err;
3157 ptr_result_valobj_sp = ptr_result_valobj_sp->Dereference(err);
3158 if (ptr_result_valobj_sp && !name.empty())
3159 ptr_result_valobj_sp->SetName(ConstString(name));
3160 }
3161 return ptr_result_valobj_sp;
3162 }
3163 }
3164 return lldb::ValueObjectSP();
3165 }
3166
CreateValueObjectFromData(llvm::StringRef name,const DataExtractor & data,const ExecutionContext & exe_ctx,CompilerType type)3167 lldb::ValueObjectSP ValueObject::CreateValueObjectFromData(
3168 llvm::StringRef name, const DataExtractor &data,
3169 const ExecutionContext &exe_ctx, CompilerType type) {
3170 lldb::ValueObjectSP new_value_sp;
3171 new_value_sp = ValueObjectConstResult::Create(
3172 exe_ctx.GetBestExecutionContextScope(), type, ConstString(name), data,
3173 LLDB_INVALID_ADDRESS);
3174 new_value_sp->SetAddressTypeOfChildren(eAddressTypeLoad);
3175 if (new_value_sp && !name.empty())
3176 new_value_sp->SetName(ConstString(name));
3177 return new_value_sp;
3178 }
3179
GetModule()3180 ModuleSP ValueObject::GetModule() {
3181 ValueObject *root(GetRoot());
3182 if (root != this)
3183 return root->GetModule();
3184 return lldb::ModuleSP();
3185 }
3186
GetRoot()3187 ValueObject *ValueObject::GetRoot() {
3188 if (m_root)
3189 return m_root;
3190 return (m_root = FollowParentChain([](ValueObject *vo) -> bool {
3191 return (vo->m_parent != nullptr);
3192 }));
3193 }
3194
3195 ValueObject *
FollowParentChain(std::function<bool (ValueObject *)> f)3196 ValueObject::FollowParentChain(std::function<bool(ValueObject *)> f) {
3197 ValueObject *vo = this;
3198 while (vo) {
3199 if (!f(vo))
3200 break;
3201 vo = vo->m_parent;
3202 }
3203 return vo;
3204 }
3205
GetAddressTypeOfChildren()3206 AddressType ValueObject::GetAddressTypeOfChildren() {
3207 if (m_address_type_of_ptr_or_ref_children == eAddressTypeInvalid) {
3208 ValueObject *root(GetRoot());
3209 if (root != this)
3210 return root->GetAddressTypeOfChildren();
3211 }
3212 return m_address_type_of_ptr_or_ref_children;
3213 }
3214
GetDynamicValueType()3215 lldb::DynamicValueType ValueObject::GetDynamicValueType() {
3216 ValueObject *with_dv_info = this;
3217 while (with_dv_info) {
3218 if (with_dv_info->HasDynamicValueTypeInfo())
3219 return with_dv_info->GetDynamicValueTypeImpl();
3220 with_dv_info = with_dv_info->m_parent;
3221 }
3222 return lldb::eNoDynamicValues;
3223 }
3224
GetFormat() const3225 lldb::Format ValueObject::GetFormat() const {
3226 const ValueObject *with_fmt_info = this;
3227 while (with_fmt_info) {
3228 if (with_fmt_info->m_format != lldb::eFormatDefault)
3229 return with_fmt_info->m_format;
3230 with_fmt_info = with_fmt_info->m_parent;
3231 }
3232 return m_format;
3233 }
3234
GetPreferredDisplayLanguage()3235 lldb::LanguageType ValueObject::GetPreferredDisplayLanguage() {
3236 lldb::LanguageType type = m_preferred_display_language;
3237 if (m_preferred_display_language == lldb::eLanguageTypeUnknown) {
3238 if (GetRoot()) {
3239 if (GetRoot() == this) {
3240 if (StackFrameSP frame_sp = GetFrameSP()) {
3241 const SymbolContext &sc(
3242 frame_sp->GetSymbolContext(eSymbolContextCompUnit));
3243 if (CompileUnit *cu = sc.comp_unit)
3244 type = cu->GetLanguage();
3245 }
3246 } else {
3247 type = GetRoot()->GetPreferredDisplayLanguage();
3248 }
3249 }
3250 }
3251 return (m_preferred_display_language = type); // only compute it once
3252 }
3253
SetPreferredDisplayLanguage(lldb::LanguageType lt)3254 void ValueObject::SetPreferredDisplayLanguage(lldb::LanguageType lt) {
3255 m_preferred_display_language = lt;
3256 }
3257
SetPreferredDisplayLanguageIfNeeded(lldb::LanguageType lt)3258 void ValueObject::SetPreferredDisplayLanguageIfNeeded(lldb::LanguageType lt) {
3259 if (m_preferred_display_language == lldb::eLanguageTypeUnknown)
3260 SetPreferredDisplayLanguage(lt);
3261 }
3262
CanProvideValue()3263 bool ValueObject::CanProvideValue() {
3264 // we need to support invalid types as providers of values because some bare-
3265 // board debugging scenarios have no notion of types, but still manage to
3266 // have raw numeric values for things like registers. sigh.
3267 const CompilerType &type(GetCompilerType());
3268 return (!type.IsValid()) || (0 != (type.GetTypeInfo() & eTypeHasValue));
3269 }
3270
IsChecksumEmpty()3271 bool ValueObject::IsChecksumEmpty() { return m_value_checksum.empty(); }
3272
Persist()3273 ValueObjectSP ValueObject::Persist() {
3274 if (!UpdateValueIfNeeded())
3275 return nullptr;
3276
3277 TargetSP target_sp(GetTargetSP());
3278 if (!target_sp)
3279 return nullptr;
3280
3281 PersistentExpressionState *persistent_state =
3282 target_sp->GetPersistentExpressionStateForLanguage(
3283 GetPreferredDisplayLanguage());
3284
3285 if (!persistent_state)
3286 return nullptr;
3287
3288 auto prefix = persistent_state->GetPersistentVariablePrefix();
3289 ConstString name =
3290 persistent_state->GetNextPersistentVariableName(*target_sp, prefix);
3291
3292 ValueObjectSP const_result_sp =
3293 ValueObjectConstResult::Create(target_sp.get(), GetValue(), name);
3294
3295 ExpressionVariableSP clang_var_sp =
3296 persistent_state->CreatePersistentVariable(const_result_sp);
3297 clang_var_sp->m_live_sp = clang_var_sp->m_frozen_sp;
3298 clang_var_sp->m_flags |= ExpressionVariable::EVIsProgramReference;
3299
3300 return clang_var_sp->GetValueObject();
3301 }
3302
IsSyntheticChildrenGenerated()3303 bool ValueObject::IsSyntheticChildrenGenerated() {
3304 return m_is_synthetic_children_generated;
3305 }
3306
SetSyntheticChildrenGenerated(bool b)3307 void ValueObject::SetSyntheticChildrenGenerated(bool b) {
3308 m_is_synthetic_children_generated = b;
3309 }
3310
GetLanguageFlags()3311 uint64_t ValueObject::GetLanguageFlags() { return m_language_flags; }
3312
SetLanguageFlags(uint64_t flags)3313 void ValueObject::SetLanguageFlags(uint64_t flags) { m_language_flags = flags; }
3314
ValueObjectManager(lldb::ValueObjectSP in_valobj_sp,lldb::DynamicValueType use_dynamic,bool use_synthetic)3315 ValueObjectManager::ValueObjectManager(lldb::ValueObjectSP in_valobj_sp,
3316 lldb::DynamicValueType use_dynamic,
3317 bool use_synthetic) : m_root_valobj_sp(),
3318 m_user_valobj_sp(), m_use_dynamic(use_dynamic), m_stop_id(UINT32_MAX),
3319 m_use_synthetic(use_synthetic) {
3320 if (!in_valobj_sp)
3321 return;
3322 // If the user passes in a value object that is dynamic or synthetic, then
3323 // water it down to the static type.
3324 m_root_valobj_sp = in_valobj_sp->GetQualifiedRepresentationIfAvailable(lldb::eNoDynamicValues, false);
3325 }
3326
IsValid() const3327 bool ValueObjectManager::IsValid() const {
3328 if (!m_root_valobj_sp)
3329 return false;
3330 lldb::TargetSP target_sp = GetTargetSP();
3331 if (target_sp)
3332 return target_sp->IsValid();
3333 return false;
3334 }
3335
GetSP()3336 lldb::ValueObjectSP ValueObjectManager::GetSP() {
3337 lldb::ProcessSP process_sp = GetProcessSP();
3338 if (!process_sp)
3339 return lldb::ValueObjectSP();
3340
3341 const uint32_t current_stop_id = process_sp->GetLastNaturalStopID();
3342 if (current_stop_id == m_stop_id)
3343 return m_user_valobj_sp;
3344
3345 m_stop_id = current_stop_id;
3346
3347 if (!m_root_valobj_sp) {
3348 m_user_valobj_sp.reset();
3349 return m_root_valobj_sp;
3350 }
3351
3352 m_user_valobj_sp = m_root_valobj_sp;
3353
3354 if (m_use_dynamic != lldb::eNoDynamicValues) {
3355 lldb::ValueObjectSP dynamic_sp = m_user_valobj_sp->GetDynamicValue(m_use_dynamic);
3356 if (dynamic_sp)
3357 m_user_valobj_sp = dynamic_sp;
3358 }
3359
3360 if (m_use_synthetic) {
3361 lldb::ValueObjectSP synthetic_sp = m_user_valobj_sp->GetSyntheticValue(m_use_synthetic);
3362 if (synthetic_sp)
3363 m_user_valobj_sp = synthetic_sp;
3364 }
3365
3366 return m_user_valobj_sp;
3367 }
3368
SetUseDynamic(lldb::DynamicValueType use_dynamic)3369 void ValueObjectManager::SetUseDynamic(lldb::DynamicValueType use_dynamic) {
3370 if (use_dynamic != m_use_dynamic) {
3371 m_use_dynamic = use_dynamic;
3372 m_user_valobj_sp.reset();
3373 m_stop_id = UINT32_MAX;
3374 }
3375 }
3376
SetUseSynthetic(bool use_synthetic)3377 void ValueObjectManager::SetUseSynthetic(bool use_synthetic) {
3378 if (m_use_synthetic != use_synthetic) {
3379 m_use_synthetic = use_synthetic;
3380 m_user_valobj_sp.reset();
3381 m_stop_id = UINT32_MAX;
3382 }
3383 }
3384
GetTargetSP() const3385 lldb::TargetSP ValueObjectManager::GetTargetSP() const {
3386 if (!m_root_valobj_sp)
3387 return m_root_valobj_sp->GetTargetSP();
3388 return lldb::TargetSP();
3389 }
3390
GetProcessSP() const3391 lldb::ProcessSP ValueObjectManager::GetProcessSP() const {
3392 if (m_root_valobj_sp)
3393 return m_root_valobj_sp->GetProcessSP();
3394 return lldb::ProcessSP();
3395 }
3396
GetThreadSP() const3397 lldb::ThreadSP ValueObjectManager::GetThreadSP() const {
3398 if (m_root_valobj_sp)
3399 return m_root_valobj_sp->GetThreadSP();
3400 return lldb::ThreadSP();
3401 }
3402
GetFrameSP() const3403 lldb::StackFrameSP ValueObjectManager::GetFrameSP() const {
3404 if (m_root_valobj_sp)
3405 return m_root_valobj_sp->GetFrameSP();
3406 return lldb::StackFrameSP();
3407 }
3408
3409