Skip to content

Commit 77bdeeb

Browse files
[3.12] gh-105436: The environment block should end with two null wchar_t values (GH-105495) (#105700)
gh-105436: The environment block should end with two null wchar_t values (GH-105495) (cherry picked from commit 4f7d3b6) Co-authored-by: Dora203 <[email protected]>
1 parent 2eed1f5 commit 77bdeeb

File tree

3 files changed

+22
-1
lines changed

3 files changed

+22
-1
lines changed

Lib/test/test_subprocess.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1692,6 +1692,13 @@ def test_run_with_pathlike_path_and_arguments(self):
16921692
res = subprocess.run(args)
16931693
self.assertEqual(res.returncode, 57)
16941694

1695+
@unittest.skipUnless(mswindows, "Maybe test trigger a leak on Ubuntu")
1696+
def test_run_with_an_empty_env(self):
1697+
# gh-105436: fix subprocess.run(..., env={}) broken on Windows
1698+
args = [sys.executable, "-c", 'import sys; sys.exit(57)']
1699+
res = subprocess.run(args, env={})
1700+
self.assertEqual(res.returncode, 57)
1701+
16951702
def test_capture_output(self):
16961703
cp = self.run_python(("import sys;"
16971704
"sys.stdout.write('BDFL'); "
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Ensure that an empty environment block is terminated by two null characters,
2+
as is required by Windows.

Modules/_winapi.c

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -796,6 +796,17 @@ getenvironment(PyObject* environment)
796796
}
797797

798798
envsize = PyList_GET_SIZE(keys);
799+
800+
if (envsize == 0) {
801+
// A environment block must be terminated by two null characters --
802+
// one for the last string and one for the block.
803+
buffer = PyMem_Calloc(2, sizeof(wchar_t));
804+
if (!buffer) {
805+
PyErr_NoMemory();
806+
}
807+
goto cleanup;
808+
}
809+
799810
if (PyList_GET_SIZE(values) != envsize) {
800811
PyErr_SetString(PyExc_RuntimeError,
801812
"environment changed size during iteration");
@@ -869,7 +880,8 @@ getenvironment(PyObject* environment)
869880
*p++ = L'\0';
870881
assert(p == end);
871882

872-
error:
883+
cleanup:
884+
error:
873885
Py_XDECREF(keys);
874886
Py_XDECREF(values);
875887
return buffer;

0 commit comments

Comments
 (0)