Blame SOURCES/00196-avoid-double-close-of-pipes.patch

f63228
f63228
# HG changeset patch
f63228
# User Antoine Pitrou <solipsis@pitrou.net>
f63228
# Date 1377898693 -7200
f63228
# Node ID 43749cb6bdbd0fdab70f76cd171c3c02a3f600dd
f63228
# Parent  ba54011aa295004ad87438211fe3bb1568dd69ab
f63228
Issue #18851: Avoid a double close of subprocess pipes when the child process fails starting.
f63228
f63228
diff --git a/Lib/subprocess.py b/Lib/subprocess.py
f63228
--- a/Lib/subprocess.py
f63228
+++ b/Lib/subprocess.py
f63228
@@ -698,12 +698,12 @@ class Popen(object):
f63228
 
f63228
         (p2cread, p2cwrite,
f63228
          c2pread, c2pwrite,
f63228
-         errread, errwrite) = self._get_handles(stdin, stdout, stderr)
f63228
+         errread, errwrite), to_close = self._get_handles(stdin, stdout, stderr)
f63228
 
f63228
         try:
f63228
             self._execute_child(args, executable, preexec_fn, close_fds,
f63228
                                 cwd, env, universal_newlines,
f63228
-                                startupinfo, creationflags, shell,
f63228
+                                startupinfo, creationflags, shell, to_close,
f63228
                                 p2cread, p2cwrite,
f63228
                                 c2pread, c2pwrite,
f63228
                                 errread, errwrite)
f63228
@@ -711,18 +711,12 @@ class Popen(object):
f63228
             # Preserve original exception in case os.close raises.
f63228
             exc_type, exc_value, exc_trace = sys.exc_info()
f63228
 
f63228
-            to_close = []
f63228
-            # Only close the pipes we created.
f63228
-            if stdin == PIPE:
f63228
-                to_close.extend((p2cread, p2cwrite))
f63228
-            if stdout == PIPE:
f63228
-                to_close.extend((c2pread, c2pwrite))
f63228
-            if stderr == PIPE:
f63228
-                to_close.extend((errread, errwrite))
f63228
-
f63228
             for fd in to_close:
f63228
                 try:
f63228
-                    os.close(fd)
f63228
+                    if mswindows:
f63228
+                        fd.Close()
f63228
+                    else:
f63228
+                        os.close(fd)
f63228
                 except EnvironmentError:
f63228
                     pass
f63228
 
f63228
@@ -816,8 +810,9 @@ class Popen(object):
f63228
             """Construct and return tuple with IO objects:
f63228
             p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
f63228
             """
f63228
+            to_close = set()
f63228
             if stdin is None and stdout is None and stderr is None:
f63228
-                return (None, None, None, None, None, None)
f63228
+                return (None, None, None, None, None, None), to_close
f63228
 
f63228
             p2cread, p2cwrite = None, None
f63228
             c2pread, c2pwrite = None, None
f63228
@@ -835,6 +830,10 @@ class Popen(object):
f63228
                 # Assuming file-like object
f63228
                 p2cread = msvcrt.get_osfhandle(stdin.fileno())
f63228
             p2cread = self._make_inheritable(p2cread)
f63228
+            # We just duplicated the handle, it has to be closed at the end
f63228
+            to_close.add(p2cread)
f63228
+            if stdin == PIPE:
f63228
+                to_close.add(p2cwrite)
f63228
 
f63228
             if stdout is None:
f63228
                 c2pwrite = _subprocess.GetStdHandle(_subprocess.STD_OUTPUT_HANDLE)
f63228
@@ -848,6 +847,10 @@ class Popen(object):
f63228
                 # Assuming file-like object
f63228
                 c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
f63228
             c2pwrite = self._make_inheritable(c2pwrite)
f63228
+            # We just duplicated the handle, it has to be closed at the end
f63228
+            to_close.add(c2pwrite)
f63228
+            if stdout == PIPE:
f63228
+                to_close.add(c2pread)
f63228
 
f63228
             if stderr is None:
f63228
                 errwrite = _subprocess.GetStdHandle(_subprocess.STD_ERROR_HANDLE)
f63228
@@ -863,10 +866,14 @@ class Popen(object):
f63228
                 # Assuming file-like object
f63228
                 errwrite = msvcrt.get_osfhandle(stderr.fileno())
f63228
             errwrite = self._make_inheritable(errwrite)
f63228
+            # We just duplicated the handle, it has to be closed at the end
f63228
+            to_close.add(errwrite)
f63228
+            if stderr == PIPE:
f63228
+                to_close.add(errread)
f63228
 
