1fe57a
diff --git a/Lib/test/test_gc.py b/Lib/test/test_gc.py
1fe57a
index 7e47b2d..12a210d 100644
1fe57a
--- a/Lib/test/test_gc.py
1fe57a
+++ b/Lib/test/test_gc.py
1fe57a
@@ -1,7 +1,8 @@
1fe57a
 import unittest
1fe57a
 from test.support import (verbose, run_unittest, start_threads,
1fe57a
-                          requires_type_collecting)
1fe57a
+                          requires_type_collecting, import_module)
1fe57a
 import sys
1fe57a
+import sysconfig
1fe57a
 import time
1fe57a
 import gc
1fe57a
 import weakref
1fe57a
@@ -39,6 +40,8 @@ class GC_Detector(object):
1fe57a
         self.wr = weakref.ref(C1055820(666), it_happened)
1fe57a
 
1fe57a
 
1fe57a
+BUILT_WITH_NDEBUG = ('-DNDEBUG' in sysconfig.get_config_vars()['PY_CFLAGS'])
1fe57a
+
1fe57a
 ### Tests
1fe57a
 ###############################################################################
1fe57a
 
1fe57a
@@ -537,6 +540,49 @@ class GCTests(unittest.TestCase):
1fe57a
             # would be damaged, with an empty __dict__.
1fe57a
             self.assertEqual(x, None)
1fe57a
 
1fe57a
+    @unittest.skipIf(BUILT_WITH_NDEBUG,
1fe57a
+                     'built with -NDEBUG')
1fe57a
+    def test_refcount_errors(self):
1fe57a
+        # Verify the "handling" of objects with broken refcounts
1fe57a
+ 
1fe57a
+        import_module("ctypes") #skip if not supported
1fe57a
+
1fe57a
+        import subprocess
1fe57a
+        code = '''if 1:
1fe57a
+        a = []
1fe57a
+        b = [a]
1fe57a
+
1fe57a
+        # Simulate the refcount of "a" being too low (compared to the
1fe57a
+        # references held on it by live data), but keeping it above zero
1fe57a
+        # (to avoid deallocating it):
1fe57a
+        import ctypes
1fe57a
+        ctypes.pythonapi.Py_DecRef(ctypes.py_object(a))
1fe57a
+
1fe57a
+        # The garbage collector should now have a fatal error when it reaches
1fe57a
+        # the broken object:
1fe57a
+        import gc
1fe57a
+        gc.collect()
1fe57a
+        '''
1fe57a
+        p = subprocess.Popen([sys.executable, "-c", code],
1fe57a
+                             stdout=subprocess.PIPE,
1fe57a
+                             stderr=subprocess.PIPE)
1fe57a
+        stdout, stderr = p.communicate()
1fe57a
+        p.stdout.close()
1fe57a
+        p.stderr.close()
1fe57a
+        # Verify that stderr has a useful error message:
1fe57a
+        self.assertRegexpMatches(stderr,
1fe57a
+            b'Modules/gcmodule.c:[0-9]+: visit_decref: Assertion "gc->gc.gc_refs != 0" failed.')
1fe57a
+        self.assertRegexpMatches(stderr,
1fe57a
+            b'refcount was too small')
1fe57a
+        self.assertRegexpMatches(stderr,
1fe57a
+            b'object  : \[\]')
1fe57a
+        self.assertRegexpMatches(stderr,
1fe57a
+            b'type    : list')
1fe57a
+        self.assertRegexpMatches(stderr,
1fe57a
+            b'refcount: 1')
1fe57a
+        self.assertRegexpMatches(stderr,
1fe57a
+            b'address : 0x[0-9a-f]+')
1fe57a
+
1fe57a
 class GCTogglingTests(unittest.TestCase):
1fe57a
     def setUp(self):
1fe57a
         gc.enable()
1fe57a
diff --git a/Modules/gcmodule.c b/Modules/gcmodule.c
1fe57a
index 916e481..0233ce2 100644
1fe57a
--- a/Modules/gcmodule.c
1fe57a
+++ b/Modules/gcmodule.c
1fe57a
@@ -21,6 +21,73 @@
1fe57a
 #include "Python.h"
