pytracer.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
  2. # For details: https://bitbucket.org/ned/coveragepy/src/default/NOTICE.txt
  3. """Raw data collector for coverage.py."""
  4. import atexit
  5. import dis
  6. import sys
  7. from coverage import env
  8. # We need the YIELD_VALUE opcode below, in a comparison-friendly form.
  9. YIELD_VALUE = dis.opmap['YIELD_VALUE']
  10. if env.PY2:
  11. YIELD_VALUE = chr(YIELD_VALUE)
  12. class PyTracer(object):
  13. """Python implementation of the raw data tracer."""
  14. # Because of poor implementations of trace-function-manipulating tools,
  15. # the Python trace function must be kept very simple. In particular, there
  16. # must be only one function ever set as the trace function, both through
  17. # sys.settrace, and as the return value from the trace function. Put
  18. # another way, the trace function must always return itself. It cannot
  19. # swap in other functions, or return None to avoid tracing a particular
  20. # frame.
  21. #
  22. # The trace manipulator that introduced this restriction is DecoratorTools,
  23. # which sets a trace function, and then later restores the pre-existing one
  24. # by calling sys.settrace with a function it found in the current frame.
  25. #
  26. # Systems that use DecoratorTools (or similar trace manipulations) must use
  27. # PyTracer to get accurate results. The command-line --timid argument is
  28. # used to force the use of this tracer.
  29. def __init__(self):
  30. # Attributes set from the collector:
  31. self.data = None
  32. self.trace_arcs = False
  33. self.should_trace = None
  34. self.should_trace_cache = None
  35. self.warn = None
  36. # The threading module to use, if any.
  37. self.threading = None
  38. self.cur_file_dict = []
  39. self.last_line = 0 # int, but uninitialized.
  40. self.data_stack = []
  41. self.last_exc_back = None
  42. self.last_exc_firstlineno = 0
  43. self.thread = None
  44. self.stopped = False
  45. self._activity = False
  46. self.in_atexit = False
  47. # On exit, self.in_atexit = True
  48. atexit.register(setattr, self, 'in_atexit', True)
  49. def __repr__(self):
  50. return "<PyTracer at {0}: {1} lines in {2} files>".format(
  51. id(self),
  52. sum(len(v) for v in self.data.values()),
  53. len(self.data),
  54. )
  55. def _trace(self, frame, event, arg_unused):
  56. """The trace function passed to sys.settrace."""
  57. if (self.stopped and sys.gettrace() == self._trace):
  58. # The PyTrace.stop() method has been called, possibly by another
  59. # thread, let's deactivate ourselves now.
  60. sys.settrace(None)
  61. return
  62. if self.last_exc_back:
  63. if frame == self.last_exc_back:
  64. # Someone forgot a return event.
  65. if self.trace_arcs and self.cur_file_dict:
  66. pair = (self.last_line, -self.last_exc_firstlineno)
  67. self.cur_file_dict[pair] = None
  68. self.cur_file_dict, self.last_line = self.data_stack.pop()
  69. self.last_exc_back = None
  70. if event == 'call':
  71. # Entering a new function context. Decide if we should trace
  72. # in this file.
  73. self._activity = True
  74. self.data_stack.append((self.cur_file_dict, self.last_line))
  75. filename = frame.f_code.co_filename
  76. disp = self.should_trace_cache.get(filename)
  77. if disp is None:
  78. disp = self.should_trace(filename, frame)
  79. self.should_trace_cache[filename] = disp
  80. self.cur_file_dict = None
  81. if disp.trace:
  82. tracename = disp.source_filename
  83. if tracename not in self.data:
  84. self.data[tracename] = {}
  85. self.cur_file_dict = self.data[tracename]
  86. # The call event is really a "start frame" event, and happens for
  87. # function calls and re-entering generators. The f_lasti field is
  88. # -1 for calls, and a real offset for generators. Use <0 as the
  89. # line number for calls, and the real line number for generators.
  90. if getattr(frame, 'f_lasti', -1) < 0:
  91. self.last_line = -frame.f_code.co_firstlineno
  92. else:
  93. self.last_line = frame.f_lineno
  94. elif event == 'line':
  95. # Record an executed line.
  96. if self.cur_file_dict is not None:
  97. lineno = frame.f_lineno
  98. if self.trace_arcs:
  99. self.cur_file_dict[(self.last_line, lineno)] = None
  100. else:
  101. self.cur_file_dict[lineno] = None
  102. self.last_line = lineno
  103. elif event == 'return':
  104. if self.trace_arcs and self.cur_file_dict:
  105. # Record an arc leaving the function, but beware that a
  106. # "return" event might just mean yielding from a generator.
  107. # Jython seems to have an empty co_code, so just assume return.
  108. code = frame.f_code.co_code
  109. if (not code) or code[frame.f_lasti] != YIELD_VALUE:
  110. first = frame.f_code.co_firstlineno
  111. self.cur_file_dict[(self.last_line, -first)] = None
  112. # Leaving this function, pop the filename stack.
  113. self.cur_file_dict, self.last_line = self.data_stack.pop()
  114. elif event == 'exception':
  115. self.last_exc_back = frame.f_back
  116. self.last_exc_firstlineno = frame.f_code.co_firstlineno
  117. return self._trace
  118. def start(self):
  119. """Start this Tracer.
  120. Return a Python function suitable for use with sys.settrace().
  121. """
  122. self.stopped = False
  123. if self.threading:
  124. if self.thread is None:
  125. self.thread = self.threading.currentThread()
  126. else:
  127. if self.thread.ident != self.threading.currentThread().ident:
  128. # Re-starting from a different thread!? Don't set the trace
  129. # function, but we are marked as running again, so maybe it
  130. # will be ok?
  131. return self._trace
  132. sys.settrace(self._trace)
  133. return self._trace
  134. def stop(self):
  135. """Stop this Tracer."""
  136. # Get the activate tracer callback before setting the stop flag to be
  137. # able to detect if the tracer was changed prior to stopping it.
  138. tf = sys.gettrace()
  139. # Set the stop flag. The actual call to sys.settrace(None) will happen
  140. # in the self._trace callback itself to make sure to call it from the
  141. # right thread.
  142. self.stopped = True
  143. if self.threading and self.thread.ident != self.threading.currentThread().ident:
  144. # Called on a different thread than started us: we can't unhook
  145. # ourselves, but we've set the flag that we should stop, so we
  146. # won't do any more tracing.
  147. return
  148. if self.warn:
  149. # PyPy clears the trace function before running atexit functions,
  150. # so don't warn if we are in atexit on PyPy and the trace function
  151. # has changed to None.
  152. dont_warn = (env.PYPY and env.PYPYVERSION >= (5, 4) and self.in_atexit and tf is None)
  153. if (not dont_warn) and tf != self._trace:
  154. self.warn(
  155. "Trace function changed, measurement is likely wrong: %r" % (tf,),
  156. slug="trace-changed",
  157. )
  158. def activity(self):
  159. """Has there been any activity?"""
  160. return self._activity
  161. def reset_activity(self):
  162. """Reset the activity() flag."""
  163. self._activity = False
  164. def get_stats(self):
  165. """Return a dictionary of statistics, or None."""
  166. return None