~barcc/gedit-debugger/trunk

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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
# -*- coding: utf-8 -*-

#  Copyright © 2013, 2015  B. Clausius <barcc@gmx.de>
#
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  This program 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 General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.

from __future__ import print_function, division

import sys, os
import select
import multiprocessing.connection
import bdb
if sys.version_info[0] < 3:
    from repr import Repr
else:
    from reprlib import Repr

AUTHKEY = b'Wrtlprmft'
# Create a custom safe Repr instance and increase its maxstring.
# The default of 30 truncates error messages too easily.
_repr = Repr()
_repr.maxstring = 200
_saferepr = _repr.repr


class Restart(Exception):
    """Causes a debugger to be restarted for the debugged python program."""
    pass
    
    
class RPdb(bdb.Bdb):
    line_prefix = '\n-> '
    
    def __init__(self, connection=None):
        bdb.Bdb.__init__(self)
        
        self.connection = connection
        self.wait = True
        self.mainpyfile = ''
        self._wait_for_mainpyfile = 0
        self.expanded = {'locals': {}, 'globals': {}}
        
    ### functions to send results to the plugin
    
    @staticmethod
    def typestr(value):
        try:
            return type(value).__name__
        except AttributeError:
            return str(type(value))
        
    @staticmethod
    def valuestr(value):
        try:
            return str(value)[:100]
        except Exception:
            return '<unknown>'
        
    @classmethod
    def varchildren(self, name, value, expanded):
        children = []
        if name in expanded:
            expanded = expanded[name]
            try:
                values = vars(value)
            except TypeError:
                pass
            else:
                if isinstance(values, dict):
                    children.extend(self.vartuple(n, v, expanded) for n, v in sorted(values.items()))
            if isinstance(value, BaseException):
                children.append(self.vartuple('args', value.args, expanded))
            if isinstance(value, (list, tuple)):
                children.extend(self.vartuple(str(i), v, expanded) for i, v in enumerate(value))
            if isinstance(value, dict):
                children.extend(sorted(self.vartuple(str(k), v, expanded) for k, v in value.items()))
        return children
        
    @classmethod
    def vartuple(self, name, value, expanded):
        return name, self.typestr(value), self.valuestr(value), self.varchildren(name, value, expanded)
            
    @classmethod
    def exctuple(self, name, exc, expanded):
        cls, val = exc
        return name, cls.__name__, self.valuestr(val), self.varchildren(name, val, expanded)
            
    def safe_dict(self, vals, expanded, exclude=[]):
        return [self.vartuple(n, v, expanded) for n, v in sorted(vals.items()) if n not in exclude]
        
    def rsend_stack(self, keepframe=False):
        self.print_stack_entry(self.stack[self.curindex])
        def build_tree(frame):
            tree = []
            if frame.f_locals is not frame.f_globals:
                if 'locals' in self.expanded:
                    children = self.safe_dict(frame.f_locals, self.expanded['locals'],
                                              exclude = ['__exception__', '__return__'])
                else:
                    children = []
                tree.append(('locals', '', '', children))
            if '__exception__' in frame.f_locals:
                tree.append(self.exctuple('exception', frame.f_locals['__exception__'], self.expanded))
            if '__return__' in frame.f_locals:
                tree.append(self.vartuple('return', frame.f_locals['__return__'], self.expanded))
            if 'globals' in self.expanded:
                children = self.safe_dict(frame.f_globals, self.expanded['globals'])
            else:
                children = []
            tree.append(('globals', '', '', children))
            return tree
        stack = [(  self.canonic(frame.f_code.co_filename),
                    lineno,
                    frame.f_code.co_name,
                    build_tree(frame),
                 ) for frame, lineno in self.stack]
        try:
            self.connection.send(('stack', (stack, keepframe)))
        except IOError:
            return self.cmd_quit()
        else:
            return True
        
    def rsend_breakpoint(self, cnum, snum, filename, lineno):
        self.connection.send(('break', (cnum, snum, filename, lineno)))
        
    ### functions to process commands from the plugin
    
    def setup(self, f, t):
        self.stack, self.curindex = self.get_stack(f, t)
        self.curframe = self.stack[self.curindex][0]
        
    def forget(self):
        self.stack = []
        self.curindex = 0
        self.curframe = None
        
    def print_stack_entry(self, frame_lineno):
        print('>', self.format_stack_entry(frame_lineno, self.line_prefix))
        
    def interaction(self, frame, traceback):
        """Repeatedly accept input and dispatch to action methods"""
        # Two cases to distinguish:
        # 1. self.wait == True:
        #   Suspend execution until we receive a command to resume
        # 2. self.wait == False:
        #   Received data while the program is running.
        #   Some commands are not useful and discarded
        self.setup(frame, traceback)
        wait = True
        if self.wait:
            wait = self.rsend_stack()
        while wait:
            try:
                cmd, args = self.connection.recv()
            except EOFError:
                wait = self.cmd_quit()
            else:
                func = getattr(self, 'cmd_' + cmd)
                wait = func(*args)
        self.wait = True
        self.forget()
            
    ### override bdb.Bdb methods
    
    def reset(self):
        bdb.Bdb.reset(self)
        self.forget()
        
    def stop_here(self, frame):
        if self.connection.poll():
            self.wait = False
            return True
        return bdb.Bdb.stop_here(self, frame)
        
    def do_clear(self, str_num):
        """clear breakpoints by number"""
        num = int(str_num)
        self.clear_bpbynumber(num)
        
    def user_call(self, frame, argument_list):
        """This method is called when there is the remote possibility
        that we ever need to stop in this function."""
        if self._wait_for_mainpyfile:
            return
        if self.stop_here(frame):
            print('--Call--')
            self.interaction(frame, None)
            
    def user_line(self, frame):
        """This function is called when we stop or break at this line."""
        if self._wait_for_mainpyfile:
            if self.mainpyfile != self.canonic(frame.f_code.co_filename) or frame.f_lineno <= 0:
                return
            self._wait_for_mainpyfile = 0
            self.botframe = frame
        self.interaction(frame, None)
        
    def user_return(self, frame, return_value):
        """This function is called when a return trap is set here."""
        if self._wait_for_mainpyfile:
            return
        frame.f_locals['__return__'] = return_value
        print('--Return--')
        self.interaction(frame, None)
        
    def user_exception(self, frame, exc_info):
        """This function is called if an exception occurs,
        but only if we are to stop at or just below this level."""
        if self._wait_for_mainpyfile:
            return
        exc_type, exc_value, exc_traceback = exc_info
        frame.f_locals['__exception__'] = exc_type, exc_value
        if type(exc_type) == type(''):
            exc_type_name = exc_type
        else:
            exc_type_name = exc_type.__name__
        print(exc_type_name + ':', _saferepr(exc_value))
        self.interaction(frame, exc_traceback)
        
    def set_continue(self, nopause=False):
        # if no breakpoints bdb.Bdb.set_continue will run without debugger,
        # fake breakpoints, so debugger can be paused even without breakpoints
        breaks = self.breaks
        self.breaks = not nopause
        bdb.Bdb.set_continue(self)
        self.breaks = breaks
        
    ### command definitions, called when waiting at a breakpoint
    # this functions return True if the debugger should wait for another command, False otherwise
    
    def cmd_break(self, num, filename, lineno):
        # add a new breakpoint
        err = self.set_break(filename, lineno, 0, None, None)
        if err:
            print('***', err)
            self.rsend_breakpoint(num, 0, filename, lineno)
        else:
            bp = self.get_breaks(filename, lineno)[-1]
            self.rsend_breakpoint(num, bp.number, bp.file, bp.line)
            print("Breakpoint %d at %s:%d" % (bp.number, bp.file, bp.line))
        return self.wait or self.connection.poll()
        
    def cmd_clear(self, snum):
        err = self.clear_bpbynumber(snum)
        if err:
            print('***', err)
        return self.wait or self.connection.poll()
                
    def cmd_step(self):
        if self.wait:
            self.set_step()
            return False
        else:
            return self.connection.poll()
        
    def cmd_next(self):
        if self.wait:
            self.set_next(self.curframe)
            return False
        else:
            return self.connection.poll()
        
    def cmd_return(self):
        if self.wait:
            self.set_return(self.curframe)
            return False
        else:
            return self.connection.poll()
        
    def cmd_run_to(self, filename, lineno):
        if self.wait:
            self.set_break(filename, lineno, 1, None, None)
            self.set_continue()
            return False
        else:
            return self.connection.poll()
        
    def cmd_jump_to(self, filename, lineno):
        if self.wait:
            try:
                # Do the jump and fix up our copy of the stack
                self.curframe.f_lineno = lineno
                self.stack[self.curindex] = self.stack[self.curindex][0], lineno
            except ValueError as e:
                print('*** Jump failed:', e)
            self.rsend_stack()
            return True
        else:
            return self.connection.poll()
        
    def cmd_continue(self, nopause):
        if self.wait:
            self.set_continue(nopause=nopause)
            return False
        else:
            return self.connection.poll()
        
    def cmd_pause(self):
        if not self.wait:
            self.rsend_stack()
            self.wait = True
        return True
        
    def cmd_quit(self):
        self._user_requested_quit = 1
        self.set_quit()
        return False
        
    def cmd_chargs(self, *args):
        sys.argv[1:] = args
        print("argv:", sys.argv)
        return self.wait or self.connection.poll()
        
    def cmd_chdir(self, workingdir):
        try:
            os.chdir(workingdir)
        except OSError as e:
            print("chdir failed:", e)
        else:
            print("chdir:", workingdir)
        return self.wait or self.connection.poll()
        
    def cmd_inspect(self, *keys):
        if self.wait:
            print('inspect:', '.'.join(keys))
            expanded = self.expanded
            for key in keys[:-1]:
                expanded = expanded.setdefault(key, {})
            key = keys[-1]
            if key in expanded:
                del expanded[key]
            else:
                expanded[key] = {}
            self.rsend_stack(keepframe=True)
            return True
        else:
            return self.connection.poll()
        
    ###
    
    def _runscript(self, filename):
        # The script has to run in __main__ namespace (or imports from
        # __main__ will break).
        #
        # So we clear up the __main__ and set several special variables
        # (this gets rid of globals and cleans old variables on restarts).
        import __main__
        __main__.__dict__.clear()
        __main__.__dict__.update({"__name__"    : "__main__",
                                  "__file__"    : filename,
                                  "__builtins__": __builtins__,
                                 })
        
        # When bdb sets tracing, a number of call and line events happens
        # BEFORE debugger even reaches user's code (and the exact sequence of
        # events depends on python version). So we take special measures to
        # avoid stopping before we reach the main script (see user_line and
        # user_call for details).
        self._wait_for_mainpyfile = 1
        self.mainpyfile = self.canonic(filename)
        self._user_requested_quit = 0
        with open(filename, "rb") as fp:
            statement = "exec(compile(%r, %r, 'exec'))" % (fp.read(), self.mainpyfile)
        self.run(statement)
        
        
def main():
    print('\nStarting ...')
    import sys, os
    print('Interpreter:', sys.version)
    address =  sys.argv[1]
    mainpyfile =  sys.argv[2]
    del sys.argv[0:2]         # Hide the debugger script and address from argument list
    sys.path[0] = os.path.dirname(mainpyfile)
    print('='*40)
    
    connection = multiprocessing.connection.Client(address, authkey=AUTHKEY)
    rpdb = RPdb(connection)
    while True:
        try:
            rpdb._runscript(mainpyfile)
        except Restart:
            print('Restarting', mainpyfile, 'with arguments:')
            print('\t' + ' '.join(sys.argv[1:]))
            continue
        except SystemExit:
            # In most cases SystemExit does not warrant a post-mortem session.
            print('The program exited via sys.exit(). Exit status:', sys.exc_info()[1])
        except:
            sys.excepthook(*sys.exc_info())
            print('Uncaught exception. Entering post mortem debugging')
            print("Running 'cont' or 'step' will exit the program")
            t = sys.exc_info()[2]
            rpdb.interaction(None, t)
            print('Post mortem debugger finished.')
        break
    connection.close()
    print('Program exited.')
    
    
if __name__ == '__main__':
    import run_pdb
    run_pdb.main()