Index: docs/reference/gobject/gobject-stats.xml
===================================================================
--- docs/reference/gobject/gobject-stats.xml	(revision 0)
+++ docs/reference/gobject/gobject-stats.xml	(revision 0)
@@ -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",
+or "destroyed"
+</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>
Index: docs/reference/gobject/gobject-stats.1
===================================================================
--- docs/reference/gobject/gobject-stats.1	(revision 0)
+++ docs/reference/gobject/gobject-stats.1	(revision 0)
@@ -0,0 +1,218 @@
+.\"     Title: gobject-stats
+.\"    Author: [see the "Author" section]
+.\" Generator: DocBook XSL Stylesheets v1.74.0 <http://docbook.sf.net/>
+.\"      Date: 01/02/2009
+.\"    Manual: [FIXME: manual]
+.\"    Source: [FIXME: source]
+.\"  Language: English
+.\"
+.TH "GOBJECT\-STATS" "1" "01/02/2009" "[FIXME: source]" "[FIXME: manual]"
+.\" -----------------------------------------------------------------
+.\" * (re)Define some macros
+.\" -----------------------------------------------------------------
+.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+.\" toupper - uppercase a string (locale-aware)
+.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+.de toupper
+.tr aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ
+\\$*
+.tr aabbccddeeffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz
+..
+.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+.\" SH-xref - format a cross-reference to an SH section
+.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+.de SH-xref
+.ie n \{\
+.\}
+.toupper \\$*
+.el \{\
+\\$*
+.\}
+..
+.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+.\" SH - level-one heading that works better for non-TTY output
+.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+.de1 SH
+.\" put an extra blank line of space above the head in non-TTY output
+.if t \{\
+.sp 1
+.\}
+.sp \\n[PD]u
+.nr an-level 1
+.set-an-margin
+.nr an-prevailing-indent \\n[IN]
+.fi
+.in \\n[an-margin]u
+.ti 0
+.HTML-TAG ".NH \\n[an-level]"
+.it 1 an-trap
+.nr an-no-space-flag 1
+.nr an-break-flag 1
+\." make the size of the head bigger
+.ps +3
+.ft B
+.ne (2v + 1u)
+.ie n \{\
+.\" if n (TTY output), use uppercase
+.toupper \\$*
+.\}
+.el \{\
+.nr an-break-flag 0
+.\" if not n (not TTY), use normal case (not uppercase)
+\\$1
+.in \\n[an-margin]u
+.ti 0
+.\" if not n (not TTY), put a border/line under subheading
+.sp -.6
+\l'\n(.lu'
+.\}
+..
+.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+.\" SS - level-two heading that works better for non-TTY output
+.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+.de1 SS
+.sp \\n[PD]u
+.nr an-level 1
+.set-an-margin
+.nr an-prevailing-indent \\n[IN]
+.fi
+.in \\n[IN]u
+.ti \\n[SN]u
+.it 1 an-trap
+.nr an-no-space-flag 1
+.nr an-break-flag 1
+.ps \\n[PS-SS]u
+\." make the size of the head bigger
+.ps +2
+.ft B
+.ne (2v + 1u)
+.if \\n[.$] \&\\$*
+..
+.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+.\" BB/BE - put background/screen (filled box) around block of text
+.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+.de BB
+.if t \{\
+.sp -.5
+.br
+.in +2n
+.ll -2n
+.gcolor red
+.di BX
+.\}
+..
+.de EB
+.if t \{\
+.if "\\$2"adjust-for-leading-newline" \{\
+.sp -1
+.\}
+.br
+.di
+.in
+.ll
+.gcolor
+.nr BW \\n(.lu-\\n(.i
+.nr BH \\n(dn+.5v
+.ne \\n(BHu+.5v
+.ie "\\$2"adjust-for-leading-newline" \{\
+\M[\\$1]\h'1n'\v'+.5v'\D'P \\n(BWu 0 0 \\n(BHu -\\n(BWu 0 0 -\\n(BHu'\M[]
+.\}
+.el \{\
+\M[\\$1]\h'1n'\v'-.5v'\D'P \\n(BWu 0 0 \\n(BHu -\\n(BWu 0 0 -\\n(BHu'\M[]
+.\}
+.in 0
+.sp -.5v
+.nf
+.BX
+.in
+.sp .5v
+.fi
+.\}
+..
+.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+.\" BM/EM - put colored marker in margin next to block of text
+.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+.de BM
+.if t \{\
+.br
+.ll -2n
+.gcolor red
+.di BX
+.\}
+..
+.de EM
+.if t \{\
+.br
+.di
+.ll
+.gcolor
+.nr BH \\n(dn
+.ne \\n(BHu
+\M[\\$1]\D'P -.75n 0 0 \\n(BHu -(\\n[.i]u - \\n(INu - .75n) 0 0 -\\n(BHu'\M[]
+.in 0
+.nf
+.BX
+.in
+.fi
+.\}
+..
+.\" -----------------------------------------------------------------
+.\" * set default formatting
+.\" -----------------------------------------------------------------
+.\" disable hyphenation
+.nh
+.\" disable justification (adjust text to left margin only)
+.ad l
+.\" -----------------------------------------------------------------
+.\" * MAIN CONTENT STARTS HERE *
+.\" -----------------------------------------------------------------
+.SH "Name"
+gobject-stats \- Generate a nicely formatted report of GType usage
+.SH "Synopsis"
+.fam C
+.HP \w'\fBgobject\-stats\fR\ 'u
+\fBgobject\-stats\fR [options...] [files...]
+.fam
+.SH "Description"
+.PP
+\fBgobject\-stats\fR
+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\&.
+.SH "Invocation"
+.PP
+\fBgobject\-stats\fR
+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\&.
+.SS "Options"
+.PP
+\fB\-s\fR \fIcol\fR, \fB\-\-sort\-ascending\fR \fIcol\fR
+.RS 4
+Sort column
+\fIcol\fR
+in ascending order, where
+\fIcol\fR
+is one of "type", "population", "created", or "destroyed"
+.RE
+.PP
+\fB\-S\fR \fIcol\fR \fB\-\-sort\-descending\fR \fIcol\fR
+.RS 4
+Sort column
+\fIcol\fR
+in descending order, where
+\fIcol\fR
+is one of "type", "population", "created", or "destroyed"
+.RE
+.PP
+\fB\-\-help\fR
+.RS 4
+Print brief help and exit\&.
+.RE
+.SH "Bugs"
+.PP
+None known yet\&.
+.SH "Author"
+.PP
+\fBgobject\-stats\fR
+has been written by Matthew Barnes
+\FCmbarnes@redhat\&.com\F[]
+.PP
+This manual page was provided by Matthew Barnes
+\FCmbarnes@redhat\&.com\F[]\&.
Index: docs/reference/gobject/Makefile.am
===================================================================
--- docs/reference/gobject/Makefile.am	(revision 7759)
+++ docs/reference/gobject/Makefile.am	(working copy)
@@ -48,6 +48,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 \
@@ -67,7 +68,7 @@ EXTRA_DIST += 		\
 
 ########################################################################
 
-man_MANS = glib-mkenums.1 glib-genmarshal.1 gobject-query.1
+man_MANS = glib-mkenums.1 glib-genmarshal.1 gobject-query.1 gobject-stats.1
 
 if ENABLE_MAN
 
Index: gobject/gobject-stats
===================================================================
--- gobject/gobject-stats	(revision 0)
+++ gobject/gobject-stats	(revision 0)
@@ -0,0 +1,137 @@
+#!/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
+
+# Default sort criteria:
+#   --sort-descending=population
+#   --sort-descending=created
+#   --sort-ascending=type
+default_sort = (
+    lambda a, b: cmp(a[1][POPULATION], b[1][POPULATION]) * -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', or
+    'destroyed' (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
+    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')
+    help = 'sort column COL in %s order, where COL is one of ' + \
+           '"type", "population", "created", or "destroyed"'
+    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)
+        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')
+    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)
Index: gobject/gtype.c
===================================================================
--- gobject/gtype.c	(revision 7759)
+++ gobject/gtype.c	(working copy)
@@ -359,6 +359,50 @@ static GQuark          static_quark_ifac
 static GQuark          static_quark_dependants_array = 0;
 GTypeDebugFlags	       _g_type_debug_flags = 0;
 
+#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 */
+
 
 /* --- type nodes --- */
 static GHashTable       *static_type_nodes_ht = NULL;
@@ -1672,6 +1716,30 @@ g_type_create_instance (GType type)
   instance->g_class = class;
   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
   
   return instance;
 }
@@ -1713,6 +1781,18 @@ g_type_free_instance (GTypeInstance *ins
   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);
 
@@ -4000,6 +4080,7 @@ g_type_init_with_debug_flags (GTypeDebug
       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,
@@ -4073,6 +4154,14 @@ g_type_init_with_debug_flags (GTypeDebug
   /* 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);
 }
Index: gobject/Makefile.am
===================================================================
--- gobject/Makefile.am	(revision 7759)
+++ gobject/Makefile.am	(working copy)
@@ -207,7 +207,7 @@ libgobject_2_0_la_SOURCES = $(gobject_ta
 # 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
Index: gobject/gtype.h
===================================================================
--- gobject/gtype.h	(revision 7759)
+++ gobject/gtype.h	(working copy)
@@ -625,7 +625,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;
 
 
