Skip to content
Open
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
28 changes: 28 additions & 0 deletions Lib/test/test_os/test_os.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,34 @@ def test_closerange(self):
os.closerange(first, first + 2)
self.assertRaises(OSError, os.write, first, b"a")

@support.requires_subprocess()
def test_closerange_empty(self):
# Run in a subprocess: a regression could close the standard streams
# and the test runner's own file descriptors.
code = textwrap.dedent("""\
import os
import sys

fd = os.open(os.devnull, os.O_RDONLY)
try:
result = os.closerange(int(sys.argv[1]), int(sys.argv[2]))
os.fstat(fd)
except BaseException:
os._exit(1)
os._exit(0 if result is None else 2)
""")
int_min = -(1 << (struct.calcsize('i') * 8 - 1))
int_max = -int_min - 1
for low, high in ((0, 0), (1, 0), (10, 5), (-1, 0), (-2, -1),
(-1, -1), (int_min, int_min), (0, int_min),
(int_max, int_max)):
with self.subTest(low=low, high=high):
proc = subprocess.run(
[sys.executable, '-I', '-c', code, str(low), str(high)],
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, timeout=support.SHORT_TIMEOUT)
self.assertEqual(proc.returncode, 0)

@support.cpython_only
def test_rename(self):
path = os_helper.TESTFN
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix :func:`os.closerange` closing unrelated file descriptors for empty or
negative-only ranges on platforms using ``close_range()``.
5 changes: 4 additions & 1 deletion Modules/posixmodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -11895,7 +11895,10 @@ os_closerange_impl(PyObject *module, int fd_low, int fd_high)
/*[clinic end generated code: output=0ce5c20fcda681c2 input=5855a3d053ebd4ec]*/
{
Py_BEGIN_ALLOW_THREADS
_Py_closerange(fd_low, fd_high - 1);
/* Check the exclusive upper bound before converting it to inclusive. */
if (fd_high > 0 && fd_low < fd_high) {
_Py_closerange(fd_low, fd_high - 1);
}
Py_END_ALLOW_THREADS
Py_RETURN_NONE;
}
Expand Down
Loading