| 1 |
#!/usr/bin/env python3 |
| 2 |
#***************************************************************************** |
| 3 |
# Copyright (C) 2013 Volker Braun <[email protected]> |
| 4 |
# |
| 5 |
# cysignals is free software: you can redistribute it and/or modify it |
| 6 |
# under the terms of the GNU Lesser General Public License as published |
| 7 |
# by the Free Software Foundation, either version 3 of the License, or |
| 8 |
# (at your option) any later version. |
| 9 |
# |
| 10 |
# cysignals is distributed in the hope that it will be useful, |
| 11 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 13 |
# GNU Lesser General Public License for more details. |
| 14 |
# |
| 15 |
# You should have received a copy of the GNU Lesser General Public License |
| 16 |
# along with cysignals. If not, see <http://www.gnu.org/licenses/>. |
| 17 |
# |
| 18 |
#***************************************************************************** |
| 19 |
|
| 20 |
description = """ |
| 21 |
Attach the debugger to a Python process (given by its pid) and |
| 22 |
extract as much information about its internal state as possible |
| 23 |
without any user interaction. The target process is frozen while |
| 24 |
this script runs and resumes when it is finished.""" |
| 25 |
|
| 26 |
# A backtrace is saved in the directory $CYSIGNALS_CRASH_LOGS, which is |
| 27 |
# cysignals_crash_logs by default. Any backtraces older than |
| 28 |
# $CYSIGNALS_CRASH_DAYS (default: 7 if CYSIGNALS_CRASH_LOGS unset, -1 if |
| 29 |
# set) are automatically deleted, but with a negative value they are |
| 30 |
# never deleted. |
| 31 |
|
| 32 |
import sys |
| 33 |
import os |
| 34 |
from subprocess import Popen, PIPE |
| 35 |
import signal |
| 36 |
import tempfile |
| 37 |
import sysconfig |
| 38 |
import site |
| 39 |
|
| 40 |
import datetime |
| 41 |
from argparse import ArgumentParser |
| 42 |
from shutil import which |
| 43 |
import importlib.resources as importlib_resources |
| 44 |
|
| 45 |
|
| 46 |
def pid_exists(pid): |
| 47 |
""" |
| 48 |
Return ``True`` if and only if there is a process with id pid running. |
| 49 |
""" |
| 50 |
try: |
| 51 |
os.kill(pid, 0) |
| 52 |
return True |
| 53 |
except (OSError, ValueError): |
| 54 |
return False |
| 55 |
|
| 56 |
|
| 57 |
def gdb_commands(pid, color): |
| 58 |
cmds = b'' |
| 59 |
cmds += b'set prompt (cysignals-gdb-prompt)\n' |
| 60 |
cmds += b'set verbose off\n' |
| 61 |
cmds += b'attach %d\n' % pid |
| 62 |
cmds += b'python\n' |
| 63 |
cmds += b'print("\\n")\n' |
| 64 |
cmds += b'print("Stack backtrace")\n' |
| 65 |
cmds += b'print("---------------")\n' |
| 66 |
cmds += b'import sys; sys.stdout.flush()\n' |
| 67 |
cmds += b'end\n' |
| 68 |
cmds += b'bt full\n' |
| 69 |
script = importlib_resources.files('cysignals') / 'cysignals-CSI-helper.py' |
| 70 |
cmds += b'python\n' |
| 71 |
cmds += b'color = %r; ' % color |
| 72 |
cmds += b'sys_path = %r; ' % sys.path |
| 73 |
cmds += script.read_bytes() |
| 74 |
cmds += b'end\n' |
| 75 |
cmds += b'detach inferior 1\n' |
| 76 |
cmds += b'quit\n' |
| 77 |
return cmds |
| 78 |
|
| 79 |
|
| 80 |
def run_gdb(pid, color): |
| 81 |
""" |
| 82 |
Execute gdb. |
| 83 |
""" |
| 84 |
whichgdb = which('gdb') |
| 85 |
if whichgdb is None: |
| 86 |
return b"Cannot find gdb installed" |
| 87 |
|
| 88 |
env = dict(os.environ) |
| 89 |
try: |
| 90 |
cmd = Popen(["gdb"], executable=whichgdb, |
| 91 |
stdin=PIPE, stdout=PIPE, stderr=PIPE, env=env) |
| 92 |
except OSError: |
| 93 |
return b"Unable to start gdb (not installed?)" |
| 94 |
|
| 95 |
try: |
| 96 |
stdout, stderr = cmd.communicate(gdb_commands(pid, color)) |
| 97 |
except BaseException: |
| 98 |
# Something went wrong => kill gdb |
| 99 |
cmd.kill() |
| 100 |
raise |
| 101 |
|
| 102 |
result = [] |
| 103 |
for line in stdout.splitlines(): |
| 104 |
if line.find(b"(cysignals-gdb-prompt)") >= 0: |
| 105 |
continue |
| 106 |
if line.startswith(b"Reading symbols from "): |
| 107 |
continue |
| 108 |
if line.startswith(b"Loaded symbols for "): |
| 109 |
continue |
| 110 |
result.append(line) |
| 111 |
result.append(stderr) |
| 112 |
if cmd.wait() != 0: |
| 113 |
result.append(b"Failed to run gdb.") |
| 114 |
|
| 115 |
return b'\n'.join(result) |
| 116 |
|
| 117 |
|
| 118 |
def mkdir_p(path): |
| 119 |
try: |
| 120 |
os.makedirs(path) |
| 121 |
except OSError as e: |
| 122 |
if not os.path.isdir(path): |
| 123 |
raise |
| 124 |
|
| 125 |
|
| 126 |
def prune_old_logs(directory, days): |
| 127 |
""" |
| 128 |
Delete all files in ``directory`` that are older than a given |
| 129 |
number of days. |
| 130 |
""" |
| 131 |
for filename in os.listdir(directory): |
| 132 |
filename = os.path.join(directory, filename) |
| 133 |
mtime = datetime.datetime.fromtimestamp(os.path.getmtime(filename), datetime.UTC) |
| 134 |
age = datetime.datetime.now(datetime.UTC) - mtime |
| 135 |
if age.days >= days: |
| 136 |
try: |
| 137 |
os.unlink(filename) |
| 138 |
except OSError: |
| 139 |
pass |
| 140 |
|
| 141 |
|
| 142 |
def save_backtrace(output): |
| 143 |
try: |
| 144 |
bt_dir = os.environ['CYSIGNALS_CRASH_LOGS'] |
| 145 |
# Don't delete all files in this directory, in case the user |
| 146 |
# set CYSIGNALS_CRASH_LOGS to a stupid value. |
| 147 |
bt_days = -1 |
| 148 |
except KeyError: |
| 149 |
bt_dir = 'cysignals_crash_logs' |
| 150 |
bt_days = 7 |
| 151 |
|
| 152 |
if not bt_dir: |
| 153 |
return None |
| 154 |
|
| 155 |
try: |
| 156 |
bt_days = int(os.environ['CYSIGNALS_CRASH_DAYS']) |
| 157 |
except KeyError: |
| 158 |
pass |
| 159 |
|
| 160 |
mkdir_p(bt_dir) |
| 161 |
if bt_days >= 0: |
| 162 |
prune_old_logs(bt_dir, bt_days) |
| 163 |
f, filename = tempfile.mkstemp(dir=bt_dir, prefix='crash_', suffix='.log') |
| 164 |
os.write(f, output) |
| 165 |
os.close(f) |
| 166 |
return filename |
| 167 |
|
| 168 |
|
| 169 |
def main(args): |
| 170 |
print(f'Attaching gdb to process id {args.pid}.') |
| 171 |
sys.stdout.flush() |
| 172 |
trace = run_gdb(args.pid, not args.nocolor) |
| 173 |
os.write(1, trace) |
| 174 |
|
| 175 |
fatalities = [ |
| 176 |
(b'Cannot find gdb', |
| 177 |
'GDB is not installed.'), |
| 178 |
(b'Unable to start gdb', |
| 179 |
'GDB is not installed.'), |
| 180 |
(b'Hangup detected on fd 0', |
| 181 |
'Your system GDB is an old version that does not work with pipes.'), |
| 182 |
(b'error detected on stdin', |
| 183 |
'Your system GDB does not have Python support.'), |
| 184 |
(b'ImportError: No module named', |
| 185 |
'Your system GDB uses an incompatible version of Python.'), |
| 186 |
(b'Failed to run gdb', 'Failed to run gdb.'), |
| 187 |
] |
| 188 |
|
| 189 |
for key, msg in fatalities: |
| 190 |
if key in trace: |
| 191 |
print() |
| 192 |
print(msg) |
| 193 |
print('Install gdb for enhanced tracebacks.') |
| 194 |
return |
| 195 |
|
| 196 |
filename = save_backtrace(trace) |
| 197 |
if filename is not None: |
| 198 |
print(f'Saved trace to {filename}') |
| 199 |
|
| 200 |
|
| 201 |
if __name__ == '__main__': |
| 202 |
parser = ArgumentParser(description=description) |
| 203 |
parser.add_argument('-p', '--pid', dest='pid', action='store', |
| 204 |
default=None, type=int, |
| 205 |
help='the pid to attach to.') |
| 206 |
parser.add_argument('-nc', '--no-color', dest='nocolor', action='store_true', |
| 207 |
default=False, |
| 208 |
help='turn off syntax-highlighting.') |
| 209 |
parser.add_argument('-k', '--kill', dest='kill', action='store_true', |
| 210 |
default=False, |
| 211 |
help='kill after inspection is finished.') |
| 212 |
args = parser.parse_args() |
| 213 |
|
| 214 |
if args.pid is None: |
| 215 |
parser.print_help() |
| 216 |
sys.exit(0) |
| 217 |
|
| 218 |
if not pid_exists(args.pid): |
| 219 |
print(f'There is no process with pid {args.pid}.') |
| 220 |
sys.exit(1) |
| 221 |
|
| 222 |
try: |
| 223 |
main(args) |
| 224 |
finally: |
| 225 |
if args.kill: |
| 226 |
os.kill(args.pid, signal.SIGKILL) |