1333 lines · plain
1Variable Formatting2===================3 4LLDB has a data formatters subsystem that allows users to define custom display5options for their variables.6 7Usually, when you type ``frame variable`` or run some expression LLDB will8automatically choose the way to display your results on a per-type basis, as in9the following example:10 11::12 13 (lldb) frame variable14 (uint8_t) x = 'a'15 (intptr_t) y = 12475228716 17Note: ``frame variable`` without additional arguments prints the list of18variables of the current frame.19 20However, in certain cases, you may want to associate a different style to the21display for certain datatypes. To do so, you need to give hints to the debugger22as to how variables should be displayed. The LLDB type command allows you to do23just that.24 25Using it you can change your visualization to look like this:26 27::28 29 (lldb) frame variable30 (uint8_t) x = chr='a' dec=65 hex=0x4131 (intptr_t) y = 0x76f919f32 33In addition, some data structures can encode their data in a way that is not34easily readable to the user, in which case a data formatter can be used to35show the data in a human readable way. For example, without a formatter,36printing a ``std::deque<int>`` with the elements ``{2, 3, 4, 5, 6}`` would37result in something like:38 39::40 41 (lldb) frame variable a_deque42 (std::deque<Foo, std::allocator<int> >) $0 = {43 std::_Deque_base<Foo, std::allocator<int> > = {44 _M_impl = {45 _M_map = 0x000000000062ceb046 _M_map_size = 847 _M_start = {48 _M_cur = 0x000000000062cf0049 _M_first = 0x000000000062cf0050 _M_last = 0x000000000062d2f451 _M_node = 0x000000000062cec852 }53 _M_finish = {54 _M_cur = 0x000000000062d30055 _M_first = 0x000000000062d30056 _M_last = 0x000000000062d6f457 _M_node = 0x000000000062ced058 }59 }60 }61 }62 63which is very hard to make sense of.64 65Note: ``frame variable <var>`` prints out the variable ``<var>`` in the current66frame.67 68On the other hand, a proper formatter is able to produce the following output:69 70::71 72 (lldb) frame variable a_deque73 (std::deque<Foo, std::allocator<int> >) $0 = size=5 {74 [0] = 275 [1] = 376 [2] = 477 [3] = 578 [4] = 679 }80 81which is what the user would expect from a good debugger.82 83Note: you can also use ``v <var>`` instead of ``frame variable <var>``.84 85It's worth mentioning that the ``size=5`` string is produced by a summary86provider and the list of children is produced by a synthetic child provider.87More information about these providers is available later in this document.88 89 90There are several features related to data visualization: formats, summaries,91filters, synthetic children.92 93To reflect this, the type command has five subcommands:94 95::96 97 type format98 type summary99 type filter100 type synthetic101 type category102 103These commands are meant to bind printing options to types. When variables are104printed, LLDB will first check if custom printing options have been associated105to a variable's type and, if so, use them instead of picking the default106choices.107 108Each of the commands (except ``type category``) has four subcommands available:109 110- ``add``: associates a new printing option to one or more types111- ``delete``: deletes an existing association112- ``list``: provides a listing of all associations113- ``clear``: deletes all associations114 115Type Format116-----------117 118Type formats enable you to quickly override the default format for displaying119primitive types (the usual basic C/C++/ObjC types: int, float, char, ...).120 121If for some reason you want all int variables in your program to print out as122hex, you can add a format to the int type.123 124This is done by typing125 126::127 128 (lldb) type format add --format hex int129 130at the LLDB command line.131 132The ``--format`` (which you can shorten to -f) option accepts a `format133name`_. Then, you provide one or more types to which you want the134new format applied.135 136A frequent scenario is that your program has a typedef for a numeric type that137you know represents something that must be printed in a certain way. Again, you138can add a format just to that typedef by using type format add with the name139alias.140 141But things can quickly get hierarchical. Let's say you have a situation like142the following:143 144::145 146 typedef int A;147 typedef A B;148 typedef B C;149 typedef C D;150 151and you want to show all A's as hex, all C's as byte arrays and leave the152defaults untouched for other types (albeit its contrived look, the example is153far from unrealistic in large software systems).154 155If you simply type156 157::158 159 (lldb) type format add -f hex A160 (lldb) type format add -f uint8_t[] C161 162values of type B will be shown as hex and values of type D as byte arrays, as in:163 164::165 166 (lldb) frame variable -T167 (A) a = 0x00000001168 (B) b = 0x00000002169 (C) c = {0x03 0x00 0x00 0x00}170 (D) d = {0x04 0x00 0x00 0x00}171 172This is because by default LLDB cascades formats through typedef chains. In173order to avoid that you can use the option -C no to prevent cascading, thus174making the two commands required to achieve your goal:175 176::177 178 (lldb) type format add -C no -f hex A179 (lldb) type format add -C no -f uint8_t[] C180 181 182which provides the desired output:183 184::185 186 (lldb) frame variable -T187 (A) a = 0x00000001188 (B) b = 2189 (C) c = {0x03 0x00 0x00 0x00}190 (D) d = 4191 192Note, that qualifiers such as const and volatile will be stripped when matching types for example:193 194::195 196 (lldb) frame var x y z197 (int) x = 1198 (const int) y = 2199 (volatile int) z = 4200 (lldb) type format add -f hex int201 (lldb) frame var x y z202 (int) x = 0x00000001203 (const int) y = 0x00000002204 (volatile int) z = 0x00000004205 206Two additional options that you will want to look at are --skip-pointers (-p)207and --skip-references (-r). These two options prevent LLDB from applying a208format for type T to values of type T* and T& respectively.209 210::211 212 (lldb) type format add -f float32[] int213 (lldb) frame variable pointer *pointer -T214 (int *) pointer = {1.46991e-39 1.4013e-45}215 (int) *pointer = {1.53302e-42}216 (lldb) type format add -f float32[] int -p217 (lldb) frame variable pointer *pointer -T218 (int *) pointer = 0x0000000100100180219 (int) *pointer = {1.53302e-42}220 221While they can be applied to pointers and references, formats will make no222attempt to dereference the pointer and extract the value before applying the223format, which means you are effectively formatting the address stored in the224pointer rather than the pointee value. For this reason, you may want to use the225-p option when defining formats.226 227If you need to delete a custom format simply type type format delete followed228by the name of the type to which the format applies.Even if you defined the229same format for multiple types on the same command, type format delete will230only remove the format for the type name passed as argument.231 232To delete ALL formats, use ``type format clear``. To see all the formats233defined, use type format list.234 235If all you need to do, however, is display one variable in a custom format,236while leaving the others of the same type untouched, you can simply type:237 238::239 240 (lldb) frame variable counter -f hex241 242This has the effect of displaying the value of counter as an hexadecimal243number, and will keep showing it this way until you either pick a different244format or till you let your program run again.245 246Finally, this is a list of formatting options available out of which you can247pick:248 249.. _`format name`:250 251+-----------------------------------------------+------------------+--------------------------------------------------------------------------+252| **Format name** | **Abbreviation** | **Description** |253+-----------------------------------------------+------------------+--------------------------------------------------------------------------+254| ``default`` | | the default LLDB algorithm is used to pick a format |255+-----------------------------------------------+------------------+--------------------------------------------------------------------------+256| ``boolean`` | B | show this as a true/false boolean, using the customary rule that 0 is |257| | | false and everything else is true |258+-----------------------------------------------+------------------+--------------------------------------------------------------------------+259| ``binary`` | b | show this as a sequence of bits |260+-----------------------------------------------+------------------+--------------------------------------------------------------------------+261| ``bytes`` | y | show the bytes one after the other |262+-----------------------------------------------+------------------+--------------------------------------------------------------------------+263| ``bytes with ASCII`` | Y | show the bytes, but try to display them as ASCII characters as well |264+-----------------------------------------------+------------------+--------------------------------------------------------------------------+265| ``character`` | c | show the bytes as ASCII characters |266+-----------------------------------------------+------------------+--------------------------------------------------------------------------+267| ``printable character`` | C | show the bytes as printable ASCII characters |268+-----------------------------------------------+------------------+--------------------------------------------------------------------------+269| ``complex float`` | F | interpret this value as the real and imaginary part of a complex |270| | | floating-point number |271+-----------------------------------------------+------------------+--------------------------------------------------------------------------+272| ``c-string`` | s | show this as a 0-terminated C string |273+-----------------------------------------------+------------------+--------------------------------------------------------------------------+274| ``decimal`` | d | show this as a signed integer number (this does not perform a cast, it |275| | | simply shows the bytes as an integer with sign) |276+-----------------------------------------------+------------------+--------------------------------------------------------------------------+277| ``enumeration`` | E | show this as an enumeration, printing the |278| | | value's name if available or the integer value otherwise |279+-----------------------------------------------+------------------+--------------------------------------------------------------------------+280| ``hex`` | x | show this as in hexadecimal notation (this does |281| | | not perform a cast, it simply shows the bytes as hex) |282+-----------------------------------------------+------------------+--------------------------------------------------------------------------+283| ``float`` | f | show this as a floating-point number (this does not perform a cast, it |284| | | simply interprets the bytes as an IEEE754 floating-point value) |285+-----------------------------------------------+------------------+--------------------------------------------------------------------------+286| ``octal`` | o | show this in octal notation |287+-----------------------------------------------+------------------+--------------------------------------------------------------------------+288| ``OSType`` | O | show this as a MacOS OSType |289+-----------------------------------------------+------------------+--------------------------------------------------------------------------+290| ``unicode16`` | U | show this as UTF-16 characters |291+-----------------------------------------------+------------------+--------------------------------------------------------------------------+292| ``unicode32`` | | show this as UTF-32 characters |293+-----------------------------------------------+------------------+--------------------------------------------------------------------------+294| ``unsigned decimal`` | u | show this as an unsigned integer number (this does not perform a cast, |295| | | it simply shows the bytes as unsigned integer) |296+-----------------------------------------------+------------------+--------------------------------------------------------------------------+297| ``pointer`` | p | show this as a native pointer (unless this is really a pointer, the |298| | | resulting address will probably be invalid) |299+-----------------------------------------------+------------------+--------------------------------------------------------------------------+300| ``char[]`` | | show this as an array of characters |301+-----------------------------------------------+------------------+--------------------------------------------------------------------------+302| ``int8_t[], uint8_t[]`` | | show this as an array of the corresponding integer type |303| ``int16_t[], uint16_t[]`` | | |304| ``int32_t[], uint32_t[]`` | | |305| ``int64_t[], uint64_t[]`` | | |306| ``uint128_t[]`` | | |307+-----------------------------------------------+------------------+--------------------------------------------------------------------------+308| ``float32[], float64[]`` | | show this as an array of the corresponding |309| | | floating-point type |310+-----------------------------------------------+------------------+--------------------------------------------------------------------------+311| ``complex integer`` | I | interpret this value as the real and imaginary part of a complex integer |312| | | number |313+-----------------------------------------------+------------------+--------------------------------------------------------------------------+314| ``character array`` | a | show this as a character array |315+-----------------------------------------------+------------------+--------------------------------------------------------------------------+316| ``address`` | A | show this as an address target (symbol/file/line + offset), possibly |317| | | also the string this address is pointing to |318+-----------------------------------------------+------------------+--------------------------------------------------------------------------+319| ``hex float`` | | show this as hexadecimal floating point |320+-----------------------------------------------+------------------+--------------------------------------------------------------------------+321| ``instruction`` | i | show this as an disassembled opcode |322+-----------------------------------------------+------------------+--------------------------------------------------------------------------+323| ``void`` | v | don't show anything |324+-----------------------------------------------+------------------+--------------------------------------------------------------------------+325 326Type Summary327------------328 329Type formats work by showing a different kind of display for the value of a330variable. However, they only work for basic types. When you want to display a331class or struct in a custom format, you cannot do that using formats.332 333A different feature, type summaries, works by extracting information from334classes, structures, ... (aggregate types) and arranging it in a user-defined335format, as in the following example:336 337before adding a summary...338 339::340 341 (lldb) frame variable -T one342 (i_am_cool) one = {343 (int) x = 3344 (float) y = 3.14159345 (char) z = 'E'346 }347 348after adding a summary...349 350::351 352 (lldb) frame variable one353 (i_am_cool) one = int = 3, float = 3.14159, char = 69354 355There are two ways to use type summaries: the first one is to bind a summary356string to the type; the second is to write a Python script that returns the357string to be used as summary. Both options are enabled by the type summary add358command.359 360The command to obtain the output shown in the example is:361 362::363 364(lldb) type summary add --summary-string "int = ${var.x}, float = ${var.y}, char = ${var.z%u}" i_am_cool365 366Initially, we will focus on summary strings, and then describe the Python367binding mechanism.368 369Summary Format Matching On Pointers370----------------------371 372A summary formatter for a type ``T`` might or might not be appropriate to use373for pointers to that type. If the formatter is only appropriate for the type and374not its pointers, use the ``-p`` option to restrict it to match SBValues of type375``T``. If you want the formatter to also match pointers to the type, you can use376the ``-d`` option to specify how many pointer layers the formatter should match.377The default value is 1, so if you don't specify ``-p`` or ``-d``, your formatter378will be used on SBValues of type ``T`` and ``T*``. If you want to also match379``T**`` set ``-d`` to 2, etc. In all cases, the SBValue passed to the summary380formatter will be the matched ValueObject. lldb doesn't dereference the matched381value down to the SBValue of type ``T`` before passing it to your formatter.382 383Summary Strings384---------------385 386Summary strings are written using a simple control language, exemplified by the387snippet above. A summary string contains a sequence of tokens that are388processed by LLDB to generate the summary.389 390Summary strings can contain plain text, control characters and special391variables that have access to information about the current object and the392overall program state.393 394Plain text is any sequence of characters that doesn't contain a ``{``, ``}``, ``$``,395or ``\`` character, which are the syntax control characters.396 397The special variables are found in between a "${" prefix, and end with a "}"398suffix. Variables can be a simple name or they can refer to complex objects399that have subitems themselves. In other words, a variable looks like400``${object}`` or ``${object.child.otherchild}``. A variable can also be401prefixed or suffixed with other symbols meant to change the way its value is402handled. An example is ``${*var.int_pointer[0-3]}``.403 404Basically, the syntax is the same one described Frame and Thread Formatting405plus additional symbols specific for summary strings. The main of them is406${var, which is used refer to the variable that a summary is being created for.407 408The simplest thing you can do is grab a member variable of a class or structure409by typing its expression path. In the previous example, the expression path for410the field float y is simply .y. Thus, to ask the summary string to display y411you would type ${var.y}.412 413If you have code like the following:414 415::416 417 struct A {418 int x;419 int y;420 };421 struct B {422 A x;423 A y;424 int *z;425 };426 427the expression path for the y member of the x member of an object of type B428would be .x.y and you would type ``${var.x.y}`` to display it in a summary429string for type B.430 431By default, a summary defined for type T, also works for types T* and T& (you432can disable this behavior if desired). For this reason, expression paths do not433differentiate between . and ->, and the above expression path .x.y would be434just as good if you were displaying a B*, or even if the actual definition of B435were:436 437::438 439 struct B {440 A *x;441 A y;442 int *z;443 };444 445This is unlike the behavior of frame variable which, on the contrary, will446enforce the distinction. As hinted above, the rationale for this choice is that447waiving this distinction enables you to write a summary string once for type T448and use it for both T and T* instances. As a summary string is mostly about449extracting nested members' information, a pointer to an object is just as good450as the object itself for the purpose.451 452If you need to access the value of the integer pointed to by B::z, you cannot453simply say ${var.z} because that symbol refers to the pointer z. In order to454dereference it and get the pointed value, you should say ``${*var.z}``. The455``${*var`` tells LLDB to get the object that the expression paths leads to, and456then dereference it. In this example is it equivalent to ``*(bObject.z)`` in457C/C++ syntax. Because ``.`` and ``->`` operators can both be used, there is no458need to have dereferences in the middle of an expression path (e.g. you do not459need to type ``${*(var.x).x}``) to read A::x as contained in ``*(B::x)``. To460achieve that effect you can simply write ``${var.x->x}``, or even461``${var.x.x}``. The ``*`` operator only binds to the result of the whole462expression path, rather than piecewise, and there is no way to use parentheses463to change that behavior.464 465Of course, a summary string can contain more than one ${var specifier, and can466use ``${var`` and ``${*var`` specifiers together.467 468Formatting Summary Elements469---------------------------470 471An expression path can include formatting codes. Much like the type formats472discussed previously, you can also customize the way variables are displayed in473summary strings, regardless of the format they have applied to their types. To474do that, you can use %format inside an expression path, as in ${var.x->x%u},475which would display the value of x as an unsigned integer.476 477Additionally, custom output can be achieved by using an LLVM format string,478commencing with the ``:`` marker. To illustrate, compare ``${var.byte%x}`` and479``${var.byte:x-}``. The former uses lldb's builtin hex formatting (``x``),480which unconditionally inserts a ``0x`` prefix, and also zero pads the value to481match the size of the type. The latter uses ``llvm::formatv`` formatting482(``:x-``), and will print only the hex value, with no ``0x`` prefix, and no483padding. This raw control is useful when composing multiple pieces into a484larger whole.485 486You can also use some other special format markers, not available for formats487themselves, but which carry a special meaning when used in this context:488 489+------------+--------------------------------------------------------------------------+490| **Symbol** | **Description** |491+------------+--------------------------------------------------------------------------+492| ``Symbol`` | ``Description`` |493+------------+--------------------------------------------------------------------------+494| ``%S`` | Use this object's summary (the default for aggregate types) |495+------------+--------------------------------------------------------------------------+496| ``%V`` | Use this object's value (the default for non-aggregate types) |497+------------+--------------------------------------------------------------------------+498| ``%@`` | Use a language-runtime specific description (for C++ this does nothing, |499| | for Objective-C it calls the NSPrintForDebugger API) |500+------------+--------------------------------------------------------------------------+501| ``%L`` | Use this object's location (memory address, register name, ...) |502+------------+--------------------------------------------------------------------------+503| ``%#`` | Use the count of the children of this object |504+------------+--------------------------------------------------------------------------+505| ``%T`` | Use this object's datatype name |506+------------+--------------------------------------------------------------------------+507| ``%N`` | Print the variable's basename |508+------------+--------------------------------------------------------------------------+509| ``%>`` | Print the expression path for this item |510+------------+--------------------------------------------------------------------------+511 512Since lldb 3.7.0, you can also specify ``${script.var:pythonFuncName}``.513 514It is expected that the function name you use specifies a function whose515signature is the same as a Python summary function. The return string from the516function will be placed verbatim in the output.517 518You cannot use element access, or formatting symbols, in combination with this519syntax. For example the following:520 521::522 523 ${script.var.element[0]:myFunctionName%@}524 525is not valid and will cause the summary to fail to evaluate.526 527 528Element Inlining529----------------530 531Option --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.532 533As an example, given a type pair:534 535::536 537 (lldb) frame variable --show-types a_pair538 (pair) a_pair = {539 (int) first = 1;540 (int) second = 2;541 }542 543If one types the following commands:544 545::546 547 (lldb) type summary add --inline-children pair548 549the output becomes:550 551::552 553 (lldb) frame variable a_pair554 (pair) a_pair = (first=1, second=2)555 556 557Of course, one can obtain the same effect by typing558 559::560 561 (lldb) type summary add pair --summary-string "(first=${var.first}, second=${var.second})"562 563While the final result is the same, using --inline-children can often save564time. If one does not need to see the names of the variables, but just their565values, the option --omit-names (-O, uppercase letter o), can be combined with566--inline-children to obtain:567 568::569 570 (lldb) frame variable a_pair571 (pair) a_pair = (1, 2)572 573which is of course the same as typing574 575::576 577 (lldb) type summary add pair --summary-string "(${var.first}, ${var.second})"578 579Bitfields And Array Syntax580--------------------------581 582Sometimes, a basic type's value actually represents several different values583packed together in a bitfield.584 585With the classical view, there is no way to look at them. Hexadecimal display586can help, but if the bits actually span nibble boundaries, the help is limited.587 588Binary view would show it all without ambiguity, but is often too detailed and589hard to read for real-life scenarios.590 591To cope with the issue, LLDB supports native bitfield formatting in summary592strings. If your expression paths leads to a so-called scalar type (the usual593int, float, char, double, short, long, long long, double, long double and594unsigned variants), you can ask LLDB to only grab some bits out of the value595and display them in any format you like. If you only need one bit you can use596the [n], just like indexing an array. To extract multiple bits, you can use a597slice-like syntax: [n-m], e.g.598 599::600 601 (lldb) frame variable float_point602 (float) float_point = -3.14159603 604::605 606 (lldb) type summary add --summary-string "Sign: ${var[31]%B} Exponent: ${var[30-23]%x} Mantissa: ${var[0-22]%u}" float607 (lldb) frame variable float_point608 (float) float_point = -3.14159 Sign: true Exponent: 0x00000080 Mantissa: 4788184609 610In this example, LLDB shows the internal representation of a float variable by611extracting bitfields out of a float object.612 613When typing a range, the extremes n and m are always included, and the order of614the indices is irrelevant.615 616LLDB 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.617e.g.618 619::620 621 (lldb) frame variable sarray622 (Simple [3]) sarray = {623 [0] = {624 x = 1625 y = 2626 z = '\x03'627 }628 [1] = {629 x = 4630 y = 5631 z = '\x06'632 }633 [2] = {634 x = 7635 y = 8636 z = '\t'637 }638 }639 640 (lldb) type summary add --summary-string "${var[].x}" "Simple [3]"641 642 (lldb) frame variable sarray643 (Simple [3]) sarray = [1,4,7]644 645The [] 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:646 647::648 649 (lldb) frame variable sarray[1]650 (Simple) sarray[1] = {651 x = 4652 y = 5653 z = '\x06'654 }655 656You can also ask LLDB to only print a subset of the array range by using the657same syntax used to extract bit for bitfields:658 659::660 661 (lldb) type summary add --summary-string "${var[1-2].x}" "Simple [3]"662 663 (lldb) frame variable sarray664 (Simple [3]) sarray = [4,7]665 666If you are dealing with a pointer that you know is an array, you can use this667syntax to display the elements contained in the pointed array instead of just668the pointer value. However, because pointers have no notion of their size, the669empty brackets [] operator does not work, and you must explicitly provide670higher and lower bounds.671 672In general, LLDB needs the square brackets ``operator []`` in order to handle673arrays and pointers correctly, and for pointers it also needs a range. However,674a few special cases are defined to make your life easier:675 676you can print a 0-terminated string (C-string) using the %s format, omitting677square brackets, as in:678 679::680 681 (lldb) type summary add --summary-string "${var%s}" "char *"682 683This syntax works for char* as well as for char[] because LLDB can rely on the684final \0 terminator to know when the string has ended.685 686LLDB has default summary strings for char* and char[] that use this special687case. On debugger startup, the following are defined automatically:688 689::690 691 (lldb) type summary add --summary-string "${var%s}" "char *"692 (lldb) type summary add --summary-string "${var%s}" -x "char \[[0-9]+]"693 694any of the array formats (int8_t[], float32{}, ...), and the y, Y and a formats695work to print an array of a non-aggregate type, even if square brackets are696omitted.697 698::699 700 (lldb) type summary add --summary-string "${var%int32_t[]}" "int [10]"701 702This feature, however, is not enabled for pointers because there is no way for703LLDB to detect the end of the pointed data.704 705This also does not work for other formats (e.g. boolean), and you must specify706the square brackets operator to get the expected output.707 708Python Scripting709----------------710 711Most of the times, summary strings prove good enough for the job of summarizing712the contents of a variable. However, as soon as you need to do more than713picking some values and rearranging them for display, summary strings stop714being an effective tool. This is because summary strings lack the power to715actually perform any kind of computation on the value of variables.716 717To solve this issue, you can bind some Python scripting code as a summary for718your datatype, and that script has the ability to both extract children719variables as the summary strings do and to perform active computation on the720extracted values. As a small example, let's say we have a Rectangle class:721 722::723 724 725 class Rectangle726 {727 private:728 int height;729 int width;730 public:731 Rectangle() : height(3), width(5) {}732 Rectangle(int H) : height(H), width(H*2-1) {}733 Rectangle(int H, int W) : height(H), width(W) {}734 int GetHeight() { return height; }735 int GetWidth() { return width; }736 };737 738Summary strings are effective to reduce the screen real estate used by the739default viewing mode, but are not effective if we want to display the area and740perimeter of Rectangle objects741 742To obtain this, we can simply attach a small Python script to the Rectangle743class, as shown in this example:744 745::746 747 (lldb) type summary add -P Rectangle748 Enter your Python command(s). Type 'DONE' to end.749 def function (valobj,internal_dict,options):750 height_val = valobj.GetChildMemberWithName('height')751 width_val = valobj.GetChildMemberWithName('width')752 height = height_val.GetValueAsUnsigned(0)753 width = width_val.GetValueAsUnsigned(0)754 area = height*width755 perimeter = 2*(height + width)756 return 'Area: ' + str(area) + ', Perimeter: ' + str(perimeter)757 DONE758 (lldb) frame variable759 (Rectangle) r1 = Area: 20, Perimeter: 18760 (Rectangle) r2 = Area: 72, Perimeter: 36761 (Rectangle) r3 = Area: 16, Perimeter: 16762 763In order to write effective summary scripts, you need to know the LLDB public764API, which is the way Python code can access the LLDB object model. For further765details on the API you should look at the LLDB API reference documentation.766 767 768As a brief introduction, your script is encapsulated into a function that is769passed two parameters: ``valobj`` and ``internal_dict``.770 771``internal_dict`` is an internal support parameter used by LLDB and you should772not touch it.773 774``valobj`` is the object encapsulating the actual variable being displayed, and775its type is `SBValue`. Out of the many possible operations on an `SBValue`, the776basic one is retrieve the children objects it contains (essentially, the fields777of the object wrapped by it), by calling ``GetChildMemberWithName()``, passing778it the child's name as a string.779 780If the variable has a value, you can ask for it, and return it as a string781using ``GetValue()``, or as a signed/unsigned number using782``GetValueAsSigned()``, ``GetValueAsUnsigned()``. It is also possible to783retrieve an `SBData` object by calling ``GetData()`` and then read the object's784contents out of the `SBData`.785 786If you need to delve into several levels of hierarchy, as you can do with787summary strings, you can use the method ``GetValueForExpressionPath()``,788passing it an expression path just like those you could use for summary strings789(one of the differences is that dereferencing a pointer does not occur by790prefixing the path with a ``*```, but by calling the ``Dereference()`` method791on the returned `SBValue`). If you need to access array slices, you cannot do792that (yet) via this method call, and you must use ``GetChildAtIndex()``793querying it for the array items one by one. Also, handling custom formats is794something you have to deal with on your own.795 796``options`` Python summary formatters can optionally define this797third argument, which is an object of type ``lldb.SBTypeSummaryOptions``,798allowing for a few customizations of the result. The decision to799adopt or not this third argument - and the meaning of options800thereof - is up to the individual formatter's writer.801 802Other than interactively typing a Python script there are two other ways for803you to input a Python script as a summary:804 805- using the --python-script option to type summary add and typing the script806 code as an option argument; as in:807 808::809 810 (lldb) type summary add --python-script "height = valobj.GetChildMemberWithName('height').GetValueAsUnsigned(0);width = valobj.GetChildMemberWithName('width').GetValueAsUnsigned(0); return 'Area: %d' % (height*width)" Rectangle811 812 813- using the --python-function (-F) option to type summary add and giving the814 name of a Python function with the correct prototype. Most probably, you will815 define (or have already defined) the function in the interactive interpreter,816 or somehow loaded it from a file, using the command script import command.817 LLDB will emit a warning if it is unable to find the function you passed, but818 will still register the binding.819 820Regular Expression Typenames821----------------------------822 823As you noticed, in order to associate the custom summary string to the array824types, one must give the array size as part of the typename. This can long825become tiresome when using arrays of different sizes, Simple [3], Simple [9],826Simple [12], ...827 828If you use the -x option, type names are treated as regular expressions instead829of type names. This would let you rephrase the above example for arrays of type830Simple [3] as:831 832::833 834 (lldb) type summary add --summary-string "${var[].x}" -x "Simple \[[0-9]+\]"835 (lldb) frame variable836 (Simple [3]) sarray = [1,4,7]837 (Simple [2]) sother = [3,6]838 839The above scenario works for Simple [3] as well as for any other array of840Simple objects.841 842While this feature is mostly useful for arrays, you could also use regular843expressions to catch other type sets grouped by name. However, as regular844expression matching is slower than normal name matching, LLDB will first try to845match by name in any way it can, and only when this fails, will it resort to846regular expression matching.847 848One of the ways LLDB uses this feature internally, is to match the names of STL849container classes, regardless of the template arguments provided. The details850for this are found at FormatManager.cpp851 852The regular expression language used by LLDB is the POSIX extended language, as853defined by the Single UNIX Specification, of which macOS is a compliant854implementation.855 856Names Summaries857---------------858 859For a given type, there may be different meaningful summary representations.860However, currently, only one summary can be associated to a type at each861moment. If you need to temporarily override the association for a variable,862without changing the summary string for to its type, you can use named863summaries.864 865Named summaries work by attaching a name to a summary when creating it. Then,866when there is a need to attach the summary to a variable, the frame variable867command, supports a --summary option that tells LLDB to use the named summary868given instead of the default one.869 870::871 872 (lldb) type summary add --summary-string "x=${var.integer}" --name NamedSummary873 (lldb) frame variable one874 (i_am_cool) one = int = 3, float = 3.14159, char = 69875 (lldb) frame variable one --summary NamedSummary876 (i_am_cool) one = x=3877 878When defining a named summary, binding it to one or more types becomes879optional. Even if you bind the named summary to a type, and later change the880summary string for that type, the named summary will not be changed by that.881You can delete named summaries by using the type summary delete command, as if882the summary name was the datatype that the summary is applied to883 884A summary attached to a variable using the --summary option, has the same885semantics that a custom format attached using the -f option has: it stays886attached till you attach a new one, or till you let your program run again.887 888Synthetic Children889------------------890 891Summaries work well when one is able to navigate through an expression path. In892order for LLDB to do so, appropriate debugging information must be available.893 894Some types are opaque, i.e. no knowledge of their internals is provided. When895that's the case, expression paths do not work correctly.896 897In other cases, the internals are available to use in expression paths, but898they do not provide a user-friendly representation of the object's value.899 900For instance, consider an STL vector, as implemented by the GNU C++ Library:901 902::903 904 (lldb) frame variable numbers -T905 (std::vector<int>) numbers = {906 (std::_Vector_base<int, std::allocator<int> >) std::_Vector_base<int, std::allocator<int> > = {907 (std::_Vector_base<int, std::allocator&tl;int> >::_Vector_impl) _M_impl = {908 (int *) _M_start = 0x00000001001008a0909 (int *) _M_finish = 0x00000001001008a8910 (int *) _M_end_of_storage = 0x00000001001008a8911 }912 }913 }914 915Here, you can see how the type is implemented, and you can write a summary for916that implementation but that is not going to help you infer what items are917actually stored in the vector.918 919What you would like to see is probably something like:920 921::922 923 (lldb) frame variable numbers -T924 (std::vector<int>) numbers = {925 (int) [0] = 1926 (int) [1] = 12927 (int) [2] = 123928 (int) [3] = 1234929 }930 931Synthetic children are a way to get that result.932 933The feature is based upon the idea of providing a new set of children for a934variable that replaces the ones available by default through the debug935information. In the example, we can use synthetic children to provide the936vector items as children for the std::vector object.937 938In order to create synthetic children, you need to provide a Python class that939adheres to a given interface (the word is italicized because Python has no940explicit notion of interface, by that word we mean a given set of methods must941be implemented by the Python class):942 943.. code-block:: python944 945 class SyntheticChildrenProvider:946 def __init__(self, valobj, internal_dict):947 this call should initialize the Python object using valobj as the948 variable to provide synthetic children for949 def num_children(self, max_children):950 this call should return the number of children that you want your951 object to have[1]952 def get_child_index(self,name):953 this call should return the index of the synthetic child whose name is954 given as argument955 def get_child_at_index(self,index):956 this call should return a new LLDB SBValue object representing the957 child at the index given as argument958 def update(self):959 this call should be used to update the internal state of this Python960 object whenever the state of the variables in LLDB changes.[2]961 Also, this method is invoked before any other method in the interface.962 def has_children(self):963 this call should return True if this object might have children, and964 False if this object can be guaranteed not to have children.[3]965 def get_value(self):966 this call can return an SBValue to be presented as the value of the967 synthetic value under consideration.[4]968 969As a warning, exceptions that are thrown by python formatters are caught970silently by LLDB and should be handled appropriately by the formatter itself.971Being more specific, in case of exceptions, LLDB might assume that the given972object has no children or it might skip printing some children, as they are973printed one by one.974 975[1] The `max_children` argument is optional (since lldb 3.8.0) and indicates the976maximum number of children that lldb is interested in (at this moment). If the977computation of the number of children is expensive (for example, requires978traversing a linked list to determine its size) your implementation may return979`max_children` rather than the actual number. If the computation is cheap (e.g., the980number is stored as a field of the object), then you can always return the true981number of children (that is, ignore the `max_children` argument).982 983[2] This method is optional. Also, a boolean value must be returned (since lldb9843.1.0). If ``False`` is returned, then whenever the process reaches a new stop,985this method will be invoked again to generate an updated list of the children986for a given variable. Otherwise, if ``True`` is returned, then the value is987cached and this method won't be called again, effectively freezing the state of988the value in subsequent stops. Beware that returning ``True`` incorrectly could989show misleading information to the user.990 991[3] This method is optional (since lldb 3.2.0). While implementing it in terms992of num_children is acceptable, implementors are encouraged to look for993optimized coding alternatives whenever reasonable.994 995[4] This method is optional (since lldb 3.5.2). The `SBValue` you return here996will most likely be a numeric type (int, float, ...) as its value bytes will be997used as-if they were the value of the root `SBValue` proper. As a shortcut for998this, you can inherit from lldb.SBSyntheticValueProvider, and just define999get_value as other methods are defaulted in the superclass as returning default1000no-children responses.1001 1002If a synthetic child provider supplies a special child named1003``$$dereference$$`` then it will be used when evaluating ``operator *`` and1004``operator ->`` in the frame variable command and related SB API1005functions. It is possible to declare this synthetic child without1006including it in the range of children displayed by LLDB. For example,1007this subset of a synthetic children provider class would allow the1008synthetic value to be dereferenced without actually showing any1009synthetic children in the UI:1010 1011.. code-block:: python1012 1013 class SyntheticChildrenProvider:1014 [...]1015 def num_children(self):1016 return 01017 def get_child_index(self, name):1018 if name == '$$dereference$$':1019 return 01020 return -11021 def get_child_at_index(self, index):1022 if index == 0:1023 return <valobj resulting from dereference>1024 return None1025 1026 1027For examples of how synthetic children are created, you are encouraged to look1028at examples/synthetic in the LLDB trunk. Please, be aware that the code in1029those files (except bitfield/) is legacy code and is not maintained. You may1030especially want to begin looking at this example to get a feel for this1031feature, as it is a very easy and well commented example.1032 1033The design pattern consistently used in synthetic providers shipping with LLDB1034is to use the __init__ to store the `SBValue` instance as a part of self. The1035update function is then used to perform the actual initialization. Once a1036synthetic children provider is written, one must load it into LLDB before it1037can be used. Currently, one can use the LLDB script command to type Python code1038interactively, or use the command script import fileName command to load Python1039code from a Python module (ordinary rules apply to importing modules this way).1040A third option is to type the code for the provider class interactively while1041adding it.1042 1043For example, let's pretend we have a class Foo for which a synthetic children1044provider class Foo_Provider is available, in a Python module contained in file1045~/Foo_Tools.py. The following interaction sets Foo_Provider as a synthetic1046children provider in LLDB:1047 1048::1049 1050 (lldb) command script import ~/Foo_Tools.py1051 (lldb) type synthetic add Foo --python-class Foo_Tools.Foo_Provider1052 (lldb) frame variable a_foo1053 (Foo) a_foo = {1054 x = 11055 y = "Hello world"1056 }1057 1058LLDB has synthetic children providers for a core subset of STL classes, both in1059the version provided by libstdcpp and by libcxx, as well as for several1060Foundation classes.1061 1062Synthetic children extend summary strings by enabling a new special variable:1063``${svar``.1064 1065This symbol tells LLDB to refer expression paths to the synthetic children1066instead of the real ones. For instance,1067 1068::1069 1070 (lldb) type summary add --expand -x "std::vector<" --summary-string "${svar%#} items"1071 (lldb) frame variable numbers1072 (std::vector<int>) numbers = 4 items {1073 (int) [0] = 11074 (int) [1] = 121075 (int) [2] = 1231076 (int) [3] = 12341077 }1078 1079It's important to mention that LLDB invokes the synthetic child provider before1080invoking the summary string provider, which allows the latter to have access to1081the actual displayable children. This applies to both inlined summary strings1082and python-based summary providers.1083 1084 1085As a warning, when programmatically accessing the children or children count of1086a variable that has a synthetic child provider, notice that LLDB hides the1087actual raw children. For example, suppose we have a ``std::vector``, which has1088an actual in-memory property ``__begin`` marking the beginning of its data.1089After the synthetic child provider is executed, the ``std::vector`` variable1090won't show ``__begin`` as child anymore, even through the SB API. It will have1091instead the children calculated by the provider. In case the actual raw1092children are needed, a call to ``value.GetNonSyntheticValue()`` is enough to1093get a raw version of the value. It is import to remember this when implementing1094summary string providers, as they run after the synthetic child provider.1095 1096 1097In some cases, if LLDB is unable to use the real object to get a child1098specified in an expression path, it will automatically refer to the synthetic1099children. While in summaries it is best to always use ${svar to make your1100intentions clearer, interactive debugging can benefit from this behavior, as1101in:1102 1103::1104 1105 (lldb) frame variable numbers[0] numbers[1]1106 (int) numbers[0] = 11107 (int) numbers[1] = 121108 1109Unlike many other visualization features, however, the access to synthetic1110children only works when using frame variable, and is not supported in1111expression:1112 1113::1114 1115 (lldb) expression numbers[0]1116 Error [IRForTarget]: Call to a function '_ZNSt33vector<int, std::allocator<int> >ixEm' that is not present in the target1117 error: Couldn't convert the expression to DWARF1118 1119The reason for this is that classes might have an overloaded ``operator []``,1120or other special provisions and the expression command chooses to ignore1121synthetic children in the interest of equivalency with code you asked to have1122compiled from source.1123 1124Filters1125-------1126 1127Filters are a solution to the display of complex classes. At times, classes1128have many member variables but not all of these are actually necessary for the1129user to see.1130 1131A filter will solve this issue by only letting the user see those member1132variables they care about. Of course, the equivalent of a filter can be1133implemented easily using synthetic children, but a filter lets you get the job1134done without having to write Python code.1135 1136For instance, if your class Foobar has member variables named A thru Z, but you1137only need to see the ones named B, H and Q, you can define a filter:1138 1139::1140 1141 (lldb) type filter add Foobar --child B --child H --child Q1142 (lldb) frame variable a_foobar1143 (Foobar) a_foobar = {1144 (int) B = 11145 (char) H = 'H'1146 (std::string) Q = "Hello world"1147 }1148 1149Callback-based type matching1150----------------------------1151 1152Even though regular expression matching works well for the vast majority of data1153formatters (you normally know the name of the type you're writing a formatter1154for), there are some cases where it's useful to look at the type before deciding1155what formatter to apply.1156 1157As an example scenario, imagine we have a code generator that produces some1158classes that inherit from a common ``GeneratedObject`` class, and we have a1159summary function and a synthetic child provider that work for all1160``GeneratedObject`` instances (they all follow the same pattern). However, there1161is no common pattern in the name of these classes, so we can't register the1162formatter neither by name nor by regular expression.1163 1164In that case, you can write a recognizer function like this:1165 1166::1167 1168 def is_generated_object(sbtype, internal_dict):1169 for base in sbtype.get_bases_array():1170 if base.GetName() == "GeneratedObject"1171 return True1172 return False1173 1174And pass this function to ``type summary add`` and ``type synthetic add`` using1175the flag ``--recognizer-function``.1176 1177::1178 1179 (lldb) type summary add --expand --python-function my_summary_function --recognizer-function is_generated_object1180 (lldb) type synthetic add --python-class my_child_provider --recognizer-function is_generated_object1181 1182Objective-C Dynamic Type Discovery1183----------------------------------1184 1185When doing Objective-C development, you may notice that some of your variables1186come out as of type id (for instance, items extracted from NSArray). By1187default, LLDB will not show you the real type of the object. it can actually1188dynamically discover the type of an Objective-C variable, much like the runtime1189itself does when invoking a selector. In order to be shown the result of that1190discovery that, however, a special option to frame variable or expression is1191required: ``--dynamic-type``.1192 1193 1194``--dynamic-type`` can have one of three values:1195 1196- ``no-dynamic-values``: the default, prevents dynamic type discovery1197- ``no-run-target``: enables dynamic type discovery as long as running code on1198 the target is not required1199- ``run-target``: enables code execution on the target in order to perform1200 dynamic type discovery1201 1202If you specify a value of either no-run-target or run-target, LLDB will detect1203the dynamic type of your variables and show the appropriate formatters for1204them. As an example:1205 1206::1207 1208 (lldb) expr @"Hello"1209 (NSString *) $0 = 0x00000001048000b0 @"Hello"1210 (lldb) expr -d no-run @"Hello"1211 (__NSCFString *) $1 = 0x00000001048000b0 @"Hello"1212 1213Because LLDB uses a detection algorithm that does not need to invoke any1214functions on the target process, no-run-target is enough for this to work.1215 1216As a side note, the summary for NSString shown in the example is built right1217into LLDB. It was initially implemented through Python (the code is still1218available for reference at CFString.py). However, this is out of sync with the1219current implementation of the NSString formatter (which is a C++ function1220compiled into the LLDB core).1221 1222Categories1223----------1224 1225Categories are a way to group related formatters. For instance, LLDB itself1226groups the formatters for STL types in a category named cpluspus. Basically,1227categories act like containers in which to store formatters for a same library1228or OS release.1229 1230By default, several categories are created in LLDB:1231 1232- default: this is the category where every formatter ends up, unless another category is specified1233- objc: formatters for basic and common Objective-C types that do not specifically depend on macOS1234- cplusplus: formatters for STL types (currently only libc++ and libstdc++ are supported). Enabled when debugging C++ targets.1235- system: truly basic types for which a formatter is required1236- AppKit: Cocoa classes1237- CoreFoundation: CF classes1238- CoreGraphics: CG classes1239- CoreServices: CS classes1240- VectorTypes: compact display for several vector types1241 1242If you want to use a custom category for your formatters, all the ``type ... add``1243provide a ``--category`` (``-w``) option, that names the category to add the formatter1244to. To delete the formatter, you then have to specify the correct category.1245 1246Categories can be in one of two states: enabled and disabled. A category is1247initially disabled, and can be enabled using the ``type category enable`` command.1248To disable an enabled category, the command to use is ``type category disable``.1249 1250The order in which categories are enabled or disabled is significant, in that1251LLDB uses that order when looking for formatters. Therefore, when you enable a1252category, it becomes the second one to be searched (after default, which always1253stays on top of the list). The default categories are enabled in such a way1254that the search order is:1255 1256- default1257- objc1258- CoreFoundation1259- AppKit1260- CoreServices1261- CoreGraphics1262- cplusplus1263- VectorTypes1264- system1265 1266As said, cplusplus contain formatters for C++ STL data types.1267system contains formatters for char* and char[], which reflect the behavior of1268older versions of LLDB which had built-in formatters for these types. Because1269now these are formatters, you can even replace them with your own if so you1270wish.1271 1272There is no special command to create a category. When you place a formatter in1273a category, if that category does not exist, it is automatically created. For1274instance,1275 1276::1277 1278 (lldb) type summary add Foobar --summary-string "a foobar" --category newcategory1279 1280automatically creates a (disabled) category named newcategory.1281 1282Another way to create a new (empty) category, is to enable it, as in:1283 1284::1285 1286 (lldb) type category enable newcategory1287 1288However, in this case LLDB warns you that enabling an empty category has no1289effect. If you add formatters to the category after enabling it, they will be1290honored. But an empty category per se does not change the way any type is1291displayed. The reason the debugger warns you is that enabling an empty category1292might be a typo, and you effectively wanted to enable a similarly-named but1293not-empty category.1294 1295Finding Formatters 1011296----------------------1297 1298Searching for a formatter (including formats, since lldb 3.4.0) given a1299variable goes through a rather intricate set of rules. Namely, what happens is1300that LLDB starts looking in each enabled category, according to the order in1301which they were enabled (latest enabled first). In each category, LLDB does the1302following:1303 1304- If there is a formatter for the type of the variable, use it1305- If this object is a pointer, and there is a formatter for the pointee type1306 that does not skip pointers, use it1307- If this object is a reference, and there is a formatter for the referred type1308 that does not skip references, use it1309- If this object is an Objective-C class and dynamic types are enabled, look1310 for a formatter for the dynamic type of the object. If dynamic types are1311 disabled, or the search failed, look for a formatter for the declared type of1312 the object1313- If this object's type is a typedef, go through typedef hierarchy (LLDB might1314 not be able to do this if the compiler has not emitted enough information. If1315 the required information to traverse typedef hierarchies is missing, type1316 cascading will not work. The clang compiler, part of the LLVM project, emits1317 the correct debugging information for LLDB to cascade). If at any level of1318 the hierarchy there is a valid formatter that can cascade, use it.1319- If everything has failed, repeat the above search, looking for regular1320 expressions instead of exact matches1321 1322If any of those attempts returned a valid formatter to be used, that one is1323used, and the search is terminated (without going to look in other categories).1324If nothing was found in the current category, the next enabled category is1325scanned according to the same algorithm. If there are no more enabled1326categories, the search has failed.1327 1328**Warning**: previous versions of LLDB defined cascading to mean not only going1329through typedef chains, but also through inheritance chains. This feature has1330been removed since it significantly degrades performance. You need to set up1331your formatters for every type in inheritance chains to which you want the1332formatter to apply.1333