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