Package: pygdbmi
pygdbmi - Get Structured Output from GDB's Machine InterfaceDocumentationhttps://cs01.github.io/pygdbmiSource Codehttps://github.com/cs01/pygdbmiPython (py)gdbmachine interface(mi)GDB/MI is a line based machine oriented text interface to GDB and is activated by specifying using the --interpreter command line option (see Mode Options). It is specifically intended to support the development of systems which use the debugger as just one small component of a larger system.What's in the box?A function to parse gdb machine interface string output and return structured data types (Python dicts) that are JSON serializable. Useful for writing the backend to a gdb frontend. For example,gdbguiuses pygdbmi on the backend.A Python class to control and interact with gdb as a subprocessTo getmachine interfaceoutput from gdb, run gdb with the--interpreter=mi2flag like so:gdb --interpreter=mi2Installationpip install pygdbmiCompatibilityOperating SystemsCross platform support for Linux, macOS and WindowsLinux/UnixUbuntu 14.04 and 16.04 have been tested to work. Other versions likely work as well.macOSNote: the errorplease check gdb is codesigned - see taskgated(8)can be fixed by codesigning gdb withthese instructions. If the error is not fixed, pleasecreate an issue in github.WindowsWindows 10 has been tested to work with MinGW and cygwin.gdb versionsgdb 7.6+ has been tested. Older versions may work as well.Examplesgdb mi defines a syntax for its output that is suitable for machine readability and scripting:example output:-> -break-insert main
<- ^done,bkpt={number="1",type="breakpoint",disp="keep",
enabled="y",addr="0x08048564",func="main",file="myprog.c",
fullname="/home/myprog.c",line="68",thread-groups=["i1"],
times="0"}
<- (gdb)Usepygdbmi.gdbmiparser.parse_responseto turn that string output into a JSON serializable dictionaryfrompygdbmiimportgdbmiparserfrompprintimportpprintresponse=gdbmiparser.parse_response('^done,bkpt={number="1",type="breakpoint",disp="keep", enabled="y",addr="0x08048564",func="main",file="myprog.c",fullname="/home/myprog.c",line="68",thread-groups=["i1"],times="0"')pprint(response)pprint(response)# Prints:# {'message': 'done',#  'payload': {'bkpt': {'addr': '0x08048564',#                       'disp': 'keep',#                       'enabled': 'y',#                       'file': 'myprog.c',#                       'fullname': '/home/myprog.c',#                       'func': 'main',#                       'line': '68',#                       'number': '1',#                       'thread-groups': ['i1'],#                       'times': '0',#                       'type': 'breakpoint'}},#  'token': None,#  'type': 'result'}Programmatic Control Over gdbBut how do you get the gdb output into Python in the first place? If you want,pygdbmialso has a class to control gdb as subprocess. You can write commands, and get structured output back:frompygdbmi.gdbcontrollerimportGdbControllerfrompprintimportpprint# Start gdb processgdbmi=GdbController()print(gdbmi.command)# print actual command run as subprocess# Load binary a.out and get structured responseresponse=gdbmi.write('-file-exec-file a.out')pprint(response)# Prints:# [{'message': 'thread-group-added',#   'payload': {'id': 'i1'},#   'stream': 'stdout',#   'token': None,#   'type': 'notify'},#  {'message': 'done',#   'payload': None,#   'stream': 'stdout',#   'token': None,#   'type': 'result'}]Now do whatever you want with gdb. All gdb commands, as well as gdbmachine interface commandsare acceptable. gdb mi commands give better structured output that is machine readable, rather than gdb console output. mi commands begin with a-.response=gdbmi.write('-break-insert main')# machine interface (MI) commands start with a '-'response=gdbmi.write('break main')# normal gdb commands work too, but the return value is slightly differentresponse=gdbmi.write('-exec-run')response=gdbmi.write('run')response=gdbmi.write('-exec-next',timeout_sec=0.1)# the wait time can be modified from the default of 1 secondresponse=gdbmi.write('next')response=gdbmi.write('next',raise_error_on_timeout=False)response=gdbmi.write('next',raise_error_on_timeout=True,timeout_sec=0.01)response=gdbmi.write('-exec-continue')response=gdbmi.send_signal_to_gdb('SIGKILL')# name of signal is okayresponse=gdbmi.send_signal_to_gdb(2)# value of signal is okay tooresponse=gdbmi.interrupt_gdb()# sends SIGINT to gdbresponse=gdbmi.write('continue')response=gdbmi.exit()Parsed Output FormatEach parsed gdb response consists of a list of dictionaries. Each dictionary has keysmessage,payload,token, andtype.messagecontains a textual message from gdb, which is not always present. When missing, this isNone.payloadcontains the content of gdb's output, which can contain any of the following:dictionary,list,string. This too is not always present, and can beNonedepending on the response.tokenIf an input command was prefixed with a (optional) token then the corresponding output for that command will also be prefixed by that same token. This field is only present for pygdbmi output typesnofityandresult. When missing, this isNone.Thetypeis defined based on gdb's variousmi output record types, and can beresult- the result of a gdb command, such asdone,running,error, etc.notify- additional async changes that have occurred, such as breakpoint modifiedconsole- textual responses to cli commandslog- debugging messages from gdb's internalsoutput- output from targettarget- output from remote targetdone- when gdb has finished its outputContributingDocumentation fixes, bug fixes, performance improvements, and functional improvements are welcome. You may want to create an issue before beginning work to make sure I am interested in merging it to the master branch.pygdbmi usesnoxfor automation.See available tasks withnox -lRun tests and lint withnox -s tests
nox -s lintPositional arguments passed tonox -s testsare passed directly topytest. For instance, to run only the parse tests usenox -s tests -- tests/test_gdbmiparser.pySeepytest's documentationfor more details on how to run tests.To format code using the correct settings usenox -s formatOr, to format only specified files, usenox -s format -- example.py pygdbmi/IoManager.pyMaking a releaseOnly maintainers of thepygdbmi package on PyPican make a release.In the following steps, replace these strings with the correct values:<REMOTE>is the name of the remote for the main pygdbmi repository (for instance,origin)<VERSION>is the version number chosen in step 2.To make a release:Checkout themasterbranch and pull from the main repository withgit pull <REMOTE> masterDecide the version number for the new release; we followSemantic Versioningbut prefixing the version with0.: given a version
number0.SECOND.THIRD.FOURTH, increment the:SECONDcomponent when you make incompatible API changesTHIRDcomponent when you add functionality in a backwards compatible mannerFOURTHcomponent when you make backwards compatible bug fixesUpdateCHANGELOG.mdto list the chosen version number instead of## devUpdate__version__inpygdbmi/__init__.pyto the chosen version numberCreate a branch, for instance usinggit checkout -b before-release-<VERSION>Commit your changes, for instance usinggit commit -a -m 'Bump version to <VERSION> for release'Check that the docs look fine by serving them locally withnox -s serve_docsPush the branch, for instance withgit push --set-upstream <REMOTE> before-release-<VERSION>If tests pass on the PR you created, you can merge intomasterGo to thenew release pageand prepare the
release:Add a tag in the formv<VERSION>(for examplev0.1.2.3)Set the title topygdbmi v<VERSION>(for examplepygdbmi v0.1.2.3)Copy and paste the section for the new release only fromCHANGELOG.mdexcluding the line
with the version numberPress “Publish release”Publish the release to PyPI withnox -s publishPublish the docs withnox -s publish_docsVerify that thePyPi page for pygdbmilooks correctVerify that thepublished docslook correctPrepare for changes for the next release by adding something like this above the previous
entries inCHANGELOG.md(where<VERSION+1>is<VERSION>with the last digit increaded
by 1):## <VERSION+1>.dev0

- *Replace this line with new entries*Create a branch for the changes withgit checkout -b after-release-<VERSION>Commit the change withgit commit -m 'Prepare for work on the next release' CHANGELOG.mdPush the branch withgit push --set-upstream <REMOTE> after-release-<VERSION>If tests pass, merge intomasterSimilar projectstsgdbmiA port of pygdbmi to TypeScriptdanielzfranklin/gdbmiA port of pygdbmi to RustProjects Using pygdbmigdbguiimplements a browser-based frontend to gdb, using pygdbmi on the backendPINCEis a gdb frontend that aims to provide a reverse engineering tool and a reusable library focused on games. It uses pygdbmi to parse gdb/mi based output for some functionsavatar²is an orchestration framework for reversing and analysing firmware of embedded devices. It utilizes pygdbmi for internal communication to different analysis targets.UDBis a proprietary time-travel debugger for C and C++ based on GDB. It uses pygdbmi in its extensive test suite to parse the debugger's output.Know of another project? Create a PR and add it here.AuthorsChad Smith(main author and creator).Marco Barisione(co-maintainer).The community. Thanks especially to @mariusmue, @bobthekingofegypt, @mouuff, and @felipesere.