Blame SOURCES/00147-add-debug-malloc-stats.patch

72be67
diff --git a/Include/dictobject.h b/Include/dictobject.h
72be67
index 5a1e9fe..da89cec 100644
72be67
--- a/Include/dictobject.h
72be67
+++ b/Include/dictobject.h
72be67
@@ -154,6 +154,8 @@ PyAPI_FUNC(PyObject *) PyDict_GetItemString(PyObject *dp, const char *key);
72be67
 PyAPI_FUNC(int) PyDict_SetItemString(PyObject *dp, const char *key, PyObject *item);
72be67
 PyAPI_FUNC(int) PyDict_DelItemString(PyObject *dp, const char *key);
72be67
 
72be67
+PyAPI_FUNC(void) _PyDict_DebugMallocStats(FILE *out);
72be67
+
72be67
 #ifdef __cplusplus
72be67
 }
72be67
 #endif
72be67
diff --git a/Include/floatobject.h b/Include/floatobject.h
72be67
index 54e8825..33c6ac0 100644
72be67
--- a/Include/floatobject.h
72be67
+++ b/Include/floatobject.h
72be67
@@ -132,6 +132,7 @@ PyAPI_FUNC(PyObject *) _PyFloat_FormatAdvanced(PyObject *obj,
72be67
    failure.  Used in builtin_round in bltinmodule.c. */
72be67
 PyAPI_FUNC(PyObject *) _Py_double_round(double x, int ndigits);
72be67
 
72be67
+PyAPI_FUNC(void) _PyFloat_DebugMallocStats(FILE* out);
72be67
 
72be67
 
72be67
 #ifdef __cplusplus
72be67
diff --git a/Include/frameobject.h b/Include/frameobject.h
72be67
index 3460379..db89a4a 100644
72be67
--- a/Include/frameobject.h
72be67
+++ b/Include/frameobject.h
72be67
@@ -80,6 +80,8 @@ PyAPI_FUNC(void) PyFrame_FastToLocals(PyFrameObject *);
72be67
 
72be67
 PyAPI_FUNC(int) PyFrame_ClearFreeList(void);
72be67
 
72be67
+PyAPI_FUNC(void) _PyFrame_DebugMallocStats(FILE *out);
72be67
+
72be67
 /* Return the line of code the frame is currently executing. */
72be67
 PyAPI_FUNC(int) PyFrame_GetLineNumber(PyFrameObject *);
72be67
 
72be67
diff --git a/Include/intobject.h b/Include/intobject.h
72be67
index d198574..60cb9e0 100644
72be67
--- a/Include/intobject.h
72be67
+++ b/Include/intobject.h
72be67
@@ -78,6 +78,8 @@ PyAPI_FUNC(PyObject *) _PyInt_FormatAdvanced(PyObject *obj,
72be67
 					     char *format_spec,
72be67
 					     Py_ssize_t format_spec_len);
72be67
 
72be67
+PyAPI_FUNC(void) _PyInt_DebugMallocStats(FILE *out);
72be67
+
72be67
 #ifdef __cplusplus
72be67
 }
72be67
 #endif
72be67
diff --git a/Include/listobject.h b/Include/listobject.h
72be67
index f19b1c5..7fccb47 100644
72be67
--- a/Include/listobject.h
72be67
+++ b/Include/listobject.h
72be67
@@ -62,6 +62,8 @@ PyAPI_FUNC(PyObject *) _PyList_Extend(PyListObject *, PyObject *);
72be67
 #define PyList_SET_ITEM(op, i, v) (((PyListObject *)(op))->ob_item[i] = (v))
72be67
 #define PyList_GET_SIZE(op)    Py_SIZE(op)
72be67
 
72be67
+PyAPI_FUNC(void) _PyList_DebugMallocStats(FILE *out);
72be67
+
72be67
 #ifdef __cplusplus
72be67
 }
72be67
 #endif
72be67
diff --git a/Include/methodobject.h b/Include/methodobject.h
72be67
index 6e160b6..1944517 100644
72be67
--- a/Include/methodobject.h
72be67
+++ b/Include/methodobject.h
72be67
@@ -87,6 +87,10 @@ typedef struct {
72be67
 
72be67
 PyAPI_FUNC(int) PyCFunction_ClearFreeList(void);
72be67
 
72be67
+PyAPI_FUNC(void) _PyCFunction_DebugMallocStats(FILE *out);
72be67
+PyAPI_FUNC(void) _PyMethod_DebugMallocStats(FILE *out);
72be67
+
72be67
+
72be67
 #ifdef __cplusplus
72be67
 }
72be67
 #endif
72be67
diff --git a/Include/object.h b/Include/object.h
72be67
index 807b241..a9d2079 100644
72be67
--- a/Include/object.h
72be67
+++ b/Include/object.h
72be67
@@ -1040,6 +1040,13 @@ PyAPI_FUNC(void) _PyTrash_thread_destroy_chain(void);
72be67
             _PyTrash_thread_deposit_object((PyObject*)op); \
