Skip to content

bpo-46606: os.getgroups() doesn't overallocate #31569

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 26, 2022
Merged

bpo-46606: os.getgroups() doesn't overallocate #31569

merged 2 commits into from
Feb 26, 2022

Conversation

vstinner
Copy link
Member

@vstinner vstinner commented Feb 25, 2022

@vstinner
Copy link
Member Author

Python 3.10 already uses similar code.

@methane: Would you mind to review this change?

@@ -7641,8 +7641,7 @@ os_getgroups_impl(PyObject *module)
if (n < 0) {
return posix_error();
} else {
n++; // Avoid malloc(0)
grouplist = PyMem_New(gid_t, n+1);
grouplist = PyMem_New(gid_t, n);
Copy link
Member

@methane methane Feb 25, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

n+1 can be removed.

But I think n++ should be kept to avoid n = getgropus(0, grouplist) later.
When n=0, getgroups returns number of groups without changing grouplist.
Overallocating one entry is not so bad.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@methane It's easy to fix by surrounding:

n = getgroups(n, grouplist);
if (n == -1) {
    PyMem_Free(grouplist);
    return posix_error();
}

with: if (n > 0) { ... }.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I modified my PR to not call getgroups() if n=0. I also cleaned up the code to make it easier to follow.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@arhadthedev: See my updated PR. I rewrote the code more it more "flat", easier to follow for the most common path.

@vstinner vstinner merged commit e02c475 into python:main Feb 26, 2022
@vstinner vstinner deleted the getgroup branch February 26, 2022 23:14
@vstinner
Copy link
Member Author

Thanks for the review @methane! The old code was easy to misunderstand. IMO having a special code path for n == 0 makes the code simpler to review but also more reliable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants