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