@@ -704,7 +704,8 @@ static PyObject *
704704gen_get_name (PyObject * self , void * Py_UNUSED (ignored ))
705705{
706706 PyGenObject * op = _PyGen_CAST (self );
707- return Py_NewRef (op -> gi_name );
707+ PyObject * name = FT_ATOMIC_LOAD_PTR_ACQUIRE (op -> gi_name );
708+ return Py_NewRef (name );
708709}
709710
710711static int
@@ -718,15 +719,20 @@ gen_set_name(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
718719 "__name__ must be set to a string object" );
719720 return -1 ;
720721 }
721- Py_XSETREF (op -> gi_name , Py_NewRef (value ));
722+ Py_BEGIN_CRITICAL_SECTION (self );
723+ // gh-133931: To prevent use-after-free from other threads that reference
724+ // the gi_name.
725+ _PyObject_XSetRefDelayed (& op -> gi_name , Py_NewRef (value ));
726+ Py_END_CRITICAL_SECTION ();
722727 return 0 ;
723728}
724729
725730static PyObject *
726731gen_get_qualname (PyObject * self , void * Py_UNUSED (ignored ))
727732{
728733 PyGenObject * op = _PyGen_CAST (self );
729- return Py_NewRef (op -> gi_qualname );
734+ PyObject * qualname = FT_ATOMIC_LOAD_PTR_ACQUIRE (op -> gi_qualname );
735+ return Py_NewRef (qualname );
730736}
731737
732738static int
@@ -740,7 +746,11 @@ gen_set_qualname(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
740746 "__qualname__ must be set to a string object" );
741747 return -1 ;
742748 }
743- Py_XSETREF (op -> gi_qualname , Py_NewRef (value ));
749+ Py_BEGIN_CRITICAL_SECTION (self );
750+ // gh-133931: To prevent use-after-free from other threads that reference
751+ // the gi_qualname.
752+ _PyObject_XSetRefDelayed (& op -> gi_qualname , Py_NewRef (value ));
753+ Py_END_CRITICAL_SECTION ();
744754 return 0 ;
745755}
746756
0 commit comments