xref: /xnu-11215.61.5/tools/lldbmacros/README.md (revision 4f1223e81cd707a65cc109d0b8ad6653699da3c4)
1*4f1223e8SApple OSS DistributionsTable of Contents
2*4f1223e8SApple OSS Distributions=================
3*4f1223e8SApple OSS Distributions
4*4f1223e8SApple OSS Distributions      A. How to use lldb for kernel debugging
5*4f1223e8SApple OSS Distributions      B. Design of lldb kernel debugging platform.
6*4f1223e8SApple OSS Distributions      C. Kernel debugging commands.
7*4f1223e8SApple OSS Distributions          i. Using commands.
8*4f1223e8SApple OSS Distributions         ii. Writing new commands.
9*4f1223e8SApple OSS Distributions      D. Kernel type summaries.
10*4f1223e8SApple OSS Distributions          i. Using summaries
11*4f1223e8SApple OSS Distributions         ii. Writing new summary functions
12*4f1223e8SApple OSS Distributions      E. FAQ and General Coding Guidelines
13*4f1223e8SApple OSS Distributions          i. Frequently Asked Questions
14*4f1223e8SApple OSS Distributions         ii. Formatted Output printing guidelines [MUST READ]
15*4f1223e8SApple OSS Distributions        iii. Coding conventions.  [MUST READ]
16*4f1223e8SApple OSS Distributions         iv. Submitting changes in lldbmacros [MUST READ]
17*4f1223e8SApple OSS Distributions          v. Common utility functions and paradigms
18*4f1223e8SApple OSS Distributions      F. Development and Debugging on lldb kernel debugging platform.
19*4f1223e8SApple OSS Distributions          i. Reading a exception backtrace
20*4f1223e8SApple OSS Distributions         ii. Loading custom or local lldbmacros and operating_system plugin
21*4f1223e8SApple OSS Distributions        iii. Adding debug related 'printf's
22*4f1223e8SApple OSS Distributions
23*4f1223e8SApple OSS DistributionsA. How to use lldb for kernel debugging
24*4f1223e8SApple OSS Distributions========================================
25*4f1223e8SApple OSS Distributions
26*4f1223e8SApple OSS Distributionslldb can be used for kernel debugging the same way as gdb. The simplest way is to start lldb with kernel symbol file. The lldb environment by default does not allow loading automatic python modules. Please add the following setting in
27*4f1223e8SApple OSS Distributions
28*4f1223e8SApple OSS Distributions    File: ~/.lldbinit
29*4f1223e8SApple OSS Distributions    settings set target.load-script-from-symbol-file true
30*4f1223e8SApple OSS Distributions
31*4f1223e8SApple OSS DistributionsNow lldb will be ready to connect over kdp-remote '\<hostname:port>' or 'gdb-remote \<hostname:port>'.
32*4f1223e8SApple OSS DistributionsIf you need to debug a core file, you can add '--core /path/to/corefile' to your lldb command (e.g. `xcrun --sdk macosx.internal lldb --core /path/to/corefile`)
33*4f1223e8SApple OSS Distributions
34*4f1223e8SApple OSS DistributionsFollowing are detailed steps on how to debug a panic'ed / NMI'ed machine (For the curious souls).
35*4f1223e8SApple OSS Distributions
36*4f1223e8SApple OSS Distributionslldb debugging in detail:-
37*4f1223e8SApple OSS Distributions
38*4f1223e8SApple OSS Distributions  * start lldb with the right symbols file. If you do not know the version apriori, then enable dsymForUUID to load symbols dynamically.
39*4f1223e8SApple OSS Distributions        bash$ dsymForUUID --enable
40*4f1223e8SApple OSS Distributions        bash$ lldb /path/to/mach_kernel.symbols
41*4f1223e8SApple OSS Distributions        Current executable set to '/Sources/Symbols/xnu/xnu-2253~2/mach_kernel' (x86_64).
42*4f1223e8SApple OSS Distributions        (lldb)
43*4f1223e8SApple OSS Distributions
44*4f1223e8SApple OSS Distributions  * connect to remote device or load a core file
45*4f1223e8SApple OSS Distributions        #for kdp
46*4f1223e8SApple OSS Distributions        (lldb) process connect --plugin kdp-remote udp://17.123.45.67:41139
47*4f1223e8SApple OSS Distributions        #for gdb (eg with astris)
48*4f1223e8SApple OSS Distributions        (lldb) process connect --plugin gdb-remote gdb://17.123.45.67:8000
49*4f1223e8SApple OSS Distributions        #for loading a core file
50*4f1223e8SApple OSS Distributions        (lldb) file --core /path/to/core/file  /path/to/kernel_symbol_file
51*4f1223e8SApple OSS Distributions
52*4f1223e8SApple OSS Distributions  * Once connected you can debug with basic lldb commands like print, bt, expr etc. The xnu debug macros will also be loaded automatically from the dSYM files.
53*4f1223e8SApple OSS Distributions  In case if you are working with older kernel files you can load kernel specific commands by doing -
54*4f1223e8SApple OSS Distributions        (lldb) command script import /path/to/xnu/tools/lldbmacros/xnu.py
55*4f1223e8SApple OSS Distributions        (lldb) showbootargs
56*4f1223e8SApple OSS Distributions        debug=0x14e ncpus=2
57*4f1223e8SApple OSS Distributions
58*4f1223e8SApple OSS Distributions  * You can do `kgmhelp` to get a list of commands available through xnu.py
59*4f1223e8SApple OSS Distributions
60*4f1223e8SApple OSS DistributionsSPECIAL: The `xnu.py` script brings in kernel type summary functions. To enable these please do -
61*4f1223e8SApple OSS Distributions
62*4f1223e8SApple OSS Distributions    (lldb) showlldbtypesummaries
63*4f1223e8SApple OSS Distributions
64*4f1223e8SApple OSS DistributionsThese could be very handy in printing important information from structures easily.
65*4f1223e8SApple OSS DistributionsFor ex.
66*4f1223e8SApple OSS Distributions
67*4f1223e8SApple OSS Distributions    (lldb) print (thread_t)0x80d6a620
68*4f1223e8SApple OSS Distributions    (thread_t) $45 = 0x80d6a620
69*4f1223e8SApple OSS Distributions    thread                   thread_id  processor            pri    io_policy  state wait_queue           wait_event           wmesg                thread_name
70*4f1223e8SApple OSS Distributions    0x80d6a620               0x317      0x902078c8           61                W     0x910cadd4           0x0                                       SystemSoundServer
71*4f1223e8SApple OSS Distributions
72*4f1223e8SApple OSS Distributions
73*4f1223e8SApple OSS Distributions
74*4f1223e8SApple OSS DistributionsB. Design of lldb kernel debugging platform.
75*4f1223e8SApple OSS Distributions=============================================
76*4f1223e8SApple OSS Distributions
77*4f1223e8SApple OSS DistributionsThe lldb debugger provides python scripting bridge for customizing commands and summaries in lldb. Following is the stack of platforms and how commands and summaries interact with it.
78*4f1223e8SApple OSS Distributions
79*4f1223e8SApple OSS Distributions    |------- xnu scripts ----------|
80*4f1223e8SApple OSS Distributions    | |- lldb Command/Scripting-|  |   <-- provides scriptability for kernel data structures through summary/command invocation.
81*4f1223e8SApple OSS Distributions    | |    |--lldb core--|      |  |   <-- interacts with remote kernel or corefile.
82*4f1223e8SApple OSS Distributions    | |-------------------------|  |
83*4f1223e8SApple OSS Distributions    |------------------------------|
84*4f1223e8SApple OSS Distributions
85*4f1223e8SApple OSS DistributionsThe xnu script in xnu/tools/lldbmacros provides the following:
86*4f1223e8SApple OSS Distributions
87*4f1223e8SApple OSS Distributions  * Custom functions to do plumbing of lldb command invocation to python function call. (see doc strings for @lldb_command)
88*4f1223e8SApple OSS Distributions    The command interface provides some common features (which can be invoked after passing '--' on cmd line) like -
89*4f1223e8SApple OSS Distributions
90*4f1223e8SApple OSS Distributions      i. send the output of command to file on disk
91*4f1223e8SApple OSS Distributions      ii. search for a string in the output and selectively print the line containing it.
92*4f1223e8SApple OSS Distributions      iii. -v options to increase verbosity levels in commands.
93*4f1223e8SApple OSS Distributions        For example: (lldb)showalltasks -- -s kernel_task --o /tmp/kernel_task.output -v
94*4f1223e8SApple OSS Distributions        will show task summary output with lines matching string 'kernel_task' into a file /tmp/kernel_task.output and with a verbosity level of (default +1)
95*4f1223e8SApple OSS Distributions
96*4f1223e8SApple OSS Distributions  * Customization for plugging in summary functions for lldb type summaries. (see doc strings for @lldb_summary)
97*4f1223e8SApple OSS Distributions     It will automatically register given types with the functions within the kernel category.
98*4f1223e8SApple OSS Distributions
99*4f1223e8SApple OSS Distributions  * Ability to register test cases for macros (see doc strings for @xnudebug_test).
100*4f1223e8SApple OSS Distributions
101*4f1223e8SApple OSS DistributionsThe file layout is as follows
102*4f1223e8SApple OSS Distributions
103*4f1223e8SApple OSS Distributions    xnu/
104*4f1223e8SApple OSS Distributions     |-tools/
105*4f1223e8SApple OSS Distributions       |-lldbmacros/
106*4f1223e8SApple OSS Distributions         |-core/       # Core logic about kernel, lldb value abstraction, configs etc. **DO NOT TOUCH THIS DIR**
107*4f1223e8SApple OSS Distributions         |-plugins/    # Holds plugins for kernel commands.
108*4f1223e8SApple OSS Distributions         |-xnu.py      # xnu debug framework along with kgmhelp, xnudebug commands.
109*4f1223e8SApple OSS Distributions         |-xnudefines.py
110*4f1223e8SApple OSS Distributions         |-utils.py
111*4f1223e8SApple OSS Distributions         |-process.py  # files containing commands/summaries code for each subsystem
112*4f1223e8SApple OSS Distributions         |-memory.py
113*4f1223e8SApple OSS Distributions         |-...
114*4f1223e8SApple OSS Distributions       |-tests/
115*4f1223e8SApple OSS Distributions         |-lldb_tests/          # unit tests for macros, using lldb scripted process to simulate debugging a core file
116*4f1223e8SApple OSS Distributions         |-standalone_tests/    # standalone tests for functionality that's seperate from lldb/macros (but used by them)
117*4f1223e8SApple OSS Distributions
118*4f1223e8SApple OSS Distributions
119*4f1223e8SApple OSS DistributionsThe lldbmacros directory has a Makefile that follows the build process for xnu. This packages lldbmacros scripts into the dSYM of each kernel build. This helps in rev-locking the lldb commands with changes in kernel sources.
120*4f1223e8SApple OSS Distributions
121*4f1223e8SApple OSS Distributions
122*4f1223e8SApple OSS DistributionsC. Kernel debugging commands.
123*4f1223e8SApple OSS Distributions==============================
124*4f1223e8SApple OSS Distributionsi. Using commands.
125*4f1223e8SApple OSS Distributions------------------
126*4f1223e8SApple OSS DistributionsUsing xnu debug commands is very similar to kgmacros in gdb. You can use 'kgmhelp' to get a listing of available commands.
127*4f1223e8SApple OSS DistributionsIf you need detailed help for a command please type 'help <command name>' and the documentation for the command will be displayed.
128*4f1223e8SApple OSS DistributionsFor ex.
129*4f1223e8SApple OSS Distributions
130*4f1223e8SApple OSS Distributions    (lldb) help pmap_walk
131*4f1223e8SApple OSS Distributions    Perform a page-table walk in <pmap> for <virtual_address>.
132*4f1223e8SApple OSS Distributions         You can pass -- -v for verbose output. To increase the verbosity add more -v args after the '--'.
133*4f1223e8SApple OSS Distributions    Syntax: pmap_walk <pmap> <virtual_address>
134*4f1223e8SApple OSS Distributions
135*4f1223e8SApple OSS DistributionsThe basic format for every command provided under kgmhelp is like follows
136*4f1223e8SApple OSS Distributions
137*4f1223e8SApple OSS Distributions    (lldb) command_name [cmd_args..] [-CMDOPTIONS] [-xnuoptions]
138*4f1223e8SApple OSS Distributions    where:
139*4f1223e8SApple OSS Distributions      command_name : name of command as registed using the @lldb_command decorator and described in 'kgmhelp'
140*4f1223e8SApple OSS Distributions      cmd_args     : shell like arguments that are passed as is to the registered python function.
141*4f1223e8SApple OSS Distributions                     If there is error in these arguments than the implementor may display according error message.
142*4f1223e8SApple OSS Distributions      xnuoptions   : common options for stream based operations on the output of command_name.
143*4f1223e8SApple OSS Distributions                     Allowed options are
144*4f1223e8SApple OSS Distributions                     -h          : show help string of a command
145*4f1223e8SApple OSS Distributions                     -s <regexp> : print only the lines matching <regexp>
146*4f1223e8SApple OSS Distributions                     -o <file>   : direct the output of command to <file>. Will not display anything on terminal
147*4f1223e8SApple OSS Distributions                     -v          : increase the verbosity of the command. Each '-v' encountered will increase verbosity by 1.
148*4f1223e8SApple OSS Distributions                     -p <plugin> : pass the output of command to <plugin> for processing and followup with command requests by it.
149*4f1223e8SApple OSS Distributions      CMDOPTIONS   : These are command level options (always a CAPITAL letter option) that are defined by the macro developer. Please do
150*4f1223e8SApple OSS Distributions                     help <cmdname> to know how each option operates on that particular command. For an example of how to use CMDOPTIONS, take a look at vm_object_walk_pages in memory.py
151*4f1223e8SApple OSS Distributions
152*4f1223e8SApple OSS Distributionsii. Writing new commands.
153*4f1223e8SApple OSS Distributions--------------------------
154*4f1223e8SApple OSS DistributionsThe python modules are designed in such a way that the command from lldb invokes a python function with the arguments passed at lldb prompt.
155*4f1223e8SApple OSS Distributions
156*4f1223e8SApple OSS DistributionsIt is recommended that you do a decoupled development for command interface and core utility function so that any function/code can be called as a simple util function and get the same output. i.e.
157*4f1223e8SApple OSS Distributions
158*4f1223e8SApple OSS Distributions    (lldb)showtask 0xabcdef000 is same as python >>> GetTaskSummary(0xabcdef000) or equivalent
159*4f1223e8SApple OSS Distributions
160*4f1223e8SApple OSS DistributionsFollowing is a step by step guideline on how to add a new command ( e.g showtaskvme ). [extra tip: Always good idea to wrap your macro code within # Macro: , # EndMacro.]
161*4f1223e8SApple OSS Distributions
162*4f1223e8SApple OSS Distributions  1. register a command to a function. Use the lldb_command decorator to map a 'command_name' to a function. Optionally you can provide getopt compatible option string for customizing your command invocation. Note: Only CAPITAL letter options are allowed. lowercase options are reserved for the framework level features.
163*4f1223e8SApple OSS Distributions
164*4f1223e8SApple OSS Distributions  2. Immediately after the register define the function to handle the command invocation. The signature is always like Abc(cmd_args=None, cmd_options={})
165*4f1223e8SApple OSS Distributions
166*4f1223e8SApple OSS Distributions  3. Add documentation for Abc(). This is very important for lldb to show help for each command. [ Follow the guidelines above with documentation ]
167*4f1223e8SApple OSS Distributions
168*4f1223e8SApple OSS Distributions  4. Use cmd_args array to get args passed on command. For example a command like `showtaskvme 0xabcdef00` will put have cmd_args=['0xabcdef00']
169*4f1223e8SApple OSS Distributions      - note that we use core.value class as an interface to underlying C structures. Refer [Section B] for more details.
170*4f1223e8SApple OSS Distributions      - use kern.globals.\<variable_name> & kern.GetValueFromAddress for building values from addresses.
171*4f1223e8SApple OSS Distributions      - remember that the ideal type of object to be passed around is core.value
172*4f1223e8SApple OSS Distributions      - Anything you 'print' will be relayed to lldb terminal output.
173*4f1223e8SApple OSS Distributions
174*4f1223e8SApple OSS Distributions  5. If the user has passed any custom options they would be in cmd_options dict. the format is `{'-<optionflag>':'<value>'}`. The \<value> will be '' (empty string) for non-option flags.
175*4f1223e8SApple OSS Distributions
176*4f1223e8SApple OSS Distributions  6. If your function finds issue with the passed argument then you can `raise ArgumentError('error_message')` to notify the user. The framework will automatically catch this and show appropriate help using the function doc string.
177*4f1223e8SApple OSS Distributions
178*4f1223e8SApple OSS Distributions  7. Please use "##" for commenting your code. This is important because single "#" based strings may be mistakenly considered in `unifdef` program.
179*4f1223e8SApple OSS Distributions
180*4f1223e8SApple OSS Distributions Time for some code example? Try reading the code for function ShowTaskVmeHelper in memory.py.
181*4f1223e8SApple OSS Distributions
182*4f1223e8SApple OSS DistributionsSPECIAL Note: Very often you will find yourself making changes to a file for some command/summary and would like to test it out in lldb.
183*4f1223e8SApple OSS Distributions
184*4f1223e8SApple OSS DistributionsTo easily reload your changes in lldb please follow the below example.
185*4f1223e8SApple OSS Distributions
186*4f1223e8SApple OSS Distributions  * you fire up lldb and start using zprint. And soon you need to add functionality to zprint.
187*4f1223e8SApple OSS Distributions
188*4f1223e8SApple OSS Distributions  * you happily change a function code in memory.py file to zprint macro.
189*4f1223e8SApple OSS Distributions
190*4f1223e8SApple OSS Distributions  * now to reload that particular changes without killing your debug session do
191*4f1223e8SApple OSS Distributions        (lldb) xnudebug reload memory
192*4f1223e8SApple OSS Distributions         memory is reloaded from ./memory.py
193*4f1223e8SApple OSS Distributions        (lldb)
194*4f1223e8SApple OSS Distributions
195*4f1223e8SApple OSS Distributions  * Alternatively, you can use lldb`s command for script loading as
196*4f1223e8SApple OSS Distributions        (lldb) command script import /path/to/memory.py
197*4f1223e8SApple OSS Distributions    You can re-run the same command every time you update the code in file.
198*4f1223e8SApple OSS Distributions
199*4f1223e8SApple OSS Distributions It is very important that you do reload using xnudebug command as it does the plumbing of commands and types for your change in the module. Otherwise you could easily get confused
200*4f1223e8SApple OSS Distributions why your changes are not reflected in the command.
201*4f1223e8SApple OSS Distributions
202*4f1223e8SApple OSS Distributions
203*4f1223e8SApple OSS DistributionsD. Kernel type summaries.
204*4f1223e8SApple OSS Distributions==========================
205*4f1223e8SApple OSS Distributionsi. Using summaries
206*4f1223e8SApple OSS Distributions------------------
207*4f1223e8SApple OSS DistributionsThe lldb debugger provides ways for user to customize how a particular type of object be described when printed. These are very useful in displaying complex and large structures
208*4f1223e8SApple OSS Distributionswhere only certain fields are important based on some flag or value in some field or variable. The way it works is every time lldb wants to print an object it checks
209*4f1223e8SApple OSS Distributionsfor registered summaries. We can define python functions and hook it up with lldb as callbacks for type summaries.  For example.
210*4f1223e8SApple OSS Distributions
211*4f1223e8SApple OSS Distributions    (lldb) print first_zone
212*4f1223e8SApple OSS Distributions    (zone_t) $49 = 0xd007c000
213*4f1223e8SApple OSS Distributions          ZONE            TOT_SZ ALLOC_ELTS  FREE_ELTS    FREE_SZ ELT_SZ  ALLOC(ELTS  PGS  SLK)     FLAGS      NAME
214*4f1223e8SApple OSS Distributions    0x00000000d007c000      29808        182         25       3600    144   4096   28    1   64   X$          zones
215*4f1223e8SApple OSS Distributions    (lldb)
216*4f1223e8SApple OSS DistributionsJust printing the value of first_zone as (zone_t) 0xd007c000 wouldnt have been much help. But with the registered summary for zone_t we can see all the interesting info easily.
217*4f1223e8SApple OSS Distributions
218*4f1223e8SApple OSS DistributionsYou do not need to do anything special to use summaries. Once they are registered with lldb they show info automatically when printing objects. However if you wish to
219*4f1223e8SApple OSS Distributionssee all the registered type summaries run the command `type summary list -w kernel` on lldb prompt.
220*4f1223e8SApple OSS DistributionsAlso if you wish to quickly disable the summaries for a particular command use the `showraw` command.
221*4f1223e8SApple OSS Distributions
222*4f1223e8SApple OSS Distributionsii. Writing new summary functions
223*4f1223e8SApple OSS Distributions---------------------------------
224*4f1223e8SApple OSS Distributionslldb provides really flexible interface for building summaries for complex objects and data. If you find that a struct or list can be
225*4f1223e8SApple OSS Distributionsdiagnosed better if displayed differently, then feel free to add a type summary for that type. Following is an easy guide on how to do that.
226*4f1223e8SApple OSS Distributions
227*4f1223e8SApple OSS Distributions  1. Register a function as a callback for displaying information for a type. Use the `@lldb_type_summary()` decorator with an array of types you wish to register for callback
228*4f1223e8SApple OSS Distributions
229*4f1223e8SApple OSS Distributions  2. Provide a header for the summary using `@header()` decorator. This is a strong requirement for summaries. This gets displayed before the output
230*4f1223e8SApple OSS Distributions     of `GetTypeSummary()` is displayed. [In case you do not wish to have header then still define it as "" (empty string) ]
231*4f1223e8SApple OSS Distributions
232*4f1223e8SApple OSS Distributions  3. Define the function with signature of `GetSomeTypeSummary(valobj)`. It is highly recommended that the naming be consistent to `Get.*?Summary(valobj)`
233*4f1223e8SApple OSS Distributions     The valobj argument holds the core.value object for display.
234*4f1223e8SApple OSS Distributions
235*4f1223e8SApple OSS Distributions  4. Use the utility functions and memory read operations to pull out the required information.
236*4f1223e8SApple OSS Distributions     [ use `kern.globals` & `kern.GetValueFromAddress` for building args to core functions. ]
237*4f1223e8SApple OSS Distributions     [ remember that the ideal type of object to be passed around is core.value ]
238*4f1223e8SApple OSS Distributions
239*4f1223e8SApple OSS Distributions  5. return a string that would be printed by the caller. When lldb makes a call back it expects a str to be returned. So do not print
240*4f1223e8SApple OSS Distributions     directly out to console. [ debug info or logs output is okay to be printed anywhere :) ]
241*4f1223e8SApple OSS Distributions
242*4f1223e8SApple OSS DistributionsTime for some code example? Try reading the code for GetTaskSummary() in process.py.
243*4f1223e8SApple OSS Distributions
244*4f1223e8SApple OSS Distributions
245*4f1223e8SApple OSS Distributions
246*4f1223e8SApple OSS DistributionsE. FAQs and Generel Coding Guidelines
247*4f1223e8SApple OSS Distributions======================================
248*4f1223e8SApple OSS Distributions
249*4f1223e8SApple OSS Distributionsi. Frequently Asked Questions
250*4f1223e8SApple OSS Distributions-----------------------------
251*4f1223e8SApple OSS Distributions
252*4f1223e8SApple OSS Distributions  Q. How do I avoid printing the summary and see the actual data in a structure?
253*4f1223e8SApple OSS Distributions
254*4f1223e8SApple OSS Distributions  A. There is a command called `showraw`. This will disable all kernel specific type summaries and execute any command you provide. For ex.
255*4f1223e8SApple OSS Distributions
256*4f1223e8SApple OSS Distributions    (lldb) print (thread_t) 0x80d6a620
257*4f1223e8SApple OSS Distributions    (thread_t) $45 = 0x80d6a620
258*4f1223e8SApple OSS Distributions    thread                   thread_id  processor            pri    io_policy  state wait_queue           wait_event           wmesg                thread_name
259*4f1223e8SApple OSS Distributions    0x80d6a620               0x317      0x902078c8           61                W     0x910cadd4           0x0                                       SystemSoundServer
260*4f1223e8SApple OSS Distributions    (lldb) showraw print (thread_t) 0x80d6a620
261*4f1223e8SApple OSS Distributions    (thread_t) $48 = 0x80d6a620
262*4f1223e8SApple OSS Distributions
263*4f1223e8SApple OSS Distributions  Q. I typed `showallvnodes` and nothing happens for a long time? OR How do I get output of long running command instantly on the terminal?
264*4f1223e8SApple OSS Distributions
265*4f1223e8SApple OSS Distributions  A. The lldb command interface tries to build result object from output of a python function. So in case of functions with very long output or runtime it may
266*4f1223e8SApple OSS Distributions     seem that the lldb process is hung. But it is not. You can use "-i" option to get immediate output on terminal.
267*4f1223e8SApple OSS Distributions
268*4f1223e8SApple OSS Distributions        ex. (lldb) showallvnodes -- -i
269*4f1223e8SApple OSS Distributions         Immediate Output
270*4f1223e8SApple OSS Distributions         ....
271*4f1223e8SApple OSS Distributions
272*4f1223e8SApple OSS Distributions  Q. I made a change in a python file for a command or summary, but the output is not reflected in the lldb command?
273*4f1223e8SApple OSS Distributions
274*4f1223e8SApple OSS Distributions  A. The python framework does not allow for removing a loaded module and then reloading it. So sometimes if a command has a cached value from
275*4f1223e8SApple OSS Distributions     old code that it will still call the old function and hence will not display new changes in file on disk. If you find yourself in such a situation
276*4f1223e8SApple OSS Distributions     please see [Section C. -> SPECIAL Note]. If the change is to basic class or caching mechanism than it is advised to quit lldb and re-load all modules again.
277*4f1223e8SApple OSS Distributions
278*4f1223e8SApple OSS Distributions  Q. I am new to python. I get an error message that I do not understand. what should I do?
279*4f1223e8SApple OSS Distributions
280*4f1223e8SApple OSS Distributions  A. The syntax for python is different from conventional programming languages. If you get any message with SyntaxError or TypeError or ValueError then please review your code and look for common errors like
281*4f1223e8SApple OSS Distributions
282*4f1223e8SApple OSS Distributions  - wrong level of indentation?
283*4f1223e8SApple OSS Distributions  - missed a ':' at the end of an if, elif, for, while statement?
284*4f1223e8SApple OSS Distributions  - referencing a key in dictionary that doesn't exist? You might see KeyError in such cases.
285*4f1223e8SApple OSS Distributions  - mistakenly used python reserved keyword as variable? (check http://docs.python.org/release/3.0.1/reference/lexical_analysis.html#id8)
286*4f1223e8SApple OSS Distributions  - Trying to modify a string value? You can only create new strings but never modify existing ones.
287*4f1223e8SApple OSS Distributions  - Trying to add a non string value to a string? This typically happens in print "time is " + gettime(). here gettime() returns int and not str.
288*4f1223e8SApple OSS Distributions  - using a local variable with same name as global variable?
289*4f1223e8SApple OSS Distributions  - assigning a value to global variable without declaring first? Its highly recommended to always declare global variable with 'global' keyword
290*4f1223e8SApple OSS Distributions  If you still have difficulty you can look at the python documentation at http://docs.python.org
291*4f1223e8SApple OSS Distributions
292*4f1223e8SApple OSS Distributions
293*4f1223e8SApple OSS Distributions  Q. I wish to pass value of variable/expression to xnu lldb macro that accepts only pointers. How can I achieve that?
294*4f1223e8SApple OSS Distributions
295*4f1223e8SApple OSS Distributions  A. Many lldb macros have syntax that accepts pointers (eg showtaskstacks etc). In order to have your expression be evaluated before passing to command use `back ticks`. For example:
296*4f1223e8SApple OSS Distributions
297*4f1223e8SApple OSS Distributions        (lldb) showtaskstacks  `(task_t)tasks.next`
298*4f1223e8SApple OSS Distributions        This way the expressing withing ` ` is evaluated by lldb and the value is passed to the command.
299*4f1223e8SApple OSS Distributions        Note that if your argument pointer is bad or the memory is corrupted lldb macros will fail with a long backtrace that may not make sense. gdb used to fail silently but lldb does not.
300*4f1223e8SApple OSS Distributions        Please see Section F(i) for more information on reading backtraces.
301*4f1223e8SApple OSS Distributions
302*4f1223e8SApple OSS Distributions  Q. I connected to a coredump file with lldb --core corefile and I got RuntimeError: Unable to find lldb thread for tid=XYZ. What should I do?
303*4f1223e8SApple OSS Distributions
304*4f1223e8SApple OSS Distributions  A. This is most likely the case that lldb ignored the operating system plugin in the dSYM and hence threads are not populated. Please put the line 'settings set target.load-script-from-symbol-file true' in your ~/.lldbinit file. If you do not have access you can alternatively do
305*4f1223e8SApple OSS Distributions
306*4f1223e8SApple OSS Distributions        bash# lldb
307*4f1223e8SApple OSS Distributions        (lldb) settings set target.load-script-from-symbol-file true
308*4f1223e8SApple OSS Distributions        (lldb) file --core corefile
309*4f1223e8SApple OSS Distributions
310*4f1223e8SApple OSS Distributions
311*4f1223e8SApple OSS Distributionsii. Formatted output printing - zen and peace for life
312*4f1223e8SApple OSS Distributions------------------------------------------------------
313*4f1223e8SApple OSS Distributions
314*4f1223e8SApple OSS DistributionsTo avoid the horrors of printing a tabular data on console and then 2 weeks later again messing with it for a new field, it is recommended to follow these guidelines.
315*4f1223e8SApple OSS Distributions
316*4f1223e8SApple OSS Distributions  * any python string can be invoked to "".format() and hence makes it very easy to play with formats
317*4f1223e8SApple OSS Distributions
318*4f1223e8SApple OSS Distributions  * As a convention, I suggest that for printing pointer values in hex use "{0: <#020x}".format(some_int_value). This will print nice 0x prefixed strings with length padded to 20.
319*4f1223e8SApple OSS Distributions
320*4f1223e8SApple OSS Distributions  * If you need help with format options take a look at http://docs.python.org/library/string.html#format-string-syntax
321*4f1223e8SApple OSS Distributions
322*4f1223e8SApple OSS Distributions  * [ I'd first create a format string for data and then for the header just change the x's and d's to s and pass the header strings to format command. see GetTaskSummary()]
323*4f1223e8SApple OSS Distributions
324*4f1223e8SApple OSS Distributions  * If you need to print a string from a core.value object then use str() to get string representation of value.
325*4f1223e8SApple OSS Distributions
326*4f1223e8SApple OSS Distributions
327*4f1223e8SApple OSS Distributionsiii. Coding conventions
328*4f1223e8SApple OSS Distributions-----------------------
329*4f1223e8SApple OSS DistributionsIt is very very HIGHLY RECOMMENDED to follow these guidelines for writing any python code.
330*4f1223e8SApple OSS Distributions
331*4f1223e8SApple OSS Distributions * Python is very sensitive to tabs and spaces for alignment. So please make sure you **INDENT YOUR CODE WITH SPACES** at all times.
332*4f1223e8SApple OSS Distributions
333*4f1223e8SApple OSS Distributions * The standard tab width is 4 spaces. Each increasing indent adds 4 spaces beginning of the line.
334*4f1223e8SApple OSS Distributions
335*4f1223e8SApple OSS Distributions * The format for documentation is -
336*4f1223e8SApple OSS Distributions        """ A one line summary describing what this function / class does
337*4f1223e8SApple OSS Distributions            Detailed explanation if necessary along with params and return values.
338*4f1223e8SApple OSS Distributions        """
339*4f1223e8SApple OSS Distributions
340*4f1223e8SApple OSS Distributions * All Classes and functions should have a doc string describing what the function does
341*4f1223e8SApple OSS Distributions   A consistent format is expected. For ex.
342*4f1223e8SApple OSS Distributions    def SumOfNumbers(a, b, c, d):
343*4f1223e8SApple OSS Distributions        """ Calculate sum of numbers.
344*4f1223e8SApple OSS Distributions            params:
345*4f1223e8SApple OSS Distributions                a - int, value to be added. can be 0
346*4f1223e8SApple OSS Distributions                b - int/float, value to be added.
347*4f1223e8SApple OSS Distributions            returns:
348*4f1223e8SApple OSS Distributions                int/float - Sum of two values
349*4f1223e8SApple OSS Distributions            raises:
350*4f1223e8SApple OSS Distributions                TypeError - If any type is not identified in the params
351*4f1223e8SApple OSS Distributions        """
352*4f1223e8SApple OSS Distributions
353*4f1223e8SApple OSS Distributions * A Class or Function should always start with CAPITAL letter and be CamelCase. If a function is for internal use only than it starts with '_'.
354*4f1223e8SApple OSS Distributions
355*4f1223e8SApple OSS Distributions * Function params should always be lower_case and be word separated with '_'
356*4f1223e8SApple OSS Distributions
357*4f1223e8SApple OSS Distributions * A local variable inside a function should be lower_case and separated with '_'
358*4f1223e8SApple OSS Distributions
359*4f1223e8SApple OSS Distributions * A variable for internal use in object should start with '_'.
360*4f1223e8SApple OSS Distributions
361*4f1223e8SApple OSS Distributions * if a class variable is supposed to hold non native type of object, it is good idea to comment what type it holds
362*4f1223e8SApple OSS Distributions
363*4f1223e8SApple OSS Distributions * A class function with name matching `Get(.*?)Summary()` is always supposed to return a string which can be printed on stdout or any file.
364*4f1223e8SApple OSS Distributions
365*4f1223e8SApple OSS Distributions * Functions beginning with "Get" (eg. GetVnodePath())  mean they return a value and will not print any output to stdout.
366*4f1223e8SApple OSS Distributions
367*4f1223e8SApple OSS Distributions * Functions beginning with "Show"  (eg. ShowZTrace()) mean they will print data on screen and may not return any value.
368*4f1223e8SApple OSS Distributions
369*4f1223e8SApple OSS Distributions
370*4f1223e8SApple OSS Distributionsiv. Submitting changes in lldbmacros
371*4f1223e8SApple OSS Distributions------------------------------------
372*4f1223e8SApple OSS Distributions
373*4f1223e8SApple OSS DistributionsTo contribute new commands or fixes to existing one, it is recommended that you follow the procedure below.
374*4f1223e8SApple OSS Distributions
375*4f1223e8SApple OSS Distributions  * Save the changes requried for new command or fix into lldbmacros directory.
376*4f1223e8SApple OSS Distributions
377*4f1223e8SApple OSS Distributions  * Make sure that the coding conventions are strictly followed.
378*4f1223e8SApple OSS Distributions
379*4f1223e8SApple OSS Distributions  * Run syntax checker on each of the modified files. It will find basic formatting errors in the changed files for you.
380*4f1223e8SApple OSS Distributions
381*4f1223e8SApple OSS Distributions  * If you are adding new file then please update the Makefile and xnu.py imports to ensure they get compiled during kernel build.
382*4f1223e8SApple OSS Distributions
383*4f1223e8SApple OSS Distributions  * Do a clean build of kernel from xnu top level directory.
384*4f1223e8SApple OSS Distributions
385*4f1223e8SApple OSS Distributions  * Verify that your changes are present in the dSYM directory of new build.
386*4f1223e8SApple OSS Distributions
387*4f1223e8SApple OSS Distributions  * Re-run all your test and verification steps with the lldbmacros from the newly packaged dSYM/Contents/Resources/Python/lldbmacros.
388*4f1223e8SApple OSS Distributions
389*4f1223e8SApple OSS Distributionsv. Common utility functions and paradigms
390*4f1223e8SApple OSS Distributions-----------------------------------------
391*4f1223e8SApple OSS DistributionsPlease search and look around the code for common util functions and paradigm
392*4f1223e8SApple OSS Distributions
393*4f1223e8SApple OSS Distributions  * Take a peek at utils.py for common utility like sizeof_fmt() to humanize size strings in KB, MB etc. The convention is to have functions that do self contained actions and does not require intricate knowledge of kernel structures in utils.py
394*4f1223e8SApple OSS Distributions
395*4f1223e8SApple OSS Distributions  * If you need to get pagesize of the traget system, do not hard code any value. kern.globals.page_size is your friend. Similarly use config['verbosity'] for finding about configs.
396*4f1223e8SApple OSS Distributions
397*4f1223e8SApple OSS Distributions  * If you are developing a command for structure that is different based on development/release kernels please use "hasattr()" functionality to conditionalize referencing #ifdef'ed fields in structure. See example in def GetTaskSummary(task) in process.py
398*4f1223e8SApple OSS Distributions
399*4f1223e8SApple OSS Distributions  * `ArgumentStringToInt()` is recommended for argument parsing, as it supports binary/octal/decimal/hexadecimal literal
400*4f1223e8SApple OSS Distributions    representations, as well as lldb expressions, which allows for convenient for usage e.g. `showmapvme foo_map_ptr`
401*4f1223e8SApple OSS Distributions
402*4f1223e8SApple OSS Distributions
403*4f1223e8SApple OSS DistributionsF. Development and Debugging on lldb kernel debugging platform.
404*4f1223e8SApple OSS Distributions===============================================================
405*4f1223e8SApple OSS Distributions
406*4f1223e8SApple OSS Distributionsi. Reading a exception backtrace
407*4f1223e8SApple OSS Distributions--------------------------------
408*4f1223e8SApple OSS DistributionsIn case of an error the lldbmacros may print out an exception backtrace and halt immediately. The important thing is to
409*4f1223e8SApple OSS Distributionsisolate possible causes of failure, and eventually filing a bug with kernel team. Following are some common ways where
410*4f1223e8SApple OSS Distributionsyou may see an exception instead of your expected result.
411*4f1223e8SApple OSS Distributions
412*4f1223e8SApple OSS Distributions  * The lldbmacros cannot divine the type of memory by inspection. If a wrong pointer is passed from commandline then,
413*4f1223e8SApple OSS Distributions    the command code will try to read and show some results. It may still be junk or plain erronous. Please make sure
414*4f1223e8SApple OSS Distributions	your command arguments are correct. For example: a common mistake is to pass task address to showactstack. In such
415*4f1223e8SApple OSS Distributions	a case lldb command may fail and show you a confusing backtrace.
416*4f1223e8SApple OSS Distributions
417*4f1223e8SApple OSS Distributions  * Kernel debugging is particularly tricky. Many parts of memory may not be readable. There could be failure in network,
418*4f1223e8SApple OSS Distributions    debugging protocol or just plain bad memory. In such a case please try to see if you can examine memory for the object
419*4f1223e8SApple OSS Distributions	you are trying to access.
420*4f1223e8SApple OSS Distributions
421*4f1223e8SApple OSS Distributions  * In case of memory corruption, the lldbmacros may have followed wrong pointer dereferencing. This might lead to failure
422*4f1223e8SApple OSS Distributions    and a exception to be thrown.
423*4f1223e8SApple OSS Distributions
424*4f1223e8SApple OSS DistributionsThere are few more options that you can use when a macro is raising exceptions:
425*4f1223e8SApple OSS Distributions
426*4f1223e8SApple OSS Distributions  * Add --debug to your macro invocation to provide more detailed/verbose exception output.
427*4f1223e8SApple OSS Distributions  * Add --radar to generate tar.gz archive when filling a new radar for kernel team.
428*4f1223e8SApple OSS Distributions  * Add --pdb to attach pdb to exception stack for debugging.
429*4f1223e8SApple OSS Distributions
430*4f1223e8SApple OSS Distributionsii. Loading custom or local lldbmacros and operating_system plugin
431*4f1223e8SApple OSS Distributions------------------------------------------------------------------
432*4f1223e8SApple OSS Distributions
433*4f1223e8SApple OSS DistributionsThe lldbmacros are packaged right into the dSYM for the kernel executable. This makes debugging very easy since they can get loaded automatically when symbols are loaded.
434*4f1223e8SApple OSS DistributionsHowever, this setup makes it difficult for a lldbmacro developer to load custom/local macros. Following is the suggested solution for customizing your debugging setup:
435*4f1223e8SApple OSS Distributions
436*4f1223e8SApple OSS Distributions  * set up environment variable DEBUG_XNU_LLDBMACROS=1 on your shell. This will disable the automatic setup of lldbmacros and the operating_system.py from the symbols.
437*4f1223e8SApple OSS Distributions     - bash$ export DEBUG_XNU_LLDBMACROS=1
438*4f1223e8SApple OSS Distributions
439*4f1223e8SApple OSS Distributions  * start lldb from the shell
440*4f1223e8SApple OSS Distributions     - bash$ lldb
441*4f1223e8SApple OSS Distributions
442*4f1223e8SApple OSS Distributions  * [optional] If you are making changes in the operating_system plugin then you need to set the plugin path for lldb to find your custom operating_system plugin file.
443*4f1223e8SApple OSS Distributions     - (lldb)settings set target.process.python-os-plugin-path /path/to/xnu/tools/lldbmacros/core/operating_system.py
444*4f1223e8SApple OSS Distributions     If you do not wish to change anything in operating_system plugin then just leave the setting empty. The symbol loading module will set one up for you.
445*4f1223e8SApple OSS Distributions
446*4f1223e8SApple OSS Distributions  * Load the xnu debug macros from your custom location.
447*4f1223e8SApple OSS Distributions     - (lldb)command script import /path/to/xnu/tools/lldbmacros/xnu.py
448*4f1223e8SApple OSS Distributions
449*4f1223e8SApple OSS Distributions
450*4f1223e8SApple OSS Distributionsiii. Adding debug related 'printf's
451*4f1223e8SApple OSS Distributions-----------------------------------
452*4f1223e8SApple OSS Distributions
453*4f1223e8SApple OSS DistributionsThe xnu debug framework provides a utility function (debuglog) in utils.py. Please use this for any of your debugging needs. It will not print any output unless the user turns on debug logging on the command. Please check the documentaiton of debuglog for usage and options.
454*4f1223e8SApple OSS Distributions
455*4f1223e8SApple OSS Distributions  * To enable/disable logging
456*4f1223e8SApple OSS Distributions     - (lldb) xnudebug debug
457*4f1223e8SApple OSS Distributions       Enabled debug logging.
458*4f1223e8SApple OSS Distributions
459*4f1223e8SApple OSS Distributions
460