bdb.py 32 KB

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