]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - www/python-reference.html
Vendor import of lldb trunk r256945:
[FreeBSD/FreeBSD.git] / www / python-reference.html
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">
3 <head>
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>
7 </head>
8
9 <body>
10     <div class="www_title">
11       LLDB Python Reference
12     </div>
13     
14 <div id="container">
15         <div id="content">
16          <!--#include virtual="sidebar.incl"-->
17                 <div id="middle">
18                         <div class="post">
19                                 <h1 class ="postheader">Introduction</h1>
20                                 <div class="postcontent">
21
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>
29
30                                 </div>
31                                 <div class="postfooter"></div>
32                 <div class="post">
33                         <h1 class ="postheader">Documentation</h1>
34                         <div class="postcontent">
35
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>
39     Help on package lldb:
40
41     NAME
42         lldb - The lldb module contains the public APIs for Python binding.
43
44     FILE
45         /System/Library/PrivateFrameworks/LLDB.framework/Versions/A/Resources/Python/lldb/__init__.py
46
47     DESCRIPTION
48 ...
49 </tt></pre></code>
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:
53
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),
57      |  
58      |  def print_stacktrace(thread, string_buffer = False):
59      |      '''Prints a simple stack trace of this thread.'''
60      |  
61 ...
62 </tt></pre></code>
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:
66
67     class SBProcess(__builtin__.object)
68      |  Represents the process associated with the target program.
69      |  
70      |  SBProcess supports thread iteration. For example (from test/lldbutil.py),
71      |  
72      |  # ==================================================
73      |  # Utility functions related to Threads and Processes
74      |  # ==================================================
75      |  
76 ...
77 </tt></pre></code>
78
79                                 </div>
80                                 <div class="postfooter"></div>
81
82                         <div class="post">
83                                 <h1 class ="postheader">Embedded Python Interpreter</h1>
84                                 <div class="postcontent">
85
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.
90 >>> 2+3
91 5
92 >>> hex(12345)
93 '0x3039'
94 >>> 
95 </tt></pre></code>
96
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>
101
102                     <table class="stats" width="620" cellspacing="0">
103                     <tr>
104                         <td class="hed" width="20%">Variable</td>
105                         <td class="hed" width="10%">Type</td>
106                         <td class="hed" width="70%">Description</td>
107                     </tr>
108
109                     <tr>
110                         <td class="content">
111                             <b>lldb.debugger</b>
112                         </td>
113                         <td class="content">
114                             <b>lldb.SBDebugger</b>
115                         </td>
116                         <td class="content">
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.
121                         </td>
122                     </tr>
123                     <tr>
124                         <td class="content">
125                             <b>lldb.target</b>
126                         </td>
127                         <td class="content">
128                             <b>lldb.SBTarget</b>
129                         </td>
130                         <td class="content">
131                             Contains the currently selected target - for instance the one made with the
132                             <b>file</b> or selected by the <b>target select &lt;target-index&gt;</b> command.
133                             The <b>lldb.SBTarget</b> manages one running process, and all the executable
134                             and debug files for the process.
135                         </td>
136                     </tr>
137                     <tr>
138                         <td class="content">
139                             <b>lldb.process</b>
140                         </td>
141                         <td class="content">
142                             <b>lldb.SBProcess</b>
143                         </td>
144                         <td class="content">
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.
148                         </td>
149                     </tr>
150                     <tr>
151                         <td class="content">
152                             <b>lldb.thread</b>
153                         </td>
154                         <td class="content">
155                             <b>lldb.SBThread</b>
156                         </td>
157                         <td class="content">
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 &lt;thread-index&gt;</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.
164                         </td>
165                     </tr>
166                     <tr>
167                         <td class="content">
168                             <b>lldb.frame</b>
169                         </td>
170                         <td class="content">
171                             <b>lldb.SBFrame</b>
172                         </td>
173                         <td class="content">
174                             Contains the currently selected stack frame.
175                             The <b>lldb.SBFrame</b> object manage the stack locals and the register set for
176                             that stack.
177                             A stack frame is always selected in the command interpreter when a target stops.
178                             The <b>frame select &lt;frame-index&gt;</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.
181                         </td>
182                     </tr>
183                     </table>
184
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
194                        from under you.</p>
195
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>
204 a.out
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
211 </tt></pre></code>
212
213                                 </div>
214                                 <div class="postfooter"></div>
215
216         </div>
217                 <div class="post">
218                         <h1 class ="postheader">Running a Python script when a breakpoint gets hit</h1>
219                         <div class="postcontent">
220
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>
226                     <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>
229 </tt></pre></code>
230                     <p><table class="stats" width="620" cellspacing="0">
231                     <tr>
232                         <td class="hed" width="10%">Argument</td>
233                         <td class="hed" width="10%">Type</td>
234                         <td class="hed" width="80%">Description</td>
235                     </tr>
236
237                     <tr>
238                         <td class="content">
239                             <b>frame</b>
240                         </td>
241                         <td class="content">
242                             <b>lldb.SBFrame</b>
243                         </td>
244                         <td class="content">
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>.
248                         </td>
249                     </tr>
250                     <tr>
251                         <td class="content">
252                             <b>bp_loc</b>
253                         </td>
254                         <td class="content">
255                             <b>lldb.SBBreakpointLocation</b>
256                         </td>
257                         <td class="content">
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.
261                         </td>
262                     </tr>
263                     <tr>
264                         <td class="content">
265                             <b>dict</b>
266                         </td>
267                         <td class="content">
268                             <b>dict</b>
269                         </td>
270                         <td class="content">
271                             The python session dictionary as a standard python dictionary object.
272                         </td>
273                     </tr>
274                     </table>
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>
292                 command.
293              <p>Here is the code:
294
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>
312 </tt></pre></code>
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>
316             </div>
317         </div>
318                 <div class="post">
319                         <h1 class ="postheader">Create a new LLDB command using a python function</h1>
320                         <div class="postcontent">
321
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>
326                         
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>
329         </tt></pre></code>
330
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>
335         </tt></pre></code>
336         
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>
342       </tt></pre></code>
343       
344
345         <p><table class="stats" width="620" cellspacing="0">
346         <tr>
347             <td class="hed" width="10%">Argument</td>
348             <td class="hed" width="10%">Type</td>
349             <td class="hed" width="80%">Description</td>
350         </tr>
351
352         <tr>
353             <td class="content">
354                 <b>debugger</b>
355             </td>
356             <td class="content">
357                 <b>lldb.SBDebugger</b>
358             </td>
359             <td class="content">
360                 The current debugger object.
361             </td>
362         </tr>
363         <tr>
364             <td class="content">
365                 <b>command</b>
366             </td>
367             <td class="content">
368                 <b>python string</b>
369             </td>
370             <td class="content">
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
373                 arguments.
374             </td>
375         </tr>
376         <tr>
377             <td class="content">
378                 <b>exe_ctx</b>
379             </td>
380             <td class="content">
381                 <b>lldb.SBExecutionContext</b>
382             </td>
383             <td class="content">
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>
386             </td>
387         </tr>
388         <tr>
389             <td class="content">
390                 <b>result</b>
391             </td>
392             <td class="content">
393                 <b>lldb.SBCommandReturnObject</b>
394             </td>
395             <td class="content">
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).
399             </td>
400         </tr>
401         <tr>
402             <td class="content">
403                 <b>internal_dict</b>
404             </td>
405             <td class="content">
406                 <b>python dict object</b>
407             </td>
408             <td class="content">
409                 The dictionary for the current embedded script session which contains all variables 
410                 and functions.
411             </td>
412         </tr>
413         </table>
414                                 
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>
417
418                 <code>
419                         <font color=blue>class</font> CommandObjectType:<br/>
420                         &nbsp;&nbsp;&nbsp;&nbsp;<font color=blue>def</font> __init__(self, debugger, session_dict):<br/>
421                         &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i>this call should initialize the command with respect to the command interpreter for the passed-in debugger</i> <br/>
422                         &nbsp;&nbsp;&nbsp;&nbsp;<font color=blue>def</font> __call__(self, debugger, command, exe_ctx, result): <br/>
423                         &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i>this is the actual bulk of the command, akin to Python command functions</i> <br/>
424                         &nbsp;&nbsp;&nbsp;&nbsp;<font color=blue>def</font> get_short_help(self): <br/>
425                         &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i>this call should return the short help text for this command</i><sup>[1]</sup><br/>
426                         &nbsp;&nbsp;&nbsp;&nbsp;<font color=blue>def</font> get_long_help(self): <br/>
427                         &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i>this call should return the long help text for this command</i><sup>[1]</sup><br/>
428                 </code>
429                                 
430 <sup>[1]</sup> This method is optional.
431
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>
440
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>
443 </tt></pre></code>
444
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:
456
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()
463 elif lldb.debugger:
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.'
467 </tt></pre></code>
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>
470         
471 <code><pre><tt><font color=green>#!/usr/bin/python</font>
472
473 import lldb
474 import commands
475 import optparse
476 import shlex
477
478 def ls(debugger, command, result, internal_dict):
479     print >>result, (commands.getoutput('/bin/ls %s' % command))
480
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.'
485 </tt></pre></code>
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>
491 total 365848
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
494 </tt></pre></code>
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>
498                 <p>
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:
501                 <code><pre><tt>
502 #import &lt;Foundation/Foundation.h&gt;
503 NSString*
504 ModifyString(NSString* src)
505 {
506         return [src stringByAppendingString:@"foobar"];
507 }
508
509 int main()
510 {
511         NSString* aString = @"Hello world";
512         NSString* anotherString = @"Let's be friends";
513         return 1;
514 }
515                 </tt></pre></code>
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:
518                 <code><pre><tt>
519 (lldb) <b>script</b>
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>
524 ... 
525 >>> ^D
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>
531         </div>
532                 <div class="post">
533                         <h1 class ="postheader">Using the lldb.py module in python</h1>
534                         <div class="postcontent">
535
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.
541                     To use the 
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:
547                     
548                     <p>For csh and tcsh:</p>
549                     <p><code>% <b>setenv PYTHONPATH /Developer/Library/PrivateFrameworks/LLDB.framework/Resources/Python</b></code></p>
550                     <p>For sh and bash:
551                     <p><code>% <b>export PYTHONPATH=/Developer/Library/PrivateFrameworks/LLDB.framework/Resources/Python</b></code></p>
552                     
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>
555
556                     <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:
561                         
562                     </p>
563 <code><pre><tt><font color=green>#!/usr/bin/python</font>
564
565 import lldb
566 import os
567
568 def disassemble_instructions(insts):
569     for i in insts:
570         print i
571
572 <font color=green># Set the path to the executable to debug</font>
573 exe = "./a.out"
574
575 <font color=green># Create a new debugger instance</font>
576 debugger = lldb.SBDebugger.Create()
577
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)
582
583 <font color=green># Create a target from a file and arch</font>
584 print "Creating a target for '%s'" % exe
585
586 target = debugger.CreateTargetWithFileAndArch (exe, lldb.LLDB_ARCH_DEFAULT)
587
588 if target:
589     <font color=green># If the target is valid set a breakpoint at main</font>
590     main_bp = target.BreakpointCreateByName ("main", target.GetExecutable().GetFilename());
591
592     print main_bp
593
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())
597     
598     <font color=green># Make sure the launch went ok</font>
599     if process:
600         <font color=green># Print some simple process info</font>
601         state = process.GetState ()
602         print process
603         if state == lldb.eStateStopped:
604             <font color=green># Get the first thread</font>
605             thread = process.GetThreadAtIndex (0)
606             if thread:
607                 <font color=green># Print some simple thread info</font>
608                 print thread
609                 <font color=green># Get the first frame</font>
610                 frame = thread.GetFrameAtIndex (0)
611                 if frame:
612                     <font color=green># Print some simple frame info</font>
613                     print frame
614                     function = frame.GetFunction()
615                     <font color=green># See if we have debug info (a function)</font>
616                     if function:
617                         <font color=green># We do have a function, print some info for the function</font>
618                         print function
619                         <font color=green># Now get all instructions for this function and print them</font>
620                         insts = function.GetInstructions(target)
621                         disassemble_instructions (insts)
622                     else:
623                         <font color=green># See if we have a symbol in the symbol table for where we stopped</font>
624                         symbol = frame.GetSymbol();
625                         if symbol:
626                             <font color=green># We do have a symbol, print some info for the symbol</font>
627                             print symbol
628 </tt></pre></code>
629                                         </div>
630                                         <div class="postfooter"></div>
631
632                 </div>
633         </div>
634 </div>
635 </body>
636 </html>