Skip to content
5 changes: 3 additions & 2 deletions Include/internal/pycore_global_objects_fini.h
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,13 @@ extern "C" {

#include "pycore_bytesobject.h" // _PyBytes_CheckOverflow()
#include "pycore_long.h" // TAG_FROM_SIGN_AND_SIZE()
#include "pycore_object.h" // _Py_IMMORTALITY_IS_RELIABLE

static inline void
_PyStaticObject_CheckSingleton(PyObject *obj, PyTypeObject *type)
{
// Check PyObject.ob_refcnt
_PyObject_ASSERT(obj, _Py_IsImmortal(obj));
// Check immortality
_PyObject_ASSERT(obj, _Py_IsImmortal(obj) || !_Py_IMMORTALITY_IS_RELIABLE);

// Check PyObject.ob_type
_PyObject_ASSERT(obj, Py_TYPE(obj) == type);
Expand Down
3 changes: 2 additions & 1 deletion Include/internal/pycore_long.h
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ extern "C" {

#include "pycore_bytesobject.h" // _PyBytesWriter
#include "pycore_runtime.h" // _Py_SINGLETON()
#include "pycore_object.h" // _Py_ASSERT_STATIC_IMMORTAL

/*
* Default int base conversion size limitation: Denial of Service prevention.
Expand Down Expand Up @@ -240,7 +241,7 @@ _PyLong_IsSmallInt(const PyLongObject *op)
bool is_small_int = (op->long_value.lv_tag & IMMORTALITY_BIT_MASK) != 0;
if (is_small_int) {
assert(PyLong_CheckExact(op));
assert(_Py_IsImmortal(op));
_Py_ASSERT_STATIC_IMMORTAL(op);
assert((_PyLong_IsCompact(op)
&& _PY_IS_SMALL_INT(_PyLong_CompactValue(op))));
}
Expand Down
53 changes: 46 additions & 7 deletions Include/internal/pycore_object.h
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,41 @@ extern "C" {

#include <stdbool.h> // bool

// Stable ABI extensions compiled for Python 3.11 and lower can make
// immortal objects, including statically allocated ones, mortal.
// free-threading and 64-bit-GIL builds use flags to track immortality,
// so _Py_IsImmortal and _Py_IsStaticImmortal are trustworthy.
// On 32-bit-GIL builds, they are not.
#ifndef _Py_IMMORTALITY_IS_RELIABLE
# if defined(Py_GIL_DISABLED)
# define _Py_IMMORTALITY_IS_RELIABLE 1
# else
# define _Py_IMMORTALITY_IS_RELIABLE 0
# endif
#endif
#ifndef _Py_STATIC_IMMORTALITY_IS_RELIABLE
# if defined(Py_GIL_DISABLED) || (SIZEOF_VOID_P > 4)
# define _Py_STATIC_IMMORTALITY_IS_RELIABLE 1
# else
# define _Py_STATIC_IMMORTALITY_IS_RELIABLE 0
# endif
#endif
// Define the most common assertion macros.
#if _Py_IMMORTALITY_IS_RELIABLE
# define _Py_ASSERT_IMMORTAL(op) assert(_Py_IsImmortal(op))
# define _Py_ASSERT_MORTAL(op) assert(!_Py_IsImmortal(op))
#else
# define _Py_ASSERT_IMMORTAL(op) ((void)(op))
# define _Py_ASSERT_MORTAL(op) ((void)(op))
#endif
#if _Py_STATIC_IMMORTALITY_IS_RELIABLE
# define _Py_ASSERT_STATIC_IMMORTAL(op) assert(_Py_IsStaticImmortal(op))
# define _Py_ASSERT_NOT_STATIC_IMMORTAL(op) assert(!_Py_IsStaticImmortal(op))
#else
# define _Py_ASSERT_STATIC_IMMORTAL(op) ((void)(op))
# define _Py_ASSERT_NOT_STATIC_IMMORTAL(op) ((void)(op))
#endif


// This value is added to `ob_ref_shared` for objects that use deferred
// reference counting so that they are not immediately deallocated when the
Expand Down Expand Up @@ -200,7 +235,7 @@ PyAPI_FUNC(void) _Py_SetImmortalUntracked(PyObject *op);
static inline void _Py_SetMortal(PyObject *op, short refcnt)
{
if (op) {
assert(_Py_IsImmortal(op));
_Py_ASSERT_IMMORTAL(op);
#ifdef Py_GIL_DISABLED
op->ob_tid = _Py_UNOWNED_TID;
op->ob_ref_local = 0;
Expand Down Expand Up @@ -406,7 +441,7 @@ static inline void Py_DECREF_MORTAL(const char *filename, int lineno, PyObject *
_Py_NegativeRefcount(filename, lineno, op);
}
_Py_DECREF_STAT_INC();
assert(!_Py_IsStaticImmortal(op));
_Py_ASSERT_NOT_STATIC_IMMORTAL(op);
if (!_Py_IsImmortal(op)) {
_Py_DECREF_DecRefTotal();
}
Expand All @@ -422,7 +457,7 @@ static inline void _Py_DECREF_MORTAL_SPECIALIZED(const char *filename, int linen
_Py_NegativeRefcount(filename, lineno, op);
}
_Py_DECREF_STAT_INC();
assert(!_Py_IsStaticImmortal(op));
_Py_ASSERT_NOT_STATIC_IMMORTAL(op);
if (!_Py_IsImmortal(op)) {
_Py_DECREF_DecRefTotal();
}
Expand All @@ -440,7 +475,7 @@ static inline void _Py_DECREF_MORTAL_SPECIALIZED(const char *filename, int linen

static inline void Py_DECREF_MORTAL(PyObject *op)
{
assert(!_Py_IsStaticImmortal(op));
_Py_ASSERT_NOT_STATIC_IMMORTAL(op);
_Py_DECREF_STAT_INC();
if (--op->ob_refcnt == 0) {
_Py_Dealloc(op);
Expand All @@ -450,7 +485,7 @@ static inline void Py_DECREF_MORTAL(PyObject *op)

static inline void Py_DECREF_MORTAL_SPECIALIZED(PyObject *op, destructor destruct)
{
assert(!_Py_IsStaticImmortal(op));
_Py_ASSERT_NOT_STATIC_IMMORTAL(op);
_Py_DECREF_STAT_INC();
if (--op->ob_refcnt == 0) {
_PyReftracerTrack(op, PyRefTracer_DESTROY);
Expand All @@ -475,7 +510,11 @@ _PyObject_Init(PyObject *op, PyTypeObject *typeobj)
{
assert(op != NULL);
Py_SET_TYPE(op, typeobj);
assert(_PyType_HasFeature(typeobj, Py_TPFLAGS_HEAPTYPE) || _Py_IsImmortal(typeobj));
#ifndef NDEBUG
if (!_PyType_HasFeature(typeobj, Py_TPFLAGS_HEAPTYPE)) {
_Py_ASSERT_IMMORTAL(typeobj);
}
#endif
_Py_INCREF_TYPE(typeobj);
_Py_NewReference(op);
}
Expand Down Expand Up @@ -987,7 +1026,7 @@ extern int _PyObject_SetManagedDict(PyObject *obj, PyObject *new_dict);
#ifndef Py_GIL_DISABLED
static inline Py_ALWAYS_INLINE void _Py_INCREF_MORTAL(PyObject *op)
{
assert(!_Py_IsStaticImmortal(op));
_Py_ASSERT_MORTAL(op);
op->ob_refcnt++;
_Py_INCREF_STAT_INC();
#if defined(Py_REF_DEBUG) && !defined(Py_LIMITED_API)
Expand Down
16 changes: 5 additions & 11 deletions Include/internal/pycore_stackref.h
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,7 @@ _PyStackRef_DupImmortal(_PyStackRef ref, const char *filename, int linenumber)
assert(!PyStackRef_IsTaggedInt(ref));
assert(!PyStackRef_RefcountOnObject(ref));
PyObject *obj = _Py_stackref_get_object(ref);
assert(_Py_IsImmortal(obj));
_Py_ASSERT_IMMORTAL(obj);
return _Py_stackref_create(obj, Py_TAG_REFCNT, filename, linenumber);
}
#define PyStackRef_DupImmortal(REF) _PyStackRef_DupImmortal((REF), __FILE__, __LINE__)
Expand Down Expand Up @@ -361,7 +361,7 @@ static inline _PyStackRef
_PyStackRef_FromPyObjectNewMortal(PyObject *obj, const char *filename, int linenumber)
{
assert(obj != NULL);
assert(!_Py_IsStaticImmortal(obj));
_Py_ASSERT_NOT_STATIC_IMMORTAL(obj);
Py_INCREF(obj);
return _Py_stackref_create(obj, 0, filename, linenumber);
}
Expand Down Expand Up @@ -484,16 +484,10 @@ static const _PyStackRef PyStackRef_NULL = { .bits = PyStackRef_NULL_BITS };
#define PyStackRef_False ((_PyStackRef){.bits = ((uintptr_t)&_Py_FalseStruct) | Py_TAG_REFCNT })
#define PyStackRef_None ((_PyStackRef){.bits = ((uintptr_t)&_Py_NoneStruct) | Py_TAG_REFCNT })

#ifdef Py_GIL_DISABLED
// Checks that mask out the deferred bit in the free threading build.
// Checks mask out the flag bit.
#define PyStackRef_IsNone(REF) (((REF).bits & ~Py_TAG_REFCNT) == (uintptr_t)&_Py_NoneStruct)
#define PyStackRef_IsTrue(REF) (((REF).bits & ~Py_TAG_REFCNT) == (uintptr_t)&_Py_TrueStruct)
#define PyStackRef_IsFalse(REF) (((REF).bits & ~Py_TAG_REFCNT) == (uintptr_t)&_Py_FalseStruct)
#else
#define PyStackRef_IsTrue(REF) ((REF).bits == (((uintptr_t)&_Py_TrueStruct) | Py_TAG_REFCNT))
#define PyStackRef_IsFalse(REF) ((REF).bits == (((uintptr_t)&_Py_FalseStruct) | Py_TAG_REFCNT))
#define PyStackRef_IsNone(REF) ((REF).bits == (((uintptr_t)&_Py_NoneStruct) | Py_TAG_REFCNT))
#endif

#define PyStackRef_IsNullOrInt(stackref) (PyStackRef_IsNull(stackref) || PyStackRef_IsTaggedInt(stackref))

Expand All @@ -508,7 +502,7 @@ PyStackRef_CheckValid(_PyStackRef ref)
switch (tag) {
case 0:
/* Can be immortal if object was made immortal after reference came into existence */
assert(!_Py_IsStaticImmortal(obj));
_Py_ASSERT_NOT_STATIC_IMMORTAL(obj);
break;
case Py_TAG_REFCNT:
break;
Expand Down Expand Up @@ -650,7 +644,7 @@ PyStackRef_DupImmortal(_PyStackRef ref)
{
assert(!PyStackRef_IsNull(ref));
assert(!PyStackRef_RefcountOnObject(ref));
assert(_Py_IsImmortal(BITS_TO_PTR_MASKED(ref)));
_Py_ASSERT_IMMORTAL(BITS_TO_PTR_MASKED(ref));
return ref;
}

Expand Down
3 changes: 2 additions & 1 deletion Include/refcount.h
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,8 @@ static inline Py_ALWAYS_INLINE int _Py_IsImmortal(PyObject *op)
return (_Py_atomic_load_uint32_relaxed(&op->ob_ref_local) ==
_Py_IMMORTAL_REFCNT_LOCAL);
#elif SIZEOF_VOID_P > 4
return _Py_CAST(int32_t, op->ob_refcnt) < 0;
return (_Py_CAST(int32_t, op->ob_refcnt) < 0)
|| ((op->ob_flags & _Py_STATICALLY_ALLOCATED_FLAG) != 0);
#else
return op->ob_refcnt >= _Py_IMMORTAL_MINIMUM_REFCNT;
#endif
Expand Down
67 changes: 66 additions & 1 deletion Lib/test/test_capi/test_immortal.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import unittest
from test.support import import_helper
from test.support import import_helper, Py_GIL_DISABLED, subTests
from test.support.script_helper import assert_python_ok

_testcapi = import_helper.import_module('_testcapi')
_testinternalcapi = import_helper.import_module('_testinternalcapi')
Expand Down Expand Up @@ -37,6 +38,70 @@ def test_immortal_builtins(self):
for obj in ([], {}, set()):
self.assertFalse(_testinternalcapi.is_static_immortal(obj))

@unittest.skipIf(Py_GIL_DISABLED,
"can't de-immortalize on free-threaded build")
@subTests(
'obj_repr',
['None', 'True', 'False', '-1', '256', '""', 'b""', 'type'],
)
def test_deimmortalized_static_object_in_subinterpreter(self, obj_repr):
# gh-158401: Old Stable ABI extensions de-immortalize objects.
# Re-immortalizing such an object (e.g. when a subinterpreter
# is created) must keep it static.
# Run in a subprocess, since other tests assume deimmortalization
# doesn't happen.
assert_python_ok("-c", f"""
import sys
import _testcapi
import _testinternalcapi

obj = {obj_repr}
assert _testinternalcapi.is_static_immortal(obj)
_testinternalcapi.deimmortalize(obj)
_testcapi.run_in_subinterp("pass")
# On 64-builds, the static flag is retained
if sys.maxsize > 2**32:
assert _testinternalcapi.is_static_immortal(obj)
""")


@unittest.skipIf(Py_GIL_DISABLED,
"can't de-immortalize on free-threaded build")
def test_deimmortalized_bool(self):
# gh-158401: Old Stable ABI extensions de-immortalize objects,
# which could change a bool's truth value.
# Run in a subprocess, since other tests assume deimmortalization
# doesn't happen.
assert_python_ok("-c", f"""
import sys
import _testcapi
import _testinternalcapi

class C:
def __init__(self):
self.flag = True

def check_attr(o):
if not o.flag:
raise RuntimeError("o.flag is True but tested false")
return "ok"

def get_true():
return True

def check_return():
if not get_true():
raise RuntimeError("get_true() returned True but tested false")
return "ok"

o = C()
for _ in range(1000):
check_attr(o), check_return()

_testinternalcapi.deimmortalize(True)
check_attr(o)
check_return()
""")

if __name__ == "__main__":
unittest.main()
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fixed unreliable truthiness checks in long-running applications that use
Stable ABI extensions compiled on Python 3.11 or lower.
2 changes: 1 addition & 1 deletion Modules/_asynciomodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -1600,7 +1600,7 @@ _asyncio_Future__state_get_impl(FutureObj *self)
default:
assert (0);
}
assert(_Py_IsImmortal(ret));
_Py_ASSERT_IMMORTAL(ret);
return ret;
}

Expand Down
17 changes: 17 additions & 0 deletions Modules/_testinternalcapi.c
Original file line number Diff line number Diff line change
Expand Up @@ -3130,6 +3130,21 @@ is_static_immortal(PyObject *self, PyObject *op)
Py_RETURN_FALSE;
}

