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 need to 370have dereferences in the middle of an expression path (e.g. you do not need to 371type ``${*(var.x).x}``) to read A::x as contained in ``*(B::x)``. To achieve 372that effect you can simply write ``${var.x->x}``, or even ``${var.x.x}``. The 373``*`` operator only binds to the result of the whole expression path, rather 374than piecewise, and there is no way to use parentheses to change that behavior. 375 376Of course, a summary string can contain more than one ${var specifier, and can 377use ``${var`` and ``${*var`` specifiers together. 378 379Formatting Summary Elements 380--------------------------- 381 382An expression path can include formatting codes. Much like the type formats 383discussed previously, you can also customize the way variables are displayed in 384summary strings, regardless of the format they have applied to their types. To 385do that, you can use %format inside an expression path, as in ${var.x->x%u}, 386which would display the value of x as an unsigned integer. 387 388You can also use some other special format markers, not available for formats 389themselves, but which carry a special meaning when used in this context: 390 391+------------+--------------------------------------------------------------------------+ 392| **Symbol** | **Description** | 393+------------+--------------------------------------------------------------------------+ 394| ``Symbol`` | ``Description`` | 395+------------+--------------------------------------------------------------------------+ 396| ``%S`` | Use this object's summary (the default for aggregate types) | 397+------------+--------------------------------------------------------------------------+ 398| ``%V`` | Use this object's value (the default for non-aggregate types) | 399+------------+--------------------------------------------------------------------------+ 400| ``%@`` | Use a language-runtime specific description (for C++ this does nothing, | 401| | for Objective-C it calls the NSPrintForDebugger API) | 402+------------+--------------------------------------------------------------------------+ 403| ``%L`` | Use this object's location (memory address, register name, ...) | 404+------------+--------------------------------------------------------------------------+ 405| ``%#`` | Use the count of the children of this object | 406+------------+--------------------------------------------------------------------------+ 407| ``%T`` | Use this object's datatype name | 408+------------+--------------------------------------------------------------------------+ 409| ``%N`` | Print the variable's basename | 410+------------+--------------------------------------------------------------------------+ 411| ``%>`` | Print the expression path for this item | 412+------------+--------------------------------------------------------------------------+ 413 414Starting with SVN r228207, you can also specify 415``${script.var:pythonFuncName}``. Previously, back to r220821, this was 416specified with a different syntax: ``${var.script:pythonFuncName}``. 417 418It is expected that the function name you use specifies a function whose 419signature is the same as a Python summary function. The return string from the 420function will be placed verbatim in the output. 421 422You cannot use element access, or formatting symbols, in combination with this 423syntax. For example the following: 424 425:: 426 427 ${script.var.element[0]:myFunctionName%@} 428 429is not valid and will cause the summary to fail to evaluate. 430 431 432Element Inlining 433---------------- 434 435Option --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. 436 437As an example, given a type pair: 438 439:: 440 441 (lldb) frame variable --show-types a_pair 442 (pair) a_pair = { 443 (int) first = 1; 444 (int) second = 2; 445 } 446 447If one types the following commands: 448 449:: 450 451 (lldb) type summary add --inline-children pair 452 453the output becomes: 454 455:: 456 457 (lldb) frame variable a_pair 458 (pair) a_pair = (first=1, second=2) 459 460 461Of course, one can obtain the same effect by typing 462 463:: 464 465 (lldb) type summary add pair --summary-string "(first=${var.first}, second=${var.second})" 466 467While the final result is the same, using --inline-children can often save 468time. If one does not need to see the names of the variables, but just their 469values, the option --omit-names (-O, uppercase letter o), can be combined with 470--inline-children to obtain: 471 472:: 473 474 (lldb) frame variable a_pair 475 (pair) a_pair = (1, 2) 476 477which is of course the same as typing 478 479:: 480 481 (lldb) type summary add pair --summary-string "(${var.first}, ${var.second})" 482 483Bitfields And Array Syntax 484-------------------------- 485 486Sometimes, a basic type's value actually represents several different values 487packed together in a bitfield. 488 489With the classical view, there is no way to look at them. Hexadecimal display 490can help, but if the bits actually span nibble boundaries, the help is limited. 491 492Binary view would show it all without ambiguity, but is often too detailed and 493hard to read for real-life scenarios. 494 495To cope with the issue, LLDB supports native bitfield formatting in summary 496strings. If your expression paths leads to a so-called scalar type (the usual 497int, float, char, double, short, long, long long, double, long double and 498unsigned variants), you can ask LLDB to only grab some bits out of the value 499and display them in any format you like. If you only need one bit you can use 500the [n], just like indexing an array. To extract multiple bits, you can use a 501slice-like syntax: [n-m], e.g. 502 503:: 504 505 (lldb) frame variable float_point 506 (float) float_point = -3.14159 507 508:: 509 510 (lldb) type summary add --summary-string "Sign: ${var[31]%B} Exponent: ${var[30-23]%x} Mantissa: ${var[0-22]%u}" float 511 (lldb) frame variable float_point 512 (float) float_point = -3.14159 Sign: true Exponent: 0x00000080 Mantissa: 4788184 513 514In this example, LLDB shows the internal representation of a float variable by 515extracting bitfields out of a float object. 516 517When typing a range, the extremes n and m are always included, and the order of 518the indices is irrelevant. 519 520LLDB 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. 521e.g. 522 523:: 524 525 (lldb) frame variable sarray 526 (Simple [3]) sarray = { 527 [0] = { 528 x = 1 529 y = 2 530 z = '\x03' 531 } 532 [1] = { 533 x = 4 534 y = 5 535 z = '\x06' 536 } 537 [2] = { 538 x = 7 539 y = 8 540 z = '\t' 541 } 542 } 543 544 (lldb) type summary add --summary-string "${var[].x}" "Simple [3]" 545 546 (lldb) frame variable sarray 547 (Simple [3]) sarray = [1,4,7] 548 549The [] 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: 550 551:: 552 553 (lldb) frame variable sarray[1] 554 (Simple) sarray[1] = { 555 x = 4 556 y = 5 557 z = '\x06' 558 } 559 560You can also ask LLDB to only print a subset of the array range by using the 561same syntax used to extract bit for bitfields: 562 563:: 564 565 (lldb) type summary add --summary-string "${var[1-2].x}" "Simple [3]" 566 567 (lldb) frame variable sarray 568 (Simple [3]) sarray = [4,7] 569 570If you are dealing with a pointer that you know is an array, you can use this 571syntax to display the elements contained in the pointed array instead of just 572the pointer value. However, because pointers have no notion of their size, the 573empty brackets [] operator does not work, and you must explicitly provide 574higher and lower bounds. 575 576In general, LLDB needs the square brackets operator [] in order to handle 577arrays and pointers correctly, and for pointers it also needs a range. However, 578a few special cases are defined to make your life easier: 579 580you can print a 0-terminated string (C-string) using the %s format, omitting 581square brackets, as in: 582 583:: 584 585 (lldb) type summary add --summary-string "${var%s}" "char *" 586 587This syntax works for char* as well as for char[] because LLDB can rely on the 588final \0 terminator to know when the string has ended. 589 590LLDB has default summary strings for char* and char[] that use this special 591case. On debugger startup, the following are defined automatically: 592 593:: 594 595 (lldb) type summary add --summary-string "${var%s}" "char *" 596 (lldb) type summary add --summary-string "${var%s}" -x "char \[[0-9]+]" 597 598any of the array formats (int8_t[], float32{}, ...), and the y, Y and a formats 599work to print an array of a non-aggregate type, even if square brackets are 600omitted. 601 602:: 603 604 (lldb) type summary add --summary-string "${var%int32_t[]}" "int [10]" 605 606This feature, however, is not enabled for pointers because there is no way for 607LLDB to detect the end of the pointed data. 608 609This also does not work for other formats (e.g. boolean), and you must specify 610the square brackets operator to get the expected output. 611 612Python Scripting 613---------------- 614 615Most of the times, summary strings prove good enough for the job of summarizing 616the contents of a variable. However, as soon as you need to do more than 617picking some values and rearranging them for display, summary strings stop 618being an effective tool. This is because summary strings lack the power to 619actually perform any kind of computation on the value of variables. 620 621To solve this issue, you can bind some Python scripting code as a summary for 622your datatype, and that script has the ability to both extract children 623variables as the summary strings do and to perform active computation on the 624extracted values. As a small example, let's say we have a Rectangle class: 625 626:: 627 628 629 class Rectangle 630 { 631 private: 632 int height; 633 int width; 634 public: 635 Rectangle() : height(3), width(5) {} 636 Rectangle(int H) : height(H), width(H*2-1) {} 637 Rectangle(int H, int W) : height(H), width(W) {} 638 int GetHeight() { return height; } 639 int GetWidth() { return width; } 640 }; 641 642Summary strings are effective to reduce the screen real estate used by the 643default viewing mode, but are not effective if we want to display the area and 644perimeter of Rectangle objects 645 646To obtain this, we can simply attach a small Python script to the Rectangle 647class, as shown in this example: 648 649:: 650 651 (lldb) type summary add -P Rectangle 652 Enter your Python command(s). Type 'DONE' to end. 653 def function (valobj,internal_dict): 654 height_val = valobj.GetChildMemberWithName('height') 655 width_val = valobj.GetChildMemberWithName('width') 656 height = height_val.GetValueAsUnsigned(0) 657 width = width_val.GetValueAsUnsigned(0) 658 area = height*width 659 perimeter = 2*(height + width) 660 return 'Area: ' + str(area) + ', Perimeter: ' + str(perimeter) 661 DONE 662 (lldb) frame variable 663 (Rectangle) r1 = Area: 20, Perimeter: 18 664 (Rectangle) r2 = Area: 72, Perimeter: 36 665 (Rectangle) r3 = Area: 16, Perimeter: 16 666 667In order to write effective summary scripts, you need to know the LLDB public 668API, which is the way Python code can access the LLDB object model. For further 669details on the API you should look at the LLDB API reference documentation. 670 671 672As a brief introduction, your script is encapsulated into a function that is 673passed two parameters: ``valobj`` and ``internal_dict``. 674 675``internal_dict`` is an internal support parameter used by LLDB and you should 676not touch it. 677 678``valobj`` is the object encapsulating the actual variable being displayed, and 679its type is SBValue. Out of the many possible operations on an SBValue, the 680basic one is retrieve the children objects it contains (essentially, the fields 681of the object wrapped by it), by calling ``GetChildMemberWithName()``, passing 682it the child's name as a string. 683 684If the variable has a value, you can ask for it, and return it as a string 685using ``GetValue()``, or as a signed/unsigned number using 686``GetValueAsSigned()``, ``GetValueAsUnsigned()``. It is also possible to 687retrieve an SBData object by calling ``GetData()`` and then read the object's 688contents out of the SBData. 689 690If you need to delve into several levels of hierarchy, as you can do with 691summary strings, you can use the method ``GetValueForExpressionPath()``, 692passing it an expression path just like those you could use for summary strings 693(one of the differences is that dereferencing a pointer does not occur by 694prefixing the path with a ``*```, but by calling the ``Dereference()`` method 695on the returned SBValue). If you need to access array slices, you cannot do 696that (yet) via this method call, and you must use ``GetChildAtIndex()`` 697querying it for the array items one by one. Also, handling custom formats is 698something you have to deal with on your own. 699 700Other than interactively typing a Python script there are two other ways for 701you to input a Python script as a summary: 702 703- using the --python-script option to type summary add and typing the script 704 code as an option argument; as in: 705 706:: 707 708 (lldb) type summary add --python-script "height = valobj.GetChildMemberWithName('height').GetValueAsUnsigned(0);width = valobj.GetChildMemberWithName('width').GetValueAsUnsigned(0); return 'Area: %d' % (height*width)" Rectangle 709 710 711- using the --python-function (-F) option to type summary add and giving the 712 name of a Python function with the correct prototype. Most probably, you will 713 define (or have already defined) the function in the interactive interpreter, 714 or somehow loaded it from a file, using the command script import command. 715 LLDB will emit a warning if it is unable to find the function you passed, but 716 will still register the binding. 717 718Starting in SVN r222593, Python summary formatters can optionally define a 719third argument: options 720 721This is an object of type ``lldb.SBTypeSummaryOptions`` that can be passed into 722the formatter, allowing for a few customizations of the result. The decision to 723adopt or not this third argument - and the meaning of options thereof - is 724within the individual formatters' writer. 725 726Regular Expression Typenames 727---------------------------- 728 729As you noticed, in order to associate the custom summary string to the array 730types, one must give the array size as part of the typename. This can long 731become tiresome when using arrays of different sizes, Simple [3], Simple [9], 732Simple [12], ... 733 734If you use the -x option, type names are treated as regular expressions instead 735of type names. This would let you rephrase the above example for arrays of type 736Simple [3] as: 737 738:: 739 (lldb) type summary add --summary-string "${var[].x}" -x "Simple \[[0-9]+\]" 740 (lldb) frame variable 741 (Simple [3]) sarray = [1,4,7] 742 (Simple [2]) sother = [3,6] 743 744The above scenario works for Simple [3] as well as for any other array of 745Simple objects. 746 747While this feature is mostly useful for arrays, you could also use regular 748expressions to catch other type sets grouped by name. However, as regular 749expression matching is slower than normal name matching, LLDB will first try to 750match by name in any way it can, and only when this fails, will it resort to 751regular expression matching. 752 753One of the ways LLDB uses this feature internally, is to match the names of STL 754container classes, regardless of the template arguments provided. The details 755for this are found at FormatManager.cpp 756 757The regular expression language used by LLDB is the POSIX extended language, as 758defined by the Single UNIX Specification, of which macOS is a compliant 759implementation. 760 761Names Summaries 762--------------- 763 764For a given type, there may be different meaningful summary representations. 765However, currently, only one summary can be associated to a type at each 766moment. If you need to temporarily override the association for a variable, 767without changing the summary string for to its type, you can use named 768summaries. 769 770Named summaries work by attaching a name to a summary when creating it. Then, 771when there is a need to attach the summary to a variable, the frame variable 772command, supports a --summary option that tells LLDB to use the named summary 773given instead of the default one. 774 775:: 776 777 (lldb) type summary add --summary-string "x=${var.integer}" --name NamedSummary 778 (lldb) frame variable one 779 (i_am_cool) one = int = 3, float = 3.14159, char = 69 780 (lldb) frame variable one --summary NamedSummary 781 (i_am_cool) one = x=3 782 783When defining a named summary, binding it to one or more types becomes 784optional. Even if you bind the named summary to a type, and later change the 785summary string for that type, the named summary will not be changed by that. 786You can delete named summaries by using the type summary delete command, as if 787the summary name was the datatype that the summary is applied to 788 789A summary attached to a variable using the --summary option, has the same 790semantics that a custom format attached using the -f option has: it stays 791attached till you attach a new one, or till you let your program run again. 792 793Synthetic Children 794------------------ 795 796Summaries work well when one is able to navigate through an expression path. In 797order for LLDB to do so, appropriate debugging information must be available. 798 799Some types are opaque, i.e. no knowledge of their internals is provided. When 800that's the case, expression paths do not work correctly. 801 802In other cases, the internals are available to use in expression paths, but 803they do not provide a user-friendly representation of the object's value. 804 805For instance, consider an STL vector, as implemented by the GNU C++ Library: 806 807:: 808 809 (lldb) frame variable numbers -T 810 (std::vector<int>) numbers = { 811 (std::_Vector_base<int, std::allocator<int> >) std::_Vector_base<int, std::allocator<int> > = { 812 (std::_Vector_base<int, std::allocator&tl;int> >::_Vector_impl) _M_impl = { 813 (int *) _M_start = 0x00000001001008a0 814 (int *) _M_finish = 0x00000001001008a8 815 (int *) _M_end_of_storage = 0x00000001001008a8 816 } 817 } 818 } 819 820Here, you can see how the type is implemented, and you can write a summary for 821that implementation but that is not going to help you infer what items are 822actually stored in the vector. 823 824What you would like to see is probably something like: 825 826:: 827 828 (lldb) frame variable numbers -T 829 (std::vector<int>) numbers = { 830 (int) [0] = 1 831 (int) [1] = 12 832 (int) [2] = 123 833 (int) [3] = 1234 834 } 835 836Synthetic children are a way to get that result. 837 838The feature is based upon the idea of providing a new set of children for a 839variable that replaces the ones available by default through the debug 840information. In the example, we can use synthetic children to provide the 841vector items as children for the std::vector object. 842 843In order to create synthetic children, you need to provide a Python class that 844adheres to a given interface (the word is italicized because Python has no 845explicit notion of interface, by that word we mean a given set of methods must 846be implemented by the Python class): 847 848:: 849 850 class SyntheticChildrenProvider: 851 def __init__(self, valobj, internal_dict): 852 this call should initialize the Python object using valobj as the variable to provide synthetic children for 853 def num_children(self): 854 this call should return the number of children that you want your object to have 855 def get_child_index(self,name): 856 this call should return the index of the synthetic child whose name is given as argument 857 def get_child_at_index(self,index): 858 this call should return a new LLDB SBValue object representing the child at the index given as argument 859 def update(self): 860 this call should be used to update the internal state of this Python object whenever the state of the variables in LLDB changes.[1] 861 def has_children(self): 862 this call should return True if this object might have children, and False if this object can be guaranteed not to have children.[2] 863 def get_value(self): 864 this call can return an SBValue to be presented as the value of the synthetic value under consideration.[3] 865 866[1] This method is optional. Also, it may optionally choose to return a value 867(starting with SVN rev153061/LLDB-134). If it returns a value, and that value 868is True, LLDB will be allowed to cache the children and the children count it 869previously obtained, and will not return to the provider class to ask. If 870nothing, None, or anything other than True is returned, LLDB will discard the 871cached information and ask. Regardless, whenever necessary LLDB will call 872update. 873 874[2] This method is optional (starting with SVN rev166495/LLDB-175). While 875implementing it in terms of num_children is acceptable, implementors are 876encouraged to look for optimized coding alternatives whenever reasonable. 877 878[3] This method is optional (starting with SVN revision 219330). The SBValue 879you return here will most likely be a numeric type (int, float, ...) as its 880value bytes will be used as-if they were the value of the root SBValue proper. 881As a shortcut for this, you can inherit from lldb.SBSyntheticValueProvider, and 882just define get_value as other methods are defaulted in the superclass as 883returning default no-children responses. 884 885If a synthetic child provider supplies a special child named $$dereference$$ 886then it will be used when evaluating opertaor* and operator-> in the frame 887variable command and related SB API functions. 888 889For examples of how synthetic children are created, you are encouraged to look 890at examples/synthetic in the LLDB trunk. Please, be aware that the code in 891those files (except bitfield/) is legacy code and is not maintained. You may 892especially want to begin looking at this example to get a feel for this 893feature, as it is a very easy and well commented example. 894 895The design pattern consistently used in synthetic providers shipping with LLDB 896is to use the __init__ to store the SBValue instance as a part of self. The 897update function is then used to perform the actual initialization. Once a 898synthetic children provider is written, one must load it into LLDB before it 899can be used. Currently, one can use the LLDB script command to type Python code 900interactively, or use the command script import fileName command to load Python 901code from a Python module (ordinary rules apply to importing modules this way). 902A third option is to type the code for the provider class interactively while 903adding it. 904 905For example, let's pretend we have a class Foo for which a synthetic children 906provider class Foo_Provider is available, in a Python module contained in file 907~/Foo_Tools.py. The following interaction sets Foo_Provider as a synthetic 908children provider in LLDB: 909 910:: 911 912 (lldb) command script import ~/Foo_Tools.py 913 (lldb) type synthetic add Foo --python-class Foo_Tools.Foo_Provider 914 (lldb) frame variable a_foo 915 (Foo) a_foo = { 916 x = 1 917 y = "Hello world" 918 } 919 920LLDB has synthetic children providers for a core subset of STL classes, both in 921the version provided by libstdcpp and by libcxx, as well as for several 922Foundation classes. 923 924Synthetic children extend summary strings by enabling a new special variable: 925``${svar``. 926 927This symbol tells LLDB to refer expression paths to the synthetic children 928instead of the real ones. For instance, 929 930:: 931 932 (lldb) type summary add --expand -x "std::vector<" --summary-string "${svar%#} items" 933 (lldb) frame variable numbers 934 (std::vector<int>) numbers = 4 items { 935 (int) [0] = 1 936 (int) [1] = 12 937 (int) [2] = 123 938 (int) [3] = 1234 939 } 940 941In some cases, if LLDB is unable to use the real object to get a child 942specified in an expression path, it will automatically refer to the synthetic 943children. While in summaries it is best to always use ${svar to make your 944intentions clearer, interactive debugging can benefit from this behavior, as 945in: 946 947:: 948 949 (lldb) frame variable numbers[0] numbers[1] 950 (int) numbers[0] = 1 951 (int) numbers[1] = 12 952 953Unlike many other visualization features, however, the access to synthetic 954children only works when using frame variable, and is not supported in 955expression: 956 957:: 958 959 (lldb) expression numbers[0] 960 Error [IRForTarget]: Call to a function '_ZNSt33vector<int, std::allocator<int> >ixEm' that is not present in the target 961 error: Couldn't convert the expression to DWARF 962 963The reason for this is that classes might have an overloaded operator [], or 964other special provisions and the expression command chooses to ignore synthetic 965children in the interest of equivalency with code you asked to have compiled 966from source. 967 968Filters 969------- 970 971Filters are a solution to the display of complex classes. At times, classes 972have many member variables but not all of these are actually necessary for the 973user to see. 974 975A filter will solve this issue by only letting the user see those member 976variables he cares about. Of course, the equivalent of a filter can be 977implemented easily using synthetic children, but a filter lets you get the job 978done without having to write Python code. 979 980For instance, if your class Foobar has member variables named A thru Z, but you 981only need to see the ones named B, H and Q, you can define a filter: 982 983:: 984 985 (lldb) type filter add Foobar --child B --child H --child Q 986 (lldb) frame variable a_foobar 987 (Foobar) a_foobar = { 988 (int) B = 1 989 (char) H = 'H' 990 (std::string) Q = "Hello world" 991 } 992 993Objective-C Dynamic Type Discovery 994---------------------------------- 995 996When doing Objective-C development, you may notice that some of your variables 997come out as of type id (for instance, items extracted from NSArray). By 998default, LLDB will not show you the real type of the object. it can actually 999dynamically discover the type of an Objective-C variable, much like the runtime 1000itself does when invoking a selector. In order to be shown the result of that 1001discovery that, however, a special option to frame variable or expression is 1002required: ``--dynamic-type``. 1003 1004 1005``--dynamic-type`` can have one of three values: 1006 1007- ``no-dynamic-values``: the default, prevents dynamic type discovery 1008- ``no-run-target``: enables dynamic type discovery as long as running code on 1009 the target is not required 1010- ``run-target``: enables code execution on the target in order to perform 1011 dynamic type discovery 1012 1013If you specify a value of either no-run-target or run-target, LLDB will detect 1014the dynamic type of your variables and show the appropriate formatters for 1015them. As an example: 1016 1017:: 1018 1019 (lldb) expr @"Hello" 1020 (NSString *) $0 = 0x00000001048000b0 @"Hello" 1021 (lldb) expr -d no-run @"Hello" 1022 (__NSCFString *) $1 = 0x00000001048000b0 @"Hello" 1023 1024Because LLDB uses a detection algorithm that does not need to invoke any 1025functions on the target process, no-run-target is enough for this to work. 1026 1027As a side note, the summary for NSString shown in the example is built right 1028into LLDB. It was initially implemented through Python (the code is still 1029available for reference at CFString.py). However, this is out of sync with the 1030current implementation of the NSString formatter (which is a C++ function 1031compiled into the LLDB core). 1032 1033Categories 1034---------- 1035 1036Categories are a way to group related formatters. For instance, LLDB itself 1037groups the formatters for the libstdc++ types in a category named 1038gnu-libstdc++. Basically, categories act like containers in which to store 1039formatters for a same library or OS release. 1040 1041By default, several categories are created in LLDB: 1042 1043- default: this is the category where every formatter ends up, unless another category is specified 1044- objc: formatters for basic and common Objective-C types that do not specifically depend on macOS 1045- gnu-libstdc++: formatters for std::string, std::vector, std::list and std::map as implemented by libstdcpp 1046- libcxx: formatters for std::string, std::vector, std::list and std::map as implemented by libcxx 1047- system: truly basic types for which a formatter is required 1048- AppKit: Cocoa classes 1049- CoreFoundation: CF classes 1050- CoreGraphics: CG classes 1051- CoreServices: CS classes 1052- VectorTypes: compact display for several vector types 1053 1054If you want to use a custom category for your formatters, all the type ... add 1055provide a --category (-w) option, that names the category to add the formatter 1056to. To delete the formatter, you then have to specify the correct category. 1057 1058Categories can be in one of two states: enabled and disabled. A category is 1059initially disabled, and can be enabled using the type category enable command. 1060To disable an enabled category, the command to use is type category disable. 1061 1062The order in which categories are enabled or disabled is significant, in that 1063LLDB uses that order when looking for formatters. Therefore, when you enable a 1064category, it becomes the second one to be searched (after default, which always 1065stays on top of the list). The default categories are enabled in such a way 1066that the search order is: 1067 1068- default 1069- objc 1070- CoreFoundation 1071- AppKit 1072- CoreServices 1073- CoreGraphics 1074- gnu-libstdc++ 1075- libcxx 1076- VectorTypes 1077- system 1078 1079As said, gnu-libstdc++ and libcxx contain formatters for C++ STL data types. 1080system contains formatters for char* and char[], which reflect the behavior of 1081older versions of LLDB which had built-in formatters for these types. Because 1082now these are formatters, you can even replace them with your own if so you 1083wish. 1084 1085There is no special command to create a category. When you place a formatter in 1086a category, if that category does not exist, it is automatically created. For 1087instance, 1088 1089:: 1090 1091 (lldb) type summary add Foobar --summary-string "a foobar" --category newcategory 1092 1093automatically creates a (disabled) category named newcategory. 1094 1095Another way to create a new (empty) category, is to enable it, as in: 1096 1097:: 1098 1099 (lldb) type category enable newcategory 1100 1101However, in this case LLDB warns you that enabling an empty category has no 1102effect. If you add formatters to the category after enabling it, they will be 1103honored. But an empty category per se does not change the way any type is 1104displayed. The reason the debugger warns you is that enabling an empty category 1105might be a typo, and you effectively wanted to enable a similarly-named but 1106not-empty category. 1107 1108Finding Formatters 101 1109---------------------- 1110 1111Searching for a formatter (including formats, starting in SVN rev r192217) 1112given a variable goes through a rather intricate set of rules. Namely, what 1113happens is that LLDB starts looking in each enabled category, according to the 1114order in which they were enabled (latest enabled first). In each category, LLDB 1115does the following: 1116 1117- If there is a formatter for the type of the variable, use it 1118- If this object is a pointer, and there is a formatter for the pointee type 1119 that does not skip pointers, use it 1120- If this object is a reference, and there is a formatter for the referred type 1121 that does not skip references, use it 1122- If this object is an Objective-C class and dynamic types are enabled, look 1123 for a formatter for the dynamic type of the object. If dynamic types are 1124 disabled, or the search failed, look for a formatter for the declared type of 1125 the object 1126- If this object's type is a typedef, go through typedef hierarchy (LLDB might 1127 not be able to do this if the compiler has not emitted enough information. If 1128 the required information to traverse typedef hierarchies is missing, type 1129 cascading will not work. The clang compiler, part of the LLVM project, emits 1130 the correct debugging information for LLDB to cascade). If at any level of 1131 the hierarchy there is a valid formatter that can cascade, use it. 1132- If everything has failed, repeat the above search, looking for regular 1133 expressions instead of exact matches 1134 1135If any of those attempts returned a valid formatter to be used, that one is 1136used, and the search is terminated (without going to look in other categories). 1137If nothing was found in the current category, the next enabled category is 1138scanned according to the same algorithm. If there are no more enabled 1139categories, the search has failed. 1140 1141**Warning**: previous versions of LLDB defined cascading to mean not only going 1142through typedef chains, but also through inheritance chains. This feature has 1143been removed since it significantly degrades performance. You need to set up 1144your formatters for every type in inheritance chains to which you want the 1145formatter to apply. 1146