blob: dd1f4287c1b0e4b0a94ffc9ccb8914b15fbb67f5 [file] [log] [blame]
Guido van Rossum4acc25b2000-02-02 15:10:15 +00001"""Debugger basics"""
Guido van Rossumbabe2bf1992-01-22 22:21:31 +00002
Georg Brandl243ad662009-05-05 09:00:19 +00003import fnmatch
Guido van Rossumbabe2bf1992-01-22 22:21:31 +00004import sys
Barry Warsaw148ffbc1999-09-09 23:24:33 +00005import os
Guido van Rossumbabe2bf1992-01-22 22:21:31 +00006
Georg Brandl26607472010-11-29 20:12:24 +00007__all__ = ["BdbQuit", "Bdb", "Breakpoint"]
Skip Montanaroe99d5ea2001-01-20 19:54:20 +00008
Neal Norwitz93cf79f2002-03-31 14:06:41 +00009class BdbQuit(Exception):
Georg Brandl26607472010-11-29 20:12:24 +000010 """Exception to give up completely."""
Guido van Rossumbabe2bf1992-01-22 22:21:31 +000011
12
Guido van Rossum6ea27cc1999-01-25 20:51:34 +000013class Bdb:
Guido van Rossum4acc25b2000-02-02 15:10:15 +000014 """Generic Python debugger base class.
Guido van Rossum6ea27cc1999-01-25 20:51:34 +000015
Guido van Rossum4acc25b2000-02-02 15:10:15 +000016 This class takes care of details of the trace facility;
17 a derived class should implement user interaction.
18 The standard debugger class (pdb.Pdb) is an example.
19 """
Guido van Rossum6ea27cc1999-01-25 20:51:34 +000020
Georg Brandl243ad662009-05-05 09:00:19 +000021 def __init__(self, skip=None):
22 self.skip = set(skip) if skip else None
Guido van Rossum4acc25b2000-02-02 15:10:15 +000023 self.breaks = {}
24 self.fncache = {}
Senthil Kumaran42d70812012-05-01 10:07:49 +080025 self.frame_returning = None
Barry Warsaw148ffbc1999-09-09 23:24:33 +000026
Guido van Rossum4acc25b2000-02-02 15:10:15 +000027 def canonic(self, filename):
Guido van Rossum42f53322001-11-29 02:50:15 +000028 if filename == "<" + filename[1:-1] + ">":
29 return filename
Guido van Rossum4acc25b2000-02-02 15:10:15 +000030 canonic = self.fncache.get(filename)
31 if not canonic:
32 canonic = os.path.abspath(filename)
Guido van Rossumbdba3202002-02-25 23:23:24 +000033 canonic = os.path.normcase(canonic)
Guido van Rossum4acc25b2000-02-02 15:10:15 +000034 self.fncache[filename] = canonic
35 return canonic
Tim Peters11cf6052001-01-14 21:54:20 +000036
Guido van Rossum4acc25b2000-02-02 15:10:15 +000037 def reset(self):
38 import linecache
39 linecache.checkcache()
40 self.botframe = None
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000041 self._set_stopinfo(None, None)
Tim Peters11cf6052001-01-14 21:54:20 +000042
Guido van Rossum4acc25b2000-02-02 15:10:15 +000043 def trace_dispatch(self, frame, event, arg):
44 if self.quitting:
45 return # None
46 if event == 'line':
47 return self.dispatch_line(frame)
48 if event == 'call':
49 return self.dispatch_call(frame, arg)
50 if event == 'return':
51 return self.dispatch_return(frame, arg)
52 if event == 'exception':
53 return self.dispatch_exception(frame, arg)
Nicholas Bastinc69ebe82004-03-24 21:57:10 +000054 if event == 'c_call':
55 return self.trace_dispatch
56 if event == 'c_exception':
57 return self.trace_dispatch
58 if event == 'c_return':
59 return self.trace_dispatch
Guido van Rossumbe19ed72007-02-09 05:37:30 +000060 print('bdb.Bdb.dispatch: unknown debugging event:', repr(event))
Guido van Rossum4acc25b2000-02-02 15:10:15 +000061 return self.trace_dispatch
Tim Peters11cf6052001-01-14 21:54:20 +000062
Guido van Rossum4acc25b2000-02-02 15:10:15 +000063 def dispatch_line(self, frame):
64 if self.stop_here(frame) or self.break_here(frame):
65 self.user_line(frame)
66 if self.quitting: raise BdbQuit
67 return self.trace_dispatch
Tim Peters11cf6052001-01-14 21:54:20 +000068
Guido van Rossum4acc25b2000-02-02 15:10:15 +000069 def dispatch_call(self, frame, arg):
70 # XXX 'arg' is no longer used
71 if self.botframe is None:
72 # First call of dispatch since reset()
Christian Tismer313a7512002-05-28 08:04:00 +000073 self.botframe = frame.f_back # (CT) Note that this may also be None!
Guido van Rossum4acc25b2000-02-02 15:10:15 +000074 return self.trace_dispatch
75 if not (self.stop_here(frame) or self.break_anywhere(frame)):
76 # No need to trace this function
77 return # None
78 self.user_call(frame, arg)
79 if self.quitting: raise BdbQuit
80 return self.trace_dispatch
Tim Peters11cf6052001-01-14 21:54:20 +000081
Guido van Rossum4acc25b2000-02-02 15:10:15 +000082 def dispatch_return(self, frame, arg):
83 if self.stop_here(frame) or frame == self.returnframe:
Senthil Kumaran42d70812012-05-01 10:07:49 +080084 try:
85 self.frame_returning = frame
86 self.user_return(frame, arg)
87 finally:
88 self.frame_returning = None
Guido van Rossum4acc25b2000-02-02 15:10:15 +000089 if self.quitting: raise BdbQuit
Just van Rossumae1f65f2001-06-25 18:01:24 +000090 return self.trace_dispatch
Tim Peters11cf6052001-01-14 21:54:20 +000091
Guido van Rossum4acc25b2000-02-02 15:10:15 +000092 def dispatch_exception(self, frame, arg):
93 if self.stop_here(frame):
94 self.user_exception(frame, arg)
95 if self.quitting: raise BdbQuit
96 return self.trace_dispatch
Tim Peters11cf6052001-01-14 21:54:20 +000097
Guido van Rossum4acc25b2000-02-02 15:10:15 +000098 # Normally derived classes don't override the following
99 # methods, but they may if they want to redefine the
100 # definition of stopping and breakpoints.
Tim Peters11cf6052001-01-14 21:54:20 +0000101
Georg Brandl243ad662009-05-05 09:00:19 +0000102 def is_skipped_module(self, module_name):
103 for pattern in self.skip:
104 if fnmatch.fnmatch(module_name, pattern):
105 return True
106 return False
107
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000108 def stop_here(self, frame):
Neal Norwitz72a2b4d2002-05-29 00:54:38 +0000109 # (CT) stopframe may now also be None, see dispatch_call.
110 # (CT) the former test for None is therefore removed from here.
Georg Brandl243ad662009-05-05 09:00:19 +0000111 if self.skip and \
112 self.is_skipped_module(frame.f_globals.get('__name__')):
113 return False
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000114 if frame is self.stopframe:
Georg Brandl3f940892010-07-30 10:29:19 +0000115 if self.stoplineno == -1:
116 return False
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000117 return frame.f_lineno >= self.stoplineno
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000118 while frame is not None and frame is not self.stopframe:
119 if frame is self.botframe:
Tim Petersbc0e9102002-04-04 22:55:58 +0000120 return True
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000121 frame = frame.f_back
Tim Petersbc0e9102002-04-04 22:55:58 +0000122 return False
Guido van Rossumd93643f1998-09-11 22:38:35 +0000123
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000124 def break_here(self, frame):
125 filename = self.canonic(frame.f_code.co_filename)
Georg Brandl26607472010-11-29 20:12:24 +0000126 if filename not in self.breaks:
Tim Petersbc0e9102002-04-04 22:55:58 +0000127 return False
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000128 lineno = frame.f_lineno
Georg Brandl26607472010-11-29 20:12:24 +0000129 if lineno not in self.breaks[filename]:
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000130 # The line itself has no breakpoint, but maybe the line is the
131 # first line of a function with breakpoint set by function name.
132 lineno = frame.f_code.co_firstlineno
Georg Brandl26607472010-11-29 20:12:24 +0000133 if lineno not in self.breaks[filename]:
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000134 return False
135
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000136 # flag says ok to delete temp. bp
137 (bp, flag) = effective(filename, lineno, frame)
138 if bp:
139 self.currentbp = bp.number
140 if (flag and bp.temporary):
141 self.do_clear(str(bp.number))
Tim Petersbc0e9102002-04-04 22:55:58 +0000142 return True
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000143 else:
Tim Petersbc0e9102002-04-04 22:55:58 +0000144 return False
Tim Peters11cf6052001-01-14 21:54:20 +0000145
Guido van Rossum9cec8fb2001-04-08 15:05:16 +0000146 def do_clear(self, arg):
Collin Winterce36ad82007-08-30 01:19:48 +0000147 raise NotImplementedError("subclass of bdb must implement do_clear()")
Guido van Rossum9cec8fb2001-04-08 15:05:16 +0000148
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000149 def break_anywhere(self, frame):
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000150 return self.canonic(frame.f_code.co_filename) in self.breaks
Tim Peters11cf6052001-01-14 21:54:20 +0000151
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000152 # Derived classes should override the user_* methods
153 # to gain control.
Tim Peters11cf6052001-01-14 21:54:20 +0000154
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000155 def user_call(self, frame, argument_list):
156 """This method is called when there is the remote possibility
157 that we ever need to stop in this function."""
158 pass
Tim Peters11cf6052001-01-14 21:54:20 +0000159
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000160 def user_line(self, frame):
161 """This method is called when we stop or break at this line."""
162 pass
Tim Peters11cf6052001-01-14 21:54:20 +0000163
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000164 def user_return(self, frame, return_value):
165 """This method is called when a return trap is set here."""
166 pass
Tim Peters11cf6052001-01-14 21:54:20 +0000167
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000168 def user_exception(self, frame, exc_info):
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000169 """This method is called if an exception occurs,
170 but only if we are to stop at or just below this level."""
171 pass
Tim Peters11cf6052001-01-14 21:54:20 +0000172
Georg Brandl3f940892010-07-30 10:29:19 +0000173 def _set_stopinfo(self, stopframe, returnframe, stoplineno=0):
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000174 self.stopframe = stopframe
175 self.returnframe = returnframe
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000176 self.quitting = False
Georg Brandl3f940892010-07-30 10:29:19 +0000177 # stoplineno >= 0 means: stop at line >= the stoplineno
178 # stoplineno -1 means: don't stop at all
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000179 self.stoplineno = stoplineno
180
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000181 # Derived classes and clients can call the following methods
182 # to affect the stepping state.
Tim Peters11cf6052001-01-14 21:54:20 +0000183
Georg Brandl2dfec552010-07-30 08:43:32 +0000184 def set_until(self, frame, lineno=None):
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000185 """Stop when the line with the line no greater than the current one is
186 reached or when returning from current frame"""
Georg Brandl2dfec552010-07-30 08:43:32 +0000187 # the name "until" is borrowed from gdb
188 if lineno is None:
189 lineno = frame.f_lineno + 1
190 self._set_stopinfo(frame, frame, lineno)
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000191
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000192 def set_step(self):
193 """Stop after one line of code."""
Senthil Kumaran42d70812012-05-01 10:07:49 +0800194 # Issue #13183: pdb skips frames after hitting a breakpoint and running
195 # step commands.
196 # Restore the trace function in the caller (that may not have been set
197 # for performance reasons) when returning from the current frame.
198 if self.frame_returning:
199 caller_frame = self.frame_returning.f_back
200 if caller_frame and not caller_frame.f_trace:
201 caller_frame.f_trace = self.trace_dispatch
Georg Brandl3f940892010-07-30 10:29:19 +0000202 self._set_stopinfo(None, None)
Tim Peters11cf6052001-01-14 21:54:20 +0000203
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000204 def set_next(self, frame):
205 """Stop on the next line in or below the given frame."""
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000206 self._set_stopinfo(frame, None)
Tim Peters11cf6052001-01-14 21:54:20 +0000207
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000208 def set_return(self, frame):
209 """Stop when returning from the given frame."""
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000210 self._set_stopinfo(frame.f_back, frame)
Tim Peters11cf6052001-01-14 21:54:20 +0000211
Johannes Gijsbers84a6c202004-11-07 11:35:30 +0000212 def set_trace(self, frame=None):
213 """Start debugging from `frame`.
214
215 If frame is not specified, debugging starts from caller's frame.
216 """
217 if frame is None:
218 frame = sys._getframe().f_back
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000219 self.reset()
220 while frame:
221 frame.f_trace = self.trace_dispatch
222 self.botframe = frame
223 frame = frame.f_back
224 self.set_step()
225 sys.settrace(self.trace_dispatch)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000226
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000227 def set_continue(self):
228 # Don't stop except at breakpoints or when finished
Georg Brandl3f940892010-07-30 10:29:19 +0000229 self._set_stopinfo(self.botframe, None, -1)
Georg Brandlf8b893e2010-12-04 16:22:44 +0000230 if not self.breaks:
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000231 # no breakpoints; run without debugger overhead
232 sys.settrace(None)
Christian Tismer313a7512002-05-28 08:04:00 +0000233 frame = sys._getframe().f_back
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000234 while frame and frame is not self.botframe:
235 del frame.f_trace
236 frame = frame.f_back
Tim Peters11cf6052001-01-14 21:54:20 +0000237
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000238 def set_quit(self):
239 self.stopframe = self.botframe
240 self.returnframe = None
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000241 self.quitting = True
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000242 sys.settrace(None)
Tim Peters11cf6052001-01-14 21:54:20 +0000243
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000244 # Derived classes and clients can call the following methods
245 # to manipulate breakpoints. These methods return an
246 # error message is something went wrong, None if all is well.
247 # Set_break prints out the breakpoint line and file:lineno.
248 # Call self.get_*break*() to see the breakpoints or better
249 # for bp in Breakpoint.bpbynumber: if bp: bp.bpprint().
Tim Peters11cf6052001-01-14 21:54:20 +0000250
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000251 def set_break(self, filename, lineno, temporary=False, cond=None,
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000252 funcname=None):
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000253 filename = self.canonic(filename)
254 import linecache # Import as late as possible
255 line = linecache.getline(filename, lineno)
256 if not line:
Georg Brandl26607472010-11-29 20:12:24 +0000257 return 'Line %s:%d does not exist' % (filename, lineno)
258 list = self.breaks.setdefault(filename, [])
259 if lineno not in list:
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000260 list.append(lineno)
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000261 bp = Breakpoint(filename, lineno, temporary, cond, funcname)
Guido van Rossumd93643f1998-09-11 22:38:35 +0000262
Senthil Kumaran6f107042010-11-29 11:54:17 +0000263 def _prune_breaks(self, filename, lineno):
264 if (filename, lineno) not in Breakpoint.bplist:
265 self.breaks[filename].remove(lineno)
266 if not self.breaks[filename]:
267 del self.breaks[filename]
268
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000269 def clear_break(self, filename, lineno):
270 filename = self.canonic(filename)
Georg Brandl26607472010-11-29 20:12:24 +0000271 if filename not in self.breaks:
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000272 return 'There are no breakpoints in %s' % filename
273 if lineno not in self.breaks[filename]:
Georg Brandl26607472010-11-29 20:12:24 +0000274 return 'There is no breakpoint at %s:%d' % (filename, lineno)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000275 # If there's only one bp in the list for that file,line
276 # pair, then remove the breaks entry
277 for bp in Breakpoint.bplist[filename, lineno][:]:
278 bp.deleteMe()
Senthil Kumaran6f107042010-11-29 11:54:17 +0000279 self._prune_breaks(filename, lineno)
Tim Peters11cf6052001-01-14 21:54:20 +0000280
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000281 def clear_bpbynumber(self, arg):
282 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000283 bp = self.get_bpbynumber(arg)
284 except ValueError as err:
285 return str(err)
Senthil Kumaran6f107042010-11-29 11:54:17 +0000286 bp.deleteMe()
287 self._prune_breaks(bp.file, bp.line)
Guido van Rossum6ea27cc1999-01-25 20:51:34 +0000288
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000289 def clear_all_file_breaks(self, filename):
290 filename = self.canonic(filename)
Georg Brandl26607472010-11-29 20:12:24 +0000291 if filename not in self.breaks:
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000292 return 'There are no breakpoints in %s' % filename
293 for line in self.breaks[filename]:
294 blist = Breakpoint.bplist[filename, line]
295 for bp in blist:
296 bp.deleteMe()
297 del self.breaks[filename]
Tim Peters11cf6052001-01-14 21:54:20 +0000298
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000299 def clear_all_breaks(self):
300 if not self.breaks:
301 return 'There are no breakpoints'
302 for bp in Breakpoint.bpbynumber:
303 if bp:
304 bp.deleteMe()
305 self.breaks = {}
Tim Peters11cf6052001-01-14 21:54:20 +0000306
Georg Brandl7410dd12010-07-30 12:01:20 +0000307 def get_bpbynumber(self, arg):
308 if not arg:
309 raise ValueError('Breakpoint number expected')
310 try:
311 number = int(arg)
312 except ValueError:
313 raise ValueError('Non-numeric breakpoint number %s' % arg)
314 try:
315 bp = Breakpoint.bpbynumber[number]
316 except IndexError:
317 raise ValueError('Breakpoint number %d out of range' % number)
318 if bp is None:
319 raise ValueError('Breakpoint %d already deleted' % number)
320 return bp
321
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000322 def get_break(self, filename, lineno):
323 filename = self.canonic(filename)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000324 return filename in self.breaks and \
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000325 lineno in self.breaks[filename]
Tim Peters11cf6052001-01-14 21:54:20 +0000326
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000327 def get_breaks(self, filename, lineno):
328 filename = self.canonic(filename)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000329 return filename in self.breaks and \
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000330 lineno in self.breaks[filename] and \
331 Breakpoint.bplist[filename, lineno] or []
Tim Peters11cf6052001-01-14 21:54:20 +0000332
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000333 def get_file_breaks(self, filename):
334 filename = self.canonic(filename)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000335 if filename in self.breaks:
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000336 return self.breaks[filename]
337 else:
338 return []
Tim Peters11cf6052001-01-14 21:54:20 +0000339
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000340 def get_all_breaks(self):
341 return self.breaks
Tim Peters11cf6052001-01-14 21:54:20 +0000342
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000343 # Derived classes and clients can call the following method
344 # to get a data structure representing a stack trace.
Tim Peters11cf6052001-01-14 21:54:20 +0000345
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000346 def get_stack(self, f, t):
347 stack = []
348 if t and t.tb_frame is f:
349 t = t.tb_next
350 while f is not None:
351 stack.append((f, f.f_lineno))
352 if f is self.botframe:
353 break
354 f = f.f_back
355 stack.reverse()
356 i = max(0, len(stack) - 1)
357 while t is not None:
358 stack.append((t.tb_frame, t.tb_lineno))
359 t = t.tb_next
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +0000360 if f is None:
361 i = max(0, len(stack) - 1)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000362 return stack, i
Tim Peters11cf6052001-01-14 21:54:20 +0000363
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000364 def format_stack_entry(self, frame_lineno, lprefix=': '):
Alexandre Vassalotti1f2ba4b2008-05-16 07:12:44 +0000365 import linecache, reprlib
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000366 frame, lineno = frame_lineno
367 filename = self.canonic(frame.f_code.co_filename)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000368 s = '%s(%r)' % (filename, lineno)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000369 if frame.f_code.co_name:
Georg Brandl26607472010-11-29 20:12:24 +0000370 s += frame.f_code.co_name
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000371 else:
Georg Brandl26607472010-11-29 20:12:24 +0000372 s += "<lambda>"
Raymond Hettinger54f02222002-06-01 14:18:47 +0000373 if '__args__' in frame.f_locals:
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000374 args = frame.f_locals['__args__']
375 else:
376 args = None
377 if args:
Georg Brandl26607472010-11-29 20:12:24 +0000378 s += reprlib.repr(args)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000379 else:
Georg Brandl26607472010-11-29 20:12:24 +0000380 s += '()'
Raymond Hettinger54f02222002-06-01 14:18:47 +0000381 if '__return__' in frame.f_locals:
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000382 rv = frame.f_locals['__return__']
Georg Brandl26607472010-11-29 20:12:24 +0000383 s += '->'
384 s += reprlib.repr(rv)
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000385 line = linecache.getline(filename, lineno, frame.f_globals)
Georg Brandl26607472010-11-29 20:12:24 +0000386 if line:
387 s += lprefix + line.strip()
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000388 return s
Tim Peters11cf6052001-01-14 21:54:20 +0000389
Georg Brandl46b9afc2010-07-30 09:14:20 +0000390 # The following methods can be called by clients to use
391 # a debugger to debug a statement or an expression.
392 # Both can be given as a string, or a code object.
Tim Peters11cf6052001-01-14 21:54:20 +0000393
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000394 def run(self, cmd, globals=None, locals=None):
395 if globals is None:
396 import __main__
397 globals = __main__.__dict__
398 if locals is None:
399 locals = globals
400 self.reset()
Victor Stinner4bd81722011-01-06 00:49:38 +0000401 if isinstance(cmd, str):
402 cmd = compile(cmd, "<string>", "exec")
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000403 sys.settrace(self.trace_dispatch)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000404 try:
Martin v. Löwisede8ffb2008-03-30 20:43:50 +0000405 exec(cmd, globals, locals)
406 except BdbQuit:
407 pass
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000408 finally:
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000409 self.quitting = True
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000410 sys.settrace(None)
Tim Peters11cf6052001-01-14 21:54:20 +0000411
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000412 def runeval(self, expr, globals=None, locals=None):
413 if globals is None:
414 import __main__
415 globals = __main__.__dict__
416 if locals is None:
417 locals = globals
418 self.reset()
419 sys.settrace(self.trace_dispatch)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000420 try:
Martin v. Löwisede8ffb2008-03-30 20:43:50 +0000421 return eval(expr, globals, locals)
422 except BdbQuit:
423 pass
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000424 finally:
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000425 self.quitting = True
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000426 sys.settrace(None)
Guido van Rossum5e38b6f1995-02-27 13:13:40 +0000427
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000428 def runctx(self, cmd, globals, locals):
429 # B/W compatibility
430 self.run(cmd, globals, locals)
Guido van Rossum4e160981992-09-02 20:43:20 +0000431
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000432 # This method is more useful to debug a single function call.
Guido van Rossum4e160981992-09-02 20:43:20 +0000433
Raymond Hettinger2ef7e6c2004-10-24 00:32:24 +0000434 def runcall(self, func, *args, **kwds):
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000435 self.reset()
436 sys.settrace(self.trace_dispatch)
437 res = None
438 try:
Martin v. Löwisede8ffb2008-03-30 20:43:50 +0000439 res = func(*args, **kwds)
440 except BdbQuit:
441 pass
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000442 finally:
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000443 self.quitting = True
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000444 sys.settrace(None)
445 return res
Guido van Rossumbabe2bf1992-01-22 22:21:31 +0000446
Guido van Rossumbabe2bf1992-01-22 22:21:31 +0000447
Guido van Rossumb6775db1994-08-01 11:34:53 +0000448def set_trace():
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000449 Bdb().set_trace()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000450
Guido van Rossumd93643f1998-09-11 22:38:35 +0000451
452class Breakpoint:
Georg Brandl26607472010-11-29 20:12:24 +0000453 """Breakpoint class.
Guido van Rossumd93643f1998-09-11 22:38:35 +0000454
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000455 Implements temporary breakpoints, ignore counts, disabling and
456 (re)-enabling, and conditionals.
Guido van Rossumd93643f1998-09-11 22:38:35 +0000457
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000458 Breakpoints are indexed by number through bpbynumber and by
459 the file,line tuple using bplist. The former points to a
460 single instance of class Breakpoint. The latter points to a
461 list of such instances since there may be more than one
462 breakpoint per line.
Guido van Rossumd93643f1998-09-11 22:38:35 +0000463
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000464 """
Guido van Rossumd93643f1998-09-11 22:38:35 +0000465
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000466 # XXX Keeping state in the class is a mistake -- this means
467 # you cannot have more than one active Bdb instance.
Guido van Rossumd93643f1998-09-11 22:38:35 +0000468
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000469 next = 1 # Next bp to be assigned
470 bplist = {} # indexed by (file, lineno) tuple
471 bpbynumber = [None] # Each entry is None or an instance of Bpt
472 # index 0 is unused, except for marking an
473 # effective break .... see effective()
Guido van Rossumd93643f1998-09-11 22:38:35 +0000474
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000475 def __init__(self, file, line, temporary=False, cond=None, funcname=None):
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000476 self.funcname = funcname
477 # Needed if funcname is not None.
478 self.func_first_executable_line = None
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000479 self.file = file # This better be in canonical form!
480 self.line = line
481 self.temporary = temporary
482 self.cond = cond
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000483 self.enabled = True
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000484 self.ignore = 0
485 self.hits = 0
486 self.number = Breakpoint.next
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000487 Breakpoint.next += 1
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000488 # Build the two lists
489 self.bpbynumber.append(self)
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000490 if (file, line) in self.bplist:
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000491 self.bplist[file, line].append(self)
492 else:
493 self.bplist[file, line] = [self]
Guido van Rossumd93643f1998-09-11 22:38:35 +0000494
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000495 def deleteMe(self):
496 index = (self.file, self.line)
497 self.bpbynumber[self.number] = None # No longer in list
498 self.bplist[index].remove(self)
499 if not self.bplist[index]:
500 # No more bp for this f:l combo
501 del self.bplist[index]
Guido van Rossumd93643f1998-09-11 22:38:35 +0000502
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000503 def enable(self):
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000504 self.enabled = True
Guido van Rossumd93643f1998-09-11 22:38:35 +0000505
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000506 def disable(self):
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000507 self.enabled = False
Guido van Rossumd93643f1998-09-11 22:38:35 +0000508
Thomas Wouters477c8d52006-05-27 19:21:47 +0000509 def bpprint(self, out=None):
510 if out is None:
511 out = sys.stdout
Georg Brandld2fd4ca2010-07-30 15:01:23 +0000512 print(self.bpformat(), file=out)
513
514 def bpformat(self):
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000515 if self.temporary:
Tim Peters11cf6052001-01-14 21:54:20 +0000516 disp = 'del '
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000517 else:
Tim Peters11cf6052001-01-14 21:54:20 +0000518 disp = 'keep '
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000519 if self.enabled:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000520 disp = disp + 'yes '
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000521 else:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000522 disp = disp + 'no '
Georg Brandld2fd4ca2010-07-30 15:01:23 +0000523 ret = '%-4dbreakpoint %s at %s:%d' % (self.number, disp,
524 self.file, self.line)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000525 if self.cond:
Georg Brandld2fd4ca2010-07-30 15:01:23 +0000526 ret += '\n\tstop only if %s' % (self.cond,)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000527 if self.ignore:
Georg Brandld2fd4ca2010-07-30 15:01:23 +0000528 ret += '\n\tignore next %d hits' % (self.ignore,)
529 if self.hits:
530 if self.hits > 1:
531 ss = 's'
532 else:
533 ss = ''
534 ret += '\n\tbreakpoint already hit %d time%s' % (self.hits, ss)
535 return ret
Guido van Rossumd93643f1998-09-11 22:38:35 +0000536
Georg Brandl7410dd12010-07-30 12:01:20 +0000537 def __str__(self):
538 return 'breakpoint %s at %s:%s' % (self.number, self.file, self.line)
539
Guido van Rossumd93643f1998-09-11 22:38:35 +0000540# -----------end of Breakpoint class----------
541
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000542def checkfuncname(b, frame):
543 """Check whether we should break here because of `b.funcname`."""
544 if not b.funcname:
545 # Breakpoint was set via line number.
546 if b.line != frame.f_lineno:
547 # Breakpoint was set at a line with a def statement and the function
548 # defined is called: don't break.
549 return False
550 return True
551
552 # Breakpoint set via function name.
553
554 if frame.f_code.co_name != b.funcname:
555 # It's not a function call, but rather execution of def statement.
556 return False
557
558 # We are in the right frame.
559 if not b.func_first_executable_line:
560 # The function is entered for the 1st time.
561 b.func_first_executable_line = frame.f_lineno
562
563 if b.func_first_executable_line != frame.f_lineno:
564 # But we are not at the first line number: don't break.
565 return False
566 return True
567
Guido van Rossumd93643f1998-09-11 22:38:35 +0000568# Determines if there is an effective (active) breakpoint at this
569# line of code. Returns breakpoint number or 0 if none
570def effective(file, line, frame):
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000571 """Determine which breakpoint for this file:line is to be acted upon.
Guido van Rossumd93643f1998-09-11 22:38:35 +0000572
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000573 Called only if we know there is a bpt at this
574 location. Returns breakpoint that was triggered and a flag
575 that indicates if it is ok to delete a temporary bp.
Guido van Rossumd93643f1998-09-11 22:38:35 +0000576
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000577 """
Georg Brandl9aed6cc2010-11-26 12:05:27 +0000578 possibles = Breakpoint.bplist[file, line]
579 for b in possibles:
580 if not b.enabled:
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000581 continue
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000582 if not checkfuncname(b, frame):
583 continue
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000584 # Count every hit when bp is enabled
Georg Brandl9aed6cc2010-11-26 12:05:27 +0000585 b.hits += 1
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000586 if not b.cond:
Georg Brandl9aed6cc2010-11-26 12:05:27 +0000587 # If unconditional, and ignoring go on to next, else break
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000588 if b.ignore > 0:
Georg Brandl9aed6cc2010-11-26 12:05:27 +0000589 b.ignore -= 1
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000590 continue
591 else:
Georg Brandl9aed6cc2010-11-26 12:05:27 +0000592 # breakpoint and marker that it's ok to delete if temporary
593 return (b, True)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000594 else:
595 # Conditional bp.
596 # Ignore count applies only to those bpt hits where the
597 # condition evaluates to true.
598 try:
Georg Brandl9aed6cc2010-11-26 12:05:27 +0000599 val = eval(b.cond, frame.f_globals, frame.f_locals)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000600 if val:
601 if b.ignore > 0:
Georg Brandl9aed6cc2010-11-26 12:05:27 +0000602 b.ignore -= 1
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000603 # continue
604 else:
Georg Brandl9aed6cc2010-11-26 12:05:27 +0000605 return (b, True)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000606 # else:
607 # continue
608 except:
Georg Brandl9aed6cc2010-11-26 12:05:27 +0000609 # if eval fails, most conservative thing is to stop on
610 # breakpoint regardless of ignore count. Don't delete
611 # temporary, as another hint to user.
612 return (b, False)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000613 return (None, None)
Guido van Rossumd93643f1998-09-11 22:38:35 +0000614
Georg Brandl26607472010-11-29 20:12:24 +0000615
Guido van Rossumbabe2bf1992-01-22 22:21:31 +0000616# -------------------- testing --------------------
617
618class Tdb(Bdb):
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000619 def user_call(self, frame, args):
620 name = frame.f_code.co_name
621 if not name: name = '???'
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000622 print('+++ call', name, args)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000623 def user_line(self, frame):
Eric S. Raymondb49f4a42001-02-09 05:07:04 +0000624 import linecache
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000625 name = frame.f_code.co_name
626 if not name: name = '???'
627 fn = self.canonic(frame.f_code.co_filename)
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000628 line = linecache.getline(fn, frame.f_lineno, frame.f_globals)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000629 print('+++', fn, frame.f_lineno, name, ':', line.strip())
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000630 def user_return(self, frame, retval):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000631 print('+++ return', retval)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000632 def user_exception(self, frame, exc_stuff):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000633 print('+++ exception', exc_stuff)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000634 self.set_continue()
Guido van Rossumbabe2bf1992-01-22 22:21:31 +0000635
636def foo(n):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000637 print('foo(', n, ')')
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000638 x = bar(n*10)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000639 print('bar returned', x)
Guido van Rossumbabe2bf1992-01-22 22:21:31 +0000640
641def bar(a):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000642 print('bar(', a, ')')
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000643 return a/2
Guido van Rossumbabe2bf1992-01-22 22:21:31 +0000644
645def test():
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000646 t = Tdb()
647 t.run('import bdb; bdb.foo(10)')