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