72be67
     } while (0);
72be67
 
72be67
+PyAPI_FUNC(void)
72be67
+_PyDebugAllocatorStats(FILE *out, const char *block_name, int num_blocks,
72be67
+		       size_t sizeof_block);
72be67
+
72be67
+PyAPI_FUNC(void)
72be67
+_PyObject_DebugTypeStats(FILE *out);
72be67
+
72be67
 #ifdef __cplusplus
72be67
 }
72be67
 #endif
72be67
diff --git a/Include/objimpl.h b/Include/objimpl.h
72be67
index cbf6bc3..8c14ab8 100644
72be67
--- a/Include/objimpl.h
72be67
+++ b/Include/objimpl.h
72be67
@@ -101,13 +101,13 @@ PyAPI_FUNC(void) PyObject_Free(void *);
72be67
 
72be67
 /* Macros */
72be67
 #ifdef WITH_PYMALLOC
72be67
+PyAPI_FUNC(void) _PyObject_DebugMallocStats(FILE *out);
72be67
 #ifdef PYMALLOC_DEBUG   /* WITH_PYMALLOC && PYMALLOC_DEBUG */
72be67
 PyAPI_FUNC(void *) _PyObject_DebugMalloc(size_t nbytes);
72be67
 PyAPI_FUNC(void *) _PyObject_DebugRealloc(void *p, size_t nbytes);
72be67
 PyAPI_FUNC(void) _PyObject_DebugFree(void *p);
72be67
 PyAPI_FUNC(void) _PyObject_DebugDumpAddress(const void *p);
72be67
 PyAPI_FUNC(void) _PyObject_DebugCheckAddress(const void *p);
72be67
-PyAPI_FUNC(void) _PyObject_DebugMallocStats(void);
72be67
 PyAPI_FUNC(void *) _PyObject_DebugMallocApi(char api, size_t nbytes);
72be67
 PyAPI_FUNC(void *) _PyObject_DebugReallocApi(char api, void *p, size_t nbytes);
72be67
 PyAPI_FUNC(void) _PyObject_DebugFreeApi(char api, void *p);
72be67
diff --git a/Include/setobject.h b/Include/setobject.h
72be67
index 52b07d5..73a37b6 100644
72be67
--- a/Include/setobject.h
72be67
+++ b/Include/setobject.h
72be67
@@ -92,6 +92,7 @@ PyAPI_FUNC(int) _PySet_Next(PyObject *set, Py_ssize_t *pos, PyObject **key);
72be67
 PyAPI_FUNC(int) _PySet_NextEntry(PyObject *set, Py_ssize_t *pos, PyObject **key, long *hash);
72be67
 PyAPI_FUNC(PyObject *) PySet_Pop(PyObject *set);
72be67
 PyAPI_FUNC(int) _PySet_Update(PyObject *set, PyObject *iterable);
72be67
+PyAPI_FUNC(void) _PySet_DebugMallocStats(FILE *out);
72be67
 
72be67
 #ifdef __cplusplus
72be67
 }
72be67
diff --git a/Include/stringobject.h b/Include/stringobject.h
72be67
index 12cc093..0a5fbd1 100644
72be67
--- a/Include/stringobject.h
72be67
+++ b/Include/stringobject.h
72be67
@@ -204,6 +204,8 @@ PyAPI_FUNC(PyObject *) _PyBytes_FormatAdvanced(PyObject *obj,
72be67
 					       char *format_spec,
72be67
 					       Py_ssize_t format_spec_len);
72be67
 
72be67
+PyAPI_FUNC(void) _PyString_DebugMallocStats(FILE *out);
72be67
+
72be67
 #ifdef __cplusplus
72be67
 }
72be67
 #endif
72be67
diff --git a/Include/tupleobject.h b/Include/tupleobject.h
72be67
index a5ab733..27e6ca6 100644
72be67
--- a/Include/tupleobject.h
72be67
+++ b/Include/tupleobject.h
72be67
@@ -54,6 +54,7 @@ PyAPI_FUNC(void) _PyTuple_MaybeUntrack(PyObject *);
72be67
 #define PyTuple_SET_ITEM(op, i, v) (((PyTupleObject *)(op))->ob_item[i] = v)
72be67
 
72be67
 PyAPI_FUNC(int) PyTuple_ClearFreeList(void);
72be67
+PyAPI_FUNC(void) _PyTuple_DebugMallocStats(FILE *out);
72be67
 
72be67
 #ifdef __cplusplus
72be67
 }
