### Running Nox Tasks for Automation Source: https://github.com/cs01/pygdbmi/blob/master/README.md Provides examples of how to use the `nox` tool for automating tasks such as running tests, linting, and formatting code within the project. Tasks are executed via the `nox -s ` command. ```bash nox -l nox -s tests nox -s lint nox -s format nox -s format -- example.py pygdbmi/IoManager.py ``` -------------------------------- ### Running Nox Tasks for pygdbmi Source: https://github.com/cs01/pygdbmi/blob/master/docs/README.md Provides examples of using Nox to automate tasks within the pygdbmi project, such as running tests, linting code, and formatting files. It shows how to list available tasks and execute specific ones. ```bash nox -l ``` ```bash nox -s tests ``` ```bash nox -s lint ``` ```bash nox -s tests -- tests/test_gdbmiparser.py ``` ```bash nox -s format ``` ```bash nox -s format -- example.py pygdbmi/IoManager.py ``` -------------------------------- ### Install pygdbmi using pip Source: https://context7.com/cs01/pygdbmi/llms.txt This command installs the pygdbmi library using pip, making it available for use in Python projects. Ensure you have pip installed and configured correctly. ```bash pip install pygdbmi ``` -------------------------------- ### Respawn GDB Subprocess with GdbController.spawn_new_gdb_subprocess() Source: https://context7.com/cs01/pygdbmi/llms.txt Details the `spawn_new_gdb_subprocess()` method, which terminates the current GDB process and starts a new one. This is useful for resetting the debugging session or switching to a different binary. The method returns the process ID of the newly spawned GDB instance. ```python from pygdbmi.gdbcontroller import GdbController gdbmi = GdbController() # Do some debugging work gdbmi.write("-file-exec-and-symbols /path/to/binary1") gdbmi.write("-break-insert main") gdbmi.write("-exec-run") # Terminate current gdb and start fresh pid = gdbmi.spawn_new_gdb_subprocess() print(f"New GDB process ID: {pid}") # Start debugging a different binary gdbmi.write("-file-exec-and-symbols /path/to/binary2") gdbmi.exit() ``` -------------------------------- ### Control GDB as a Subprocess with Python Source: https://github.com/cs01/pygdbmi/blob/master/README.md This class allows you to control GDB as a subprocess from Python. You can send GDB commands and receive structured output back, enabling programmatic interaction with the debugger. It handles starting GDB, sending commands, and parsing responses. ```python from pygdbmi.gdbcontroller import GdbController from pprint import pprint # Start gdb process gdbmi = GdbController() print(gdbmi.command) # print actual command run as subprocess # Load binary a.out and get structured response response = 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, ``` -------------------------------- ### GdbController Initialization Source: https://context7.com/cs01/pygdbmi/llms.txt Demonstrates how to initialize the GdbController class, both with default settings and custom GDB commands. ```APIDOC ## GdbController Initialization ### Description Initializes the GdbController to manage a GDB process. You can use default settings or specify a custom GDB command and timeout for checking output. ### Method `GdbController()` ### Parameters - `command` (list, optional): A list of strings representing the GDB command to execute. Defaults to `['gdb', '--interpreter=mi3']`. - `time_to_check_for_additional_output_sec` (float, optional): The time in seconds to wait for additional output after a command is sent. Defaults to 0.2. ### Request Example ```python from pygdbmi.gdbcontroller import GdbController # Initialize with default settings gdbmi = GdbController() # Initialize with custom command and timeout gdbmi = GdbController( command=["gdb", "--nx", "--quiet", "--interpreter=mi3"], time_to_check_for_additional_output_sec=0.2 ) print(gdbmi.command) ``` ### Response #### Success Response (200) - `command` (list): The actual command used to start GDB. ### Response Example ``` ['gdb', '--nx', '--quiet', '--interpreter=mi3'] ``` ``` -------------------------------- ### Executing GDB Commands with pygdbmi Source: https://github.com/cs01/pygdbmi/blob/master/docs/README.md Demonstrates how to execute various GDB commands, both standard and Machine Interface (MI) commands, using the pygdbmi library. It shows how to insert breakpoints, run execution, step through code, and modify command parameters like timeout and error handling. ```python response = gdbmi.write('-break-insert main') response = gdbmi.write('break main') response = gdbmi.write('-exec-run') response = gdbmi.write('run') response = gdbmi.write('-exec-next', timeout_sec=0.1) response = 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.write('continue') response = gdbmi.exit() ``` -------------------------------- ### Initialize and Use GdbController in Python Source: https://context7.com/cs01/pygdbmi/llms.txt Demonstrates how to initialize the GdbController class to manage a GDB subprocess. It shows default initialization and custom command configuration, including loading a binary and printing the GDB command being executed. The GdbController is essential for programmatic interaction with GDB. ```python from pygdbmi.gdbcontroller import GdbController from pprint import pprint # Initialize GDB controller with default settings (uses gdb --interpreter=mi3) gdbmi = GdbController() # Or specify a custom command gdbmi = GdbController( command=["gdb", "--nx", "--quiet", "--interpreter=mi3"], time_to_check_for_additional_output_sec=0.2 ) # Print the actual command being run print(gdbmi.command) # Load a binary file for debugging responses = gdbmi.write("-file-exec-and-symbols /path/to/binary") pprint(responses) # Clean up gdbmi.exit() ``` -------------------------------- ### GdbController.write() - Sending Commands Source: https://context7.com/cs01/pygdbmi/llms.txt Explains how to use the `write()` method to send commands to GDB and receive parsed responses. ```APIDOC ## GdbController.write() - Sending Commands ### Description Sends GDB/MI or regular GDB commands to the GDB process and returns parsed structured responses. Supports various options for command execution and response handling. ### Method `write(commands, timeout_sec=None, raise_error_on_timeout=True, read_response=True)` ### Parameters - `commands` (str or list): A single command string or a list of command strings to send to GDB. - `timeout_sec` (float, optional): The maximum time in seconds to wait for a response. If `None`, the default timeout is used. - `raise_error_on_timeout` (bool, optional): If `True`, raises a `GdbTimeoutError` on timeout. Defaults to `True`. - `read_response` (bool, optional): If `True`, waits for and reads the response from GDB. Defaults to `True`. ### Request Example ```python from pygdbmi.gdbcontroller import GdbController gdbmi = GdbController() # Send a single MI command responses = gdbmi.write("-break-insert main") # Send a regular GDB command responses = gdbmi.write("break main") # Send multiple commands responses = gdbmi.write(["-file-list-exec-source-files", "-break-insert main"]) # Send command with custom timeout responses = gdbmi.write("-exec-next", timeout_sec=0.1) # Send command without raising error on timeout responses = gdbmi.write("next", raise_error_on_timeout=False) # Send command without reading response immediately gdbmi.write("-exec-run", read_response=False) gdbmi.exit() ``` ### Response #### Success Response (200) - `responses` (list): A list of dictionaries, where each dictionary represents a parsed GDB/MI response. #### Response Example ```json [ { "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" } }, "stream": "stdout", "token": null, "type": "result" } ] ``` ``` -------------------------------- ### Automate GDB Debugging Session with pygdbmi Source: https://context7.com/cs01/pygdbmi/llms.txt This snippet demonstrates a complete debugging workflow, including initializing the GDB controller, setting breakpoints, executing code, and inspecting local variables. It requires a compiled binary and uses GDB/MI commands for structured interaction. ```python from pygdbmi.gdbcontroller import GdbController from pygdbmi.constants import GdbTimeoutError def debug_program(binary_path: str): gdbmi = GdbController() try: gdbmi.write(f"-file-exec-and-symbols {binary_path}") gdbmi.write("-break-insert main") gdbmi.write("-exec-run", timeout_sec=3) responses = gdbmi.write("-stack-list-locals 1") print(responses) except GdbTimeoutError: print("Program timed out") finally: gdbmi.exit() ``` -------------------------------- ### Prepare Changelog for Next Release Source: https://github.com/cs01/pygdbmi/blob/master/README.md This snippet shows the format required in CHANGELOG.md to initialize the development section for the next version after a release is completed. ```markdown ## .dev0 - *Replace this line with new entries* ``` -------------------------------- ### GdbController.spawn_new_gdb_subprocess() - Respawning GDB Source: https://context7.com/cs01/pygdbmi/llms.txt Explains how to restart the GDB subprocess using `spawn_new_gdb_subprocess()`. ```APIDOC ## GdbController.spawn_new_gdb_subprocess() - Respawning GDB ### Description Terminates the current GDB process and starts a new one. This is useful for resetting the debugging session or switching to a different binary. ### Method `spawn_new_gdb_subprocess()` ### Parameters None ### Request Example ```python from pygdbmi.gdbcontroller import GdbController gdbmi = GdbController() # Perform some debugging operations gdbmi.write("-file-exec-and-symbols /path/to/binary1") gdbmi.write("-break-insert main") # Terminate current GDB and start a fresh process pid = gdbmi.spawn_new_gdb_subprocess() print(f"New GDB process ID: {pid}") # Start debugging a different binary in the new process gdbmi.write("-file-exec-and-symbols /path/to/binary2") gdbmi.exit() ``` ### Response #### Success Response (200) - `pid` (int): The process ID of the newly spawned GDB subprocess. #### Response Example ``` New GDB process ID: 12345 ``` ``` -------------------------------- ### POST /gdb/write Source: https://github.com/cs01/pygdbmi/blob/master/docs/README.md Sends a command to the GDB process and returns the parsed output. ```APIDOC ## POST /gdb/write ### Description Sends a GDB command (CLI or MI) to the active GDB process. MI commands should be prefixed with a '-'. ### Method POST ### Endpoint /gdb/write ### Parameters #### Request Body - **command** (string) - Required - The GDB command to execute. - **timeout_sec** (float) - Optional - Time in seconds to wait for a response (default: 1.0). - **raise_error_on_timeout** (boolean) - Optional - Whether to raise an exception on timeout. ### Request Example { "command": "-break-insert main", "timeout_sec": 0.5 } ### Response #### Success Response (200) - **response** (list) - A list of dictionaries containing 'message', 'payload', 'token', and 'type'. #### Response Example [ { "type": "result", "message": "done", "payload": {"bkpt": {"number": "1", "addr": "0x4005de"}}, "token": null } ] ``` -------------------------------- ### Sending Signals to GDB with pygdbmi Source: https://github.com/cs01/pygdbmi/blob/master/docs/README.md Illustrates how to send signals to the GDB process using pygdbmi. This includes sending signals by name (e.g., 'SIGKILL') or by their numerical value. ```python response = gdbmi.send_signal_to_gdb('SIGKILL') response = gdbmi.send_signal_to_gdb(2) ``` -------------------------------- ### GdbController Class Source: https://github.com/cs01/pygdbmi/blob/master/docs/README.md Provides a mechanism to spawn GDB as a subprocess, send commands, and receive structured output. ```APIDOC ## pygdbmi.gdbcontroller.GdbController ### Description Controls a GDB process as a subprocess, allowing for command execution and structured response retrieval. ### Methods - **write(command)**: Sends a command to the GDB process and returns the parsed response list. ### Request Example ```python from pygdbmi.gdbcontroller import GdbController gdbmi = GdbController() response = gdbmi.write('-file-exec-file a.out') ``` ### Response #### Success Response (List) - **response** (list) - A list of dictionaries representing the parsed output from the command execution. #### Response Example [ { "type": "notify", "message": "thread-group-added", "payload": {"id": "i1"} } ] ``` -------------------------------- ### Send Commands to GDB using GdbController.write() Source: https://context7.com/cs01/pygdbmi/llms.txt Illustrates the usage of the `write()` method in GdbController to send GDB/MI and regular GDB commands. It covers inserting breakpoints, sending multiple commands, configuring timeouts, disabling timeout exceptions, and executing commands without immediate response reading. This method is the primary way to interact with the GDB process. ```python from pygdbmi.gdbcontroller import GdbController gdbmi = GdbController() gdbmi.write("-file-exec-and-symbols /path/to/a.out") # Insert a breakpoint using MI command (starts with -) responses = gdbmi.write("-break-insert main") # Regular GDB commands work too responses = gdbmi.write("break main") # Send multiple commands at once responses = gdbmi.write(["-file-list-exec-source-files", "-break-insert main"]) # Configure timeout (default is 1 second) responses = gdbmi.write("-exec-next", timeout_sec=0.1) # Disable timeout exception responses = gdbmi.write("next", raise_error_on_timeout=False) # Don't wait for response (useful with threaded reading) gdbmi.write("-exec-run", read_response=False) gdbmi.exit() ``` -------------------------------- ### Control GDB as a Subprocess Source: https://github.com/cs01/pygdbmi/blob/master/docs/README.md Initializes a GDB instance as a subprocess and sends commands to it using the GdbController class. This allows for programmatic interaction and retrieval of structured responses from the debugger. ```python from pygdbmi.gdbcontroller import GdbController from pprint import pprint # Start gdb process gdbmi = GdbController() # Load binary a.out and get structured response response = gdbmi.write('-file-exec-file a.out') pprint(response) ``` -------------------------------- ### Low-Level I/O Management with IoManager Source: https://context7.com/cs01/pygdbmi/llms.txt The `IoManager` class offers direct control over I/O for GDB processes or pseudo-terminals, intended for internal use by `GdbController` but available for custom integrations. It manages writing commands and reading responses, with configurable timeouts for operations. ```python import subprocess from pygdbmi.IoManager import IoManager # Start gdb process manually gdb_process = subprocess.Popen( ["gdb", "--interpreter=mi3"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=0 ) # Create IoManager with file handles io_manager = IoManager( stdin=gdb_process.stdin, stdout=gdb_process.stdout, stderr=gdb_process.stderr, time_to_check_for_additional_output_sec=0.2 ) # Write command and get response responses = io_manager.write("-gdb-version", timeout_sec=2.0) for resp in responses: if resp['type'] == 'console': print(resp['payload'], end='') # Read response without writing responses = io_manager.get_gdb_response(timeout_sec=1.0, raise_error_on_timeout=False) # Clean up gdb_process.terminate() gdb_process.wait() ``` -------------------------------- ### Read GDB Output with GdbController.get_gdb_response() Source: https://context7.com/cs01/pygdbmi/llms.txt Explains how to use `get_gdb_response()` to block and retrieve GDB output, particularly when commands were sent using `read_response=False`. It demonstrates handling potential `GdbTimeoutError` exceptions and iterating through the parsed responses. This method is crucial for synchronous reading of GDB's output. ```python from pygdbmi.gdbcontroller import GdbController from pygdbmi.constants import GdbTimeoutError gdbmi = GdbController() gdbmi.write("-file-exec-and-symbols /path/to/binary") # Write command without reading response gdbmi.write("-exec-run", read_response=False) # Later, read the response try: responses = gdbmi.get_gdb_response(timeout_sec=5.0, raise_error_on_timeout=True) for response in responses: print(f"Type: {response['type']}, Message: {response['message']}") except GdbTimeoutError: print("GDB did not respond within timeout period") gdbmi.exit() ``` -------------------------------- ### POST /gdb/signal Source: https://github.com/cs01/pygdbmi/blob/master/docs/README.md Sends a signal to the running GDB process. ```APIDOC ## POST /gdb/signal ### Description Sends a specific signal to the GDB process to control execution or state. ### Method POST ### Endpoint /gdb/signal ### Parameters #### Request Body - **signal** (string/integer) - Required - The signal name (e.g., 'SIGKILL') or signal value (e.g., 2). ### Request Example { "signal": "SIGKILL" } ### Response #### Success Response (200) - **status** (string) - Confirmation of signal delivery. ``` -------------------------------- ### GdbController.get_gdb_response() - Reading Output Source: https://context7.com/cs01/pygdbmi/llms.txt Details on how to use `get_gdb_response()` to block and read output from GDB when responses were not read immediately. ```APIDOC ## GdbController.get_gdb_response() - Reading GDB Output ### Description Blocks execution and waits for GDB output, returning parsed responses. This is useful when commands are sent using `write()` with `read_response=False`. ### Method `get_gdb_response(timeout_sec=None, raise_error_on_timeout=True)` ### Parameters - `timeout_sec` (float, optional): The maximum time in seconds to wait for a response. If `None`, the default timeout is used. - `raise_error_on_timeout` (bool, optional): If `True`, raises a `GdbTimeoutError` on timeout. Defaults to `True`. ### Request Example ```python from pygdbmi.gdbcontroller import GdbController from pygdbmi.constants import GdbTimeoutError gdbmi = GdbController() gdbmi.write("-file-exec-and-symbols /path/to/binary") # Write command without reading response gdbmi.write("-exec-run", read_response=False) # Later, read the response try: responses = gdbmi.get_gdb_response(timeout_sec=5.0, raise_error_on_timeout=True) for response in responses: print(f"Type: {response['type']}, Message: {response['message']}") except GdbTimeoutError: print("GDB did not respond within timeout period") gdbmi.exit() ``` ### Response #### Success Response (200) - `responses` (list): A list of dictionaries, where each dictionary represents a parsed GDB/MI response. #### Response Example ```json [ { "type": "notify", "message": "thread-group-added", "payload": {"id": "i1"}, "stream": "stdout", "token": null }, { "type": "result", "message": "done", "payload": null, "stream": "stdout", "token": null } ] ``` ``` -------------------------------- ### Interrupting GDB with pygdbmi Source: https://github.com/cs01/pygdbmi/blob/master/docs/README.md Shows how to interrupt the GDB process, typically by sending a SIGINT signal, using the `interrupt_gdb` method. ```python response = gdbmi.interrupt_gdb() ``` -------------------------------- ### Parse GDB/MI Response Source: https://github.com/cs01/pygdbmi/blob/master/docs/README.md This function parses raw GDB/MI string output into a structured Python dictionary. ```APIDOC ## pygdbmi.gdbmiparser.parse_response ### Description Parses a raw GDB/MI response string and returns a structured, JSON-serializable dictionary representing the message, payload, and type. ### Parameters #### Arguments - **response_string** (string) - Required - The raw string output from GDB/MI. ### Request Example ```python from pygdbmi import gdbmiparser response = gdbmiparser.parse_response('^done,bkpt={number="1",type="breakpoint"}') ``` ### Response #### Success Response (Dict) - **type** (string) - The type of GDB response (e.g., result, notify, console). - **message** (string) - The status message (e.g., done, running). - **payload** (dict) - The structured data extracted from the response. #### Response Example { "type": "result", "message": "done", "payload": { "bkpt": { "number": "1", "type": "breakpoint" } } } ``` -------------------------------- ### Parse GDB/MI Response Types Source: https://context7.com/cs01/pygdbmi/llms.txt This snippet illustrates how to use the parse_response function to convert raw GDB output strings into structured dictionaries. It covers various response types including result, notify, console, log, target, and program output. ```python from pygdbmi.gdbmiparser import parse_response # Result record result = parse_response('^done,value="42"') # Notify record notify = parse_response('=thread-group-added,id="i1"') # Console output console = parse_response('~"GNU gdb 9.2\\n"') # Log output log = parse_response('&"Reading symbols...\\n"') # Target output target = parse_response('@"Target output here"') ``` -------------------------------- ### Parse GDB/MI Output Strings with parse_response() Source: https://context7.com/cs01/pygdbmi/llms.txt The `parse_response()` function converts GDB/MI output strings into structured Python dictionaries. It handles various response types including results, console output, async notifications, and errors, and can also parse tokens for command correlation. It correctly handles GDB bugs with repeated dictionary keys. ```python from pygdbmi.gdbmiparser import parse_response from pprint import pprint # Parse a result record (breakpoint insertion response) response = 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) # Parse console output console = parse_response('~"Reading symbols from a.out..."') print(console) # Parse async notify record notify = parse_response('*stopped,reason="breakpoint-hit",thread-id="1"') print(notify) # Parse error response error = parse_response('^error,msg="No symbol table is loaded."') print(error) # Parse record with token (for correlating commands with responses) tokenized = parse_response('1342^done') print(tokenized) # Handle gdb bug with repeated dictionary keys thread_response = parse_response( '^done,thread-ids={thread-id="3",thread-id="2",thread-id="1"}' ) print(thread_response['payload']) ``` -------------------------------- ### Parse GDB/MI Output String Source: https://github.com/cs01/pygdbmi/blob/master/docs/README.md Converts a raw GDB/MI output string into a structured Python dictionary using the gdbmiparser module. This is useful for processing debugger responses in a machine-readable format. ```python from pygdbmi import gdbmiparser from pprint import pprint response = 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) ``` -------------------------------- ### Parse GDB/MI Output to Python Dicts Source: https://github.com/cs01/pygdbmi/blob/master/README.md This function takes GDB/MI formatted string output and converts it into a JSON-serializable Python dictionary. This is useful for building GDB frontends or any application that needs to process GDB's machine interface data. ```python from pygdbmi import gdbmiparser from pprint import pprint response = 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'} ``` -------------------------------- ### Detect End of GDB Response with response_is_finished() Source: https://context7.com/cs01/pygdbmi/llms.txt The `response_is_finished()` function checks if a given GDB/MI response line signifies the end of the GDB output, typically indicated by the '(gdb)' prompt. It returns `True` if the line matches the completion marker, even with trailing whitespace, and `False` otherwise. ```python from pygdbmi.gdbmiparser import response_is_finished # Check various response lines print(response_is_finished("(gdb)")) # True - response is complete print(response_is_finished("(gdb) ")) # True - with trailing space print(response_is_finished("^done")) # False - not a finish marker print(response_is_finished('~"output"')) # False - console output ``` -------------------------------- ### Handling Timeouts with GdbTimeoutError Source: https://context7.com/cs01/pygdbmi/llms.txt The `GdbTimeoutError` exception is raised when GDB fails to respond within a specified timeout period during command execution. The library provides mechanisms to either catch this exception for custom handling or to disable exception raising and check for empty responses instead. ```python from pygdbmi.gdbcontroller import GdbController from pygdbmi.constants import GdbTimeoutError gdbmi = GdbController() gdbmi.write("-file-exec-and-symbols /path/to/binary") gdbmi.write("-break-insert main") gdbmi.write("-exec-run") try: # Program may block waiting for input - use short timeout responses = gdbmi.write("-exec-continue", timeout_sec=0.5, raise_error_on_timeout=True) except GdbTimeoutError as e: print(f"Timeout occurred: {e}") # Handle timeout - maybe interrupt the program # Alternative: disable exception and check for empty response responses = gdbmi.write("-exec-continue", timeout_sec=0.5, raise_error_on_timeout=False) if not responses: print("No response received within timeout") gdbmi.exit() ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.