#ifndef Py_GIL_DISABLED
// Make an immortal object mortal, which old Stable ABI extensions can do.
static PyObject *
deimmortalize(PyObject *self, PyObject *op)
{
if (!_Py_IsImmortal(op)) {
PyErr_SetString(PyExc_ValueError, "object is not immortal");
return NULL;
}
op->ob_refcnt = _Py_IMMORTAL_MINIMUM_REFCNT - (1 << 20);
assert(!_Py_IsImmortal(op) || _Py_IsStaticImmortal(op));
Py_RETURN_NONE;
}
#endif

static PyObject *
incref_decref_delayed(PyObject *self, PyObject *op)
{
Expand Down Expand Up @@ -3591,6 +3606,8 @@ static PyMethodDef module_functions[] = {
{"get_tlbc", get_tlbc, METH_O, NULL},
{"get_tlbc_id", get_tlbc_id, METH_O, NULL},
{"get_long_lived_total", get_long_lived_total, METH_NOARGS},
#else
{"deimmortalize", deimmortalize, METH_O},
#endif
#ifdef _Py_TIER2
{"uop_symbols_test", _Py_uop_symbols_test, METH_NOARGS},
Expand Down
3 changes: 2 additions & 1 deletion Modules/_testinternalcapi/test_cases.c.h

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Modules/_typesmodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ _types_exec(PyObject *m)
{
#define EXPORT_STATIC_TYPE(NAME, TYPE) \
do { \
assert(PyUnstable_IsImmortal((PyObject *)&(TYPE))); \
_Py_ASSERT_STATIC_IMMORTAL((PyObject *)&(TYPE)); \
if (PyModule_AddObjectRef(m, (NAME), (PyObject *)&(TYPE)) < 0) { \
return -1; \
} \
Expand Down
2 changes: 1 addition & 1 deletion Objects/bytearrayobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ bytearray_reinit_from_bytes(PyByteArrayObject *self, Py_ssize_t size)
}
else {
// Use the empty bytes string singleton for an empty bytearray
assert(_Py_IsImmortal(self->ob_bytes_object));
_Py_ASSERT_IMMORTAL(self->ob_bytes_object);
}

self->ob_bytes = self->ob_start = PyBytes_AS_STRING(self->ob_bytes_object);
Expand Down
4 changes: 2 additions & 2 deletions Objects/bytesobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ static inline PyObject*
bytes_get_empty(void)
{
PyObject *empty = &EMPTY->ob_base.ob_base;
assert(_Py_IsImmortal(empty));
_Py_ASSERT_STATIC_IMMORTAL(empty);
return empty;
}

Expand All @@ -56,7 +56,7 @@ static inline PyObject*
bytes_get_char(uint8_t ch)
{
PyObject *obj = (PyObject*)CHARACTER(ch);
assert(_Py_IsImmortal(obj));
_Py_ASSERT_STATIC_IMMORTAL(obj);
return obj;
}

Expand Down
2 changes: 1 addition & 1 deletion Objects/codeobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -3127,7 +3127,7 @@ intern_one_constant(PyObject *op)
return op;
}

assert(_Py_IsImmortal(entry->value));
_Py_ASSERT_IMMORTAL(entry->value);
return (PyObject *)entry->value;
}

Expand Down
2 changes: 1 addition & 1 deletion Objects/exceptions.c
Original file line number Diff line number Diff line change
Expand Up @@ -1435,7 +1435,7 @@ BaseExceptionGroup_split_impl(PyBaseExceptionGroupObject *self,
return NULL;
}

assert(_Py_IsStaticImmortal(Py_None));
_Py_ASSERT_STATIC_IMMORTAL(Py_None);
PyObject *result = _PyTuple_FromPairSteal(
split_result.match ? split_result.match : Py_None,
split_result.rest ? split_result.rest : Py_None);
Expand Down
Loading
Loading