SCons.Debug

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.  Not everything here is
      4  guaranteed to work all the way back to Python 1.5.2, and shouldn't be
      5  needed by most users.
      6
      7  """
      8
      9  #
     10  # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 The SCons Foundation
     11  #
     12  # Permission is hereby granted, free of charge, to any person obtaining
     13  # a copy of this software and associated documentation files (the
     14  # "Software"), to deal in the Software without restriction, including
     15  # without limitation the rights to use, copy, modify, merge, publish,
     16  # distribute, sublicense, and/or sell copies of the Software, and to
     17  # permit persons to whom the Software is furnished to do so, subject to
     18  # the following conditions:
     19  #
     20  # The above copyright notice and this permission notice shall be included
     21  # in all copies or substantial portions of the Software.
     22  #
     23  # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
     24  # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
     25  # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
     26  # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
     27  # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
     28  # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
     29  # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
     30  #
     31
     32  __revision__ = "src/engine/SCons/Debug.py 2725 2008/03/31 12:52:02 knight"
     33
     34  import os
     35  import string
     36  import sys
     37
     38  # Recipe 14.10 from the Python Cookbook.
     39  try:
     40      import weakref
     41  except ImportError:
     42 -    def logInstanceCreation(instance, name=None):
     43          pass
     44  else:
     45 -    def logInstanceCreation(instance, name=None):
     46          if name is None:
     47              name = instance.__class__.__name__
     48          if not tracked_classes.has_key(name):
     49              tracked_classes[name] = []
     50          tracked_classes[name].append(weakref.ref(instance))
     51
     52
     53
     54  tracked_classes = {}
     55
     56 -def string_to_classes(s):
     57      if s == '*':
     58          c = tracked_classes.keys()
     59          c.sort()
     60          return c
     61      else:
     62          return string.split(s)
     63
     64 -def fetchLoggedInstances(classes="*"):
     65      classnames = string_to_classes(classes)
     66      return map(lambda cn: (cn, len(tracked_classes[cn])), classnames)
     67
     68 -def countLoggedInstances(classes, file=sys.stdout):
     69      for classname in string_to_classes(classes):
     70          file.write("%s: %d\n" % (classname, len(tracked_classes[classname])))
     71
     72 -def listLoggedInstances(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' % repr(obj))
     79
     80 -def dumpLoggedInstances(classes, file=sys.stdout):
     81      for classname in string_to_classes(classes):
     82          file.write('\n%s:\n' % classname)
     83          for ref in tracked_classes[classname]:
     84              obj = ref()
     85              if obj is not None:
     86                  file.write('    %s:\n' % obj)
     87                  for key, value in obj.__dict__.items():
     88                      file.write('        %20s : %s\n' % (key, value))
     89
     90
     91
     92  if sys.platform[:5] == "linux":
     93      # Linux doesn't actually support memory usage stats from getrusage().
     94 -    def memory():
     95          mstr = open('/proc/self/stat').read()
     96          mstr = string.split(mstr)[22]
     97          return int(mstr)
     98  else:
     99      try:
    100          import resource
    101      except ImportError:
    102          try:
    103              import win32process
    104              import win32api
    105          except ImportError:
    106 -            def memory():
    107                  return 0
    108          else:
    109 -            def memory():
    110                  process_handle = win32api.GetCurrentProcess()
    111                  memory_info = win32process.GetProcessMemoryInfo( process_handle )
    112                  return memory_info['PeakWorkingSetSize']
    113      else:
    114 -        def memory():
    115              res = resource.getrusage(resource.RUSAGE_SELF)
    116              return res[4]
    117
    118
    119
    120  caller_dicts = {}
    121
    122 -def caller(*backlist):
    123      import traceback
    124      if not backlist:
    125          backlist = [0]
    126      result = []
    127      for back in backlist:
    128          tb = traceback.extract_stack(limit=3+back)
    129          key = tb[1][:3]
    130          try:
    131              entry = caller_dicts[key]
    132          except KeyError:
    133              entry = caller_dicts[key] = {}
    134          key = tb[0][:3]
    135          entry[key] = entry.get(key, 0) + 1
    136          result.append('%s:%d(%s)' % func_shorten(key))
    137      return result
    138
    139 -def dump_caller_counts(file=sys.stdout):
    140      keys = caller_dicts.keys()
    141      keys.sort()
    142      for k in keys:
    143          file.write("Callers of %s:%d(%s):\n" % func_shorten(k))
    144          counts = caller_dicts[k]
    145          callers = counts.keys()
    146          callers.sort()
    147          for c in callers:
    148              #file.write("    counts[%s] = %s\n" % (c, counts[c]))
    149              t = ((counts[c],) + func_shorten(c))
    150              file.write("    %6d %s:%d(%s)\n" % t)
    151
    152  shorten_list = [
    153      ( '/scons/SCons/',          1),
    154      ( '/src/engine/SCons/',     1),
    155      ( '/usr/lib/python',        0),
    156  ]
    157
    158  if os.sep != '/':
    159 -   def platformize(t):
    160         return (string.replace(t[0], '/', os.sep), t[1])
    161     shorten_list = map(platformize, shorten_list)
    162     del platformize
    163
    164 -def func_shorten(func_tuple):
    165      f = func_tuple[0]
    166      for t in shorten_list:
    167          i = string.find(f, t[0])
    168          if i >= 0:
    169              if t[1]:
    170                  i = i + len(t[0])
    171              f = f[i:]
    172              break
    173      return (f,)+func_tuple[1:]
    174
    175
    176
    177  TraceFP = {}
    178  if sys.platform == 'win32':
    179      TraceDefault = 'con'
    180  else:
    181      TraceDefault = '/dev/tty'
    182
    183 -def Trace(msg, file=None, mode='w'):
    184      """Write a trace message to a file.  Whenever a file is specified,
    185      it becomes the default for the next call to Trace()."""
    186      global TraceDefault
    187      if file is None:
    188          file = TraceDefault
    189      else:
    190          TraceDefault = file
    191      try:
    192          fp = TraceFP[file]
    193      except KeyError:
    194          try:
    195              fp = TraceFP[file] = open(file, mode)
    196          except TypeError:
    197              # Assume we were passed an open file pointer.
    198              fp = file
    199      fp.write(msg)
    200      fp.flush()
    201