72be67
diff --git a/Include/unicodeobject.h b/Include/unicodeobject.h
72be67
index 7781f96..321bd20 100644
72be67
--- a/Include/unicodeobject.h
72be67
+++ b/Include/unicodeobject.h
72be67
@@ -1406,6 +1406,8 @@ PyAPI_FUNC(int) _PyUnicode_IsAlpha(
72be67
     Py_UNICODE ch       /* Unicode character */
72be67
     );
72be67
 
72be67
+PyAPI_FUNC(void) _PyUnicode_DebugMallocStats(FILE *out);
72be67
+
72be67
 #ifdef __cplusplus
72be67
 }
72be67
 #endif
72be67
diff --git a/Lib/test/test_sys.py b/Lib/test/test_sys.py
72be67
index 9342716..8eeb5ab 100644
72be67
--- a/Lib/test/test_sys.py
72be67
+++ b/Lib/test/test_sys.py
72be67
@@ -487,6 +487,32 @@ class SysModuleTest(unittest.TestCase):
72be67
         p.wait()
72be67
         self.assertIn(executable, ["''", repr(sys.executable)])
72be67
 
72be67
+    def test_debugmallocstats(self):
72be67
+        # Test sys._debugmallocstats()
72be67
+
72be67
+        import subprocess
72be67
+
72be67
+        # Verify the default of writing to stderr:
72be67
+        p = subprocess.Popen([sys.executable,
72be67
+                              '-c', 'import sys; sys._debugmallocstats()'],
72be67
+                             stderr=subprocess.PIPE)
72be67
+        out, err = p.communicate()
72be67
+        p.wait()
72be67
+        self.assertIn("arenas allocated current", err)
72be67
+
72be67
+        # Verify that we can redirect the output to a file (not a file-like
72be67
+        # object, though):
72be67
+        with open('mallocstats.txt', 'w') as out:
72be67
+            sys._debugmallocstats(out)
72be67
+        result = open('mallocstats.txt').read()
72be67
+        self.assertIn("arenas allocated current", result)
72be67
+        os.unlink('mallocstats.txt')
72be67
+
72be67
+        # Verify that the destination must be a file:
72be67
+        with self.assertRaises(TypeError):
72be67
+            sys._debugmallocstats(42)
72be67
+
72be67
+
72be67
 @test.test_support.cpython_only
72be67
 class SizeofTest(unittest.TestCase):
72be67
 
72be67
diff --git a/Objects/classobject.c b/Objects/classobject.c
72be67
index 02d7cfd..1c44a47 100644
72be67
--- a/Objects/classobject.c
72be67
+++ b/Objects/classobject.c
72be67
@@ -2691,3 +2691,12 @@ PyMethod_Fini(void)
72be67
 {
72be67
     (void)PyMethod_ClearFreeList();
72be67
 }
72be67
+
72be67
+/* Print summary info about the state of the optimized allocator */
72be67
+void
72be67
+_PyMethod_DebugMallocStats(FILE *out)
72be67
+{
72be67
+    _PyDebugAllocatorStats(out,
72be67
+                           "free PyMethodObject",
72be67
+                           numfree, sizeof(PyMethodObject));
72be67
+}
72be67
diff --git a/Objects/dictobject.c b/Objects/dictobject.c
72be67
index c544ecd..89ca39c 100644
72be67
--- a/Objects/dictobject.c
72be67
+++ b/Objects/dictobject.c
72be67
@@ -225,6 +225,15 @@ show_track(void)
72be67
 static PyDictObject *free_list[PyDict_MAXFREELIST];
72be67
 static int numfree = 0;
72be67
 
72be67
+/* Print summary info about the state of the optimized allocator */
72be67
+void
72be67
+_PyDict_DebugMallocStats(FILE *out)
72be67
+{
72be67
+    _PyDebugAllocatorStats(out,
72be67
+                           "free PyDictObject", numfree, sizeof(PyDictObject));
72be67
+}
72be67
+
72be67
+
72be67
 void
72be67
 PyDict_Fini(void)
