xref: /freebsd/contrib/llvm-project/lldb/include/lldb/ValueObject/ValueObject.h (revision 700637cbb5e582861067a11aaca4d053546871d2)
1 //===-- ValueObject.h -------------------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #ifndef LLDB_VALUEOBJECT_VALUEOBJECT_H
10 #define LLDB_VALUEOBJECT_VALUEOBJECT_H
11 
12 #include "lldb/Core/Value.h"
13 #include "lldb/Symbol/CompilerType.h"
14 #include "lldb/Symbol/Type.h"
15 #include "lldb/Target/ExecutionContext.h"
16 #include "lldb/Target/Process.h"
17 #include "lldb/Utility/ConstString.h"
18 #include "lldb/Utility/DataExtractor.h"
19 #include "lldb/Utility/SharedCluster.h"
20 #include "lldb/Utility/Status.h"
21 #include "lldb/Utility/UserID.h"
22 #include "lldb/lldb-defines.h"
23 #include "lldb/lldb-enumerations.h"
24 #include "lldb/lldb-forward.h"
25 #include "lldb/lldb-private-enumerations.h"
26 #include "lldb/lldb-types.h"
27 
28 #include "llvm/ADT/ArrayRef.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/StringRef.h"
31 
32 #include <functional>
33 #include <initializer_list>
34 #include <map>
35 #include <mutex>
36 #include <optional>
37 #include <string>
38 #include <utility>
39 
40 #include <cstddef>
41 #include <cstdint>
42 
43 namespace lldb_private {
44 class Declaration;
45 class DumpValueObjectOptions;
46 class EvaluateExpressionOptions;
47 class ExecutionContextScope;
48 class Log;
49 class Scalar;
50 class Stream;
51 class SymbolContextScope;
52 class TypeFormatImpl;
53 class TypeSummaryImpl;
54 class TypeSummaryOptions;
55 
56 /// ValueObject:
57 ///
58 /// This abstract class provides an interface to a particular value, be it a
59 /// register, a local or global variable,
60 /// that is evaluated in some particular scope.  The ValueObject also has the
61 /// capability of being the "child" of
62 /// some other variable object, and in turn of having children.
63 /// If a ValueObject is a root variable object - having no parent - then it must
64 /// be constructed with respect to some
65 /// particular ExecutionContextScope.  If it is a child, it inherits the
66 /// ExecutionContextScope from its parent.
67 /// The ValueObject will update itself if necessary before fetching its value,
68 /// summary, object description, etc.
69 /// But it will always update itself in the ExecutionContextScope with which it
70 /// was originally created.
71 
72 /// A brief note on life cycle management for ValueObjects.  This is a little
73 /// tricky because a ValueObject can contain
74 /// various other ValueObjects - the Dynamic Value, its children, the
75 /// dereference value, etc.  Any one of these can be
76 /// handed out as a shared pointer, but for that contained value object to be
77 /// valid, the root object and potentially other
78 /// of the value objects need to stay around.
79 /// We solve this problem by handing out shared pointers to the Value Object and
80 /// any of its dependents using a shared
81 /// ClusterManager.  This treats each shared pointer handed out for the entire
82 /// cluster as a reference to the whole
83 /// cluster.  The whole cluster will stay around until the last reference is
84 /// released.
85 ///
86 /// The ValueObject mostly handle this automatically, if a value object is made
87 /// with a Parent ValueObject, then it adds
88 /// itself to the ClusterManager of the parent.
89 
90 /// It does mean that external to the ValueObjects we should only ever make
91 /// available ValueObjectSP's, never ValueObjects
92 /// or pointers to them.  So all the "Root level" ValueObject derived
93 /// constructors should be private, and
94 /// should implement a Create function that new's up object and returns a Shared
95 /// Pointer that it gets from the GetSP() method.
96 ///
97 /// However, if you are making an derived ValueObject that will be contained in
98 /// a parent value object, you should just
99 /// hold onto a pointer to it internally, and by virtue of passing the parent
100 /// ValueObject into its constructor, it will
101 /// be added to the ClusterManager for the parent.  Then if you ever hand out a
102 /// Shared Pointer to the contained ValueObject,
103 /// just do so by calling GetSP() on the contained object.
104 
105 class ValueObject {
106 public:
107   enum GetExpressionPathFormat {
108     eGetExpressionPathFormatDereferencePointers = 1,
109     eGetExpressionPathFormatHonorPointers
110   };
111 
112   enum ValueObjectRepresentationStyle {
113     eValueObjectRepresentationStyleValue = 1,
114     eValueObjectRepresentationStyleSummary,
115     eValueObjectRepresentationStyleLanguageSpecific,
116     eValueObjectRepresentationStyleLocation,
117     eValueObjectRepresentationStyleChildrenCount,
118     eValueObjectRepresentationStyleType,
119     eValueObjectRepresentationStyleName,
120     eValueObjectRepresentationStyleExpressionPath
121   };
122 
123   enum ExpressionPathScanEndReason {
124     /// Out of data to parse.
125     eExpressionPathScanEndReasonEndOfString = 1,
126     /// Child element not found.
127     eExpressionPathScanEndReasonNoSuchChild,
128     /// (Synthetic) child  element not found.
129     eExpressionPathScanEndReasonNoSuchSyntheticChild,
130     /// [] only allowed for arrays.
131     eExpressionPathScanEndReasonEmptyRangeNotAllowed,
132     /// . used when -> should be used.
133     eExpressionPathScanEndReasonDotInsteadOfArrow,
134     /// -> used when . should be used.
135     eExpressionPathScanEndReasonArrowInsteadOfDot,
136     /// ObjC ivar expansion not allowed.
137     eExpressionPathScanEndReasonFragileIVarNotAllowed,
138     /// [] not allowed by options.
139     eExpressionPathScanEndReasonRangeOperatorNotAllowed,
140     /// [] not valid on objects  other than scalars, pointers or arrays.
141     eExpressionPathScanEndReasonRangeOperatorInvalid,
142     /// [] is good for arrays,  but I cannot parse it.
143     eExpressionPathScanEndReasonArrayRangeOperatorMet,
144     /// [] is good for bitfields, but I cannot parse after it.
145     eExpressionPathScanEndReasonBitfieldRangeOperatorMet,
146     /// Something is malformed in he expression.
147     eExpressionPathScanEndReasonUnexpectedSymbol,
148     /// Impossible to apply &  operator.
149     eExpressionPathScanEndReasonTakingAddressFailed,
150     /// Impossible to apply *  operator.
151     eExpressionPathScanEndReasonDereferencingFailed,
152     /// [] was expanded into a  VOList.
153     eExpressionPathScanEndReasonRangeOperatorExpanded,
154     /// getting the synthetic children failed.
155     eExpressionPathScanEndReasonSyntheticValueMissing,
156     eExpressionPathScanEndReasonUnknown = 0xFFFF
157   };
158 
159   enum ExpressionPathEndResultType {
160     /// Anything but...
161     eExpressionPathEndResultTypePlain = 1,
162     /// A bitfield.
163     eExpressionPathEndResultTypeBitfield,
164     /// A range [low-high].
165     eExpressionPathEndResultTypeBoundedRange,
166     /// A range [].
167     eExpressionPathEndResultTypeUnboundedRange,
168     /// Several items in a VOList.
169     eExpressionPathEndResultTypeValueObjectList,
170     eExpressionPathEndResultTypeInvalid = 0xFFFF
171   };
172 
173   enum ExpressionPathAftermath {
174     /// Just return it.
175     eExpressionPathAftermathNothing = 1,
176     /// Dereference the target.
177     eExpressionPathAftermathDereference,
178     /// Take target's address.
179     eExpressionPathAftermathTakeAddress
180   };
181 
182   enum ClearUserVisibleDataItems {
183     eClearUserVisibleDataItemsNothing = 1u << 0,
184     eClearUserVisibleDataItemsValue = 1u << 1,
185     eClearUserVisibleDataItemsSummary = 1u << 2,
186     eClearUserVisibleDataItemsLocation = 1u << 3,
187     eClearUserVisibleDataItemsDescription = 1u << 4,
188     eClearUserVisibleDataItemsSyntheticChildren = 1u << 5,
189     eClearUserVisibleDataItemsAllStrings =
190         eClearUserVisibleDataItemsValue | eClearUserVisibleDataItemsSummary |
191         eClearUserVisibleDataItemsLocation |
192         eClearUserVisibleDataItemsDescription,
193     eClearUserVisibleDataItemsAll = 0xFFFF
194   };
195 
196   struct GetValueForExpressionPathOptions {
197     enum class SyntheticChildrenTraversal {
198       None,
199       ToSynthetic,
200       FromSynthetic,
201       Both
202     };
203 
204     bool m_check_dot_vs_arrow_syntax;
205     bool m_no_fragile_ivar;
206     bool m_allow_bitfields_syntax;
207     SyntheticChildrenTraversal m_synthetic_children_traversal;
208 
209     GetValueForExpressionPathOptions(
210         bool dot = false, bool no_ivar = false, bool bitfield = true,
211         SyntheticChildrenTraversal synth_traverse =
212             SyntheticChildrenTraversal::ToSynthetic)
m_check_dot_vs_arrow_syntaxGetValueForExpressionPathOptions213         : m_check_dot_vs_arrow_syntax(dot), m_no_fragile_ivar(no_ivar),
214           m_allow_bitfields_syntax(bitfield),
215           m_synthetic_children_traversal(synth_traverse) {}
216 
DoCheckDotVsArrowSyntaxGetValueForExpressionPathOptions217     GetValueForExpressionPathOptions &DoCheckDotVsArrowSyntax() {
218       m_check_dot_vs_arrow_syntax = true;
219       return *this;
220     }
221 
DontCheckDotVsArrowSyntaxGetValueForExpressionPathOptions222     GetValueForExpressionPathOptions &DontCheckDotVsArrowSyntax() {
223       m_check_dot_vs_arrow_syntax = false;
224       return *this;
225     }
226 
DoAllowFragileIVarGetValueForExpressionPathOptions227     GetValueForExpressionPathOptions &DoAllowFragileIVar() {
228       m_no_fragile_ivar = false;
229       return *this;
230     }
231 
DontAllowFragileIVarGetValueForExpressionPathOptions232     GetValueForExpressionPathOptions &DontAllowFragileIVar() {
233       m_no_fragile_ivar = true;
234       return *this;
235     }
236 
DoAllowBitfieldSyntaxGetValueForExpressionPathOptions237     GetValueForExpressionPathOptions &DoAllowBitfieldSyntax() {
238       m_allow_bitfields_syntax = true;
239       return *this;
240     }
241 
DontAllowBitfieldSyntaxGetValueForExpressionPathOptions242     GetValueForExpressionPathOptions &DontAllowBitfieldSyntax() {
243       m_allow_bitfields_syntax = false;
244       return *this;
245     }
246 
247     GetValueForExpressionPathOptions &
SetSyntheticChildrenTraversalGetValueForExpressionPathOptions248     SetSyntheticChildrenTraversal(SyntheticChildrenTraversal traverse) {
249       m_synthetic_children_traversal = traverse;
250       return *this;
251     }
252 
DefaultOptionsGetValueForExpressionPathOptions253     static const GetValueForExpressionPathOptions DefaultOptions() {
254       static GetValueForExpressionPathOptions g_default_options;
255 
256       return g_default_options;
257     }
258   };
259 
260   class EvaluationPoint {
261   public:
262     EvaluationPoint();
263 
264     EvaluationPoint(ExecutionContextScope *exe_scope,
265                     bool use_selected = false);
266 
267     EvaluationPoint(const EvaluationPoint &rhs);
268 
269     ~EvaluationPoint();
270 
GetExecutionContextRef()271     const ExecutionContextRef &GetExecutionContextRef() const {
272       return m_exe_ctx_ref;
273     }
274 
SetIsConstant()275     void SetIsConstant() {
276       SetUpdated();
277       m_mod_id.SetInvalid();
278     }
279 
IsConstant()280     bool IsConstant() const { return !m_mod_id.IsValid(); }
281 
GetModID()282     ProcessModID GetModID() const { return m_mod_id; }
283 
SetUpdateID(ProcessModID new_id)284     void SetUpdateID(ProcessModID new_id) { m_mod_id = new_id; }
285 
SetNeedsUpdate()286     void SetNeedsUpdate() { m_needs_update = true; }
287 
288     void SetUpdated();
289 
NeedsUpdating(bool accept_invalid_exe_ctx)290     bool NeedsUpdating(bool accept_invalid_exe_ctx) {
291       SyncWithProcessState(accept_invalid_exe_ctx);
292       return m_needs_update;
293     }
294 
IsValid()295     bool IsValid() {
296       const bool accept_invalid_exe_ctx = false;
297       if (!m_mod_id.IsValid())
298         return false;
299       else if (SyncWithProcessState(accept_invalid_exe_ctx)) {
300         if (!m_mod_id.IsValid())
301           return false;
302       }
303       return true;
304     }
305 
SetInvalid()306     void SetInvalid() {
307       // Use the stop id to mark us as invalid, leave the thread id and the
308       // stack id around for logging and history purposes.
309       m_mod_id.SetInvalid();
310 
311       // Can't update an invalid state.
312       m_needs_update = false;
313     }
314 
315   private:
316     bool SyncWithProcessState(bool accept_invalid_exe_ctx);
317 
318     ProcessModID m_mod_id; // This is the stop id when this ValueObject was last
319                            // evaluated.
320     ExecutionContextRef m_exe_ctx_ref;
321     bool m_needs_update = true;
322   };
323 
324   virtual ~ValueObject();
325 
GetUpdatePoint()326   const EvaluationPoint &GetUpdatePoint() const { return m_update_point; }
327 
GetUpdatePoint()328   EvaluationPoint &GetUpdatePoint() { return m_update_point; }
329 
GetExecutionContextRef()330   const ExecutionContextRef &GetExecutionContextRef() const {
331     return m_update_point.GetExecutionContextRef();
332   }
333 
GetTargetSP()334   lldb::TargetSP GetTargetSP() const {
335     return m_update_point.GetExecutionContextRef().GetTargetSP();
336   }
337 
GetProcessSP()338   lldb::ProcessSP GetProcessSP() const {
339     return m_update_point.GetExecutionContextRef().GetProcessSP();
340   }
341 
GetThreadSP()342   lldb::ThreadSP GetThreadSP() const {
343     return m_update_point.GetExecutionContextRef().GetThreadSP();
344   }
345 
GetFrameSP()346   lldb::StackFrameSP GetFrameSP() const {
347     return m_update_point.GetExecutionContextRef().GetFrameSP();
348   }
349 
350   void SetNeedsUpdate();
351 
GetCompilerType()352   CompilerType GetCompilerType() { return MaybeCalculateCompleteType(); }
353 
354   // this vends a TypeImpl that is useful at the SB API layer
GetTypeImpl()355   virtual TypeImpl GetTypeImpl() { return TypeImpl(GetCompilerType()); }
356 
357   virtual bool CanProvideValue();
358 
359   // Subclasses must implement the functions below.
360   virtual llvm::Expected<uint64_t> GetByteSize() = 0;
361 
362   virtual lldb::ValueType GetValueType() const = 0;
363 
364   // Subclasses can implement the functions below.
GetTypeName()365   virtual ConstString GetTypeName() { return GetCompilerType().GetTypeName(); }
366 
GetDisplayTypeName()367   virtual ConstString GetDisplayTypeName() { return GetTypeName(); }
368 
GetQualifiedTypeName()369   virtual ConstString GetQualifiedTypeName() {
370     return GetCompilerType().GetTypeName();
371   }
372 
GetObjectRuntimeLanguage()373   lldb::LanguageType GetObjectRuntimeLanguage() {
374     return GetCompilerType().GetMinimumLanguage();
375   }
376 
377   uint32_t
378   GetTypeInfo(CompilerType *pointee_or_element_compiler_type = nullptr) {
379     return GetCompilerType().GetTypeInfo(pointee_or_element_compiler_type);
380   }
381 
IsPointerType()382   bool IsPointerType() { return GetCompilerType().IsPointerType(); }
383 
IsArrayType()384   bool IsArrayType() { return GetCompilerType().IsArrayType(); }
385 
IsScalarType()386   bool IsScalarType() { return GetCompilerType().IsScalarType(); }
387 
IsPointerOrReferenceType()388   bool IsPointerOrReferenceType() {
389     return GetCompilerType().IsPointerOrReferenceType();
390   }
391 
392   bool IsPossibleDynamicType();
393 
394   bool IsNilReference();
395 
396   bool IsUninitializedReference();
397 
IsBaseClass()398   virtual bool IsBaseClass() { return false; }
399 
400   bool IsBaseClass(uint32_t &depth);
401 
IsDereferenceOfParent()402   virtual bool IsDereferenceOfParent() { return false; }
403 
IsIntegerType(bool & is_signed)404   bool IsIntegerType(bool &is_signed) {
405     return GetCompilerType().IsIntegerType(is_signed);
406   }
407 
408   virtual void GetExpressionPath(
409       Stream &s,
410       GetExpressionPathFormat = eGetExpressionPathFormatDereferencePointers);
411 
412   lldb::ValueObjectSP GetValueForExpressionPath(
413       llvm::StringRef expression,
414       ExpressionPathScanEndReason *reason_to_stop = nullptr,
415       ExpressionPathEndResultType *final_value_type = nullptr,
416       const GetValueForExpressionPathOptions &options =
417           GetValueForExpressionPathOptions::DefaultOptions(),
418       ExpressionPathAftermath *final_task_on_target = nullptr);
419 
IsInScope()420   virtual bool IsInScope() { return true; }
421 
GetByteOffset()422   virtual lldb::offset_t GetByteOffset() { return 0; }
423 
GetBitfieldBitSize()424   virtual uint32_t GetBitfieldBitSize() { return 0; }
425 
GetBitfieldBitOffset()426   virtual uint32_t GetBitfieldBitOffset() { return 0; }
427 
IsBitfield()428   bool IsBitfield() {
429     return (GetBitfieldBitSize() != 0) || (GetBitfieldBitOffset() != 0);
430   }
431 
432   virtual const char *GetValueAsCString();
433 
434   virtual bool GetValueAsCString(const lldb_private::TypeFormatImpl &format,
435                                  std::string &destination);
436 
437   bool GetValueAsCString(lldb::Format format, std::string &destination);
438 
439   virtual uint64_t GetValueAsUnsigned(uint64_t fail_value,
440                                       bool *success = nullptr);
441 
442   virtual int64_t GetValueAsSigned(int64_t fail_value, bool *success = nullptr);
443 
444   /// If the current ValueObject is of an appropriate type, convert the
445   /// value to an APSInt and return that. Otherwise return an error.
446   llvm::Expected<llvm::APSInt> GetValueAsAPSInt();
447 
448   /// If the current ValueObject is of an appropriate type, convert the
449   /// value to an APFloat and return that. Otherwise return an error.
450   llvm::Expected<llvm::APFloat> GetValueAsAPFloat();
451 
452   /// If the current ValueObject is of an appropriate type, convert the
453   /// value to a boolean and return that. Otherwise return an error.
454   llvm::Expected<bool> GetValueAsBool();
455 
456   /// Update an existing integer ValueObject with a new integer value. This
457   /// is only intended to be used with 'temporary' ValueObjects, i.e. ones that
458   /// are not associated with program variables. It does not update program
459   /// memory, registers, stack, etc.
460   void SetValueFromInteger(const llvm::APInt &value, Status &error);
461 
462   /// Update an existing integer ValueObject with an integer value created
463   /// frome 'new_val_sp'.  This is only intended to be used with 'temporary'
464   /// ValueObjects, i.e. ones that are not associated with program variables.
465   /// It does not update program  memory, registers, stack, etc.
466   void SetValueFromInteger(lldb::ValueObjectSP new_val_sp, Status &error);
467 
468   virtual bool SetValueFromCString(const char *value_str, Status &error);
469 
470   /// Return the module associated with this value object in case the value is
471   /// from an executable file and might have its data in sections of the file.
472   /// This can be used for variables.
473   virtual lldb::ModuleSP GetModule();
474 
475   ValueObject *GetRoot();
476 
477   /// Given a ValueObject, loop over itself and its parent, and its parent's
478   /// parent, .. until either the given callback returns false, or you end up at
479   /// a null pointer
480   ValueObject *FollowParentChain(std::function<bool(ValueObject *)>);
481 
482   virtual bool GetDeclaration(Declaration &decl);
483 
484   // The functions below should NOT be modified by subclasses
485   const Status &GetError();
486 
GetName()487   ConstString GetName() const { return m_name; }
488 
489   /// Returns a unique id for this ValueObject.
GetID()490   lldb::user_id_t GetID() const { return m_id.GetID(); }
491 
492   virtual lldb::ValueObjectSP GetChildAtIndex(uint32_t idx,
493                                               bool can_create = true);
494 
495   // The method always creates missing children in the path, if necessary.
496   lldb::ValueObjectSP GetChildAtNamePath(llvm::ArrayRef<llvm::StringRef> names);
497 
498   virtual lldb::ValueObjectSP GetChildMemberWithName(llvm::StringRef name,
499                                                      bool can_create = true);
500 
501   virtual llvm::Expected<size_t> GetIndexOfChildWithName(llvm::StringRef name);
502 
503   llvm::Expected<uint32_t> GetNumChildren(uint32_t max = UINT32_MAX);
504   /// Like \c GetNumChildren but returns 0 on error.  You probably
505   /// shouldn't be using this function. It exists primarily to ease the
506   /// transition to more pervasive error handling while not all APIs
507   /// have been updated.
508   uint32_t GetNumChildrenIgnoringErrors(uint32_t max = UINT32_MAX);
HasChildren()509   bool HasChildren() { return GetNumChildrenIgnoringErrors() > 0; }
510 
GetValue()511   const Value &GetValue() const { return m_value; }
512 
GetValue()513   Value &GetValue() { return m_value; }
514 
515   virtual bool ResolveValue(Scalar &scalar);
516 
517   // return 'false' whenever you set the error, otherwise callers may assume
518   // true means everything is OK - this will break breakpoint conditions among
519   // potentially a few others
520   virtual bool IsLogicalTrue(Status &error);
521 
GetLocationAsCString()522   virtual const char *GetLocationAsCString() {
523     return GetLocationAsCStringImpl(m_value, m_data);
524   }
525 
526   const char *
527   GetSummaryAsCString(lldb::LanguageType lang = lldb::eLanguageTypeUnknown);
528 
529   bool
530   GetSummaryAsCString(TypeSummaryImpl *summary_ptr, std::string &destination,
531                       lldb::LanguageType lang = lldb::eLanguageTypeUnknown);
532 
533   bool GetSummaryAsCString(std::string &destination,
534                            const TypeSummaryOptions &options);
535 
536   bool GetSummaryAsCString(TypeSummaryImpl *summary_ptr,
537                            std::string &destination,
538                            const TypeSummaryOptions &options);
539 
540   llvm::Expected<std::string> GetObjectDescription();
541 
542   bool HasSpecialPrintableRepresentation(
543       ValueObjectRepresentationStyle val_obj_display,
544       lldb::Format custom_format);
545 
546   enum class PrintableRepresentationSpecialCases : bool {
547     eDisable = false,
548     eAllow = true
549   };
550 
551   bool
552   DumpPrintableRepresentation(Stream &s,
553                               ValueObjectRepresentationStyle val_obj_display =
554                                   eValueObjectRepresentationStyleSummary,
555                               lldb::Format custom_format = lldb::eFormatInvalid,
556                               PrintableRepresentationSpecialCases special =
557                                   PrintableRepresentationSpecialCases::eAllow,
558                               bool do_dump_error = true);
GetValueIsValid()559   bool GetValueIsValid() const { return m_flags.m_value_is_valid; }
560 
561   // If you call this on a newly created ValueObject, it will always return
562   // false.
GetValueDidChange()563   bool GetValueDidChange() { return m_flags.m_value_did_change; }
564 
565   bool UpdateValueIfNeeded(bool update_format = true);
566 
567   bool UpdateFormatsIfNeeded();
568 
GetSP()569   lldb::ValueObjectSP GetSP() { return m_manager->GetSharedPointer(this); }
570 
571   /// Change the name of the current ValueObject. Should *not* be used from a
572   /// synthetic child provider as it would change the name of the non synthetic
573   /// child as well.
SetName(ConstString name)574   void SetName(ConstString name) { m_name = name; }
575 
576   struct AddrAndType {
577     lldb::addr_t address = LLDB_INVALID_ADDRESS;
578     AddressType type = eAddressTypeInvalid;
579   };
580 
581   virtual AddrAndType GetAddressOf(bool scalar_is_load_address = true);
582 
583   AddrAndType GetPointerValue();
584 
585   lldb::ValueObjectSP GetSyntheticChild(ConstString key) const;
586 
587   lldb::ValueObjectSP GetSyntheticArrayMember(size_t index, bool can_create);
588 
589   lldb::ValueObjectSP GetSyntheticBitFieldChild(uint32_t from, uint32_t to,
590                                                 bool can_create);
591 
592   lldb::ValueObjectSP GetSyntheticExpressionPathChild(const char *expression,
593                                                       bool can_create);
594 
595   virtual lldb::ValueObjectSP
596   GetSyntheticChildAtOffset(uint32_t offset, const CompilerType &type,
597                             bool can_create,
598                             ConstString name_const_str = ConstString());
599 
600   virtual lldb::ValueObjectSP
601   GetSyntheticBase(uint32_t offset, const CompilerType &type, bool can_create,
602                    ConstString name_const_str = ConstString());
603 
604   virtual lldb::ValueObjectSP GetDynamicValue(lldb::DynamicValueType valueType);
605 
606   lldb::DynamicValueType GetDynamicValueType();
607 
GetStaticValue()608   virtual lldb::ValueObjectSP GetStaticValue() { return GetSP(); }
609 
GetNonSyntheticValue()610   virtual lldb::ValueObjectSP GetNonSyntheticValue() { return GetSP(); }
611 
612   lldb::ValueObjectSP GetSyntheticValue();
613 
614   virtual bool HasSyntheticValue();
615 
IsSynthetic()616   virtual bool IsSynthetic() { return false; }
617 
618   lldb::ValueObjectSP
619   GetQualifiedRepresentationIfAvailable(lldb::DynamicValueType dynValue,
620                                         bool synthValue);
621 
622   virtual lldb::ValueObjectSP CreateConstantValue(ConstString name);
623 
624   virtual lldb::ValueObjectSP Dereference(Status &error);
625 
626   /// Creates a copy of the ValueObject with a new name and setting the current
627   /// ValueObject as its parent. It should be used when we want to change the
628   /// name of a ValueObject without modifying the actual ValueObject itself
629   /// (e.g. sythetic child provider).
630   virtual lldb::ValueObjectSP Clone(ConstString new_name);
631 
632   virtual lldb::ValueObjectSP AddressOf(Status &error);
633 
GetLiveAddress()634   virtual lldb::addr_t GetLiveAddress() { return LLDB_INVALID_ADDRESS; }
635 
636   virtual void SetLiveAddress(lldb::addr_t addr = LLDB_INVALID_ADDRESS,
637                               AddressType address_type = eAddressTypeLoad) {}
638 
639   lldb::ValueObjectSP Cast(const CompilerType &compiler_type);
640 
641   virtual lldb::ValueObjectSP DoCast(const CompilerType &compiler_type);
642 
643   virtual lldb::ValueObjectSP CastPointerType(const char *name,
644                                               CompilerType &ast_type);
645 
646   virtual lldb::ValueObjectSP CastPointerType(const char *name,
647                                               lldb::TypeSP &type_sp);
648 
649   /// Return the target load address associated with this value object.
650   lldb::addr_t GetLoadAddress();
651 
652   /// Take a ValueObject whose type is an inherited class, and cast it to
653   /// 'type', which should be one of its base classes. 'base_type_indices'
654   /// contains the indices of direct base classes on the path from the
655   /// ValueObject's current type to 'type'
656   llvm::Expected<lldb::ValueObjectSP>
657   CastDerivedToBaseType(CompilerType type,
658                         const llvm::ArrayRef<uint32_t> &base_type_indices);
659 
660   /// Take a ValueObject whose type is a base class, and cast it to 'type',
661   /// which should be one of its derived classes. 'base_type_indices'
662   /// contains the indices of direct base classes on the path from the
663   /// ValueObject's current type to 'type'
664   llvm::Expected<lldb::ValueObjectSP> CastBaseToDerivedType(CompilerType type,
665                                                             uint64_t offset);
666 
667   // Take a ValueObject that contains a scalar, enum or pointer type, and
668   // cast it to a "basic" type (integer, float or boolean).
669   lldb::ValueObjectSP CastToBasicType(CompilerType type);
670 
671   // Take a ValueObject that contain an integer, float or enum, and cast it
672   // to an enum.
673   lldb::ValueObjectSP CastToEnumType(CompilerType type);
674 
675   /// If this object represents a C++ class with a vtable, return an object
676   /// that represents the virtual function table. If the object isn't a class
677   /// with a vtable, return a valid ValueObject with the error set correctly.
678   lldb::ValueObjectSP GetVTable();
679   // The backing bits of this value object were updated, clear any descriptive
680   // string, so we know we have to refetch them.
ValueUpdated()681   void ValueUpdated() {
682     ClearUserVisibleData(eClearUserVisibleDataItemsValue |
683                          eClearUserVisibleDataItemsSummary |
684                          eClearUserVisibleDataItemsDescription);
685   }
686 
IsDynamic()687   virtual bool IsDynamic() { return false; }
688 
DoesProvideSyntheticValue()689   virtual bool DoesProvideSyntheticValue() { return false; }
690 
IsSyntheticChildrenGenerated()691   virtual bool IsSyntheticChildrenGenerated() {
692     return m_flags.m_is_synthetic_children_generated;
693   }
694 
SetSyntheticChildrenGenerated(bool b)695   virtual void SetSyntheticChildrenGenerated(bool b) {
696     m_flags.m_is_synthetic_children_generated = b;
697   }
698 
699   virtual SymbolContextScope *GetSymbolContextScope();
700 
701   llvm::Error Dump(Stream &s);
702 
703   llvm::Error Dump(Stream &s, const DumpValueObjectOptions &options);
704 
705   static lldb::ValueObjectSP
706   CreateValueObjectFromExpression(llvm::StringRef name,
707                                   llvm::StringRef expression,
708                                   const ExecutionContext &exe_ctx);
709 
710   static lldb::ValueObjectSP
711   CreateValueObjectFromExpression(llvm::StringRef name,
712                                   llvm::StringRef expression,
713                                   const ExecutionContext &exe_ctx,
714                                   const EvaluateExpressionOptions &options);
715 
716   /// Given an address either create a value object containing the value at
717   /// that address, or create a value object containing the address itself
718   /// (pointer value), depending on whether the parameter 'do_deref' is true or
719   /// false.
720   static lldb::ValueObjectSP
721   CreateValueObjectFromAddress(llvm::StringRef name, uint64_t address,
722                                const ExecutionContext &exe_ctx,
723                                CompilerType type, bool do_deref = true);
724 
725   static lldb::ValueObjectSP
726   CreateValueObjectFromData(llvm::StringRef name, const DataExtractor &data,
727                             const ExecutionContext &exe_ctx, CompilerType type);
728 
729   /// Create a value object containing the given APInt value.
730   static lldb::ValueObjectSP CreateValueObjectFromAPInt(lldb::TargetSP target,
731                                                         const llvm::APInt &v,
732                                                         CompilerType type,
733                                                         llvm::StringRef name);
734 
735   /// Create a value object containing the given APFloat value.
736   static lldb::ValueObjectSP
737   CreateValueObjectFromAPFloat(lldb::TargetSP target, const llvm::APFloat &v,
738                                CompilerType type, llvm::StringRef name);
739 
740   /// Create a value object containing the given boolean value.
741   static lldb::ValueObjectSP CreateValueObjectFromBool(lldb::TargetSP target,
742                                                        bool value,
743                                                        llvm::StringRef name);
744 
745   /// Create a nullptr value object with the specified type (must be a
746   /// nullptr type).
747   static lldb::ValueObjectSP CreateValueObjectFromNullptr(lldb::TargetSP target,
748                                                           CompilerType type,
749                                                           llvm::StringRef name);
750 
751   lldb::ValueObjectSP Persist();
752 
753   /// Returns true if this is a char* or a char[] if it is a char* and
754   /// check_pointer is true, it also checks that the pointer is valid.
755   bool IsCStringContainer(bool check_pointer = false);
756 
757   std::pair<size_t, bool>
758   ReadPointedString(lldb::WritableDataBufferSP &buffer_sp, Status &error,
759                     bool honor_array);
760 
761   virtual size_t GetPointeeData(DataExtractor &data, uint32_t item_idx = 0,
762                                 uint32_t item_count = 1);
763 
764   virtual uint64_t GetData(DataExtractor &data, Status &error);
765 
766   virtual bool SetData(DataExtractor &data, Status &error);
767 
GetIsConstant()768   virtual bool GetIsConstant() const { return m_update_point.IsConstant(); }
769 
NeedsUpdating()770   bool NeedsUpdating() {
771     const bool accept_invalid_exe_ctx =
772         (CanUpdateWithInvalidExecutionContext() == eLazyBoolYes);
773     return m_update_point.NeedsUpdating(accept_invalid_exe_ctx);
774   }
775 
SetIsConstant()776   void SetIsConstant() { m_update_point.SetIsConstant(); }
777 
778   lldb::Format GetFormat() const;
779 
SetFormat(lldb::Format format)780   virtual void SetFormat(lldb::Format format) {
781     if (format != m_format)
782       ClearUserVisibleData(eClearUserVisibleDataItemsValue);
783     m_format = format;
784   }
785 
786   virtual lldb::LanguageType GetPreferredDisplayLanguage();
787 
SetPreferredDisplayLanguage(lldb::LanguageType lt)788   void SetPreferredDisplayLanguage(lldb::LanguageType lt) {
789     m_preferred_display_language = lt;
790   }
791 
GetSummaryFormat()792   lldb::TypeSummaryImplSP GetSummaryFormat() {
793     UpdateFormatsIfNeeded();
794     return m_type_summary_sp;
795   }
796 
SetSummaryFormat(lldb::TypeSummaryImplSP format)797   void SetSummaryFormat(lldb::TypeSummaryImplSP format) {
798     m_type_summary_sp = std::move(format);
799     ClearUserVisibleData(eClearUserVisibleDataItemsSummary);
800   }
801 
SetDerefValobj(ValueObject * deref)802   void SetDerefValobj(ValueObject *deref) { m_deref_valobj = deref; }
803 
GetDerefValobj()804   ValueObject *GetDerefValobj() { return m_deref_valobj; }
805 
SetValueFormat(lldb::TypeFormatImplSP format)806   void SetValueFormat(lldb::TypeFormatImplSP format) {
807     m_type_format_sp = std::move(format);
808     ClearUserVisibleData(eClearUserVisibleDataItemsValue);
809   }
810 
GetValueFormat()811   lldb::TypeFormatImplSP GetValueFormat() {
812     UpdateFormatsIfNeeded();
813     return m_type_format_sp;
814   }
815 
SetSyntheticChildren(const lldb::SyntheticChildrenSP & synth_sp)816   void SetSyntheticChildren(const lldb::SyntheticChildrenSP &synth_sp) {
817     if (synth_sp.get() == m_synthetic_children_sp.get())
818       return;
819     ClearUserVisibleData(eClearUserVisibleDataItemsSyntheticChildren);
820     m_synthetic_children_sp = synth_sp;
821   }
822 
GetSyntheticChildren()823   lldb::SyntheticChildrenSP GetSyntheticChildren() {
824     UpdateFormatsIfNeeded();
825     return m_synthetic_children_sp;
826   }
827 
828   // Use GetParent for display purposes, but if you want to tell the parent to
829   // update itself then use m_parent.  The ValueObjectDynamicValue's parent is
830   // not the correct parent for displaying, they are really siblings, so for
831   // display it needs to route through to its grandparent.
GetParent()832   virtual ValueObject *GetParent() { return m_parent; }
833 
GetParent()834   virtual const ValueObject *GetParent() const { return m_parent; }
835 
836   ValueObject *GetNonBaseClassParent();
837 
SetAddressTypeOfChildren(AddressType at)838   void SetAddressTypeOfChildren(AddressType at) {
839     m_address_type_of_ptr_or_ref_children = at;
840   }
841 
842   AddressType GetAddressTypeOfChildren();
843 
SetHasCompleteType()844   void SetHasCompleteType() {
845     m_flags.m_did_calculate_complete_objc_class_type = true;
846   }
847 
848   /// Find out if a ValueObject might have children.
849   ///
850   /// This call is much more efficient than CalculateNumChildren() as
851   /// it doesn't need to complete the underlying type. This is designed
852   /// to be used in a UI environment in order to detect if the
853   /// disclosure triangle should be displayed or not.
854   ///
855   /// This function returns true for class, union, structure,
856   /// pointers, references, arrays and more. Again, it does so without
857   /// doing any expensive type completion.
858   ///
859   /// \return
860   ///     Returns \b true if the ValueObject might have children, or \b
861   ///     false otherwise.
862   virtual bool MightHaveChildren();
863 
GetVariable()864   virtual lldb::VariableSP GetVariable() { return nullptr; }
865 
866   virtual bool IsRuntimeSupportValue();
867 
GetLanguageFlags()868   virtual uint64_t GetLanguageFlags() { return m_language_flags; }
869 
SetLanguageFlags(uint64_t flags)870   virtual void SetLanguageFlags(uint64_t flags) { m_language_flags = flags; }
871 
872   /// Returns the local buffer that this ValueObject points to if it's
873   /// available.
874   /// \return
875   ///     The local buffer if this value object's value points to a
876   ///     host address, and if that buffer can be determined. Otherwise, returns
877   ///     an empty ArrayRef.
878   ///
879   /// TODO: Because a ValueObject's Value can point to any arbitrary memory
880   /// location, it is possible that we can't find what what buffer we're
881   /// pointing to, and thus also can't know its size. See the comment in
882   /// Value::m_value for a more thorough explanation of why that is.
883   llvm::ArrayRef<uint8_t> GetLocalBuffer() const;
884 
885 protected:
886   typedef ClusterManager<ValueObject> ValueObjectManager;
887 
888   class ChildrenManager {
889   public:
890     ChildrenManager() = default;
891 
HasChildAtIndex(size_t idx)892     bool HasChildAtIndex(size_t idx) {
893       std::lock_guard<std::recursive_mutex> guard(m_mutex);
894       return (m_children.find(idx) != m_children.end());
895     }
896 
GetChildAtIndex(uint32_t idx)897     ValueObject *GetChildAtIndex(uint32_t idx) {
898       std::lock_guard<std::recursive_mutex> guard(m_mutex);
899       const auto iter = m_children.find(idx);
900       return ((iter == m_children.end()) ? nullptr : iter->second);
901     }
902 
SetChildAtIndex(size_t idx,ValueObject * valobj)903     void SetChildAtIndex(size_t idx, ValueObject *valobj) {
904       // we do not need to be mutex-protected to make a pair
905       ChildrenPair pair(idx, valobj);
906       std::lock_guard<std::recursive_mutex> guard(m_mutex);
907       m_children.insert(pair);
908     }
909 
SetChildrenCount(size_t count)910     void SetChildrenCount(size_t count) { Clear(count); }
911 
GetChildrenCount()912     size_t GetChildrenCount() { return m_children_count; }
913 
914     void Clear(size_t new_count = 0) {
915       std::lock_guard<std::recursive_mutex> guard(m_mutex);
916       m_children_count = new_count;
917       m_children.clear();
918     }
919 
920   private:
921     typedef std::map<size_t, ValueObject *> ChildrenMap;
922     typedef ChildrenMap::iterator ChildrenIterator;
923     typedef ChildrenMap::value_type ChildrenPair;
924     std::recursive_mutex m_mutex;
925     ChildrenMap m_children;
926     size_t m_children_count = 0;
927   };
928 
929   // Classes that inherit from ValueObject can see and modify these
930 
931   /// The parent value object, or nullptr if this has no parent.
932   ValueObject *m_parent = nullptr;
933   /// The root of the hierarchy for this ValueObject (or nullptr if never
934   /// calculated).
935   ValueObject *m_root = nullptr;
936   /// Stores both the stop id and the full context at which this value was last
937   /// updated.  When we are asked to update the value object, we check whether
938   /// the context & stop id are the same before updating.
939   EvaluationPoint m_update_point;
940   /// The name of this object.
941   ConstString m_name;
942   /// A data extractor that can be used to extract the value.
943   DataExtractor m_data;
944   Value m_value;
945   /// An error object that can describe any errors that occur when updating
946   /// values.
947   Status m_error;
948   /// Cached value string that will get cleared if/when the value is updated.
949   std::string m_value_str;
950   /// Cached old value string from the last time the value was gotten
951   std::string m_old_value_str;
952   /// Cached location string that will get cleared if/when the value is updated.
953   std::string m_location_str;
954   /// Cached summary string that will get cleared if/when the value is updated.
955   std::string m_summary_str;
956   /// Cached result of the "object printer". This differs from the summary
957   /// in that the summary is consed up by us, the object_desc_string is builtin.
958   std::string m_object_desc_str;
959   /// If the type of the value object should be overridden, the type to impose.
960   CompilerType m_override_type;
961 
962   /// This object is managed by the root object (any ValueObject that gets
963   /// created without a parent.) The manager gets passed through all the
964   /// generations of dependent objects, and will keep the whole cluster of
965   /// objects alive as long as a shared pointer to any of them has been handed
966   /// out. Shared pointers to value objects must always be made with the GetSP
967   /// method.
968   ValueObjectManager *m_manager = nullptr;
969 
970   ChildrenManager m_children;
971   std::map<ConstString, ValueObject *> m_synthetic_children;
972 
973   ValueObject *m_dynamic_value = nullptr;
974   ValueObject *m_synthetic_value = nullptr;
975   ValueObject *m_deref_valobj = nullptr;
976 
977   /// We have to hold onto a shared  pointer to this one because it is created
978   /// as an independent ValueObjectConstResult, which isn't managed by us.
979   lldb::ValueObjectSP m_addr_of_valobj_sp;
980 
981   lldb::Format m_format = lldb::eFormatDefault;
982   lldb::Format m_last_format = lldb::eFormatDefault;
983   uint32_t m_last_format_mgr_revision = 0;
984   lldb::TypeSummaryImplSP m_type_summary_sp;
985   lldb::TypeFormatImplSP m_type_format_sp;
986   lldb::SyntheticChildrenSP m_synthetic_children_sp;
987   ProcessModID m_user_id_of_forced_summary;
988   AddressType m_address_type_of_ptr_or_ref_children = eAddressTypeInvalid;
989 
990   llvm::SmallVector<uint8_t, 16> m_value_checksum;
991 
992   lldb::LanguageType m_preferred_display_language = lldb::eLanguageTypeUnknown;
993 
994   uint64_t m_language_flags = 0;
995 
996   /// Unique identifier for every value object.
997   UserID m_id;
998 
999   // Utility class for initializing all bitfields in ValueObject's constructors.
1000   // FIXME: This could be done via default initializers once we have C++20.
1001   struct Bitflags {
1002     bool m_value_is_valid : 1, m_value_did_change : 1,
1003         m_children_count_valid : 1, m_old_value_valid : 1,
1004         m_is_deref_of_parent : 1, m_is_array_item_for_pointer : 1,
1005         m_is_bitfield_for_scalar : 1, m_is_child_at_offset : 1,
1006         m_is_getting_summary : 1, m_did_calculate_complete_objc_class_type : 1,
1007         m_is_synthetic_children_generated : 1;
BitflagsBitflags1008     Bitflags() {
1009       m_value_is_valid = false;
1010       m_value_did_change = false;
1011       m_children_count_valid = false;
1012       m_old_value_valid = false;
1013       m_is_deref_of_parent = false;
1014       m_is_array_item_for_pointer = false;
1015       m_is_bitfield_for_scalar = false;
1016       m_is_child_at_offset = false;
1017       m_is_getting_summary = false;
1018       m_did_calculate_complete_objc_class_type = false;
1019       m_is_synthetic_children_generated = false;
1020     }
1021   } m_flags;
1022 
1023   friend class ValueObjectChild;
1024   friend class ExpressionVariable; // For SetName
1025   friend class Target;             // For SetName
1026   friend class ValueObjectConstResultImpl;
1027   friend class ValueObjectSynthetic; // For ClearUserVisibleData
1028 
1029   /// Use this constructor to create a "root variable object".  The ValueObject
1030   /// will be locked to this context through-out its lifespan.
1031   ValueObject(ExecutionContextScope *exe_scope, ValueObjectManager &manager,
1032               AddressType child_ptr_or_ref_addr_type = eAddressTypeLoad);
1033 
1034   /// Use this constructor to create a ValueObject owned by another ValueObject.
1035   /// It will inherit the ExecutionContext of its parent.
1036   ValueObject(ValueObject &parent);
1037 
GetManager()1038   ValueObjectManager *GetManager() { return m_manager; }
1039 
1040   virtual bool UpdateValue() = 0;
1041 
CanUpdateWithInvalidExecutionContext()1042   virtual LazyBool CanUpdateWithInvalidExecutionContext() {
1043     return eLazyBoolCalculate;
1044   }
1045 
1046   virtual void CalculateDynamicValue(lldb::DynamicValueType use_dynamic);
1047 
GetDynamicValueTypeImpl()1048   virtual lldb::DynamicValueType GetDynamicValueTypeImpl() {
1049     return lldb::eNoDynamicValues;
1050   }
1051 
HasDynamicValueTypeInfo()1052   virtual bool HasDynamicValueTypeInfo() { return false; }
1053 
1054   virtual void CalculateSyntheticValue();
1055 
1056   /// Should only be called by ValueObject::GetChildAtIndex().
1057   ///
1058   /// \return A ValueObject managed by this ValueObject's manager.
1059   virtual ValueObject *CreateChildAtIndex(size_t idx);
1060 
1061   /// Should only be called by ValueObject::GetSyntheticArrayMember().
1062   ///
1063   /// \return A ValueObject managed by this ValueObject's manager.
1064   virtual ValueObject *CreateSyntheticArrayMember(size_t idx);
1065 
1066   /// Should only be called by ValueObject::GetNumChildren().
1067   virtual llvm::Expected<uint32_t>
1068   CalculateNumChildren(uint32_t max = UINT32_MAX) = 0;
1069 
1070   void SetNumChildren(uint32_t num_children);
1071 
SetValueDidChange(bool value_changed)1072   void SetValueDidChange(bool value_changed) {
1073     m_flags.m_value_did_change = value_changed;
1074   }
1075 
SetValueIsValid(bool valid)1076   void SetValueIsValid(bool valid) { m_flags.m_value_is_valid = valid; }
1077 
1078   void ClearUserVisibleData(
1079       uint32_t items = ValueObject::eClearUserVisibleDataItemsAllStrings);
1080 
1081   void AddSyntheticChild(ConstString key, ValueObject *valobj);
1082 
1083   DataExtractor &GetDataExtractor();
1084 
1085   void ClearDynamicTypeInformation();
1086 
1087   // Subclasses must implement the functions below.
1088 
1089   virtual CompilerType GetCompilerTypeImpl() = 0;
1090 
1091   const char *GetLocationAsCStringImpl(const Value &value,
1092                                        const DataExtractor &data);
1093 
IsChecksumEmpty()1094   bool IsChecksumEmpty() { return m_value_checksum.empty(); }
1095 
1096   void SetPreferredDisplayLanguageIfNeeded(lldb::LanguageType);
1097 
1098 protected:
DoUpdateChildrenAddressType(ValueObject & valobj)1099   virtual void DoUpdateChildrenAddressType(ValueObject &valobj) {};
1100 
1101 private:
1102   virtual CompilerType MaybeCalculateCompleteType();
UpdateChildrenAddressType()1103   void UpdateChildrenAddressType() {
1104     GetRoot()->DoUpdateChildrenAddressType(*this);
1105   }
1106 
1107   lldb::ValueObjectSP GetValueForExpressionPath_Impl(
1108       llvm::StringRef expression_cstr,
1109       ExpressionPathScanEndReason *reason_to_stop,
1110       ExpressionPathEndResultType *final_value_type,
1111       const GetValueForExpressionPathOptions &options,
1112       ExpressionPathAftermath *final_task_on_target);
1113 
1114   ValueObject(const ValueObject &) = delete;
1115   const ValueObject &operator=(const ValueObject &) = delete;
1116 };
1117 
1118 } // namespace lldb_private
1119 
1120 #endif // LLDB_VALUEOBJECT_VALUEOBJECT_H
1121