Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
gh-98724: Fix type punning issue in Py_SETREF()
Fix type punning issue in Py_CLEAR(), Py_SETREF() and Py_XSETREF()
macros. Don't cast pointers to avoid type punning which cause
miscompilation of functions using these macros.
  • Loading branch information
vstinner committed Nov 23, 2022
commit 822d5663cada64a1fe4b394f9b5d05859f432799
12 changes: 6 additions & 6 deletions Include/cpython/object.h
Original file line number Diff line number Diff line change
Expand Up @@ -325,9 +325,9 @@ PyAPI_FUNC(PyObject *) _PyObject_FunctionStr(PyObject *);
*/
#define Py_SETREF(dst, src) \
do { \
PyObject **_tmp_dst_ptr = _Py_CAST(PyObject**, &(dst)); \
PyObject *_tmp_dst = (*_tmp_dst_ptr); \
*_tmp_dst_ptr = _PyObject_CAST(src); \
_PY_TYPEOF(dst)* _tmp_dst_ptr = &(dst); \
_PY_TYPEOF(dst) _tmp_dst = *_tmp_dst_ptr; \
*_tmp_dst_ptr = (src); \
Py_DECREF(_tmp_dst); \
} while (0)

Expand All @@ -336,9 +336,9 @@ PyAPI_FUNC(PyObject *) _PyObject_FunctionStr(PyObject *);
*/
#define Py_XSETREF(dst, src) \
do { \
PyObject **_tmp_dst_ptr = _Py_CAST(PyObject**, &(dst)); \
PyObject *_tmp_dst = (*_tmp_dst_ptr); \
*_tmp_dst_ptr = _PyObject_CAST(src); \
_PY_TYPEOF(dst)* _tmp_dst_ptr = &(dst); \
_PY_TYPEOF(dst) _tmp_dst = *_tmp_dst_ptr; \
*_tmp_dst_ptr = (src); \
Py_XDECREF(_tmp_dst); \
} while (0)

Expand Down
4 changes: 2 additions & 2 deletions Include/object.h
Original file line number Diff line number Diff line change
Expand Up @@ -604,9 +604,9 @@ static inline void Py_DECREF(PyObject *op)
*/
#define Py_CLEAR(op) \
do { \
PyObject **_py_tmp_ptr = _Py_CAST(PyObject**, &(op)); \
_PY_TYPEOF(op)* _py_tmp_ptr = &(op); \
if (*_py_tmp_ptr != NULL) { \
PyObject* _py_tmp = (*_py_tmp_ptr); \
_PY_TYPEOF(op) _py_tmp = *_py_tmp_ptr; \
*_py_tmp_ptr = NULL; \
Py_DECREF(_py_tmp); \
} \
Expand Down
3 changes: 3 additions & 0 deletions Include/pyport.h
Original file line number Diff line number Diff line change
Expand Up @@ -717,4 +717,7 @@ extern char * _getpty(int *, int, mode_t, int);
# endif
#endif

// Get the type of an expression
#define _PY_TYPEOF(EXPR) __typeof__(EXPR)

#endif /* Py_PYPORT_H */