Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit e02c475

Browse files
authored
bpo-46606: os.getgroups() doesn't overallocate (GH-31569)
1 parent fc44b81 commit e02c475

1 file changed

Lines changed: 25 additions & 32 deletions

File tree

Modules/posixmodule.c

Lines changed: 25 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -7623,29 +7623,19 @@ static PyObject *
76237623
os_getgroups_impl(PyObject *module)
76247624
/*[clinic end generated code: output=42b0c17758561b56 input=d3f109412e6a155c]*/
76257625
{
7626-
/* On MacOSX getgroups(2) can return more than MAX_GROUPS results
7627-
* This is a helper variable to store the intermediate result when
7628-
* that happens.
7629-
*
7630-
* See bpo-7900.
7631-
*/
7632-
gid_t *grouplist = NULL;
7633-
int n;
7634-
7635-
/* Issue #17557: As of OS X 10.8, getgroups(2) no longer raises EINVAL if
7636-
* there are more groups than can fit in grouplist. Therefore, on OS X
7637-
* always first call getgroups with length 0 to get the actual number
7638-
* of groups.
7639-
*/
7640-
n = getgroups(0, NULL);
7626+
// Call getgroups with length 0 to get the actual number of groups
7627+
int n = getgroups(0, NULL);
76417628
if (n < 0) {
76427629
return posix_error();
7643-
} else {
7644-
n++; // Avoid malloc(0)
7645-
grouplist = PyMem_New(gid_t, n+1);
7646-
if (grouplist == NULL) {
7647-
return PyErr_NoMemory();
7648-
}
7630+
}
7631+
7632+
if (n == 0) {
7633+
return PyList_New(0);
7634+
}
7635+
7636+
gid_t *grouplist = PyMem_New(gid_t, n);
7637+
if (grouplist == NULL) {
7638+
return PyErr_NoMemory();
76497639
}
76507640

76517641
n = getgroups(n, grouplist);
@@ -7655,22 +7645,25 @@ os_getgroups_impl(PyObject *module)
76557645
}
76567646

76577647
PyObject *result = PyList_New(n);
7658-
if (result != NULL) {
7659-
int i;
7660-
for (i = 0; i < n; ++i) {
7661-
PyObject *o = _PyLong_FromGid(grouplist[i]);
7662-
if (o == NULL) {
7663-
Py_DECREF(result);
7664-
result = NULL;
7665-
break;
7666-
}
7667-
PyList_SET_ITEM(result, i, o);
7668-
}
7648+
if (result == NULL) {
7649+
goto error;
76697650
}
76707651

7652+
for (int i = 0; i < n; ++i) {
7653+
PyObject *group = _PyLong_FromGid(grouplist[i]);
7654+
if (group == NULL) {
7655+
goto error;
7656+
}
7657+
PyList_SET_ITEM(result, i, group);
7658+
}
76717659
PyMem_Free(grouplist);
76727660

76737661
return result;
7662+
7663+
error:
7664+
PyMem_Free(grouplist);
7665+
Py_XDECREF(result);
7666+
return NULL;
76747667
}
76757668
#endif /* HAVE_GETGROUPS */
76767669

0 commit comments

Comments
 (0)