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

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