From 90e8da7dca92bf2955e5e3794c1dd2b7e4e1043f Mon Sep 17 00:00:00 2001 From: Ned Batchelder Date: Mon, 13 Jan 2020 08:30:30 -0500 Subject: [PATCH 1/2] bpo-39318: Catch a failure in NamedTemporaryFile to prevent leaking a descriptor This happened in the real world because someone mocked _TemporaryFileWrapper to raise an OSError. See https://nedbatchelder.com/blog/202001/bug_915_solved.html for more details. --- Lib/tempfile.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/Lib/tempfile.py b/Lib/tempfile.py index 448163f04380d5..dbc10a300f8799 100644 --- a/Lib/tempfile.py +++ b/Lib/tempfile.py @@ -543,12 +543,18 @@ def NamedTemporaryFile(mode='w+b', buffering=-1, encoding=None, file = _io.open(fd, mode, buffering=buffering, newline=newline, encoding=encoding, errors=errors) - return _TemporaryFileWrapper(file, name, delete) except BaseException: _os.unlink(name) _os.close(fd) raise + try: + return _TemporaryFileWrapper(file, name, delete) + except BaseException: + _os.unlink(name) + file.close() + raise + if _os.name != 'posix' or _sys.platform == 'cygwin': # On non-POSIX and Cygwin systems, assume that we cannot unlink a file # while it is open. From 6e5c7fbb2c808e6d0932e9d5a3e3a075f846de2d Mon Sep 17 00:00:00 2001 From: "blurb-it[bot]" <43283697+blurb-it[bot]@users.noreply.github.com> Date: Mon, 13 Jan 2020 13:36:07 +0000 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=93=9C=F0=9F=A4=96=20Added=20by=20blu?= =?UTF-8?q?rb=5Fit.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../NEWS.d/next/Library/2020-01-13-13-36-05.bpo-39318.236VwO.rst | 1 + 1 file changed, 1 insertion(+) create mode 100644 Misc/NEWS.d/next/Library/2020-01-13-13-36-05.bpo-39318.236VwO.rst diff --git a/Misc/NEWS.d/next/Library/2020-01-13-13-36-05.bpo-39318.236VwO.rst b/Misc/NEWS.d/next/Library/2020-01-13-13-36-05.bpo-39318.236VwO.rst new file mode 100644 index 00000000000000..7ce343179c3ba6 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2020-01-13-13-36-05.bpo-39318.236VwO.rst @@ -0,0 +1 @@ +Fix a file descriptor leak in NamedTemporaryFile under unusual circumstances. \ No newline at end of file