f63228
             return (p2cread, p2cwrite,
f63228
                     c2pread, c2pwrite,
f63228
-                    errread, errwrite)
f63228
+                    errread, errwrite), to_close
f63228
 
f63228
 
f63228
         def _make_inheritable(self, handle):
f63228
@@ -895,7 +902,7 @@ class Popen(object):
f63228
 
f63228
         def _execute_child(self, args, executable, preexec_fn, close_fds,
f63228
                            cwd, env, universal_newlines,
f63228
-                           startupinfo, creationflags, shell,
f63228
+                           startupinfo, creationflags, shell, to_close,
f63228
                            p2cread, p2cwrite,
f63228
                            c2pread, c2pwrite,
f63228
                            errread, errwrite):
f63228
@@ -934,6 +941,10 @@ class Popen(object):
f63228
                     # kill children.
f63228
                     creationflags |= _subprocess.CREATE_NEW_CONSOLE
f63228
 
f63228
+            def _close_in_parent(fd):
f63228
+                fd.Close()
f63228
+                to_close.remove(fd)
f63228
+
f63228
             # Start the process
f63228
             try:
f63228
                 hp, ht, pid, tid = _subprocess.CreateProcess(executable, args,
f63228
@@ -958,11 +969,11 @@ class Popen(object):
f63228
                 # pipe will not close when the child process exits and the
f63228
                 # ReadFile will hang.
f63228
                 if p2cread is not None:
f63228
-                    p2cread.Close()
f63228
+                    _close_in_parent(p2cread)
f63228
                 if c2pwrite is not None:
f63228
-                    c2pwrite.Close()
f63228
+                    _close_in_parent(c2pwrite)
f63228
                 if errwrite is not None:
f63228
-                    errwrite.Close()
f63228
+                    _close_in_parent(errwrite)
f63228
 
f63228
             # Retain the process handle, but close the thread handle
f63228
             self._child_created = True
f63228
@@ -1088,6 +1099,7 @@ class Popen(object):
f63228
             """Construct and return tuple with IO objects:
f63228
             p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
f63228
             """
f63228
+            to_close = set()
f63228
             p2cread, p2cwrite = None, None
f63228
             c2pread, c2pwrite = None, None
f63228
             errread, errwrite = None, None
f63228
@@ -1096,6 +1108,7 @@ class Popen(object):
f63228
                 pass
f63228
             elif stdin == PIPE:
f63228
                 p2cread, p2cwrite = self.pipe_cloexec()
f63228
+                to_close.update((p2cread, p2cwrite))
f63228
             elif isinstance(stdin, int):
f63228
                 p2cread = stdin
f63228
             else:
f63228
@@ -1106,6 +1119,7 @@ class Popen(object):
f63228
                 pass
f63228
             elif stdout == PIPE:
f63228
                 c2pread, c2pwrite = self.pipe_cloexec()
f63228
+                to_close.update((c2pread, c2pwrite))
f63228
             elif isinstance(stdout, int):
f63228
                 c2pwrite = stdout
f63228
             else:
f63228
@@ -1116,6 +1130,7 @@ class Popen(object):
f63228
                 pass
f63228
             elif stderr == PIPE:
f63228
                 errread, errwrite = self.pipe_cloexec()
f63228
+                to_close.update((errread, errwrite))
f63228
             elif stderr == STDOUT:
f63228
                 errwrite = c2pwrite
f63228
             elif isinstance(stderr, int):
f63228
@@ -1126,7 +1141,7 @@ class Popen(object):
f63228
 
f63228
             return (p2cread, p2cwrite,
f63228
                     c2pread, c2pwrite,
f63228
-                    errread, errwrite)
f63228
+                    errread, errwrite), to_close
f63228
 
f63228
 
f63228
         def _set_cloexec_flag(self, fd, cloexec=True):
f63228
@@ -1170,7 +1185,7 @@ class Popen(object):
f63228
 
f63228
         def _execute_child(self, args, executable, preexec_fn, close_fds,
f63228
                            cwd, env, universal_newlines,
f63228
-                           startupinfo, creationflags, shell,
f63228
+                           startupinfo, creationflags, shell, to_close,
f63228
                            p2cread, p2cwrite,
f63228
                            c2pread, c2pwrite,
f63228
                            errread, errwrite):
f63228
@@ -1189,6 +1204,10 @@ class Popen(object):
f63228
             if executable is None:
f63228
                 executable = args[0]
f63228
 
f63228
+            def _close_in_parent(fd):
f63228
+                os.close(fd)
f63228
+                to_close.remove(fd)
f63228
+
f63228
             # For transferring possible exec failure from child to parent
