commit db424ea9fc77705bae94b0f0cee1ea9a8e5f7191
Author: Matthew Barnes <mbarnes@redhat.com>
Date:   Wed Mar 9 16:49:39 2011 -0500

    Bug 354457 - Per-Type Statistics for Instantiable GTypes

diff --git a/docs/reference/gobject/Makefile.am b/docs/reference/gobject/Makefile.am
index 61de126..77a10d2 100644
--- a/docs/reference/gobject/Makefile.am
+++ b/docs/reference/gobject/Makefile.am
@@ -47,6 +47,7 @@ content_files = version.xml 		\
 		glib-mkenums.xml 	\
 		glib-genmarshal.xml	\
 		gobject-query.xml \
+		gobject-stats.xml \
 		tut_gobject.xml \
 		tut_gsignal.xml \
 		tut_gtype.xml \
@@ -69,7 +70,8 @@ EXTRA_DIST += 		\
 man_MANS = 			\
 	glib-mkenums.1 		\
 	glib-genmarshal.1 	\
-	gobject-query.1
+	gobject-query.1		\
+	gobject-stats.1
 
 if ENABLE_MAN
 
diff --git a/docs/reference/gobject/gobject-stats.xml b/docs/reference/gobject/gobject-stats.xml
new file mode 100644
index 0000000..4578d8e
--- /dev/null
+++ b/docs/reference/gobject/gobject-stats.xml
@@ -0,0 +1,86 @@
+<refentry id="gobject-stats">
+
+<refmeta>
+<refentrytitle>gobject-stats</refentrytitle>
+<manvolnum>1</manvolnum>
+</refmeta>
+
+<refnamediv>
+<refname>gobject-stats</refname>
+<refpurpose>Generate a nicely formatted report of GType usage</refpurpose>
+</refnamediv>
+
+<refsynopsisdiv>
+<cmdsynopsis>
+<command>gobject-stats</command>
+<arg choice="opt" rep="repeat">options</arg>
+<arg choice="opt" rep="repeat">files</arg>
+</cmdsynopsis>
+</refsynopsisdiv>
+
+<refsect1><title>Description</title>
+<para><command>gobject-stats</command> generates a nicely formatted
+report from the debugging messages triggered by setting GObject's
+G_TYPE_DEBUG_TYPES debug flag. See the GTypeDebugFlags section fo the
+GObject Reference Manual to learn how to set this flag.
+</para>
+</refsect1>
+
+<refsect1><title>Invocation</title>
+<para><command>gobject-stats</command> takes a list of GObject-generated
+statistics on GType usage as input. The statistics are either read from
+standard input or from files passed as additional arguments on the command
+line.
+</para>
+
+<refsect2><title>Options</title>
+<variablelist>
+
+<varlistentry>
+<term><option>-s</option> <replaceable>col</replaceable>,
+<option>--sort-ascending</option> <replaceable>col</replaceable></term>
+<listitem><para>
+Sort column <replaceable>col</replaceable> in ascending order, where
+<replaceable>col</replaceable> is one of "type", "population", "created",
+"destroyed", or "leaked"
+</para></listitem>
+</varlistentry>
+
+<varlistentry>
+<term><option>-S</option> <replaceable>col</replaceable>
+<option>--sort-descending</option> <replaceable>col</replaceable></term>
+<listitem><para>
+Sort column <replaceable>col</replaceable> in descending order, where
+<replaceable>col</replaceable> is one of "type", "population", "created",
+or "destroyed"
+</para></listitem>
+</varlistentry>
+
+<varlistentry>
+<term><option>--help</option></term>
+<listitem><para>
+Print brief help and exit.
+</para></listitem>
+</varlistentry>
+
+</variablelist>
+</refsect2>
+</refsect1>
+
+<refsect1><title>Bugs</title>
+<para>
+None known yet.
+</para>
+</refsect1>
+
+<refsect1><title>Author</title>
+<para><command>gobject-stats</command> has been written by Matthew Barnes
+<email>mbarnes@redhat.com</email>
+</para>
+<para>
+This manual page was provided by Matthew Barnes
+<email>mbarnes@redhat.com</email>.
+</para>
+</refsect1>
+
+</refentry>
diff --git a/gobject/Makefile.am b/gobject/Makefile.am
index a9bc8a0..e02f0c4 100644
--- a/gobject/Makefile.am
+++ b/gobject/Makefile.am
@@ -230,7 +230,7 @@ libgobject_2_0_la_SOURCES = $(gobject_target_sources)
 # programs to compile and install
 #
 bin_PROGRAMS = gobject-query glib-genmarshal
