xref: /openbsd-src/gnu/llvm/lldb/docs/use/variable.rst (revision f1dd7b858388b4a23f4f67a4957ec5ff656ebbe8)
1Variable Formatting
2===================
3
4.. contents::
5   :local:
6
7LLDB has a data formatters subsystem that allows users to define custom display
8options for their variables.
9
10Usually, when you type frame variable or run some expression LLDB will
11automatically choose the way to display your results on a per-type basis, as in
12the following example:
13
14::
15
16   (lldb) frame variable
17   (uint8_t) x = 'a'
18   (intptr_t) y = 124752287
19
20However, in certain cases, you may want to associate a different style to the display for certain datatypes. To do so, you need to give hints to the debugger
21as to how variables should be displayed. The LLDB type command allows you to do
22just that.
23
24Using it you can change your visualization to look like this:
25
26::
27
28   (lldb) frame variable
29   (uint8_t) x = chr='a' dec=65 hex=0x41
30   (intptr_t) y = 0x76f919f
31
32There are several features related to data visualization: formats, summaries,
33filters, synthetic children.
34
35To reflect this, the type command has five subcommands:
36
37::
38
39   type format
40   type summary
41   type filter
42   type synthetic
43   type category
44
45These commands are meant to bind printing options to types. When variables are
46printed, LLDB will first check if custom printing options have been associated
47to a variable's type and, if so, use them instead of picking the default
48choices.
49
50Each of the commands (except ``type category``) has four subcommands available:
51
52- ``add``: associates a new printing option to one or more types
53- ``delete``: deletes an existing association
54- ``list``: provides a listing of all associations
55- ``clear``: deletes all associations
56
57Type Format
58-----------
59
60Type formats enable you to quickly override the default format for displaying
61primitive types (the usual basic C/C++/ObjC types: int, float, char, ...).
62
63If for some reason you want all int variables in your program to print out as
64hex, you can add a format to the int type.
65
66This is done by typing
67
68::
69
70   (lldb) type format add --format hex int
71
72at the LLDB command line.
73
74The ``--format`` (which you can shorten to -f) option accepts a :doc:`format
75name<formatting>`. Then, you provide one or more types to which you want the
76new format applied.
77
78A frequent scenario is that your program has a typedef for a numeric type that
79you know represents something that must be printed in a certain way. Again, you
80can add a format just to that typedef by using type format add with the name
81alias.
82
83But things can quickly get hierarchical. Let's say you have a situation like
84the following:
85
86::
87
88   typedef int A;
89   typedef A B;
90   typedef B C;
91   typedef C D;
92
93and you want to show all A's as hex, all C's as byte arrays and leave the
94defaults untouched for other types (albeit its contrived look, the example is
95far from unrealistic in large software systems).
96
97If you simply type
98
99::
100
101   (lldb) type format add -f hex A
102   (lldb) type format add -f uint8_t[] C
103
104values of type B will be shown as hex and values of type D as byte arrays, as in:
105
106::
107
108   (lldb) frame variable -T
109   (A) a = 0x00000001
110   (B) b = 0x00000002
111   (C) c = {0x03 0x00 0x00 0x00}
112   (D) d = {0x04 0x00 0x00 0x00}
113
114This is because by default LLDB cascades formats through typedef chains. In
115order to avoid that you can use the option -C no to prevent cascading, thus
116making the two commands required to achieve your goal:
117
118::
119
120   (lldb) type format add -C no -f hex A
121   (lldb) type format add -C no -f uint8_t[] C
122
123
124which provides the desired output:
125
126::
127
128   (lldb) frame variable -T
129   (A) a = 0x00000001
130   (B) b = 2
131   (C) c = {0x03 0x00 0x00 0x00}
132   (D) d = 4
133
134Two additional options that you will want to look at are --skip-pointers (-p)
135and --skip-references (-r). These two options prevent LLDB from applying a
136format for type T to values of type T* and T& respectively.
137
138::
139
140   (lldb) type format add -f float32[] int
141   (lldb) frame variable pointer *pointer -T
142   (int *) pointer = {1.46991e-39 1.4013e-45}
143   (int) *pointer = {1.53302e-42}
144   (lldb) type format add -f float32[] int -p
145   (lldb) frame variable pointer *pointer -T
146   (int *) pointer = 0x0000000100100180
147   (int) *pointer = {1.53302e-42}
148
149While they can be applied to pointers and references, formats will make no
150attempt to dereference the pointer and extract the value before applying the
151format, which means you are effectively formatting the address stored in the
152pointer rather than the pointee value. For this reason, you may want to use the
153-p option when defining formats.
154
155If you need to delete a custom format simply type type format delete followed
156by the name of the type to which the format applies.Even if you defined the
157same format for multiple types on the same command, type format delete will
158only remove the format for the type name passed as argument.
159
160To delete ALL formats, use ``type format clear``. To see all the formats
161defined, use type format list.
162
163If all you need to do, however, is display one variable in a custom format,
164while leaving the others of the same type untouched, you can simply type:
165
166::
167
168   (lldb) frame variable counter -f hex
169
170This has the effect of displaying the value of counter as an hexadecimal
171number, and will keep showing it this way until you either pick a different
172format or till you let your program run again.
173
174Finally, this is a list of formatting options available out of which you can
175pick:
176
177+-----------------------------------------------+------------------+--------------------------------------------------------------------------+
178| **Format name**                               | **Abbreviation** | **Description**                                                          |
179+-----------------------------------------------+------------------+--------------------------------------------------------------------------+
180| ``default``                                   |                  | the default LLDB algorithm is used to pick a format                      |
181+-----------------------------------------------+------------------+--------------------------------------------------------------------------+
182| ``boolean``                                   | B                | show this as a true/false boolean, using the customary rule that 0 is    |
183|                                               |                  | false and everything else is true                                        |
184+-----------------------------------------------+------------------+--------------------------------------------------------------------------+
185| ``binary``                                    | b                | show this as a sequence of bits                                          |
186+-----------------------------------------------+------------------+--------------------------------------------------------------------------+
187| ``bytes``                                     | y                | show the bytes one after the other                                       |
188+-----------------------------------------------+------------------+--------------------------------------------------------------------------+
189| ``bytes with ASCII``                          | Y                | show the bytes, but try to display them as ASCII characters as well      |
190+-----------------------------------------------+------------------+--------------------------------------------------------------------------+
191| ``character``                                 | c                | show the bytes as ASCII characters                                       |
192+-----------------------------------------------+------------------+--------------------------------------------------------------------------+
193| ``printable character``                       | C                | show the bytes as printable ASCII characters                             |
194+-----------------------------------------------+------------------+--------------------------------------------------------------------------+
195| ``complex float``                             | F                | interpret this value as the real and imaginary part of a complex         |
196|                                               |                  | floating-point number                                                    |
197+-----------------------------------------------+------------------+--------------------------------------------------------------------------+
198| ``c-string``                                  | s                | show this as a 0-terminated C string                                     |
199+-----------------------------------------------+------------------+--------------------------------------------------------------------------+
200| ``decimal``                                   | d                | show this as a signed integer number (this does not perform a cast, it   |
201|                                               |                  | simply shows the bytes as  an integer with sign)                         |
202+-----------------------------------------------+------------------+--------------------------------------------------------------------------+
203| ``enumeration``                               | E                | show this as an enumeration, printing the                                |
204|                                               |                  | value's name if available or the integer value otherwise                 |
205+-----------------------------------------------+------------------+--------------------------------------------------------------------------+
206| ``hex``                                       | x                | show this as in hexadecimal notation (this does                          |
207|                                               |                  | not perform a cast, it simply shows the bytes as hex)                    |
208+-----------------------------------------------+------------------+--------------------------------------------------------------------------+
209| ``float``                                     | f                | show this as a floating-point number (this does not perform a cast, it   |
210|                                               |                  | simply interprets the bytes as an IEEE754 floating-point value)          |
211+-----------------------------------------------+------------------+--------------------------------------------------------------------------+
212| ``octal``                                     | o                | show this in octal notation                                              |
213+-----------------------------------------------+------------------+--------------------------------------------------------------------------+
214| ``OSType``                                    | O                | show this as a MacOS OSType                                              |
215+-----------------------------------------------+------------------+--------------------------------------------------------------------------+
216| ``unicode16``                                 | U                | show this as UTF-16 characters                                           |
217+-----------------------------------------------+------------------+--------------------------------------------------------------------------+
218| ``unicode32``                                 |                  | show this as UTF-32 characters                                           |
219+-----------------------------------------------+------------------+--------------------------------------------------------------------------+
220| ``unsigned decimal``                          | u                | show this as an unsigned integer number (this does not perform a cast,   |
221|                                               |                  | it simply shows the bytes as unsigned integer)                           |
222+-----------------------------------------------+------------------+--------------------------------------------------------------------------+
223| ``pointer``                                   | p                | show this as a native pointer (unless this is really a pointer, the      |
224|                                               |                  | resulting address will probably be invalid)                              |
225+-----------------------------------------------+------------------+--------------------------------------------------------------------------+
226| ``char[]``                                    |                  | show this as an array of characters                                      |
227+-----------------------------------------------+------------------+--------------------------------------------------------------------------+
228| ``int8_t[], uint8_t[]``                       |                  | show this as an array of the corresponding integer type                  |
229| ``int16_t[], uint16_t[]``                     |                  |                                                                          |
230| ``int32_t[], uint32_t[]``                     |                  |                                                                          |
231| ``int64_t[], uint64_t[]``                     |                  |                                                                          |
232| ``uint128_t[]``                               |                  |                                                                          |
233+-----------------------------------------------+------------------+--------------------------------------------------------------------------+
234| ``float32[], float64[]``                      |                  | show this as an array of the corresponding                               |
235|                                               |                  |                       floating-point type                                |
236+-----------------------------------------------+------------------+--------------------------------------------------------------------------+
237| ``complex integer``                           | I                | interpret this value as the real and imaginary part of a complex integer |
238|                                               |                  | number                                                                   |
239+-----------------------------------------------+------------------+--------------------------------------------------------------------------+
240| ``character array``                           | a                | show this as a character array                                           |
241+-----------------------------------------------+------------------+--------------------------------------------------------------------------+
242| ``address``                                   | A                | show this as an address target (symbol/file/line + offset), possibly     |
243|                                               |                  | also the string this address is pointing to                              |
244+-----------------------------------------------+------------------+--------------------------------------------------------------------------+
245| ``hex float``                                 |                  | show this as hexadecimal floating point                                  |
246+-----------------------------------------------+------------------+--------------------------------------------------------------------------+
247| ``instruction``                               | i                | show this as an disassembled opcode                                      |
248+-----------------------------------------------+------------------+--------------------------------------------------------------------------+
249| ``void``                                      | v                | don't show anything                                                      |
250+-----------------------------------------------+------------------+--------------------------------------------------------------------------+
251
252Type Summary
253------------
254
255Type formats work by showing a different kind of display for the value of a
256variable. However, they only work for basic types. When you want to display a
257class or struct in a custom format, you cannot do that using formats.
258
259A different feature, type summaries, works by extracting information from
260classes, structures, ... (aggregate types) and arranging it in a user-defined
261format, as in the following example:
262
263before adding a summary...
264
265::
266
267   (lldb) frame variable -T one
268   (i_am_cool) one = {
269      (int) x = 3
270      (float) y = 3.14159
271      (char) z = 'E'
272   }
273
274after adding a summary...
275
276::
277
278   (lldb) frame variable one
279   (i_am_cool) one = int = 3, float = 3.14159, char = 69
280
281There are two ways to use type summaries: the first one is to bind a summary
282string to the type; the second is to write a Python script that returns the
283string to be used as summary. Both options are enabled by the type summary add
284command.
285
286The command to obtain the output shown in the example is:
287
288::
289
290(lldb) type summary add --summary-string "int = ${var.x}, float = ${var.y}, char = ${var.z%u}" i_am_cool
291
292Initially, we will focus on summary strings, and then describe the Python
293binding mechanism.
294
295Summary Strings
296---------------
297
298Summary strings are written using a simple control language, exemplified by the
299snippet above. A summary string contains a sequence of tokens that are
300processed by LLDB to generate the summary.
301
302Summary strings can contain plain text, control characters and special
303variables that have access to information about the current object and the
304overall program state.
305
306Plain text is any sequence of characters that doesn't contain a ``{``, ``}``, ``$``,
307or ``\`` character, which are the syntax control characters.
308
309The special variables are found in between a "${" prefix, and end with a "}"
310suffix. Variables can be a simple name or they can refer to complex objects
311that have subitems themselves. In other words, a variable looks like
312``${object}`` or ``${object.child.otherchild}``. A variable can also be
313prefixed or suffixed with other symbols meant to change the way its value is
314handled. An example is ``${*var.int_pointer[0-3]}``.
315
316Basically, the syntax is the same one described Frame and Thread Formatting
317plus additional symbols specific for summary strings. The main of them is
318${var, which is used refer to the variable that a summary is being created for.
319
320The simplest thing you can do is grab a member variable of a class or structure
321by typing its expression path. In the previous example, the expression path for
322the field float y is simply .y. Thus, to ask the summary string to display y
323you would type ${var.y}.
324
325If you have code like the following:
326
327::
328
329   struct A {
330      int x;
331      int y;
332   };
333   struct B {
334      A x;
335      A y;
336      int *z;
337   };
338
339the expression path for the y member of the x member of an object of type B
340would be .x.y and you would type ``${var.x.y}`` to display it in a summary
341string for type B.
342
343By default, a summary defined for type T, also works for types T* and T& (you
344can disable this behavior if desired). For this reason, expression paths do not
345differentiate between . and ->, and the above expression path .x.y would be
346just as good if you were displaying a B*, or even if the actual definition of B
347were:
348
349::
350
351   struct B {
352      A *x;
353      A y;
354      int *z;
355   };
356
357This is unlike the behavior of frame variable which, on the contrary, will
358enforce the distinction. As hinted above, the rationale for this choice is that
359waiving this distinction enables you to write a summary string once for type T
360and use it for both T and T* instances. As a summary string is mostly about
361extracting nested members' information, a pointer to an object is just as good
362as the object itself for the purpose.
363
364If you need to access the value of the integer pointed to by B::z, you cannot
365simply say ${var.z} because that symbol refers to the pointer z. In order to
366dereference it and get the pointed value, you should say ``${*var.z}``. The
367``${*var`` tells LLDB to get the object that the expression paths leads to, and
368then dereference it. In this example is it equivalent to ``*(bObject.z)`` in
369C/C++ syntax. Because ``.`` and ``->`` operators can both be used, there is no
370need to have dereferences in the middle of an expression path (e.g. you do not
371need to type ``${*(var.x).x}``) to read A::x as contained in ``*(B::x)``. To
372achieve that effect you can simply write ``${var.x->x}``, or even
373``${var.x.x}``. The ``*`` operator only binds to the result of the whole
374expression path, rather than piecewise, and there is no way to use parentheses
375to change that behavior.
376
377Of course, a summary string can contain more than one ${var specifier, and can
378use ``${var`` and ``${*var`` specifiers together.
379
380Formatting Summary Elements
381---------------------------
382
383An expression path can include formatting codes. Much like the type formats
384discussed previously, you can also customize the way variables are displayed in
385summary strings, regardless of the format they have applied to their types. To
386do that, you can use %format inside an expression path, as in ${var.x->x%u},
387which would display the value of x as an unsigned integer.
388
389You can also use some other special format markers, not available for formats
390themselves, but which carry a special meaning when used in this context:
391
392+------------+--------------------------------------------------------------------------+
393| **Symbol** | **Description**                                                          |
394+------------+--------------------------------------------------------------------------+
395| ``Symbol`` | ``Description``                                                          |
396+------------+--------------------------------------------------------------------------+
397| ``%S``     | Use this object's summary (the default for aggregate types)              |
398+------------+--------------------------------------------------------------------------+
399| ``%V``     | Use this object's value (the default for non-aggregate types)            |
400+------------+--------------------------------------------------------------------------+
401| ``%@``     | Use a language-runtime specific description (for C++ this does nothing,  |
402|            |                     for Objective-C it calls the NSPrintForDebugger API) |
403+------------+--------------------------------------------------------------------------+
404| ``%L``     | Use this object's location (memory address, register name, ...)          |
405+------------+--------------------------------------------------------------------------+
406| ``%#``     | Use the count of the children of this object                             |
407+------------+--------------------------------------------------------------------------+
408| ``%T``     | Use this object's datatype name                                          |
409+------------+--------------------------------------------------------------------------+
410| ``%N``     | Print the variable's basename                                            |
411+------------+--------------------------------------------------------------------------+
412| ``%>``     | Print the expression path for this item                                  |
413+------------+--------------------------------------------------------------------------+
414
415Starting with SVN r228207, you can also specify
416``${script.var:pythonFuncName}``. Previously, back to r220821, this was
417specified with a different syntax: ``${var.script:pythonFuncName}``.
418
419It is expected that the function name you use specifies a function whose
420signature is the same as a Python summary function. The return string from the
421function will be placed verbatim in the output.
422
423You cannot use element access, or formatting symbols, in combination with this
424syntax. For example the following:
425
426::
427
428   ${script.var.element[0]:myFunctionName%@}
429
430is not valid and will cause the summary to fail to evaluate.
431
432
433Element Inlining
434----------------
435
436Option --inline-children (-c) to type summary add tells LLDB not to look for a summary string, but instead to just print a listing of all the object's children on one line.
437
438As an example, given a type pair:
439
440::
441
442   (lldb) frame variable --show-types a_pair
443   (pair) a_pair = {
444      (int) first = 1;
445      (int) second = 2;
446   }
447
448If one types the following commands:
449
450::
451
452   (lldb) type summary add --inline-children pair
453
454the output becomes:
455
456::
457
458   (lldb) frame variable a_pair
459   (pair) a_pair = (first=1, second=2)
460
461
462Of course, one can obtain the same effect by typing
463
464::
465
466   (lldb) type summary add pair --summary-string "(first=${var.first}, second=${var.second})"
467
468While the final result is the same, using --inline-children can often save
469time. If one does not need to see the names of the variables, but just their
470values, the option --omit-names (-O, uppercase letter o), can be combined with
471--inline-children to obtain:
472
473::
474
475   (lldb) frame variable a_pair
476   (pair) a_pair = (1, 2)
477
478which is of course the same as typing
479
480::
481
482   (lldb) type summary add pair --summary-string "(${var.first}, ${var.second})"
483
484Bitfields And Array Syntax
485--------------------------
486
487Sometimes, a basic type's value actually represents several different values
488packed together in a bitfield.
489
490With the classical view, there is no way to look at them. Hexadecimal display
491can help, but if the bits actually span nibble boundaries, the help is limited.
492
493Binary view would show it all without ambiguity, but is often too detailed and
494hard to read for real-life scenarios.
495
496To cope with the issue, LLDB supports native bitfield formatting in summary
497strings. If your expression paths leads to a so-called scalar type (the usual
498int, float, char, double, short, long, long long, double, long double and
499unsigned variants), you can ask LLDB to only grab some bits out of the value
500and display them in any format you like. If you only need one bit you can use
501the [n], just like indexing an array. To extract multiple bits, you can use a
502slice-like syntax: [n-m], e.g.
503
504::
505
506   (lldb) frame variable float_point
507   (float) float_point = -3.14159
508
509::
510
511   (lldb) type summary add --summary-string "Sign: ${var[31]%B} Exponent: ${var[30-23]%x} Mantissa: ${var[0-22]%u}" float
512   (lldb) frame variable float_point
513   (float) float_point = -3.14159 Sign: true Exponent: 0x00000080 Mantissa: 4788184
514
515In this example, LLDB shows the internal representation of a float variable by
516extracting bitfields out of a float object.
517
518When typing a range, the extremes n and m are always included, and the order of
519the indices is irrelevant.
520
521LLDB also allows to use a similar syntax to display array members inside a summary string. For instance, you may want to display all arrays of a given type using a more compact notation than the default, and then just delve into individual array members that prove interesting to your debugging task. You can tell LLDB to format arrays in special ways, possibly independent of the way the array members' datatype is formatted.
522e.g.
523
524::
525
526   (lldb) frame variable sarray
527   (Simple [3]) sarray = {
528      [0] = {
529         x = 1
530         y = 2
531         z = '\x03'
532      }
533      [1] = {
534         x = 4
535         y = 5
536         z = '\x06'
537      }
538      [2] = {
539         x = 7
540         y = 8
541         z = '\t'
542      }
543   }
544
545   (lldb) type summary add --summary-string "${var[].x}" "Simple [3]"
546
547   (lldb) frame variable sarray
548   (Simple [3]) sarray = [1,4,7]
549
550The [] symbol amounts to: if var is an array and I know its size, apply this summary string to every element of the array. Here, we are asking LLDB to display .x for every element of the array, and in fact this is what happens. If you find some of those integers anomalous, you can then inspect that one item in greater detail, without the array format getting in the way:
551
552::
553
554   (lldb) frame variable sarray[1]
555   (Simple) sarray[1] = {
556      x = 4
557      y = 5
558      z = '\x06'
559   }
560
561You can also ask LLDB to only print a subset of the array range by using the
562same syntax used to extract bit for bitfields:
563
564::
565
566   (lldb) type summary add --summary-string "${var[1-2].x}" "Simple [3]"
567
568   (lldb) frame variable sarray
569   (Simple [3]) sarray = [4,7]
570
571If you are dealing with a pointer that you know is an array, you can use this
572syntax to display the elements contained in the pointed array instead of just
573the pointer value. However, because pointers have no notion of their size, the
574empty brackets [] operator does not work, and you must explicitly provide
575higher and lower bounds.
576
577In general, LLDB needs the square brackets ``operator []`` in order to handle
578arrays and pointers correctly, and for pointers it also needs a range. However,
579a few special cases are defined to make your life easier:
580
581you can print a 0-terminated string (C-string) using the %s format, omitting
582square brackets, as in:
583
584::
585
586   (lldb) type summary add --summary-string "${var%s}" "char *"
587
588This syntax works for char* as well as for char[] because LLDB can rely on the
589final \0 terminator to know when the string has ended.
590
591LLDB has default summary strings for char* and char[] that use this special
592case. On debugger startup, the following are defined automatically:
593
594::
595
596   (lldb) type summary add --summary-string "${var%s}" "char *"
597   (lldb) type summary add --summary-string "${var%s}" -x "char \[[0-9]+]"
598
599any of the array formats (int8_t[], float32{}, ...), and the y, Y and a formats
600work to print an array of a non-aggregate type, even if square brackets are
601omitted.
602
603::
604
605   (lldb) type summary add --summary-string "${var%int32_t[]}" "int [10]"
606
607This feature, however, is not enabled for pointers because there is no way for
608LLDB to detect the end of the pointed data.
609
610This also does not work for other formats (e.g. boolean), and you must specify
611the square brackets operator to get the expected output.
612
613Python Scripting
614----------------
615
616Most of the times, summary strings prove good enough for the job of summarizing
617the contents of a variable. However, as soon as you need to do more than
618picking some values and rearranging them for display, summary strings stop
619being an effective tool. This is because summary strings lack the power to
620actually perform any kind of computation on the value of variables.
621
622To solve this issue, you can bind some Python scripting code as a summary for
623your datatype, and that script has the ability to both extract children
624variables as the summary strings do and to perform active computation on the
625extracted values. As a small example, let's say we have a Rectangle class:
626
627::
628
629
630   class Rectangle
631   {
632   private:
633      int height;
634      int width;
635   public:
636      Rectangle() : height(3), width(5) {}
637      Rectangle(int H) : height(H), width(H*2-1) {}
638      Rectangle(int H, int W) : height(H), width(W) {}
639      int GetHeight() { return height; }
640      int GetWidth() { return width; }
641   };
642
643Summary strings are effective to reduce the screen real estate used by the
644default viewing mode, but are not effective if we want to display the area and
645perimeter of Rectangle objects
646
647To obtain this, we can simply attach a small Python script to the Rectangle
648class, as shown in this example:
649
650::
651
652   (lldb) type summary add -P Rectangle
653   Enter your Python command(s). Type 'DONE' to end.
654   def function (valobj,internal_dict,options):
655      height_val = valobj.GetChildMemberWithName('height')
656      width_val = valobj.GetChildMemberWithName('width')
657      height = height_val.GetValueAsUnsigned(0)
658      width = width_val.GetValueAsUnsigned(0)
659      area = height*width
660      perimeter = 2*(height + width)
661      return 'Area: ' + str(area) + ', Perimeter: ' + str(perimeter)
662      DONE
663   (lldb) frame variable
664   (Rectangle) r1 = Area: 20, Perimeter: 18
665   (Rectangle) r2 = Area: 72, Perimeter: 36
666   (Rectangle) r3 = Area: 16, Perimeter: 16
667
668In order to write effective summary scripts, you need to know the LLDB public
669API, which is the way Python code can access the LLDB object model. For further
670details on the API you should look at the LLDB API reference documentation.
671
672
673As a brief introduction, your script is encapsulated into a function that is
674passed two parameters: ``valobj`` and ``internal_dict``.
675
676``internal_dict`` is an internal support parameter used by LLDB and you should
677not touch it.
678
679``valobj`` is the object encapsulating the actual variable being displayed, and
680its type is SBValue. Out of the many possible operations on an SBValue, the
681basic one is retrieve the children objects it contains (essentially, the fields
682of the object wrapped by it), by calling ``GetChildMemberWithName()``, passing
683it the child's name as a string.
684
685If the variable has a value, you can ask for it, and return it as a string
686using ``GetValue()``, or as a signed/unsigned number using
687``GetValueAsSigned()``, ``GetValueAsUnsigned()``. It is also possible to
688retrieve an SBData object by calling ``GetData()`` and then read the object's
689contents out of the SBData.
690
691If you need to delve into several levels of hierarchy, as you can do with
692summary strings, you can use the method ``GetValueForExpressionPath()``,
693passing it an expression path just like those you could use for summary strings
694(one of the differences is that dereferencing a pointer does not occur by
695prefixing the path with a ``*```, but by calling the ``Dereference()`` method
696on the returned SBValue). If you need to access array slices, you cannot do
697that (yet) via this method call, and you must use ``GetChildAtIndex()``
698querying it for the array items one by one. Also, handling custom formats is
699something you have to deal with on your own.
700
701``options`` Python summary formatters can optionally define this
702third argument, which is an object of type ``lldb.SBTypeSummaryOptions``,
703allowing for a few customizations of the result. The decision to
704adopt or not this third argument - and the meaning of options
705thereof - is up to the individual formatter's writer.
706
707Other than interactively typing a Python script there are two other ways for
708you to input a Python script as a summary:
709
710- using the --python-script option to type summary add and typing the script
711  code as an option argument; as in:
712
713::
714
715   (lldb) type summary add --python-script "height = valobj.GetChildMemberWithName('height').GetValueAsUnsigned(0);width = valobj.GetChildMemberWithName('width').GetValueAsUnsigned(0); return 'Area: %d' % (height*width)" Rectangle
716
717
718- using the --python-function (-F) option to type summary add and giving the
719  name of a Python function with the correct prototype. Most probably, you will
720  define (or have already defined) the function in the interactive interpreter,
721  or somehow loaded it from a file, using the command script import command.
722  LLDB will emit a warning if it is unable to find the function you passed, but
723  will still register the binding.
724
725Regular Expression Typenames
726----------------------------
727
728As you noticed, in order to associate the custom summary string to the array
729types, one must give the array size as part of the typename. This can long
730become tiresome when using arrays of different sizes, Simple [3], Simple [9],
731Simple [12], ...
732
733If you use the -x option, type names are treated as regular expressions instead
734of type names. This would let you rephrase the above example for arrays of type
735Simple [3] as:
736
737::
738   (lldb) type summary add --summary-string "${var[].x}" -x "Simple \[[0-9]+\]"
739   (lldb) frame variable
740   (Simple [3]) sarray = [1,4,7]
741   (Simple [2]) sother = [3,6]
742
743The above scenario works for Simple [3] as well as for any other array of
744Simple objects.
745
746While this feature is mostly useful for arrays, you could also use regular
747expressions to catch other type sets grouped by name. However, as regular
748expression matching is slower than normal name matching, LLDB will first try to
749match by name in any way it can, and only when this fails, will it resort to
750regular expression matching.
751
752One of the ways LLDB uses this feature internally, is to match the names of STL
753container classes, regardless of the template arguments provided. The details
754for this are found at FormatManager.cpp
755
756The regular expression language used by LLDB is the POSIX extended language, as
757defined by the Single UNIX Specification, of which macOS is a compliant
758implementation.
759
760Names Summaries
761---------------
762
763For a given type, there may be different meaningful summary representations.
764However, currently, only one summary can be associated to a type at each
765moment. If you need to temporarily override the association for a variable,
766without changing the summary string for to its type, you can use named
767summaries.
768
769Named summaries work by attaching a name to a summary when creating it. Then,
770when there is a need to attach the summary to a variable, the frame variable
771command, supports a --summary option that tells LLDB to use the named summary
772given instead of the default one.
773
774::
775
776   (lldb) type summary add --summary-string "x=${var.integer}" --name NamedSummary
777   (lldb) frame variable one
778   (i_am_cool) one = int = 3, float = 3.14159, char = 69
779   (lldb) frame variable one --summary NamedSummary
780   (i_am_cool) one = x=3
781
782When defining a named summary, binding it to one or more types becomes
783optional. Even if you bind the named summary to a type, and later change the
784summary string for that type, the named summary will not be changed by that.
785You can delete named summaries by using the type summary delete command, as if
786the summary name was the datatype that the summary is applied to
787
788A summary attached to a variable using the --summary option, has the same
789semantics that a custom format attached using the -f option has: it stays
790attached till you attach a new one, or till you let your program run again.
791
792Synthetic Children
793------------------
794
795Summaries work well when one is able to navigate through an expression path. In
796order for LLDB to do so, appropriate debugging information must be available.
797
798Some types are opaque, i.e. no knowledge of their internals is provided. When
799that's the case, expression paths do not work correctly.
800
801In other cases, the internals are available to use in expression paths, but
802they do not provide a user-friendly representation of the object's value.
803
804For instance, consider an STL vector, as implemented by the GNU C++ Library:
805
806::
807
808   (lldb) frame variable numbers -T
809   (std::vector<int>) numbers = {
810      (std::_Vector_base<int, std::allocator<int> >) std::_Vector_base<int, std::allocator<int> > = {
811         (std::_Vector_base<int, std::allocator&tl;int> >::_Vector_impl) _M_impl = {
812               (int *) _M_start = 0x00000001001008a0
813               (int *) _M_finish = 0x00000001001008a8
814               (int *) _M_end_of_storage = 0x00000001001008a8
815         }
816      }
817   }
818
819Here, you can see how the type is implemented, and you can write a summary for
820that implementation but that is not going to help you infer what items are
821actually stored in the vector.
822
823What you would like to see is probably something like:
824
825::
826
827   (lldb) frame variable numbers -T
828   (std::vector<int>) numbers = {
829      (int) [0] = 1
830      (int) [1] = 12
831      (int) [2] = 123
832      (int) [3] = 1234
833   }
834
835Synthetic children are a way to get that result.
836
837The feature is based upon the idea of providing a new set of children for a
838variable that replaces the ones available by default through the debug
839information. In the example, we can use synthetic children to provide the
840vector items as children for the std::vector object.
841
842In order to create synthetic children, you need to provide a Python class that
843adheres to a given interface (the word is italicized because Python has no
844explicit notion of interface, by that word we mean a given set of methods must
845be implemented by the Python class):
846
847.. code-block:: python
848
849   class SyntheticChildrenProvider:
850      def __init__(self, valobj, internal_dict):
851         this call should initialize the Python object using valobj as the variable to provide synthetic children for
852      def num_children(self):
853         this call should return the number of children that you want your object to have
854      def get_child_index(self,name):
855         this call should return the index of the synthetic child whose name is given as argument
856      def get_child_at_index(self,index):
857         this call should return a new LLDB SBValue object representing the child at the index given as argument
858      def update(self):
859         this call should be used to update the internal state of this Python object whenever the state of the variables in LLDB changes.[1]
860      def has_children(self):
861         this call should return True if this object might have children, and False if this object can be guaranteed not to have children.[2]
862      def get_value(self):
863         this call can return an SBValue to be presented as the value of the synthetic value under consideration.[3]
864
865[1] This method is optional. Also, it may optionally choose to return a value
866(starting with SVN rev153061/LLDB-134). If it returns a value, and that value
867is True, LLDB will be allowed to cache the children and the children count it
868previously obtained, and will not return to the provider class to ask. If
869nothing, None, or anything other than True is returned, LLDB will discard the
870cached information and ask. Regardless, whenever necessary LLDB will call
871update.
872
873[2] This method is optional (starting with SVN rev166495/LLDB-175). While
874implementing it in terms of num_children is acceptable, implementors are
875encouraged to look for optimized coding alternatives whenever reasonable.
876
877[3] This method is optional (starting with SVN revision 219330). The SBValue
878you return here will most likely be a numeric type (int, float, ...) as its
879value bytes will be used as-if they were the value of the root SBValue proper.
880As a shortcut for this, you can inherit from lldb.SBSyntheticValueProvider, and
881just define get_value as other methods are defaulted in the superclass as
882returning default no-children responses.
883
884If a synthetic child provider supplies a special child named
885``$$dereference$$`` then it will be used when evaluating ``operator *`` and
886``operator ->`` in the frame variable command and related SB API
887functions. It is possible to declare this synthetic child without
888including it in the range of children displayed by LLDB. For example,
889this subset of a synthetic children provider class would allow the
890synthetic value to be dereferenced without actually showing any
891synthtic children in the UI:
892
893.. code-block:: python
894
895      class SyntheticChildrenProvider:
896          [...]
897          def num_children(self):
898              return 0
899          def get_child_index(self, name):
900              if name == '$$dereference$$':
901                  return 0
902              return -1
903          def get_child_at_index(self, index):
904              if index == 0:
905                  return <valobj resulting from dereference>
906              return None
907
908
909For examples of how synthetic children are created, you are encouraged to look
910at examples/synthetic in the LLDB trunk. Please, be aware that the code in
911those files (except bitfield/) is legacy code and is not maintained. You may
912especially want to begin looking at this example to get a feel for this
913feature, as it is a very easy and well commented example.
914
915The design pattern consistently used in synthetic providers shipping with LLDB
916is to use the __init__ to store the SBValue instance as a part of self. The
917update function is then used to perform the actual initialization. Once a
918synthetic children provider is written, one must load it into LLDB before it
919can be used. Currently, one can use the LLDB script command to type Python code
920interactively, or use the command script import fileName command to load Python
921code from a Python module (ordinary rules apply to importing modules this way).
922A third option is to type the code for the provider class interactively while
923adding it.
924
925For example, let's pretend we have a class Foo for which a synthetic children
926provider class Foo_Provider is available, in a Python module contained in file
927~/Foo_Tools.py. The following interaction sets Foo_Provider as a synthetic
928children provider in LLDB:
929
930::
931
932   (lldb) command script import ~/Foo_Tools.py
933   (lldb) type synthetic add Foo --python-class Foo_Tools.Foo_Provider
934   (lldb) frame variable a_foo
935   (Foo) a_foo = {
936      x = 1
937      y = "Hello world"
938   }
939
940LLDB has synthetic children providers for a core subset of STL classes, both in
941the version provided by libstdcpp and by libcxx, as well as for several
942Foundation classes.
943
944Synthetic children extend summary strings by enabling a new special variable:
945``${svar``.
946
947This symbol tells LLDB to refer expression paths to the synthetic children
948instead of the real ones. For instance,
949
950::
951
952   (lldb) type summary add --expand -x "std::vector<" --summary-string "${svar%#} items"
953   (lldb) frame variable numbers
954   (std::vector<int>) numbers = 4 items {
955      (int) [0] = 1
956      (int) [1] = 12
957      (int) [2] = 123
958      (int) [3] = 1234
959   }
960
961In some cases, if LLDB is unable to use the real object to get a child
962specified in an expression path, it will automatically refer to the synthetic
963children. While in summaries it is best to always use ${svar to make your
964intentions clearer, interactive debugging can benefit from this behavior, as
965in:
966
967::
968
969   (lldb) frame variable numbers[0] numbers[1]
970   (int) numbers[0] = 1
971   (int) numbers[1] = 12
972
973Unlike many other visualization features, however, the access to synthetic
974children only works when using frame variable, and is not supported in
975expression:
976
977::
978
979   (lldb) expression numbers[0]
980   Error [IRForTarget]: Call to a function '_ZNSt33vector<int, std::allocator<int> >ixEm' that is not present in the target
981   error: Couldn't convert the expression to DWARF
982
983The reason for this is that classes might have an overloaded ``operator []``,
984or other special provisions and the expression command chooses to ignore
985synthetic children in the interest of equivalency with code you asked to have
986compiled from source.
987
988Filters
989-------
990
991Filters are a solution to the display of complex classes. At times, classes
992have many member variables but not all of these are actually necessary for the
993user to see.
994
995A filter will solve this issue by only letting the user see those member
996variables he cares about. Of course, the equivalent of a filter can be
997implemented easily using synthetic children, but a filter lets you get the job
998done without having to write Python code.
999
1000For instance, if your class Foobar has member variables named A thru Z, but you
1001only need to see the ones named B, H and Q, you can define a filter:
1002
1003::
1004
1005   (lldb) type filter add Foobar --child B --child H --child Q
1006   (lldb) frame variable a_foobar
1007   (Foobar) a_foobar = {
1008      (int) B = 1
1009      (char) H = 'H'
1010      (std::string) Q = "Hello world"
1011   }
1012
1013Objective-C Dynamic Type Discovery
1014----------------------------------
1015
1016When doing Objective-C development, you may notice that some of your variables
1017come out as of type id (for instance, items extracted from NSArray). By
1018default, LLDB will not show you the real type of the object. it can actually
1019dynamically discover the type of an Objective-C variable, much like the runtime
1020itself does when invoking a selector. In order to be shown the result of that
1021discovery that, however, a special option to frame variable or expression is
1022required: ``--dynamic-type``.
1023
1024
1025``--dynamic-type`` can have one of three values:
1026
1027- ``no-dynamic-values``: the default, prevents dynamic type discovery
1028- ``no-run-target``: enables dynamic type discovery as long as running code on
1029  the target is not required
1030- ``run-target``: enables code execution on the target in order to perform
1031  dynamic type discovery
1032
1033If you specify a value of either no-run-target or run-target, LLDB will detect
1034the dynamic type of your variables and show the appropriate formatters for
1035them. As an example:
1036
1037::
1038
1039   (lldb) expr @"Hello"
1040   (NSString *) $0 = 0x00000001048000b0 @"Hello"
1041   (lldb) expr -d no-run @"Hello"
1042   (__NSCFString *) $1 = 0x00000001048000b0 @"Hello"
1043
1044Because LLDB uses a detection algorithm that does not need to invoke any
1045functions on the target process, no-run-target is enough for this to work.
1046
1047As a side note, the summary for NSString shown in the example is built right
1048into LLDB. It was initially implemented through Python (the code is still
1049available for reference at CFString.py). However, this is out of sync with the
1050current implementation of the NSString formatter (which is a C++ function
1051compiled into the LLDB core).
1052
1053Categories
1054----------
1055
1056Categories are a way to group related formatters. For instance, LLDB itself
1057groups the formatters for the libstdc++ types in a category named
1058gnu-libstdc++. Basically, categories act like containers in which to store
1059formatters for a same library or OS release.
1060
1061By default, several categories are created in LLDB:
1062
1063- default: this is the category where every formatter ends up, unless another category is specified
1064- objc: formatters for basic and common Objective-C types that do not specifically depend on macOS
1065- gnu-libstdc++: formatters for std::string, std::vector, std::list and std::map as implemented by libstdcpp
1066- libcxx: formatters for std::string, std::vector, std::list and std::map as implemented by libcxx
1067- system: truly basic types for which a formatter is required
1068- AppKit: Cocoa classes
1069- CoreFoundation: CF classes
1070- CoreGraphics: CG classes
1071- CoreServices: CS classes
1072- VectorTypes: compact display for several vector types
1073
1074If you want to use a custom category for your formatters, all the type ... add
1075provide a --category (-w) option, that names the category to add the formatter
1076to. To delete the formatter, you then have to specify the correct category.
1077
1078Categories can be in one of two states: enabled and disabled. A category is
1079initially disabled, and can be enabled using the type category enable command.
1080To disable an enabled category, the command to use is type category disable.
1081
1082The order in which categories are enabled or disabled is significant, in that
1083LLDB uses that order when looking for formatters. Therefore, when you enable a
1084category, it becomes the second one to be searched (after default, which always
1085stays on top of the list). The default categories are enabled in such a way
1086that the search order is:
1087
1088- default
1089- objc
1090- CoreFoundation
1091- AppKit
1092- CoreServices
1093- CoreGraphics
1094- gnu-libstdc++
1095- libcxx
1096- VectorTypes
1097- system
1098
1099As said, gnu-libstdc++ and libcxx contain formatters for C++ STL data types.
1100system contains formatters for char* and char[], which reflect the behavior of
1101older versions of LLDB which had built-in formatters for these types. Because
1102now these are formatters, you can even replace them with your own if so you
1103wish.
1104
1105There is no special command to create a category. When you place a formatter in
1106a category, if that category does not exist, it is automatically created. For
1107instance,
1108
1109::
1110
1111   (lldb) type summary add Foobar --summary-string "a foobar" --category newcategory
1112
1113automatically creates a (disabled) category named newcategory.
1114
1115Another way to create a new (empty) category, is to enable it, as in:
1116
1117::
1118
1119   (lldb) type category enable newcategory
1120
1121However, in this case LLDB warns you that enabling an empty category has no
1122effect. If you add formatters to the category after enabling it, they will be
1123honored. But an empty category per se does not change the way any type is
1124displayed. The reason the debugger warns you is that enabling an empty category
1125might be a typo, and you effectively wanted to enable a similarly-named but
1126not-empty category.
1127
1128Finding Formatters 101
1129----------------------
1130
1131Searching for a formatter (including formats, starting in SVN rev r192217)
1132given a variable goes through a rather intricate set of rules. Namely, what
1133happens is that LLDB starts looking in each enabled category, according to the
1134order in which they were enabled (latest enabled first). In each category, LLDB
1135does the following:
1136
1137- If there is a formatter for the type of the variable, use it
1138- If this object is a pointer, and there is a formatter for the pointee type
1139  that does not skip pointers, use it
1140- If this object is a reference, and there is a formatter for the referred type
1141  that does not skip references, use it
1142- If this object is an Objective-C class and dynamic types are enabled, look
1143  for a formatter for the dynamic type of the object. If dynamic types are
1144  disabled, or the search failed, look for a formatter for the declared type of
1145  the object
1146- If this object's type is a typedef, go through typedef hierarchy (LLDB might
1147  not be able to do this if the compiler has not emitted enough information. If
1148  the required information to traverse typedef hierarchies is missing, type
1149  cascading will not work. The clang compiler, part of the LLVM project, emits
1150  the correct debugging information for LLDB to cascade). If at any level of
1151  the hierarchy there is a valid formatter that can cascade, use it.
1152- If everything has failed, repeat the above search, looking for regular
1153  expressions instead of exact matches
1154
1155If any of those attempts returned a valid formatter to be used, that one is
1156used, and the search is terminated (without going to look in other categories).
1157If nothing was found in the current category, the next enabled category is
1158scanned according to the same algorithm. If there are no more enabled
1159categories, the search has failed.
1160
1161**Warning**: previous versions of LLDB defined cascading to mean not only going
1162through typedef chains, but also through inheritance chains. This feature has
1163been removed since it significantly degrades performance. You need to set up
1164your formatters for every type in inheritance chains to which you want the
1165formatter to apply.
1166