# Python scripting LLDB supports controlling the debugger from a Python script. ## LLDB API The entire LLDB API is available as Python functions through a script bridging interface. This means you can use the LLDB API directly from Python, either interactively or to build Python apps that provide debugger features. Additionally, you can use Python as a programmatic interface in the LLDB command interpreter (for brevity, this interpreter is referred to as the *embedded interpreter*). In this context it has full access to the LLDB API. The LLDB API is contained in a Python module named `lldb`. When writing Python extensions, a useful resource is the [LLDB Python Classes Reference Guide](http://lldb.llvm.org/python_reference/index.html). The documentation is also accessible in an interactive debugger session with the following command: (lldb) script help(lldb) Copy to clipboard You can also get help using a module class name. The full API that is exposed for that class is displayed in a manpage style window. To get help on the `lldb.SBFrame` class: (lldb) script help(lldb.SBFrame) Copy to clipboard Or you can get help using any Python object. In the following example, the `lldb.process` object is used, which is a global variable in the lldb module that represents the currently selected process: (lldb) script help(lldb.process) Copy to clipboard ## Embedded Python interpreter You can access the embedded Python interpreter in a variety of ways from within LLDB. The easiest way is to use the LLDB script command with no arguments at the LLDB command prompt: (lldb) script Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D. >>> 2+3 5 >>> hex(12345) '0x3039' >>> Copy to clipboard This script drops you into the embedded Python interpreter. When running under the script command, LLDB sets some convenience variables which 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 IsValid method will return FALSE. **Table 7-1 Python convenience variables** | **Variable** | **Type** | **Description** | | --- | --- | --- | | lldb.debugger | lldb.SBDebugger | Contains the debugger object whose script command was invoked.


The lldb.SBDebugger object owns the command interpreter and all
the targets in your debug session.


There is always a debugger in the embedded interpreter. | | lldb.target | lldb.SBTarget | Contains the currently selected target - for instance the one
made with the file or selected by the target select
<target-index> command.


The lldb.SBTarget manages one running process, and all the
executable and debug files for the process. | | lldb.process | lldb.SBProcess | Contains the process of the currently selected target.


The lldb.SBProcess object manages the threads and allows access
to memory for the process. | | lldb.thread | lldb.SBThread | Contains the currently selected thread.


The lldb.SBThread object manages the stack frames in that thread.


A thread is always selected in the command interpreter when a
target stops. Use the thread select


<thread-index> command to change the currently selected thread.
As long as you have a stopped process, there is a selected thread. | | lldb.frame | lldb.SBFrame | Contains the currently selected stack frame.


The lldb.SBFrame object manages the stack locals and the
register set for that stack.


A stack frame is always selected in the command interpreter
when a target stops. Use the frame select


<frame-index> command to change the currently selected frame.
As long as you have a stopped process, there is a selected frame. | While extremely convenient, these variables have few restrictions on their use. First, they only hold the values of the selected objects on entry to the embedded interpreter. Their values are not updated when you use the LLDB APIs to change, for example, the currently selected stack frame or thread. Second, they are only defined and meaningful while in the interactive Python interpreter. There is no guarantee on their value in any other situation, so do not use them when defining Python formatters, breakpoint scripts, or commands (or any other Python extension point that LLDB provides). Note As a rationale for such behavior, consider that LLDB can run in a multi-threaded environment, and another thread might call the script command, changing the value out from under you. To assist you in getting started with objects and LLDB scripting, be aware that most of the LLDB Python objects can briefly describe themselves when they are passed to the Python print function: (lldb) script Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D. >>> print lldb.debugger Debugger (instance: "debugger_1", id: 1) >>> print lldb.target a.out >>> print lldb.process SBProcess: pid = 59289, state = stopped, threads = 1, executable = a.out >>> print lldb.thread SBThread: tid = 0x1f03 >>> print lldb.frame frame #0: 0x0000000100000bb6 a.out main + 54 at main.c:16 Copy to clipboard ## Run a script when a breakpoint is hit One powerful use of the LLDB Python API is to have a Python script run when a breakpoint is hit. Adding Python scripts to breakpoints provides a way to create complex breakpoint conditions, and they allow for smart logging and data gathering. When your process hits a breakpoint to which you have attached some Python code, the code is executed as the body of a function that takes three arguments: def breakpoint\_function\_wrapper(frame, bp\_loc, dict): # Your code goes here **Table 7-2 Python breakpoint function arguments** | **Argument** | **Type** | **Description** | | --- | --- | --- | | frame | lldb.SBFrame | The current stack frame where the breakpoint got hit.