-bin_SCRIPTS = glib-mkenums
+bin_SCRIPTS = glib-mkenums gobject-stats
 noinst_PROGRAMS = testgobject
 # source files
 gobject_query_SOURCES = gobject-query.c
diff --git a/gobject/gobject-stats b/gobject/gobject-stats
new file mode 100644
index 0000000..2a2c721
--- /dev/null
+++ b/gobject/gobject-stats
@@ -0,0 +1,142 @@
+#!/bin/env python
+'''Generate a nicely formatted report from the debugging messages triggered
+by setting GObject's G_TYPE_DEBUG_TYPES debug flag.  See the GTypeDebugFlags
+section of the GObject Reference Manual to learn how to set this flag.'''
+
+import sys
+from optparse import *
+
+# Data triplets
+POPULATION = 0
+CREATED    = 1
+DESTROYED  = 2
+LEAKED     = 3
+
+# Default sort criteria:
+#   --sort-descending=leaked
+#   --sort-descending=created
+#   --sort-ascending=type
+default_sort = (
+    lambda a, b: cmp(a[1][LEAKED], b[1][LEAKED]) * -1,
+    lambda a, b: cmp(a[1][CREATED], b[1][CREATED]) * -1,
+    lambda a, b: cmp(a[0], b[0]))
+
+def parse_sort_value(value, order):
+    '''Generate a comparison function from the given sort option.
+
+    The value argument must be one of 'type', 'population', 'created',
+    'destroyed', or 'leaked' (or just the first letter).  The order argument
+    must be a non-zero integer.  It determines the sort order: positive for
+    ascending, negative for descending.'''
+    column = value.lower()
+    # In the lambda forms below, each argument is a (key, value) pair.
+    # The key is the GType name and the value is an integer triplet.
+    if column == 't' or column == 'type':
+        return lambda a, b: cmp(a[0], b[0]) * order
+    if column == 'p' or column == 'population':
+        return lambda a, b: cmp(a[1][POPULATION], b[1][POPULATION]) * order
+    if column == 'c' or column == 'created':
+        return lambda a, b: cmp(a[1][CREATED], b[1][CREATED]) * order
+    if column == 'd' or column == 'destroyed':
+        return lambda a, b: cmp(a[1][DESTROYED], b[1][DESTROYED]) * order
+    if column == 'l' or column == 'leaked':
+        return lambda a, b: cmp(a[1][LEAKED], b[1][LEAKED]) * order
+    raise OptionValueError("invalid column name '%s'" % value)
+
+def parse_sort_ascending(option, optstr, value, parser):
+    '''Callback for the --sort-ascending option'''
+    if not parser.values.sort:
+        parser.values.sort = []
+    compare_func = parse_sort_value(value, 1)
+    parser.values.sort.append(compare_func)
+
+def parse_sort_descending(option, optstr, value, parser):
+    '''Callback for the --sort-descending option'''
+    if not parser.values.sort:
+        parser.values.sort = []
+    compare_func = parse_sort_value(value, -1)
+    parser.values.sort.append(compare_func)
+
+def parse_options():
+    '''Parse the command-line arguments.
+
+    Returns a two-item tuple.  The first item is a list of file objects
+    opened for reading.  The second item is the sort criteria to use in
+    the type usage report.'''
+    usage = 'usage: %prog [options] [FILE...]'
+    choices = ('type', 'population', 'created', 'destroyed', 'leaked')
+    help = 'sort column COL in %s order, where COL is one of ' + \
+           '"type", "population", "created", "destroyed", or "leaked"'
+    parser = OptionParser(description=__doc__, usage=usage)
+    parser.add_option('-s', '--sort-ascending', action='callback',
+        callback=parse_sort_ascending, dest='sort', metavar='COL',
+        type='string', help=help % 'ascending')
+    parser.add_option('-S', '--sort-descending', action='callback',
+        callback=parse_sort_descending, dest='sort', metavar='COL',
+        type='string', help=help % 'descending')
+    options, args = parser.parse_args()
+    input_files = [open(path) for path in args] or [sys.stdin]
+    sort_criteria = options.sort or default_sort
+    return input_files, sort_criteria
+
+def parse_type_usage(file):
+    '''Parse GObject messages reporting creation and destruction statistics
+    for instantiable GTypes.
+
+    Returns a dictionary of statistics.  The keys are GType names and the
+    values are integer triplets (max_population, num_created, num_destroyed).
+    '''
+    stats = {}
+    for line in file:
+        try:
+            line = line.replace('GLib-GObject-Message:', '')
+            data = [x.strip() for x in line.split('|')]
+            name = data.pop(0)
+            data = dict(x.split() for x in data)
+            max_population = int(data['max-population'])
+            num_created = int(data['created'])
+            num_destroyed = int(data['destroyed'])
+            stats[name] = (max_population,
+                           num_created, num_destroyed,
+                           max(0, num_created - num_destroyed))
+        except:
+            continue  # If anything goes wrong, move on.
+    return stats
+
+def apply_sort_criteria(a, b, sort_criteria):
+    '''Compare a and b using the given sort criteria.
+
+    The sort criteria consists of a list of comparison functions suitable
+    for passing to sorted().  If the sort criteria fails to differentiate
+    the items, fall back to sorting by type name.'''
+    for compare_func in sort_criteria:
+        result = compare_func(a, b)
+        if result != 0:
+            return result
+    return cmp(a[0], b[0])
+
+def report_type_usage(stats, sort_criteria=None):
+    '''Print a report of instantiable GType usage to standard output.'''
+    if not stats:
+        return
+    if sort_criteria == None:
+        sort_criteria = default_sort
+    sep = '  '
+    name_width = max(len(x) for x in stats.keys())
+    fields = ('Instance Type'.ljust(name_width),
+              'Max Population', '# Created', '# Destroyed', '# Leaked')
+    widths = tuple(len(x) for x in fields)
+    print sep.join(fields)
+    print sep.join('-' * x for x in widths)
+    cmp_func = lambda a, b: apply_sort_criteria(a, b, sort_criteria)
+    sorted_items = sorted(stats.items(), cmp=cmp_func)
+    for name, data in sorted_items:
+        print sep.join((name.ljust(name_width),) +
+              tuple(str(value).rjust(width) for value, width in
+              zip(data, widths[1:])))
+
+if __name__ == '__main__':
+    input_files, sort_criteria = parse_options()
+    for file in input_files:
+        stats = parse_type_usage(file)
+        report_type_usage(stats, sort_criteria)
diff --git a/gobject/gtype.c b/gobject/gtype.c
index dac5e8f..cee0dd1 100644
--- a/gobject/gtype.c
+++ b/gobject/gtype.c
@@ -370,6 +370,50 @@ typedef struct {
   GTypeInterfaceCheckFunc check_func;
 } IFaceCheckFunc;
 
