Package SCons :: Module Debug
[hide private]
[frames] | no frames]

Source Code for Module SCons.Debug

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