72be67
 {
72be67
diff --git a/Objects/floatobject.c b/Objects/floatobject.c
72be67
index 5954d39..02acc8c 100644
72be67
--- a/Objects/floatobject.c
72be67
+++ b/Objects/floatobject.c
72be67
@@ -34,6 +34,22 @@ typedef struct _floatblock PyFloatBlock;
72be67
 static PyFloatBlock *block_list = NULL;
72be67
 static PyFloatObject *free_list = NULL;
72be67
 
72be67
+/* Print summary info about the state of the optimized allocator */
72be67
+void
72be67
+_PyFloat_DebugMallocStats(FILE *out)
72be67
+{
72be67
+  int num_blocks = 0;
72be67
+  PyFloatBlock *block;
72be67
+
72be67
+  /* Walk the block list, counting */
72be67
+  for (block = block_list; block ; block = block->next) {
72be67
+      num_blocks++;
72be67
+  }
72be67
+
72be67
+  _PyDebugAllocatorStats(out,
72be67
+                         "PyFloatBlock", num_blocks, sizeof(PyFloatBlock));
72be67
+}
72be67
+
72be67
 static PyFloatObject *
72be67
 fill_free_list(void)
72be67
 {
72be67
diff --git a/Objects/frameobject.c b/Objects/frameobject.c
72be67
index 4c91dd0..03a66dc 100644
72be67
--- a/Objects/frameobject.c
72be67
+++ b/Objects/frameobject.c
72be67
@@ -1019,3 +1019,13 @@ PyFrame_Fini(void)
72be67
     Py_XDECREF(builtin_object);
72be67
     builtin_object = NULL;
72be67
 }
72be67
+
72be67
+/* Print summary info about the state of the optimized allocator */
72be67
+void
72be67
+_PyFrame_DebugMallocStats(FILE *out)
72be67
+{
72be67
+    _PyDebugAllocatorStats(out,
72be67
+                           "free PyFrameObject",
72be67
+                           numfree, sizeof(PyFrameObject));
72be67
+}
72be67
+
72be67
diff --git a/Objects/intobject.c b/Objects/intobject.c
72be67
index 9b27c35..703fa5a 100644
72be67
--- a/Objects/intobject.c
72be67
+++ b/Objects/intobject.c
72be67
@@ -44,6 +44,23 @@ typedef struct _intblock PyIntBlock;
72be67
 static PyIntBlock *block_list = NULL;
72be67
 static PyIntObject *free_list = NULL;
72be67
 
72be67
+
72be67
+/* Print summary info about the state of the optimized allocator */
72be67
+void
72be67
+_PyInt_DebugMallocStats(FILE *out)
72be67
+{
72be67
+    int num_blocks = 0;
72be67
+    PyIntBlock *block;
72be67
+
72be67
+    /* Walk the block list, counting */
72be67
+    for (block = block_list; block ; block = block->next) {
72be67
+        num_blocks++;
72be67
+    }
72be67
+
72be67
+    _PyDebugAllocatorStats(out,
72be67
+                           "PyIntBlock", num_blocks, sizeof(PyIntBlock));
72be67
+}
72be67
+
72be67
 static PyIntObject *
72be67
 fill_free_list(void)
72be67
 {
72be67
diff --git a/Objects/listobject.c b/Objects/listobject.c
72be67
index 24eff76..38848bd 100644
72be67
--- a/Objects/listobject.c
72be67
+++ b/Objects/listobject.c
72be67
@@ -109,6 +109,15 @@ PyList_Fini(void)
72be67
     }
72be67
 }
72be67
 
72be67
+/* Print summary info about the state of the optimized allocator */
72be67
+void
72be67
+_PyList_DebugMallocStats(FILE *out)
72be67
+{
72be67
+    _PyDebugAllocatorStats(out,
72be67
+                           "free PyListObject",
72be67
+                           numfree, sizeof(PyListObject));
72be67
+}
72be67
+
72be67
 PyObject *
72be67
 PyList_New(Py_ssize_t size)
72be67
 {
72be67
diff --git a/Objects/methodobject.c b/Objects/methodobject.c
72be67
index c1a99ab..ea5df77 100644
72be67
--- a/Objects/methodobject.c
72be67
+++ b/Objects/methodobject.c
72be67
@@ -412,6 +412,15 @@ PyCFunction_Fini(void)
72be67
     (void)PyCFunction_ClearFreeList();
72be67
 }
72be67
 
72be67
+/* Print summary info about the state of the optimized allocator */
72be67
+void
72be67
+_PyCFunction_DebugMallocStats(FILE *out)
72be67
+{
72be67
+    _PyDebugAllocatorStats(out,
72be67
+                           "free PyCFunction",
72be67
+                           numfree, sizeof(PyCFunction));
72be67
+}
72be67
+
72be67
 /* PyCFunction_New() is now just a macro that calls PyCFunction_NewEx(),
72be67
    but it's part of the API so we need to keep a function around that
72be67
    existing C extensions can call.
72be67
diff --git a/Objects/object.c b/Objects/object.c
72be67
index 65366b0..acef3ce 100644
72be67
--- a/Objects/object.c
72be67
+++ b/Objects/object.c
72be67
@@ -2360,6 +2360,23 @@ PyMem_Free(void *p)
72be67
     PyMem_FREE(p);
72be67
 }
72be67
 
72be67
+void
72be67
+_PyObject_DebugTypeStats(FILE *out)
72be67
+{
72be67
+    _PyString_DebugMallocStats(out);
72be67
+    _PyCFunction_DebugMallocStats(out);
72be67
+    _PyDict_DebugMallocStats(out);
72be67
+    _PyFloat_DebugMallocStats(out);
72be67
+    _PyFrame_DebugMallocStats(out);
72be67
+    _PyInt_DebugMallocStats(out);
72be67
+    _PyList_DebugMallocStats(out);
72be67
+    _PyMethod_DebugMallocStats(out);
72be67
+    _PySet_DebugMallocStats(out);
72be67
+    _PyTuple_DebugMallocStats(out);
72be67
+#if Py_USING_UNICODE
72be67
+    _PyUnicode_DebugMallocStats(out);
72be67
+#endif
72be67
+}
72be67
 
72be67
 /* These methods are used to control infinite recursion in repr, str, print,
72be67
    etc.  Container objects that may recursively contain themselves,
72be67
diff --git a/Objects/obmalloc.c b/Objects/obmalloc.c
72be67
index 0778c85..f049f5c 100644
72be67
--- a/Objects/obmalloc.c
72be67
+++ b/Objects/obmalloc.c
72be67
@@ -541,12 +541,10 @@ static struct arena_object* usable_arenas = NULL;
72be67
 /* Number of arenas allocated that haven't been free()'d. */
72be67
 static size_t narenas_currently_allocated = 0;
72be67
 
72be67
-#ifdef PYMALLOC_DEBUG
72be67
 /* Total number of times malloc() called to allocate an arena. */
72be67
 static size_t ntimes_arena_allocated = 0;
72be67
 /* High water mark (max value ever seen) for narenas_currently_allocated. */
72be67
 static size_t narenas_highwater = 0;
72be67
-#endif
72be67
 
72be67
 /* Allocate a new arena.  If we run out of memory, return NULL.  Else
72be67
  * allocate a new arena, and return the address of an arena_object
72be67
@@ -563,7 +561,7 @@ new_arena(void)
72be67
 
72be67
 #ifdef PYMALLOC_DEBUG
72be67
     if (Py_GETENV("PYTHONMALLOCSTATS"))
72be67
-        _PyObject_DebugMallocStats();
72be67
+        _PyObject_DebugMallocStats(stderr);
72be67
 #endif
72be67
     if (unused_arena_objects == NULL) {
72be67
         uint i;
72be67
@@ -631,11 +629,9 @@ new_arena(void)
72be67
     arenaobj->address = (uptr)address;
72be67
 
72be67
     ++narenas_currently_allocated;
72be67
-#ifdef PYMALLOC_DEBUG
72be67
     ++ntimes_arena_allocated;
72be67
     if (narenas_currently_allocated > narenas_highwater)
72be67
         narenas_highwater = narenas_currently_allocated;
72be67
-#endif
72be67
     arenaobj->freepools = NULL;
72be67
     /* pool_address <- first pool-aligned address in the arena
72be67
        nfreepools <- number of whole pools that fit after alignment */
72be67
@@ -1796,17 +1792,19 @@ _PyObject_DebugDumpAddress(const void *p)
72be67
     }
72be67
 }
72be67
 
72be67
+#endif  /* PYMALLOC_DEBUG */
72be67
+
72be67
 static size_t
72be67
-printone(const char* msg, size_t value)
72be67
+printone(FILE *out, const char* msg, size_t value)
72be67
 {
72be67
     int i, k;
72be67
     char buf[100];
72be67
     size_t origvalue = value;
72be67
 
72be67
-    fputs(msg, stderr);
72be67
+    fputs(msg, out);
72be67
     for (i = (int)strlen(msg); i < 35; ++i)
72be67
-        fputc(' ', stderr);
72be67
-    fputc('=', stderr);
72be67
+        fputc(' ', out);
72be67
+    fputc('=', out);
72be67
 
72be67
     /* Write the value with commas. */
72be67
     i = 22;
72be67
@@ -1827,17 +1825,32 @@ printone(const char* msg, size_t value)
72be67
 
72be67
     while (i >= 0)
72be67
         buf[i--] = ' ';
72be67
-    fputs(buf, stderr);
72be67
+    fputs(buf, out);
72be67
 
72be67
     return origvalue;
72be67
 }
72be67
 
72be67
-/* Print summary info to stderr about the state of pymalloc's structures.
72be67
+void
72be67
+_PyDebugAllocatorStats(FILE *out,
72be67
+                       const char *block_name, int num_blocks, size_t sizeof_block)
72be67
+{
72be67
+       char buf1[128];
72be67
+       char buf2[128];
72be67
+       PyOS_snprintf(buf1, sizeof(buf1),
72be67
+                     "%d %ss * %zd bytes each",
72be67
+                     num_blocks, block_name, sizeof_block);
72be67
+       PyOS_snprintf(buf2, sizeof(buf2),
72be67
+                     "%48s ", buf1);
72be67
+      (void)printone(out, buf2, num_blocks * sizeof_block);
72be67
+}
72be67
+
72be67
+
72be67
+/* Print summary info to "out" about the state of pymalloc's structures.
72be67
  * In Py_DEBUG mode, also perform some expensive internal consistency
72be67
  * checks.
72be67
  */
