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 SBData.
384 
385     @param[in] item_idx
386         The index of the first item to retrieve. For an array
387         this is equivalent to array[item_idx], for a pointer
388         to *(pointer + item_idx). In either case, the measurement
389         unit for item_idx is the sizeof(T) rather than the byte
390 
391     @param[in] item_count
392         How many items should be copied into the output. By default
393         only one item is copied, but more can be asked for.
394 
395     @return
396         An SBData with the contents of the copied items, on success.
397         An empty SBData otherwise.") GetPointeeData;
398   lldb::SBData
399   GetPointeeData (uint32_t item_idx = 0,
400           uint32_t item_count = 1);
401 
402     %feature("docstring", "
403     Get an SBData wrapping the contents of this SBValue.
404 
405     This method will read the contents of this object in memory
406     and copy them into an SBData for future use.
407 
408     @return
409         An SBData with the contents of this SBValue, on success.
410         An empty SBData otherwise.") GetData;
411     lldb::SBData
412     GetData ();
413 
414     bool
415     SetData (lldb::SBData &data, lldb::SBError& error);
416 
417   lldb::addr_t
418   GetLoadAddress();
419 
420   lldb::SBAddress
421   GetAddress();
422 
423     lldb::SBValue
424     Persist ();
425 
426     %feature("docstring", "Returns an expression path for this value."
427     ) GetExpressionPath;
428     bool
429     GetExpressionPath (lldb::SBStream &description, bool qualify_cxx_base_classes);
430 
431     lldb::SBValue
432     EvaluateExpression(const char *expr) const;
433 
434     lldb::SBValue
435     EvaluateExpression(const char *expr,
436                        const SBExpressionOptions &options) const;
437 
438     lldb::SBValue
439     EvaluateExpression(const char *expr,
440                        const SBExpressionOptions &options,
441                        const char *name) const;
442 
443     STRING_EXTENSION(SBValue)
444 
445 #ifdef SWIGPYTHON
446     %pythoncode %{
447         def __get_dynamic__ (self):
448             '''Helper function for the "SBValue.dynamic" property.'''
449             return self.GetDynamicValue (eDynamicCanRunTarget)
450 
451         class children_access(object):
452             '''A helper object that will lazily hand out thread for a process when supplied an index.'''
453 
454             def __init__(self, sbvalue):
455                 self.sbvalue = sbvalue
456 
457             def __len__(self):
458                 if self.sbvalue:
459                     return int(self.sbvalue.GetNumChildren())
460                 return 0
461 
462             def __getitem__(self, key):
463                 if type(key) is int and key < len(self):
464                     return self.sbvalue.GetChildAtIndex(key)
465                 return None
466 
467         def get_child_access_object(self):
468             '''An accessor function that returns a children_access() object which allows lazy member variable access from a lldb.SBValue object.'''
469             return self.children_access (self)
470 
471         def get_value_child_list(self):
472             '''An accessor function that returns a list() that contains all children in a lldb.SBValue object.'''
473             children = []
474             accessor = self.get_child_access_object()
475             for idx in range(len(accessor)):
476                 children.append(accessor[idx])
477             return children
478 
479         def __iter__(self):
480             '''Iterate over all child values of a lldb.SBValue object.'''
481             return lldb_iter(self, 'GetNumChildren', 'GetChildAtIndex')
482 
483         def __len__(self):
484             '''Return the number of child values of a lldb.SBValue object.'''
485             return self.GetNumChildren()
486 
487         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.''')
488         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]).''')
489         name = property(GetName, None, doc='''A read only property that returns the name of this value as a string.''')
490         type = property(GetType, None, doc='''A read only property that returns a lldb.SBType object that represents the type for this value.''')
491         size = property(GetByteSize, None, doc='''A read only property that returns the size in bytes of this value.''')
492         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.''')
493         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".''')
494         value = property(GetValue, SetValueFromCString, doc='''A read/write property that gets/sets value from a string.''')
495         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.).''')
496         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.''')
497         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.''')
498         load_addr = property(GetLoadAddress, None, doc='''A read only property that returns the load address of this value as an integer.''')
499         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.''')
500         deref = property(Dereference, None, doc='''A read only property that returns an lldb.SBValue that is created by dereferencing this value.''')
501         address_of = property(AddressOf, None, doc='''A read only property that returns an lldb.SBValue that represents the address-of this value.''')
502         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.''')
503         summary = property(GetSummary, None, doc='''A read only property that returns the summary for this value as a string''')
504         description = property(GetObjectDescription, None, doc='''A read only property that returns the language-specific description of this value as a string''')
505         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.''')
506         location = property(GetLocation, None, doc='''A read only property that returns the location of this value as a string.''')
507         target = property(GetTarget, None, doc='''A read only property that returns the lldb.SBTarget that this value is associated with.''')
508         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.''')
509         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.''')
510         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.''')
511         num_children = property(GetNumChildren, None, doc='''A read only property that returns the number of child lldb.SBValues that this value has.''')
512         unsigned = property(GetValueAsUnsigned, None, doc='''A read only property that returns the value of this SBValue as an usigned integer.''')
513         signed = property(GetValueAsSigned, None, doc='''A read only property that returns the value of this SBValue as a signed integer.''')
514 
515         def get_expr_path(self):
516             s = SBStream()
517             self.GetExpressionPath (s)
518             return s.GetData()
519 
520         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.''')
521 
522         def synthetic_child_from_expression(self, name, expr, options=None):
523             if options is None: options = lldb.SBExpressionOptions()
524             child = self.CreateValueFromExpression(name, expr, options)
525             child.SetSyntheticChildrenGenerated(True)
526             return child
527 
528         def synthetic_child_from_data(self, name, data, type):
529             child = self.CreateValueFromData(name, data, type)
530             child.SetSyntheticChildrenGenerated(True)
531             return child
532 
533         def synthetic_child_from_address(self, name, addr, type):
534             child = self.CreateValueFromAddress(name, addr, type)
535             child.SetSyntheticChildrenGenerated(True)
536             return child
537 
538         def __eol_test(val):
539             """Default function for end of list test takes an SBValue object.
540 
541             Return True if val is invalid or it corresponds to a null pointer.
542             Otherwise, return False.
543             """
544             if not val or val.GetValueAsUnsigned() == 0:
545                 return True
546             else:
547                 return False
548 
549         # ==================================================
550         # Iterator for lldb.SBValue treated as a linked list
551         # ==================================================
552         def linked_list_iter(self, next_item_name, end_of_list_test=__eol_test):
553             """Generator adaptor to support iteration for SBValue as a linked list.
554 
555             linked_list_iter() is a special purpose iterator to treat the SBValue as
556             the head of a list data structure, where you specify the child member
557             name which points to the next item on the list and you specify the
558             end-of-list test function which takes an SBValue for an item and returns
559             True if EOL is reached and False if not.
560 
561             linked_list_iter() also detects infinite loop and bails out early.
562 
563             The end_of_list_test arg, if omitted, defaults to the __eol_test
564             function above.
565 
566             For example,
567 
568             # Get Frame #0.
569             ...
570 
571             # Get variable 'task_head'.
572             task_head = frame0.FindVariable('task_head')
573             ...
574 
575             for t in task_head.linked_list_iter('next'):
576                 print t
577             """
578             if end_of_list_test(self):
579                 return
580             item = self
581             visited = set()
582             try:
583                 while not end_of_list_test(item) and not item.GetValueAsUnsigned() in visited:
584                     visited.add(item.GetValueAsUnsigned())
585                     yield item
586                     # Prepare for the next iteration.
587                     item = item.GetChildMemberWithName(next_item_name)
588             except:
589                 # Exception occurred.  Stop the generator.
590                 pass
591 
592             return
593     %}
594 #endif
595 
596 };
597 
598 } // namespace lldb
599