Skip to content

Commit 261d0b4

Browse files
[3.11] gh-105436: The environment block should end with two null wchar_t values (GH-105495) (#105701)
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 f5b63ea commit 261d0b4

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
@@ -1690,6 +1690,13 @@ def test_run_with_pathlike_path_and_arguments(self):
16901690
res = subprocess.run(args)
16911691
self.assertEqual(res.returncode, 57)
16921692

1693+
@unittest.skipUnless(mswindows, "Maybe test trigger a leak on Ubuntu")
1694+
def test_run_with_an_empty_env(self):
1695+
# gh-105436: fix subprocess.run(..., env={}) broken on Windows
1696+
args = [sys.executable, "-c", 'import sys; sys.exit(57)']
1697+
res = subprocess.run(args, env={})
1698+
self.assertEqual(res.returncode, 57)
1699+
16931700
def test_capture_output(self):
16941701
cp = self.run_python(("import sys;"
16951702
"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
@@ -805,6 +805,17 @@ getenvironment(PyObject* environment)
805805
}
806806

807807
envsize = PyList_GET_SIZE(keys);
808+
809+
if (envsize == 0) {
810+
// A environment block must be terminated by two null characters --
811+
// one for the last string and one for the block.
812+
buffer = PyMem_Calloc(2, sizeof(wchar_t));
813+
if (!buffer) {
814+
PyErr_NoMemory();
815+
}
816+
goto cleanup;
817+
}
818+
808819
if (PyList_GET_SIZE(values) != envsize) {
809820
PyErr_SetString(PyExc_RuntimeError,
810821
"environment changed size during iteration");
@@ -878,7 +889,8 @@ getenvironment(PyObject* environment)
878889
*p++ = L'\0';
879890
assert(p == end);
880891

881-
error:
892+
cleanup:
893+
error:
882894
Py_XDECREF(keys);
883895
Py_XDECREF(values);
884896
return buffer;

0 commit comments

Comments
 (0)