bdb.py 32 KB

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