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