+#ifdef G_ENABLE_DEBUG
+#define IF_DEBUG(debug_type)    if (_g_type_debug_flags & G_TYPE_DEBUG_ ## debug_type)
+G_LOCK_DEFINE_STATIC (debug_types);
+static GTree *debug_types_tree = NULL;
+
+typedef struct {
+  guint num_created;
+  guint num_destroyed;
+  guint max_population;
+} DebugTypeStats;
+
+static gint
+debug_types_compare (gconstpointer a, gconstpointer b)
+{
+  return strcmp (g_type_name (GPOINTER_TO_SIZE (a)),
+                 g_type_name (GPOINTER_TO_SIZE (b)));
+}
+
+static gboolean
+debug_types_foreach (gpointer key,
+                     gpointer value,
+                     gpointer user_data)
+{
+  GType type = GPOINTER_TO_SIZE (key);
+  DebugTypeStats *stats = value;
+
+  g_message ("%s | created %u | destroyed %u | max-population %u",
+             g_type_name (type), stats->num_created, stats->num_destroyed,
+             stats->max_population);
+  return FALSE;
+}
+
+static void
+debug_types_atexit (void)
+{
+  IF_DEBUG (TYPES)
+    {
+      G_LOCK (debug_types);
+      g_tree_foreach (debug_types_tree, debug_types_foreach, NULL);
+      G_UNLOCK (debug_types);
+    }
+}
+#endif /* G_ENABLE_DEBUG */
+
 
 /* --- variables --- */
 static GStaticRWLock   type_rw_lock = G_STATIC_RW_LOCK_INIT;
