Skip to content

bpo-39395: Clear env vars set by Python at exit #18078

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

Closed
wants to merge 1 commit into from
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Environment variables set by :data:`os.environ` and :func:`os.putenv` are now
cleared at exit. Python manages their memory which is released at exit.
26 changes: 26 additions & 0 deletions Modules/posixmodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -2101,10 +2101,36 @@ statresult_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
return (PyObject*)result;
}


#ifdef HAVE_UNSETENV
/* bpo-39395: Clear environment variables set by os.environ and os.putenv()
before clearing posix_putenv_garbage dictionary. Python manages the
variables memory which is cleared at exit. */
static void
posix_unset_envvars(PyObject *posix_putenv_garbage)
{
if (posix_putenv_garbage == NULL) {
return;
}
assert(PyDict_CheckExact(posix_putenv_garbage));

Py_ssize_t pos = 0;
PyObject *key, *value;
while (PyDict_Next(posix_putenv_garbage, &pos, &key, &value)) {
/* ignore unsetenv() error */
unsetenv(PyBytes_AS_STRING(key));
}
}
#endif


static int
_posix_clear(PyObject *module)
{
Py_CLEAR(_posixstate(module)->billion);
#ifdef HAVE_UNSETENV
posix_unset_envvars(_posixstate(module)->posix_putenv_garbage);
#endif
Py_CLEAR(_posixstate(module)->posix_putenv_garbage);
Copy link
Contributor

@eduardo-elizondo eduardo-elizondo Jan 20, 2020

Choose a reason for hiding this comment

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

Given that you are already doing these fixes around this, posix_putenv_garbage should also be guarded by HAVE_PUTENV (check its initialization in the init function).

Py_CLEAR(_posixstate(module)->DirEntryType);
Py_CLEAR(_posixstate(module)->ScandirIteratorType);
Expand Down