bdb.py 31 KB

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