1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2 <html xmlns="http://www.w3.org/1999/xhtml">
4 <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
5 <link href="style.css" rel="stylesheet" type="text/css" />
6 <title>LLDB Python Reference</title>
10 <div class="www_title">
16 <!--#include virtual="sidebar.incl"-->
19 <h1 class ="postheader">Introduction</h1>
20 <div class="postcontent">
22 <p>The entire LLDB API is available as Python functions through a script bridging interface.
23 This means the LLDB API's can be used directly from python either interactively or to build python apps that
24 provide debugger features. </p>
25 <p>Additionally, Python can be used as a programmatic interface within the
26 lldb command interpreter (we refer to this for brevity as the embedded interpreter). Of course,
27 in this context it has full access to the LLDB API - with some additional conveniences we will
28 call out in the FAQ.</p>
31 <div class="postfooter"></div>
33 <h1 class ="postheader">Documentation</h1>
34 <div class="postcontent">
36 <p>The LLDB API is contained in a python module named <b>lldb</b>. A useful resource when writing Python extensions is the <a href="python_reference/index.html">lldb Python classes reference guide</a>.</p>
37 <p>The documentation is also accessible in an interactive debugger session with the following command:</p>
38 <code><pre><tt>(lldb) <b>script help(lldb)</b>
42 lldb - The lldb module contains the public APIs for Python binding.
45 /System/Library/PrivateFrameworks/LLDB.framework/Versions/A/Resources/Python/lldb/__init__.py
50 <p>You can also get help using a module class name. The full API that is exposed for that class will be displayed in a man page style window. Below we want to get help on the lldb.SBFrame class:</p>
51 <code><pre><tt>(lldb) <b>script help(lldb.SBFrame)</b>
52 Help on class SBFrame in module lldb:
54 class SBFrame(__builtin__.object)
55 | Represents one of the stack frames associated with a thread.
56 | SBThread contains SBFrame(s). For example (from test/lldbutil.py),
58 | def print_stacktrace(thread, string_buffer = False):
59 | '''Prints a simple stack trace of this thread.'''
63 <p>Or you can get help using any python object, here we use the <b>lldb.process</b> object which is a global variable in the <b>lldb</b> module which represents the currently selected process:</p>
64 <code><pre><tt>(lldb) <b>script help(lldb.process)</b>
65 Help on SBProcess in module lldb object:
67 class SBProcess(__builtin__.object)
68 | Represents the process associated with the target program.
70 | SBProcess supports thread iteration. For example (from test/lldbutil.py),
72 | # ==================================================
73 | # Utility functions related to Threads and Processes
74 | # ==================================================
80 <div class="postfooter"></div>
83 <h1 class ="postheader">Embedded Python Interpreter</h1>
84 <div class="postcontent">
86 <p>The embedded python interpreter can be accessed in a variety of ways from within LLDB. The
87 easiest way is to use the lldb command <b>script</b> with no arguments at the lldb command prompt:</p>
88 <code><pre><tt>(lldb) <strong>script</strong>
89 Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.
97 <p>This drops you into the embedded python interpreter. When running under the <b>script</b> command,
98 lldb sets some convenience variables that give you quick access to the currently selected entities that characterize
99 the program and debugger state. In each case, if there is no currently selected entity of the appropriate
100 type, the variable's <b>IsValid</b> method will return false. These variables are:</p>
102 <table class="stats" width="620" cellspacing="0">
104 <td class="hed" width="20%">Variable</td>
105 <td class="hed" width="10%">Type</td>
106 <td class="hed" width="70%">Description</td>
114 <b>lldb.SBDebugger</b>
117 Contains the debugger object whose <b>script</b> command was invoked.
118 The <b>lldb.SBDebugger</b> object owns the command interpreter
119 and all the targets in your debug session. There will always be a
120 Debugger in the embedded interpreter.
131 Contains the currently selected target - for instance the one made with the
132 <b>file</b> or selected by the <b>target select <target-index></b> command.
133 The <b>lldb.SBTarget</b> manages one running process, and all the executable
134 and debug files for the process.
142 <b>lldb.SBProcess</b>
145 Contains the process of the currently selected target.
146 The <b>lldb.SBProcess</b> object manages the threads and allows access to
147 memory for the process.
158 Contains the currently selected thread.
159 The <b>lldb.SBThread</b> object manages the stack frames in that thread.
160 A thread is always selected in the command interpreter when a target stops.
161 The <b>thread select <thread-index></b> command can be used to change the
162 currently selected thread. So as long as you have a stopped process, there will be
163 some selected thread.
174 Contains the currently selected stack frame.
175 The <b>lldb.SBFrame</b> object manage the stack locals and the register set for
177 A stack frame is always selected in the command interpreter when a target stops.
178 The <b>frame select <frame-index></b> command can be used to change the
179 currently selected frame. So as long as you have a stopped process, there will
180 be some selected frame.
185 <p>While extremely convenient, these variables have a couple caveats that you should be aware of.
186 First of all, they hold the values
187 of the selected objects on entry to the embedded interpreter. They do not update as you use the LLDB
188 API's to change, for example, the currently selected stack frame or thread.
189 <p>Moreover, they are only defined and meaningful while in the interactive Python interpreter.
190 There is no guarantee on their value in any other situation, hence you should not use them when defining
191 Python formatters, breakpoint scripts and commands (or any other Python extension point that LLDB provides).
192 As a rationale for such behavior, consider that lldb can
193 run in a multithreaded environment, and another thread might call the "script" command, changing the value out
196 <p>To get started with these objects and LLDB scripting, please note that almost
197 all of the <b>lldb</b> Python objects are able to briefly describe themselves when you pass them
198 to the Python <b>print</b> function:
199 <code><pre><tt>(lldb) <b>script</b>
200 Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.
201 >>> <strong>print lldb.debugger</strong>
202 Debugger (instance: "debugger_1", id: 1)
203 >>> <strong>print lldb.target</strong>
205 >>> <strong>print lldb.process</strong>
206 SBProcess: pid = 59289, state = stopped, threads = 1, executable = a.out
207 >>> <strong>print lldb.thread</strong>
208 SBThread: tid = 0x1f03
209 >>> <strong>print lldb.frame</strong>
210 frame #0: 0x0000000100000bb6 a.out main + 54 at main.c:16
214 <div class="postfooter"></div>
218 <h1 class ="postheader">Running a Python script when a breakpoint gets hit</h1>
219 <div class="postcontent">
221 <p>One very powerful use of the lldb Python API is to have a python script run when a breakpoint gets hit. Adding python
222 scripts to breakpoints provides a way to create complex breakpoint
223 conditions and also allows for smart logging and data gathering.</p>
224 <p>When your process hits a breakpoint to which you have attached some python code, the code is executed as the
225 body of a function which takes three arguments:</p>
227 <code><pre><tt>def breakpoint_function_wrapper(<b>frame</b>, <b>bp_loc</b>, <b>dict</b>):
228 <font color=green># Your code goes here</font>
230 <p><table class="stats" width="620" cellspacing="0">
232 <td class="hed" width="10%">Argument</td>
233 <td class="hed" width="10%">Type</td>
234 <td class="hed" width="80%">Description</td>
245 The current stack frame where the breakpoint got hit.
246 The object will always be valid.
247 This <b>frame</b> argument might <i>not</i> match the currently selected stack frame found in the <b>lldb</b> module global variable <b>lldb.frame</b>.
255 <b>lldb.SBBreakpointLocation</b>
258 The breakpoint location that just got hit. Breakpoints are represented by <b>lldb.SBBreakpoint</b>
259 objects. These breakpoint objects can have one or more locations. These locations
260 are represented by <b>lldb.SBBreakpointLocation</b> objects.
271 The python session dictionary as a standard python dictionary object.
275 <p>Optionally, a Python breakpoint command can return a value. Returning False tells LLDB that you do not want to stop at the breakpoint.
276 Any other return value (including None or leaving out the return statement altogether) is akin to telling LLDB to actually stop at the breakpoint.
277 This can be useful in situations where a breakpoint only needs to stop the process when certain conditions are met, and you do not want to inspect the
278 program state manually at every stop and then continue.
279 <p>An example will show how simple it is to write some python code and attach it to a breakpoint.
280 The following example will allow you to track the order in which the functions in a given shared library
281 are first executed during one run of your program. This is a simple method to gather an order file which
282 can be used to optimize function placement within a binary for execution locality.</p>
283 <p>We do this by setting a regular expression breakpoint
284 that will match every function in the shared library. The regular expression '.' will match
285 any string that has at least one character in it, so we will use that.
286 This will result in one <b>lldb.SBBreakpoint</b> object
287 that contains an <b>lldb.SBBreakpointLocation</b> object for each function. As the breakpoint gets
288 hit, we use a counter to track the order in which the function at this particular breakpoint location got hit.
289 Since our code is passed the location that was hit, we can get the name of the function from the location,
290 disable the location so we won't count this function again; then log some info and continue the process.</p>
291 <p>Note we also have to initialize our counter, which we do with the simple one-line version of the <b>script</b>
295 <code><pre><tt>(lldb) <strong>breakpoint set --func-regex=. --shlib=libfoo.dylib</strong>
296 Breakpoint created: 1: regex = '.', module = libfoo.dylib, locations = 223
297 (lldb) <strong>script counter = 0</strong>
298 (lldb) <strong>breakpoint command add --script-type python 1</strong>
299 Enter your Python command(s). Type 'DONE' to end.
300 > <font color=green># Increment our counter. Since we are in a function, this must be a global python variable</font>
301 > <strong>global counter</strong>
302 > <strong>counter += 1</strong>
303 > <font color=green># Get the name of the function</font>
304 > <strong>name = frame.GetFunctionName()</strong>
305 > <font color=green># Print the order and the function name</font>
306 > <strong>print '[%i] %s' % (counter, name)</strong>
307 > <font color=green># Disable the current breakpoint location so it doesn't get hit again</font>
308 > <strong>bp_loc.SetEnabled(False)</strong>
309 > <font color=green># No need to stop here</font>
310 > <strong>return False</strong>
311 > <strong>DONE</strong>
313 <p>The <b>breakpoint command add</b> command above attaches a python script to breakpoint 1.
314 To remove the breakpoint command:
315 <p><code>(lldb) <strong>breakpoint command delete 1</strong></code>
319 <h1 class ="postheader">Create a new LLDB command using a python function</h1>
320 <div class="postcontent">
322 <p>Python functions can be used to create new LLDB command interpreter commands, which will work
323 like all the natively defined lldb commands. This provides a very flexible and easy way to extend LLDB to meet your
324 debugging requirements. </p>
325 <p>To write a python function that implements a new LLDB command define the function to take four arguments as follows:</p>
327 <code><pre><tt>def command_function(<b>debugger</b>, <b>command</b>, <b>result</b>, <b>internal_dict</b>):
328 <font color=green># Your code goes here</font>
331 Optionally, you can also provide a Python docstring, and LLDB will use it when providing help for your command, as in:
332 <code><pre><tt>def command_function(<b>debugger</b>, <b>command</b>, <b>result</b>, <b>internal_dict</b>):
333 <font color=green>"""This command takes a lot of options and does many fancy things"""</font>
334 <font color=green># Your code goes here</font>
337 Starting with SVN revision 218834, LLDB Python commands can also take an SBExecutionContext as an argument.
338 This is useful in cases where the command's notion of <i>where to act</i> is independent of the currently-selected entities in the debugger.<br/>
339 This feature is enabled if the command-implementing function can be recognized as taking 5 arguments, or a variable number of arguments, and it alters the signature as such:
340 <code><pre><tt>def command_function(<b>debugger</b>, <b>command</b>, <b>exe_ctx</b>, <b>result</b>, <b>internal_dict</b>):
341 <font color=green># Your code goes here</font>
345 <p><table class="stats" width="620" cellspacing="0">
347 <td class="hed" width="10%">Argument</td>
348 <td class="hed" width="10%">Type</td>
349 <td class="hed" width="80%">Description</td>
357 <b>lldb.SBDebugger</b>
360 The current debugger object.
371 A python string containing all arguments for your command. If you need to chop up the arguments
372 try using the <b>shlex</b> module's <code>shlex.split(command)</code> to properly extract the
381 <b>lldb.SBExecutionContext</b>
384 An execution context object carrying around information on the inferior process' context in which the command is expected to act
385 <br/><i>Optional since SVN r218834, unavailable before</i>
393 <b>lldb.SBCommandReturnObject</b>
396 A return object which encapsulates success/failure information for the command and output text
397 that needs to be printed as a result of the command. The plain Python "print" command also works but
398 text won't go in the result by default (it is useful as a temporary logging facility).
406 <b>python dict object</b>
409 The dictionary for the current embedded script session which contains all variables
415 <p>Starting with SVN revision 232224, Python commands can also be implemented by means of a class
416 which should implement the following interface:</p>
419 <font color=blue>class</font> CommandObjectType:<br/>
420 <font color=blue>def</font> __init__(self, debugger, session_dict):<br/>
421 <i>this call should initialize the command with respect to the command interpreter for the passed-in debugger</i> <br/>
422 <font color=blue>def</font> __call__(self, debugger, command, exe_ctx, result): <br/>
423 <i>this is the actual bulk of the command, akin to Python command functions</i> <br/>
424 <font color=blue>def</font> get_short_help(self): <br/>
425 <i>this call should return the short help text for this command</i><sup>[1]</sup><br/>
426 <font color=blue>def</font> get_long_help(self): <br/>
427 <i>this call should return the long help text for this command</i><sup>[1]</sup><br/>
430 <sup>[1]</sup> This method is optional.
432 <p>As a convenience, you can treat the result object as a Python file object, and say
433 <code><pre><tt>print >>result, "my command does lots of cool stuff"</tt></pre></code>
434 SBCommandReturnObject and SBStream
435 both support this file-like behavior by providing write() and flush() calls at the Python layer.</p>
436 <p>One other handy convenience when defining lldb command-line commands is the command
437 <b>command script import</b> which will import a module specified by file path - so you
438 don't have to change your PYTHONPATH for temporary scripts. It also has another convenience
439 that if your new script module has a function of the form:</p>
441 <code><pre><tt>def __lldb_init_module(<b>debugger</b>, <b>internal_dict</b>):
442 <font color=green># Command Initialization code goes here</font>
445 <p>where <b>debugger</b> and <b>internal_dict</b> are as above, that function will get run when the module is loaded
446 allowing you to add whatever commands you want into the current debugger. Note that
447 this function will only be run when using the LLDB command <b>command script import</b>,
448 it will not get run if anyone imports your module from another module.
449 If you want to always run code when your module is loaded from LLDB
450 <u>or</u> when loaded via an <b>import</b> statement in python code
451 you can test the <b>lldb.debugger</b> object, since you imported the
452 <lldb> module at the top of the python <b>ls.py</b> module. This test
453 must be in code that isn't contained inside of any function or class,
454 just like the standard test for <b>__main__</b> like all python modules
455 usually do. Sample code would look like:
457 <code><pre><tt>if __name__ == '__main__':
458 <font color=green># Create a new debugger instance in your module if your module
459 # can be run from the command line. When we run a script from
460 # the command line, we won't have any debugger object in
461 # lldb.debugger, so we can just create it if it will be needed</font>
462 lldb.debugger = lldb.SBDebugger.Create()
464 <font color=green># Module is being run inside the LLDB interpreter</font>
465 lldb.debugger.HandleCommand('command script add -f ls.ls ls')
466 print 'The "ls" python command has been installed and is ready for use.'
468 <p>Now we can create a module called <b>ls.py</b> in the file <b>~/ls.py</b> that will implement a function that
469 can be used by LLDB's python command code:</p>
471 <code><pre><tt><font color=green>#!/usr/bin/python</font>
478 def ls(debugger, command, result, internal_dict):
479 print >>result, (commands.getoutput('/bin/ls %s' % command))
481 <font color=green># And the initialization code to add your commands </font>
482 def __lldb_init_module(debugger, internal_dict):
483 debugger.HandleCommand('command script add -f ls.ls ls')
484 print 'The "ls" python command has been installed and is ready for use.'
486 <p>Now we can load the module into LLDB and use it</p>
487 <code><pre><tt>% lldb
488 (lldb) <strong>command script import ~/ls.py</strong>
489 The "ls" python command has been installed and is ready for use.
490 (lldb) <strong>ls -l /tmp/</strong>
492 -rw-r--r--@ 1 someuser wheel 6148 Jan 19 17:27 .DS_Store
493 -rw------- 1 someuser wheel 7331 Jan 19 15:37 crash.log
495 <p>A more interesting template has been created in the source repository that can help you to create
496 lldb command quickly:</p>
497 <a href="http://llvm.org/svn/llvm-project/lldb/trunk/examples/python/cmdtemplate.py">cmdtemplate.py</a>
499 A commonly required facility is being able to create a command that does some token substitution, and then runs a different debugger command
500 (usually, it po'es the result of an expression evaluated on its argument). For instance, given the following program:
502 #import <Foundation/Foundation.h>
504 ModifyString(NSString* src)
506 return [src stringByAppendingString:@"foobar"];
511 NSString* aString = @"Hello world";
512 NSString* anotherString = @"Let's be friends";
516 you may want a pofoo X command, that equates po [ModifyString(X) capitalizedString].
517 The following debugger interaction shows how to achieve that goal:
520 Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.
521 >>> <b>def pofoo_funct(debugger, command, result, internal_dict):</b>
522 ... <b>cmd = "po [ModifyString(" + command + ") capitalizedString]"</b>
523 ... <b>lldb.debugger.HandleCommand(cmd)</b>
526 (lldb) <b>command script add pofoo -f pofoo_funct</b>
527 (lldb) <b>pofoo aString</b>
528 $1 = 0x000000010010aa00 Hello Worldfoobar
529 (lldb) <b>pofoo anotherString</b>
530 $2 = 0x000000010010aba0 Let's Be Friendsfoobar</tt></pre></code>
533 <h1 class ="postheader">Using the lldb.py module in python</h1>
534 <div class="postcontent">
536 <p>LLDB has all of its core code build into a shared library which gets
537 used by the <b>lldb</b> command line application. On Mac OS X this
538 shared library is a framework: <b>LLDB.framework</b> and on other
539 unix variants the program is a shared library: <b>lldb.so</b>. LLDB also
540 provides an lldb.py module that contains the bindings from LLDB into Python.
542 <b>LLDB.framework</b> to create your own stand-alone python programs, you will
543 need to tell python where to look in order to find this module. This
544 is done by setting the <b>PYTHONPATH</b> environment variable, adding
545 a path to the directory that contains the <b>lldb.py</b> python module. On
546 Mac OS X, this is contained inside the LLDB.framework, so you would do:
548 <p>For csh and tcsh:</p>
549 <p><code>% <b>setenv PYTHONPATH /Developer/Library/PrivateFrameworks/LLDB.framework/Resources/Python</b></code></p>
551 <p><code>% <b>export PYTHONPATH=/Developer/Library/PrivateFrameworks/LLDB.framework/Resources/Python</b></code></p>
553 <p> Alternately, you can append the LLDB Python directory to the <b>sys.path</b> list directly in
554 your Python code before importing the lldb module.</p>
557 Now your python scripts are ready to import the lldb module. Below is a
558 python script that will launch a program from the current working directory
559 called "a.out", set a breakpoint at "main", and then run and hit the breakpoint,
560 and print the process, thread and frame objects if the process stopped:
563 <code><pre><tt><font color=green>#!/usr/bin/python</font>
568 def disassemble_instructions(insts):
572 <font color=green># Set the path to the executable to debug</font>
575 <font color=green># Create a new debugger instance</font>
576 debugger = lldb.SBDebugger.Create()
578 <font color=green># When we step or continue, don't return from the function until the process
579 # stops. Otherwise we would have to handle the process events ourselves which, while doable is
580 #a little tricky. We do this by setting the async mode to false.</font>
581 debugger.SetAsync (False)
583 <font color=green># Create a target from a file and arch</font>
584 print "Creating a target for '%s'" % exe
586 target = debugger.CreateTargetWithFileAndArch (exe, lldb.LLDB_ARCH_DEFAULT)
589 <font color=green># If the target is valid set a breakpoint at main</font>
590 main_bp = target.BreakpointCreateByName ("main", target.GetExecutable().GetFilename());
594 <font color=green># Launch the process. Since we specified synchronous mode, we won't return
595 # from this function until we hit the breakpoint at main</font>
596 process = target.LaunchSimple (None, None, os.getcwd())
598 <font color=green># Make sure the launch went ok</font>
600 <font color=green># Print some simple process info</font>
601 state = process.GetState ()
603 if state == lldb.eStateStopped:
604 <font color=green># Get the first thread</font>
605 thread = process.GetThreadAtIndex (0)
607 <font color=green># Print some simple thread info</font>
609 <font color=green># Get the first frame</font>
610 frame = thread.GetFrameAtIndex (0)
612 <font color=green># Print some simple frame info</font>
614 function = frame.GetFunction()
615 <font color=green># See if we have debug info (a function)</font>
617 <font color=green># We do have a function, print some info for the function</font>
619 <font color=green># Now get all instructions for this function and print them</font>
620 insts = function.GetInstructions(target)
621 disassemble_instructions (insts)
623 <font color=green># See if we have a symbol in the symbol table for where we stopped</font>
624 symbol = frame.GetSymbol();
626 <font color=green># We do have a symbol, print some info for the symbol</font>
630 <div class="postfooter"></div>