xref: /llvm-project/lldb/docs/use/python-reference.rst (revision 04b443e77845cd20ab5acc4356cee509316135dd)
17b844849SJonas DevliegherePython Reference
27b844849SJonas Devlieghere================
37b844849SJonas Devlieghere
47b844849SJonas DevlieghereThe entire LLDB API is available as Python functions through a script bridging
57b844849SJonas Devlieghereinterface. This means the LLDB API's can be used directly from python either
67b844849SJonas Devlieghereinteractively or to build python apps that provide debugger features.
77b844849SJonas Devlieghere
87b844849SJonas DevlieghereAdditionally, Python can be used as a programmatic interface within the lldb
97b844849SJonas Devliegherecommand interpreter (we refer to this for brevity as the embedded interpreter).
107b844849SJonas DevlieghereOf course, in this context it has full access to the LLDB API - with some
117b844849SJonas Devlieghereadditional conveniences we will call out in the FAQ.
127b844849SJonas Devlieghere
137b844849SJonas DevlieghereDocumentation
147b844849SJonas Devlieghere--------------
157b844849SJonas Devlieghere
167b844849SJonas DevlieghereThe LLDB API is contained in a python module named lldb. A useful resource when
177b844849SJonas Devliegherewriting Python extensions is the lldb Python classes reference guide.
187b844849SJonas Devlieghere
197b844849SJonas DevlieghereThe documentation is also accessible in an interactive debugger session with
207b844849SJonas Devliegherethe following command:
217b844849SJonas Devlieghere
227b844849SJonas Devlieghere::
237b844849SJonas Devlieghere
247b844849SJonas Devlieghere   (lldb) script help(lldb)
257b844849SJonas Devlieghere      Help on package lldb:
267b844849SJonas Devlieghere
277b844849SJonas Devlieghere      NAME
287b844849SJonas Devlieghere         lldb - The lldb module contains the public APIs for Python binding.
297b844849SJonas Devlieghere
307b844849SJonas Devlieghere      FILE
317b844849SJonas Devlieghere         /System/Library/PrivateFrameworks/LLDB.framework/Versions/A/Resources/Python/lldb/__init__.py
327b844849SJonas Devlieghere
337b844849SJonas Devlieghere      DESCRIPTION
347b844849SJonas Devlieghere   ...
357b844849SJonas Devlieghere
367b844849SJonas DevlieghereYou can also get help using a module class name. The full API that is exposed
377b844849SJonas Devliegherefor that class will be displayed in a man page style window. Below we want to
387b844849SJonas Devlieghereget help on the lldb.SBFrame class:
397b844849SJonas Devlieghere
407b844849SJonas Devlieghere::
417b844849SJonas Devlieghere
427b844849SJonas Devlieghere   (lldb) script help(lldb.SBFrame)
437b844849SJonas Devlieghere      Help on class SBFrame in module lldb:
447b844849SJonas Devlieghere
457b844849SJonas Devlieghere      class SBFrame(__builtin__.object)
467b844849SJonas Devlieghere      |  Represents one of the stack frames associated with a thread.
477b844849SJonas Devlieghere      |  SBThread contains SBFrame(s). For example (from test/lldbutil.py),
487b844849SJonas Devlieghere      |
497b844849SJonas Devlieghere      |  def print_stacktrace(thread, string_buffer = False):
507b844849SJonas Devlieghere      |      '''Prints a simple stack trace of this thread.'''
517b844849SJonas Devlieghere      |
527b844849SJonas Devlieghere   ...
537b844849SJonas Devlieghere
547b844849SJonas DevlieghereOr you can get help using any python object, here we use the lldb.process
557b844849SJonas Devlieghereobject which is a global variable in the lldb module which represents the
567b844849SJonas Devliegherecurrently selected process:
577b844849SJonas Devlieghere
587b844849SJonas Devlieghere::
597b844849SJonas Devlieghere
607b844849SJonas Devlieghere   (lldb) script help(lldb.process)
617b844849SJonas Devlieghere      Help on SBProcess in module lldb object:
627b844849SJonas Devlieghere
637b844849SJonas Devlieghere      class SBProcess(__builtin__.object)
647b844849SJonas Devlieghere      |  Represents the process associated with the target program.
657b844849SJonas Devlieghere      |
667b844849SJonas Devlieghere      |  SBProcess supports thread iteration. For example (from test/lldbutil.py),
677b844849SJonas Devlieghere      |
687b844849SJonas Devlieghere      |  # ==================================================
697b844849SJonas Devlieghere      |  # Utility functions related to Threads and Processes
707b844849SJonas Devlieghere      |  # ==================================================
717b844849SJonas Devlieghere      |
727b844849SJonas Devlieghere   ...
737b844849SJonas Devlieghere
747b844849SJonas DevlieghereEmbedded Python Interpreter
757b844849SJonas Devlieghere---------------------------
767b844849SJonas Devlieghere
777b844849SJonas DevlieghereThe embedded python interpreter can be accessed in a variety of ways from
787b844849SJonas Devliegherewithin LLDB. The easiest way is to use the lldb command script with no
797b844849SJonas Devliegherearguments at the lldb command prompt:
807b844849SJonas Devlieghere
817b844849SJonas Devlieghere::
827b844849SJonas Devlieghere
837b844849SJonas Devlieghere   (lldb) script
847b844849SJonas Devlieghere   Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.
857b844849SJonas Devlieghere   >>> 2+3
867b844849SJonas Devlieghere   5
877b844849SJonas Devlieghere   >>> hex(12345)
887b844849SJonas Devlieghere   '0x3039'
897b844849SJonas Devlieghere   >>>
907b844849SJonas Devlieghere
917b844849SJonas DevlieghereThis drops you into the embedded python interpreter. When running under the
927b844849SJonas Devliegherescript command, lldb sets some convenience variables that give you quick access
937b844849SJonas Devlieghereto the currently selected entities that characterize the program and debugger
947b844849SJonas Devliegherestate. In each case, if there is no currently selected entity of the
957b844849SJonas Devlieghereappropriate type, the variable's IsValid method will return false. These
967b844849SJonas Devliegherevariables are:
977b844849SJonas Devlieghere
98f46a441bSJonas Devlieghere+-------------------+---------------------+-------------------------------------+-------------------------------------------------------------------------------------+
99f46a441bSJonas Devlieghere| Variable          | Type                | Equivalent                          | Description                                                                         |
100f46a441bSJonas Devlieghere+-------------------+---------------------+-------------------------------------+-------------------------------------------------------------------------------------+
10151ab17b9SRaphael Isemann| ``lldb.debugger`` | `lldb.SBDebugger`   | `SBTarget.GetDebugger`              | Contains the debugger object whose ``script`` command was invoked.                  |
102f46a441bSJonas Devlieghere|                   |                     |                                     | The `lldb.SBDebugger` object owns the command interpreter                           |
103f46a441bSJonas Devlieghere|                   |                     |                                     | and all the targets in your debug session.  There will always be a                  |
104f46a441bSJonas Devlieghere|                   |                     |                                     | Debugger in the embedded interpreter.                                               |
105f46a441bSJonas Devlieghere+-------------------+---------------------+-------------------------------------+-------------------------------------------------------------------------------------+
10651ab17b9SRaphael Isemann| ``lldb.target``   | `lldb.SBTarget`     | `SBDebugger.GetSelectedTarget`      | Contains the currently selected target - for instance the one made with the         |
10751ab17b9SRaphael Isemann|                   |                     |                                     | ``file`` or selected by the ``target select <target-index>`` command.               |
108f46a441bSJonas Devlieghere|                   |                     | `SBProcess.GetTarget`               | The `lldb.SBTarget` manages one running process, and all the executable             |
109f46a441bSJonas Devlieghere|                   |                     |                                     | and debug files for the process.                                                    |
110f46a441bSJonas Devlieghere+-------------------+---------------------+-------------------------------------+-------------------------------------------------------------------------------------+
11151ab17b9SRaphael Isemann| ``lldb.process``  | `lldb.SBProcess`    | `SBTarget.GetProcess`               | Contains the process of the currently selected target.                              |
112f46a441bSJonas Devlieghere|                   |                     |                                     | The `lldb.SBProcess` object manages the threads and allows access to                |
113f46a441bSJonas Devlieghere|                   |                     | `SBThread.GetProcess`               | memory for the process.                                                             |
114f46a441bSJonas Devlieghere+-------------------+---------------------+-------------------------------------+-------------------------------------------------------------------------------------+
11551ab17b9SRaphael Isemann| ``lldb.thread``   | `lldb.SBThread`     | `SBProcess.GetSelectedThread`       | Contains the currently selected thread.                                             |
116f46a441bSJonas Devlieghere|                   |                     |                                     | The `lldb.SBThread` object manages the stack frames in that thread.                 |
117f46a441bSJonas Devlieghere|                   |                     | `SBFrame.GetThread`                 | A thread is always selected in the command interpreter when a target stops.         |
11851ab17b9SRaphael Isemann|                   |                     |                                     | The ``thread select <thread-index>`` command can be used to change the              |
119f46a441bSJonas Devlieghere|                   |                     |                                     | currently selected thread.  So as long as you have a stopped process, there will be |
120f46a441bSJonas Devlieghere|                   |                     |                                     | some selected thread.                                                               |
121f46a441bSJonas Devlieghere+-------------------+---------------------+-------------------------------------+-------------------------------------------------------------------------------------+
12251ab17b9SRaphael Isemann| ``lldb.frame``    | `lldb.SBFrame`      | `SBThread.GetSelectedFrame`         | Contains the currently selected stack frame.                                        |
123f46a441bSJonas Devlieghere|                   |                     |                                     | The `lldb.SBFrame` object manage the stack locals and the register set for          |
124f46a441bSJonas Devlieghere|                   |                     |                                     | that stack.                                                                         |
125f46a441bSJonas Devlieghere|                   |                     |                                     | A stack frame is always selected in the command interpreter when a target stops.    |
12651ab17b9SRaphael Isemann|                   |                     |                                     | The ``frame select <frame-index>`` command can be used to change the                |
127f46a441bSJonas Devlieghere|                   |                     |                                     | currently selected frame.  So as long as you have a stopped process, there will     |
128f46a441bSJonas Devlieghere|                   |                     |                                     | be some selected frame.                                                             |
129f46a441bSJonas Devlieghere+-------------------+---------------------+-------------------------------------+-------------------------------------------------------------------------------------+
1307b844849SJonas Devlieghere
1317b844849SJonas DevlieghereWhile extremely convenient, these variables have a couple caveats that you
1327b844849SJonas Devlieghereshould be aware of. First of all, they hold the values of the selected objects
1337b844849SJonas Devlieghereon entry to the embedded interpreter. They do not update as you use the LLDB
1347b844849SJonas DevlieghereAPI's to change, for example, the currently selected stack frame or thread.
1357b844849SJonas Devlieghere
1367b844849SJonas DevlieghereMoreover, they are only defined and meaningful while in the interactive Python
1377b844849SJonas Devlieghereinterpreter. There is no guarantee on their value in any other situation, hence
1387b844849SJonas Devlieghereyou should not use them when defining Python formatters, breakpoint scripts and
139f46a441bSJonas Devliegherecommands (or any other Python extension point that LLDB provides). For the
140f46a441bSJonas Devliegherelatter you'll be passed an `SBDebugger`, `SBTarget`, `SBProcess`, `SBThread` or
14151ab17b9SRaphael Isemann`SBFrame` instance and you can use the functions from the "Equivalent" column
142f46a441bSJonas Devlieghereto navigate between them.
143f46a441bSJonas Devlieghere
144f46a441bSJonas DevlieghereAs a rationale for such behavior, consider that lldb can run in a multithreaded
1457b844849SJonas Devlieghereenvironment, and another thread might call the "script" command, changing the
1467b844849SJonas Devliegherevalue out from under you.
1477b844849SJonas Devlieghere
1487b844849SJonas DevlieghereTo get started with these objects and LLDB scripting, please note that almost
1497b844849SJonas Devlieghereall of the lldb Python objects are able to briefly describe themselves when you
1507b844849SJonas Devliegherepass them to the Python print function:
1517b844849SJonas Devlieghere
1527b844849SJonas Devlieghere::
1537b844849SJonas Devlieghere
1547b844849SJonas Devlieghere   (lldb) script
1557b844849SJonas Devlieghere   Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.
1567b844849SJonas Devlieghere   >>> print lldb.debugger
1577b844849SJonas Devlieghere   Debugger (instance: "debugger_1", id: 1)
1587b844849SJonas Devlieghere   >>> print lldb.target
1597b844849SJonas Devlieghere   a.out
1607b844849SJonas Devlieghere   >>> print lldb.process
1617b844849SJonas Devlieghere   SBProcess: pid = 59289, state = stopped, threads = 1, executable = a.out
1627b844849SJonas Devlieghere   >>> print lldb.thread
1637b844849SJonas Devlieghere   SBThread: tid = 0x1f03
1647b844849SJonas Devlieghere   >>> print lldb.frame
1657b844849SJonas Devlieghere   frame #0: 0x0000000100000bb6 a.out main + 54 at main.c:16
1667b844849SJonas Devlieghere
1677b844849SJonas Devlieghere
1687b844849SJonas DevlieghereRunning a python script when a breakpoint gets hit
1697b844849SJonas Devlieghere--------------------------------------------------
1707b844849SJonas Devlieghere
1717b844849SJonas DevlieghereOne very powerful use of the lldb Python API is to have a python script run
1727b844849SJonas Devliegherewhen a breakpoint gets hit. Adding python scripts to breakpoints provides a way
1737b844849SJonas Devlieghereto create complex breakpoint conditions and also allows for smart logging and
1747b844849SJonas Devliegheredata gathering.
1757b844849SJonas Devlieghere
1767b844849SJonas DevlieghereWhen your process hits a breakpoint to which you have attached some python
1777b844849SJonas Devliegherecode, the code is executed as the body of a function which takes three
1787b844849SJonas Devliegherearguments:
1797b844849SJonas Devlieghere
1807b844849SJonas Devlieghere::
1817b844849SJonas Devlieghere
182483ec136SJim Ingham  def breakpoint_function_wrapper(frame, bp_loc, internal_dict):
1837b844849SJonas Devlieghere     # Your code goes here
1847b844849SJonas Devlieghere
185365b186cSJim Inghamor:
1867b844849SJonas Devlieghere
187365b186cSJim Ingham::
188365b186cSJim Ingham
189483ec136SJim Ingham  def breakpoint_function_wrapper(frame, bp_loc, extra_args, internal_dict):
190365b186cSJim Ingham     # Your code goes here
191365b186cSJim Ingham
192365b186cSJim Ingham
193483ec136SJim Ingham+-------------------+-------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------+
1947b844849SJonas Devlieghere| Argument          | Type                          | Description                                                                                                                               |
195483ec136SJim Ingham+-------------------+-------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------+
19651ab17b9SRaphael Isemann| ``frame``         | `lldb.SBFrame`                | The current stack frame where the breakpoint got hit.                                                                                     |
1977b844849SJonas Devlieghere|                   |                               | The object will always be valid.                                                                                                          |
19851ab17b9SRaphael Isemann|                   |                               | This ``frame`` argument might *not* match the currently selected stack frame found in the `lldb` module global variable ``lldb.frame``.   |
199483ec136SJim Ingham+-------------------+-------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------+
20051ab17b9SRaphael Isemann| ``bp_loc``        | `lldb.SBBreakpointLocation`   | The breakpoint location that just got hit. Breakpoints are represented by `lldb.SBBreakpoint`                                             |
2017b844849SJonas Devlieghere|                   |                               | objects. These breakpoint objects can have one or more locations. These locations                                                         |
202f46a441bSJonas Devlieghere|                   |                               | are represented by `lldb.SBBreakpointLocation` objects.                                                                                   |
203483ec136SJim Ingham+-------------------+-------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------+
20451ab17b9SRaphael Isemann| ``extra_args``    | `lldb.SBStructuredData`       | ``Optional`` If your breakpoint callback function takes this extra parameter, then when the callback gets added to a breakpoint, its      |
205365b186cSJim Ingham|                   |                               | contents can parametrize this use of the callback.  For instance, instead of writing a callback that stops when the caller is "Foo",      |
20651ab17b9SRaphael Isemann|                   |                               | you could take the function name from a field in the ``extra_args``, making the callback more general.  The ``-k`` and ``-v`` options     |
20751ab17b9SRaphael Isemann|                   |                               | to ``breakpoint command add`` will be passed as a Dictionary in the ``extra_args`` parameter, or you can provide it with the SB API's.    |
208483ec136SJim Ingham+-------------------+-------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------+
20951ab17b9SRaphael Isemann| ``internal_dict`` | ``dict``                      | The python session dictionary as a standard python dictionary object.                                                                     |
210483ec136SJim Ingham+-------------------+-------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------+
2117b844849SJonas Devlieghere
2127b844849SJonas DevlieghereOptionally, a Python breakpoint command can return a value. Returning False
2137b844849SJonas Devliegheretells LLDB that you do not want to stop at the breakpoint. Any other return
2147b844849SJonas Devliegherevalue (including None or leaving out the return statement altogether) is akin
2157b844849SJonas Devlieghereto telling LLDB to actually stop at the breakpoint. This can be useful in
2167b844849SJonas Devliegheresituations where a breakpoint only needs to stop the process when certain
2177b844849SJonas Devlieghereconditions are met, and you do not want to inspect the program state manually
2187b844849SJonas Devlieghereat every stop and then continue.
2197b844849SJonas Devlieghere
2207b844849SJonas DevlieghereAn example will show how simple it is to write some python code and attach it
2217b844849SJonas Devlieghereto a breakpoint. The following example will allow you to track the order in
2227b844849SJonas Devliegherewhich the functions in a given shared library are first executed during one run
2237b844849SJonas Devlieghereof your program. This is a simple method to gather an order file which can be
2247b844849SJonas Devlieghereused to optimize function placement within a binary for execution locality.
2257b844849SJonas Devlieghere
2267b844849SJonas DevlieghereWe do this by setting a regular expression breakpoint that will match every
2277b844849SJonas Devliegherefunction in the shared library. The regular expression '.' will match any
2287b844849SJonas Devliegherestring that has at least one character in it, so we will use that. This will
2297b844849SJonas Devlieghereresult in one lldb.SBBreakpoint object that contains an
2307b844849SJonas Devliegherelldb.SBBreakpointLocation object for each function. As the breakpoint gets hit,
2317b844849SJonas Devliegherewe use a counter to track the order in which the function at this particular
2327b844849SJonas Devliegherebreakpoint location got hit. Since our code is passed the location that was
2337b844849SJonas Devliegherehit, we can get the name of the function from the location, disable the
2347b844849SJonas Devliegherelocation so we won't count this function again; then log some info and continue
2357b844849SJonas Devliegherethe process.
2367b844849SJonas Devlieghere
2377b844849SJonas DevlieghereNote we also have to initialize our counter, which we do with the simple
2387b844849SJonas Devlieghereone-line version of the script command.
2397b844849SJonas Devlieghere
2407b844849SJonas DevlieghereHere is the code:
2417b844849SJonas Devlieghere
2427b844849SJonas Devlieghere::
2437b844849SJonas Devlieghere
2447b844849SJonas Devlieghere   (lldb) breakpoint set --func-regex=. --shlib=libfoo.dylib
2457b844849SJonas Devlieghere   Breakpoint created: 1: regex = '.', module = libfoo.dylib, locations = 223
2467b844849SJonas Devlieghere   (lldb) script counter = 0
2477b844849SJonas Devlieghere   (lldb) breakpoint command add --script-type python 1
2487b844849SJonas Devlieghere   Enter your Python command(s). Type 'DONE' to end.
2497b844849SJonas Devlieghere   > # Increment our counter.  Since we are in a function, this must be a global python variable
2507b844849SJonas Devlieghere   > global counter
2517b844849SJonas Devlieghere   > counter += 1
2527b844849SJonas Devlieghere   > # Get the name of the function
2537b844849SJonas Devlieghere   > name = frame.GetFunctionName()
2547b844849SJonas Devlieghere   > # Print the order and the function name
2557b844849SJonas Devlieghere   > print '[%i] %s' % (counter, name)
2567b844849SJonas Devlieghere   > # Disable the current breakpoint location so it doesn't get hit again
2577b844849SJonas Devlieghere   > bp_loc.SetEnabled(False)
2587b844849SJonas Devlieghere   > # No need to stop here
2597b844849SJonas Devlieghere   > return False
2607b844849SJonas Devlieghere   > DONE
2617b844849SJonas Devlieghere
2627b844849SJonas DevlieghereThe breakpoint command add command above attaches a python script to breakpoint 1. To remove the breakpoint command:
2637b844849SJonas Devlieghere
2647b844849SJonas Devlieghere::
2657b844849SJonas Devlieghere
2667b844849SJonas Devlieghere   (lldb) breakpoint command delete 1
2677b844849SJonas Devlieghere
2687b844849SJonas Devlieghere
2697b844849SJonas DevlieghereUsing the python api's to create custom breakpoints
2707b844849SJonas Devlieghere---------------------------------------------------
2717b844849SJonas Devlieghere
2727b844849SJonas Devlieghere
2737b844849SJonas DevlieghereAnother use of the Python API's in lldb is to create a custom breakpoint
2747b844849SJonas Devlieghereresolver. This facility was added in r342259.
2757b844849SJonas Devlieghere
2767b844849SJonas DevlieghereIt allows you to provide the algorithm which will be used in the breakpoint's
2777b844849SJonas Devliegheresearch of the space of the code in a given Target to determine where to set the
2787b844849SJonas Devliegherebreakpoint locations - the actual places where the breakpoint will trigger. To
2797b844849SJonas Devlieghereunderstand how this works you need to know a little about how lldb handles
2807b844849SJonas Devliegherebreakpoints.
2817b844849SJonas Devlieghere
2827b844849SJonas DevlieghereIn lldb, a breakpoint is composed of three parts: the Searcher, the Resolver,
2837b844849SJonas Devlieghereand the Stop Options. The Searcher and Resolver cooperate to determine how
2847b844849SJonas Devliegherebreakpoint locations are set and differ between each breakpoint type. Stop
2857b844849SJonas Devlieghereoptions determine what happens when a location triggers and includes the
2867b844849SJonas Devliegherecommands, conditions, ignore counts, etc. Stop options are common between all
2877b844849SJonas Devliegherebreakpoint types, so for our purposes only the Searcher and Resolver are
2887b844849SJonas Devlieghererelevant.
2897b844849SJonas Devlieghere
2907b844849SJonas DevlieghereThe Searcher's job is to traverse in a structured way the code in the current
2917b844849SJonas Devliegheretarget. It proceeds from the Target, to search all the Modules in the Target,
2927b844849SJonas Devliegherein each Module it can recurse into the Compile Units in that module, and within
2937b844849SJonas Devlieghereeach Compile Unit it can recurse over the Functions it contains.
2947b844849SJonas Devlieghere
2957b844849SJonas DevlieghereThe Searcher can be provided with a SearchFilter that it will use to restrict
2967b844849SJonas Devliegherethis search. For instance, if the SearchFilter specifies a list of Modules, the
2977b844849SJonas DevlieghereSearcher will not recurse into Modules that aren't on the list. When you pass
2987b844849SJonas Devliegherethe -s modulename flag to break set you are creating a Module-based search
2997b844849SJonas Devliegherefilter. When you pass -f filename.c to break set -n you are creating a file
3007b844849SJonas Devliegherebased search filter. If neither of these is specified, the breakpoint will have
3017b844849SJonas Devliegherea no-op search filter, so all parts of the program are searched and all
3027b844849SJonas Devliegherelocations accepted.
3037b844849SJonas Devlieghere
3047b844849SJonas DevlieghereThe Resolver has two functions. The most important one is the callback it
3057b844849SJonas Devlieghereprovides. This will get called at the appropriate time in the course of the
3067b844849SJonas Devliegheresearch. The callback is where the job of adding locations to the breakpoint
3077b844849SJonas Devliegheregets done.
3087b844849SJonas Devlieghere
3097b844849SJonas DevlieghereThe other function is specifying to the Searcher at what depth in the above
3107b844849SJonas Devliegheredescribed recursion it wants to be called. Setting a search depth also provides
3117b844849SJonas Devliegherea stop for the recursion. For instance, if you request a Module depth search,
3127b844849SJonas Devliegherethen the callback will be called for each Module as it gets added to the
3137b844849SJonas DevlieghereTarget, but the searcher will not recurse into the Compile Units in the module.
3147b844849SJonas Devlieghere
31536597e47SBruce MitchenerOne other slight subtlety is that the depth at which you get called back is not
31636597e47SBruce Mitchenernecessarily the depth at which the SearchFilter is specified. For instance,
3177b844849SJonas Devlieghereif you are doing symbol searches, it is convenient to use the Module depth for
3187b844849SJonas Devliegherethe search, since symbols are stored in the module. But the SearchFilter might
3197b844849SJonas Devliegherespecify some subset of CompileUnits, so not all the symbols you might find in
3207b844849SJonas Devlieghereeach module will pass the search. You don't need to handle this situation
3217b844849SJonas Devlieghereyourself, since SBBreakpoint::AddLocation will only add locations that pass the
3227b844849SJonas DevlieghereSearch Filter. This API returns an SBError to inform you whether your location
3237b844849SJonas Devliegherewas added.
3247b844849SJonas Devlieghere
3257b844849SJonas DevlieghereWhen the breakpoint is originally created, its Searcher will process all the
3267b844849SJonas Devliegherecurrently loaded modules. The Searcher will also visit any new modules as they
3277b844849SJonas Devlieghereare added to the target. This happens, for instance, when a new shared library
3287b844849SJonas Devliegheregets added to the target in the course of running, or on rerunning if any of
3297b844849SJonas Devliegherethe currently loaded modules have been changed. Note, in the latter case, all
3307b844849SJonas Devliegherethe locations set in the old module will get deleted and you will be asked to
3317b844849SJonas Devlieghererecreate them in the new version of the module when your callback gets called
3327b844849SJonas Devliegherewith that module. For this reason, you shouldn't try to manage the locations
3337b844849SJonas Devlieghereyou add to the breakpoint yourself. Note that the Breakpoint takes care of
3347b844849SJonas Devliegherededuplicating equal addresses in AddLocation, so you shouldn't need to worry
3357b844849SJonas Devlieghereabout that anyway.
3367b844849SJonas Devlieghere
3377b844849SJonas DevlieghereAt present, when adding a scripted Breakpoint type, you can only provide a
3387b844849SJonas Devliegherecustom Resolver, not a custom SearchFilter.
3397b844849SJonas Devlieghere
3407b844849SJonas DevlieghereThe custom Resolver is provided as a Python class with the following methods:
3417b844849SJonas Devlieghere
3422f67cbb6SJonas Devlieghere+--------------------+---------------------------------------+------------------------------------------------------------------------------------------------------------------+
3437b844849SJonas Devlieghere| Name               | Arguments                             | Description                                                                                                      |
3442f67cbb6SJonas Devlieghere+--------------------+---------------------------------------+------------------------------------------------------------------------------------------------------------------+
34551ab17b9SRaphael Isemann| ``__init__``       | ``bkpt``:`lldb.SBBreakpoint`          | This is the constructor for the new Resolver.                                                                    |
34651ab17b9SRaphael Isemann|                    | ``extra_args``:`lldb.SBStructuredData`|                                                                                                                  |
3477b844849SJonas Devlieghere|                    |                                       |                                                                                                                  |
34851ab17b9SRaphael Isemann|                    |                                       | ``bkpt`` is the breakpoint owning this Resolver.                                                                 |
3497b844849SJonas Devlieghere|                    |                                       |                                                                                                                  |
3507b844849SJonas Devlieghere|                    |                                       |                                                                                                                  |
35151ab17b9SRaphael Isemann|                    |                                       | ``extra_args`` is an `SBStructuredData` object that the user can pass in when creating instances of this         |
3527b844849SJonas Devlieghere|                    |                                       | breakpoint.  It is not required, but is quite handy.  For instance if you were implementing a breakpoint on some |
3537b844849SJonas Devlieghere|                    |                                       | symbol name, you could write a generic symbol name based Resolver, and then allow the user to pass               |
3547b844849SJonas Devlieghere|                    |                                       | in the particular symbol in the extra_args                                                                       |
3552f67cbb6SJonas Devlieghere+--------------------+---------------------------------------+------------------------------------------------------------------------------------------------------------------+
35651ab17b9SRaphael Isemann| ``__callback__``   | ``sym_ctx``:`lldb.SBSymbolContext`    | This is the Resolver callback.                                                                                   |
35751ab17b9SRaphael Isemann|                    |                                       | The ``sym_ctx`` argument will be filled with the current stage                                                   |
3587b844849SJonas Devlieghere|                    |                                       | of the search.                                                                                                   |
3597b844849SJonas Devlieghere|                    |                                       |                                                                                                                  |
3607b844849SJonas Devlieghere|                    |                                       |                                                                                                                  |
3617b844849SJonas Devlieghere|                    |                                       | For instance, if you asked for a search depth of lldb.eSearchDepthCompUnit, then the                             |
3627b844849SJonas Devlieghere|                    |                                       | target, module and compile_unit fields of the sym_ctx will be filled.  The callback should look just in the      |
36351ab17b9SRaphael Isemann|                    |                                       | context passed in ``sym_ctx`` for new locations.  If the callback finds an address of interest, it               |
36451ab17b9SRaphael Isemann|                    |                                       | can add it to the breakpoint with the `SBBreakpoint.AddLocation` method, using the breakpoint passed             |
36551ab17b9SRaphael Isemann|                    |                                       | in to the ``__init__`` method.                                                                                   |
3662f67cbb6SJonas Devlieghere+--------------------+---------------------------------------+------------------------------------------------------------------------------------------------------------------+
36751ab17b9SRaphael Isemann| ``__get_depth__``  | ``None``                              | Specify the depth at which you wish your callback to get called.  The currently supported options are:           |
3687b844849SJonas Devlieghere|                    |                                       |                                                                                                                  |
36951ab17b9SRaphael Isemann|                    |                                       | `lldb.eSearchDepthModule`                                                                                        |
37051ab17b9SRaphael Isemann|                    |                                       | `lldb.eSearchDepthCompUnit`                                                                                      |
37151ab17b9SRaphael Isemann|                    |                                       | `lldb.eSearchDepthFunction`                                                                                      |
3727b844849SJonas Devlieghere|                    |                                       |                                                                                                                  |
3737b844849SJonas Devlieghere|                    |                                       | For instance, if you are looking                                                                                 |
3747b844849SJonas Devlieghere|                    |                                       | up symbols, which are stored at the Module level, you will want to get called back module by module.             |
375f46a441bSJonas Devlieghere|                    |                                       | So you would want to return `lldb.eSearchDepthModule`.  This method is optional.  If not provided the search     |
3767b844849SJonas Devlieghere|                    |                                       | will be done at Module depth.                                                                                    |
3772f67cbb6SJonas Devlieghere+--------------------+---------------------------------------+------------------------------------------------------------------------------------------------------------------+
37887990fd8SDave Lee| ``get_short_help`` | ``None``                              | This is an optional method.  If provided, the returned string will be printed at the beginning of                |
3797b844849SJonas Devlieghere|                    |                                       | the description for this breakpoint.                                                                             |
3802f67cbb6SJonas Devlieghere+--------------------+---------------------------------------+------------------------------------------------------------------------------------------------------------------+
3817b844849SJonas Devlieghere
3827b844849SJonas DevlieghereTo define a new breakpoint command defined by this class from the lldb command
3837b844849SJonas Devlieghereline, use the command:
3847b844849SJonas Devlieghere
3857b844849SJonas Devlieghere::
3867b844849SJonas Devlieghere
3877b844849SJonas Devlieghere  (lldb) breakpoint set -P MyModule.MyResolverClass
3887b844849SJonas Devlieghere
3897b844849SJonas DevlieghereYou can also populate the extra_args SBStructuredData with a dictionary of
3907b844849SJonas Devliegherekey/value pairs with:
3917b844849SJonas Devlieghere
3927b844849SJonas Devlieghere::
3937b844849SJonas Devlieghere
3947b844849SJonas Devlieghere  (lldb) breakpoint set -P MyModule.MyResolverClass -k key_1 -v value_1 -k key_2 -v value_2
3957b844849SJonas Devlieghere
3967b844849SJonas DevlieghereAlthough you can't write a scripted SearchFilter, both the command line and the
3977b844849SJonas DevlieghereSB API's for adding a scripted resolver allow you to specify a SearchFilter
3987b844849SJonas Devlieghererestricted to certain modules or certain compile units. When using the command
3997b844849SJonas Devlieghereline to create the resolver, you can specify a Module specific SearchFilter by
4007b844849SJonas Devliegherepassing the -s ModuleName option - which can be specified multiple times. You
4017b844849SJonas Devliegherecan also specify a SearchFilter restricted to certain compile units by passing
4027b844849SJonas Devliegherein the -f CompUnitName option. This can also be specified more than once. And
4037b844849SJonas Devlieghereyou can mix the two to specify "this comp unit in this module". So, for
4047b844849SJonas Devlieghereinstance,
4057b844849SJonas Devlieghere
4067b844849SJonas Devlieghere::
4077b844849SJonas Devlieghere
4087b844849SJonas Devlieghere  (lldb) breakpoint set -P MyModule.MyResolverClass -s a.out
4097b844849SJonas Devlieghere
4107b844849SJonas Devliegherewill use your resolver, but will only recurse into or accept new locations in
4117b844849SJonas Devliegherethe module a.out.
4127b844849SJonas Devlieghere
4137b844849SJonas DevlieghereAnother option for creating scripted breakpoints is to use the
4147b844849SJonas DevlieghereSBTarget.CreateBreakpointFromScript API. This one has the advantage that you
4157b844849SJonas Devliegherecan pass in an arbitrary SBStructuredData object, so you can create more
4167b844849SJonas Devliegherecomplex parametrizations. SBStructuredData has a handy SetFromJSON method which
4177b844849SJonas Devlieghereyou can use for this purpose. Your __init__ function gets passed this
4187b844849SJonas DevlieghereSBStructuredData object. This API also allows you to directly provide the list
4197b844849SJonas Devlieghereof Modules and the list of CompileUnits that will make up the SearchFilter. If
4207b844849SJonas Devlieghereyou pass in empty lists, the breakpoint will use the default "search
4217b844849SJonas Devlieghereeverywhere,accept everything" filter.
4227b844849SJonas Devlieghere
4237b844849SJonas DevlieghereUsing the python API' to create custom stepping logic
4247b844849SJonas Devlieghere-----------------------------------------------------
4257b844849SJonas Devlieghere
4267b844849SJonas DevlieghereA slightly esoteric use of the Python API's is to construct custom stepping
4277b844849SJonas Devliegheretypes. LLDB's stepping is driven by a stack of "thread plans" and a fairly
4287b844849SJonas Devliegheresimple state machine that runs the plans. You can create a Python class that
4297b844849SJonas Devlieghereworks as a thread plan, and responds to the requests the state machine makes to
4307b844849SJonas Devlieghererun its operations.
4317b844849SJonas Devlieghere
4327b844849SJonas DevlieghereThere is a longer discussion of scripted thread plans and the state machine,
4337b844849SJonas Devlieghereand several interesting examples of their use in:
4347b844849SJonas Devlieghere
43594fac81fSxguptahttps://github.com/llvm/llvm-project/blob/main/lldb/examples/python/scripted_step.py
4367b844849SJonas Devlieghere
4377b844849SJonas DevlieghereAnd for a MUCH fuller discussion of the whole state machine, see:
4387b844849SJonas Devlieghere
43994fac81fSxguptahttps://github.com/llvm/llvm-project/blob/main/lldb/include/lldb/Target/ThreadPlan.h
4407b844849SJonas Devlieghere
4417b844849SJonas DevlieghereIf you are reading those comments it is useful to know that scripted thread
44204cbfa95SQuinn Phamplans are set to be "ControllingPlans", and not "OkayToDiscard".
4437b844849SJonas Devlieghere
4447b844849SJonas DevlieghereTo implement a scripted step, you define a python class that has the following
4457b844849SJonas Devliegheremethods:
4467b844849SJonas Devlieghere
4477b844849SJonas Devlieghere+-------------------+------------------------------------+---------------------------------------------------------------------------------------+
4487b844849SJonas Devlieghere| Name              | Arguments                          | Description                                                                           |
4497b844849SJonas Devlieghere+-------------------+------------------------------------+---------------------------------------------------------------------------------------+
45051ab17b9SRaphael Isemann| ``__init__``      | ``thread_plan``:`lldb.SBThreadPlan`| This is the underlying `SBThreadPlan` that is pushed onto the plan stack.             |
4517b844849SJonas Devlieghere|                   |                                    | You will want to store this away in an ivar.  Also, if you are going to               |
4527b844849SJonas Devlieghere|                   |                                    | use one of the canned thread plans, you can queue it at this point.                   |
4537b844849SJonas Devlieghere+-------------------+------------------------------------+---------------------------------------------------------------------------------------+
45451ab17b9SRaphael Isemann| ``explains_stop`` | ``event``: `lldb.SBEvent`          | Return True if this stop is part of your thread plans logic, false otherwise.         |
4557b844849SJonas Devlieghere+-------------------+------------------------------------+---------------------------------------------------------------------------------------+
45651ab17b9SRaphael Isemann| ``is_stale``      | ``None``                           | If your plan is no longer relevant (for instance, you were                            |
4577b844849SJonas Devlieghere|                   |                                    | stepping in a particular stack frame, but some other operation                        |
4587b844849SJonas Devlieghere|                   |                                    | pushed that frame off the stack) return True and your plan will                       |
4597b844849SJonas Devlieghere|                   |                                    | get popped.                                                                           |
4607b844849SJonas Devlieghere+-------------------+------------------------------------+---------------------------------------------------------------------------------------+
46151ab17b9SRaphael Isemann| ``should_step``   | ``None``                           | Return ``True`` if you want lldb to instruction step one instruction,                 |
4627b844849SJonas Devlieghere|                   |                                    | or False to continue till the next breakpoint is hit.                                 |
4637b844849SJonas Devlieghere+-------------------+------------------------------------+---------------------------------------------------------------------------------------+
46451ab17b9SRaphael Isemann| ``should_stop``   | ``event``: `lldb.SBEvent`          | If your plan wants to stop and return control to the user at this point, return True. |
4657b844849SJonas Devlieghere|                   |                                    | If your plan is done at this point, call SetPlanComplete on your                      |
4667b844849SJonas Devlieghere|                   |                                    | thread plan instance.                                                                 |
4677b844849SJonas Devlieghere|                   |                                    | Also, do any work you need here to set up the next stage of stepping.                 |
4687b844849SJonas Devlieghere+-------------------+------------------------------------+---------------------------------------------------------------------------------------+
4697b844849SJonas Devlieghere
4707b844849SJonas DevlieghereTo use this class to implement a step, use the command:
4717b844849SJonas Devlieghere
4727b844849SJonas Devlieghere::
4737b844849SJonas Devlieghere
4747b844849SJonas Devlieghere  (lldb) thread step-scripted -C MyModule.MyStepPlanClass
4757b844849SJonas Devlieghere
4767b844849SJonas DevlieghereOr use the SBThread.StepUsingScriptedThreadPlan API. The SBThreadPlan passed
4777b844849SJonas Devlieghereinto your __init__ function can also push several common plans (step
4787b844849SJonas Devliegherein/out/over and run-to-address) in front of itself on the stack, which can be
4797b844849SJonas Devlieghereused to compose more complex stepping operations. When you use subsidiary plans
4807b844849SJonas Devlieghereyour explains_stop and should_stop methods won't get called until the
4817b844849SJonas Devliegheresubsidiary plan is done, or the process stops for an event the subsidiary plan
4827b844849SJonas Devliegheredoesn't explain. For instance, step over plans don't explain a breakpoint hit
4837b844849SJonas Devliegherewhile performing the step-over.
4847b844849SJonas Devlieghere
4857b844849SJonas Devlieghere
4867b844849SJonas DevlieghereCreate a new lldb command using a Python function
4877b844849SJonas Devlieghere-------------------------------------------------
4887b844849SJonas Devlieghere
4897b844849SJonas DevliegherePython functions can be used to create new LLDB command interpreter commands,
4907b844849SJonas Devliegherewhich will work like all the natively defined lldb commands. This provides a
4917b844849SJonas Devliegherevery flexible and easy way to extend LLDB to meet your debugging requirements.
4927b844849SJonas Devlieghere
4937b844849SJonas DevlieghereTo write a python function that implements a new LLDB command define the
494b6dfaf4cSjiminghamfunction to take five arguments as follows:
4957b844849SJonas Devlieghere
4967b844849SJonas Devlieghere::
4977b844849SJonas Devlieghere
498b6dfaf4cSjimingham  def command_function(debugger, command, exe_ctx, result, internal_dict):
4997b844849SJonas Devlieghere      # Your code goes here
5007b844849SJonas Devlieghere
501b6dfaf4cSjiminghamThe meaning of the arguments is given in the table below.
502b6dfaf4cSjimingham
503b6dfaf4cSjiminghamIf you provide a Python docstring in your command function LLDB will use it
504b6dfaf4cSjiminghamwhen providing "long help" for your command, as in:
5057b844849SJonas Devlieghere
5067b844849SJonas Devlieghere::
5077b844849SJonas Devlieghere
5087b844849SJonas Devlieghere  def command_function(debugger, command, result, internal_dict):
5097b844849SJonas Devlieghere      """This command takes a lot of options and does many fancy things"""
5107b844849SJonas Devlieghere      # Your code goes here
5117b844849SJonas Devlieghere
512b6dfaf4cSjiminghamthough providing help can also be done programmatically (see below).
5137b844849SJonas Devlieghere
514b6dfaf4cSjiminghamPrior to lldb 3.5.2 (April 2015), LLDB Python command definitions didn't take the SBExecutionContext
515b6dfaf4cSjiminghamargument. So you may still see commands where the command definition is:
5167b844849SJonas Devlieghere
5177b844849SJonas Devlieghere::
5187b844849SJonas Devlieghere
519b6dfaf4cSjimingham  def command_function(debugger, command, result, internal_dict):
5207b844849SJonas Devlieghere      # Your code goes here
5217b844849SJonas Devlieghere
522b6dfaf4cSjiminghamUsing this form is strongly discouraged because it can only operate on the "currently selected"
523b6dfaf4cSjiminghamtarget, process, thread, frame.  The command will behave as expected when run
524b6dfaf4cSjiminghamdirectly on the command line.  But if the command is used in a stop-hook, breakpoint
525b6dfaf4cSjiminghamcallback, etc. where the response to the callback determines whether we will select
526b6dfaf4cSjiminghamthis or that particular process/frame/thread, the global "currently selected"
527b6dfaf4cSjiminghamentity is not necessarily the one the callback is meant to handle.  In that case, this
528b6dfaf4cSjiminghamcommand definition form can't do the right thing.
529b6dfaf4cSjimingham
5307b844849SJonas Devlieghere+-------------------+--------------------------------+----------------------------------------------------------------------------------------------------------------------------------+
5317b844849SJonas Devlieghere| Argument          | Type                           | Description                                                                                                                      |
5327b844849SJonas Devlieghere+-------------------+--------------------------------+----------------------------------------------------------------------------------------------------------------------------------+
53351ab17b9SRaphael Isemann| ``debugger``      | `lldb.SBDebugger`              | The current debugger object.                                                                                                     |
5347b844849SJonas Devlieghere+-------------------+--------------------------------+----------------------------------------------------------------------------------------------------------------------------------+
53551ab17b9SRaphael Isemann| ``command``       | ``python string``              | A python string containing all arguments for your command. If you need to chop up the arguments                                  |
53651ab17b9SRaphael Isemann|                   |                                | try using the ``shlex`` module's ``shlex.split(command)`` to properly extract the                                                |
5377b844849SJonas Devlieghere|                   |                                | arguments.                                                                                                                       |
5387b844849SJonas Devlieghere+-------------------+--------------------------------+----------------------------------------------------------------------------------------------------------------------------------+
53951ab17b9SRaphael Isemann| ``exe_ctx``       | `lldb.SBExecutionContext`      | An execution context object carrying around information on the inferior process' context in which the command is expected to act |
5407b844849SJonas Devlieghere|                   |                                |                                                                                                                                  |
54190148db0SDave Lee|                   |                                | *Optional since lldb 3.5.2, unavailable before*                                                                                  |
5427b844849SJonas Devlieghere+-------------------+--------------------------------+----------------------------------------------------------------------------------------------------------------------------------+
54351ab17b9SRaphael Isemann| ``result``        | `lldb.SBCommandReturnObject`   | A return object which encapsulates success/failure information for the command and output text                                   |
5447b844849SJonas Devlieghere|                   |                                | that needs to be printed as a result of the command. The plain Python "print" command also works but                             |
5457b844849SJonas Devlieghere|                   |                                | text won't go in the result by default (it is useful as a temporary logging facility).                                           |
5467b844849SJonas Devlieghere+-------------------+--------------------------------+----------------------------------------------------------------------------------------------------------------------------------+
54751ab17b9SRaphael Isemann| ``internal_dict`` | ``python dict object``         | The dictionary for the current embedded script session which contains all variables                                              |
5487b844849SJonas Devlieghere|                   |                                | and functions.                                                                                                                   |
5497b844849SJonas Devlieghere+-------------------+--------------------------------+----------------------------------------------------------------------------------------------------------------------------------+
5507b844849SJonas Devlieghere
55190148db0SDave LeeSince lldb 3.7, Python commands can also be implemented by means of a class
55290148db0SDave Leewhich should implement the following interface:
5537b844849SJonas Devlieghere
554*04b443e7Sjimingham.. code-block:: python
5557b844849SJonas Devlieghere
5567b844849SJonas Devlieghere  class CommandObjectType:
557483ec136SJim Ingham      def __init__(self, debugger, internal_dict):
5587b844849SJonas Devlieghere          this call should initialize the command with respect to the command interpreter for the passed-in debugger
5597b844849SJonas Devlieghere      def __call__(self, debugger, command, exe_ctx, result):
5607b844849SJonas Devlieghere          this is the actual bulk of the command, akin to Python command functions
5617b844849SJonas Devlieghere      def get_short_help(self):
5627b844849SJonas Devlieghere          this call should return the short help text for this command[1]
5637b844849SJonas Devlieghere      def get_long_help(self):
5647b844849SJonas Devlieghere          this call should return the long help text for this command[1]
565615bd9eeSjimingham      def get_flags(self):
566615bd9eeSjimingham          this will be called when the command is added to the command interpreter,
567615bd9eeSjimingham          and should return a flag field made from or-ing together the appropriate
568615bd9eeSjimingham          elements of the lldb.CommandFlags enum to specify the requirements of this command.
569615bd9eeSjimingham          The CommandInterpreter will make sure all these requirements are met, and will
570615bd9eeSjimingham          return the standard lldb error if they are not.[1]
57177d131edSjimingham      def get_repeat_command(self, command):
57277d131edSjimingham          The auto-repeat command is what will get executed when the user types just
57377d131edSjimingham          a return at the next prompt after this command is run.  Even if your command
57477d131edSjimingham          was run because it was specified as a repeat command, that invocation will still
57577d131edSjimingham          get asked for IT'S repeat command, so you can chain a series of repeats, for instance
57677d131edSjimingham          to implement a pager.
57777d131edSjimingham
57877d131edSjimingham          The command argument is the command that is about to be executed.
57977d131edSjimingham
58077d131edSjimingham          If this call returns None, then the ordinary repeat mechanism will be used
58177d131edSjimingham          If this call returns an empty string, then auto-repeat is disabled
58277d131edSjimingham          If this call returns any other string, that will be the repeat command [1]
5837b844849SJonas Devlieghere
5847b844849SJonas Devlieghere[1] This method is optional.
5857b844849SJonas Devlieghere
5867b844849SJonas DevlieghereAs a convenience, you can treat the result object as a Python file object, and
5877b844849SJonas Devliegheresay
5887b844849SJonas Devlieghere
589*04b443e7Sjimingham.. code-block:: python
5907b844849SJonas Devlieghere
5917b844849SJonas Devlieghere  print >>result, "my command does lots of cool stuff"
5927b844849SJonas Devlieghere
5937b844849SJonas DevlieghereSBCommandReturnObject and SBStream both support this file-like behavior by
5947b844849SJonas Devlieghereproviding write() and flush() calls at the Python layer.
5957b844849SJonas Devlieghere
596*04b443e7SjiminghamThe commands that are added using this class definition are what lldb calls
597*04b443e7Sjimingham"raw" commands.  The command interpreter doesn't attempt to parse the command,
598*04b443e7Sjiminghamdoesn't handle option values, neither generating help for them, or their
599*04b443e7Sjiminghamcompletion.  Raw commands are useful when the arguments passed to the command
600*04b443e7Sjiminghamare unstructured, and having to protect them against lldb command parsing would
601*04b443e7Sjiminghambe onerous.  For instance, "expr" is a raw command.
602*04b443e7Sjimingham
603*04b443e7SjiminghamYou can also add scripted commands that implement the "parsed command", where
604*04b443e7Sjiminghamthe options and their types are specified, as well as the argument and argument
605*04b443e7Sjiminghamtypes.  These commands look and act like the majority of lldb commands, and you
606*04b443e7Sjiminghamcan also add custom completions for the options and/or the arguments if you have
607*04b443e7Sjiminghamspecial needs.
608*04b443e7Sjimingham
609*04b443e7SjiminghamThe easiest way to do this is to derive your new command from the lldb.ParsedCommand
610*04b443e7Sjiminghamclass.  That responds in the same way to the help & repeat command interfaces, and
611*04b443e7Sjiminghamprovides some convenience methods, and most importantly an LLDBOptionValueParser,
612*04b443e7Sjiminghamaccessed throught lldb.ParsedCommand.get_parser().  The parser is used to set
613*04b443e7Sjiminghamyour command definitions, and to retrieve option values in the __call__ method.
614*04b443e7Sjimingham
615*04b443e7SjiminghamTo set up the command definition, implement the ParsedCommand abstract method:
616*04b443e7Sjimingham
617*04b443e7Sjimingham.. code-block:: python
618*04b443e7Sjimingham
619*04b443e7Sjimingham   def setup_command_definition(self):
620*04b443e7Sjimingham
621*04b443e7SjiminghamThis is called when your command is added to lldb.  In this method you add the
622*04b443e7Sjiminghamoptions and their types, the option help strings, etc. to the command using the API:
623*04b443e7Sjimingham
624*04b443e7Sjimingham.. code-block:: python
625*04b443e7Sjimingham
626*04b443e7Sjimingham    def add_option(self, short_option, long_option, help, default,
627*04b443e7Sjimingham                   dest = None, required=False, groups = None,
628*04b443e7Sjimingham                   value_type=lldb.eArgTypeNone, completion_type=None,
629*04b443e7Sjimingham                   enum_values=None):
630*04b443e7Sjimingham        """
631*04b443e7Sjimingham        short_option: one character, must be unique, not required
632*04b443e7Sjimingham        long_option:  no spaces, must be unique, required
633*04b443e7Sjimingham        help:         a usage string for this option, will print in the command help
634*04b443e7Sjimingham        default:      the initial value for this option (if it has a value)
635*04b443e7Sjimingham        dest:         the name of the property that gives you access to the value for
636*04b443e7Sjimingham                      this value.  Defaults to the long option if not provided.
637*04b443e7Sjimingham        required: if true, this option must be provided or the command will error out
638*04b443e7Sjimingham        groups: Which "option groups" does this option belong to.  This can either be
639*04b443e7Sjimingham                a simple list (e.g. [1, 3, 4, 5]) or you can specify ranges by sublists:
640*04b443e7Sjimingham                so [1, [3,5]] is the same as [1, 3, 4, 5].
641*04b443e7Sjimingham        value_type: one of the lldb.eArgType enum values.  Some of the common arg
642*04b443e7Sjimingham                    types also have default completers, which will be applied automatically.
643*04b443e7Sjimingham        completion_type: currently these are values form the lldb.CompletionType enum.	If
644*04b443e7Sjimingham                         you need custom completions, implement	handle_option_argument_completion.
645*04b443e7Sjimingham        enum_values: An array of duples: ["element_name", "element_help"].  If provided,
646*04b443e7Sjimingham                     only one of the enum elements is allowed.  The value will be the
647*04b443e7Sjimingham                     element_name for the chosen enum element as a string.
648*04b443e7Sjimingham        """
649*04b443e7Sjimingham
650*04b443e7SjiminghamSimilarly, you can add argument types to the command:
651*04b443e7Sjimingham
652*04b443e7Sjimingham.. code-block:: python
653*04b443e7Sjimingham
654*04b443e7Sjimingham    def make_argument_element(self, arg_type, repeat = "optional", groups = None):
655*04b443e7Sjimingham        """
656*04b443e7Sjimingham      	arg_type: The argument type, one of the	lldb.eArgType enum values.
657*04b443e7Sjimingham      	repeat:	Choose from the	following options:
658*04b443e7Sjimingham      	      	"plain"	- one value
659*04b443e7Sjimingham      	      	"optional" - zero or more values
660*04b443e7Sjimingham      	      	"plus" - one or	more values
661*04b443e7Sjimingham      	groups:	As with	add_option.
662*04b443e7Sjimingham        """
663*04b443e7Sjimingham
664*04b443e7SjiminghamThen implement the body of the command by defining:
665*04b443e7Sjimingham
666*04b443e7Sjimingham.. code-block:: python
667*04b443e7Sjimingham
668*04b443e7Sjimingham    def __call__(self, debugger, args_array, exe_ctx, result):
669*04b443e7Sjimingham        """This is the command callback.  The option values are
670*04b443e7Sjimingham        provided by the 'dest' properties on the parser.
671*04b443e7Sjimingham
672*04b443e7Sjimingham        args_array: This is the list of arguments provided.
673*04b443e7Sjimingham        exe_ctx: Gives the SBExecutionContext on which the
674*04b443e7Sjimingham                 command should operate.
675*04b443e7Sjimingham        result:  Any results of the command should be
676*04b443e7Sjimingham                 written into this SBCommandReturnObject.
677*04b443e7Sjimingham        """
678*04b443e7Sjimingham
679*04b443e7SjiminghamThis differs from the "raw" command's __call__ in that the arguments are already
680*04b443e7Sjiminghamparsed into the args_array, and the option values are set in the parser, and
681*04b443e7Sjiminghamcan be accessed using their property name.  The LLDBOptionValueParser class has
682*04b443e7Sjiminghama couple of other handy methods:
683*04b443e7Sjimingham
684*04b443e7Sjimingham.. code-block:: python
685*04b443e7Sjimingham    def was_set(self, long_option_name):
686*04b443e7Sjimingham
687*04b443e7Sjiminghamreturns True if the option was specified on the command line.
688*04b443e7Sjimingham
689*04b443e7Sjimingham.. code-block:: python
690*04b443e7Sjimingham
691*04b443e7Sjimingham    def dest_for_option(self, long_option_name):
692*04b443e7Sjimingham    """
693*04b443e7Sjimingham    This will return the value of the dest variable you defined for opt_name.
694*04b443e7Sjimingham    Mostly useful for handle_completion where you get passed the long option.
695*04b443e7Sjimingham    """
696*04b443e7Sjimingham
697*04b443e7Sjiminghamlldb will handle completing your option names, and all your enum values
698*04b443e7Sjiminghamautomatically.  If your option or argument types have associated built-in completers,
699*04b443e7Sjiminghamthen lldb will also handle that completion for you.  But if you have a need for
700*04b443e7Sjiminghamcustom completions, either in your arguments or option values, you can handle
701*04b443e7Sjiminghamcompletion by hand as well.  To handle completion of option value arguments,
702*04b443e7Sjiminghamyour lldb.ParsedCommand subclass should implement:
703*04b443e7Sjimingham
704*04b443e7Sjimingham.. code-block:: python
705*04b443e7Sjimingham
706*04b443e7Sjimingham    def handle_option_argument_completion(self, long_option, cursor_pos):
707*04b443e7Sjimingham    """
708*04b443e7Sjimingham    long_option: The long option name of the option whose value you are
709*04b443e7Sjimingham                 asked to complete.
710*04b443e7Sjimingham    cursor_pos: The cursor position in the value for that option - which
711*04b443e7Sjimingham    you can get from the option parser.
712*04b443e7Sjimingham    """
713*04b443e7Sjimingham
714*04b443e7SjiminghamAnd to handle the completion of arguments:
715*04b443e7Sjimingham
716*04b443e7Sjimingham.. code-block:: python
717*04b443e7Sjimingham
718*04b443e7Sjimingham    def handle_argument_completion(self, args, arg_pos, cursor_pos):
719*04b443e7Sjimingham    """
720*04b443e7Sjimingham    args: A list of the arguments to the command
721*04b443e7Sjimingham    arg_pos: An index into the args list of the argument with the cursor
722*04b443e7Sjimingham    cursor_pos: The cursor position in the arg specified by arg_pos
723*04b443e7Sjimingham    """
724*04b443e7Sjimingham
725*04b443e7SjiminghamWhen either of these API's is called, the command line will have been parsed up to
726*04b443e7Sjiminghamthe word containing the cursor, and any option values set in that part of the command
727*04b443e7Sjiminghamstring are available from the option value parser.  That's useful for instance
728*04b443e7Sjiminghamif you have a --shared-library option that would constrain the completions for,
729*04b443e7Sjiminghamsay, a symbol name option or argument.
730*04b443e7Sjimingham
731*04b443e7SjiminghamThe return value specifies what the completion options are.  You have four
732*04b443e7Sjiminghamchoices:
733*04b443e7Sjimingham
734*04b443e7Sjimingham- `True`: the completion was handled with no completions.
735*04b443e7Sjimingham
736*04b443e7Sjimingham- `False`: the completion was not handled, forward it to the regular
737*04b443e7Sjiminghamcompletion machinery.
738*04b443e7Sjimingham
739*04b443e7Sjimingham- A dictionary with the key: "completion": there is one candidate,
740*04b443e7Sjiminghamwhose value is the value of the "completion" key.  Optionally you can pass a
741*04b443e7Sjimingham"mode" key whose value is either "partial" or "complete".  Return partial if
742*04b443e7Sjiminghamthe "completion" string is a prefix for all the completed value.
743*04b443e7Sjimingham
744*04b443e7SjiminghamFor instance, if the string you are completing is "Test" and the available completions are:
745*04b443e7Sjimingham"Test1", "Test11" and "Test111", you should return the dictionary:
746*04b443e7Sjimingham
747*04b443e7Sjimingham.. code-block:: python
748*04b443e7Sjimingham
749*04b443e7Sjimingham   return {"completion": "Test1", "mode" : "partial"}
750*04b443e7Sjimingham
751*04b443e7Sjiminghamand then lldb will add the "1" at the curson and advance it after the added string,
752*04b443e7Sjiminghamwaiting for more completions.  But if "Test1" is the only completion, return:
753*04b443e7Sjimingham
754*04b443e7Sjimingham.. code-block:: python
755*04b443e7Sjimingham
756*04b443e7Sjimingham   {"completion": "Test1", "mode": "complete"}
757*04b443e7Sjimingham
758*04b443e7Sjiminghamand lldb will add "1 " at the cursor, indicating the command string is complete.
759*04b443e7Sjimingham
760*04b443e7SjiminghamThe default is "complete", you don't need to specify a "mode" in that case.
761*04b443e7Sjimingham
762*04b443e7Sjimingham- A dictionary with the key: "values" whose value is a list of candidate completion
763*04b443e7Sjiminghamstrings.  The command interpreter will present those strings as the available choices.
764*04b443e7SjiminghamYou can optionally include a "descriptions" key, whose value is a parallel array
765*04b443e7Sjiminghamof description strings, and the completion will show the description next to
766*04b443e7Sjiminghameach completion.
767*04b443e7Sjimingham
768*04b443e7Sjimingham
7697b844849SJonas DevlieghereOne other handy convenience when defining lldb command-line commands is the
770*04b443e7Sjiminghamcommand "command script import" which will import a module specified by file
7717b844849SJonas Devliegherepath, so you don't have to change your PYTHONPATH for temporary scripts. It
7727b844849SJonas Devliegherealso has another convenience that if your new script module has a function of
7737b844849SJonas Devliegherethe form:
7747b844849SJonas Devlieghere
775*04b443e7Sjimingham.. code-block python
7767b844849SJonas Devlieghere
7777b844849SJonas Devlieghere  def __lldb_init_module(debugger, internal_dict):
7787b844849SJonas Devlieghere      # Command Initialization code goes here
7797b844849SJonas Devlieghere
7807b844849SJonas Devliegherewhere debugger and internal_dict are as above, that function will get run when
7817b844849SJonas Devliegherethe module is loaded allowing you to add whatever commands you want into the
7827b844849SJonas Devliegherecurrent debugger. Note that this function will only be run when using the LLDB
7831441ffe6SDave Leecommand ``command script import``, it will not get run if anyone imports your
7841441ffe6SDave Leemodule from another module.
7851441ffe6SDave Lee
7861441ffe6SDave LeeThe standard test for ``__main__``, like many python modules do, is useful for
7871441ffe6SDave Leecreating scripts that can be run from the command line. However, for command
7881441ffe6SDave Leeline scripts, the debugger instance must be created manually. Sample code would
7891441ffe6SDave Leelook like:
7907b844849SJonas Devlieghere
791*04b443e7Sjimingham.. code-block:: python
7927b844849SJonas Devlieghere
7937b844849SJonas Devlieghere  if __name__ == '__main__':
7941441ffe6SDave Lee      # Initialize the debugger before making any API calls.
7951441ffe6SDave Lee      lldb.SBDebugger.Initialize()
7967b844849SJonas Devlieghere      # Create a new debugger instance in your module if your module
7977b844849SJonas Devlieghere      # can be run from the command line. When we run a script from
7987b844849SJonas Devlieghere      # the command line, we won't have any debugger object in
7997b844849SJonas Devlieghere      # lldb.debugger, so we can just create it if it will be needed
8001441ffe6SDave Lee      debugger = lldb.SBDebugger.Create()
8011441ffe6SDave Lee
8021441ffe6SDave Lee      # Next, do whatever work this module should do when run as a command.
8031441ffe6SDave Lee      # ...
8041441ffe6SDave Lee
8051441ffe6SDave Lee      # Finally, dispose of the debugger you just made.
8061441ffe6SDave Lee      lldb.SBDebugger.Destroy(debugger)
8077240436cSGabriel Ravier      # Terminate the debug session
8081441ffe6SDave Lee      lldb.SBDebugger.Terminate()
8091441ffe6SDave Lee
8107b844849SJonas Devlieghere
8117b844849SJonas DevlieghereNow we can create a module called ls.py in the file ~/ls.py that will implement
8127b844849SJonas Devliegherea function that can be used by LLDB's python command code:
8137b844849SJonas Devlieghere
814*04b443e7Sjimingham.. code-block:: python
8157b844849SJonas Devlieghere
816a54f160bSHarmen Stoppels  #!/usr/bin/env python
8177b844849SJonas Devlieghere
8187b844849SJonas Devlieghere  import lldb
8197b844849SJonas Devlieghere  import commands
8207b844849SJonas Devlieghere  import optparse
8217b844849SJonas Devlieghere  import shlex
8227b844849SJonas Devlieghere
8237b844849SJonas Devlieghere  def ls(debugger, command, result, internal_dict):
8247b844849SJonas Devlieghere      print >>result, (commands.getoutput('/bin/ls %s' % command))
8257b844849SJonas Devlieghere
8267b844849SJonas Devlieghere  # And the initialization code to add your commands
8277b844849SJonas Devlieghere  def __lldb_init_module(debugger, internal_dict):
8287b844849SJonas Devlieghere      debugger.HandleCommand('command script add -f ls.ls ls')
8297b844849SJonas Devlieghere      print 'The "ls" python command has been installed and is ready for use.'
8307b844849SJonas Devlieghere
8317b844849SJonas DevlieghereNow we can load the module into LLDB and use it
8327b844849SJonas Devlieghere
8337b844849SJonas Devlieghere::
8347b844849SJonas Devlieghere
83559c954f7SShivam Gupta  $ lldb
8367b844849SJonas Devlieghere  (lldb) command script import ~/ls.py
8377b844849SJonas Devlieghere  The "ls" python command has been installed and is ready for use.
8387b844849SJonas Devlieghere  (lldb) ls -l /tmp/
8397b844849SJonas Devlieghere  total 365848
8407b844849SJonas Devlieghere  -rw-r--r--@  1 someuser  wheel         6148 Jan 19 17:27 .DS_Store
8417b844849SJonas Devlieghere  -rw-------   1 someuser  wheel         7331 Jan 19 15:37 crash.log
8427b844849SJonas Devlieghere
843aa7470a1SJim InghamYou can also make "container" commands to organize the commands you are adding to
844aa7470a1SJim Inghamlldb.  Most of the lldb built-in commands structure themselves this way, and using
845aa7470a1SJim Inghama tree structure has the benefit of leaving the one-word command space free for user
846aa7470a1SJim Inghamaliases.  It can also make it easier to find commands if you are adding more than
847aa7470a1SJim Inghama few of them.  Here's a trivial example of adding two "utility" commands into a
848aa7470a1SJim Ingham"my-utilities" container:
849aa7470a1SJim Ingham
850aa7470a1SJim Ingham::
851aa7470a1SJim Ingham
852aa7470a1SJim Ingham  #!/usr/bin/env python
853aa7470a1SJim Ingham
854aa7470a1SJim Ingham  import lldb
855aa7470a1SJim Ingham
856aa7470a1SJim Ingham  def first_utility(debugger, command, result, internal_dict):
857aa7470a1SJim Ingham      print("I am the first utility")
858aa7470a1SJim Ingham
859aa7470a1SJim Ingham  def second_utility(debugger, command, result, internal_dict):
860aa7470a1SJim Ingham      print("I am the second utility")
861aa7470a1SJim Ingham
862aa7470a1SJim Ingham  # And the initialization code to add your commands
863aa7470a1SJim Ingham  def __lldb_init_module(debugger, internal_dict):
864aa7470a1SJim Ingham      debugger.HandleCommand('command container add -h "A container for my utilities" my-utilities')
865aa7470a1SJim Ingham      debugger.HandleCommand('command script add -f my_utilities.first_utility -h "My first utility" my-utilities first')
866aa7470a1SJim Ingham      debugger.HandleCommand('command script add -f my_utilities.second_utility -h "My second utility" my-utilities second')
867aa7470a1SJim Ingham      print('The "my-utilities" python command has been installed and its subcommands are ready for use.')
868aa7470a1SJim Ingham
869aa7470a1SJim InghamThen your new commands are available under the my-utilities node:
870aa7470a1SJim Ingham
871aa7470a1SJim Ingham::
872aa7470a1SJim Ingham
873aa7470a1SJim Ingham  (lldb) help my-utilities
874aa7470a1SJim Ingham  A container for my utilities
875aa7470a1SJim Ingham
876aa7470a1SJim Ingham  Syntax: my-utilities
877aa7470a1SJim Ingham
878aa7470a1SJim Ingham  The following subcommands are supported:
879aa7470a1SJim Ingham
880aa7470a1SJim Ingham      first  -- My first utility  Expects 'raw' input (see 'help raw-input'.)
881aa7470a1SJim Ingham      second -- My second utility  Expects 'raw' input (see 'help raw-input'.)
882aa7470a1SJim Ingham
883aa7470a1SJim Ingham  For more help on any particular subcommand, type 'help <command> <subcommand>'.
884aa7470a1SJim Ingham  (lldb) my-utilities first
885aa7470a1SJim Ingham  I am the first utility
886aa7470a1SJim Ingham
887aa7470a1SJim Ingham
8887b844849SJonas DevlieghereA more interesting template has been created in the source repository that can
8897b844849SJonas Devliegherehelp you to create lldb command quickly:
8907b844849SJonas Devlieghere
89194fac81fSxguptahttps://github.com/llvm/llvm-project/blob/main/lldb/examples/python/cmdtemplate.py
8927b844849SJonas Devlieghere
8937b844849SJonas DevlieghereA commonly required facility is being able to create a command that does some
8947b844849SJonas Devliegheretoken substitution, and then runs a different debugger command (usually, it
8957b844849SJonas Devliegherepo'es the result of an expression evaluated on its argument). For instance,
8967b844849SJonas Devliegheregiven the following program:
8977b844849SJonas Devlieghere
8987b844849SJonas Devlieghere::
8997b844849SJonas Devlieghere
9007b844849SJonas Devlieghere  #import <Foundation/Foundation.h>
9017b844849SJonas Devlieghere  NSString*
9027b844849SJonas Devlieghere  ModifyString(NSString* src)
9037b844849SJonas Devlieghere  {
9047b844849SJonas Devlieghere  	return [src stringByAppendingString:@"foobar"];
9057b844849SJonas Devlieghere  }
9067b844849SJonas Devlieghere
9077b844849SJonas Devlieghere  int main()
9087b844849SJonas Devlieghere  {
9097b844849SJonas Devlieghere  	NSString* aString = @"Hello world";
9107b844849SJonas Devlieghere  	NSString* anotherString = @"Let's be friends";
9117b844849SJonas Devlieghere  	return 1;
9127b844849SJonas Devlieghere  }
9137b844849SJonas Devlieghere
9147b844849SJonas Devlieghereyou may want a pofoo X command, that equates po [ModifyString(X)
9157b844849SJonas DevliegherecapitalizedString]. The following debugger interaction shows how to achieve
9167b844849SJonas Devliegherethat goal:
9177b844849SJonas Devlieghere
9187b844849SJonas Devlieghere::
9197b844849SJonas Devlieghere
9207b844849SJonas Devlieghere  (lldb) script
9217b844849SJonas Devlieghere  Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.
9227b844849SJonas Devlieghere  >>> def pofoo_funct(debugger, command, result, internal_dict):
9237b844849SJonas Devlieghere  ...	cmd = "po [ModifyString(" + command + ") capitalizedString]"
9241441ffe6SDave Lee  ...	debugger.HandleCommand(cmd)
9257b844849SJonas Devlieghere  ...
9267b844849SJonas Devlieghere  >>> ^D
9277b844849SJonas Devlieghere  (lldb) command script add pofoo -f pofoo_funct
9287b844849SJonas Devlieghere  (lldb) pofoo aString
9297b844849SJonas Devlieghere  $1 = 0x000000010010aa00 Hello Worldfoobar
9307b844849SJonas Devlieghere  (lldb) pofoo anotherString
9317b844849SJonas Devlieghere  $2 = 0x000000010010aba0 Let's Be Friendsfoobar
9327b844849SJonas Devlieghere
9337b844849SJonas DevlieghereUsing the lldb.py module in Python
9347b844849SJonas Devlieghere----------------------------------
9357b844849SJonas Devlieghere
9367b844849SJonas DevlieghereLLDB has all of its core code build into a shared library which gets used by
93719ae9d01SAdrian Prantlthe `lldb` command line application. On macOS this shared library is a
9387b844849SJonas Devlieghereframework: LLDB.framework and on other unix variants the program is a shared
9397b844849SJonas Devliegherelibrary: lldb.so. LLDB also provides an lldb.py module that contains the
9407b844849SJonas Devliegherebindings from LLDB into Python. To use the LLDB.framework to create your own
9417b844849SJonas Devliegherestand-alone python programs, you will need to tell python where to look in
9427b844849SJonas Devlieghereorder to find this module. This is done by setting the PYTHONPATH environment
9437b844849SJonas Devliegherevariable, adding a path to the directory that contains the lldb.py python
9447b844849SJonas Devliegheremodule. The lldb driver program has an option to report the path to the lldb
9457b844849SJonas Devliegheremodule. You can use that to point to correct lldb.py:
9467b844849SJonas Devlieghere
9477b844849SJonas DevlieghereFor csh and tcsh:
9487b844849SJonas Devlieghere
9497b844849SJonas Devlieghere::
9507b844849SJonas Devlieghere
9517b844849SJonas Devlieghere  % setenv PYTHONPATH `lldb -P`
9527b844849SJonas Devlieghere
9537b844849SJonas DevlieghereFor sh and bash:
9547b844849SJonas Devlieghere
9557b844849SJonas Devlieghere::
9567b844849SJonas Devlieghere
95759c954f7SShivam Gupta  $ export PYTHONPATH=`lldb -P`
9587b844849SJonas Devlieghere
9597b844849SJonas DevlieghereAlternately, you can append the LLDB Python directory to the sys.path list
9607b844849SJonas Devliegheredirectly in your Python code before importing the lldb module.
9617b844849SJonas Devlieghere
9627b844849SJonas DevlieghereNow your python scripts are ready to import the lldb module. Below is a python
9637b844849SJonas Devliegherescript that will launch a program from the current working directory called
9647b844849SJonas Devlieghere"a.out", set a breakpoint at "main", and then run and hit the breakpoint, and
9657b844849SJonas Devlieghereprint the process, thread and frame objects if the process stopped:
9667b844849SJonas Devlieghere
9677b844849SJonas Devlieghere::
9687b844849SJonas Devlieghere
969a54f160bSHarmen Stoppels  #!/usr/bin/env python
9707b844849SJonas Devlieghere
9717b844849SJonas Devlieghere  import lldb
9727b844849SJonas Devlieghere  import os
9737b844849SJonas Devlieghere
9747b844849SJonas Devlieghere  def disassemble_instructions(insts):
9757b844849SJonas Devlieghere      for i in insts:
9767b844849SJonas Devlieghere          print i
9777b844849SJonas Devlieghere
9787b844849SJonas Devlieghere  # Set the path to the executable to debug
9797b844849SJonas Devlieghere  exe = "./a.out"
9807b844849SJonas Devlieghere
9817b844849SJonas Devlieghere  # Create a new debugger instance
9827b844849SJonas Devlieghere  debugger = lldb.SBDebugger.Create()
9837b844849SJonas Devlieghere
9847b844849SJonas Devlieghere  # When we step or continue, don't return from the function until the process
9857b844849SJonas Devlieghere  # stops. Otherwise we would have to handle the process events ourselves which, while doable is
9867b844849SJonas Devlieghere  #a little tricky.  We do this by setting the async mode to false.
9877b844849SJonas Devlieghere  debugger.SetAsync (False)
9887b844849SJonas Devlieghere
9897b844849SJonas Devlieghere  # Create a target from a file and arch
9907b844849SJonas Devlieghere  print "Creating a target for '%s'" % exe
9917b844849SJonas Devlieghere
9927b844849SJonas Devlieghere  target = debugger.CreateTargetWithFileAndArch (exe, lldb.LLDB_ARCH_DEFAULT)
9937b844849SJonas Devlieghere
9947b844849SJonas Devlieghere  if target:
9957b844849SJonas Devlieghere      # If the target is valid set a breakpoint at main
9967b844849SJonas Devlieghere      main_bp = target.BreakpointCreateByName ("main", target.GetExecutable().GetFilename());
9977b844849SJonas Devlieghere
9987b844849SJonas Devlieghere      print main_bp
9997b844849SJonas Devlieghere
10007b844849SJonas Devlieghere      # Launch the process. Since we specified synchronous mode, we won't return
10017b844849SJonas Devlieghere      # from this function until we hit the breakpoint at main
10027b844849SJonas Devlieghere      process = target.LaunchSimple (None, None, os.getcwd())
10037b844849SJonas Devlieghere
10047b844849SJonas Devlieghere      # Make sure the launch went ok
10057b844849SJonas Devlieghere      if process:
10067b844849SJonas Devlieghere          # Print some simple process info
10077b844849SJonas Devlieghere          state = process.GetState ()
10087b844849SJonas Devlieghere          print process
10097b844849SJonas Devlieghere          if state == lldb.eStateStopped:
10107b844849SJonas Devlieghere              # Get the first thread
10117b844849SJonas Devlieghere              thread = process.GetThreadAtIndex (0)
10127b844849SJonas Devlieghere              if thread:
10137b844849SJonas Devlieghere                  # Print some simple thread info
10147b844849SJonas Devlieghere                  print thread
10157b844849SJonas Devlieghere                  # Get the first frame
10167b844849SJonas Devlieghere                  frame = thread.GetFrameAtIndex (0)
10177b844849SJonas Devlieghere                  if frame:
10187b844849SJonas Devlieghere                      # Print some simple frame info
10197b844849SJonas Devlieghere                      print frame
10207b844849SJonas Devlieghere                      function = frame.GetFunction()
10217b844849SJonas Devlieghere                      # See if we have debug info (a function)
10227b844849SJonas Devlieghere                      if function:
10237b844849SJonas Devlieghere                          # We do have a function, print some info for the function
10247b844849SJonas Devlieghere                          print function
10257b844849SJonas Devlieghere                          # Now get all instructions for this function and print them
10267b844849SJonas Devlieghere                          insts = function.GetInstructions(target)
10277b844849SJonas Devlieghere                          disassemble_instructions (insts)
10287b844849SJonas Devlieghere                      else:
10297b844849SJonas Devlieghere                          # See if we have a symbol in the symbol table for where we stopped
10307b844849SJonas Devlieghere                          symbol = frame.GetSymbol();
10317b844849SJonas Devlieghere                          if symbol:
10327b844849SJonas Devlieghere                              # We do have a symbol, print some info for the symbol
10337b844849SJonas Devlieghere                              print symbol
10347b844849SJonas Devlieghere
10357b844849SJonas DevlieghereWriting lldb frame recognizers in Python
10367b844849SJonas Devlieghere----------------------------------------
10377b844849SJonas Devlieghere
10387b844849SJonas DevlieghereFrame recognizers allow for retrieving information about special frames based
10397b844849SJonas Devlieghereon ABI, arguments or other special properties of that frame, even without
10407b844849SJonas Devliegheresource code or debug info. Currently, one use case is to extract function
10414fd3347dSKazu Hirataarguments that would otherwise be inaccessible, or augment existing arguments.
10427b844849SJonas Devlieghere
10437b844849SJonas DevlieghereAdding a custom frame recognizer is done by implementing a Python class and
10447b844849SJonas Devlieghereusing the 'frame recognizer add' command. The Python class should have a
10457b844849SJonas Devlieghere'get_recognized_arguments' method and it will receive an argument of type
10467b844849SJonas Devliegherelldb.SBFrame representing the current frame that we are trying to recognize.
10477b844849SJonas DevlieghereThe method should return a (possibly empty) list of lldb.SBValue objects that
10487b844849SJonas Devlieghererepresent the recognized arguments.
10497b844849SJonas Devlieghere
10507b844849SJonas DevlieghereAn example of a recognizer that retrieves the file descriptor values from libc
10517b844849SJonas Devliegherefunctions 'read', 'write' and 'close' follows:
10527b844849SJonas Devlieghere
10537b844849SJonas Devlieghere::
10547b844849SJonas Devlieghere
10557b844849SJonas Devlieghere  class LibcFdRecognizer(object):
10567b844849SJonas Devlieghere    def get_recognized_arguments(self, frame):
10577b844849SJonas Devlieghere      if frame.name in ["read", "write", "close"]:
10587b844849SJonas Devlieghere        fd = frame.EvaluateExpression("$arg1").unsigned
1059edea4a34SJim Ingham        target = frame.thread.process.target
1060edea4a34SJim Ingham        value = target.CreateValueFromExpression("fd", "(int)%d" % fd)
10617b844849SJonas Devlieghere        return [value]
10627b844849SJonas Devlieghere      return []
10637b844849SJonas Devlieghere
106451ab17b9SRaphael IsemannThe file containing this implementation can be imported via ``command script import``
106551ab17b9SRaphael Isemannand then we can register this recognizer with ``frame recognizer add``.
10667b844849SJonas DevlieghereIt's important to restrict the recognizer to the libc library (which is
10677b844849SJonas Devliegherelibsystem_kernel.dylib on macOS) to avoid matching functions with the same name
10687b844849SJonas Devliegherein other modules:
10697b844849SJonas Devlieghere
10707b844849SJonas Devlieghere::
10717b844849SJonas Devlieghere
10727b844849SJonas Devlieghere  (lldb) command script import .../fd_recognizer.py
10737b844849SJonas Devlieghere  (lldb) frame recognizer add -l fd_recognizer.LibcFdRecognizer -n read -s libsystem_kernel.dylib
10747b844849SJonas Devlieghere
10757b844849SJonas DevlieghereWhen the program is stopped at the beginning of the 'read' function in libc, we can view the recognizer arguments in 'frame variable':
10767b844849SJonas Devlieghere
10777b844849SJonas Devlieghere::
10787b844849SJonas Devlieghere
10797b844849SJonas Devlieghere  (lldb) b read
10807b844849SJonas Devlieghere  (lldb) r
10817b844849SJonas Devlieghere  Process 1234 stopped
10827b844849SJonas Devlieghere  * thread #1, queue = 'com.apple.main-thread', stop reason = breakpoint 1.3
10837b844849SJonas Devlieghere      frame #0: 0x00007fff06013ca0 libsystem_kernel.dylib`read
10847b844849SJonas Devlieghere  (lldb) frame variable
10857b844849SJonas Devlieghere  (int) fd = 3
10861b1d9815SJim Ingham
1087ae92f6e8SDavid SpickettWriting Target Stop-Hooks in Python
1088ae92f6e8SDavid Spickett-----------------------------------
10891b1d9815SJim Ingham
10901b1d9815SJim InghamStop hooks fire whenever the process stops just before control is returned to the
10911b1d9815SJim Inghamuser.  Stop hooks can either be a set of lldb command-line commands, or can
10921b1d9815SJim Inghambe implemented by a suitably defined Python class.  The Python based stop-hooks
10931b1d9815SJim Inghamcan also be passed as set of -key -value pairs when they are added, and those
10941b1d9815SJim Inghamwill get packaged up into a SBStructuredData Dictionary and passed to the
10951b1d9815SJim Inghamconstructor of the Python object managing the stop hook.  This allows for
10961b1d9815SJim Inghamparametrization of the stop hooks.
10971b1d9815SJim Ingham
10981b1d9815SJim InghamTo add a Python-based stop hook, first define a class with the following methods:
10991b1d9815SJim Ingham
11001b1d9815SJim Ingham+--------------------+---------------------------------------+------------------------------------------------------------------------------------------------------------------+
11011b1d9815SJim Ingham| Name               | Arguments                             | Description                                                                                                      |
11021b1d9815SJim Ingham+--------------------+---------------------------------------+------------------------------------------------------------------------------------------------------------------+
110351ab17b9SRaphael Isemann| ``__init__``       | ``target: lldb.SBTarget``             | This is the constructor for the new stop-hook.                                                                   |
110451ab17b9SRaphael Isemann|                    | ``extra_args: lldb.SBStructuredData`` |                                                                                                                  |
11051b1d9815SJim Ingham|                    |                                       |                                                                                                                  |
110651ab17b9SRaphael Isemann|                    |                                       | ``target`` is the SBTarget to which the stop hook is added.                                                      |
11071b1d9815SJim Ingham|                    |                                       |                                                                                                                  |
110851ab17b9SRaphael Isemann|                    |                                       | ``extra_args`` is an SBStructuredData object that the user can pass in when creating instances of this           |
11091b1d9815SJim Ingham|                    |                                       | breakpoint.  It is not required, but allows for reuse of stop-hook classes.                                      |
11101b1d9815SJim Ingham+--------------------+---------------------------------------+------------------------------------------------------------------------------------------------------------------+
111151ab17b9SRaphael Isemann| ``handle_stop``    | ``exe_ctx: lldb.SBExecutionContext``  | This is the called when the target stops.                                                                        |
111251ab17b9SRaphael Isemann|                    | ``stream: lldb.SBStream``             |                                                                                                                  |
111351ab17b9SRaphael Isemann|                    |                                       | ``exe_ctx`` argument will be filled with the current stop point for which the stop hook is                       |
11141b1d9815SJim Ingham|                    |                                       | being evaluated.                                                                                                 |
11151b1d9815SJim Ingham|                    |                                       |                                                                                                                  |
111651ab17b9SRaphael Isemann|                    |                                       | ``stream`` an lldb.SBStream, anything written to this stream will be written to the debugger console.            |
11171b1d9815SJim Ingham|                    |                                       |                                                                                                                  |
11181b1d9815SJim Ingham|                    |                                       | The return value is a "Should Stop" vote from this thread.  If the method returns either True or no return       |
11191b1d9815SJim Ingham|                    |                                       | this thread votes to stop.  If it returns False, then the thread votes to continue after all the stop-hooks      |
11201b1d9815SJim Ingham|                    |                                       | are evaluated.                                                                                                   |
11211b1d9815SJim Ingham|                    |                                       | Note, the --auto-continue flag to 'target stop-hook add' overrides a True return value from the method.          |
11221b1d9815SJim Ingham+--------------------+---------------------------------------+------------------------------------------------------------------------------------------------------------------+
11231b1d9815SJim Ingham
11241b1d9815SJim InghamTo use this class in lldb, run the command:
11251b1d9815SJim Ingham
11261b1d9815SJim Ingham::
11271b1d9815SJim Ingham
11281b1d9815SJim Ingham   (lldb) command script import MyModule.py
11291b1d9815SJim Ingham   (lldb) target stop-hook add -P MyModule.MyStopHook -k first -v 1 -k second -v 2
11301b1d9815SJim Ingham
11311b1d9815SJim Inghamwhere MyModule.py is the file containing the class definition MyStopHook.
1132