GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — gh-109496: Detect Py_DECREF() after dealloc in debug mode by vstinner · Pull Request #109539 · python/cpython

gh-109496: Detect Py_DECREF() after dealloc in debug mode #109539

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Sign up for GitHub

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
vstinner merged 1 commit into python:main from vstinner:detect_double_decref
Sep 18, 2023

Uh oh!

There was an error while loading. Please reload this page.

Merged

gh-109496: Detect Py_DECREF() after dealloc in debug mode #109539

Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
1 commit
Select commit
8ea43e9
gh-109496: Detect Py_DECREF() after dealloc in debug mode
vstinner Sep 18, 2023
File filter
Filter by extension

Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Diff view
Diff view

There are no files selected for viewing

10 changes: 4 additions & 6 deletions 10 Include/object.h
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -660,17 +660,15 @@ static inline void Py_DECREF(PyObject *op) {
#elif defined(Py_REF_DEBUG)
static inline void Py_DECREF(const char *filename, int lineno, PyObject *op)
{
if (op->ob_refcnt <= 0) {
_Py_NegativeRefcount(filename, lineno, op);
}
if (_Py_IsImmortal(op)) {
return;
}
_Py_DECREF_STAT_INC();
_Py_DECREF_DecRefTotal();
if (--op->ob_refcnt != 0) {
if (op->ob_refcnt < 0) {
_Py_NegativeRefcount(filename, lineno, op);
}
}
else {
if (--op->ob_refcnt == 0) {
_Py_Dealloc(op);
}
}
Expand Down
36 changes: 26 additions & 10 deletions 36 Lib/test/test_capi/test_misc.py
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -301,24 +301,40 @@ def test_getitem_with_error(self):
def test_buildvalue_N(self):
_testcapi.test_buildvalue_N()

@unittest.skipUnless(hasattr(_testcapi, 'negative_refcount'),
'need _testcapi.negative_refcount')
def test_negative_refcount(self):
def check_negative_refcount(self, code):
# bpo-35059: Check that Py_DECREF() reports the correct filename
# when calling _Py_NegativeRefcount() to abort Python.
code = textwrap.dedent("""
import _testcapi
from test import support

with support.SuppressCrashReport():
_testcapi.negative_refcount()
""")
code = textwrap.dedent(code)
rc, out, err = assert_python_failure('-c', code)
self.assertRegex(err,
br'_testcapimodule\.c:[0-9]+: '
br'_Py_NegativeRefcount: Assertion failed: '
br'object has negative ref count')

@unittest.skipUnless(hasattr(_testcapi, 'negative_refcount'),
'need _testcapi.negative_refcount()')
def test_negative_refcount(self):
code = """
import _testcapi
from test import support

with support.SuppressCrashReport():
_testcapi.negative_refcount()
"""
self.check_negative_refcount(code)

@unittest.skipUnless(hasattr(_testcapi, 'decref_freed_object'),
'need _testcapi.decref_freed_object()')
def test_decref_freed_object(self):
code = """
import _testcapi
from test import support

with support.SuppressCrashReport():
_testcapi.decref_freed_object()
"""
self.check_negative_refcount(code)

def test_trashcan_subclass(self):
# bpo-35983: Check that the trashcan mechanism for "list" is NOT
# activated when its tp_dealloc is being called by a subclass
Expand Down
5 changes: 5 additions & 0 deletions 5 Misc/NEWS.d/next/Core and Builtins/2023-09-18-15-35-08.gh-issue-109496.Kleoz3.rst
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
On a Python built in debug mode, :c:func:`Py_DECREF()` now calls
``_Py_NegativeRefcount()`` if the object is a dangling pointer to
deallocated memory: memory filled with ``0xDD`` "dead byte" by the debug
hook on memory allocators. The fix is to check the reference count *before*
checking for ``_Py_IsImmortal()``. Patch by Victor Stinner.
21 changes: 21 additions & 0 deletions 21 Modules/_testcapimodule.c
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -2034,6 +2034,26 @@ negative_refcount(PyObject *self, PyObject *Py_UNUSED(args))

Py_RETURN_NONE;
}

static PyObject *
decref_freed_object(PyObject *self, PyObject *Py_UNUSED(args))
{
PyObject *obj = PyUnicode_FromString("decref_freed_object");
if (obj == NULL) {
return NULL;
}
assert(Py_REFCNT(obj) == 1);

// Deallocate the memory
Py_DECREF(obj);
// obj is a now a dangling pointer
Comment thread
Comment on lines +2048 to +2049

@sorcio sorcio Sep 18, 2023

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a chance this could be an actual pointer to deallocated memory, or memory written to by another thread? Would it be safer to just call Py_DECREF on a fake object which is explicitly memset to 0xDD bytes?

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

@vstinner vstinner Sep 18, 2023

Copy link
Copy Markdown
Member Author

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I prefer to use a functional test: not mock anything here.

This test is very fragile, it makes sure that a dangling pointer has a determinstic behavior. Problem: by definition, it has an undefined behavior :-) But in practice, almost always, the memory should remain around and should just be filled by 0xDD bytes.

If tomorrow the test starts to fail randomly, sure, we can rewrite it by "mocking" the first DECREF() and just pass memory filled by 0xDD byte pattern.

test_capi should not be run in a process with more than 1 thread. libregrtest works hard to make sure that previous tests don't leak tests. Also, it's strongly recommended to run tests with -jN: each test file is run in a fresh process, so with a known number of threads: just 1 :-)

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

// gh-109496: If Python is built in debug mode, Py_DECREF() must call
// _Py_NegativeRefcount() and abort Python.
Py_DECREF(obj);

Py_RETURN_NONE;
}
#endif


Expand Down Expand Up @@ -3299,6 +3319,7 @@ static PyMethodDef TestMethods[] = {
{"bad_get", _PyCFunction_CAST(bad_get), METH_FASTCALL},
#ifdef Py_REF_DEBUG
{"negative_refcount", negative_refcount, METH_NOARGS},
{"decref_freed_object", decref_freed_object, METH_NOARGS},
#endif
{"meth_varargs", meth_varargs, METH_VARARGS},
{"meth_varargs_keywords", _PyCFunction_CAST(meth_varargs_keywords), METH_VARARGS|METH_KEYWORDS},
Expand Down
Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.