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