bdb.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874
  1. """Debugger basics"""
  2. import fnmatch
  3. import sys
  4. import os
  5. from inspect import CO_GENERATOR, CO_COROUTINE, CO_ASYNC_GENERATOR
  6. __all__ = ["BdbQuit", "Bdb", "Breakpoint"]
  7. GENERATOR_AND_COROUTINE_FLAGS = CO_GENERATOR | CO_COROUTINE | CO_ASYNC_GENERATOR
  8. class BdbQuit(Exception):
  9. """Exception to give up completely."""
  10. class Bdb:
  11. """Generic Python debugger base class.
  12. This class takes care of details of the trace facility;
  13. a derived class should implement user interaction.
  14. The standard debugger class (pdb.Pdb) is an example.
  15. The optional skip argument must be an iterable of glob-style
  16. module name patterns. The debugger will not step into frames
  17. that originate in a module that matches one of these patterns.
  18. Whether a frame is considered to originate in a certain module
  19. is determined by the __name__ in the frame globals.
  20. """
  21. def __init__(self, skip=None):
  22. self.skip = set(skip) if skip else None
  23. self.breaks = {}
  24. self.fncache = {}
  25. self.frame_returning = None
  26. def canonic(self, filename):
  27. """Return canonical form of filename.
  28. For real filenames, the canonical form is a case-normalized (on
  29. case insenstive filesystems) absolute path. 'Filenames' with
  30. angle brackets, such as "<stdin>", generated in interactive
  31. mode, are returned unchanged.
  32. """
  33. if filename == "<" + filename[1:-1] + ">":
  34. return filename
  35. canonic = self.fncache.get(filename)
  36. if not canonic:
  37. canonic = os.path.abspath(filename)
  38. canonic = os.path.normcase(canonic)
  39. self.fncache[filename] = canonic
  40. return canonic
  41. def reset(self):
  42. """Set values of attributes as ready to start debugging."""
  43. import linecache
  44. linecache.checkcache()
  45. self.botframe = None
  46. self._set_stopinfo(None, None)
  47. def trace_dispatch(self, frame, event, arg):
  48. """Dispatch a trace function for debugged frames based on the event.
  49. This function is installed as the trace function for debugged
  50. frames. Its return value is the new trace function, which is
  51. usually itself. The default implementation decides how to
  52. dispatch a frame, depending on the type of event (passed in as a
  53. string) that is about to be executed.
  54. The event can be one of the following:
  55. line: A new line of code is going to be executed.
  56. call: A function is about to be called or another code block
  57. is entered.
  58. return: A function or other code block is about to return.
  59. exception: An exception has occurred.
  60. c_call: A C function is about to be called.
  61. c_return: A C function has returned.
  62. c_exception: A C function has raised an exception.
  63. For the Python events, specialized functions (see the dispatch_*()
  64. methods) are called. For the C events, no action is taken.
  65. The arg parameter depends on the previous event.
  66. """
  67. if self.quitting:
  68. return # None
  69. if event == 'line':
  70. return self.dispatch_line(frame)
  71. if event == 'call':
  72. return self.dispatch_call(frame, arg)
  73. if event == 'return':
  74. return self.dispatch_return(frame, arg)
  75. if event == 'exception':
  76. return self.dispatch_exception(frame, arg)
  77. if event == 'c_call':
  78. return self.trace_dispatch
  79. if event == 'c_exception':
  80. return self.trace_dispatch
  81. if event == 'c_return':
  82. return self.trace_dispatch
  83. print('bdb.Bdb.dispatch: unknown debugging event:', repr(event))
  84. return self.trace_dispatch
  85. def dispatch_line(self, frame):
  86. """Invoke user function and return trace function for line event.
  87. If the debugger stops on the current line, invoke
  88. self.user_line(). Raise BdbQuit if self.quitting is set.
  89. Return self.trace_dispatch to continue tracing in this scope.
  90. """
  91. if self.stop_here(frame) or self.break_here(frame):
  92. self.user_line(frame)
  93. if self.quitting: raise BdbQuit
  94. return self.trace_dispatch
  95. def dispatch_call(self, frame, arg):
  96. """Invoke user function and return trace function for call event.
  97. If the debugger stops on this function call, invoke
  98. self.user_call(). Raise BbdQuit if self.quitting is set.
  99. Return self.trace_dispatch to continue tracing in this scope.
  100. """
  101. # XXX 'arg' is no longer used
  102. if self.botframe is None:
  103. # First call of dispatch since reset()
  104. self.botframe = frame.f_back # (CT) Note that this may also be None!
  105. return self.trace_dispatch
  106. if not (self.stop_here(frame) or self.break_anywhere(frame)):
  107. # No need to trace this function
  108. return # None
  109. # Ignore call events in generator except when stepping.
  110. if self.stopframe and frame.f_code.co_flags & GENERATOR_AND_COROUTINE_FLAGS:
  111. return self.trace_dispatch
  112. self.user_call(frame, arg)
  113. if self.quitting: raise BdbQuit
  114. return self.trace_dispatch
  115. def dispatch_return(self, frame, arg):
  116. """Invoke user function and return trace function for return event.
  117. If the debugger stops on this function return, invoke
  118. self.user_return(). Raise BdbQuit if self.quitting is set.
  119. Return self.trace_dispatch to continue tracing in this scope.
  120. """
  121. if self.stop_here(frame) or frame == self.returnframe:
  122. # Ignore return events in generator except when stepping.
  123. if self.stopframe and frame.f_code.co_flags & GENERATOR_AND_COROUTINE_FLAGS:
  124. return self.trace_dispatch
  125. try:
  126. self.frame_returning = frame
  127. self.user_return(frame, arg)
  128. finally:
  129. self.frame_returning = None
  130. if self.quitting: raise BdbQuit
  131. # The user issued a 'next' or 'until' command.
  132. if self.stopframe is frame and self.stoplineno != -1:
  133. self._set_stopinfo(None, None)
  134. return self.trace_dispatch
  135. def dispatch_exception(self, frame, arg):
  136. """Invoke user function and return trace function for exception event.
  137. If the debugger stops on this exception, invoke
  138. self.user_exception(). Raise BdbQuit if self.quitting is set.
  139. Return self.trace_dispatch to continue tracing in this scope.
  140. """
  141. if self.stop_here(frame):
  142. # When stepping with next/until/return in a generator frame, skip
  143. # the internal StopIteration exception (with no traceback)
  144. # triggered by a subiterator run with the 'yield from' statement.
  145. if not (frame.f_code.co_flags & GENERATOR_AND_COROUTINE_FLAGS
  146. and arg[0] is StopIteration and arg[2] is None):
  147. self.user_exception(frame, arg)
  148. if self.quitting: raise BdbQuit
  149. # Stop at the StopIteration or GeneratorExit exception when the user
  150. # has set stopframe in a generator by issuing a return command, or a
  151. # next/until command at the last statement in the generator before the
  152. # exception.
  153. elif (self.stopframe and frame is not self.stopframe
  154. and self.stopframe.f_code.co_flags & GENERATOR_AND_COROUTINE_FLAGS
  155. and arg[0] in (StopIteration, GeneratorExit)):
  156. self.user_exception(frame, arg)
  157. if self.quitting: raise BdbQuit
  158. return self.trace_dispatch
  159. # Normally derived classes don't override the following
  160. # methods, but they may if they want to redefine the
  161. # definition of stopping and breakpoints.
  162. def is_skipped_module(self, module_name):
  163. "Return True if module_name matches any skip pattern."
  164. for pattern in self.skip:
  165. if fnmatch.fnmatch(module_name, pattern):
  166. return True
  167. return False
  168. def stop_here(self, frame):
  169. "Return True if frame is below the starting frame in the stack."
  170. # (CT) stopframe may now also be None, see dispatch_call.
  171. # (CT) the former test for None is therefore removed from here.
  172. if self.skip and \
  173. self.is_skipped_module(frame.f_globals.get('__name__')):
  174. return False
  175. if frame is self.stopframe:
  176. if self.stoplineno == -1:
  177. return False
  178. return frame.f_lineno >= self.stoplineno
  179. if not self.stopframe:
  180. return True
  181. return False
  182. def break_here(self, frame):
  183. """Return True if there is an effective breakpoint for this line.
  184. Check for line or function breakpoint and if in effect.
  185. Delete temporary breakpoints if effective() says to.
  186. """
  187. filename = self.canonic(frame.f_code.co_filename)
  188. if filename not in self.breaks:
  189. return False
  190. lineno = frame.f_lineno
  191. if lineno not in self.breaks[filename]:
  192. # The line itself has no breakpoint, but maybe the line is the
  193. # first line of a function with breakpoint set by function name.
  194. lineno = frame.f_code.co_firstlineno
  195. if lineno not in self.breaks[filename]:
  196. return False
  197. # flag says ok to delete temp. bp
  198. (bp, flag) = effective(filename, lineno, frame)
  199. if bp:
  200. self.currentbp = bp.number
  201. if (flag and bp.temporary):
  202. self.do_clear(str(bp.number))
  203. return True
  204. else:
  205. return False
  206. def do_clear(self, arg):
  207. """Remove temporary breakpoint.
  208. Must implement in derived classes or get NotImplementedError.
  209. """
  210. raise NotImplementedError("subclass of bdb must implement do_clear()")
  211. def break_anywhere(self, frame):
  212. """Return True if there is any breakpoint for frame's filename.
  213. """
  214. return self.canonic(frame.f_code.co_filename) in self.breaks
  215. # Derived classes should override the user_* methods
  216. # to gain control.
  217. def user_call(self, frame, argument_list):
  218. """Called if we might stop in a function."""
  219. pass
  220. def user_line(self, frame):
  221. """Called when we stop or break at a line."""
  222. pass
  223. def user_return(self, frame, return_value):
  224. """Called when a return trap is set here."""
  225. pass
  226. def user_exception(self, frame, exc_info):
  227. """Called when we stop on an exception."""
  228. pass
  229. def _set_stopinfo(self, stopframe, returnframe, stoplineno=0):
  230. """Set the attributes for stopping.
  231. If stoplineno is greater than or equal to 0, then stop at line
  232. greater than or equal to the stopline. If stoplineno is -1, then
  233. don't stop at all.
  234. """
  235. self.stopframe = stopframe
  236. self.returnframe = returnframe
  237. self.quitting = False
  238. # stoplineno >= 0 means: stop at line >= the stoplineno
  239. # stoplineno -1 means: don't stop at all
  240. self.stoplineno = stoplineno
  241. # Derived classes and clients can call the following methods
  242. # to affect the stepping state.
  243. def set_until(self, frame, lineno=None):
  244. """Stop when the line with the lineno greater than the current one is
  245. reached or when returning from current frame."""
  246. # the name "until" is borrowed from gdb
  247. if lineno is None:
  248. lineno = frame.f_lineno + 1
  249. self._set_stopinfo(frame, frame, lineno)
  250. def set_step(self):
  251. """Stop after one line of code."""
  252. # Issue #13183: pdb skips frames after hitting a breakpoint and running
  253. # step commands.
  254. # Restore the trace function in the caller (that may not have been set
  255. # for performance reasons) when returning from the current frame.
  256. if self.frame_returning:
  257. caller_frame = self.frame_returning.f_back
  258. if caller_frame and not caller_frame.f_trace:
  259. caller_frame.f_trace = self.trace_dispatch
  260. self._set_stopinfo(None, None)
  261. def set_next(self, frame):
  262. """Stop on the next line in or below the given frame."""
  263. self._set_stopinfo(frame, None)
  264. def set_return(self, frame):
  265. """Stop when returning from the given frame."""
  266. if frame.f_code.co_flags & GENERATOR_AND_COROUTINE_FLAGS:
  267. self._set_stopinfo(frame, None, -1)
  268. else:
  269. self._set_stopinfo(frame.f_back, frame)
  270. def set_trace(self, frame=None):
  271. """Start debugging from frame.
  272. If frame is not specified, debugging starts from caller's frame.
  273. """
  274. if frame is None:
  275. frame = sys._getframe().f_back
  276. self.reset()
  277. while frame:
  278. frame.f_trace = self.trace_dispatch
  279. self.botframe = frame
  280. frame = frame.f_back
  281. self.set_step()
  282. sys.settrace(self.trace_dispatch)
  283. def set_continue(self):
  284. """Stop only at breakpoints or when finished.
  285. If there are no breakpoints, set the system trace function to None.
  286. """
  287. # Don't stop except at breakpoints or when finished
  288. self._set_stopinfo(self.botframe, None, -1)
  289. if not self.breaks:
  290. # no breakpoints; run without debugger overhead
  291. sys.settrace(None)
  292. frame = sys._getframe().f_back
  293. while frame and frame is not self.botframe:
  294. del frame.f_trace
  295. frame = frame.f_back
  296. def set_quit(self):
  297. """Set quitting attribute to True.
  298. Raises BdbQuit exception in the next call to a dispatch_*() method.
  299. """
  300. self.stopframe = self.botframe
  301. self.returnframe = None
  302. self.quitting = True
  303. sys.settrace(None)
  304. # Derived classes and clients can call the following methods
  305. # to manipulate breakpoints. These methods return an
  306. # error message if something went wrong, None if all is well.
  307. # Set_break prints out the breakpoint line and file:lineno.
  308. # Call self.get_*break*() to see the breakpoints or better
  309. # for bp in Breakpoint.bpbynumber: if bp: bp.bpprint().
  310. def set_break(self, filename, lineno, temporary=False, cond=None,
  311. funcname=None):
  312. """Set a new breakpoint for filename:lineno.
  313. If lineno doesn't exist for the filename, return an error message.
  314. The filename should be in canonical form.
  315. """
  316. filename = self.canonic(filename)
  317. import linecache # Import as late as possible
  318. line = linecache.getline(filename, lineno)
  319. if not line:
  320. return 'Line %s:%d does not exist' % (filename, lineno)
  321. list = self.breaks.setdefault(filename, [])
  322. if lineno not in list:
  323. list.append(lineno)
  324. bp = Breakpoint(filename, lineno, temporary, cond, funcname)
  325. return None
  326. def _prune_breaks(self, filename, lineno):
  327. """Prune breakpoints for filname:lineno.
  328. A list of breakpoints is maintained in the Bdb instance and in
  329. the Breakpoint class. If a breakpoint in the Bdb instance no
  330. longer exists in the Breakpoint class, then it's removed from the
  331. Bdb instance.
  332. """
  333. if (filename, lineno) not in Breakpoint.bplist:
  334. self.breaks[filename].remove(lineno)
  335. if not self.breaks[filename]:
  336. del self.breaks[filename]
  337. def clear_break(self, filename, lineno):
  338. """Delete breakpoints for filename:lineno.
  339. If no breakpoints were set, return an error message.
  340. """
  341. filename = self.canonic(filename)
  342. if filename not in self.breaks:
  343. return 'There are no breakpoints in %s' % filename
  344. if lineno not in self.breaks[filename]:
  345. return 'There is no breakpoint at %s:%d' % (filename, lineno)
  346. # If there's only one bp in the list for that file,line
  347. # pair, then remove the breaks entry
  348. for bp in Breakpoint.bplist[filename, lineno][:]:
  349. bp.deleteMe()
  350. self._prune_breaks(filename, lineno)
  351. return None
  352. def clear_bpbynumber(self, arg):
  353. """Delete a breakpoint by its index in Breakpoint.bpbynumber.
  354. If arg is invalid, return an error message.
  355. """
  356. try:
  357. bp = self.get_bpbynumber(arg)
  358. except ValueError as err:
  359. return str(err)
  360. bp.deleteMe()
  361. self._prune_breaks(bp.file, bp.line)
  362. return None
  363. def clear_all_file_breaks(self, filename):
  364. """Delete all breakpoints in filename.
  365. If none were set, return an error message.
  366. """
  367. filename = self.canonic(filename)
  368. if filename not in self.breaks:
  369. return 'There are no breakpoints in %s' % filename
  370. for line in self.breaks[filename]:
  371. blist = Breakpoint.bplist[filename, line]
  372. for bp in blist:
  373. bp.deleteMe()
  374. del self.breaks[filename]
  375. return None
  376. def clear_all_breaks(self):
  377. """Delete all existing breakpoints.
  378. If none were set, return an error message.
  379. """
  380. if not self.breaks:
  381. return 'There are no breakpoints'
  382. for bp in Breakpoint.bpbynumber:
  383. if bp:
  384. bp.deleteMe()
  385. self.breaks = {}
  386. return None
  387. def get_bpbynumber(self, arg):
  388. """Return a breakpoint by its index in Breakpoint.bybpnumber.
  389. For invalid arg values or if the breakpoint doesn't exist,
  390. raise a ValueError.
  391. """
  392. if not arg:
  393. raise ValueError('Breakpoint number expected')
  394. try:
  395. number = int(arg)
  396. except ValueError:
  397. raise ValueError('Non-numeric breakpoint number %s' % arg) from None
  398. try:
  399. bp = Breakpoint.bpbynumber[number]
  400. except IndexError:
  401. raise ValueError('Breakpoint number %d out of range' % number) from None
  402. if bp is None:
  403. raise ValueError('Breakpoint %d already deleted' % number)
  404. return bp
  405. def get_break(self, filename, lineno):
  406. """Return True if there is a breakpoint for filename:lineno."""
  407. filename = self.canonic(filename)
  408. return filename in self.breaks and \
  409. lineno in self.breaks[filename]
  410. def get_breaks(self, filename, lineno):
  411. """Return all breakpoints for filename:lineno.
  412. If no breakpoints are set, return an empty list.
  413. """
  414. filename = self.canonic(filename)
  415. return filename in self.breaks and \
  416. lineno in self.breaks[filename] and \
  417. Breakpoint.bplist[filename, lineno] or []
  418. def get_file_breaks(self, filename):
  419. """Return all lines with breakpoints for filename.
  420. If no breakpoints are set, return an empty list.
  421. """
  422. filename = self.canonic(filename)
  423. if filename in self.breaks:
  424. return self.breaks[filename]
  425. else:
  426. return []
  427. def get_all_breaks(self):
  428. """Return all breakpoints that are set."""
  429. return self.breaks
  430. # Derived classes and clients can call the following method
  431. # to get a data structure representing a stack trace.
  432. def get_stack(self, f, t):
  433. """Return a list of (frame, lineno) in a stack trace and a size.
  434. List starts with original calling frame, if there is one.
  435. Size may be number of frames above or below f.
  436. """
  437. stack = []
  438. if t and t.tb_frame is f:
  439. t = t.tb_next
  440. while f is not None:
  441. stack.append((f, f.f_lineno))
  442. if f is self.botframe:
  443. break
  444. f = f.f_back
  445. stack.reverse()
  446. i = max(0, len(stack) - 1)
  447. while t is not None:
  448. stack.append((t.tb_frame, t.tb_lineno))
  449. t = t.tb_next
  450. if f is None:
  451. i = max(0, len(stack) - 1)
  452. return stack, i
  453. def format_stack_entry(self, frame_lineno, lprefix=': '):
  454. """Return a string with information about a stack entry.
  455. The stack entry frame_lineno is a (frame, lineno) tuple. The
  456. return string contains the canonical filename, the function name
  457. or '<lambda>', the input arguments, the return value, and the
  458. line of code (if it exists).
  459. """
  460. import linecache, reprlib
  461. frame, lineno = frame_lineno
  462. filename = self.canonic(frame.f_code.co_filename)
  463. s = '%s(%r)' % (filename, lineno)
  464. if frame.f_code.co_name:
  465. s += frame.f_code.co_name
  466. else:
  467. s += "<lambda>"
  468. s += '()'
  469. if '__return__' in frame.f_locals:
  470. rv = frame.f_locals['__return__']
  471. s += '->'
  472. s += reprlib.repr(rv)
  473. line = linecache.getline(filename, lineno, frame.f_globals)
  474. if line:
  475. s += lprefix + line.strip()
  476. return s
  477. # The following methods can be called by clients to use
  478. # a debugger to debug a statement or an expression.
  479. # Both can be given as a string, or a code object.
  480. def run(self, cmd, globals=None, locals=None):
  481. """Debug a statement executed via the exec() function.
  482. globals defaults to __main__.dict; locals defaults to globals.
  483. """
  484. if globals is None:
  485. import __main__
  486. globals = __main__.__dict__
  487. if locals is None:
  488. locals = globals
  489. self.reset()
  490. if isinstance(cmd, str):
  491. cmd = compile(cmd, "<string>", "exec")
  492. sys.settrace(self.trace_dispatch)
  493. try:
  494. exec(cmd, globals, locals)
  495. except BdbQuit:
  496. pass
  497. finally:
  498. self.quitting = True
  499. sys.settrace(None)
  500. def runeval(self, expr, globals=None, locals=None):
  501. """Debug an expression executed via the eval() function.
  502. globals defaults to __main__.dict; locals defaults to globals.
  503. """
  504. if globals is None:
  505. import __main__
  506. globals = __main__.__dict__
  507. if locals is None:
  508. locals = globals
  509. self.reset()
  510. sys.settrace(self.trace_dispatch)
  511. try:
  512. return eval(expr, globals, locals)
  513. except BdbQuit:
  514. pass
  515. finally:
  516. self.quitting = True
  517. sys.settrace(None)
  518. def runctx(self, cmd, globals, locals):
  519. """For backwards-compatibility. Defers to run()."""
  520. # B/W compatibility
  521. self.run(cmd, globals, locals)
  522. # This method is more useful to debug a single function call.
  523. def runcall(*args, **kwds):
  524. """Debug a single function call.
  525. Return the result of the function call.
  526. """
  527. if len(args) >= 2:
  528. self, func, *args = args
  529. elif not args:
  530. raise TypeError("descriptor 'runcall' of 'Bdb' object "
  531. "needs an argument")
  532. elif 'func' in kwds:
  533. func = kwds.pop('func')
  534. self, *args = args
  535. else:
  536. raise TypeError('runcall expected at least 1 positional argument, '
  537. 'got %d' % (len(args)-1))
  538. self.reset()
  539. sys.settrace(self.trace_dispatch)
  540. res = None
  541. try:
  542. res = func(*args, **kwds)
  543. except BdbQuit:
  544. pass
  545. finally:
  546. self.quitting = True
  547. sys.settrace(None)
  548. return res
  549. def set_trace():
  550. """Start debugging with a Bdb instance from the caller's frame."""
  551. Bdb().set_trace()
  552. class Breakpoint:
  553. """Breakpoint class.
  554. Implements temporary breakpoints, ignore counts, disabling and
  555. (re)-enabling, and conditionals.
  556. Breakpoints are indexed by number through bpbynumber and by
  557. the (file, line) tuple using bplist. The former points to a
  558. single instance of class Breakpoint. The latter points to a
  559. list of such instances since there may be more than one
  560. breakpoint per line.
  561. When creating a breakpoint, its associated filename should be
  562. in canonical form. If funcname is defined, a breakpoint hit will be
  563. counted when the first line of that function is executed. A
  564. conditional breakpoint always counts a hit.
  565. """
  566. # XXX Keeping state in the class is a mistake -- this means
  567. # you cannot have more than one active Bdb instance.
  568. next = 1 # Next bp to be assigned
  569. bplist = {} # indexed by (file, lineno) tuple
  570. bpbynumber = [None] # Each entry is None or an instance of Bpt
  571. # index 0 is unused, except for marking an
  572. # effective break .... see effective()
  573. def __init__(self, file, line, temporary=False, cond=None, funcname=None):
  574. self.funcname = funcname
  575. # Needed if funcname is not None.
  576. self.func_first_executable_line = None
  577. self.file = file # This better be in canonical form!
  578. self.line = line
  579. self.temporary = temporary
  580. self.cond = cond
  581. self.enabled = True
  582. self.ignore = 0
  583. self.hits = 0
  584. self.number = Breakpoint.next
  585. Breakpoint.next += 1
  586. # Build the two lists
  587. self.bpbynumber.append(self)
  588. if (file, line) in self.bplist:
  589. self.bplist[file, line].append(self)
  590. else:
  591. self.bplist[file, line] = [self]
  592. def deleteMe(self):
  593. """Delete the breakpoint from the list associated to a file:line.
  594. If it is the last breakpoint in that position, it also deletes
  595. the entry for the file:line.
  596. """
  597. index = (self.file, self.line)
  598. self.bpbynumber[self.number] = None # No longer in list
  599. self.bplist[index].remove(self)
  600. if not self.bplist[index]:
  601. # No more bp for this f:l combo
  602. del self.bplist[index]
  603. def enable(self):
  604. """Mark the breakpoint as enabled."""
  605. self.enabled = True
  606. def disable(self):
  607. """Mark the breakpoint as disabled."""
  608. self.enabled = False
  609. def bpprint(self, out=None):
  610. """Print the output of bpformat().
  611. The optional out argument directs where the output is sent
  612. and defaults to standard output.
  613. """
  614. if out is None:
  615. out = sys.stdout
  616. print(self.bpformat(), file=out)
  617. def bpformat(self):
  618. """Return a string with information about the breakpoint.
  619. The information includes the breakpoint number, temporary
  620. status, file:line position, break condition, number of times to
  621. ignore, and number of times hit.
  622. """
  623. if self.temporary:
  624. disp = 'del '
  625. else:
  626. disp = 'keep '
  627. if self.enabled:
  628. disp = disp + 'yes '
  629. else:
  630. disp = disp + 'no '
  631. ret = '%-4dbreakpoint %s at %s:%d' % (self.number, disp,
  632. self.file, self.line)
  633. if self.cond:
  634. ret += '\n\tstop only if %s' % (self.cond,)
  635. if self.ignore:
  636. ret += '\n\tignore next %d hits' % (self.ignore,)
  637. if self.hits:
  638. if self.hits > 1:
  639. ss = 's'
  640. else:
  641. ss = ''
  642. ret += '\n\tbreakpoint already hit %d time%s' % (self.hits, ss)
  643. return ret
  644. def __str__(self):
  645. "Return a condensed description of the breakpoint."
  646. return 'breakpoint %s at %s:%s' % (self.number, self.file, self.line)
  647. # -----------end of Breakpoint class----------
  648. def checkfuncname(b, frame):
  649. """Return True if break should happen here.
  650. Whether a break should happen depends on the way that b (the breakpoint)
  651. was set. If it was set via line number, check if b.line is the same as
  652. the one in the frame. If it was set via function name, check if this is
  653. the right function and if it is on the first executable line.
  654. """
  655. if not b.funcname:
  656. # Breakpoint was set via line number.
  657. if b.line != frame.f_lineno:
  658. # Breakpoint was set at a line with a def statement and the function
  659. # defined is called: don't break.
  660. return False
  661. return True
  662. # Breakpoint set via function name.
  663. if frame.f_code.co_name != b.funcname:
  664. # It's not a function call, but rather execution of def statement.
  665. return False
  666. # We are in the right frame.
  667. if not b.func_first_executable_line:
  668. # The function is entered for the 1st time.
  669. b.func_first_executable_line = frame.f_lineno
  670. if b.func_first_executable_line != frame.f_lineno:
  671. # But we are not at the first line number: don't break.
  672. return False
  673. return True
  674. # Determines if there is an effective (active) breakpoint at this
  675. # line of code. Returns breakpoint number or 0 if none
  676. def effective(file, line, frame):
  677. """Determine which breakpoint for this file:line is to be acted upon.
  678. Called only if we know there is a breakpoint at this location. Return
  679. the breakpoint that was triggered and a boolean that indicates if it is
  680. ok to delete a temporary breakpoint. Return (None, None) if there is no
  681. matching breakpoint.
  682. """
  683. possibles = Breakpoint.bplist[file, line]
  684. for b in possibles:
  685. if not b.enabled:
  686. continue
  687. if not checkfuncname(b, frame):
  688. continue
  689. # Count every hit when bp is enabled
  690. b.hits += 1
  691. if not b.cond:
  692. # If unconditional, and ignoring go on to next, else break
  693. if b.ignore > 0:
  694. b.ignore -= 1
  695. continue
  696. else:
  697. # breakpoint and marker that it's ok to delete if temporary
  698. return (b, True)
  699. else:
  700. # Conditional bp.
  701. # Ignore count applies only to those bpt hits where the
  702. # condition evaluates to true.
  703. try:
  704. val = eval(b.cond, frame.f_globals, frame.f_locals)
  705. if val:
  706. if b.ignore > 0:
  707. b.ignore -= 1
  708. # continue
  709. else:
  710. return (b, True)
  711. # else:
  712. # continue
  713. except:
  714. # if eval fails, most conservative thing is to stop on
  715. # breakpoint regardless of ignore count. Don't delete
  716. # temporary, as another hint to user.
  717. return (b, False)
  718. return (None, None)
  719. # -------------------- testing --------------------
  720. class Tdb(Bdb):
  721. def user_call(self, frame, args):
  722. name = frame.f_code.co_name
  723. if not name: name = '???'
  724. print('+++ call', name, args)
  725. def user_line(self, frame):
  726. import linecache
  727. name = frame.f_code.co_name
  728. if not name: name = '???'
  729. fn = self.canonic(frame.f_code.co_filename)
  730. line = linecache.getline(fn, frame.f_lineno, frame.f_globals)
  731. print('+++', fn, frame.f_lineno, name, ':', line.strip())
  732. def user_return(self, frame, retval):
  733. print('+++ return', retval)
  734. def user_exception(self, frame, exc_stuff):
  735. print('+++ exception', exc_stuff)
  736. self.set_continue()
  737. def foo(n):
  738. print('foo(', n, ')')
  739. x = bar(n*10)
  740. print('bar returned', x)
  741. def bar(a):
  742. print('bar(', a, ')')
  743. return a/2
  744. def test():
  745. t = Tdb()
  746. t.run('import bdb; bdb.foo(10)')