1fe57a
 #include "frameobject.h"        /* for PyFrame_ClearFreeList */
1fe57a
 
1fe57a
+/* 
1fe57a
+   Define a pair of assertion macros.
1fe57a
+
1fe57a
+   These work like the regular C assert(), in that they will abort the
1fe57a
+   process with a message on stderr if the given condition fails to hold,
1fe57a
+   but compile away to nothing if NDEBUG is defined.
1fe57a
+
1fe57a
+   However, before aborting, Python will also try to call _PyObject_Dump() on
1fe57a
+   the given object.  This may be of use when investigating bugs in which a
1fe57a
+   particular object is corrupt (e.g. buggy a tp_visit method in an extension
1fe57a
+   module breaking the garbage collector), to help locate the broken objects.
1fe57a
+
1fe57a
+   The WITH_MSG variant allows you to supply an additional message that Python
1fe57a
+   will attempt to print to stderr, after the object dump.
1fe57a
+*/
1fe57a
+#ifdef NDEBUG
1fe57a
+/* No debugging: compile away the assertions: */
1fe57a
+#define PyObject_ASSERT_WITH_MSG(obj, expr, msg) ((void)0)
1fe57a
+#else
1fe57a
+/* With debugging: generate checks: */
1fe57a
+#define PyObject_ASSERT_WITH_MSG(obj, expr, msg) \
1fe57a
+  ((expr)                                           \
1fe57a
+   ? (void)(0)                                      \
1fe57a
+   : _PyObject_AssertFailed((obj),                  \
1fe57a
+                            (msg),                  \
1fe57a
+                            (__STRING(expr)),       \
1fe57a
+                            (__FILE__),             \
1fe57a
+                            (__LINE__),             \
1fe57a
+                            (__PRETTY_FUNCTION__)))
1fe57a
+#endif
1fe57a
+
1fe57a
+#define PyObject_ASSERT(obj, expr) \
1fe57a
+  PyObject_ASSERT_WITH_MSG(obj, expr, NULL)
1fe57a
+
1fe57a
+static void _PyObject_AssertFailed(PyObject *,  const char *,
1fe57a
+				   const char *, const char *, int,
1fe57a
+				   const char *);
1fe57a
+
1fe57a
+static void
1fe57a
+_PyObject_AssertFailed(PyObject *obj, const char *msg, const char *expr,
1fe57a
+		       const char *file, int line, const char *function)
1fe57a
+{
1fe57a
+    fprintf(stderr,
1fe57a
+            "%s:%d: %s: Assertion \"%s\" failed.\n",
1fe57a
+            file, line, function, expr);
1fe57a
+    if (msg) {
1fe57a
+        fprintf(stderr, "%s\n", msg);
1fe57a
+    }
1fe57a
+
1fe57a
+    fflush(stderr);
1fe57a
+
1fe57a
+    if (obj) {
1fe57a
+        /* This might succeed or fail, but we're about to abort, so at least
1fe57a
+           try to provide any extra info we can: */
1fe57a
+        _PyObject_Dump(obj);
1fe57a
+    }
1fe57a
+    else {
1fe57a
+        fprintf(stderr, "NULL object\n");
1fe57a
+    }
1fe57a
+
1fe57a
+    fflush(stdout);
1fe57a
+    fflush(stderr);
1fe57a
+
1fe57a
+    /* Terminate the process: */
1fe57a
+    abort();
1fe57a
+}
1fe57a
+
1fe57a
 /* Get an object's GC head */
1fe57a
 #define AS_GC(o) ((PyGC_Head *)(o)-1)
1fe57a
 
1fe57a
@@ -328,7 +395,8 @@ update_refs(PyGC_Head *containers)
1fe57a
 {
1fe57a
     PyGC_Head *gc = containers->gc.gc_next;
1fe57a
     for (; gc != containers; gc = gc->gc.gc_next) {
1fe57a
-        assert(gc->gc.gc_refs == GC_REACHABLE);
1fe57a
+        PyObject_ASSERT(FROM_GC(gc),
1fe57a
+                        gc->gc.gc_refs == GC_REACHABLE);
1fe57a
         gc->gc.gc_refs = Py_REFCNT(FROM_GC(gc));
1fe57a
         /* Python's cyclic gc should never see an incoming refcount
1fe57a
          * of 0:  if something decref'ed to 0, it should have been
1fe57a
@@ -348,7 +416,8 @@ update_refs(PyGC_Head *containers)
1fe57a
          * so serious that maybe this should be a release-build
1fe57a
          * check instead of an assert?
1fe57a
          */
1fe57a
-        assert(gc->gc.gc_refs != 0);
1fe57a
+        PyObject_ASSERT(FROM_GC(gc),
1fe57a
+                        gc->gc.gc_refs != 0);
1fe57a
     }
1fe57a
 }
1fe57a
 
1fe57a
@@ -363,7 +432,9 @@ visit_decref(PyObject *op, void *data)
1fe57a
          * generation being collected, which can be recognized
1fe57a
          * because only they have positive gc_refs.
1fe57a
          */
1fe57a
-        assert(gc->gc.gc_refs != 0); /* else refcount was too small */
1fe57a
+        PyObject_ASSERT_WITH_MSG(FROM_GC(gc),
1fe57a
+                                 gc->gc.gc_refs != 0,
1fe57a
+                                 "refcount was too small");
1fe57a
         if (gc->gc.gc_refs > 0)
1fe57a
             gc->gc.gc_refs--;
1fe57a
     }
1fe57a
@@ -423,9 +494,10 @@ visit_reachable(PyObject *op, PyGC_Head *reachable)
1fe57a
          * If gc_refs == GC_UNTRACKED, it must be ignored.
1fe57a
          */
1fe57a
          else {
1fe57a
-            assert(gc_refs > 0
1fe57a
-                   || gc_refs == GC_REACHABLE
1fe57a
-                   || gc_refs == GC_UNTRACKED);
1fe57a
+             PyObject_ASSERT(FROM_GC(gc),
1fe57a
+                             gc_refs > 0
1fe57a
+                             || gc_refs == GC_REACHABLE
1fe57a
+                             || gc_refs == GC_UNTRACKED);
1fe57a
          }
1fe57a
     }
1fe57a
     return 0;
1fe57a
@@ -467,7 +539,7 @@ move_unreachable(PyGC_Head *young, PyGC_Head *unreachable)
1fe57a
              */
1fe57a
             PyObject *op = FROM_GC(gc);
1fe57a
             traverseproc traverse = Py_TYPE(op)->tp_traverse;
1fe57a
-            assert(gc->gc.gc_refs > 0);
1fe57a
+            PyObject_ASSERT(op, gc->gc.gc_refs > 0);
1fe57a
             gc->gc.gc_refs = GC_REACHABLE;
1fe57a
             (void) traverse(op,
1fe57a
                             (visitproc)visit_reachable,
1fe57a
@@ -545,7 +617,8 @@ move_finalizers(PyGC_Head *unreachable, PyGC_Head *finalizers)
1fe57a
     for (gc = unreachable->gc.gc_next; gc != unreachable; gc = next) {
1fe57a
         PyObject *op = FROM_GC(gc);
1fe57a
 
1fe57a
-        assert(IS_TENTATIVELY_UNREACHABLE(op));
1fe57a
+        PyObject_ASSERT(op, IS_TENTATIVELY_UNREACHABLE(op));
1fe57a
+
1fe57a
         next = gc->gc.gc_next;
1fe57a
 
1fe57a
         if (has_finalizer(op)) {
1fe57a
@@ -621,7 +694,7 @@ handle_weakrefs(PyGC_Head *unreachable, PyGC_Head *old)
1fe57a
         PyWeakReference **wrlist;
1fe57a
 
1fe57a
         op = FROM_GC(gc);
1fe57a
-        assert(IS_TENTATIVELY_UNREACHABLE(op));
1fe57a
+        PyObject_ASSERT(op, IS_TENTATIVELY_UNREACHABLE(op));
1fe57a
         next = gc->gc.gc_next;
1fe57a
 
1fe57a
         if (! PyType_SUPPORTS_WEAKREFS(Py_TYPE(op)))
1fe57a
@@ -642,9 +715,9 @@ handle_weakrefs(PyGC_Head *unreachable, PyGC_Head *old)
1fe57a
              * the callback pointer intact.  Obscure:  it also
1fe57a
              * changes *wrlist.
1fe57a
              */
1fe57a
-            assert(wr->wr_object == op);
1fe57a
+            PyObject_ASSERT(wr->wr_object, wr->wr_object == op);
1fe57a
             _PyWeakref_ClearRef(wr);
1fe57a
-            assert(wr->wr_object == Py_None);
1fe57a
+            PyObject_ASSERT(wr->wr_object, wr->wr_object == Py_None);
1fe57a
             if (wr->wr_callback == NULL)
1fe57a
                 continue;                       /* no callback */
1fe57a
 
1fe57a
@@ -678,7 +751,7 @@ handle_weakrefs(PyGC_Head *unreachable, PyGC_Head *old)
1fe57a
      */
1fe57a
             if (IS_TENTATIVELY_UNREACHABLE(wr))
1fe57a
                 continue;
1fe57a
-            assert(IS_REACHABLE(wr));
1fe57a
+            PyObject_ASSERT(op, IS_REACHABLE(wr));
1fe57a
 
1fe57a
             /* Create a new reference so that wr can't go away
1fe57a
              * before we can process it again.
1fe57a
@@ -687,7 +760,8 @@ handle_weakrefs(PyGC_Head *unreachable, PyGC_Head *old)
1fe57a
 
1fe57a
             /* Move wr to wrcb_to_call, for the next pass. */
1fe57a
             wrasgc = AS_GC(wr);
1fe57a
-            assert(wrasgc != next); /* wrasgc is reachable, but
1fe57a
+            PyObject_ASSERT(op, wrasgc != next);
1fe57a
+                                    /* wrasgc is reachable, but
1fe57a
                                        next isn't, so they can't
1fe57a
                                        be the same */
1fe57a
             gc_list_move(wrasgc, &wrcb_to_call);
1fe57a
@@ -703,11 +777,11 @@ handle_weakrefs(PyGC_Head *unreachable, PyGC_Head *old)
1fe57a
 
1fe57a
         gc = wrcb_to_call.gc.gc_next;
1fe57a
         op = FROM_GC(gc);
1fe57a
-        assert(IS_REACHABLE(op));
1fe57a
-        assert(PyWeakref_Check(op));
1fe57a
+        PyObject_ASSERT(op, IS_REACHABLE(op));
1fe57a
+        PyObject_ASSERT(op, PyWeakref_Check(op));
1fe57a
         wr = (PyWeakReference *)op;
1fe57a
         callback = wr->wr_callback;
1fe57a
-        assert(callback != NULL);
1fe57a
+        PyObject_ASSERT(op, callback != NULL);
1fe57a
 
1fe57a
         /* copy-paste of weakrefobject.c's handle_callback() */
1fe57a
         temp = PyObject_CallFunctionObjArgs(callback, wr, NULL);
1fe57a
@@ -810,7 +884,7 @@ delete_garbage(PyGC_Head *collectable, PyGC_Head *old)
1fe57a
         PyGC_Head *gc = collectable->gc.gc_next;
1fe57a
         PyObject *op = FROM_GC(gc);
1fe57a
 
1fe57a
-        assert(IS_TENTATIVELY_UNREACHABLE(op));
1fe57a
+        PyObject_ASSERT(op, IS_TENTATIVELY_UNREACHABLE(op));
1fe57a
         if (debug & DEBUG_SAVEALL) {
1fe57a
             PyList_Append(garbage, op);
1fe57a
         }