blob: 18491da897357e152dfe92527b361bf0765002db [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
Pablo Galindoc7ab5812018-01-29 01:31:00 +00006from inspect import CO_GENERATOR, CO_COROUTINE, CO_ASYNC_GENERATOR
Guido van Rossumbabe2bf1992-01-22 22:21:31 +00007
Georg Brandl26607472010-11-29 20:12:24 +00008__all__ = ["BdbQuit", "Bdb", "Breakpoint"]
Skip Montanaroe99d5ea2001-01-20 19:54:20 +00009
Pablo Galindoc7ab5812018-01-29 01:31:00 +000010GENERATOR_AND_COROUTINE_FLAGS = CO_GENERATOR | CO_COROUTINE | CO_ASYNC_GENERATOR
11
csabella0774e792017-05-16 18:28:02 -040012
Neal Norwitz93cf79f2002-03-31 14:06:41 +000013class BdbQuit(Exception):
Georg Brandl26607472010-11-29 20:12:24 +000014 """Exception to give up completely."""
Guido van Rossumbabe2bf1992-01-22 22:21:31 +000015
16
Guido van Rossum6ea27cc1999-01-25 20:51:34 +000017class Bdb:
Guido van Rossum4acc25b2000-02-02 15:10:15 +000018 """Generic Python debugger base class.
Guido van Rossum6ea27cc1999-01-25 20:51:34 +000019
Guido van Rossum4acc25b2000-02-02 15:10:15 +000020 This class takes care of details of the trace facility;
21 a derived class should implement user interaction.
22 The standard debugger class (pdb.Pdb) is an example.
csabella0774e792017-05-16 18:28:02 -040023
24 The optional skip argument must be an iterable of glob-style
25 module name patterns. The debugger will not step into frames
26 that originate in a module that matches one of these patterns.
27 Whether a frame is considered to originate in a certain module
28 is determined by the __name__ in the frame globals.
Guido van Rossum4acc25b2000-02-02 15:10:15 +000029 """
Guido van Rossum6ea27cc1999-01-25 20:51:34 +000030
Georg Brandl243ad662009-05-05 09:00:19 +000031 def __init__(self, skip=None):
32 self.skip = set(skip) if skip else None
Guido van Rossum4acc25b2000-02-02 15:10:15 +000033 self.breaks = {}
34 self.fncache = {}
Senthil Kumaran42d70812012-05-01 10:07:49 +080035 self.frame_returning = None
Barry Warsaw148ffbc1999-09-09 23:24:33 +000036
Guido van Rossum4acc25b2000-02-02 15:10:15 +000037 def canonic(self, filename):
csabella0774e792017-05-16 18:28:02 -040038 """Return canonical form of filename.
39
40 For real filenames, the canonical form is a case-normalized (on
Miss Islington (bot)4bd1d052019-08-30 13:42:54 -070041 case insensitive filesystems) absolute path. 'Filenames' with
csabella0774e792017-05-16 18:28:02 -040042 angle brackets, such as "<stdin>", generated in interactive
43 mode, are returned unchanged.
44 """
Guido van Rossum42f53322001-11-29 02:50:15 +000045 if filename == "<" + filename[1:-1] + ">":
46 return filename
Guido van Rossum4acc25b2000-02-02 15:10:15 +000047 canonic = self.fncache.get(filename)
48 if not canonic:
49 canonic = os.path.abspath(filename)
Guido van Rossumbdba3202002-02-25 23:23:24 +000050 canonic = os.path.normcase(canonic)
Guido van Rossum4acc25b2000-02-02 15:10:15 +000051 self.fncache[filename] = canonic
52 return canonic
Tim Peters11cf6052001-01-14 21:54:20 +000053
Guido van Rossum4acc25b2000-02-02 15:10:15 +000054 def reset(self):
csabella0774e792017-05-16 18:28:02 -040055 """Set values of attributes as ready to start debugging."""
Guido van Rossum4acc25b2000-02-02 15:10:15 +000056 import linecache
57 linecache.checkcache()
58 self.botframe = None
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000059 self._set_stopinfo(None, None)
Tim Peters11cf6052001-01-14 21:54:20 +000060
Guido van Rossum4acc25b2000-02-02 15:10:15 +000061 def trace_dispatch(self, frame, event, arg):
csabella0774e792017-05-16 18:28:02 -040062 """Dispatch a trace function for debugged frames based on the event.
63
64 This function is installed as the trace function for debugged
65 frames. Its return value is the new trace function, which is
66 usually itself. The default implementation decides how to
67 dispatch a frame, depending on the type of event (passed in as a
68 string) that is about to be executed.
69
70 The event can be one of the following:
71 line: A new line of code is going to be executed.
72 call: A function is about to be called or another code block
73 is entered.
74 return: A function or other code block is about to return.
75 exception: An exception has occurred.
76 c_call: A C function is about to be called.
Stéphane Wirtel07fbbfd2018-10-05 16:17:18 +020077 c_return: A C function has returned.
csabella0774e792017-05-16 18:28:02 -040078 c_exception: A C function has raised an exception.
79
80 For the Python events, specialized functions (see the dispatch_*()
81 methods) are called. For the C events, no action is taken.
82
83 The arg parameter depends on the previous event.
84 """
Guido van Rossum4acc25b2000-02-02 15:10:15 +000085 if self.quitting:
86 return # None
87 if event == 'line':
88 return self.dispatch_line(frame)
89 if event == 'call':
90 return self.dispatch_call(frame, arg)
91 if event == 'return':
92 return self.dispatch_return(frame, arg)
93 if event == 'exception':
94 return self.dispatch_exception(frame, arg)
Nicholas Bastinc69ebe82004-03-24 21:57:10 +000095 if event == 'c_call':
96 return self.trace_dispatch
97 if event == 'c_exception':
98 return self.trace_dispatch
99 if event == 'c_return':
100 return self.trace_dispatch
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000101 print('bdb.Bdb.dispatch: unknown debugging event:', repr(event))
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000102 return self.trace_dispatch
Tim Peters11cf6052001-01-14 21:54:20 +0000103
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000104 def dispatch_line(self, frame):
csabella0774e792017-05-16 18:28:02 -0400105 """Invoke user function and return trace function for line event.
106
107 If the debugger stops on the current line, invoke
108 self.user_line(). Raise BdbQuit if self.quitting is set.
109 Return self.trace_dispatch to continue tracing in this scope.
110 """
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000111 if self.stop_here(frame) or self.break_here(frame):
112 self.user_line(frame)
113 if self.quitting: raise BdbQuit
114 return self.trace_dispatch
Tim Peters11cf6052001-01-14 21:54:20 +0000115
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000116 def dispatch_call(self, frame, arg):
csabella0774e792017-05-16 18:28:02 -0400117 """Invoke user function and return trace function for call event.
118
119 If the debugger stops on this function call, invoke
120 self.user_call(). Raise BbdQuit if self.quitting is set.
121 Return self.trace_dispatch to continue tracing in this scope.
122 """
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000123 # XXX 'arg' is no longer used
124 if self.botframe is None:
125 # First call of dispatch since reset()
Christian Tismer313a7512002-05-28 08:04:00 +0000126 self.botframe = frame.f_back # (CT) Note that this may also be None!
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000127 return self.trace_dispatch
128 if not (self.stop_here(frame) or self.break_anywhere(frame)):
129 # No need to trace this function
130 return # None
Guido van Rossum8820c232013-11-21 11:30:06 -0800131 # Ignore call events in generator except when stepping.
Pablo Galindoc7ab5812018-01-29 01:31:00 +0000132 if self.stopframe and frame.f_code.co_flags & GENERATOR_AND_COROUTINE_FLAGS:
Guido van Rossum8820c232013-11-21 11:30:06 -0800133 return self.trace_dispatch
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000134 self.user_call(frame, arg)
135 if self.quitting: raise BdbQuit
136 return self.trace_dispatch
Tim Peters11cf6052001-01-14 21:54:20 +0000137
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000138 def dispatch_return(self, frame, arg):
csabella0774e792017-05-16 18:28:02 -0400139 """Invoke user function and return trace function for return event.
140
141 If the debugger stops on this function return, invoke
142 self.user_return(). Raise BdbQuit if self.quitting is set.
143 Return self.trace_dispatch to continue tracing in this scope.
144 """
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000145 if self.stop_here(frame) or frame == self.returnframe:
Guido van Rossum8820c232013-11-21 11:30:06 -0800146 # Ignore return events in generator except when stepping.
Pablo Galindoc7ab5812018-01-29 01:31:00 +0000147 if self.stopframe and frame.f_code.co_flags & GENERATOR_AND_COROUTINE_FLAGS:
Guido van Rossum8820c232013-11-21 11:30:06 -0800148 return self.trace_dispatch
Senthil Kumaran42d70812012-05-01 10:07:49 +0800149 try:
150 self.frame_returning = frame
151 self.user_return(frame, arg)
152 finally:
153 self.frame_returning = None
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000154 if self.quitting: raise BdbQuit
Guido van Rossum8820c232013-11-21 11:30:06 -0800155 # The user issued a 'next' or 'until' command.
156 if self.stopframe is frame and self.stoplineno != -1:
157 self._set_stopinfo(None, None)
Just van Rossumae1f65f2001-06-25 18:01:24 +0000158 return self.trace_dispatch
Tim Peters11cf6052001-01-14 21:54:20 +0000159
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000160 def dispatch_exception(self, frame, arg):
csabella0774e792017-05-16 18:28:02 -0400161 """Invoke user function and return trace function for exception event.
162
163 If the debugger stops on this exception, invoke
164 self.user_exception(). Raise BdbQuit if self.quitting is set.
165 Return self.trace_dispatch to continue tracing in this scope.
166 """
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000167 if self.stop_here(frame):
Guido van Rossum8820c232013-11-21 11:30:06 -0800168 # When stepping with next/until/return in a generator frame, skip
169 # the internal StopIteration exception (with no traceback)
170 # triggered by a subiterator run with the 'yield from' statement.
Pablo Galindoc7ab5812018-01-29 01:31:00 +0000171 if not (frame.f_code.co_flags & GENERATOR_AND_COROUTINE_FLAGS
Guido van Rossum8820c232013-11-21 11:30:06 -0800172 and arg[0] is StopIteration and arg[2] is None):
173 self.user_exception(frame, arg)
174 if self.quitting: raise BdbQuit
175 # Stop at the StopIteration or GeneratorExit exception when the user
176 # has set stopframe in a generator by issuing a return command, or a
177 # next/until command at the last statement in the generator before the
178 # exception.
179 elif (self.stopframe and frame is not self.stopframe
Pablo Galindoc7ab5812018-01-29 01:31:00 +0000180 and self.stopframe.f_code.co_flags & GENERATOR_AND_COROUTINE_FLAGS
Guido van Rossum8820c232013-11-21 11:30:06 -0800181 and arg[0] in (StopIteration, GeneratorExit)):
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000182 self.user_exception(frame, arg)
183 if self.quitting: raise BdbQuit
Guido van Rossum8820c232013-11-21 11:30:06 -0800184
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000185 return self.trace_dispatch
Tim Peters11cf6052001-01-14 21:54:20 +0000186
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000187 # Normally derived classes don't override the following
188 # methods, but they may if they want to redefine the
189 # definition of stopping and breakpoints.
Tim Peters11cf6052001-01-14 21:54:20 +0000190
Georg Brandl243ad662009-05-05 09:00:19 +0000191 def is_skipped_module(self, module_name):
csabella0774e792017-05-16 18:28:02 -0400192 "Return True if module_name matches any skip pattern."
Anthony Sottile86900a42019-03-12 20:57:09 -0700193 if module_name is None: # some modules do not have names
194 return False
Georg Brandl243ad662009-05-05 09:00:19 +0000195 for pattern in self.skip:
196 if fnmatch.fnmatch(module_name, pattern):
197 return True
198 return False
199
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000200 def stop_here(self, frame):
csabella0774e792017-05-16 18:28:02 -0400201 "Return True if frame is below the starting frame in the stack."
Neal Norwitz72a2b4d2002-05-29 00:54:38 +0000202 # (CT) stopframe may now also be None, see dispatch_call.
203 # (CT) the former test for None is therefore removed from here.
Georg Brandl243ad662009-05-05 09:00:19 +0000204 if self.skip and \
205 self.is_skipped_module(frame.f_globals.get('__name__')):
206 return False
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000207 if frame is self.stopframe:
Georg Brandl3f940892010-07-30 10:29:19 +0000208 if self.stoplineno == -1:
209 return False
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000210 return frame.f_lineno >= self.stoplineno
Guido van Rossum8820c232013-11-21 11:30:06 -0800211 if not self.stopframe:
212 return True
Tim Petersbc0e9102002-04-04 22:55:58 +0000213 return False
Guido van Rossumd93643f1998-09-11 22:38:35 +0000214
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000215 def break_here(self, frame):
csabella0774e792017-05-16 18:28:02 -0400216 """Return True if there is an effective breakpoint for this line.
217
218 Check for line or function breakpoint and if in effect.
219 Delete temporary breakpoints if effective() says to.
220 """
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000221 filename = self.canonic(frame.f_code.co_filename)
Georg Brandl26607472010-11-29 20:12:24 +0000222 if filename not in self.breaks:
Tim Petersbc0e9102002-04-04 22:55:58 +0000223 return False
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000224 lineno = frame.f_lineno
Georg Brandl26607472010-11-29 20:12:24 +0000225 if lineno not in self.breaks[filename]:
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000226 # The line itself has no breakpoint, but maybe the line is the
227 # first line of a function with breakpoint set by function name.
228 lineno = frame.f_code.co_firstlineno
Georg Brandl26607472010-11-29 20:12:24 +0000229 if lineno not in self.breaks[filename]:
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000230 return False
231
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000232 # flag says ok to delete temp. bp
233 (bp, flag) = effective(filename, lineno, frame)
234 if bp:
235 self.currentbp = bp.number
236 if (flag and bp.temporary):
237 self.do_clear(str(bp.number))
Tim Petersbc0e9102002-04-04 22:55:58 +0000238 return True
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000239 else:
Tim Petersbc0e9102002-04-04 22:55:58 +0000240 return False
Tim Peters11cf6052001-01-14 21:54:20 +0000241
Guido van Rossum9cec8fb2001-04-08 15:05:16 +0000242 def do_clear(self, arg):
csabella0774e792017-05-16 18:28:02 -0400243 """Remove temporary breakpoint.
244
245 Must implement in derived classes or get NotImplementedError.
246 """
Collin Winterce36ad82007-08-30 01:19:48 +0000247 raise NotImplementedError("subclass of bdb must implement do_clear()")
Guido van Rossum9cec8fb2001-04-08 15:05:16 +0000248
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000249 def break_anywhere(self, frame):
csabella0774e792017-05-16 18:28:02 -0400250 """Return True if there is any breakpoint for frame's filename.
251 """
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000252 return self.canonic(frame.f_code.co_filename) in self.breaks
Tim Peters11cf6052001-01-14 21:54:20 +0000253
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000254 # Derived classes should override the user_* methods
255 # to gain control.
Tim Peters11cf6052001-01-14 21:54:20 +0000256
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000257 def user_call(self, frame, argument_list):
csabella0774e792017-05-16 18:28:02 -0400258 """Called if we might stop in a function."""
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000259 pass
Tim Peters11cf6052001-01-14 21:54:20 +0000260
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000261 def user_line(self, frame):
Eitan Adlerb5c246f2018-06-02 07:16:19 -0700262 """Called when we stop or break at a line."""
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000263 pass
Tim Peters11cf6052001-01-14 21:54:20 +0000264
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000265 def user_return(self, frame, return_value):
csabella0774e792017-05-16 18:28:02 -0400266 """Called when a return trap is set here."""
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000267 pass
Tim Peters11cf6052001-01-14 21:54:20 +0000268
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000269 def user_exception(self, frame, exc_info):
csabella0774e792017-05-16 18:28:02 -0400270 """Called when we stop on an exception."""
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000271 pass
Tim Peters11cf6052001-01-14 21:54:20 +0000272
Georg Brandl3f940892010-07-30 10:29:19 +0000273 def _set_stopinfo(self, stopframe, returnframe, stoplineno=0):
csabella0774e792017-05-16 18:28:02 -0400274 """Set the attributes for stopping.
275
276 If stoplineno is greater than or equal to 0, then stop at line
277 greater than or equal to the stopline. If stoplineno is -1, then
278 don't stop at all.
279 """
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000280 self.stopframe = stopframe
281 self.returnframe = returnframe
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000282 self.quitting = False
Georg Brandl3f940892010-07-30 10:29:19 +0000283 # stoplineno >= 0 means: stop at line >= the stoplineno
284 # stoplineno -1 means: don't stop at all
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000285 self.stoplineno = stoplineno
286
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000287 # Derived classes and clients can call the following methods
288 # to affect the stepping state.
Tim Peters11cf6052001-01-14 21:54:20 +0000289
Georg Brandl2dfec552010-07-30 08:43:32 +0000290 def set_until(self, frame, lineno=None):
csabella0774e792017-05-16 18:28:02 -0400291 """Stop when the line with the lineno greater than the current one is
292 reached or when returning from current frame."""
Georg Brandl2dfec552010-07-30 08:43:32 +0000293 # the name "until" is borrowed from gdb
294 if lineno is None:
295 lineno = frame.f_lineno + 1
296 self._set_stopinfo(frame, frame, lineno)
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000297
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000298 def set_step(self):
299 """Stop after one line of code."""
Senthil Kumaran42d70812012-05-01 10:07:49 +0800300 # Issue #13183: pdb skips frames after hitting a breakpoint and running
301 # step commands.
302 # Restore the trace function in the caller (that may not have been set
303 # for performance reasons) when returning from the current frame.
304 if self.frame_returning:
305 caller_frame = self.frame_returning.f_back
306 if caller_frame and not caller_frame.f_trace:
307 caller_frame.f_trace = self.trace_dispatch
Georg Brandl3f940892010-07-30 10:29:19 +0000308 self._set_stopinfo(None, None)
Tim Peters11cf6052001-01-14 21:54:20 +0000309
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000310 def set_next(self, frame):
311 """Stop on the next line in or below the given frame."""
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000312 self._set_stopinfo(frame, None)
Tim Peters11cf6052001-01-14 21:54:20 +0000313
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000314 def set_return(self, frame):
315 """Stop when returning from the given frame."""
Pablo Galindoc7ab5812018-01-29 01:31:00 +0000316 if frame.f_code.co_flags & GENERATOR_AND_COROUTINE_FLAGS:
Guido van Rossum8820c232013-11-21 11:30:06 -0800317 self._set_stopinfo(frame, None, -1)
318 else:
319 self._set_stopinfo(frame.f_back, frame)
Tim Peters11cf6052001-01-14 21:54:20 +0000320
Johannes Gijsbers84a6c202004-11-07 11:35:30 +0000321 def set_trace(self, frame=None):
csabella0774e792017-05-16 18:28:02 -0400322 """Start debugging from frame.
Johannes Gijsbers84a6c202004-11-07 11:35:30 +0000323
324 If frame is not specified, debugging starts from caller's frame.
325 """
326 if frame is None:
327 frame = sys._getframe().f_back
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000328 self.reset()
329 while frame:
330 frame.f_trace = self.trace_dispatch
331 self.botframe = frame
332 frame = frame.f_back
333 self.set_step()
334 sys.settrace(self.trace_dispatch)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000335
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000336 def set_continue(self):
csabella0774e792017-05-16 18:28:02 -0400337 """Stop only at breakpoints or when finished.
338
339 If there are no breakpoints, set the system trace function to None.
340 """
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000341 # Don't stop except at breakpoints or when finished
Georg Brandl3f940892010-07-30 10:29:19 +0000342 self._set_stopinfo(self.botframe, None, -1)
Georg Brandlf8b893e2010-12-04 16:22:44 +0000343 if not self.breaks:
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000344 # no breakpoints; run without debugger overhead
345 sys.settrace(None)
Christian Tismer313a7512002-05-28 08:04:00 +0000346 frame = sys._getframe().f_back
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000347 while frame and frame is not self.botframe:
348 del frame.f_trace
349 frame = frame.f_back
Tim Peters11cf6052001-01-14 21:54:20 +0000350
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000351 def set_quit(self):
csabella0774e792017-05-16 18:28:02 -0400352 """Set quitting attribute to True.
353
354 Raises BdbQuit exception in the next call to a dispatch_*() method.
355 """
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000356 self.stopframe = self.botframe
357 self.returnframe = None
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000358 self.quitting = True
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000359 sys.settrace(None)
Tim Peters11cf6052001-01-14 21:54:20 +0000360
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000361 # Derived classes and clients can call the following methods
362 # to manipulate breakpoints. These methods return an
csabella0774e792017-05-16 18:28:02 -0400363 # error message if something went wrong, None if all is well.
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000364 # Set_break prints out the breakpoint line and file:lineno.
365 # Call self.get_*break*() to see the breakpoints or better
366 # for bp in Breakpoint.bpbynumber: if bp: bp.bpprint().
Tim Peters11cf6052001-01-14 21:54:20 +0000367
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000368 def set_break(self, filename, lineno, temporary=False, cond=None,
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000369 funcname=None):
csabella0774e792017-05-16 18:28:02 -0400370 """Set a new breakpoint for filename:lineno.
371
372 If lineno doesn't exist for the filename, return an error message.
373 The filename should be in canonical form.
374 """
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000375 filename = self.canonic(filename)
376 import linecache # Import as late as possible
377 line = linecache.getline(filename, lineno)
378 if not line:
Georg Brandl26607472010-11-29 20:12:24 +0000379 return 'Line %s:%d does not exist' % (filename, lineno)
380 list = self.breaks.setdefault(filename, [])
381 if lineno not in list:
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000382 list.append(lineno)
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000383 bp = Breakpoint(filename, lineno, temporary, cond, funcname)
csabella0774e792017-05-16 18:28:02 -0400384 return None
Guido van Rossumd93643f1998-09-11 22:38:35 +0000385
Senthil Kumaran6f107042010-11-29 11:54:17 +0000386 def _prune_breaks(self, filename, lineno):
Xtreak0d702272019-06-03 04:42:33 +0530387 """Prune breakpoints for filename:lineno.
csabella0774e792017-05-16 18:28:02 -0400388
389 A list of breakpoints is maintained in the Bdb instance and in
390 the Breakpoint class. If a breakpoint in the Bdb instance no
391 longer exists in the Breakpoint class, then it's removed from the
392 Bdb instance.
393 """
Senthil Kumaran6f107042010-11-29 11:54:17 +0000394 if (filename, lineno) not in Breakpoint.bplist:
395 self.breaks[filename].remove(lineno)
396 if not self.breaks[filename]:
397 del self.breaks[filename]
398
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000399 def clear_break(self, filename, lineno):
csabella0774e792017-05-16 18:28:02 -0400400 """Delete breakpoints for filename:lineno.
401
402 If no breakpoints were set, return an error message.
403 """
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000404 filename = self.canonic(filename)
Georg Brandl26607472010-11-29 20:12:24 +0000405 if filename not in self.breaks:
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000406 return 'There are no breakpoints in %s' % filename
407 if lineno not in self.breaks[filename]:
Georg Brandl26607472010-11-29 20:12:24 +0000408 return 'There is no breakpoint at %s:%d' % (filename, lineno)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000409 # If there's only one bp in the list for that file,line
410 # pair, then remove the breaks entry
411 for bp in Breakpoint.bplist[filename, lineno][:]:
412 bp.deleteMe()
Senthil Kumaran6f107042010-11-29 11:54:17 +0000413 self._prune_breaks(filename, lineno)
csabella0774e792017-05-16 18:28:02 -0400414 return None
Tim Peters11cf6052001-01-14 21:54:20 +0000415
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000416 def clear_bpbynumber(self, arg):
csabella0774e792017-05-16 18:28:02 -0400417 """Delete a breakpoint by its index in Breakpoint.bpbynumber.
418
419 If arg is invalid, return an error message.
420 """
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000421 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000422 bp = self.get_bpbynumber(arg)
423 except ValueError as err:
424 return str(err)
Senthil Kumaran6f107042010-11-29 11:54:17 +0000425 bp.deleteMe()
426 self._prune_breaks(bp.file, bp.line)
csabella0774e792017-05-16 18:28:02 -0400427 return None
Guido van Rossum6ea27cc1999-01-25 20:51:34 +0000428
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000429 def clear_all_file_breaks(self, filename):
csabella0774e792017-05-16 18:28:02 -0400430 """Delete all breakpoints in filename.
431
432 If none were set, return an error message.
433 """
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000434 filename = self.canonic(filename)
Georg Brandl26607472010-11-29 20:12:24 +0000435 if filename not in self.breaks:
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000436 return 'There are no breakpoints in %s' % filename
437 for line in self.breaks[filename]:
438 blist = Breakpoint.bplist[filename, line]
439 for bp in blist:
440 bp.deleteMe()
441 del self.breaks[filename]
csabella0774e792017-05-16 18:28:02 -0400442 return None
Tim Peters11cf6052001-01-14 21:54:20 +0000443
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000444 def clear_all_breaks(self):
csabella0774e792017-05-16 18:28:02 -0400445 """Delete all existing breakpoints.
446
447 If none were set, return an error message.
448 """
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000449 if not self.breaks:
450 return 'There are no breakpoints'
451 for bp in Breakpoint.bpbynumber:
452 if bp:
453 bp.deleteMe()
454 self.breaks = {}
csabella0774e792017-05-16 18:28:02 -0400455 return None
Tim Peters11cf6052001-01-14 21:54:20 +0000456
Georg Brandl7410dd12010-07-30 12:01:20 +0000457 def get_bpbynumber(self, arg):
csabella0774e792017-05-16 18:28:02 -0400458 """Return a breakpoint by its index in Breakpoint.bybpnumber.
459
460 For invalid arg values or if the breakpoint doesn't exist,
461 raise a ValueError.
462 """
Georg Brandl7410dd12010-07-30 12:01:20 +0000463 if not arg:
464 raise ValueError('Breakpoint number expected')
465 try:
466 number = int(arg)
467 except ValueError:
Serhiy Storchaka5affd232017-04-05 09:37:24 +0300468 raise ValueError('Non-numeric breakpoint number %s' % arg) from None
Georg Brandl7410dd12010-07-30 12:01:20 +0000469 try:
470 bp = Breakpoint.bpbynumber[number]
471 except IndexError:
Serhiy Storchaka5affd232017-04-05 09:37:24 +0300472 raise ValueError('Breakpoint number %d out of range' % number) from None
Georg Brandl7410dd12010-07-30 12:01:20 +0000473 if bp is None:
474 raise ValueError('Breakpoint %d already deleted' % number)
475 return bp
476
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000477 def get_break(self, filename, lineno):
csabella0774e792017-05-16 18:28:02 -0400478 """Return True if there is a breakpoint for filename:lineno."""
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000479 filename = self.canonic(filename)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000480 return filename in self.breaks and \
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000481 lineno in self.breaks[filename]
Tim Peters11cf6052001-01-14 21:54:20 +0000482
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000483 def get_breaks(self, filename, lineno):
csabella0774e792017-05-16 18:28:02 -0400484 """Return all breakpoints for filename:lineno.
485
486 If no breakpoints are set, return an empty list.
487 """
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000488 filename = self.canonic(filename)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000489 return filename in self.breaks and \
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000490 lineno in self.breaks[filename] and \
491 Breakpoint.bplist[filename, lineno] or []
Tim Peters11cf6052001-01-14 21:54:20 +0000492
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000493 def get_file_breaks(self, filename):
csabella0774e792017-05-16 18:28:02 -0400494 """Return all lines with breakpoints for filename.
495
496 If no breakpoints are set, return an empty list.
497 """
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000498 filename = self.canonic(filename)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000499 if filename in self.breaks:
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000500 return self.breaks[filename]
501 else:
502 return []
Tim Peters11cf6052001-01-14 21:54:20 +0000503
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000504 def get_all_breaks(self):
csabella0774e792017-05-16 18:28:02 -0400505 """Return all breakpoints that are set."""
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000506 return self.breaks
Tim Peters11cf6052001-01-14 21:54:20 +0000507
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000508 # Derived classes and clients can call the following method
509 # to get a data structure representing a stack trace.
Tim Peters11cf6052001-01-14 21:54:20 +0000510
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000511 def get_stack(self, f, t):
csabella0774e792017-05-16 18:28:02 -0400512 """Return a list of (frame, lineno) in a stack trace and a size.
513
514 List starts with original calling frame, if there is one.
515 Size may be number of frames above or below f.
516 """
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000517 stack = []
518 if t and t.tb_frame is f:
519 t = t.tb_next
520 while f is not None:
521 stack.append((f, f.f_lineno))
522 if f is self.botframe:
523 break
524 f = f.f_back
525 stack.reverse()
526 i = max(0, len(stack) - 1)
527 while t is not None:
528 stack.append((t.tb_frame, t.tb_lineno))
529 t = t.tb_next
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +0000530 if f is None:
531 i = max(0, len(stack) - 1)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000532 return stack, i
Tim Peters11cf6052001-01-14 21:54:20 +0000533
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000534 def format_stack_entry(self, frame_lineno, lprefix=': '):
csabella0774e792017-05-16 18:28:02 -0400535 """Return a string with information about a stack entry.
536
537 The stack entry frame_lineno is a (frame, lineno) tuple. The
538 return string contains the canonical filename, the function name
539 or '<lambda>', the input arguments, the return value, and the
540 line of code (if it exists).
541
542 """
Alexandre Vassalotti1f2ba4b2008-05-16 07:12:44 +0000543 import linecache, reprlib
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000544 frame, lineno = frame_lineno
545 filename = self.canonic(frame.f_code.co_filename)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000546 s = '%s(%r)' % (filename, lineno)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000547 if frame.f_code.co_name:
Georg Brandl26607472010-11-29 20:12:24 +0000548 s += frame.f_code.co_name
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000549 else:
Georg Brandl26607472010-11-29 20:12:24 +0000550 s += "<lambda>"
Miss Islington (bot)c97fc562020-02-23 19:33:07 -0800551 s += '()'
Raymond Hettinger54f02222002-06-01 14:18:47 +0000552 if '__return__' in frame.f_locals:
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000553 rv = frame.f_locals['__return__']
Georg Brandl26607472010-11-29 20:12:24 +0000554 s += '->'
555 s += reprlib.repr(rv)
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000556 line = linecache.getline(filename, lineno, frame.f_globals)
Georg Brandl26607472010-11-29 20:12:24 +0000557 if line:
558 s += lprefix + line.strip()
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000559 return s
Tim Peters11cf6052001-01-14 21:54:20 +0000560
Georg Brandl46b9afc2010-07-30 09:14:20 +0000561 # The following methods can be called by clients to use
562 # a debugger to debug a statement or an expression.
563 # Both can be given as a string, or a code object.
Tim Peters11cf6052001-01-14 21:54:20 +0000564
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000565 def run(self, cmd, globals=None, locals=None):
csabella0774e792017-05-16 18:28:02 -0400566 """Debug a statement executed via the exec() function.
567
568 globals defaults to __main__.dict; locals defaults to globals.
569 """
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000570 if globals is None:
571 import __main__
572 globals = __main__.__dict__
573 if locals is None:
574 locals = globals
575 self.reset()
Victor Stinner4bd81722011-01-06 00:49:38 +0000576 if isinstance(cmd, str):
577 cmd = compile(cmd, "<string>", "exec")
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000578 sys.settrace(self.trace_dispatch)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000579 try:
Martin v. Löwisede8ffb2008-03-30 20:43:50 +0000580 exec(cmd, globals, locals)
581 except BdbQuit:
582 pass
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000583 finally:
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000584 self.quitting = True
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000585 sys.settrace(None)
Tim Peters11cf6052001-01-14 21:54:20 +0000586
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000587 def runeval(self, expr, globals=None, locals=None):
csabella0774e792017-05-16 18:28:02 -0400588 """Debug an expression executed via the eval() function.
589
590 globals defaults to __main__.dict; locals defaults to globals.
591 """
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000592 if globals is None:
593 import __main__
594 globals = __main__.__dict__
595 if locals is None:
596 locals = globals
597 self.reset()
598 sys.settrace(self.trace_dispatch)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000599 try:
Martin v. Löwisede8ffb2008-03-30 20:43:50 +0000600 return eval(expr, globals, locals)
601 except BdbQuit:
602 pass
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000603 finally:
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000604 self.quitting = True
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000605 sys.settrace(None)
Guido van Rossum5e38b6f1995-02-27 13:13:40 +0000606
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000607 def runctx(self, cmd, globals, locals):
csabella0774e792017-05-16 18:28:02 -0400608 """For backwards-compatibility. Defers to run()."""
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000609 # B/W compatibility
610 self.run(cmd, globals, locals)
Guido van Rossum4e160981992-09-02 20:43:20 +0000611
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000612 # This method is more useful to debug a single function call.
Guido van Rossum4e160981992-09-02 20:43:20 +0000613
Serhiy Storchaka42a139e2019-04-01 09:16:35 +0300614 def runcall(*args, **kwds):
csabella0774e792017-05-16 18:28:02 -0400615 """Debug a single function call.
616
617 Return the result of the function call.
618 """
Serhiy Storchaka42a139e2019-04-01 09:16:35 +0300619 if len(args) >= 2:
620 self, func, *args = args
621 elif not args:
622 raise TypeError("descriptor 'runcall' of 'Bdb' object "
623 "needs an argument")
624 elif 'func' in kwds:
625 func = kwds.pop('func')
626 self, *args = args
627 import warnings
628 warnings.warn("Passing 'func' as keyword argument is deprecated",
629 DeprecationWarning, stacklevel=2)
630 else:
631 raise TypeError('runcall expected at least 1 positional argument, '
632 'got %d' % (len(args)-1))
633
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000634 self.reset()
635 sys.settrace(self.trace_dispatch)
636 res = None
637 try:
Martin v. Löwisede8ffb2008-03-30 20:43:50 +0000638 res = func(*args, **kwds)
639 except BdbQuit:
640 pass
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000641 finally:
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000642 self.quitting = True
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000643 sys.settrace(None)
644 return res
Serhiy Storchakad53cf992019-05-06 22:40:27 +0300645 runcall.__text_signature__ = '($self, func, /, *args, **kwds)'
Guido van Rossumbabe2bf1992-01-22 22:21:31 +0000646
Guido van Rossumbabe2bf1992-01-22 22:21:31 +0000647
Guido van Rossumb6775db1994-08-01 11:34:53 +0000648def set_trace():
csabella0774e792017-05-16 18:28:02 -0400649 """Start debugging with a Bdb instance from the caller's frame."""
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000650 Bdb().set_trace()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000651
Guido van Rossumd93643f1998-09-11 22:38:35 +0000652
653class Breakpoint:
Georg Brandl26607472010-11-29 20:12:24 +0000654 """Breakpoint class.
Guido van Rossumd93643f1998-09-11 22:38:35 +0000655
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000656 Implements temporary breakpoints, ignore counts, disabling and
657 (re)-enabling, and conditionals.
Guido van Rossumd93643f1998-09-11 22:38:35 +0000658
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000659 Breakpoints are indexed by number through bpbynumber and by
csabella0774e792017-05-16 18:28:02 -0400660 the (file, line) tuple using bplist. The former points to a
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000661 single instance of class Breakpoint. The latter points to a
662 list of such instances since there may be more than one
663 breakpoint per line.
Guido van Rossumd93643f1998-09-11 22:38:35 +0000664
csabella0774e792017-05-16 18:28:02 -0400665 When creating a breakpoint, its associated filename should be
666 in canonical form. If funcname is defined, a breakpoint hit will be
667 counted when the first line of that function is executed. A
668 conditional breakpoint always counts a hit.
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000669 """
Guido van Rossumd93643f1998-09-11 22:38:35 +0000670
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000671 # XXX Keeping state in the class is a mistake -- this means
672 # you cannot have more than one active Bdb instance.
Guido van Rossumd93643f1998-09-11 22:38:35 +0000673
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000674 next = 1 # Next bp to be assigned
675 bplist = {} # indexed by (file, lineno) tuple
676 bpbynumber = [None] # Each entry is None or an instance of Bpt
677 # index 0 is unused, except for marking an
678 # effective break .... see effective()
Guido van Rossumd93643f1998-09-11 22:38:35 +0000679
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000680 def __init__(self, file, line, temporary=False, cond=None, funcname=None):
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000681 self.funcname = funcname
682 # Needed if funcname is not None.
683 self.func_first_executable_line = None
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000684 self.file = file # This better be in canonical form!
685 self.line = line
686 self.temporary = temporary
687 self.cond = cond
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000688 self.enabled = True
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000689 self.ignore = 0
690 self.hits = 0
691 self.number = Breakpoint.next
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000692 Breakpoint.next += 1
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000693 # Build the two lists
694 self.bpbynumber.append(self)
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000695 if (file, line) in self.bplist:
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000696 self.bplist[file, line].append(self)
697 else:
698 self.bplist[file, line] = [self]
Guido van Rossumd93643f1998-09-11 22:38:35 +0000699
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000700 def deleteMe(self):
csabella0774e792017-05-16 18:28:02 -0400701 """Delete the breakpoint from the list associated to a file:line.
702
703 If it is the last breakpoint in that position, it also deletes
704 the entry for the file:line.
705 """
706
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000707 index = (self.file, self.line)
708 self.bpbynumber[self.number] = None # No longer in list
709 self.bplist[index].remove(self)
710 if not self.bplist[index]:
711 # No more bp for this f:l combo
712 del self.bplist[index]
Guido van Rossumd93643f1998-09-11 22:38:35 +0000713
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000714 def enable(self):
csabella0774e792017-05-16 18:28:02 -0400715 """Mark the breakpoint as enabled."""
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000716 self.enabled = True
Guido van Rossumd93643f1998-09-11 22:38:35 +0000717
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000718 def disable(self):
csabella0774e792017-05-16 18:28:02 -0400719 """Mark the breakpoint as disabled."""
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000720 self.enabled = False
Guido van Rossumd93643f1998-09-11 22:38:35 +0000721
Thomas Wouters477c8d52006-05-27 19:21:47 +0000722 def bpprint(self, out=None):
csabella0774e792017-05-16 18:28:02 -0400723 """Print the output of bpformat().
724
725 The optional out argument directs where the output is sent
726 and defaults to standard output.
727 """
Thomas Wouters477c8d52006-05-27 19:21:47 +0000728 if out is None:
729 out = sys.stdout
Georg Brandld2fd4ca2010-07-30 15:01:23 +0000730 print(self.bpformat(), file=out)
731
732 def bpformat(self):
csabella0774e792017-05-16 18:28:02 -0400733 """Return a string with information about the breakpoint.
734
735 The information includes the breakpoint number, temporary
736 status, file:line position, break condition, number of times to
737 ignore, and number of times hit.
738
739 """
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000740 if self.temporary:
Tim Peters11cf6052001-01-14 21:54:20 +0000741 disp = 'del '
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000742 else:
Tim Peters11cf6052001-01-14 21:54:20 +0000743 disp = 'keep '
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000744 if self.enabled:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000745 disp = disp + 'yes '
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000746 else:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000747 disp = disp + 'no '
Georg Brandld2fd4ca2010-07-30 15:01:23 +0000748 ret = '%-4dbreakpoint %s at %s:%d' % (self.number, disp,
749 self.file, self.line)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000750 if self.cond:
Georg Brandld2fd4ca2010-07-30 15:01:23 +0000751 ret += '\n\tstop only if %s' % (self.cond,)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000752 if self.ignore:
Georg Brandld2fd4ca2010-07-30 15:01:23 +0000753 ret += '\n\tignore next %d hits' % (self.ignore,)
754 if self.hits:
755 if self.hits > 1:
756 ss = 's'
757 else:
758 ss = ''
759 ret += '\n\tbreakpoint already hit %d time%s' % (self.hits, ss)
760 return ret
Guido van Rossumd93643f1998-09-11 22:38:35 +0000761
Georg Brandl7410dd12010-07-30 12:01:20 +0000762 def __str__(self):
csabella0774e792017-05-16 18:28:02 -0400763 "Return a condensed description of the breakpoint."
Georg Brandl7410dd12010-07-30 12:01:20 +0000764 return 'breakpoint %s at %s:%s' % (self.number, self.file, self.line)
765
Guido van Rossumd93643f1998-09-11 22:38:35 +0000766# -----------end of Breakpoint class----------
767
csabella0774e792017-05-16 18:28:02 -0400768
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000769def checkfuncname(b, frame):
csabella0774e792017-05-16 18:28:02 -0400770 """Return True if break should happen here.
771
772 Whether a break should happen depends on the way that b (the breakpoint)
773 was set. If it was set via line number, check if b.line is the same as
774 the one in the frame. If it was set via function name, check if this is
775 the right function and if it is on the first executable line.
776 """
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000777 if not b.funcname:
778 # Breakpoint was set via line number.
779 if b.line != frame.f_lineno:
780 # Breakpoint was set at a line with a def statement and the function
781 # defined is called: don't break.
782 return False
783 return True
784
785 # Breakpoint set via function name.
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000786 if frame.f_code.co_name != b.funcname:
787 # It's not a function call, but rather execution of def statement.
788 return False
789
790 # We are in the right frame.
791 if not b.func_first_executable_line:
792 # The function is entered for the 1st time.
793 b.func_first_executable_line = frame.f_lineno
794
csabella0774e792017-05-16 18:28:02 -0400795 if b.func_first_executable_line != frame.f_lineno:
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000796 # But we are not at the first line number: don't break.
797 return False
798 return True
799
csabella0774e792017-05-16 18:28:02 -0400800
Guido van Rossumd93643f1998-09-11 22:38:35 +0000801# Determines if there is an effective (active) breakpoint at this
802# line of code. Returns breakpoint number or 0 if none
803def effective(file, line, frame):
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000804 """Determine which breakpoint for this file:line is to be acted upon.
Guido van Rossumd93643f1998-09-11 22:38:35 +0000805
csabella0774e792017-05-16 18:28:02 -0400806 Called only if we know there is a breakpoint at this location. Return
807 the breakpoint that was triggered and a boolean that indicates if it is
808 ok to delete a temporary breakpoint. Return (None, None) if there is no
809 matching breakpoint.
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000810 """
Georg Brandl9aed6cc2010-11-26 12:05:27 +0000811 possibles = Breakpoint.bplist[file, line]
812 for b in possibles:
813 if not b.enabled:
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000814 continue
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000815 if not checkfuncname(b, frame):
816 continue
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000817 # Count every hit when bp is enabled
Georg Brandl9aed6cc2010-11-26 12:05:27 +0000818 b.hits += 1
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000819 if not b.cond:
Georg Brandl9aed6cc2010-11-26 12:05:27 +0000820 # If unconditional, and ignoring go on to next, else break
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000821 if b.ignore > 0:
Georg Brandl9aed6cc2010-11-26 12:05:27 +0000822 b.ignore -= 1
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000823 continue
824 else:
Georg Brandl9aed6cc2010-11-26 12:05:27 +0000825 # breakpoint and marker that it's ok to delete if temporary
826 return (b, True)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000827 else:
828 # Conditional bp.
829 # Ignore count applies only to those bpt hits where the
830 # condition evaluates to true.
831 try:
Georg Brandl9aed6cc2010-11-26 12:05:27 +0000832 val = eval(b.cond, frame.f_globals, frame.f_locals)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000833 if val:
834 if b.ignore > 0:
Georg Brandl9aed6cc2010-11-26 12:05:27 +0000835 b.ignore -= 1
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000836 # continue
837 else:
Georg Brandl9aed6cc2010-11-26 12:05:27 +0000838 return (b, True)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000839 # else:
840 # continue
841 except:
Georg Brandl9aed6cc2010-11-26 12:05:27 +0000842 # if eval fails, most conservative thing is to stop on
843 # breakpoint regardless of ignore count. Don't delete
844 # temporary, as another hint to user.
845 return (b, False)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000846 return (None, None)
Guido van Rossumd93643f1998-09-11 22:38:35 +0000847
Georg Brandl26607472010-11-29 20:12:24 +0000848
Guido van Rossumbabe2bf1992-01-22 22:21:31 +0000849# -------------------- testing --------------------
850
851class Tdb(Bdb):
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000852 def user_call(self, frame, args):
853 name = frame.f_code.co_name
854 if not name: name = '???'
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000855 print('+++ call', name, args)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000856 def user_line(self, frame):
Eric S. Raymondb49f4a42001-02-09 05:07:04 +0000857 import linecache
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000858 name = frame.f_code.co_name
859 if not name: name = '???'
860 fn = self.canonic(frame.f_code.co_filename)
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000861 line = linecache.getline(fn, frame.f_lineno, frame.f_globals)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000862 print('+++', fn, frame.f_lineno, name, ':', line.strip())
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000863 def user_return(self, frame, retval):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000864 print('+++ return', retval)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000865 def user_exception(self, frame, exc_stuff):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000866 print('+++ exception', exc_stuff)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000867 self.set_continue()
Guido van Rossumbabe2bf1992-01-22 22:21:31 +0000868
869def foo(n):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000870 print('foo(', n, ')')
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000871 x = bar(n*10)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000872 print('bar returned', x)
Guido van Rossumbabe2bf1992-01-22 22:21:31 +0000873
874def bar(a):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000875 print('bar(', a, ')')
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000876 return a/2
Guido van Rossumbabe2bf1992-01-22 22:21:31 +0000877
878def test():
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000879 t = Tdb()
880 t.run('import bdb; bdb.foo(10)')