From 6eb358cf890c89c2811882307bec17b7300b2144 Mon Sep 17 00:00:00 2001 From: Victor Stinner Date: Fri, 13 Sep 2024 23:11:48 +0200 Subject: [PATCH] gh-124074: Add _Py_NewImmortalRef() function --- Include/internal/pycore_long.h | 4 ++-- Include/internal/pycore_object.h | 9 +++++++++ Objects/boolobject.c | 3 ++- Objects/object.c | 2 +- 4 files changed, 14 insertions(+), 4 deletions(-) diff --git a/Include/internal/pycore_long.h b/Include/internal/pycore_long.h index a516a3edd12203..08586f944d5507 100644 --- a/Include/internal/pycore_long.h +++ b/Include/internal/pycore_long.h @@ -63,12 +63,12 @@ extern void _PyLong_FiniTypes(PyInterpreterState *interp); # error "_PY_NSMALLPOSINTS must be greater than or equal to 257" #endif -// Return a reference to the immortal zero singleton. +// Return a borrowed reference to the immortal zero singleton. // The function cannot return NULL. static inline PyObject* _PyLong_GetZero(void) { return (PyObject *)&_PyLong_SMALL_INTS[_PY_NSMALLNEGINTS]; } -// Return a reference to the immortal one singleton. +// Return a borrowed reference to the immortal one singleton. // The function cannot return NULL. static inline PyObject* _PyLong_GetOne(void) { return (PyObject *)&_PyLong_SMALL_INTS[_PY_NSMALLNEGINTS+1]; } diff --git a/Include/internal/pycore_object.h b/Include/internal/pycore_object.h index 64ff44bd7f5e43..d2c3fd30601d5a 100644 --- a/Include/internal/pycore_object.h +++ b/Include/internal/pycore_object.h @@ -874,6 +874,15 @@ PyAPI_DATA(int) _Py_SwappedOp[]; extern void _Py_GetConstant_Init(void); + +// Similar to Py_NewRef() but for immortal objects. +// obj must be immortal. +static inline PyObject* _Py_NewImmortalRef(PyObject *obj) +{ + assert(_Py_IsImmortalLoose(obj)); + return obj; +} + #ifdef __cplusplus } #endif diff --git a/Objects/boolobject.c b/Objects/boolobject.c index a88a8ad0cfd560..78e07f9df5c0f7 100644 --- a/Objects/boolobject.c +++ b/Objects/boolobject.c @@ -20,7 +20,8 @@ bool_repr(PyObject *self) PyObject *PyBool_FromLong(long ok) { - return ok ? Py_True : Py_False; + PyObject *result = ok ? Py_True : Py_False; + return _Py_NewImmortalRef(result); } /* We define bool_new to always return either Py_True or Py_False */ diff --git a/Objects/object.c b/Objects/object.c index 4b8b6c29266812..ca8dfe0e6b1f6a 100644 --- a/Objects/object.c +++ b/Objects/object.c @@ -3025,7 +3025,7 @@ PyObject* Py_GetConstant(unsigned int constant_id) { if (constant_id < Py_ARRAY_LENGTH(constants)) { - return constants[constant_id]; + return _Py_NewImmortalRef(constants[constant_id]); } else { PyErr_BadInternalCall();