Blame SOURCES/00170-gc-assertions.patch

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