llvm-project/lldb/www/python-reference.html

534 lines
27 KiB
HTML
Executable File

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link href="style.css" rel="stylesheet" type="text/css" />
<title>LLDB Python Reference</title>
</head>
<body>
<div class="www_title">
LLDB Python Reference
</div>
<div id="container">
<div id="content">
<!--#include virtual="sidebar.incl"-->
<div id="middle">
<div class="post">
<h1 class ="postheader">Introduction</h1>
<div class="postcontent">
<p>The entire LLDB API is available as Python functions through a script bridging interface.
This means the LLDB API's can be used directly from python either interactively or to build python apps that
provide debugger features. </p>
<p>Additionally, Python can be used as a programmatic interface within the
lldb command interpreter (we refer to this for brevity as the embedded interpreter). Of course,
in this context it has full access to the LLDB API - with some additional conveniences we will
call out in the FAQ.</p>
</div>
<div class="postfooter"></div>
<div class="post">
<h1 class ="postheader">Documentation</h1>
<div class="postcontent">
<p>The LLDB API is contained in a python module named <b>lldb</b>. Help is available through the standard python help and documentation. To get an overview of the <b>lldb</b> python module you can execute the following command:</p>
<code><pre><tt>(lldb) <b>script help(lldb)</b>
Help on package lldb:
NAME
lldb - The lldb module contains the public APIs for Python binding.
FILE
/System/Library/PrivateFrameworks/LLDB.framework/Versions/A/Resources/Python/lldb/__init__.py
DESCRIPTION
...
</tt></pre></code>
<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>
<code><pre><tt>(lldb) <b>script help(lldb.SBFrame)</b>
Help on class SBFrame in module lldb:
class SBFrame(__builtin__.object)
| Represents one of the stack frames associated with a thread.
| SBThread contains SBFrame(s). For example (from test/lldbutil.py),
|
| def print_stacktrace(thread, string_buffer = False):
| '''Prints a simple stack trace of this thread.'''
|
...
</tt></pre></code>
<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>
<code><pre><tt>(lldb) <b>script help(lldb.process)</b>
Help on SBProcess in module lldb object:
class SBProcess(__builtin__.object)
| Represents the process associated with the target program.
|
| SBProcess supports thread iteration. For example (from test/lldbutil.py),
|
| # ==================================================
| # Utility functions related to Threads and Processes
| # ==================================================
|
...
</tt></pre></code>
</div>
<div class="postfooter"></div>
<div class="post">
<h1 class ="postheader">Embedded Python Interpreter</h1>
<div class="postcontent">
<p>The embedded python interpreter can be accessed in a variety of ways from within LLDB. The
easiest way is to use the lldb command <b>script</b> with no arguments at the lldb command prompt:</p>
<code><pre><tt>(lldb) <strong>script</strong>
Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.
>>> 2+3
5
>>> hex(12345)
'0x3039'
>>>
</tt></pre></code>
<p>This drops you into the embedded python interpreter. When running under the <b>script</b> command,
lldb sets some convenience variables that give you quick access to the currently selected entities that characterize
the program and debugger state. In each case, if there is no currently selected entity of the appropriate
type, the variable's <b>IsValid</b> method will return false.
<p>Note also, these variables hold the values
of the selected objects on entry to the embedded interpreter. They do not update as you use the LLDB
API's to change, for example, the currently selected stack frame or thread.</p>
These are all global variables contained in the <b>lldb</b> python namespace :</p>
<table class="stats" width="620" cellspacing="0">
<tr>
<td class="hed" width="20%">Variable</td>
<td class="hed" width="10%">Type</td>
<td class="hed" width="70%">Description</td>
</tr>
<tr>
<td class="content">
<b>lldb.debugger</b>
</td>
<td class="content">
<b>lldb.SBDebugger</b>
</td>
<td class="content">
Contains the debugger object whose <b>script</b> command was invoked.
The <b>lldb.SBDebugger</b> object owns the command interpreter
and all the targets in your debug session. There will always be a
Debugger in the embedded interpreter.
</td>
</tr>
<tr>
<td class="content">
<b>lldb.target</b>
</td>
<td class="content">
<b>lldb.SBTarget</b>
</td>
<td class="content">
Contains the currently selected target - for instance the one made with the
<b>file</b> or selected by the <b>target select &lt;target-index&gt;</b> command.
The <b>lldb.SBTarget</b> manages one running process, and all the executable
and debug files for the process.
</td>
</tr>
<tr>
<td class="content">
<b>lldb.process</b>
</td>
<td class="content">
<b>lldb.SBProcess</b>
</td>
<td class="content">
Contains the process of the currently selected target.
The <b>lldb.SBProcess</b> object manages the threads and allows access to
memory for the process.
</td>
</tr>
<tr>
<td class="content">
<b>lldb.thread</b>
</td>
<td class="content">
<b>lldb.SBThread</b>
</td>
<td class="content">
Contains the currently selected thread.
The <b>lldb.SBThread</b> object manages the stack frames in that thread.
A thread is always selected in the command interpreter when a target stops.
The <b>thread select &lt;thread-index&gt;</b> commmand can be used to change the
currently selected thread. So as long as you have a stopped process, there will be
some selected thread.
</td>
</tr>
<tr>
<td class="content">
<b>lldb.frame</b>
</td>
<td class="content">
<b>lldb.SBFrame</b>
</td>
<td class="content">
Contains the currently selected stack frame.
The <b>lldb.SBFrame</b> object manage the stack locals and the register set for
that stack.
A stack frame is always selected in the command interpreter when a target stops.
The <b>frame select &lt;frame-index&gt;</b> commmand can be used to change the
currently selected frame. So as long as you have a stopped process, there will
be some selected frame.
</td>
</tr>
</table>
<p>Once in the embedded interpreter, these objects can be used. To get started, note that almost
all of the <b>lldb</b> Python objects are able to briefly describe themselves when you pass them
to the Python <b>print</b> function:
<code><pre><tt>(lldb) <b>script</b>
Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.
>>> <strong>print lldb.debugger</strong>
Debugger (instance: "debugger_1", id: 1)
>>> <strong>print lldb.target</strong>
a.out
>>> <strong>print lldb.process</strong>
SBProcess: pid = 59289, state = stopped, threads = 1, executable = a.out
>>> <strong>print lldb.thread</strong>
SBThread: tid = 0x1f03
>>> <strong>print lldb.frame</strong>
frame #0: 0x0000000100000bb6 a.out main + 54 at main.c:16
</tt></pre></code>
</div>
<div class="postfooter"></div>
</div>
<div class="post">
<h1 class ="postheader">Running a Python script when a breakpoint gets hit</h1>
<div class="postcontent">
<p>One very powerful use of the lldb Python API is to have a python script run when a breakpoint gets hit. Adding python
scripts to breakpoints provides a way to create complex breakpoint
conditions and also allows for smart logging and data gathering.</p>
<p>When your process hits a breakpoint to which you have attached some python code, the code is executed as the
body of a function which takes two arguments:</p>
<p>
<code><pre><tt>def breakpoint_function_wrapper(<b>frame</b>, <b>bp_loc</b>):
<font color=green># Your code goes here</font>
</tt></pre></code>
<p><table class="stats" width="620" cellspacing="0">
<tr>
<td class="hed" width="10%">Argument</td>
<td class="hed" width="10%">Type</td>
<td class="hed" width="80%">Description</td>
</tr>
<tr>
<td class="content">
<b>frame</b>
</td>
<td class="content">
<b>lldb.SBFrame</b>
</td>
<td class="content">
The current stack frame where the breakpoint got hit.
The object will always be valid.
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>.
</td>
</tr>
<tr>
<td class="content">
<b>bp_loc</b>
</td>
<td class="content">
<b>lldb.SBBreakpointLocation</b>
</td>
<td class="content">
The breakpoint location that just got hit. Breakpoints are represented by <b>lldb.SBBreakpoint</b>
objects. These breakpoint objects can have one or more locations. These locations
are represented by <b>lldb.SBBreakpointLocation</b> objects.
</td>
</tr>
</table>
<p>An example will show how simple it is to write some python code and attach it to a breakpoint.
The following example will allow you to track the order in which the functions in a given shared library
are first executed during one run of your program. This is a simple method to gather an order file which
can be used to optimize function placement within a binary for execution locality.</p>
<p>We do this by setting a regular expression breakpoint
that will match every function in the shared library. The regular expression '.' will match
any string that has at least one character in it, so we will use that.
This will result in one <b>lldb.SBBreakpoint</b> object
that contains an <b>lldb.SBBreakpointLocation</b> object for each function. As the breakpoint gets
hit, we use a counter to track the order in which the function at this particular breakpoint location got hit.
Since our code is passed the location that was hit, we can get the name of the function from the location,
disable the location so we won't count this function again; then log some info and continue the process.</p>
<p>Note we also have to initialize our counter, which we do with the simple one-line version of the <b>script</b>
command.
<p>Here is the code:
<code><pre><tt>(lldb) <strong>breakpoint set --func-regex=. --shlib=libfoo.dylib</strong>
Breakpoint created: 1: regex = '.', module = libfoo.dylib, locations = 223
(lldb) <strong>script counter = 0</strong>
(lldb) <strong>breakpoint command add --script-type python 1</strong>
Enter your Python command(s). Type 'DONE' to end.
> <font color=green># Increment our counter. Since we are in a function, this must be a global python variable</font>
> <strong>global counter</strong>
> <strong>counter += 1</strong>
> <font color=green># Get the name of the function</font>
> <strong>name = frame.GetFunctionName()</strong>
> <font color=green># Print the order and the function name</font>
> <strong>print '[%i] %s' % (counter, name)</strong>
> <font color=green># Disable the current breakpoint location so it doesn't get hit again</font>
> <strong>bp_loc.SetEnabled(False)</strong>
> <font color=green># How continue the process</font>
> <strong>frame.GetThread().GetProcess().Continue()</strong>
> <strong>DONE</strong>
</tt></pre></code>
<p>The <b>breakpoint command add</b> command above attaches a python script to breakpoint 1.
To remove the breakpoint command:
<p><code>(lldb) <strong>breakpoint command delete 1</strong></code>
</div>
</div>
<div class="post">
<h1 class ="postheader">Create a new LLDB command using a python function</h1>
<div class="postcontent">
<p>Python functions can be used to create new LLDB command interpreter commands, which will work
like all the natively defined lldb commands. This provides a very flexible and easy way to extend LLDB to meet your
debugging requirements. </p>
<p>To write a python function that implements a new LDB command define the function to take four arguments as follows:</p>
<code><pre><tt>def command_function(<b>debugger</b>, <b>command</b>, <b>result</b>, <b>dict</b>):
<font color=green># Your code goes here</font>
</tt></pre></code>
Optionally, you can also provide a Python docstring, and LLDB will use it when providing help for your command, as in:
<code><pre><tt>def command_function(<b>debugger</b>, <b>command</b>, <b>result</b>, <b>dict</b>):
<font color=green>"""This command takes a lot of options and does many fancy things"""</font>
<font color=green># Your code goes here</font>
</tt></pre></code>
<p><table class="stats" width="620" cellspacing="0">
<tr>
<td class="hed" width="10%">Argument</td>
<td class="hed" width="10%">Type</td>
<td class="hed" width="80%">Description</td>
</tr>
<tr>
<td class="content">
<b>debugger</b>
</td>
<td class="content">
<b>lldb.SBDebugger</b>
</td>
<td class="content">
The current debugger object.
</td>
</tr>
<tr>
<td class="content">
<b>command</b>
</td>
<td class="content">
<b>python string</b>
</td>
<td class="content">
A python string containing all arguments for your command. If you need to chop up the arguments
try using the <b>shlex</b> module's <code>shlex.split(command)</code> to properly extract the
arguments.
</td>
</tr>
<tr>
<td class="content">
<b>result</b>
</td>
<td class="content">
<b>lldb.SBCommandReturnObject</b>
</td>
<td class="content">
A return object where you can indicate the success or failure of your command. You can also
provide information for the command result by printing data into it. You can also just print
data as you normally would in a python script and the output will show up; this is useful for
logging, but the real output for your command should go in the result object.
</td>
</tr>
<tr>
<td class="content">
<b>dict</b>
</td>
<td class="content">
<b>python dict object</b>
</td>
<td class="content">
The dictionary for the current embedded script session which contains all variables
and functions.
</td>
</tr>
</table>
<p>One other handy convenience when defining lldb command-line commands is the command
<b>command script import</b> which will import a module specified by file path - so you
don't have to change your PYTHONPATH for temporary scripts. It also has another convenience
that if your new script module has a function of the form:</p>
<code><pre><tt>def __lldb_init_module(<b>debugger</b>, <b>dict</b>):
<font color=green># Command Initialization code goes here</font>
</tt></pre></code>
<p>where <b>debugger</b> and <b>dict</b> are as above, that function will get run when the module is loaded
allowing you to add whatever commands you want into the current debugger. Note that
this function will only be run when using the LLDB comand <b>command script import</b>,
it will not get run if anyone imports your module from another module.
If you want to always run code when your module is loaded from LLDB
<u>or</u> when loaded via an <b>import</b> statement in python code
you can test the <b>lldb.debugger</b> object, since you imported the
<lldb> module at the top of the python <b>ls.py</b> module. This test
must be in code that isn't contained inside of any function or class,
just like the standard test for <b>__main__</b> like all python modules
usally do. Sample code would look like:
<code><pre><tt>if __name__ == '__main__':
<font color=green># Create a new debugger instance in your module if your module
# can be run from the command line. When we run a script from
# the command line, we won't have any debugger object in
# lldb.debugger, so we can just create it if it will be needed</font>
lldb.debugger = lldb.SBDebugger.Create()
elif lldb.debugger:
<font color=green># Module is being run inside the LLDB interpreter</font>
lldb.debugger.HandleCommand('command script add -f ls.ls ls')
print 'The "ls" python command has been installed and is ready for use.'
</tt></pre></code>
<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
can be used by LLDB's python command code:</p>
<code><pre><tt><font color=green>#!/usr/bin/python</font>
import lldb
import commands
import optparse
import shlex
def ls(debugger, command, result, dict):
result.PutCString(commands.getoutput('/bin/ls %s' % command))
<font color=green># And the initialization code to add your commands </font>
def __lldb_init_module(debugger, dict):
debugger.HandleCommand('command script add -f ls.ls ls')
print 'The "ls" python command has been installed and is ready for use.'
</tt></pre></code>
<p>Now we can load the module into LLDB and use it</p>
<code><pre><tt>% lldb
(lldb) <strong>command script import ~/ls.py</strong>
The "ls" python command has been installed and is ready for use.
(lldb) <strong>ls -l /tmp/</strong>
total 365848
-rw-r--r--@ 1 someuser wheel 6148 Jan 19 17:27 .DS_Store
-rw------- 1 someuser wheel 7331 Jan 19 15:37 crash.log
</tt></pre></code>
<p>A template has been created in the source repository that can help you to create
lldb command quickly:</p>
<a href="http://llvm.org/svn/llvm-project/lldb/trunk/examples/python/cmdtemplate.py">cmdtemplate.py</a>
</div>
<div class="post">
<h1 class ="postheader">Using the lldb.py module in python</h1>
<div class="postcontent">
<p>LLDB has all of its core code build into a shared library which gets
used by the <b>lldb</b> command line application. On Mac OS X this
shared library is a framework: <b>LLDB.framework</b> and on other
unix variants the program is a shared library: <b>lldb.so</b>. LLDB also
provides an lldb.py module that contains the bindings from LLDB into Python.
To use the
<b>LLDB.framework</b> to create your own stand-alone python programs, you will
need to tell python where to look in order to find this module. This
is done by setting the <b>PYTHONPATH</b> environment variable, adding
a path to the directory that contains the <b>lldb.py</b> python module. On
Mac OS X, this is contained inside the LLDB.framework, so you would do:
<p>For csh and tcsh:</p>
<p><code>% <b>setenv PYTHONPATH /Developer/Library/PrivateFrameworks/LLDB.framework/Resources/Python</b></code></p>
<p>For sh and bash:
<p><code>% <b>export PYTHONPATH=/Developer/Library/PrivateFrameworks/LLDB.framework/Resources/Python</b></code></p>
<p> Alternately, you can append the LLDB Python directory to the <b>sys.path</b> list directly in
your Python code before importing the lldb module.</p>
<p>
Now your python scripts are ready to import the lldb module. Below is a
python script that will launch a program from the current working directory
called "a.out", set a breakpoint at "main", and then run and hit the breakpoint,
and print the process, thread and frame objects if the process stopped:
</p>
<code><pre><tt><font color=green>#!/usr/bin/python</font>
import lldb
<font color=green># Set the path to the executable to debug</font>
exe = "./a.out"
<font color=green># Create a new debugger instance</font>
debugger = lldb.SBDebugger.Create()
<font color=green># When we step or continue, don't return from the function until the process
# stops. Otherwise we would have to handle the process events ourselves which, while doable is
#a little tricky. We do this by setting the async mode to false.</font>
debugger.SetAsync (False)
<font color=green># Create a target from a file and arch</font>
print "Creating a target for '%s'" % exe
target = debugger.CreateTargetWithFileAndArch (exe, lldb.LLDB_ARCH_DEFAULT)
if target:
<font color=green># If the target is valid set a breakpoint at main</font>
main_bp = target.BreakpointCreateByName ("main", target.GetExecutable().GetFilename());
print main_bp
<font color=green># Launch the process. Since we specified synchronous mode, we won't return
# from this function until we hit the breakpoint at main</font>
process = target.LaunchSimple (None, None, os.getcwd())
<font color=green># Make sure the launch went ok</font>
if process:
<font color=green># Print some simple process info</font>
state = process.GetState ()
print process
if state == lldb.eStateStopped:
<font color=green># Get the first thread</font>
thread = process.GetThreadAtIndex (0)
if thread:
<font color=green># Print some simple thread info</font>
print thread
<font color=green># Get the first frame</font>
frame = thread.GetFrameAtIndex (0)
if frame:
<font color=green># Print some simple frame info</font>
print frame
function = frame.GetFunction()
<font color=green># See if we have debug info (a function)</font>
if function:
<font color=green># We do have a function, print some info for the function</font>
print function
<font color=green># Now get all instructions for this function and print them</font>
insts = function.GetInstructions(target)
disassemble_instructions (insts)
else:
<font color=green># See if we have a symbol in the symbol table for where we stopped</font>
symbol = frame.GetSymbol();
if symbol:
<font color=green># We do have a symbol, print some info for the symbol</font>
print symbol
</tt></pre></code>
</div>
<div class="postfooter"></div>
</div>
</div>
</div>
</body>
</html>