@@ -1888,6 +1932,30 @@ g_type_create_instance (GType type)
   if (node->data->instance.instance_init)
     node->data->instance.instance_init (instance, class);
 
+#ifdef G_ENABLE_DEBUG
+  IF_DEBUG (TYPES)
+    {
+      DebugTypeStats *stats;
+      gpointer key = GSIZE_TO_POINTER (type);
+
+      G_LOCK (debug_types);
+      stats = g_tree_lookup (debug_types_tree, key);
+      if (stats)
+        {
+          guint cur_population;
+          cur_population = ++stats->num_created - stats->num_destroyed;
+          stats->max_population = MAX (cur_population, stats->max_population);
+        }
+      else
+        {
+          stats = g_new0 (DebugTypeStats, 1);
+          stats->max_population = stats->num_created = 1;
+          g_tree_insert (debug_types_tree, key, stats);
+        }
+      G_UNLOCK (debug_types);
+    }
+#endif
+
   TRACE(GOBJECT_OBJECT_NEW(instance, type));
 
   return instance;
@@ -1930,6 +1998,18 @@ g_type_free_instance (GTypeInstance *instance)
   instance->g_class = NULL;
 #ifdef G_ENABLE_DEBUG  
   memset (instance, 0xaa, type_total_instance_size_I (node));
+
+  IF_DEBUG (TYPES)
+    {
+      DebugTypeStats *stats;
+      gpointer key = GSIZE_TO_POINTER (class->g_type);
+
+      G_LOCK (debug_types);
+      stats = g_tree_lookup (debug_types_tree, key);
+      if (stats)
+        stats->num_destroyed++;
+      G_UNLOCK (debug_types);
+    }
 #endif
   g_slice_free1 (type_total_instance_size_I (node), instance);
 
@@ -4290,6 +4370,7 @@ g_type_init_with_debug_flags (GTypeDebugFlags debug_flags)
       static GDebugKey debug_keys[] = {
 	{ "objects", G_TYPE_DEBUG_OBJECTS },
 	{ "signals", G_TYPE_DEBUG_SIGNALS },
+	{ "types",   G_TYPE_DEBUG_TYPES }
       };
       
       _g_type_debug_flags |= g_parse_debug_string (env_string,
@@ -4363,6 +4444,14 @@ g_type_init_with_debug_flags (GTypeDebugFlags debug_flags)
   /* Signal system
    */
   g_signal_init ();
+
+#ifdef G_ENABLE_DEBUG
+  IF_DEBUG (TYPES)
+    {
+      debug_types_tree = g_tree_new (debug_types_compare);
+      g_atexit (debug_types_atexit);
+    }
+#endif
   
   G_UNLOCK (type_init_lock);
 }
diff --git a/gobject/gtype.h b/gobject/gtype.h
index 24970bc..4e36a12 100644
--- a/gobject/gtype.h
+++ b/gobject/gtype.h
@@ -659,7 +659,8 @@ typedef enum	/*< skip >*/
   G_TYPE_DEBUG_NONE	= 0,
   G_TYPE_DEBUG_OBJECTS	= 1 << 0,
   G_TYPE_DEBUG_SIGNALS	= 1 << 1,
-  G_TYPE_DEBUG_MASK	= 0x03
+  G_TYPE_DEBUG_TYPES	= 1 << 2,
+  G_TYPE_DEBUG_MASK	= 0x07
 } GTypeDebugFlags;
 
 