f63228
             # The first char specifies the exception type: 0 means
f63228
             # OSError, 1 means some other error.
f63228
@@ -1283,17 +1302,17 @@ class Popen(object):
f63228
                     # be sure the FD is closed no matter what
f63228
                     os.close(errpipe_write)
f63228
 
f63228
-                if p2cread is not None and p2cwrite is not None:
f63228
-                    os.close(p2cread)
f63228
-                if c2pwrite is not None and c2pread is not None:
f63228
-                    os.close(c2pwrite)
f63228
-                if errwrite is not None and errread is not None:
f63228
-                    os.close(errwrite)
f63228
-
f63228
                 # Wait for exec to fail or succeed; possibly raising exception
f63228
                 # Exception limited to 1M
f63228
                 data = _eintr_retry_call(os.read, errpipe_read, 1048576)
f63228
             finally:
f63228
+                if p2cread is not None and p2cwrite is not None:
f63228
+                    _close_in_parent(p2cread)
f63228
+                if c2pwrite is not None and c2pread is not None:
f63228
+                    _close_in_parent(c2pwrite)
f63228
+                if errwrite is not None and errread is not None:
f63228
+                    _close_in_parent(errwrite)
f63228
+
f63228
                 # be sure the FD is closed no matter what
f63228
                 os.close(errpipe_read)
f63228
 
f63228
diff --git a/Lib/test/test_subprocess.py b/Lib/test/test_subprocess.py
f63228
--- a/Lib/test/test_subprocess.py
f63228
+++ b/Lib/test/test_subprocess.py
f63228
@@ -14,6 +14,10 @@ try:
f63228
     import resource
f63228
 except ImportError:
f63228
     resource = None
f63228
+try:
f63228
+    import threading
f63228
+except ImportError:
f63228
+    threading = None
f63228
 
f63228
 mswindows = (sys.platform == "win32")
f63228
 
f63228
@@ -629,6 +633,36 @@ class ProcessTestCase(BaseTestCase):
f63228
             if c.exception.errno not in (errno.ENOENT, errno.EACCES):
f63228
                 raise c.exception
f63228
 
f63228
+    @unittest.skipIf(threading is None, "threading required")
f63228
+    def test_double_close_on_error(self):
f63228
+        # Issue #18851
f63228
+        fds = []
f63228
+        def open_fds():
f63228
+            for i in range(20):
f63228
+                fds.extend(os.pipe())
f63228
+                time.sleep(0.001)
f63228
+        t = threading.Thread(target=open_fds)
f63228
+        t.start()
f63228
+        try:
f63228
+            with self.assertRaises(EnvironmentError):
f63228
+                subprocess.Popen(['nonexisting_i_hope'],
f63228
+                                 stdin=subprocess.PIPE,
f63228
+                                 stdout=subprocess.PIPE,
f63228
+                                 stderr=subprocess.PIPE)
f63228
+        finally:
f63228
+            t.join()
f63228
+            exc = None
f63228
+            for fd in fds:
f63228
+                # If a double close occurred, some of those fds will
f63228
+                # already have been closed by mistake, and os.close()
f63228
+                # here will raise.
f63228
+                try:
f63228
+                    os.close(fd)
f63228
+                except OSError as e:
f63228
+                    exc = e
f63228
+            if exc is not None:
f63228
+                raise exc
f63228
+
f63228
     def test_handles_closed_on_exception(self):
f63228
         # If CreateProcess exits with an error, ensure the
f63228
         # duplicate output handles are released
f63228
@@ -783,7 +817,7 @@ class POSIXProcessTestCase(BaseTestCase)
f63228
 
f63228
         def _execute_child(
f63228
                 self, args, executable, preexec_fn, close_fds, cwd, env,
f63228
-                universal_newlines, startupinfo, creationflags, shell,
f63228
+                universal_newlines, startupinfo, creationflags, shell, to_close,
f63228
                 p2cread, p2cwrite,
f63228
                 c2pread, c2pwrite,
f63228
                 errread, errwrite):
f63228
@@ -791,7 +825,7 @@ class POSIXProcessTestCase(BaseTestCase)
f63228
                 subprocess.Popen._execute_child(
f63228
                         self, args, executable, preexec_fn, close_fds,
f63228
                         cwd, env, universal_newlines,
f63228
-                        startupinfo, creationflags, shell,
f63228
+                        startupinfo, creationflags, shell, to_close,
f63228
                         p2cread, p2cwrite,
f63228
                         c2pread, c2pwrite,
f63228
                         errread, errwrite)