From 25cad9655732e5855c96efa78caac23bface4280 Mon Sep 17 00:00:00 2001 From: "Daniel A. Wozniak" Date: Mon, 23 Oct 2023 00:14:53 -0700 Subject: [PATCH] Update dbg.py --- src/relenv_gdb/dbg.py | 48 +++++++++++++++++++++++++++---------------- 1 file changed, 30 insertions(+), 18 deletions(-) diff --git a/src/relenv_gdb/dbg.py b/src/relenv_gdb/dbg.py index bf23673..3510151 100755 --- a/src/relenv_gdb/dbg.py +++ b/src/relenv_gdb/dbg.py @@ -1,13 +1,12 @@ -# 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 @@ -15,7 +14,7 @@ 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 @@ -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): @@ -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)