This file is indexed.

/usr/bin/cysignals-CSI is in cysignals-tools 1.3.2+ds-1.

This file is owned by root:root, with mode 0o755.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
#!/usr/bin/python
#*****************************************************************************
#       Copyright (C) 2013 Volker Braun <vbraun.name@gmail.com>
#
#  cysignals is free software: you can redistribute it and/or modify it
#  under the terms of the GNU Lesser General Public License as published
#  by the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  cysignals is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU Lesser General Public License for more details.
#
#  You should have received a copy of the GNU Lesser General Public License
#  along with cysignals.  If not, see <http://www.gnu.org/licenses/>.
#
#*****************************************************************************

from __future__ import print_function

description = """
    Attach the debugger to a Python process (given by its pid) and
    extract as much information about its internal state as possible
    without any user interaction. The target process is frozen while
    this script runs and resumes when it is finished."""

# A backtrace is saved in the directory $CYSIGNALS_CRASH_LOGS, which is
# signals_crash_logs by default.  Any backtraces older than
# $CYSIGNALS_CRASH_DAYS (default: 7 if CYSIGNALS_CRASH_LOGS unset, -1 if
# set) are automatically deleted, but with a negative value they are
# never deleted.

import sys
import os
import subprocess
import signal
import tempfile
import sysconfig

from argparse import ArgumentParser
from datetime import datetime


def b(x):
    """
    Convert `x` (either a ``str`` or ``bytes``) to ``bytes``, assuming
    ASCII encoding.
    """
    if isinstance(x, bytes):
        return x
    return bytes(x, "ascii")


def pid_exists(pid):
    """
    Return True if and only if there is a process with id pid running.
    """
    try:
        os.kill(pid, 0)
        return True
    except (OSError, ValueError):
        return False


def gdb_commands(pid, color):
    from cysignals_gdb import __file__ as cysignals_gdb_pkg_root
    cysignals_gdb_pkg_root = os.path.dirname(cysignals_gdb_pkg_root)
    cmds = b('')
    cmds += b('set prompt (cysignals-gdb-prompt)\n')
    cmds += b('set verbose off\n')
    cmds += b('attach {0}\n'.format(pid))
    cmds += b('python\n')
    cmds += b('print("\\n")\n')
    cmds += b('print("Stack backtrace")\n')
    cmds += b('print("---------------")\n')
    cmds += b('import sys; sys.stdout.flush()\n')
    cmds += b('end\n')
    cmds += b('bt full\n')
    script = os.path.join(cysignals_gdb_pkg_root, 'cysignals-CSI-helper.py')
    with open(script, 'r') as f:
        cmds += b('python\n')
        cmds += b('color = {0}\n'.format(color))
        cmds += b(f.read())
        cmds += b('end\n')
    cmds += b('detach inferior 1\n')
    cmds += b('python print("Stack backtrace (newest frame = first)\\n")\n')
    cmds += b('python print("--------------------------------------\\n")\n')
    cmds += b('python import sys; sys.stdout.flush()\n')
    cmds += b('quit\n')
    return cmds


def run_gdb(pid, color):
    """
    Execute gdb.
    """
    # Preload the right Python library
    libpython = os.path.join(sysconfig.get_config_var('exec_prefix'), 'lib',
                             sysconfig.get_config_var('MULTIARCH'),
                             sysconfig.get_config_var('INSTSONAME'))
    env = dict(os.environ)
    if sys.platform == 'macosx':
        env['DYLD_INSERT_LIBRARIES'] = libpython
    else:
        env['LD_PRELOAD'] = libpython

    PIPE = subprocess.PIPE
    try:
        cmd = subprocess.Popen('gdb', stdin=PIPE, stdout=PIPE,
                               stderr=PIPE, env=env)
    except OSError:
        return "Unable to start gdb (not installed?)"
    try:
        stdout, stderr = cmd.communicate(gdb_commands(pid, color))
    except BaseException:
        # Something went wrong => kill gdb
        cmd.kill()
        raise
    result = []
    for line in stdout.splitlines():
        if line.find('(cysignals-gdb-prompt)') >= 0:
            continue
        if line.startswith('Reading symbols from '):
            continue
        if line.startswith('Loaded symbols for '):
            continue
        result.append(line)
    if stderr:
        result.append(stderr)
    return '\n'.join(result)


def mkdir_p(path):
    try:
        os.makedirs(path)
    except OSError as e:
        if not os.path.isdir(path):
            raise


def prune_old_logs(directory, days):
    """
    Delete all files in ``directory`` that are older than a given
    number of days.
    """
    for filename in os.listdir(directory):
        filename = os.path.join(directory, filename)
        mtime = datetime.utcfromtimestamp(os.path.getmtime(filename))
        age = datetime.utcnow() - mtime
        if age.days >= days:
            try:
                os.unlink(filename)
            except OSError:
                pass

def save_backtrace(output):
    try:
        bt_dir = os.environ['CYSIGNALS_CRASH_LOGS']
        # Don't delete all files in this directory, in case the user
        # set CYSIGNALS_CRASH_LOGS to a stupid value.
        bt_days = -1
    except KeyError:
        bt_dir = 'signals_crash_logs'
        bt_days = 7

    if not bt_dir:
        return None

    try:
        bt_days = int(os.environ['CYSIGNALS_CRASH_DAYS'])
    except KeyError:
        pass

    mkdir_p(bt_dir)
    if bt_days >= 0:
        prune_old_logs(bt_dir, bt_days)
    f, filename = tempfile.mkstemp(dir=bt_dir, prefix='crash_', suffix='.log')
    os.write(f, output)
    os.close(f)
    return filename


def main(args):
    print('Attaching gdb to process id {0}.'.format(args.pid))
    trace = run_gdb(args.pid, not args.nocolor)
    print(trace)

    fatalities = [
        ( 'Unable to start gdb',
          'GDB is not installed.' ),
        ( 'Hangup detected on fd 0',
          'Your system GDB is an old version that does not work with pipes'),
        ( 'error detected on stdin',
          'Your system GDB does not have Python support'),
        ( 'ImportError: No module named',
          'Your system GDB uses an incompatible version of Python') ]

    for key, msg in fatalities:
        if key in trace:
            print()
            print(msg)
            print('Install gdb for enhanced tracebacks.')
            return

    filename = save_backtrace(trace)
    if filename is not None:
        print('Saved trace to {0}'.format(filename))


if __name__ == '__main__':
    parser = ArgumentParser(description=description)
    parser.add_argument('-p', '--pid', dest='pid', action='store',
                        default=None, type=int,
                        help='the pid to attach to.')
    parser.add_argument('-nc', '--no-color', dest='nocolor', action='store_true',
                        default=False,
                        help='turn off syntax-highlighting.')
    parser.add_argument('-k', '--kill', dest='kill', action='store_true',
                        default=False,
                        help='kill after inspection is finished.')
    args = parser.parse_args()

    if args.pid is None:
        parser.print_help()
        sys.exit(0)

    if not pid_exists(args.pid):
        print('There is no process with pid {0}.'.format(args.pid))
        sys.exit(1)

    try:
        main(args)
    finally:
        if args.kill:
            os.kill(args.pid, signal.SIGKILL)