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