1 //===-- SWIG Interface for SBValue ------------------------------*- 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 namespace lldb {
10 
11 %feature("docstring",
12 "Represents the value of a variable, a register, or an expression.
13 
14 SBValue supports iteration through its child, which in turn is represented
15 as an SBValue.  For example, we can get the general purpose registers of a
16 frame as an SBValue, and iterate through all the registers,::
17 
18     registerSet = frame.registers # Returns an SBValueList.
19     for regs in registerSet:
20         if 'general purpose registers' in regs.name.lower():
21             GPRs = regs
22             break
23 
24     print('%s (number of children = %d):' % (GPRs.name, GPRs.num_children))
25     for reg in GPRs:
26         print('Name: ', reg.name, ' Value: ', reg.value)
27 
28 produces the output: ::
29 
30     General Purpose Registers (number of children = 21):
31     Name:  rax  Value:  0x0000000100000c5c
32     Name:  rbx  Value:  0x0000000000000000
33     Name:  rcx  Value:  0x00007fff5fbffec0
34     Name:  rdx  Value:  0x00007fff5fbffeb8
35     Name:  rdi  Value:  0x0000000000000001
36     Name:  rsi  Value:  0x00007fff5fbffea8
37     Name:  rbp  Value:  0x00007fff5fbffe80
38     Name:  rsp  Value:  0x00007fff5fbffe60
39     Name:  r8  Value:  0x0000000008668682
40     Name:  r9  Value:  0x0000000000000000
41     Name:  r10  Value:  0x0000000000001200
42     Name:  r11  Value:  0x0000000000000206
43     Name:  r12  Value:  0x0000000000000000
44     Name:  r13  Value:  0x0000000000000000
45     Name:  r14  Value:  0x0000000000000000
46     Name:  r15  Value:  0x0000000000000000
47     Name:  rip  Value:  0x0000000100000dae
48     Name:  rflags  Value:  0x0000000000000206
49     Name:  cs  Value:  0x0000000000000027
50     Name:  fs  Value:  0x0000000000000010
51     Name:  gs  Value:  0x0000000000000048
52 
53 See also linked_list_iter() for another perspective on how to iterate through an
54 SBValue instance which interprets the value object as representing the head of a
55 linked list."
56 ) SBValue;
57 class SBValue
58 {
59 public:
60     SBValue ();
61 
62     SBValue (const SBValue &rhs);
63 
64     ~SBValue ();
65 
66     bool
67     IsValid();
68 
69     explicit operator bool() const;
70 
71     void
72     Clear();
73 
74     SBError
75     GetError();
76 
77     lldb::user_id_t
78     GetID ();
79 
80     const char *
81     GetName();
82 
83     const char *
84     GetTypeName ();
85 
86     const char *
87     GetDisplayTypeName ();
88 
89     size_t
90     GetByteSize ();
91 
92     bool
93     IsInScope ();
94 
95     lldb::Format
96     GetFormat ();
97 
98     void
99     SetFormat (lldb::Format format);
100 
101     const char *
102     GetValue ();
103 
104     int64_t
105     GetValueAsSigned(SBError& error, int64_t fail_value=0);
106 
107     uint64_t
108     GetValueAsUnsigned(SBError& error, uint64_t fail_value=0);
109 
110     int64_t
111     GetValueAsSigned(int64_t fail_value=0);
112 
113     uint64_t
114     GetValueAsUnsigned(uint64_t fail_value=0);
115 
116     ValueType
117     GetValueType ();
118 
119     bool
120     GetValueDidChange ();
121 
122     const char *
123     GetSummary ();
124 
125     const char *
126     GetSummary (lldb::SBStream& stream,
127                 lldb::SBTypeSummaryOptions& options);
128 
129     const char *
130     GetObjectDescription ();
131 
132     lldb::SBValue
133     GetDynamicValue (lldb::DynamicValueType use_dynamic);
134 
135     lldb::SBValue
136     GetStaticValue ();
137 
138     lldb::SBValue
139     GetNonSyntheticValue ();
140 
141     lldb::DynamicValueType
142     GetPreferDynamicValue ();
143 
144     void
145     SetPreferDynamicValue (lldb::DynamicValueType use_dynamic);
146 
147     bool
148     GetPreferSyntheticValue ();
149 
150     void
151     SetPreferSyntheticValue (bool use_synthetic);
152 
153     bool
154     IsDynamic();
155 
156     bool
157     IsSynthetic ();
158 
159     bool
160     IsSyntheticChildrenGenerated ();
161 
162     void
163     SetSyntheticChildrenGenerated (bool);
164 
165     const char *
166     GetLocation ();
167 
168     bool
169     SetValueFromCString (const char *value_str);
170 
171     bool
172     SetValueFromCString (const char *value_str, lldb::SBError& error);
173 
174     lldb::SBTypeFormat
175     GetTypeFormat ();
176 
177     lldb::SBTypeSummary
178     GetTypeSummary ();
179 
180     lldb::SBTypeFilter
181     GetTypeFilter ();
182 
183     lldb::SBTypeSynthetic
184     GetTypeSynthetic ();
185 
186     lldb::SBValue
187     GetChildAtIndex (uint32_t idx);
188 
189     %feature("docstring", "
190     Get a child value by index from a value.
191 
192     Structs, unions, classes, arrays and pointers have child
193     values that can be access by index.
194 
195     Structs and unions access child members using a zero based index
196     for each child member. For
197 
198     Classes reserve the first indexes for base classes that have
199     members (empty base classes are omitted), and all members of the
200     current class will then follow the base classes.
201 
202     Pointers differ depending on what they point to. If the pointer
203     points to a simple type, the child at index zero
204     is the only child value available, unless synthetic_allowed
205     is true, in which case the pointer will be used as an array
206     and can create 'synthetic' child values using positive or
207     negative indexes. If the pointer points to an aggregate type
208     (an array, class, union, struct), then the pointee is
209     transparently skipped and any children are going to be the indexes
210     of the child values within the aggregate type. For example if
211     we have a 'Point' type and we have a SBValue that contains a
212     pointer to a 'Point' type, then the child at index zero will be
213     the 'x' member, and the child at index 1 will be the 'y' member
214     (the child at index zero won't be a 'Point' instance).
215 
216     If you actually need an SBValue that represents the type pointed
217     to by a SBValue for which GetType().IsPointeeType() returns true,
218     regardless of the pointee type, you can do that with the SBValue.Dereference
219     method (or the equivalent deref property).
220 
221     Arrays have a preset number of children that can be accessed by
222     index and will returns invalid child values for indexes that are
223     out of bounds unless the synthetic_allowed is true. In this
224     case the array can create 'synthetic' child values for indexes
225     that aren't in the array bounds using positive or negative
226     indexes.
227 
228     @param[in] idx
229         The index of the child value to get
230 
231     @param[in] use_dynamic
232         An enumeration that specifies whether to get dynamic values,
233         and also if the target can be run to figure out the dynamic
234         type of the child value.
235 
236     @param[in] synthetic_allowed
237         If true, then allow child values to be created by index
238         for pointers and arrays for indexes that normally wouldn't
239         be allowed.
240 
241     @return
242         A new SBValue object that represents the child member value.") GetChildAtIndex;
243     lldb::SBValue
244     GetChildAtIndex (uint32_t idx,
245                      lldb::DynamicValueType use_dynamic,
246                      bool can_create_synthetic);
247 
248     lldb::SBValue
249     CreateChildAtOffset (const char *name, uint32_t offset, lldb::SBType type);
250 
251     lldb::SBValue
252     SBValue::Cast (lldb::SBType type);
253 
254     lldb::SBValue
255     CreateValueFromExpression (const char *name, const char* expression);
256 
257     lldb::SBValue
258     CreateValueFromExpression (const char *name, const char* expression, SBExpressionOptions &options);
259 
260     lldb::SBValue
261     CreateValueFromAddress(const char* name, lldb::addr_t address, lldb::SBType type);
262 
263   lldb::SBValue
264   CreateValueFromData (const char* name,
265                        lldb::SBData data,
266                        lldb::SBType type);
267 
268     lldb::SBType
269     GetType();
270 
271     %feature("docstring", "
272     Returns the child member index.
273 
274     Matches children of this object only and will match base classes and
275     member names if this is a clang typed object.
276 
277     @param[in] name
278         The name of the child value to get
279 
280     @return
281         An index to the child member value.") GetIndexOfChildWithName;
282     uint32_t
283     GetIndexOfChildWithName (const char *name);
284 
285     lldb::SBValue
286     GetChildMemberWithName (const char *name);
287 
288     %feature("docstring", "
289     Returns the child member value.
290 
291     Matches child members of this object and child members of any base
292     classes.
293 
294     @param[in] name
295         The name of the child value to get
296 
297     @param[in] use_dynamic
298         An enumeration that specifies whether to get dynamic values,
299         and also if the target can be run to figure out the dynamic
300         type of the child value.
301 
302     @return
303         A new SBValue object that represents the child member value.") GetChildMemberWithName;
304     lldb::SBValue
305     GetChildMemberWithName (const char *name, lldb::DynamicValueType use_dynamic);
306 
307     %feature("docstring", "Expands nested expressions like .a->b[0].c[1]->d."
308     ) GetValueForExpressionPath;
309     lldb::SBValue
310     GetValueForExpressionPath(const char* expr_path);
311 
312     lldb::SBDeclaration
313     GetDeclaration ();
314 
315     bool
316     MightHaveChildren ();
317 
318     bool
319     IsRuntimeSupportValue ();
320 
321     uint32_t
322     GetNumChildren ();
323 
324     %feature("doctstring", "
325     Returns the number for children.
326 
327     @param[in] max
328         If max is less the lldb.UINT32_MAX, then the returned value is
329         capped to max.
330 
331     @return
332         An integer value capped to the argument max.") GetNumChildren;
333     uint32_t
334     GetNumChildren (uint32_t max);
335 
336     void *
337     GetOpaqueType();
338 
339     lldb::SBValue
340     Dereference ();
341 
342     lldb::SBValue
343     AddressOf();
344 
345     bool
346     TypeIsPointerType ();
347 
348     lldb::SBTarget
349     GetTarget();
350 
351     lldb::SBProcess
352     GetProcess();
353 
354     lldb::SBThread
355     GetThread();
356 
357     lldb::SBFrame
358     GetFrame();
359 
360     %feature("docstring", "
361     Find and watch a variable.
362     It returns an SBWatchpoint, which may be invalid.") Watch;
363     lldb::SBWatchpoint
364     Watch (bool resolve_location, bool read, bool write, SBError &error);
365 
366     %feature("docstring", "
367     Find and watch the location pointed to by a variable.
368     It returns an SBWatchpoint, which may be invalid.") WatchPointee;
369     lldb::SBWatchpoint
370     WatchPointee (bool resolve_location, bool read, bool write, SBError &error);
371 
372     bool
373     GetDescription (lldb::SBStream &description);
374 
375     bool
376     GetExpressionPath (lldb::SBStream &description);
377 
378   %feature("docstring", "
379     Get an SBData wrapping what this SBValue points to.
380 
381     This method will dereference the current SBValue, if its
382     data type is a ``T\*`` or ``T[]``, and extract ``item_count`` elements
383     of type ``T`` from it, copying their contents in an :py:class:`SBData`.
384 
385     :param item_idx: The index of the first item to retrieve. For an array
386         this is equivalent to array[item_idx], for a pointer
387         to ``\*(pointer + item_idx)``. In either case, the measurement
388         unit for item_idx is the ``sizeof(T)`` rather than the byte
389     :param item_count: How many items should be copied into the output. By default
390         only one item is copied, but more can be asked for.
391     :return: The contents of the copied items on success. An empty :py:class:`SBData` otherwise.
392     :rtype: SBData
393     ") GetPointeeData;
394   lldb::SBData
395   GetPointeeData (uint32_t item_idx = 0,
396           uint32_t item_count = 1);
397 
398     %feature("docstring", "
399     Get an SBData wrapping the contents of this SBValue.
400 
401     This method will read the contents of this object in memory
402     and copy them into an SBData for future use.
403 
404     @return
405         An SBData with the contents of this SBValue, on success.
406         An empty SBData otherwise.") GetData;
407     lldb::SBData
408     GetData ();
409 
410     bool
411     SetData (lldb::SBData &data, lldb::SBError& error);
412 
413   lldb::addr_t
414   GetLoadAddress();
415 
416   lldb::SBAddress
417   GetAddress();
418 
419     lldb::SBValue
420     Persist ();
421 
422     %feature("docstring", "Returns an expression path for this value."
423     ) GetExpressionPath;
424     bool
425     GetExpressionPath (lldb::SBStream &description, bool qualify_cxx_base_classes);
426 
427     lldb::SBValue
428     EvaluateExpression(const char *expr) const;
429 
430     lldb::SBValue
431     EvaluateExpression(const char *expr,
432                        const SBExpressionOptions &options) const;
433 
434     lldb::SBValue
435     EvaluateExpression(const char *expr,
436                        const SBExpressionOptions &options,
437                        const char *name) const;
438 
439     STRING_EXTENSION(SBValue)
440 
441 #ifdef SWIGPYTHON
442     %pythoncode %{
443         def __get_dynamic__ (self):
444             '''Helper function for the "SBValue.dynamic" property.'''
445             return self.GetDynamicValue (eDynamicCanRunTarget)
446 
447         class children_access(object):
448             '''A helper object that will lazily hand out thread for a process when supplied an index.'''
449 
450             def __init__(self, sbvalue):
451                 self.sbvalue = sbvalue
452 
453             def __len__(self):
454                 if self.sbvalue:
455                     return int(self.sbvalue.GetNumChildren())
456                 return 0
457 
458             def __getitem__(self, key):
459                 if type(key) is int and key < len(self):
460                     return self.sbvalue.GetChildAtIndex(key)
461                 return None
462 
463         def get_child_access_object(self):
464             '''An accessor function that returns a children_access() object which allows lazy member variable access from a lldb.SBValue object.'''
465             return self.children_access (self)
466 
467         def get_value_child_list(self):
468             '''An accessor function that returns a list() that contains all children in a lldb.SBValue object.'''
469             children = []
470             accessor = self.get_child_access_object()
471             for idx in range(len(accessor)):
472                 children.append(accessor[idx])
473             return children
474 
475         def __iter__(self):
476             '''Iterate over all child values of a lldb.SBValue object.'''
477             return lldb_iter(self, 'GetNumChildren', 'GetChildAtIndex')
478 
479         def __len__(self):
480             '''Return the number of child values of a lldb.SBValue object.'''
481             return self.GetNumChildren()
482 
483         children = property(get_value_child_list, None, doc='''A read only property that returns a list() of lldb.SBValue objects for the children of the value.''')
484         child = property(get_child_access_object, None, doc='''A read only property that returns an object that can access children of a variable by index (child_value = value.children[12]).''')
485         name = property(GetName, None, doc='''A read only property that returns the name of this value as a string.''')
486         type = property(GetType, None, doc='''A read only property that returns a lldb.SBType object that represents the type for this value.''')
487         size = property(GetByteSize, None, doc='''A read only property that returns the size in bytes of this value.''')
488         is_in_scope = property(IsInScope, None, doc='''A read only property that returns a boolean value that indicates whether this value is currently lexically in scope.''')
489         format = property(GetName, SetFormat, doc='''A read/write property that gets/sets the format used for lldb.SBValue().GetValue() for this value. See enumerations that start with "lldb.eFormat".''')
490         value = property(GetValue, SetValueFromCString, doc='''A read/write property that gets/sets value from a string.''')
491         value_type = property(GetValueType, None, doc='''A read only property that returns an lldb enumeration value (see enumerations that start with "lldb.eValueType") that represents the type of this value (local, argument, global, register, etc.).''')
492         changed = property(GetValueDidChange, None, doc='''A read only property that returns a boolean value that indicates if this value has changed since it was last updated.''')
493         data = property(GetData, None, doc='''A read only property that returns an lldb object (lldb.SBData) that represents the bytes that make up the value for this object.''')
494         load_addr = property(GetLoadAddress, None, doc='''A read only property that returns the load address of this value as an integer.''')
495         addr = property(GetAddress, None, doc='''A read only property that returns an lldb.SBAddress that represents the address of this value if it is in memory.''')
496         deref = property(Dereference, None, doc='''A read only property that returns an lldb.SBValue that is created by dereferencing this value.''')
497         address_of = property(AddressOf, None, doc='''A read only property that returns an lldb.SBValue that represents the address-of this value.''')
498         error = property(GetError, None, doc='''A read only property that returns the lldb.SBError that represents the error from the last time the variable value was calculated.''')
499         summary = property(GetSummary, None, doc='''A read only property that returns the summary for this value as a string''')
500         description = property(GetObjectDescription, None, doc='''A read only property that returns the language-specific description of this value as a string''')
501         dynamic = property(__get_dynamic__, None, doc='''A read only property that returns an lldb.SBValue that is created by finding the dynamic type of this value.''')
502         location = property(GetLocation, None, doc='''A read only property that returns the location of this value as a string.''')
503         target = property(GetTarget, None, doc='''A read only property that returns the lldb.SBTarget that this value is associated with.''')
504         process = property(GetProcess, None, doc='''A read only property that returns the lldb.SBProcess that this value is associated with, the returned value might be invalid and should be tested.''')
505         thread = property(GetThread, None, doc='''A read only property that returns the lldb.SBThread that this value is associated with, the returned value might be invalid and should be tested.''')
506         frame = property(GetFrame, None, doc='''A read only property that returns the lldb.SBFrame that this value is associated with, the returned value might be invalid and should be tested.''')
507         num_children = property(GetNumChildren, None, doc='''A read only property that returns the number of child lldb.SBValues that this value has.''')
508         unsigned = property(GetValueAsUnsigned, None, doc='''A read only property that returns the value of this SBValue as an usigned integer.''')
509         signed = property(GetValueAsSigned, None, doc='''A read only property that returns the value of this SBValue as a signed integer.''')
510 
511         def get_expr_path(self):
512             s = SBStream()
513             self.GetExpressionPath (s)
514             return s.GetData()
515 
516         path = property(get_expr_path, None, doc='''A read only property that returns the expression path that one can use to reach this value in an expression.''')
517 
518         def synthetic_child_from_expression(self, name, expr, options=None):
519             if options is None: options = lldb.SBExpressionOptions()
520             child = self.CreateValueFromExpression(name, expr, options)
521             child.SetSyntheticChildrenGenerated(True)
522             return child
523 
524         def synthetic_child_from_data(self, name, data, type):
525             child = self.CreateValueFromData(name, data, type)
526             child.SetSyntheticChildrenGenerated(True)
527             return child
528 
529         def synthetic_child_from_address(self, name, addr, type):
530             child = self.CreateValueFromAddress(name, addr, type)
531             child.SetSyntheticChildrenGenerated(True)
532             return child
533 
534         def __eol_test(val):
535             """Default function for end of list test takes an SBValue object.
536 
537             Return True if val is invalid or it corresponds to a null pointer.
538             Otherwise, return False.
539             """
540             if not val or val.GetValueAsUnsigned() == 0:
541                 return True
542             else:
543                 return False
544 
545         # ==================================================
546         # Iterator for lldb.SBValue treated as a linked list
547         # ==================================================
548         def linked_list_iter(self, next_item_name, end_of_list_test=__eol_test):
549             """Generator adaptor to support iteration for SBValue as a linked list.
550 
551             linked_list_iter() is a special purpose iterator to treat the SBValue as
552             the head of a list data structure, where you specify the child member
553             name which points to the next item on the list and you specify the
554             end-of-list test function which takes an SBValue for an item and returns
555             True if EOL is reached and False if not.
556 
557             linked_list_iter() also detects infinite loop and bails out early.
558 
559             The end_of_list_test arg, if omitted, defaults to the __eol_test
560             function above.
561 
562             For example,
563 
564             # Get Frame #0.
565             ...
566 
567             # Get variable 'task_head'.
568             task_head = frame0.FindVariable('task_head')
569             ...
570 
571             for t in task_head.linked_list_iter('next'):
572                 print t
573             """
574             if end_of_list_test(self):
575                 return
576             item = self
577             visited = set()
578             try:
579                 while not end_of_list_test(item) and not item.GetValueAsUnsigned() in visited:
580                     visited.add(item.GetValueAsUnsigned())
581                     yield item
582                     # Prepare for the next iteration.
583                     item = item.GetChildMemberWithName(next_item_name)
584             except:
585                 # Exception occurred.  Stop the generator.
586                 pass
587 
588             return
589     %}
590 #endif
591 
592 };
593 
594 } // namespace lldb
595