blob: 75d6113576372e94d8a41403ba01fe96e6665af3 [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
Irit Katrielad442a62021-04-02 17:15:21 +010037 self._load_breaks()
38
Guido van Rossum4acc25b2000-02-02 15:10:15 +000039 def canonic(self, filename):
csabella0774e792017-05-16 18:28:02 -040040 """Return canonical form of filename.
41
42 For real filenames, the canonical form is a case-normalized (on
Min ho Kim39d87b52019-08-31 06:21:19 +100043 case insensitive filesystems) absolute path. 'Filenames' with
csabella0774e792017-05-16 18:28:02 -040044 angle brackets, such as "<stdin>", generated in interactive
45 mode, are returned unchanged.
46 """
Guido van Rossum42f53322001-11-29 02:50:15 +000047 if filename == "<" + filename[1:-1] + ">":
48 return filename
Guido van Rossum4acc25b2000-02-02 15:10:15 +000049 canonic = self.fncache.get(filename)
50 if not canonic:
51 canonic = os.path.abspath(filename)
Guido van Rossumbdba3202002-02-25 23:23:24 +000052 canonic = os.path.normcase(canonic)
Guido van Rossum4acc25b2000-02-02 15:10:15 +000053 self.fncache[filename] = canonic
54 return canonic
Tim Peters11cf6052001-01-14 21:54:20 +000055
Guido van Rossum4acc25b2000-02-02 15:10:15 +000056 def reset(self):
csabella0774e792017-05-16 18:28:02 -040057 """Set values of attributes as ready to start debugging."""
Guido van Rossum4acc25b2000-02-02 15:10:15 +000058 import linecache
59 linecache.checkcache()
60 self.botframe = None
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000061 self._set_stopinfo(None, None)
Tim Peters11cf6052001-01-14 21:54:20 +000062
Guido van Rossum4acc25b2000-02-02 15:10:15 +000063 def trace_dispatch(self, frame, event, arg):
csabella0774e792017-05-16 18:28:02 -040064 """Dispatch a trace function for debugged frames based on the event.
65
66 This function is installed as the trace function for debugged
67 frames. Its return value is the new trace function, which is
68 usually itself. The default implementation decides how to
69 dispatch a frame, depending on the type of event (passed in as a
70 string) that is about to be executed.
71
72 The event can be one of the following:
73 line: A new line of code is going to be executed.
74 call: A function is about to be called or another code block
75 is entered.
76 return: A function or other code block is about to return.
77 exception: An exception has occurred.
78 c_call: A C function is about to be called.
Stéphane Wirtel07fbbfd2018-10-05 16:17:18 +020079 c_return: A C function has returned.
csabella0774e792017-05-16 18:28:02 -040080 c_exception: A C function has raised an exception.
81
82 For the Python events, specialized functions (see the dispatch_*()
83 methods) are called. For the C events, no action is taken.
84
85 The arg parameter depends on the previous event.
86 """
Guido van Rossum4acc25b2000-02-02 15:10:15 +000087 if self.quitting:
88 return # None
89 if event == 'line':
90 return self.dispatch_line(frame)
91 if event == 'call':
92 return self.dispatch_call(frame, arg)
93 if event == 'return':
94 return self.dispatch_return(frame, arg)
95 if event == 'exception':
96 return self.dispatch_exception(frame, arg)
Nicholas Bastinc69ebe82004-03-24 21:57:10 +000097 if event == 'c_call':
98 return self.trace_dispatch
99 if event == 'c_exception':
100 return self.trace_dispatch
101 if event == 'c_return':
102 return self.trace_dispatch
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000103 print('bdb.Bdb.dispatch: unknown debugging event:', repr(event))
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000104 return self.trace_dispatch
Tim Peters11cf6052001-01-14 21:54:20 +0000105
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000106 def dispatch_line(self, frame):
csabella0774e792017-05-16 18:28:02 -0400107 """Invoke user function and return trace function for line event.
108
109 If the debugger stops on the current line, invoke
110 self.user_line(). Raise BdbQuit if self.quitting is set.
111 Return self.trace_dispatch to continue tracing in this scope.
112 """
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000113 if self.stop_here(frame) or self.break_here(frame):
114 self.user_line(frame)
115 if self.quitting: raise BdbQuit
116 return self.trace_dispatch
Tim Peters11cf6052001-01-14 21:54:20 +0000117
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000118 def dispatch_call(self, frame, arg):
csabella0774e792017-05-16 18:28:02 -0400119 """Invoke user function and return trace function for call event.
120
121 If the debugger stops on this function call, invoke
Miss Islington (bot)d22fa222021-05-16 16:42:56 -0700122 self.user_call(). Raise BdbQuit if self.quitting is set.
csabella0774e792017-05-16 18:28:02 -0400123 Return self.trace_dispatch to continue tracing in this scope.
124 """
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000125 # XXX 'arg' is no longer used
126 if self.botframe is None:
127 # First call of dispatch since reset()
Christian Tismer313a7512002-05-28 08:04:00 +0000128 self.botframe = frame.f_back # (CT) Note that this may also be None!
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000129 return self.trace_dispatch
130 if not (self.stop_here(frame) or self.break_anywhere(frame)):
131 # No need to trace this function
132 return # None
Guido van Rossum8820c232013-11-21 11:30:06 -0800133 # Ignore call events in generator except when stepping.
Pablo Galindoc7ab5812018-01-29 01:31:00 +0000134 if self.stopframe and frame.f_code.co_flags & GENERATOR_AND_COROUTINE_FLAGS:
Guido van Rossum8820c232013-11-21 11:30:06 -0800135 return self.trace_dispatch
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000136 self.user_call(frame, arg)
137 if self.quitting: raise BdbQuit
138 return self.trace_dispatch
Tim Peters11cf6052001-01-14 21:54:20 +0000139
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000140 def dispatch_return(self, frame, arg):
csabella0774e792017-05-16 18:28:02 -0400141 """Invoke user function and return trace function for return event.
142
143 If the debugger stops on this function return, invoke
144 self.user_return(). Raise BdbQuit if self.quitting is set.
145 Return self.trace_dispatch to continue tracing in this scope.
146 """
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000147 if self.stop_here(frame) or frame == self.returnframe:
Guido van Rossum8820c232013-11-21 11:30:06 -0800148 # Ignore return events in generator except when stepping.
Pablo Galindoc7ab5812018-01-29 01:31:00 +0000149 if self.stopframe and frame.f_code.co_flags & GENERATOR_AND_COROUTINE_FLAGS:
Guido van Rossum8820c232013-11-21 11:30:06 -0800150 return self.trace_dispatch
Senthil Kumaran42d70812012-05-01 10:07:49 +0800151 try:
152 self.frame_returning = frame
153 self.user_return(frame, arg)
154 finally:
155 self.frame_returning = None
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000156 if self.quitting: raise BdbQuit
Guido van Rossum8820c232013-11-21 11:30:06 -0800157 # The user issued a 'next' or 'until' command.
158 if self.stopframe is frame and self.stoplineno != -1:
159 self._set_stopinfo(None, None)
Just van Rossumae1f65f2001-06-25 18:01:24 +0000160 return self.trace_dispatch
Tim Peters11cf6052001-01-14 21:54:20 +0000161
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000162 def dispatch_exception(self, frame, arg):
csabella0774e792017-05-16 18:28:02 -0400163 """Invoke user function and return trace function for exception event.
164
165 If the debugger stops on this exception, invoke
166 self.user_exception(). Raise BdbQuit if self.quitting is set.
167 Return self.trace_dispatch to continue tracing in this scope.
168 """
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000169 if self.stop_here(frame):
Guido van Rossum8820c232013-11-21 11:30:06 -0800170 # When stepping with next/until/return in a generator frame, skip
171 # the internal StopIteration exception (with no traceback)
172 # triggered by a subiterator run with the 'yield from' statement.
Pablo Galindoc7ab5812018-01-29 01:31:00 +0000173 if not (frame.f_code.co_flags & GENERATOR_AND_COROUTINE_FLAGS
Guido van Rossum8820c232013-11-21 11:30:06 -0800174 and arg[0] is StopIteration and arg[2] is None):
175 self.user_exception(frame, arg)
176 if self.quitting: raise BdbQuit
177 # Stop at the StopIteration or GeneratorExit exception when the user
178 # has set stopframe in a generator by issuing a return command, or a
179 # next/until command at the last statement in the generator before the
180 # exception.
181 elif (self.stopframe and frame is not self.stopframe
Pablo Galindoc7ab5812018-01-29 01:31:00 +0000182 and self.stopframe.f_code.co_flags & GENERATOR_AND_COROUTINE_FLAGS
Guido van Rossum8820c232013-11-21 11:30:06 -0800183 and arg[0] in (StopIteration, GeneratorExit)):
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000184 self.user_exception(frame, arg)
185 if self.quitting: raise BdbQuit
Guido van Rossum8820c232013-11-21 11:30:06 -0800186
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000187 return self.trace_dispatch
Tim Peters11cf6052001-01-14 21:54:20 +0000188
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000189 # Normally derived classes don't override the following
190 # methods, but they may if they want to redefine the
191 # definition of stopping and breakpoints.
Tim Peters11cf6052001-01-14 21:54:20 +0000192
Georg Brandl243ad662009-05-05 09:00:19 +0000193 def is_skipped_module(self, module_name):
csabella0774e792017-05-16 18:28:02 -0400194 "Return True if module_name matches any skip pattern."
Anthony Sottile86900a42019-03-12 20:57:09 -0700195 if module_name is None: # some modules do not have names
196 return False
Georg Brandl243ad662009-05-05 09:00:19 +0000197 for pattern in self.skip:
198 if fnmatch.fnmatch(module_name, pattern):
199 return True
200 return False
201
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000202 def stop_here(self, frame):
csabella0774e792017-05-16 18:28:02 -0400203 "Return True if frame is below the starting frame in the stack."
Neal Norwitz72a2b4d2002-05-29 00:54:38 +0000204 # (CT) stopframe may now also be None, see dispatch_call.
205 # (CT) the former test for None is therefore removed from here.
Georg Brandl243ad662009-05-05 09:00:19 +0000206 if self.skip and \
207 self.is_skipped_module(frame.f_globals.get('__name__')):
208 return False
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000209 if frame is self.stopframe:
Georg Brandl3f940892010-07-30 10:29:19 +0000210 if self.stoplineno == -1:
211 return False
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000212 return frame.f_lineno >= self.stoplineno
Guido van Rossum8820c232013-11-21 11:30:06 -0800213 if not self.stopframe:
214 return True
Tim Petersbc0e9102002-04-04 22:55:58 +0000215 return False
Guido van Rossumd93643f1998-09-11 22:38:35 +0000216
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000217 def break_here(self, frame):
csabella0774e792017-05-16 18:28:02 -0400218 """Return True if there is an effective breakpoint for this line.
219
220 Check for line or function breakpoint and if in effect.
221 Delete temporary breakpoints if effective() says to.
222 """
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000223 filename = self.canonic(frame.f_code.co_filename)
Georg Brandl26607472010-11-29 20:12:24 +0000224 if filename not in self.breaks:
Tim Petersbc0e9102002-04-04 22:55:58 +0000225 return False
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000226 lineno = frame.f_lineno
Georg Brandl26607472010-11-29 20:12:24 +0000227 if lineno not in self.breaks[filename]:
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000228 # The line itself has no breakpoint, but maybe the line is the
229 # first line of a function with breakpoint set by function name.
230 lineno = frame.f_code.co_firstlineno
Georg Brandl26607472010-11-29 20:12:24 +0000231 if lineno not in self.breaks[filename]:
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000232 return False
233
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000234 # flag says ok to delete temp. bp
235 (bp, flag) = effective(filename, lineno, frame)
236 if bp:
237 self.currentbp = bp.number
238 if (flag and bp.temporary):
239 self.do_clear(str(bp.number))
Tim Petersbc0e9102002-04-04 22:55:58 +0000240 return True
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000241 else:
Tim Petersbc0e9102002-04-04 22:55:58 +0000242 return False
Tim Peters11cf6052001-01-14 21:54:20 +0000243
Guido van Rossum9cec8fb2001-04-08 15:05:16 +0000244 def do_clear(self, arg):
csabella0774e792017-05-16 18:28:02 -0400245 """Remove temporary breakpoint.
246
247 Must implement in derived classes or get NotImplementedError.
248 """
Collin Winterce36ad82007-08-30 01:19:48 +0000249 raise NotImplementedError("subclass of bdb must implement do_clear()")
Guido van Rossum9cec8fb2001-04-08 15:05:16 +0000250
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000251 def break_anywhere(self, frame):
csabella0774e792017-05-16 18:28:02 -0400252 """Return True if there is any breakpoint for frame's filename.
253 """
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000254 return self.canonic(frame.f_code.co_filename) in self.breaks
Tim Peters11cf6052001-01-14 21:54:20 +0000255
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000256 # Derived classes should override the user_* methods
257 # to gain control.
Tim Peters11cf6052001-01-14 21:54:20 +0000258
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000259 def user_call(self, frame, argument_list):
csabella0774e792017-05-16 18:28:02 -0400260 """Called if we might stop in a function."""
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000261 pass
Tim Peters11cf6052001-01-14 21:54:20 +0000262
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000263 def user_line(self, frame):
Eitan Adlerb5c246f2018-06-02 07:16:19 -0700264 """Called when we stop or break at a line."""
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000265 pass
Tim Peters11cf6052001-01-14 21:54:20 +0000266
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000267 def user_return(self, frame, return_value):
csabella0774e792017-05-16 18:28:02 -0400268 """Called when a return trap is set here."""
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000269 pass
Tim Peters11cf6052001-01-14 21:54:20 +0000270
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000271 def user_exception(self, frame, exc_info):
csabella0774e792017-05-16 18:28:02 -0400272 """Called when we stop on an exception."""
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000273 pass
Tim Peters11cf6052001-01-14 21:54:20 +0000274
Georg Brandl3f940892010-07-30 10:29:19 +0000275 def _set_stopinfo(self, stopframe, returnframe, stoplineno=0):
csabella0774e792017-05-16 18:28:02 -0400276 """Set the attributes for stopping.
277
278 If stoplineno is greater than or equal to 0, then stop at line
279 greater than or equal to the stopline. If stoplineno is -1, then
280 don't stop at all.
281 """
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000282 self.stopframe = stopframe
283 self.returnframe = returnframe
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000284 self.quitting = False
Georg Brandl3f940892010-07-30 10:29:19 +0000285 # stoplineno >= 0 means: stop at line >= the stoplineno
286 # stoplineno -1 means: don't stop at all
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000287 self.stoplineno = stoplineno
288
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000289 # Derived classes and clients can call the following methods
290 # to affect the stepping state.
Tim Peters11cf6052001-01-14 21:54:20 +0000291
Georg Brandl2dfec552010-07-30 08:43:32 +0000292 def set_until(self, frame, lineno=None):
csabella0774e792017-05-16 18:28:02 -0400293 """Stop when the line with the lineno greater than the current one is
294 reached or when returning from current frame."""
Georg Brandl2dfec552010-07-30 08:43:32 +0000295 # the name "until" is borrowed from gdb
296 if lineno is None:
297 lineno = frame.f_lineno + 1
298 self._set_stopinfo(frame, frame, lineno)
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000299
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000300 def set_step(self):
301 """Stop after one line of code."""
Senthil Kumaran42d70812012-05-01 10:07:49 +0800302 # Issue #13183: pdb skips frames after hitting a breakpoint and running
303 # step commands.
304 # Restore the trace function in the caller (that may not have been set
305 # for performance reasons) when returning from the current frame.
306 if self.frame_returning:
307 caller_frame = self.frame_returning.f_back
308 if caller_frame and not caller_frame.f_trace:
309 caller_frame.f_trace = self.trace_dispatch
Georg Brandl3f940892010-07-30 10:29:19 +0000310 self._set_stopinfo(None, None)
Tim Peters11cf6052001-01-14 21:54:20 +0000311
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000312 def set_next(self, frame):
313 """Stop on the next line in or below the given frame."""
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000314 self._set_stopinfo(frame, None)
Tim Peters11cf6052001-01-14 21:54:20 +0000315
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000316 def set_return(self, frame):
317 """Stop when returning from the given frame."""
Pablo Galindoc7ab5812018-01-29 01:31:00 +0000318 if frame.f_code.co_flags & GENERATOR_AND_COROUTINE_FLAGS:
Guido van Rossum8820c232013-11-21 11:30:06 -0800319 self._set_stopinfo(frame, None, -1)
320 else:
321 self._set_stopinfo(frame.f_back, frame)
Tim Peters11cf6052001-01-14 21:54:20 +0000322
Johannes Gijsbers84a6c202004-11-07 11:35:30 +0000323 def set_trace(self, frame=None):
csabella0774e792017-05-16 18:28:02 -0400324 """Start debugging from frame.
Johannes Gijsbers84a6c202004-11-07 11:35:30 +0000325
326 If frame is not specified, debugging starts from caller's frame.
327 """
328 if frame is None:
329 frame = sys._getframe().f_back
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000330 self.reset()
331 while frame:
332 frame.f_trace = self.trace_dispatch
333 self.botframe = frame
334 frame = frame.f_back
335 self.set_step()
336 sys.settrace(self.trace_dispatch)
Guido van Rossumb6775db1994-08-01 11:34:53 +0000337
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000338 def set_continue(self):
csabella0774e792017-05-16 18:28:02 -0400339 """Stop only at breakpoints or when finished.
340
341 If there are no breakpoints, set the system trace function to None.
342 """
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000343 # Don't stop except at breakpoints or when finished
Georg Brandl3f940892010-07-30 10:29:19 +0000344 self._set_stopinfo(self.botframe, None, -1)
Georg Brandlf8b893e2010-12-04 16:22:44 +0000345 if not self.breaks:
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000346 # no breakpoints; run without debugger overhead
347 sys.settrace(None)
Christian Tismer313a7512002-05-28 08:04:00 +0000348 frame = sys._getframe().f_back
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000349 while frame and frame is not self.botframe:
350 del frame.f_trace
351 frame = frame.f_back
Tim Peters11cf6052001-01-14 21:54:20 +0000352
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000353 def set_quit(self):
csabella0774e792017-05-16 18:28:02 -0400354 """Set quitting attribute to True.
355
356 Raises BdbQuit exception in the next call to a dispatch_*() method.
357 """
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000358 self.stopframe = self.botframe
359 self.returnframe = None
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000360 self.quitting = True
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000361 sys.settrace(None)
Tim Peters11cf6052001-01-14 21:54:20 +0000362
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000363 # Derived classes and clients can call the following methods
364 # to manipulate breakpoints. These methods return an
csabella0774e792017-05-16 18:28:02 -0400365 # error message if something went wrong, None if all is well.
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000366 # Set_break prints out the breakpoint line and file:lineno.
367 # Call self.get_*break*() to see the breakpoints or better
368 # for bp in Breakpoint.bpbynumber: if bp: bp.bpprint().
Tim Peters11cf6052001-01-14 21:54:20 +0000369
Irit Katrielad442a62021-04-02 17:15:21 +0100370 def _add_to_breaks(self, filename, lineno):
371 """Add breakpoint to breaks, if not already there."""
372 bp_linenos = self.breaks.setdefault(filename, [])
373 if lineno not in bp_linenos:
374 bp_linenos.append(lineno)
375
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000376 def set_break(self, filename, lineno, temporary=False, cond=None,
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000377 funcname=None):
csabella0774e792017-05-16 18:28:02 -0400378 """Set a new breakpoint for filename:lineno.
379
380 If lineno doesn't exist for the filename, return an error message.
381 The filename should be in canonical form.
382 """
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000383 filename = self.canonic(filename)
384 import linecache # Import as late as possible
385 line = linecache.getline(filename, lineno)
386 if not line:
Georg Brandl26607472010-11-29 20:12:24 +0000387 return 'Line %s:%d does not exist' % (filename, lineno)
Irit Katrielad442a62021-04-02 17:15:21 +0100388 self._add_to_breaks(filename, lineno)
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000389 bp = Breakpoint(filename, lineno, temporary, cond, funcname)
csabella0774e792017-05-16 18:28:02 -0400390 return None
Guido van Rossumd93643f1998-09-11 22:38:35 +0000391
Irit Katrielad442a62021-04-02 17:15:21 +0100392 def _load_breaks(self):
393 """Apply all breakpoints (set in other instances) to this one.
394
395 Populates this instance's breaks list from the Breakpoint class's
396 list, which can have breakpoints set by another Bdb instance. This
397 is necessary for interactive sessions to keep the breakpoints
398 active across multiple calls to run().
399 """
400 for (filename, lineno) in Breakpoint.bplist.keys():
401 self._add_to_breaks(filename, lineno)
402
Senthil Kumaran6f107042010-11-29 11:54:17 +0000403 def _prune_breaks(self, filename, lineno):
Xtreak0d702272019-06-03 04:42:33 +0530404 """Prune breakpoints for filename:lineno.
csabella0774e792017-05-16 18:28:02 -0400405
406 A list of breakpoints is maintained in the Bdb instance and in
407 the Breakpoint class. If a breakpoint in the Bdb instance no
408 longer exists in the Breakpoint class, then it's removed from the
409 Bdb instance.
410 """
Senthil Kumaran6f107042010-11-29 11:54:17 +0000411 if (filename, lineno) not in Breakpoint.bplist:
412 self.breaks[filename].remove(lineno)
413 if not self.breaks[filename]:
414 del self.breaks[filename]
415
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000416 def clear_break(self, filename, lineno):
csabella0774e792017-05-16 18:28:02 -0400417 """Delete breakpoints for filename:lineno.
418
419 If no breakpoints were set, return an error message.
420 """
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000421 filename = self.canonic(filename)
Georg Brandl26607472010-11-29 20:12:24 +0000422 if filename not in self.breaks:
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000423 return 'There are no breakpoints in %s' % filename
424 if lineno not in self.breaks[filename]:
Georg Brandl26607472010-11-29 20:12:24 +0000425 return 'There is no breakpoint at %s:%d' % (filename, lineno)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000426 # If there's only one bp in the list for that file,line
427 # pair, then remove the breaks entry
428 for bp in Breakpoint.bplist[filename, lineno][:]:
429 bp.deleteMe()
Senthil Kumaran6f107042010-11-29 11:54:17 +0000430 self._prune_breaks(filename, lineno)
csabella0774e792017-05-16 18:28:02 -0400431 return None
Tim Peters11cf6052001-01-14 21:54:20 +0000432
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000433 def clear_bpbynumber(self, arg):
csabella0774e792017-05-16 18:28:02 -0400434 """Delete a breakpoint by its index in Breakpoint.bpbynumber.
435
436 If arg is invalid, return an error message.
437 """
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000438 try:
Georg Brandl7410dd12010-07-30 12:01:20 +0000439 bp = self.get_bpbynumber(arg)
440 except ValueError as err:
441 return str(err)
Senthil Kumaran6f107042010-11-29 11:54:17 +0000442 bp.deleteMe()
443 self._prune_breaks(bp.file, bp.line)
csabella0774e792017-05-16 18:28:02 -0400444 return None
Guido van Rossum6ea27cc1999-01-25 20:51:34 +0000445
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000446 def clear_all_file_breaks(self, filename):
csabella0774e792017-05-16 18:28:02 -0400447 """Delete all breakpoints in filename.
448
449 If none were set, return an error message.
450 """
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000451 filename = self.canonic(filename)
Georg Brandl26607472010-11-29 20:12:24 +0000452 if filename not in self.breaks:
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000453 return 'There are no breakpoints in %s' % filename
454 for line in self.breaks[filename]:
455 blist = Breakpoint.bplist[filename, line]
456 for bp in blist:
457 bp.deleteMe()
458 del self.breaks[filename]
csabella0774e792017-05-16 18:28:02 -0400459 return None
Tim Peters11cf6052001-01-14 21:54:20 +0000460
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000461 def clear_all_breaks(self):
csabella0774e792017-05-16 18:28:02 -0400462 """Delete all existing breakpoints.
463
464 If none were set, return an error message.
465 """
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000466 if not self.breaks:
467 return 'There are no breakpoints'
468 for bp in Breakpoint.bpbynumber:
469 if bp:
470 bp.deleteMe()
471 self.breaks = {}
csabella0774e792017-05-16 18:28:02 -0400472 return None
Tim Peters11cf6052001-01-14 21:54:20 +0000473
Georg Brandl7410dd12010-07-30 12:01:20 +0000474 def get_bpbynumber(self, arg):
csabella0774e792017-05-16 18:28:02 -0400475 """Return a breakpoint by its index in Breakpoint.bybpnumber.
476
477 For invalid arg values or if the breakpoint doesn't exist,
478 raise a ValueError.
479 """
Georg Brandl7410dd12010-07-30 12:01:20 +0000480 if not arg:
481 raise ValueError('Breakpoint number expected')
482 try:
483 number = int(arg)
484 except ValueError:
Serhiy Storchaka5affd232017-04-05 09:37:24 +0300485 raise ValueError('Non-numeric breakpoint number %s' % arg) from None
Georg Brandl7410dd12010-07-30 12:01:20 +0000486 try:
487 bp = Breakpoint.bpbynumber[number]
488 except IndexError:
Serhiy Storchaka5affd232017-04-05 09:37:24 +0300489 raise ValueError('Breakpoint number %d out of range' % number) from None
Georg Brandl7410dd12010-07-30 12:01:20 +0000490 if bp is None:
491 raise ValueError('Breakpoint %d already deleted' % number)
492 return bp
493
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000494 def get_break(self, filename, lineno):
csabella0774e792017-05-16 18:28:02 -0400495 """Return True if there is a breakpoint for filename:lineno."""
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000496 filename = self.canonic(filename)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000497 return filename in self.breaks and \
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000498 lineno in self.breaks[filename]
Tim Peters11cf6052001-01-14 21:54:20 +0000499
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000500 def get_breaks(self, filename, lineno):
csabella0774e792017-05-16 18:28:02 -0400501 """Return all breakpoints for filename:lineno.
502
503 If no breakpoints are set, return an empty list.
504 """
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000505 filename = self.canonic(filename)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000506 return filename in self.breaks and \
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000507 lineno in self.breaks[filename] and \
508 Breakpoint.bplist[filename, lineno] or []
Tim Peters11cf6052001-01-14 21:54:20 +0000509
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000510 def get_file_breaks(self, filename):
csabella0774e792017-05-16 18:28:02 -0400511 """Return all lines with breakpoints for filename.
512
513 If no breakpoints are set, return an empty list.
514 """
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000515 filename = self.canonic(filename)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000516 if filename in self.breaks:
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000517 return self.breaks[filename]
518 else:
519 return []
Tim Peters11cf6052001-01-14 21:54:20 +0000520
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000521 def get_all_breaks(self):
csabella0774e792017-05-16 18:28:02 -0400522 """Return all breakpoints that are set."""
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000523 return self.breaks
Tim Peters11cf6052001-01-14 21:54:20 +0000524
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000525 # Derived classes and clients can call the following method
526 # to get a data structure representing a stack trace.
Tim Peters11cf6052001-01-14 21:54:20 +0000527
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000528 def get_stack(self, f, t):
csabella0774e792017-05-16 18:28:02 -0400529 """Return a list of (frame, lineno) in a stack trace and a size.
530
531 List starts with original calling frame, if there is one.
532 Size may be number of frames above or below f.
533 """
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000534 stack = []
535 if t and t.tb_frame is f:
536 t = t.tb_next
537 while f is not None:
538 stack.append((f, f.f_lineno))
539 if f is self.botframe:
540 break
541 f = f.f_back
542 stack.reverse()
543 i = max(0, len(stack) - 1)
544 while t is not None:
545 stack.append((t.tb_frame, t.tb_lineno))
546 t = t.tb_next
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +0000547 if f is None:
548 i = max(0, len(stack) - 1)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000549 return stack, i
Tim Peters11cf6052001-01-14 21:54:20 +0000550
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000551 def format_stack_entry(self, frame_lineno, lprefix=': '):
csabella0774e792017-05-16 18:28:02 -0400552 """Return a string with information about a stack entry.
553
554 The stack entry frame_lineno is a (frame, lineno) tuple. The
555 return string contains the canonical filename, the function name
556 or '<lambda>', the input arguments, the return value, and the
557 line of code (if it exists).
558
559 """
Alexandre Vassalotti1f2ba4b2008-05-16 07:12:44 +0000560 import linecache, reprlib
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000561 frame, lineno = frame_lineno
562 filename = self.canonic(frame.f_code.co_filename)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000563 s = '%s(%r)' % (filename, lineno)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000564 if frame.f_code.co_name:
Georg Brandl26607472010-11-29 20:12:24 +0000565 s += frame.f_code.co_name
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000566 else:
Georg Brandl26607472010-11-29 20:12:24 +0000567 s += "<lambda>"
Daniel Hahler4015d1c2020-02-24 04:14:53 +0100568 s += '()'
Raymond Hettinger54f02222002-06-01 14:18:47 +0000569 if '__return__' in frame.f_locals:
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000570 rv = frame.f_locals['__return__']
Georg Brandl26607472010-11-29 20:12:24 +0000571 s += '->'
572 s += reprlib.repr(rv)
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000573 line = linecache.getline(filename, lineno, frame.f_globals)
Georg Brandl26607472010-11-29 20:12:24 +0000574 if line:
575 s += lprefix + line.strip()
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000576 return s
Tim Peters11cf6052001-01-14 21:54:20 +0000577
Georg Brandl46b9afc2010-07-30 09:14:20 +0000578 # The following methods can be called by clients to use
579 # a debugger to debug a statement or an expression.
580 # Both can be given as a string, or a code object.
Tim Peters11cf6052001-01-14 21:54:20 +0000581
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000582 def run(self, cmd, globals=None, locals=None):
csabella0774e792017-05-16 18:28:02 -0400583 """Debug a statement executed via the exec() function.
584
585 globals defaults to __main__.dict; locals defaults to globals.
586 """
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000587 if globals is None:
588 import __main__
589 globals = __main__.__dict__
590 if locals is None:
591 locals = globals
592 self.reset()
Victor Stinner4bd81722011-01-06 00:49:38 +0000593 if isinstance(cmd, str):
594 cmd = compile(cmd, "<string>", "exec")
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000595 sys.settrace(self.trace_dispatch)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000596 try:
Martin v. Löwisede8ffb2008-03-30 20:43:50 +0000597 exec(cmd, globals, locals)
598 except BdbQuit:
599 pass
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000600 finally:
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000601 self.quitting = True
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000602 sys.settrace(None)
Tim Peters11cf6052001-01-14 21:54:20 +0000603
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000604 def runeval(self, expr, globals=None, locals=None):
csabella0774e792017-05-16 18:28:02 -0400605 """Debug an expression executed via the eval() function.
606
607 globals defaults to __main__.dict; locals defaults to globals.
608 """
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000609 if globals is None:
610 import __main__
611 globals = __main__.__dict__
612 if locals is None:
613 locals = globals
614 self.reset()
615 sys.settrace(self.trace_dispatch)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000616 try:
Martin v. Löwisede8ffb2008-03-30 20:43:50 +0000617 return eval(expr, globals, locals)
618 except BdbQuit:
619 pass
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000620 finally:
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000621 self.quitting = True
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000622 sys.settrace(None)
Guido van Rossum5e38b6f1995-02-27 13:13:40 +0000623
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000624 def runctx(self, cmd, globals, locals):
csabella0774e792017-05-16 18:28:02 -0400625 """For backwards-compatibility. Defers to run()."""
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000626 # B/W compatibility
627 self.run(cmd, globals, locals)
Guido van Rossum4e160981992-09-02 20:43:20 +0000628
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000629 # This method is more useful to debug a single function call.
Guido van Rossum4e160981992-09-02 20:43:20 +0000630
Serhiy Storchaka142566c2019-06-05 18:22:31 +0300631 def runcall(self, func, /, *args, **kwds):
csabella0774e792017-05-16 18:28:02 -0400632 """Debug a single function call.
633
634 Return the result of the function call.
635 """
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000636 self.reset()
637 sys.settrace(self.trace_dispatch)
638 res = None
639 try:
Martin v. Löwisede8ffb2008-03-30 20:43:50 +0000640 res = func(*args, **kwds)
641 except BdbQuit:
642 pass
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000643 finally:
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000644 self.quitting = True
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000645 sys.settrace(None)
646 return res
Guido van Rossumbabe2bf1992-01-22 22:21:31 +0000647
Guido van Rossumbabe2bf1992-01-22 22:21:31 +0000648
Guido van Rossumb6775db1994-08-01 11:34:53 +0000649def set_trace():
csabella0774e792017-05-16 18:28:02 -0400650 """Start debugging with a Bdb instance from the caller's frame."""
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000651 Bdb().set_trace()
Guido van Rossumb6775db1994-08-01 11:34:53 +0000652
Guido van Rossumd93643f1998-09-11 22:38:35 +0000653
654class Breakpoint:
Georg Brandl26607472010-11-29 20:12:24 +0000655 """Breakpoint class.
Guido van Rossumd93643f1998-09-11 22:38:35 +0000656
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000657 Implements temporary breakpoints, ignore counts, disabling and
658 (re)-enabling, and conditionals.
Guido van Rossumd93643f1998-09-11 22:38:35 +0000659
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000660 Breakpoints are indexed by number through bpbynumber and by
csabella0774e792017-05-16 18:28:02 -0400661 the (file, line) tuple using bplist. The former points to a
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000662 single instance of class Breakpoint. The latter points to a
663 list of such instances since there may be more than one
664 breakpoint per line.
Guido van Rossumd93643f1998-09-11 22:38:35 +0000665
csabella0774e792017-05-16 18:28:02 -0400666 When creating a breakpoint, its associated filename should be
667 in canonical form. If funcname is defined, a breakpoint hit will be
668 counted when the first line of that function is executed. A
669 conditional breakpoint always counts a hit.
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000670 """
Guido van Rossumd93643f1998-09-11 22:38:35 +0000671
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000672 # XXX Keeping state in the class is a mistake -- this means
673 # you cannot have more than one active Bdb instance.
Guido van Rossumd93643f1998-09-11 22:38:35 +0000674
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000675 next = 1 # Next bp to be assigned
676 bplist = {} # indexed by (file, lineno) tuple
677 bpbynumber = [None] # Each entry is None or an instance of Bpt
678 # index 0 is unused, except for marking an
679 # effective break .... see effective()
Guido van Rossumd93643f1998-09-11 22:38:35 +0000680
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000681 def __init__(self, file, line, temporary=False, cond=None, funcname=None):
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000682 self.funcname = funcname
683 # Needed if funcname is not None.
684 self.func_first_executable_line = None
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000685 self.file = file # This better be in canonical form!
686 self.line = line
687 self.temporary = temporary
688 self.cond = cond
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000689 self.enabled = True
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000690 self.ignore = 0
691 self.hits = 0
692 self.number = Breakpoint.next
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000693 Breakpoint.next += 1
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000694 # Build the two lists
695 self.bpbynumber.append(self)
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000696 if (file, line) in self.bplist:
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000697 self.bplist[file, line].append(self)
698 else:
699 self.bplist[file, line] = [self]
Guido van Rossumd93643f1998-09-11 22:38:35 +0000700
Irit Katrielad442a62021-04-02 17:15:21 +0100701 @staticmethod
702 def clearBreakpoints():
703 Breakpoint.next = 1
704 Breakpoint.bplist = {}
705 Breakpoint.bpbynumber = [None]
706
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000707 def deleteMe(self):
csabella0774e792017-05-16 18:28:02 -0400708 """Delete the breakpoint from the list associated to a file:line.
709
710 If it is the last breakpoint in that position, it also deletes
711 the entry for the file:line.
712 """
713
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000714 index = (self.file, self.line)
715 self.bpbynumber[self.number] = None # No longer in list
716 self.bplist[index].remove(self)
717 if not self.bplist[index]:
718 # No more bp for this f:l combo
719 del self.bplist[index]
Guido van Rossumd93643f1998-09-11 22:38:35 +0000720
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000721 def enable(self):
csabella0774e792017-05-16 18:28:02 -0400722 """Mark the breakpoint as enabled."""
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000723 self.enabled = True
Guido van Rossumd93643f1998-09-11 22:38:35 +0000724
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000725 def disable(self):
csabella0774e792017-05-16 18:28:02 -0400726 """Mark the breakpoint as disabled."""
Georg Brandlac9a2bb2010-11-29 20:19:15 +0000727 self.enabled = False
Guido van Rossumd93643f1998-09-11 22:38:35 +0000728
Thomas Wouters477c8d52006-05-27 19:21:47 +0000729 def bpprint(self, out=None):
csabella0774e792017-05-16 18:28:02 -0400730 """Print the output of bpformat().
731
732 The optional out argument directs where the output is sent
733 and defaults to standard output.
734 """
Thomas Wouters477c8d52006-05-27 19:21:47 +0000735 if out is None:
736 out = sys.stdout
Georg Brandld2fd4ca2010-07-30 15:01:23 +0000737 print(self.bpformat(), file=out)
738
739 def bpformat(self):
csabella0774e792017-05-16 18:28:02 -0400740 """Return a string with information about the breakpoint.
741
742 The information includes the breakpoint number, temporary
743 status, file:line position, break condition, number of times to
744 ignore, and number of times hit.
745
746 """
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000747 if self.temporary:
Tim Peters11cf6052001-01-14 21:54:20 +0000748 disp = 'del '
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000749 else:
Tim Peters11cf6052001-01-14 21:54:20 +0000750 disp = 'keep '
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000751 if self.enabled:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000752 disp = disp + 'yes '
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000753 else:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000754 disp = disp + 'no '
Georg Brandld2fd4ca2010-07-30 15:01:23 +0000755 ret = '%-4dbreakpoint %s at %s:%d' % (self.number, disp,
756 self.file, self.line)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000757 if self.cond:
Georg Brandld2fd4ca2010-07-30 15:01:23 +0000758 ret += '\n\tstop only if %s' % (self.cond,)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000759 if self.ignore:
Georg Brandld2fd4ca2010-07-30 15:01:23 +0000760 ret += '\n\tignore next %d hits' % (self.ignore,)
761 if self.hits:
762 if self.hits > 1:
763 ss = 's'
764 else:
765 ss = ''
766 ret += '\n\tbreakpoint already hit %d time%s' % (self.hits, ss)
767 return ret
Guido van Rossumd93643f1998-09-11 22:38:35 +0000768
Georg Brandl7410dd12010-07-30 12:01:20 +0000769 def __str__(self):
csabella0774e792017-05-16 18:28:02 -0400770 "Return a condensed description of the breakpoint."
Georg Brandl7410dd12010-07-30 12:01:20 +0000771 return 'breakpoint %s at %s:%s' % (self.number, self.file, self.line)
772
Guido van Rossumd93643f1998-09-11 22:38:35 +0000773# -----------end of Breakpoint class----------
774
csabella0774e792017-05-16 18:28:02 -0400775
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000776def checkfuncname(b, frame):
csabella0774e792017-05-16 18:28:02 -0400777 """Return True if break should happen here.
778
779 Whether a break should happen depends on the way that b (the breakpoint)
780 was set. If it was set via line number, check if b.line is the same as
781 the one in the frame. If it was set via function name, check if this is
782 the right function and if it is on the first executable line.
783 """
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000784 if not b.funcname:
785 # Breakpoint was set via line number.
786 if b.line != frame.f_lineno:
787 # Breakpoint was set at a line with a def statement and the function
788 # defined is called: don't break.
789 return False
790 return True
791
792 # Breakpoint set via function name.
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000793 if frame.f_code.co_name != b.funcname:
794 # It's not a function call, but rather execution of def statement.
795 return False
796
797 # We are in the right frame.
798 if not b.func_first_executable_line:
799 # The function is entered for the 1st time.
800 b.func_first_executable_line = frame.f_lineno
801
csabella0774e792017-05-16 18:28:02 -0400802 if b.func_first_executable_line != frame.f_lineno:
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000803 # But we are not at the first line number: don't break.
804 return False
805 return True
806
csabella0774e792017-05-16 18:28:02 -0400807
Guido van Rossumd93643f1998-09-11 22:38:35 +0000808# Determines if there is an effective (active) breakpoint at this
809# line of code. Returns breakpoint number or 0 if none
810def effective(file, line, frame):
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000811 """Determine which breakpoint for this file:line is to be acted upon.
Guido van Rossumd93643f1998-09-11 22:38:35 +0000812
csabella0774e792017-05-16 18:28:02 -0400813 Called only if we know there is a breakpoint at this location. Return
814 the breakpoint that was triggered and a boolean that indicates if it is
815 ok to delete a temporary breakpoint. Return (None, None) if there is no
816 matching breakpoint.
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000817 """
Georg Brandl9aed6cc2010-11-26 12:05:27 +0000818 possibles = Breakpoint.bplist[file, line]
819 for b in possibles:
820 if not b.enabled:
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000821 continue
Johannes Gijsbers4a9faa12004-08-30 13:29:44 +0000822 if not checkfuncname(b, frame):
823 continue
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000824 # Count every hit when bp is enabled
Georg Brandl9aed6cc2010-11-26 12:05:27 +0000825 b.hits += 1
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000826 if not b.cond:
Georg Brandl9aed6cc2010-11-26 12:05:27 +0000827 # If unconditional, and ignoring go on to next, else break
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000828 if b.ignore > 0:
Georg Brandl9aed6cc2010-11-26 12:05:27 +0000829 b.ignore -= 1
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000830 continue
831 else:
Georg Brandl9aed6cc2010-11-26 12:05:27 +0000832 # breakpoint and marker that it's ok to delete if temporary
833 return (b, True)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000834 else:
835 # Conditional bp.
836 # Ignore count applies only to those bpt hits where the
837 # condition evaluates to true.
838 try:
Georg Brandl9aed6cc2010-11-26 12:05:27 +0000839 val = eval(b.cond, frame.f_globals, frame.f_locals)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000840 if val:
841 if b.ignore > 0:
Georg Brandl9aed6cc2010-11-26 12:05:27 +0000842 b.ignore -= 1
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000843 # continue
844 else:
Georg Brandl9aed6cc2010-11-26 12:05:27 +0000845 return (b, True)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000846 # else:
847 # continue
848 except:
Georg Brandl9aed6cc2010-11-26 12:05:27 +0000849 # if eval fails, most conservative thing is to stop on
850 # breakpoint regardless of ignore count. Don't delete
851 # temporary, as another hint to user.
852 return (b, False)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000853 return (None, None)
Guido van Rossumd93643f1998-09-11 22:38:35 +0000854
Georg Brandl26607472010-11-29 20:12:24 +0000855
Guido van Rossumbabe2bf1992-01-22 22:21:31 +0000856# -------------------- testing --------------------
857
858class Tdb(Bdb):
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000859 def user_call(self, frame, args):
860 name = frame.f_code.co_name
861 if not name: name = '???'
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000862 print('+++ call', name, args)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000863 def user_line(self, frame):
Eric S. Raymondb49f4a42001-02-09 05:07:04 +0000864 import linecache
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000865 name = frame.f_code.co_name
866 if not name: name = '???'
867 fn = self.canonic(frame.f_code.co_filename)
Nick Coghlanf088e5e2008-12-14 11:50:48 +0000868 line = linecache.getline(fn, frame.f_lineno, frame.f_globals)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000869 print('+++', fn, frame.f_lineno, name, ':', line.strip())
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000870 def user_return(self, frame, retval):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000871 print('+++ return', retval)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000872 def user_exception(self, frame, exc_stuff):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000873 print('+++ exception', exc_stuff)
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000874 self.set_continue()
Guido van Rossumbabe2bf1992-01-22 22:21:31 +0000875
876def foo(n):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000877 print('foo(', n, ')')
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000878 x = bar(n*10)
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000879 print('bar returned', x)
Guido van Rossumbabe2bf1992-01-22 22:21:31 +0000880
881def bar(a):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000882 print('bar(', a, ')')
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000883 return a/2
Guido van Rossumbabe2bf1992-01-22 22:21:31 +0000884
885def test():
Guido van Rossum4acc25b2000-02-02 15:10:15 +0000886 t = Tdb()
887 t.run('import bdb; bdb.foo(10)')