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 liblldb_ValueObject_h_
10 #define liblldb_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)
206         : 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 
210     GetValueForExpressionPathOptions &DoCheckDotVsArrowSyntax() {
211       m_check_dot_vs_arrow_syntax = true;
212       return *this;
213     }
214 
215     GetValueForExpressionPathOptions &DontCheckDotVsArrowSyntax() {
216       m_check_dot_vs_arrow_syntax = false;
217       return *this;
218     }
219 
220     GetValueForExpressionPathOptions &DoAllowFragileIVar() {
221       m_no_fragile_ivar = false;
222       return *this;
223     }
224 
225     GetValueForExpressionPathOptions &DontAllowFragileIVar() {
226       m_no_fragile_ivar = true;
227       return *this;
228     }
229 
230     GetValueForExpressionPathOptions &DoAllowBitfieldSyntax() {
231       m_allow_bitfields_syntax = true;
232       return *this;
233     }
234 
235     GetValueForExpressionPathOptions &DontAllowBitfieldSyntax() {
236       m_allow_bitfields_syntax = false;
237       return *this;
238     }
239 
240     GetValueForExpressionPathOptions &
241     SetSyntheticChildrenTraversal(SyntheticChildrenTraversal traverse) {
242       m_synthetic_children_traversal = traverse;
243       return *this;
244     }
245 
246     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 
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 
276     void SetIsConstant() {
277       SetUpdated();
278       m_mod_id.SetInvalid();
279     }
280 
281     bool IsConstant() const { return !m_mod_id.IsValid(); }
282 
283     ProcessModID GetModID() const { return m_mod_id; }
284 
285     void SetUpdateID(ProcessModID new_id) { m_mod_id = new_id; }
286 
287     void SetNeedsUpdate() { m_needs_update = true; }
288 
289     void SetUpdated();
290 
291     bool NeedsUpdating(bool accept_invalid_exe_ctx) {
292       SyncWithProcessState(accept_invalid_exe_ctx);
293       return m_needs_update;
294     }
295 
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 
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 
327   const EvaluationPoint &GetUpdatePoint() const { return m_update_point; }
328 
329   EvaluationPoint &GetUpdatePoint() { return m_update_point; }
330 
331   const ExecutionContextRef &GetExecutionContextRef() const {
332     return m_update_point.GetExecutionContextRef();
333   }
334 
335   lldb::TargetSP GetTargetSP() const {
336     return m_update_point.GetExecutionContextRef().GetTargetSP();
337   }
338 
339   lldb::ProcessSP GetProcessSP() const {
340     return m_update_point.GetExecutionContextRef().GetProcessSP();
341   }
342 
343   lldb::ThreadSP GetThreadSP() const {
344     return m_update_point.GetExecutionContextRef().GetThreadSP();
345   }
346 
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 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 
391   virtual bool IsBaseClass() { return false; }
392 
393   bool IsBaseClass(uint32_t &depth);
394 
395   virtual bool IsDereferenceOfParent() { return false; }
396 
397   bool IsIntegerType(bool &is_signed);
398 
399   virtual bool GetBaseClassPath(Stream &s);
400 
401   virtual void GetExpressionPath(
402       Stream &s, bool qualify_cxx_base_classes,
403       GetExpressionPathFormat = eGetExpressionPathFormatDereferencePointers);
404 
405   lldb::ValueObjectSP GetValueForExpressionPath(
406       llvm::StringRef expression,
407       ExpressionPathScanEndReason *reason_to_stop = nullptr,
408       ExpressionPathEndResultType *final_value_type = nullptr,
409       const GetValueForExpressionPathOptions &options =
410           GetValueForExpressionPathOptions::DefaultOptions(),
411       ExpressionPathAftermath *final_task_on_target = nullptr);
412 
413   virtual bool IsInScope() { return true; }
414 
415   virtual lldb::offset_t GetByteOffset() { return 0; }
416 
417   virtual uint32_t GetBitfieldBitSize() { return 0; }
418 
419   virtual uint32_t GetBitfieldBitOffset() { return 0; }
420 
421   bool IsBitfield() {
422     return (GetBitfieldBitSize() != 0) || (GetBitfieldBitOffset() != 0);
423   }
424 
425   virtual bool IsArrayItemForPointer() { return m_is_array_item_for_pointer; }
426 
427   virtual const char *GetValueAsCString();
428 
429   virtual bool GetValueAsCString(const lldb_private::TypeFormatImpl &format,
430                                  std::string &destination);
431 
432   bool GetValueAsCString(lldb::Format format, std::string &destination);
433 
434   virtual uint64_t GetValueAsUnsigned(uint64_t fail_value,
435                                       bool *success = nullptr);
436 
437   virtual int64_t GetValueAsSigned(int64_t fail_value, bool *success = nullptr);
438 
439   virtual bool SetValueFromCString(const char *value_str, Status &error);
440 
441   // Return the module associated with this value object in case the value is
442   // from an executable file and might have its data in sections of the file.
443   // This can be used for variables.
444   virtual lldb::ModuleSP GetModule();
445 
446   ValueObject *GetRoot();
447 
448   // Given a ValueObject, loop over itself and its parent, and its parent's
449   // parent, .. until either the given callback returns false, or you end up at
450   // a null pointer
451   ValueObject *FollowParentChain(std::function<bool(ValueObject *)>);
452 
453   virtual bool GetDeclaration(Declaration &decl);
454 
455   // The functions below should NOT be modified by subclasses
456   const Status &GetError();
457 
458   ConstString GetName() const;
459 
460   virtual lldb::ValueObjectSP GetChildAtIndex(size_t idx, bool can_create);
461 
462   // this will always create the children if necessary
463   lldb::ValueObjectSP GetChildAtIndexPath(llvm::ArrayRef<size_t> idxs,
464                                           size_t *index_of_error = nullptr);
465 
466   lldb::ValueObjectSP
467   GetChildAtIndexPath(llvm::ArrayRef<std::pair<size_t, bool>> idxs,
468                       size_t *index_of_error = nullptr);
469 
470   // this will always create the children if necessary
471   lldb::ValueObjectSP GetChildAtNamePath(llvm::ArrayRef<ConstString> names,
472                                          ConstString *name_of_error = nullptr);
473 
474   lldb::ValueObjectSP
475   GetChildAtNamePath(llvm::ArrayRef<std::pair<ConstString, bool>> names,
476                      ConstString *name_of_error = nullptr);
477 
478   virtual lldb::ValueObjectSP GetChildMemberWithName(ConstString name,
479                                                      bool can_create);
480 
481   virtual size_t GetIndexOfChildWithName(ConstString name);
482 
483   size_t GetNumChildren(uint32_t max = UINT32_MAX);
484 
485   const Value &GetValue() const;
486 
487   Value &GetValue();
488 
489   virtual bool ResolveValue(Scalar &scalar);
490 
491   // return 'false' whenever you set the error, otherwise callers may assume
492   // true means everything is OK - this will break breakpoint conditions among
493   // potentially a few others
494   virtual bool IsLogicalTrue(Status &error);
495 
496   virtual const char *GetLocationAsCString();
497 
498   const char *
499   GetSummaryAsCString(lldb::LanguageType lang = lldb::eLanguageTypeUnknown);
500 
501   bool
502   GetSummaryAsCString(TypeSummaryImpl *summary_ptr, std::string &destination,
503                       lldb::LanguageType lang = lldb::eLanguageTypeUnknown);
504 
505   bool GetSummaryAsCString(std::string &destination,
506                            const TypeSummaryOptions &options);
507 
508   bool GetSummaryAsCString(TypeSummaryImpl *summary_ptr,
509                            std::string &destination,
510                            const TypeSummaryOptions &options);
511 
512   const char *GetObjectDescription();
513 
514   bool HasSpecialPrintableRepresentation(
515       ValueObjectRepresentationStyle val_obj_display,
516       lldb::Format custom_format);
517 
518   enum class PrintableRepresentationSpecialCases : bool {
519     eDisable = false,
520     eAllow = true
521   };
522 
523   bool
524   DumpPrintableRepresentation(Stream &s,
525                               ValueObjectRepresentationStyle val_obj_display =
526                                   eValueObjectRepresentationStyleSummary,
527                               lldb::Format custom_format = lldb::eFormatInvalid,
528                               PrintableRepresentationSpecialCases special =
529                                   PrintableRepresentationSpecialCases::eAllow,
530                               bool do_dump_error = true);
531   bool GetValueIsValid() const;
532 
533   // If you call this on a newly created ValueObject, it will always return
534   // false.
535   bool GetValueDidChange();
536 
537   bool UpdateValueIfNeeded(bool update_format = true);
538 
539   bool UpdateFormatsIfNeeded();
540 
541   lldb::ValueObjectSP GetSP() { return m_manager->GetSharedPointer(this); }
542 
543   // Change the name of the current ValueObject. Should *not* be used from a
544   // synthetic child provider as it would change the name of the non synthetic
545   // child as well.
546   void SetName(ConstString name);
547 
548   virtual lldb::addr_t GetAddressOf(bool scalar_is_load_address = true,
549                                     AddressType *address_type = nullptr);
550 
551   lldb::addr_t GetPointerValue(AddressType *address_type = nullptr);
552 
553   lldb::ValueObjectSP GetSyntheticChild(ConstString key) const;
554 
555   lldb::ValueObjectSP GetSyntheticArrayMember(size_t index, bool can_create);
556 
557   lldb::ValueObjectSP GetSyntheticBitFieldChild(uint32_t from, uint32_t to,
558                                                 bool can_create);
559 
560   lldb::ValueObjectSP GetSyntheticExpressionPathChild(const char *expression,
561                                                       bool can_create);
562 
563   virtual lldb::ValueObjectSP
564   GetSyntheticChildAtOffset(uint32_t offset, const CompilerType &type,
565                             bool can_create,
566                             ConstString name_const_str = ConstString());
567 
568   virtual lldb::ValueObjectSP
569   GetSyntheticBase(uint32_t offset, const CompilerType &type, bool can_create,
570                    ConstString name_const_str = ConstString());
571 
572   virtual lldb::ValueObjectSP GetDynamicValue(lldb::DynamicValueType valueType);
573 
574   lldb::DynamicValueType GetDynamicValueType();
575 
576   virtual lldb::ValueObjectSP GetStaticValue();
577 
578   virtual lldb::ValueObjectSP GetNonSyntheticValue();
579 
580   lldb::ValueObjectSP GetSyntheticValue(bool use_synthetic = true);
581 
582   virtual bool HasSyntheticValue();
583 
584   virtual bool IsSynthetic() { return false; }
585 
586   lldb::ValueObjectSP
587   GetQualifiedRepresentationIfAvailable(lldb::DynamicValueType dynValue,
588                                         bool synthValue);
589 
590   virtual lldb::ValueObjectSP CreateConstantValue(ConstString name);
591 
592   virtual lldb::ValueObjectSP Dereference(Status &error);
593 
594   // Creates a copy of the ValueObject with a new name and setting the current
595   // ValueObject as its parent. It should be used when we want to change the
596   // name of a ValueObject without modifying the actual ValueObject itself
597   // (e.g. sythetic child provider).
598   virtual lldb::ValueObjectSP Clone(ConstString new_name);
599 
600   virtual lldb::ValueObjectSP AddressOf(Status &error);
601 
602   virtual lldb::addr_t GetLiveAddress() { return LLDB_INVALID_ADDRESS; }
603 
604   virtual void SetLiveAddress(lldb::addr_t addr = LLDB_INVALID_ADDRESS,
605                               AddressType address_type = eAddressTypeLoad) {}
606 
607   virtual lldb::ValueObjectSP Cast(const CompilerType &compiler_type);
608 
609   virtual lldb::ValueObjectSP CastPointerType(const char *name,
610                                               CompilerType &ast_type);
611 
612   virtual lldb::ValueObjectSP CastPointerType(const char *name,
613                                               lldb::TypeSP &type_sp);
614 
615   // The backing bits of this value object were updated, clear any descriptive
616   // string, so we know we have to refetch them
617   virtual void ValueUpdated() {
618     ClearUserVisibleData(eClearUserVisibleDataItemsValue |
619                          eClearUserVisibleDataItemsSummary |
620                          eClearUserVisibleDataItemsDescription);
621   }
622 
623   virtual bool IsDynamic() { return false; }
624 
625   virtual bool DoesProvideSyntheticValue() { return false; }
626 
627   virtual bool IsSyntheticChildrenGenerated();
628 
629   virtual void SetSyntheticChildrenGenerated(bool b);
630 
631   virtual SymbolContextScope *GetSymbolContextScope();
632 
633   void Dump(Stream &s);
634 
635   void Dump(Stream &s, const DumpValueObjectOptions &options);
636 
637   static lldb::ValueObjectSP
638   CreateValueObjectFromExpression(llvm::StringRef name,
639                                   llvm::StringRef expression,
640                                   const ExecutionContext &exe_ctx);
641 
642   static lldb::ValueObjectSP
643   CreateValueObjectFromExpression(llvm::StringRef name,
644                                   llvm::StringRef expression,
645                                   const ExecutionContext &exe_ctx,
646                                   const EvaluateExpressionOptions &options);
647 
648   static lldb::ValueObjectSP
649   CreateValueObjectFromAddress(llvm::StringRef name, uint64_t address,
650                                const ExecutionContext &exe_ctx,
651                                CompilerType type);
652 
653   static lldb::ValueObjectSP
654   CreateValueObjectFromData(llvm::StringRef name, const DataExtractor &data,
655                             const ExecutionContext &exe_ctx, CompilerType type);
656 
657   void LogValueObject(Log *log);
658 
659   void LogValueObject(Log *log, const DumpValueObjectOptions &options);
660 
661   lldb::ValueObjectSP Persist();
662 
663   // returns true if this is a char* or a char[] if it is a char* and
664   // check_pointer is true, it also checks that the pointer is valid
665   bool IsCStringContainer(bool check_pointer = false);
666 
667   std::pair<size_t, bool>
668   ReadPointedString(lldb::DataBufferSP &buffer_sp, Status &error,
669                     uint32_t max_length = 0, bool honor_array = true,
670                     lldb::Format item_format = lldb::eFormatCharArray);
671 
672   virtual size_t GetPointeeData(DataExtractor &data, uint32_t item_idx = 0,
673                                 uint32_t item_count = 1);
674 
675   virtual uint64_t GetData(DataExtractor &data, Status &error);
676 
677   virtual bool SetData(DataExtractor &data, Status &error);
678 
679   virtual bool GetIsConstant() const { return m_update_point.IsConstant(); }
680 
681   bool NeedsUpdating() {
682     const bool accept_invalid_exe_ctx =
683         (CanUpdateWithInvalidExecutionContext() == eLazyBoolYes);
684     return m_update_point.NeedsUpdating(accept_invalid_exe_ctx);
685   }
686 
687   void SetIsConstant() { m_update_point.SetIsConstant(); }
688 
689   lldb::Format GetFormat() const;
690 
691   virtual void SetFormat(lldb::Format format) {
692     if (format != m_format)
693       ClearUserVisibleData(eClearUserVisibleDataItemsValue);
694     m_format = format;
695   }
696 
697   virtual lldb::LanguageType GetPreferredDisplayLanguage();
698 
699   void SetPreferredDisplayLanguage(lldb::LanguageType);
700 
701   lldb::TypeSummaryImplSP GetSummaryFormat() {
702     UpdateFormatsIfNeeded();
703     return m_type_summary_sp;
704   }
705 
706   void SetSummaryFormat(lldb::TypeSummaryImplSP format) {
707     m_type_summary_sp = format;
708     ClearUserVisibleData(eClearUserVisibleDataItemsSummary);
709   }
710 
711   void SetValueFormat(lldb::TypeFormatImplSP format) {
712     m_type_format_sp = format;
713     ClearUserVisibleData(eClearUserVisibleDataItemsValue);
714   }
715 
716   lldb::TypeFormatImplSP GetValueFormat() {
717     UpdateFormatsIfNeeded();
718     return m_type_format_sp;
719   }
720 
721   void SetSyntheticChildren(const lldb::SyntheticChildrenSP &synth_sp) {
722     if (synth_sp.get() == m_synthetic_children_sp.get())
723       return;
724     ClearUserVisibleData(eClearUserVisibleDataItemsSyntheticChildren);
725     m_synthetic_children_sp = synth_sp;
726   }
727 
728   lldb::SyntheticChildrenSP GetSyntheticChildren() {
729     UpdateFormatsIfNeeded();
730     return m_synthetic_children_sp;
731   }
732 
733   // Use GetParent for display purposes, but if you want to tell the parent to
734   // update itself then use m_parent.  The ValueObjectDynamicValue's parent is
735   // not the correct parent for displaying, they are really siblings, so for
736   // display it needs to route through to its grandparent.
737   virtual ValueObject *GetParent() { return m_parent; }
738 
739   virtual const ValueObject *GetParent() const { return m_parent; }
740 
741   ValueObject *GetNonBaseClassParent();
742 
743   void SetAddressTypeOfChildren(AddressType at) {
744     m_address_type_of_ptr_or_ref_children = at;
745   }
746 
747   AddressType GetAddressTypeOfChildren();
748 
749   void SetHasCompleteType() { m_did_calculate_complete_objc_class_type = true; }
750 
751   /// Find out if a ValueObject might have children.
752   ///
753   /// This call is much more efficient than CalculateNumChildren() as
754   /// it doesn't need to complete the underlying type. This is designed
755   /// to be used in a UI environment in order to detect if the
756   /// disclosure triangle should be displayed or not.
757   ///
758   /// This function returns true for class, union, structure,
759   /// pointers, references, arrays and more. Again, it does so without
760   /// doing any expensive type completion.
761   ///
762   /// \return
763   ///     Returns \b true if the ValueObject might have children, or \b
764   ///     false otherwise.
765   virtual bool MightHaveChildren();
766 
767   virtual lldb::VariableSP GetVariable() { return nullptr; }
768 
769   virtual bool IsRuntimeSupportValue();
770 
771   virtual uint64_t GetLanguageFlags();
772 
773   virtual void SetLanguageFlags(uint64_t flags);
774 
775 protected:
776   typedef ClusterManager<ValueObject> ValueObjectManager;
777 
778   class ChildrenManager {
779   public:
780     ChildrenManager() : m_mutex(), m_children(), m_children_count(0) {}
781 
782     bool HasChildAtIndex(size_t idx) {
783       std::lock_guard<std::recursive_mutex> guard(m_mutex);
784       return (m_children.find(idx) != m_children.end());
785     }
786 
787     ValueObject *GetChildAtIndex(size_t idx) {
788       std::lock_guard<std::recursive_mutex> guard(m_mutex);
789       const auto iter = m_children.find(idx);
790       return ((iter == m_children.end()) ? nullptr : iter->second);
791     }
792 
793     void SetChildAtIndex(size_t idx, ValueObject *valobj) {
794       // we do not need to be mutex-protected to make a pair
795       ChildrenPair pair(idx, valobj);
796       std::lock_guard<std::recursive_mutex> guard(m_mutex);
797       m_children.insert(pair);
798     }
799 
800     void SetChildrenCount(size_t count) { Clear(count); }
801 
802     size_t GetChildrenCount() { return m_children_count; }
803 
804     void Clear(size_t new_count = 0) {
805       std::lock_guard<std::recursive_mutex> guard(m_mutex);
806       m_children_count = new_count;
807       m_children.clear();
808     }
809 
810   private:
811     typedef std::map<size_t, ValueObject *> ChildrenMap;
812     typedef ChildrenMap::iterator ChildrenIterator;
813     typedef ChildrenMap::value_type ChildrenPair;
814     std::recursive_mutex m_mutex;
815     ChildrenMap m_children;
816     size_t m_children_count;
817   };
818 
819   // Classes that inherit from ValueObject can see and modify these
820   ValueObject
821       *m_parent; // The parent value object, or nullptr if this has no parent
822   ValueObject *m_root; // The root of the hierarchy for this ValueObject (or
823                        // nullptr if never calculated)
824   EvaluationPoint m_update_point; // Stores both the stop id and the full
825                                   // context at which this value was last
826   // updated.  When we are asked to update the value object, we check whether
827   // the context & stop id are the same before updating.
828   ConstString m_name; // The name of this object
829   DataExtractor
830       m_data; // A data extractor that can be used to extract the value.
831   Value m_value;
832   Status
833       m_error; // An error object that can describe any errors that occur when
834                // updating values.
835   std::string m_value_str; // Cached value string that will get cleared if/when
836                            // the value is updated.
837   std::string m_old_value_str; // Cached old value string from the last time the
838                                // value was gotten
839   std::string m_location_str;  // Cached location string that will get cleared
840                                // if/when the value is updated.
841   std::string m_summary_str;   // Cached summary string that will get cleared
842                                // if/when the value is updated.
843   std::string m_object_desc_str; // Cached result of the "object printer".  This
844                                  // differs from the summary
845   // in that the summary is consed up by us, the object_desc_string is builtin.
846 
847   CompilerType m_override_type; // If the type of the value object should be
848                                 // overridden, the type to impose.
849 
850   ValueObjectManager *m_manager; // This object is managed by the root object
851                                  // (any ValueObject that gets created
852   // without a parent.)  The manager gets passed through all the generations of
853   // dependent objects, and will keep the whole cluster of objects alive as
854   // long as a shared pointer to any of them has been handed out.  Shared
855   // pointers to value objects must always be made with the GetSP method.
856 
857   ChildrenManager m_children;
858   std::map<ConstString, ValueObject *> m_synthetic_children;
859 
860   ValueObject *m_dynamic_value;
861   ValueObject *m_synthetic_value;
862   ValueObject *m_deref_valobj;
863 
864   lldb::ValueObjectSP m_addr_of_valobj_sp; // We have to hold onto a shared
865                                            // pointer to this one because it is
866                                            // created
867   // as an independent ValueObjectConstResult, which isn't managed by us.
868 
869   lldb::Format m_format;
870   lldb::Format m_last_format;
871   uint32_t m_last_format_mgr_revision;
872   lldb::TypeSummaryImplSP m_type_summary_sp;
873   lldb::TypeFormatImplSP m_type_format_sp;
874   lldb::SyntheticChildrenSP m_synthetic_children_sp;
875   ProcessModID m_user_id_of_forced_summary;
876   AddressType m_address_type_of_ptr_or_ref_children;
877 
878   llvm::SmallVector<uint8_t, 16> m_value_checksum;
879 
880   lldb::LanguageType m_preferred_display_language;
881 
882   uint64_t m_language_flags;
883 
884   bool m_value_is_valid : 1, m_value_did_change : 1, m_children_count_valid : 1,
885       m_old_value_valid : 1, m_is_deref_of_parent : 1,
886       m_is_array_item_for_pointer : 1, m_is_bitfield_for_scalar : 1,
887       m_is_child_at_offset : 1, m_is_getting_summary : 1,
888       m_did_calculate_complete_objc_class_type : 1,
889       m_is_synthetic_children_generated : 1;
890 
891   friend class ValueObjectChild;
892   friend class ClangExpressionDeclMap; // For GetValue
893   friend class ExpressionVariable;     // For SetName
894   friend class Target;                 // For SetName
895   friend class ValueObjectConstResultImpl;
896   friend class ValueObjectSynthetic; // For ClearUserVisibleData
897 
898   // Constructors and Destructors
899 
900   // Use the no-argument constructor to make a constant variable object (with
901   // no ExecutionContextScope.)
902 
903   ValueObject();
904 
905   // Use this constructor to create a "root variable object".  The ValueObject
906   // will be locked to this context through-out its lifespan.
907 
908   ValueObject(ExecutionContextScope *exe_scope,
909               AddressType child_ptr_or_ref_addr_type = eAddressTypeLoad);
910 
911   // Use this constructor to create a ValueObject owned by another ValueObject.
912   // It will inherit the ExecutionContext of its parent.
913 
914   ValueObject(ValueObject &parent);
915 
916   ValueObjectManager *GetManager() { return m_manager; }
917 
918   virtual bool UpdateValue() = 0;
919 
920   virtual LazyBool CanUpdateWithInvalidExecutionContext() {
921     return eLazyBoolCalculate;
922   }
923 
924   virtual void CalculateDynamicValue(lldb::DynamicValueType use_dynamic);
925 
926   virtual lldb::DynamicValueType GetDynamicValueTypeImpl() {
927     return lldb::eNoDynamicValues;
928   }
929 
930   virtual bool HasDynamicValueTypeInfo() { return false; }
931 
932   virtual void CalculateSyntheticValue(bool use_synthetic = true);
933 
934   // Should only be called by ValueObject::GetChildAtIndex() Returns a
935   // ValueObject managed by this ValueObject's manager.
936   virtual ValueObject *CreateChildAtIndex(size_t idx,
937                                           bool synthetic_array_member,
938                                           int32_t synthetic_index);
939 
940   // Should only be called by ValueObject::GetNumChildren()
941   virtual size_t CalculateNumChildren(uint32_t max = UINT32_MAX) = 0;
942 
943   void SetNumChildren(size_t num_children);
944 
945   void SetValueDidChange(bool value_changed);
946 
947   void SetValueIsValid(bool valid);
948 
949   void ClearUserVisibleData(
950       uint32_t items = ValueObject::eClearUserVisibleDataItemsAllStrings);
951 
952   void AddSyntheticChild(ConstString key, ValueObject *valobj);
953 
954   DataExtractor &GetDataExtractor();
955 
956   void ClearDynamicTypeInformation();
957 
958   // Subclasses must implement the functions below.
959 
960   virtual CompilerType GetCompilerTypeImpl() = 0;
961 
962   const char *GetLocationAsCStringImpl(const Value &value,
963                                        const DataExtractor &data);
964 
965   bool IsChecksumEmpty();
966 
967   void SetPreferredDisplayLanguageIfNeeded(lldb::LanguageType);
968 
969 private:
970   virtual CompilerType MaybeCalculateCompleteType();
971   void UpdateChildrenAddressType();
972 
973   lldb::ValueObjectSP GetValueForExpressionPath_Impl(
974       llvm::StringRef expression_cstr,
975       ExpressionPathScanEndReason *reason_to_stop,
976       ExpressionPathEndResultType *final_value_type,
977       const GetValueForExpressionPathOptions &options,
978       ExpressionPathAftermath *final_task_on_target);
979 
980   DISALLOW_COPY_AND_ASSIGN(ValueObject);
981 };
982 
983 // A value object manager class that is seeded with the static variable value
984 // and it vends the user facing value object. If the type is dynamic it can
985 // vend the dynamic type. If this user type also has a synthetic type
986 // associated with it, it will vend the synthetic type. The class watches the
987 // process' stop
988 // ID and will update the user type when needed.
989 class ValueObjectManager {
990   // The root value object is the static typed variable object.
991   lldb::ValueObjectSP m_root_valobj_sp;
992   // The user value object is the value object the user wants to see.
993   lldb::ValueObjectSP m_user_valobj_sp;
994   lldb::DynamicValueType m_use_dynamic;
995   uint32_t m_stop_id; // The stop ID that m_user_valobj_sp is valid for.
996   bool m_use_synthetic;
997 
998 public:
999   ValueObjectManager() {}
1000 
1001   ValueObjectManager(lldb::ValueObjectSP in_valobj_sp,
1002                      lldb::DynamicValueType use_dynamic, bool use_synthetic);
1003 
1004   bool IsValid() const;
1005 
1006   lldb::ValueObjectSP GetRootSP() const { return m_root_valobj_sp; }
1007 
1008   // Gets the correct value object from the root object for a given process
1009   // stop ID. If dynamic values are enabled, or if synthetic children are
1010   // enabled, the value object that the user wants to see might change while
1011   // debugging.
1012   lldb::ValueObjectSP GetSP();
1013 
1014   void SetUseDynamic(lldb::DynamicValueType use_dynamic);
1015   void SetUseSynthetic(bool use_synthetic);
1016   lldb::DynamicValueType GetUseDynamic() const { return m_use_dynamic; }
1017   bool GetUseSynthetic() const { return m_use_synthetic; }
1018   lldb::TargetSP GetTargetSP() const;
1019   lldb::ProcessSP GetProcessSP() const;
1020   lldb::ThreadSP GetThreadSP() const;
1021   lldb::StackFrameSP GetFrameSP() const;
1022 };
1023 
1024 } // namespace lldb_private
1025 
1026 #endif // liblldb_ValueObject_h_
1027