72be67
 void
72be67
-_PyObject_DebugMallocStats(void)
72be67
+_PyObject_DebugMallocStats(FILE *out)
72be67
 {
72be67
     uint i;
72be67
     const uint numclasses = SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT;
72be67
@@ -1866,7 +1879,7 @@ _PyObject_DebugMallocStats(void)
72be67
     size_t total;
72be67
     char buf[128];
72be67
 
72be67
-    fprintf(stderr, "Small block threshold = %d, in %u size classes.\n",
72be67
+    fprintf(out, "Small block threshold = %d, in %u size classes.\n",
72be67
             SMALL_REQUEST_THRESHOLD, numclasses);
72be67
 
72be67
     for (i = 0; i < numclasses; ++i)
72be67
@@ -1920,10 +1933,10 @@ _PyObject_DebugMallocStats(void)
72be67
     }
72be67
     assert(narenas == narenas_currently_allocated);
72be67
 
72be67
-    fputc('\n', stderr);
72be67
+    fputc('\n', out);
72be67
     fputs("class   size   num pools   blocks in use  avail blocks\n"
72be67
           "-----   ----   ---------   -------------  ------------\n",
72be67
-          stderr);
72be67
+          out);
72be67
 
72be67
     for (i = 0; i < numclasses; ++i) {
72be67
         size_t p = numpools[i];
72be67
@@ -1934,7 +1947,7 @@ _PyObject_DebugMallocStats(void)
72be67
             assert(b == 0 && f == 0);
72be67
             continue;
72be67
         }
72be67
-        fprintf(stderr, "%5u %6u "
72be67
+        fprintf(out, "%5u %6u "
72be67
                         "%11" PY_FORMAT_SIZE_T "u "
72be67
                         "%15" PY_FORMAT_SIZE_T "u "
72be67
                         "%13" PY_FORMAT_SIZE_T "u\n",
72be67
@@ -1944,36 +1957,35 @@ _PyObject_DebugMallocStats(void)
72be67
         pool_header_bytes += p * POOL_OVERHEAD;
72be67
         quantization += p * ((POOL_SIZE - POOL_OVERHEAD) % size);
72be67
     }
72be67
-    fputc('\n', stderr);
72be67
-    (void)printone("# times object malloc called", serialno);
72be67
-
72be67
-    (void)printone("# arenas allocated total", ntimes_arena_allocated);
72be67
-    (void)printone("# arenas reclaimed", ntimes_arena_allocated - narenas);
72be67
-    (void)printone("# arenas highwater mark", narenas_highwater);
72be67
-    (void)printone("# arenas allocated current", narenas);
72be67
+    fputc('\n', out);
72be67
+#ifdef PYMALLOC_DEBUG
72be67
+    (void)printone(out, "# times object malloc called", serialno);
72be67
+#endif
72be67
+    (void)printone(out, "# arenas allocated total", ntimes_arena_allocated);
72be67
+    (void)printone(out, "# arenas reclaimed", ntimes_arena_allocated - narenas);
72be67
+    (void)printone(out, "# arenas highwater mark", narenas_highwater);
72be67
+    (void)printone(out, "# arenas allocated current", narenas);
72be67
 
72be67
     PyOS_snprintf(buf, sizeof(buf),
72be67
         "%" PY_FORMAT_SIZE_T "u arenas * %d bytes/arena",
72be67
         narenas, ARENA_SIZE);
72be67
-    (void)printone(buf, narenas * ARENA_SIZE);
72be67
+    (void)printone(out, buf, narenas * ARENA_SIZE);
72be67
 
72be67
-    fputc('\n', stderr);
72be67
+    fputc('\n', out);
72be67
 
72be67
-    total = printone("# bytes in allocated blocks", allocated_bytes);
72be67
-    total += printone("# bytes in available blocks", available_bytes);
72be67
+    total = printone(out, "# bytes in allocated blocks", allocated_bytes);
72be67
+    total += printone(out, "# bytes in available blocks", available_bytes);
72be67
 
72be67
     PyOS_snprintf(buf, sizeof(buf),
72be67
         "%u unused pools * %d bytes", numfreepools, POOL_SIZE);
72be67
-    total += printone(buf, (size_t)numfreepools * POOL_SIZE);
72be67
+    total += printone(out, buf, (size_t)numfreepools * POOL_SIZE);
72be67
 
72be67
-    total += printone("# bytes lost to pool headers", pool_header_bytes);
72be67
-    total += printone("# bytes lost to quantization", quantization);
72be67
-    total += printone("# bytes lost to arena alignment", arena_alignment);
72be67
-    (void)printone("Total", total);
72be67
+    total += printone(out, "# bytes lost to pool headers", pool_header_bytes);
72be67
+    total += printone(out, "# bytes lost to quantization", quantization);
72be67
+    total += printone(out, "# bytes lost to arena alignment", arena_alignment);
72be67
+    (void)printone(out, "Total", total);
72be67
 }
72be67
 
72be67
-#endif  /* PYMALLOC_DEBUG */
72be67
-
72be67
 #ifdef Py_USING_MEMORY_DEBUGGER
72be67
 /* Make this function last so gcc won't inline it since the definition is
72be67
  * after the reference.
72be67
diff --git a/Objects/setobject.c b/Objects/setobject.c
72be67
index 31da3db..da086ab 100644
72be67
--- a/Objects/setobject.c
72be67
+++ b/Objects/setobject.c
72be67
@@ -1087,6 +1087,16 @@ PySet_Fini(void)
72be67
     Py_CLEAR(emptyfrozenset);
72be67
 }
72be67
 
72be67
+/* Print summary info about the state of the optimized allocator */
72be67
+void
72be67
+_PySet_DebugMallocStats(FILE *out)
72be67
+{
72be67
+    _PyDebugAllocatorStats(out,
72be67
+                           "free PySetObject",
72be67
+                           numfree, sizeof(PySetObject));
72be67
+}
72be67
+
72be67
+
72be67
 static PyObject *
72be67
 set_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
72be67
 {
72be67
diff --git a/Objects/stringobject.c b/Objects/stringobject.c
72be67
index c47d32f..b1ffa24 100644
72be67
--- a/Objects/stringobject.c
72be67
+++ b/Objects/stringobject.c
72be67
@@ -4880,3 +4880,43 @@ void _Py_ReleaseInternedStrings(void)
72be67
     PyDict_Clear(interned);
72be67
     Py_CLEAR(interned);
72be67
 }
72be67
+
72be67
+void _PyString_DebugMallocStats(FILE *out)
72be67
+{
72be67
+    ssize_t i;
72be67
+    int num_immortal = 0, num_mortal = 0;
72be67
+    ssize_t immortal_size = 0, mortal_size = 0;
72be67
+
72be67
+    if (interned == NULL || !PyDict_Check(interned))
72be67
+        return;
72be67
+
72be67
+    for (i = 0; i <= ((PyDictObject*)interned)->ma_mask; i++) {
72be67
+        PyDictEntry *ep = ((PyDictObject*)interned)->ma_table + i;
72be67
+        PyObject *pvalue = ep->me_value;
72be67
+        if (pvalue != NULL) {
72be67
+            PyStringObject *s = (PyStringObject *)ep->me_key;
72be67
+
72be67
+            switch (s->ob_sstate) {
72be67
+            case SSTATE_NOT_INTERNED:
72be67
+                /* XXX Shouldn't happen */
72be67
+                break;
72be67
+            case SSTATE_INTERNED_IMMORTAL:
72be67
+                num_immortal ++;
72be67
+                immortal_size += s->ob_size;
72be67
+                break;
72be67
+            case SSTATE_INTERNED_MORTAL:
72be67
+                num_mortal ++;
72be67
+                mortal_size += s->ob_size;
72be67
+                break;
72be67
+            default:
72be67
+                Py_FatalError("Inconsistent interned string state.");
72be67
+            }
72be67
+        }
72be67
+    }
72be67
+
72be67
+    fprintf(out, "%d mortal interned strings\n", num_mortal);
72be67
+    fprintf(out, "%d immortal interned strings\n", num_immortal);
72be67
+    fprintf(out, "total size of all interned strings: "
72be67
+            "%zi/%zi "
72be67
+            "mortal/immortal\n", mortal_size, immortal_size);
72be67
+}
72be67
diff --git a/Objects/tupleobject.c b/Objects/tupleobject.c
72be67
index 6f4b18c..e8e4490 100644
72be67
--- a/Objects/tupleobject.c
72be67
+++ b/Objects/tupleobject.c
72be67
@@ -44,6 +44,22 @@ show_track(void)
72be67
 }
72be67
 #endif
72be67
 
72be67
+/* Print summary info about the state of the optimized allocator */
72be67
+void
72be67
+_PyTuple_DebugMallocStats(FILE *out)
72be67
+{
72be67
+#if PyTuple_MAXSAVESIZE > 0
72be67
+    int i;
72be67
+    char buf[128];
72be67
+    for (i = 1; i < PyTuple_MAXSAVESIZE; i++) {
72be67
+        PyOS_snprintf(buf, sizeof(buf),
72be67
+                      "free %d-sized PyTupleObject", i);
72be67
+        _PyDebugAllocatorStats(out,
72be67
+                               buf,
72be67
+                               numfree[i], _PyObject_VAR_SIZE(&PyTuple_Type, i));
72be67
+    }
72be67
+#endif
72be67
+}
72be67
 
72be67
 PyObject *
72be67
 PyTuple_New(register Py_ssize_t size)
72be67
diff --git a/Objects/unicodeobject.c b/Objects/unicodeobject.c
72be67
index a859fa0..b6ff83e 100644
72be67
--- a/Objects/unicodeobject.c
72be67
+++ b/Objects/unicodeobject.c
72be67
@@ -9018,6 +9018,12 @@ _PyUnicode_Fini(void)
72be67
     (void)PyUnicode_ClearFreeList();
72be67
 }
72be67
 
72be67
+void _PyUnicode_DebugMallocStats(FILE *out)
72be67
+{
72be67
+    _PyDebugAllocatorStats(out, "free PyUnicodeObject", numfree,
72be67
+                           sizeof(PyUnicodeObject));
72be67
+}
72be67
+
72be67
 #ifdef __cplusplus
72be67
 }
72be67
 #endif
72be67
diff --git a/Python/pythonrun.c b/Python/pythonrun.c
72be67
index b686317..c3b3e17 100644
72be67
--- a/Python/pythonrun.c
72be67
+++ b/Python/pythonrun.c
72be67
@@ -605,7 +605,7 @@ Py_Finalize(void)
72be67
 #endif /* Py_TRACE_REFS */
72be67
 #ifdef PYMALLOC_DEBUG
72be67
     if (Py_GETENV("PYTHONMALLOCSTATS"))
72be67
-        _PyObject_DebugMallocStats();
72be67
+        _PyObject_DebugMallocStats(stderr);
72be67
 #endif
72be67
 
72be67
     call_ll_exitfuncs();
72be67
diff --git a/Python/sysmodule.c b/Python/sysmodule.c
72be67
index 22238ba..60624f2 100644
72be67
--- a/Python/sysmodule.c
72be67
+++ b/Python/sysmodule.c
72be67
@@ -890,6 +890,57 @@ a 11-tuple where the entries in the tuple are counts of:\n\
72be67
 extern "C" {
72be67
 #endif
72be67
 
72be67
+static PyObject *
72be67
+sys_debugmallocstats(PyObject *self, PyObject *args)
72be67
+{
72be67
+    PyObject *file = NULL;
72be67
+    FILE *fp;
72be67
+
72be67
+    if (!PyArg_ParseTuple(args, "|O!",
72be67
+                          &PyFile_Type, &file)) {
72be67
+      return NULL;
72be67
+    }
72be67
+    if (!file) {
72be67
+        /* Default to sys.stderr: */
72be67
+      file = PySys_GetObject("stderr");
72be67
+      if (!file) {
72be67
+          PyErr_SetString(PyExc_ValueError, "sys.stderr not set");
72be67
+          return NULL;
72be67
+      }
72be67
+      if (!PyFile_Check(file)) {
72be67
+          PyErr_SetString(PyExc_TypeError, "sys.stderr is not a file");
72be67
+          return NULL;
72be67
+      }
72be67
+    }
72be67
+
72be67
+    Py_INCREF(file);
72be67
+    /* OK, we now own a ref on non-NULL "file" */
72be67
+
72be67
+    fp = PyFile_AsFile(file);
72be67
+    if (!fp) {
72be67
+        PyErr_SetString(PyExc_ValueError, "file is closed");
72be67
+        Py_DECREF(file);
72be67
+        return NULL;
72be67
+    }
72be67
+
72be67
+    _PyObject_DebugMallocStats(fp);
72be67
+    fputc('\n', fp);
72be67
+    _PyObject_DebugTypeStats(fp);
72be67
+
72be67
+    Py_DECREF(file);
72be67
+
72be67
+    Py_RETURN_NONE;
72be67
+}
72be67
+PyDoc_STRVAR(debugmallocstats_doc,
72be67
+"_debugmallocstats([file])\n\
72be67
+\n\
72be67
+Print summary info to the given file (or sys.stderr) about the state of\n\
72be67
+pymalloc's structures.\n\
72be67
+\n\
72be67
+In Py_DEBUG mode, also perform some expensive internal consistency\n\
72be67
+checks.\n\
72be67
+");
72be67
+
72be67
 #ifdef Py_TRACE_REFS
72be67
 /* Defined in objects.c because it uses static globals if that file */
72be67
 extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
72be67
@@ -988,6 +1039,8 @@ static PyMethodDef sys_methods[] = {
72be67
     {"settrace",        sys_settrace, METH_O, settrace_doc},
72be67
     {"gettrace",        sys_gettrace, METH_NOARGS, gettrace_doc},
72be67
     {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc},
72be67
+    {"_debugmallocstats", sys_debugmallocstats, METH_VARARGS,
72be67
+     debugmallocstats_doc},
72be67
     {NULL,              NULL}           /* sentinel */
72be67
 };
72be67