bdb.py 32 KB

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