You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

243 lines
7.3 KiB

6 years ago
  1. """SCons.Debug
  2. Code for debugging SCons internal things. Shouldn't be
  3. needed by most users. Quick shortcuts:
  4. from SCons.Debug import caller_trace
  5. caller_trace()
  6. """
  7. #
  8. # Copyright (c) 2001 - 2017 The SCons Foundation
  9. #
  10. # Permission is hereby granted, free of charge, to any person obtaining
  11. # a copy of this software and associated documentation files (the
  12. # "Software"), to deal in the Software without restriction, including
  13. # without limitation the rights to use, copy, modify, merge, publish,
  14. # distribute, sublicense, and/or sell copies of the Software, and to
  15. # permit persons to whom the Software is furnished to do so, subject to
  16. # the following conditions:
  17. #
  18. # The above copyright notice and this permission notice shall be included
  19. # in all copies or substantial portions of the Software.
  20. #
  21. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
  22. # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  23. # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. #
  29. __revision__ = "src/engine/SCons/Debug.py rel_3.0.0:4395:8972f6a2f699 2017/09/18 12:59:24 bdbaddog"
  30. import os
  31. import sys
  32. import time
  33. import weakref
  34. import inspect
  35. # Global variable that gets set to 'True' by the Main script,
  36. # when the creation of class instances should get tracked.
  37. track_instances = False
  38. # List of currently tracked classes
  39. tracked_classes = {}
  40. def logInstanceCreation(instance, name=None):
  41. if name is None:
  42. name = instance.__class__.__name__
  43. if name not in tracked_classes:
  44. tracked_classes[name] = []
  45. if hasattr(instance, '__dict__'):
  46. tracked_classes[name].append(weakref.ref(instance))
  47. else:
  48. # weakref doesn't seem to work when the instance
  49. # contains only slots...
  50. tracked_classes[name].append(instance)
  51. def string_to_classes(s):
  52. if s == '*':
  53. return sorted(tracked_classes.keys())
  54. else:
  55. return s.split()
  56. def fetchLoggedInstances(classes="*"):
  57. classnames = string_to_classes(classes)
  58. return [(cn, len(tracked_classes[cn])) for cn in classnames]
  59. def countLoggedInstances(classes, file=sys.stdout):
  60. for classname in string_to_classes(classes):
  61. file.write("%s: %d\n" % (classname, len(tracked_classes[classname])))
  62. def listLoggedInstances(classes, file=sys.stdout):
  63. for classname in string_to_classes(classes):
  64. file.write('\n%s:\n' % classname)
  65. for ref in tracked_classes[classname]:
  66. if inspect.isclass(ref):
  67. obj = ref()
  68. else:
  69. obj = ref
  70. if obj is not None:
  71. file.write(' %s\n' % repr(obj))
  72. def dumpLoggedInstances(classes, file=sys.stdout):
  73. for classname in string_to_classes(classes):
  74. file.write('\n%s:\n' % classname)
  75. for ref in tracked_classes[classname]:
  76. obj = ref()
  77. if obj is not None:
  78. file.write(' %s:\n' % obj)
  79. for key, value in obj.__dict__.items():
  80. file.write(' %20s : %s\n' % (key, value))
  81. if sys.platform[:5] == "linux":
  82. # Linux doesn't actually support memory usage stats from getrusage().
  83. def memory():
  84. with open('/proc/self/stat') as f:
  85. mstr = f.read()
  86. mstr = mstr.split()[22]
  87. return int(mstr)
  88. elif sys.platform[:6] == 'darwin':
  89. #TODO really get memory stats for OS X
  90. def memory():
  91. return 0
  92. else:
  93. try:
  94. import resource
  95. except ImportError:
  96. try:
  97. import win32process
  98. import win32api
  99. except ImportError:
  100. def memory():
  101. return 0
  102. else:
  103. def memory():
  104. process_handle = win32api.GetCurrentProcess()
  105. memory_info = win32process.GetProcessMemoryInfo( process_handle )
  106. return memory_info['PeakWorkingSetSize']
  107. else:
  108. def memory():
  109. res = resource.getrusage(resource.RUSAGE_SELF)
  110. return res[4]
  111. # returns caller's stack
  112. def caller_stack():
  113. import traceback
  114. tb = traceback.extract_stack()
  115. # strip itself and the caller from the output
  116. tb = tb[:-2]
  117. result = []
  118. for back in tb:
  119. # (filename, line number, function name, text)
  120. key = back[:3]
  121. result.append('%s:%d(%s)' % func_shorten(key))
  122. return result
  123. caller_bases = {}
  124. caller_dicts = {}
  125. def caller_trace(back=0):
  126. """
  127. Trace caller stack and save info into global dicts, which
  128. are printed automatically at the end of SCons execution.
  129. """
  130. global caller_bases, caller_dicts
  131. import traceback
  132. tb = traceback.extract_stack(limit=3+back)
  133. tb.reverse()
  134. callee = tb[1][:3]
  135. caller_bases[callee] = caller_bases.get(callee, 0) + 1
  136. for caller in tb[2:]:
  137. caller = callee + caller[:3]
  138. try:
  139. entry = caller_dicts[callee]
  140. except KeyError:
  141. caller_dicts[callee] = entry = {}
  142. entry[caller] = entry.get(caller, 0) + 1
  143. callee = caller
  144. # print a single caller and its callers, if any
  145. def _dump_one_caller(key, file, level=0):
  146. leader = ' '*level
  147. for v,c in sorted([(-v,c) for c,v in caller_dicts[key].items()]):
  148. file.write("%s %6d %s:%d(%s)\n" % ((leader,-v) + func_shorten(c[-3:])))
  149. if c in caller_dicts:
  150. _dump_one_caller(c, file, level+1)
  151. # print each call tree
  152. def dump_caller_counts(file=sys.stdout):
  153. for k in sorted(caller_bases.keys()):
  154. file.write("Callers of %s:%d(%s), %d calls:\n"
  155. % (func_shorten(k) + (caller_bases[k],)))
  156. _dump_one_caller(k, file)
  157. shorten_list = [
  158. ( '/scons/SCons/', 1),
  159. ( '/src/engine/SCons/', 1),
  160. ( '/usr/lib/python', 0),
  161. ]
  162. if os.sep != '/':
  163. shorten_list = [(t[0].replace('/', os.sep), t[1]) for t in shorten_list]
  164. def func_shorten(func_tuple):
  165. f = func_tuple[0]
  166. for t in shorten_list:
  167. i = f.find(t[0])
  168. if i >= 0:
  169. if t[1]:
  170. i = i + len(t[0])
  171. return (f[i:],)+func_tuple[1:]
  172. return func_tuple
  173. TraceFP = {}
  174. if sys.platform == 'win32':
  175. TraceDefault = 'con'
  176. else:
  177. TraceDefault = '/dev/tty'
  178. TimeStampDefault = None
  179. StartTime = time.time()
  180. PreviousTime = StartTime
  181. def Trace(msg, file=None, mode='w', tstamp=None):
  182. """Write a trace message to a file. Whenever a file is specified,
  183. it becomes the default for the next call to Trace()."""
  184. global TraceDefault
  185. global TimeStampDefault
  186. global PreviousTime
  187. if file is None:
  188. file = TraceDefault
  189. else:
  190. TraceDefault = file
  191. if tstamp is None:
  192. tstamp = TimeStampDefault
  193. else:
  194. TimeStampDefault = tstamp
  195. try:
  196. fp = TraceFP[file]
  197. except KeyError:
  198. try:
  199. fp = TraceFP[file] = open(file, mode)
  200. except TypeError:
  201. # Assume we were passed an open file pointer.
  202. fp = file
  203. if tstamp:
  204. now = time.time()
  205. fp.write('%8.4f %8.4f: ' % (now - StartTime, now - PreviousTime))
  206. PreviousTime = now
  207. fp.write(msg)
  208. fp.flush()
  209. fp.close()
  210. # Local Variables:
  211. # tab-width:4
  212. # indent-tabs-mode:nil
  213. # End:
  214. # vim: set expandtab tabstop=4 shiftwidth=4: