Blame SOURCES/00170-gc-assertions.patch

036b9c
diff --git a/Include/object.h b/Include/object.h
036b9c
index 63e37b8..613b26c 100644
036b9c
--- a/Include/object.h
036b9c
+++ b/Include/object.h
036b9c
@@ -1071,6 +1071,49 @@ PyAPI_FUNC(void)
036b9c
 _PyObject_DebugTypeStats(FILE *out);
036b9c
 #endif /* ifndef Py_LIMITED_API */
036b9c
 
036b9c
+/* 
036b9c
+   Define a pair of assertion macros.
036b9c
+
036b9c
+   These work like the regular C assert(), in that they will abort the
036b9c
+   process with a message on stderr if the given condition fails to hold,
036b9c
+   but compile away to nothing if NDEBUG is defined.
036b9c
+
036b9c
+   However, before aborting, Python will also try to call _PyObject_Dump() on
036b9c
+   the given object.  This may be of use when investigating bugs in which a
036b9c
+   particular object is corrupt (e.g. buggy a tp_visit method in an extension
036b9c
+   module breaking the garbage collector), to help locate the broken objects.
036b9c
+
036b9c
+   The WITH_MSG variant allows you to supply an additional message that Python
036b9c
+   will attempt to print to stderr, after the object dump.
036b9c
+*/
036b9c
+#ifdef NDEBUG
036b9c
+/* No debugging: compile away the assertions: */
036b9c
+#define PyObject_ASSERT_WITH_MSG(obj, expr, msg) ((void)0)
036b9c
+#else
036b9c
+/* With debugging: generate checks: */
036b9c
+#define PyObject_ASSERT_WITH_MSG(obj, expr, msg) \
036b9c
+  ((expr)                                           \
036b9c
+   ? (void)(0)                                      \
036b9c
+   : _PyObject_AssertFailed((obj),                  \
036b9c
+                            (msg),                  \
036b9c
+                            (__STRING(expr)),       \
036b9c
+                            (__FILE__),             \
036b9c
+                            (__LINE__),             \
036b9c
+                            (__PRETTY_FUNCTION__)))
036b9c
+#endif
036b9c
+
036b9c
+#define PyObject_ASSERT(obj, expr) \
036b9c
+  PyObject_ASSERT_WITH_MSG(obj, expr, NULL)
036b9c
+
036b9c
+/* 
036b9c
+   Declare and define the entrypoint even when NDEBUG is defined, to avoid
036b9c
+   causing compiler/linker errors when building extensions without NDEBUG
036b9c
+   against a Python built with NDEBUG defined
036b9c
+*/
036b9c
+PyAPI_FUNC(void) _PyObject_AssertFailed(PyObject *,  const char *,
036b9c
+                                        const char *, const char *, int,
036b9c
+                                        const char *);
036b9c
+
036b9c
 #ifdef __cplusplus
036b9c
 }
036b9c
 #endif
036b9c
diff --git a/Lib/test/test_gc.py b/Lib/test/test_gc.py
036b9c
index 7e82b24..4497b8f 100644
036b9c
--- a/Lib/test/test_gc.py
036b9c
+++ b/Lib/test/test_gc.py
036b9c
@@ -1,10 +1,12 @@
036b9c
 import unittest
036b9c
 from test.support import (verbose, refcount_test, run_unittest,
036b9c
                           strip_python_stderr, cpython_only, start_threads,
036b9c
-                          temp_dir, requires_type_collecting, TESTFN, unlink)
036b9c
+                          temp_dir, requires_type_collecting, TESTFN, unlink,
036b9c
+                          import_module)
036b9c
 from test.support.script_helper import assert_python_ok, make_script
036b9c
 
036b9c
 import sys
036b9c
+import sysconfig
036b9c
 import time
036b9c
 import gc
036b9c
 import weakref
036b9c
@@ -50,6 +52,8 @@ class GC_Detector(object):
036b9c
         # gc collects it.
036b9c
         self.wr = weakref.ref(C1055820(666), it_happened)
036b9c
 
036b9c
+BUILD_WITH_NDEBUG = ('-DNDEBUG' in sysconfig.get_config_vars()['PY_CFLAGS'])
036b9c
+
036b9c
 @with_tp_del
036b9c
 class Uncollectable(object):
036b9c
     """Create a reference cycle with multiple __del__ methods.
036b9c
@@ -877,6 +881,50 @@ class GCCallbackTests(unittest.TestCase):
036b9c
         self.assertEqual(len(gc.garbage), 0)
036b9c
 
036b9c
 
036b9c
+    @unittest.skipIf(BUILD_WITH_NDEBUG,
036b9c
+                     'built with -NDEBUG')
036b9c
+    def test_refcount_errors(self):
036b9c
+        self.preclean()
036b9c
+        # Verify the "handling" of objects with broken refcounts
036b9c
+        import_module("ctypes") #skip if not supported
036b9c
+
036b9c
+        import subprocess
036b9c
+        code = '''if 1:
036b9c
+        a = []
036b9c
+        b = [a]
036b9c
+
036b9c
+        # Simulate the refcount of "a" being too low (compared to the
036b9c
+        # references held on it by live data), but keeping it above zero
036b9c
+        # (to avoid deallocating it):
036b9c
+        import ctypes
036b9c
+        ctypes.pythonapi.Py_DecRef(ctypes.py_object(a))
036b9c
+
036b9c
+        # The garbage collector should now have a fatal error when it reaches
036b9c
+        # the broken object:
036b9c
+        import gc
036b9c
+        gc.collect()
036b9c
+        '''
036b9c
+        p = subprocess.Popen([sys.executable, "-c", code],
036b9c
+                             stdout=subprocess.PIPE,
036b9c
+                             stderr=subprocess.PIPE)
036b9c
+        stdout, stderr = p.communicate()
036b9c
+        p.stdout.close()
036b9c
+        p.stderr.close()
036b9c
+        # Verify that stderr has a useful error message:
036b9c
+        self.assertRegex(stderr,
036b9c
+            b'Modules/gcmodule.c:[0-9]+: visit_decref: Assertion "\(\(gc\)->gc.gc_refs >> \(1\)\) != 0" failed.')
036b9c
+        self.assertRegex(stderr,
036b9c
+            b'refcount was too small')
036b9c
+        self.assertRegex(stderr,
036b9c
+            b'object  : \[\]')
036b9c
+        self.assertRegex(stderr,
036b9c
+            b'type    : list')
036b9c
+        self.assertRegex(stderr,
036b9c
+            b'refcount: 1')
036b9c
+        self.assertRegex(stderr,
036b9c
+            b'address : 0x[0-9a-f]+')
036b9c
+
036b9c
+
036b9c
 class GCTogglingTests(unittest.TestCase):
036b9c
     def setUp(self):
036b9c
         gc.enable()
036b9c
diff --git a/Modules/gcmodule.c b/Modules/gcmodule.c
036b9c
index 3bddc40..0cc24f7 100644
036b9c
--- a/Modules/gcmodule.c
036b9c
+++ b/Modules/gcmodule.c
036b9c
@@ -342,7 +342,8 @@ update_refs(PyGC_Head *containers)
036b9c
 {
036b9c
     PyGC_Head *gc = containers->gc.gc_next;
036b9c
     for (; gc != containers; gc = gc->gc.gc_next) {
036b9c
-        assert(_PyGCHead_REFS(gc) == GC_REACHABLE);
036b9c
+        PyObject_ASSERT(FROM_GC(gc),
036b9c
+                        _PyGCHead_REFS(gc) == GC_REACHABLE);
036b9c
         _PyGCHead_SET_REFS(gc, Py_REFCNT(FROM_GC(gc)));
036b9c
         /* Python's cyclic gc should never see an incoming refcount
036b9c
          * of 0:  if something decref'ed to 0, it should have been
036b9c
@@ -362,7 +363,8 @@ update_refs(PyGC_Head *containers)
036b9c
          * so serious that maybe this should be a release-build
036b9c
          * check instead of an assert?
036b9c
          */
036b9c
-        assert(_PyGCHead_REFS(gc) != 0);
036b9c
+        PyObject_ASSERT(FROM_GC(gc),
036b9c
+                        _PyGCHead_REFS(gc) != 0);
036b9c
     }
036b9c
 }
036b9c
 
036b9c
@@ -377,7 +379,9 @@ visit_decref(PyObject *op, void *data)
036b9c
          * generation being collected, which can be recognized
036b9c
          * because only they have positive gc_refs.
036b9c
          */
036b9c
-        assert(_PyGCHead_REFS(gc) != 0); /* else refcount was too small */
036b9c
+        PyObject_ASSERT_WITH_MSG(FROM_GC(gc),
036b9c
+                        _PyGCHead_REFS(gc) != 0,
036b9c
+                        "refcount was too small"); /* else refcount was too small */
036b9c
         if (_PyGCHead_REFS(gc) > 0)
036b9c
             _PyGCHead_DECREF(gc);
036b9c
     }
036b9c
@@ -437,9 +441,10 @@ visit_reachable(PyObject *op, PyGC_Head *reachable)
036b9c
          * If gc_refs == GC_UNTRACKED, it must be ignored.
036b9c
          */
036b9c
          else {
036b9c
-            assert(gc_refs > 0
036b9c
-                   || gc_refs == GC_REACHABLE
036b9c
-                   || gc_refs == GC_UNTRACKED);
036b9c
+             PyObject_ASSERT(FROM_GC(gc),
036b9c
+                             gc_refs > 0
036b9c
+                             || gc_refs == GC_REACHABLE
036b9c
+                             || gc_refs == GC_UNTRACKED);
036b9c
          }
036b9c
     }
036b9c
     return 0;
036b9c
@@ -481,7 +486,7 @@ move_unreachable(PyGC_Head *young, PyGC_Head *unreachable)
036b9c
              */
036b9c
             PyObject *op = FROM_GC(gc);
036b9c
             traverseproc traverse = Py_TYPE(op)->tp_traverse;
036b9c
-            assert(_PyGCHead_REFS(gc) > 0);
036b9c
+            PyObject_ASSERT(op, _PyGCHead_REFS(gc) > 0);
036b9c
             _PyGCHead_SET_REFS(gc, GC_REACHABLE);
036b9c
             (void) traverse(op,
036b9c
                             (visitproc)visit_reachable,
036b9c
@@ -544,7 +549,7 @@ move_legacy_finalizers(PyGC_Head *unreachable, PyGC_Head *finalizers)
036b9c
     for (gc = unreachable->gc.gc_next; gc != unreachable; gc = next) {
036b9c
         PyObject *op = FROM_GC(gc);
036b9c
 
036b9c
-        assert(IS_TENTATIVELY_UNREACHABLE(op));
036b9c
+        PyObject_ASSERT(op, IS_TENTATIVELY_UNREACHABLE(op));
036b9c
         next = gc->gc.gc_next;
036b9c
 
036b9c
         if (has_legacy_finalizer(op)) {
036b9c
@@ -620,7 +625,7 @@ handle_weakrefs(PyGC_Head *unreachable, PyGC_Head *old)
036b9c
         PyWeakReference **wrlist;
036b9c
 
036b9c
         op = FROM_GC(gc);
036b9c
-        assert(IS_TENTATIVELY_UNREACHABLE(op));
036b9c
+        PyObject_ASSERT(op, IS_TENTATIVELY_UNREACHABLE(op));
036b9c
         next = gc->gc.gc_next;
036b9c
 
036b9c
         if (! PyType_SUPPORTS_WEAKREFS(Py_TYPE(op)))
036b9c
@@ -641,9 +646,9 @@ handle_weakrefs(PyGC_Head *unreachable, PyGC_Head *old)
036b9c
              * the callback pointer intact.  Obscure:  it also
036b9c
              * changes *wrlist.
036b9c
              */
036b9c
-            assert(wr->wr_object == op);
036b9c
+            PyObject_ASSERT(wr->wr_object, wr->wr_object == op);
036b9c
             _PyWeakref_ClearRef(wr);
036b9c
-            assert(wr->wr_object == Py_None);
036b9c
+            PyObject_ASSERT(wr->wr_object, wr->wr_object == Py_None);
036b9c
             if (wr->wr_callback == NULL)
036b9c
                 continue;                       /* no callback */
036b9c
 
036b9c
@@ -677,7 +682,7 @@ handle_weakrefs(PyGC_Head *unreachable, PyGC_Head *old)
036b9c
      */
036b9c
             if (IS_TENTATIVELY_UNREACHABLE(wr))
036b9c
                 continue;
036b9c
-            assert(IS_REACHABLE(wr));
036b9c
+            PyObject_ASSERT(op, IS_REACHABLE(wr));
036b9c
 
036b9c
             /* Create a new reference so that wr can't go away
036b9c
              * before we can process it again.
036b9c
@@ -686,7 +691,8 @@ handle_weakrefs(PyGC_Head *unreachable, PyGC_Head *old)
036b9c
 
036b9c
             /* Move wr to wrcb_to_call, for the next pass. */
036b9c
             wrasgc = AS_GC(wr);
036b9c
-            assert(wrasgc != next); /* wrasgc is reachable, but
036b9c
+            PyObject_ASSERT(op, wrasgc != next);
036b9c
+                                    /* wrasgc is reachable, but
036b9c
                                        next isn't, so they can't
036b9c
                                        be the same */
036b9c
             gc_list_move(wrasgc, &wrcb_to_call);
036b9c
@@ -702,11 +708,11 @@ handle_weakrefs(PyGC_Head *unreachable, PyGC_Head *old)
036b9c
 
036b9c
         gc = wrcb_to_call.gc.gc_next;
036b9c
         op = FROM_GC(gc);
036b9c
-        assert(IS_REACHABLE(op));
036b9c
-        assert(PyWeakref_Check(op));
036b9c
+        PyObject_ASSERT(op, IS_REACHABLE(op));
036b9c
+        PyObject_ASSERT(op, PyWeakref_Check(op));
036b9c
         wr = (PyWeakReference *)op;
036b9c
         callback = wr->wr_callback;
036b9c
-        assert(callback != NULL);
036b9c
+        PyObject_ASSERT(op, callback != NULL);
036b9c
 
036b9c
         /* copy-paste of weakrefobject.c's handle_callback() */
036b9c
         temp = PyObject_CallFunctionObjArgs(callback, wr, NULL);
036b9c
@@ -820,12 +826,14 @@ check_garbage(PyGC_Head *collectable)
036b9c
     for (gc = collectable->gc.gc_next; gc != collectable;
036b9c
          gc = gc->gc.gc_next) {
036b9c
         _PyGCHead_SET_REFS(gc, Py_REFCNT(FROM_GC(gc)));
036b9c
-        assert(_PyGCHead_REFS(gc) != 0);
036b9c
+        PyObject_ASSERT(FROM_GC(gc),
036b9c
+                        _PyGCHead_REFS(gc) != 0);
036b9c
     }
036b9c
     subtract_refs(collectable);
036b9c
     for (gc = collectable->gc.gc_next; gc != collectable;
036b9c
          gc = gc->gc.gc_next) {
036b9c
-        assert(_PyGCHead_REFS(gc) >= 0);
036b9c
+        PyObject_ASSERT(FROM_GC(gc),
036b9c
+                        _PyGCHead_REFS(gc) >= 0);
036b9c
         if (_PyGCHead_REFS(gc) != 0)
036b9c
             return -1;
036b9c
     }
036b9c
diff --git a/Objects/object.c b/Objects/object.c
036b9c
index defff55..a50697d 100644
036b9c
--- a/Objects/object.c
036b9c
+++ b/Objects/object.c
036b9c
@@ -2030,6 +2030,35 @@ _PyTrash_thread_destroy_chain(void)
036b9c
     }
036b9c
 }
036b9c
 
036b9c
+PyAPI_FUNC(void)
036b9c
+_PyObject_AssertFailed(PyObject *obj, const char *msg, const char *expr,
036b9c
+              const char *file, int line, const char *function)
036b9c
+{
036b9c
+    fprintf(stderr,
036b9c
+            "%s:%d: %s: Assertion \"%s\" failed.\n",
036b9c
+            file, line, function, expr);
036b9c
+    if (msg) {
036b9c
+        fprintf(stderr, "%s\n", msg);
036b9c
+    }
036b9c
+
036b9c
+    fflush(stderr);
036b9c
+
036b9c
+    if (obj) {
036b9c
+        /* This might succeed or fail, but we're about to abort, so at least
036b9c
+           try to provide any extra info we can: */
036b9c
+        _PyObject_Dump(obj);
036b9c
+    }
036b9c
+    else {
036b9c
+        fprintf(stderr, "NULL object\n");
036b9c
+    }
036b9c
+
036b9c
+    fflush(stdout);
036b9c
+    fflush(stderr);
036b9c
+
036b9c
+    /* Terminate the process: */
036b9c
+    abort();
036b9c
+}
036b9c
+
036b9c
 #ifndef Py_TRACE_REFS
036b9c
 /* For Py_LIMITED_API, we need an out-of-line version of _Py_Dealloc.
036b9c
    Define this here, so we can undefine the macro. */