Skip to content

Commit

Permalink
Update dbg.py
Browse files Browse the repository at this point in the history
  • Loading branch information
dwoz committed Oct 23, 2023
1 parent 3aba7ee commit 25cad96
Showing 1 changed file with 30 additions and 18 deletions.
48 changes: 30 additions & 18 deletions src/relenv_gdb/dbg.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,20 @@
# Copyright 2023 VMware, Inc.
# SPDX-License-Identifier: Apache-2.0
"""
Use gdb to pull python stack traces for every thread in a parent process and all of it's children.
"""
import os
import pprint
import subprocess
import sys
import subprocess
import pprint
import tempfile
import pathlib

import psutil

CMD_TPL = """
set pagination off
set logging file {output}
set logging enabled on
source libpython.py
source {libpython}
echo --- thread info for pid {pid} ---\\n
info threads
Expand All @@ -32,35 +31,45 @@
quit
"""

def find_dist_info():
for name in pathlib.Path(__file__).parent.parent.rglob("relenv_gdb*dist-info"):
return name

def find_relenv_gdb():
dist_info = find_dist_info()
text = pathlib.Path(dist_info, "RECORD").read_text()
for line in text.split("\n"):
if "bin/relenv-gdb" in line:
location, digest, size = line.rsplit(",", 2)
script = (pathlib.Path(dist_info).parent / location).resolve()
if script.exists():
return script

def append_line(path, line):
"""
Append a line of text to the file.
"""
with open(path, "a") as fp:
fp.write(line + "\n")


def debug(proc, output):
"""
Debug a process.
"""
def debug(gdb, proc, output):
print(f"Debugging {proc.pid} {' '.join(proc.cmdline())}")
fd, path = tempfile.mkstemp()
with open(path, "w") as fp:
fp.write(CMD_TPL.format(output=output, pid=proc.pid))
fp.write(
CMD_TPL.format(
output=output,
pid=proc.pid,
libpython=(pathlib.Path(__file__).parent / "libpython.py").resolve(),
)
)
append_line(output, f"===[ begin {proc.pid} ]===")
append_line(output, pprint.pformat(proc.as_dict()))
subprocess.run(["gdb", "-p", f"{proc.pid}", "--command", path], capture_output=True)
subprocess.run([gdb, "-p", f"{proc.pid}", "--command", path], capture_output=True)
append_line(output, f"===[ end {proc.pid} ]===")
os.close(fd)
os.remove(path)


def main():
"""
The dbg program entry point.
"""
try:
pid = int(sys.argv[1])
except (IndexError, ValueError):
Expand All @@ -71,9 +80,12 @@ def main():
print("Please provide a valid pid as the only argument")
sys.exit(1)

gdb = find_relenv_gdb()
if not gdb:
print("Unable to find relenv-gdb script")
output = "gdb-output.txt"

debug(parent, output)
debug(gdb, parent, output)

for child in parent.children():
debug(child, output)
Expand Down

0 comments on commit 25cad96

Please sign in to comment.