The object is always valid.


This frame argument might match the currently selected stack
frame found in the LLDB module global variable, lldb.frame. | | bp\_loc | lldb.SBBreakpointLocation | The breakpoint location that was just hit.


Breakpoints are represented by lldb.SBBreakpoint objects, which
can have one or more locations. These locations are represented
by lldb.SBBreakpointLocation objects. | | dict | dict | The Python session dictionary as a standard Python dictionary object. | Optionally, a Python breakpoint command can return a value. Returning False informs LLDB that you do not want to stop at the breakpoint. Any other return value (including None or leaving out the return statement altogether) is equivalent to directing LLDB to stop at the breakpoint. This command is useful in situations where a breakpoint is required to only stop the process when certain conditions are met, and you do not want to inspect the program state manually at every stop and then continue. Writing some Python code and attaching it to a breakpoint is a fairly simple task. The following example shows how to track the order in which the functions in a given shared library are first executed during one run of your program. (lldb) breakpoint set --func-regex=. --shlib=libfoo.dylib Breakpoint created: 1: regex = '.', module = libfoo.dylib, locations = 223 (lldb) **script counter = 0** (lldb) **breakpoint command add --script-type python 1** Enter your Python command(s) and type 'DONE' to end. > # Increment counter. Since this is in a function, it must be a global Python variable > global counter > counter += 1 > # Get the name of the function > name = frame.GetFunctionName() > # Print the order and the function name > print '[%i] %s' % (counter, name) > # Disable current breakpoint location so it doesn't get hit again > bp_loc.SetEnabled(False) > # No need to stop here > return False > DONE Copy to clipboard This simple method gathers an order file that you can use to optimize function placement within a binary for execution locality. This is done 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 it is used. This will result in one lldb.SBBreakpoint object that contains an lldb.SBBreakpointLocation object for each function. When the breakpoint is hit, a counter is used to track the order in which the function at this breakpoint location was hit. Because the code is past the location that was hit, you can get the name of the function from the location, disable the location so you do not count this function again, and then log some information and continue the process. Note The counter must be initialized, which is done with the simple one-line version of the script command. The breakpoint command add command in this example attaches a Python script to breakpoint 1. To remove the breakpoint command: (lldb) breakpoint command delete 1 Copy to clipboard ## Create new command using a Python function You can use Python functions to create new LLDB command interpreter commands that work like all the natively defined LLDB commands. This provides a very flexible and easy way to extend LLDB to meet your debugging requirements. To write a Python function that implements a new LLDB command, define the function to take four arguments as follows: def command_function(debugger, command, result, internal_dict): # Your code goes here Copy to clipboard Optionally, you can also provide a Python docstring, and LLDB will use it when providing help for your command. For example: def command_function(debugger, command, result, internal_dict): """This command takes a lot of options and does many fancy things""" # *Your code goes here* Copy to clipboard **Table 7-3 Python command function arguments** | **Argument** | **Type** | **Description** | | --- | --- | --- | | debugger | lldb.SBDebugger | The current debugger object. | | command | Python string | A Python string containing all arguments for your command.


To chop up the arguments, try using the shlex module’s
shlex.split(command) to properly extract the arguments. | | result | lldb.SBCommandReturnObject | A return object that encapsulates success or failure information
for the command and output text that is to be printed as a
result of the command.


The plain Python print command also works, but text will not
go into the result by default (this command is useful as a
temporary logging facility). | | internal\_dict | Python dict object | The dictionary for the current embedded script session that
contains all variables and functions. | For convenience, you can treat the result object as a Python file object: print >>result, "my command does lots of cool stuff" Copy to clipboard `SBCommandReturnObject` and `SBStream` both support this file-like behavior by providing `write()` and `flush()` calls at the Python layer. Another convenience when defining LLDB command-line commands is the command, command script import. It imports a module specified by the file path so you are not required to change your PYTHONPATH for temporary scripts. This command also offers another convenience whereby if your new script module has a function of the form: def lldb_init_module(debugger, internal_dict): # Command initialization code goes here Copy to clipboard Where debugger and internal\_dict are defined as shown above. In this case, the function is run when the module is loaded, allowing you to add any commands into the current debugger. This function only runs when you use the LLDB command, command script import. It does not run if anyone imports your module from another module. To always run code when your module is loaded from LLDB, or when it is loaded with an import statement in Python code, you can test the lldb.debugger object because you imported the module at the top of the Python ls.py module. This test must be in code that is not contained inside any function or class, just like the standard test for main that all Python modules typically do. The sample code would look as follows: if name == ' main ': # Create a new debugger instance in your module if your module # can be run from the command line. When running a script from # the command line, there will not be any debugger object in # lldb.debugger, so you can just create it if needed lldb.debugger = lldb.SBDebugger.Create() elif lldb.debugger: # Module is being run inside the LLDB interpreter lldb.debugger.HandleCommand('command script add -f ls.ls ls') print 'The "ls" python command has been installed and is ready for use.' Copy to clipboard Next, create a module named `ls.py` in the `~/ls.py` file, which implements a function that the LLDB Python command code can use: #!/usr/bin/python import lldb import commands import optparse import shlex def ls(debugger, command, result, internal_dict): print >>result, (commands.getoutput('/bin/ls %s' % command)) # And the initialization code to add your commands def lldb_init_module(debugger, internal_dict): debugger.HandleCommand('command script add -f ls.ls ls') print 'The "ls" python command has been installed and is ready for use.' Copy to clipboard Finally, load the module into LLDB and use it: % lldb (lldb) command script import ~/ls.py The "ls" python command has been installed and is ready for use. (lldb) ls -l /tmp/ 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 Copy to clipboard Note A more interesting template, cmdtemplate.py, is available in the source repository ([http://llvm.org/svn/llvm-project/lldb/trunk/examples/python/cmdtemplate.py](http://llvm.org/svn/llvm-project/lldb/trunk/examples/python/cmdtemplate.py)). It can help you create LLDB commands quickly. A commonly required facility is the ability to create a command that performs some token substitution and then runs a different debugger command (typically, it performs a po on the result of an expression evaluated on its argument). For example, given the following program: #import NSString* ModifyString(NSString* src) { return [src stringByAppendingString:@"foobar"]; } int main() { NSString* aString = @"Hello world"; NSString* anotherString = @"Let's be friends"; return 1; } Copy to clipboard You might want a pofoo X command that equates po [ModifyString(X) capitalizedString]. The following debugger interaction shows how to achieve that goal: (lldb) script Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D. >>> def pofoo_funct(debugger, command, result, internal_dict): ... cmd = "po [ModifyString(" + command + ") capitalizedString]" ... lldb.debugger.HandleCommand(cmd) ... >>> ^D (lldb) command script add pofoo -f pofoo_funct (lldb) pofoo aString $1 = 0x000000010010aa00 Hello Worldfoobar (lldb) pofooanotherString $2 = 0x000000010010aba0 Let's Be Friendsfoobar Copy to clipboard Caution We strongly suggest that you do not use HandleCommand for anything but command script import and commands like settings set, which are not supported by the LLDB API. The LLDB API is the preferred method for interacting with LLDB through Python. Last Published: Oct 06, 2026 [Previous Topic Finding formatters 101](https://docs.qualcomm.com/bundle/publicresource/80-N3040-23/topics/variable-formatting.md) [Next Topic Script example](https://docs.qualcomm.com/bundle/publicresource/80-N3040-23/topics/script-example.md)