Skip to content

Commit dc3e963

Browse files
authored
gh-132713: Fix typing.Union[index] race condition (#132802)
Add union_init_parameters() helper function. Use a critical section to initialize the 'parameters' member.
1 parent 32c4bbe commit dc3e963

File tree

1 file changed

+19
-10
lines changed

1 file changed

+19
-10
lines changed

Objects/unionobject.c

+19-10
Original file line numberDiff line numberDiff line change
@@ -322,17 +322,29 @@ static PyMemberDef union_members[] = {
322322
{0}
323323
};
324324

325-
static PyObject *
326-
union_getitem(PyObject *self, PyObject *item)
325+
// Populate __parameters__ if needed.
326+
static int
327+
union_init_parameters(unionobject *alias)
327328
{
328-
unionobject *alias = (unionobject *)self;
329-
// Populate __parameters__ if needed.
329+
int result = 0;
330+
Py_BEGIN_CRITICAL_SECTION(alias);
330331
if (alias->parameters == NULL) {
331332
alias->parameters = _Py_make_parameters(alias->args);
332333
if (alias->parameters == NULL) {
333-
return NULL;
334+
result = -1;
334335
}
335336
}
337+
Py_END_CRITICAL_SECTION();
338+
return result;
339+
}
340+
341+
static PyObject *
342+
union_getitem(PyObject *self, PyObject *item)
343+
{
344+
unionobject *alias = (unionobject *)self;
345+
if (union_init_parameters(alias) < 0) {
346+
return NULL;
347+
}
336348

337349
PyObject *newargs = _Py_subs_parameters(self, alias->args, alias->parameters, item);
338350
if (newargs == NULL) {
@@ -352,11 +364,8 @@ static PyObject *
352364
union_parameters(PyObject *self, void *Py_UNUSED(unused))
353365
{
354366
unionobject *alias = (unionobject *)self;
355-
if (alias->parameters == NULL) {
356-
alias->parameters = _Py_make_parameters(alias->args);
357-
if (alias->parameters == NULL) {
358-
return NULL;
359-
}
367+
if (union_init_parameters(alias) < 0) {
368+
return NULL;
360369
}
361370
return Py_NewRef(alias->parameters);
362371
}

0 commit comments

Comments
 (0)