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 - 2014 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  2014/09/27 12:51:43 garyo" 
 32   
 33  import os 
 34  import sys 
 35  import time 
 36  import weakref 
 37   
 38  # Global variable that gets set to 'True' by the Main script, 
 39  # when the creation of class instances should get tracked. 
 40  track_instances = False 
 41  # List of currently tracked classes 
 42  tracked_classes = {} 
 43   
44 -def logInstanceCreation(instance, name=None):
45 if name is None: 46 name = instance.__class__.__name__ 47 if name not in tracked_classes: 48 tracked_classes[name] = [] 49 tracked_classes[name].append(weakref.ref(instance))
50
51 -def string_to_classes(s):
52 if s == '*': 53 return sorted(tracked_classes.keys()) 54 else: 55 return s.split()
56
57 -def fetchLoggedInstances(classes="*"):
58 classnames = string_to_classes(classes) 59 return [(cn, len(tracked_classes[cn])) for cn in classnames]
60
61 -def countLoggedInstances(classes, file=sys.stdout):
62 for classname in string_to_classes(classes): 63 file.write("%s: %d\n" % (classname, len(tracked_classes[classname])))
64
65 -def listLoggedInstances(classes, file=sys.stdout):
66 for classname in string_to_classes(classes): 67 file.write('\n%s:\n' % classname) 68 for ref in tracked_classes[classname]: 69 obj = ref() 70 if obj is not None: 71 file.write(' %s\n' % repr(obj))
72
73 -def dumpLoggedInstances(classes, file=sys.stdout):
74 for classname in string_to_classes(classes): 75 file.write('\n%s:\n' % classname) 76 for ref in tracked_classes[classname]: 77 obj = ref() 78 if obj is not None: 79 file.write(' %s:\n' % obj) 80 for key, value in obj.__dict__.items(): 81 file.write(' %20s : %s\n' % (key, value))
82 83 84 85 if sys.platform[:5] == "linux": 86 # Linux doesn't actually support memory usage stats from getrusage().
87 - def memory():
88 mstr = open('/proc/self/stat').read() 89 mstr = mstr.split()[22] 90 return int(mstr)
91 elif sys.platform[:6] == 'darwin': 92 #TODO really get memory stats for OS X
93 - def memory():
94 return 0
95 else: 96 try: 97 import resource 98 except ImportError: 99 try: 100 import win32process 101 import win32api 102 except ImportError:
103 - def memory():
104 return 0
105 else:
106 - def memory():
107 process_handle = win32api.GetCurrentProcess() 108 memory_info = win32process.GetProcessMemoryInfo( process_handle ) 109 return memory_info['PeakWorkingSetSize']
110 else:
111 - def memory():
112 res = resource.getrusage(resource.RUSAGE_SELF) 113 return res[4]
114 115 # returns caller's stack
116 -def caller_stack():
117 import traceback 118 tb = traceback.extract_stack() 119 # strip itself and the caller from the output 120 tb = tb[:-2] 121 result = [] 122 for back in tb: 123 # (filename, line number, function name, text) 124 key = back[:3] 125 result.append('%s:%d(%s)' % func_shorten(key)) 126 return result
127 128 caller_bases = {} 129 caller_dicts = {} 130 131 # trace a caller's stack
132 -def caller_trace(back=0):
133 import traceback 134 tb = traceback.extract_stack(limit=3+back) 135 tb.reverse() 136 callee = tb[1][:3] 137 caller_bases[callee] = caller_bases.get(callee, 0) + 1 138 for caller in tb[2:]: 139 caller = callee + caller[:3] 140 try: 141 entry = caller_dicts[callee] 142 except KeyError: 143 caller_dicts[callee] = entry = {} 144 entry[caller] = entry.get(caller, 0) + 1 145 callee = caller
146 147 # print a single caller and its callers, if any
148 -def _dump_one_caller(key, file, level=0):
149 leader = ' '*level 150 for v,c in sorted([(-v,c) for c,v in caller_dicts[key].items()]): 151 file.write("%s %6d %s:%d(%s)\n" % ((leader,-v) + func_shorten(c[-3:]))) 152 if c in caller_dicts: 153 _dump_one_caller(c, file, level+1)
154 155 # print each call tree
156 -def dump_caller_counts(file=sys.stdout):
157 for k in sorted(caller_bases.keys()): 158 file.write("Callers of %s:%d(%s), %d calls:\n" 159 % (func_shorten(k) + (caller_bases[k],))) 160 _dump_one_caller(k, file)
161 162 shorten_list = [ 163 ( '/scons/SCons/', 1), 164 ( '/src/engine/SCons/', 1), 165 ( '/usr/lib/python', 0), 166 ] 167 168 if os.sep != '/': 169 shorten_list = [(t[0].replace('/', os.sep), t[1]) for t in shorten_list] 170
171 -def func_shorten(func_tuple):
172 f = func_tuple[0] 173 for t in shorten_list: 174 i = f.find(t[0]) 175 if i >= 0: 176 if t[1]: 177 i = i + len(t[0]) 178 return (f[i:],)+func_tuple[1:] 179 return func_tuple
180 181 182 TraceFP = {} 183 if sys.platform == 'win32': 184 TraceDefault = 'con' 185 else: 186 TraceDefault = '/dev/tty' 187 188 TimeStampDefault = None 189 StartTime = time.time() 190 PreviousTime = StartTime 191
192 -def Trace(msg, file=None, mode='w', tstamp=None):
193 """Write a trace message to a file. Whenever a file is specified, 194 it becomes the default for the next call to Trace().""" 195 global TraceDefault 196 global TimeStampDefault 197 global PreviousTime 198 if file is None: 199 file = TraceDefault 200 else: 201 TraceDefault = file 202 if tstamp is None: 203 tstamp = TimeStampDefault 204 else: 205 TimeStampDefault = tstamp 206 try: 207 fp = TraceFP[file] 208 except KeyError: 209 try: 210 fp = TraceFP[file] = open(file, mode) 211 except TypeError: 212 # Assume we were passed an open file pointer. 213 fp = file 214 if tstamp: 215 now = time.time() 216 fp.write('%8.4f %8.4f: ' % (now - StartTime, now - PreviousTime)) 217 PreviousTime = now 218 fp.write(msg) 219 fp.flush()
220 221 # Local Variables: 222 # tab-width:4 223 # indent-tabs-mode:nil 224 # End: 225 # vim: set expandtab tabstop=4 shiftwidth=4: 226