Skip to content

Instantly share code, notes, and snippets.

@kouloumos
Created May 17, 2023 08:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kouloumos/e0a9c6c58b594d879644efad2d90a443 to your computer and use it in GitHub Desktop.
Save kouloumos/e0a9c6c58b594d879644efad2d90a443 to your computer and use it in GitHub Desktop.
Custom gdb command to waitfor and attach on a process
'''
To make this file available to your gdb process:
2. (gdb) source attach_helper.py
To use the custom command:
1. `attach_bitcoind` to make the debugger wait for a bitcoind process to attach on
2. Start bitcoind (e.g a functional test from another terminal)
3. Debug
'''
import gdb
import subprocess
import time
always_attach_to_the_first_process = True
def waitfor(process, target_process_index=None):
'''Helper method that waits for a process to start and returns its PID'''
print("Waiting for %s to start..." % process)
while True:
try:
output = subprocess.Popen('pgrep %s' % process, stdout=subprocess.PIPE, shell=True, text=True).communicate()[0]
if output != '':
# parse the output into a list of PIDs
pid = output.rstrip().split("\n")
if not always_attach_to_the_first_process and target_process_index is None and len(pid) > 1:
raise TypeError(
"More than one bitcoind processes are running, you might be running a functional test with multiple nodes.\
\nYou need to specify which bitcoind process you are targeting with:\
\n gdb command: attach_bitcoind <target_process_index>")
# always attach to the first bitcoind process
target_process_index = target_process_index or 0
print(f"{process} started with pid={pid}")
print(f"Ready to attach to bitcoind process with pid={pid[target_process_index]}")
# return the pid of the process that we want to attach to
return pid[target_process_index]
except gdb.error:
pass
except TypeError as e:
print(f"Error: {e}")
raise SystemExit(1) # stop the program when the TypeError occurs
time.sleep(0.1)
class AttachBitcoind(gdb.Command):
def __init__(self):
super(AttachBitcoind, self).__init__("attach_bitcoind", gdb.COMMAND_DATA)
def invoke(self, arg, from_tty):
process_index = int(arg.rstrip().split(" ")[0]) if arg.rstrip().split(" ")[0] else None
pid = waitfor("bitcoind", process_index)
gdb.execute('attach %s' % pid)
print(f'Attached to pid={pid}, process is now paused.')
# This runs on initialization when `(gdb) source extend_gdb`
print(f"Running GDB from: {gdb.PYTHONDIR}")
gdb.execute("set pagination off")
print(f"""
To make the debugger wait for a bitcoind process to attach on:
(gdb) attach_bitcoind
Then, start bitcoind (e.g a functional test from another terminal)
For more details read the source file.""")
# This registers our custom gdb commands classes to the gdb runtime at "source" time.
AttachBitcoind()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment