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

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