autoupdate
[gnulib.git] / lib / w32spawn.h
1 /* Auxiliary functions for the creation of subprocesses.  Native Woe32 API.
2    Copyright (C) 2001, 2003, 2004-2009 Free Software Foundation, Inc.
3    Written by Bruno Haible <bruno@clisp.org>, 2003.
4
5    This program is free software: you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 3 of the License, or
8    (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
17
18 /* Get declarations of the Win32 API functions.  */
19 #define WIN32_LEAN_AND_MEAN
20 #include <windows.h>
21
22 /* Get _get_osfhandle() and _open_osfhandle().  */
23 #include <io.h>
24
25 #include <stdbool.h>
26 #include <string.h>
27 #include <unistd.h>
28 #include <errno.h>
29
30 #include "xalloc.h"
31
32 /* Duplicates a file handle, making the copy uninheritable.
33    Returns -1 for a file handle that is equivalent to closed.  */
34 static int
35 dup_noinherit (int fd)
36 {
37   HANDLE curr_process = GetCurrentProcess ();
38   HANDLE old_handle = (HANDLE) _get_osfhandle (fd);
39   HANDLE new_handle;
40   int nfd;
41
42   if (old_handle == INVALID_HANDLE_VALUE)
43     /* fd is closed, or is open to no handle at all.
44        We cannot duplicate fd in this case, because _open_osfhandle fails for
45        an INVALID_HANDLE_VALUE argument.  */
46     return -1;
47
48   if (!DuplicateHandle (curr_process,               /* SourceProcessHandle */
49                         old_handle,                 /* SourceHandle */
50                         curr_process,               /* TargetProcessHandle */
51                         (PHANDLE) &new_handle,      /* TargetHandle */
52                         (DWORD) 0,                  /* DesiredAccess */
53                         FALSE,                      /* InheritHandle */
54                         DUPLICATE_SAME_ACCESS))     /* Options */
55     error (EXIT_FAILURE, 0, _("DuplicateHandle failed with error code 0x%08x"),
56            (unsigned int) GetLastError ());
57
58   nfd = _open_osfhandle ((long) new_handle, O_BINARY | O_NOINHERIT);
59   if (nfd < 0)
60     error (EXIT_FAILURE, errno, _("_open_osfhandle failed"));
61
62   return nfd;
63 }
64
65 /* Returns a file descriptor equivalent to FD, except that the resulting file
66    descriptor is none of STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO.
67    FD must be open and non-inheritable.  The result will be non-inheritable as
68    well.
69    If FD < 0, FD itself is returned.  */
70 static int
71 fd_safer_noinherit (int fd)
72 {
73   if (STDIN_FILENO <= fd && fd <= STDERR_FILENO)
74     {
75       /* The recursion depth is at most 3.  */
76       int nfd = fd_safer_noinherit (dup_noinherit (fd));
77       int saved_errno = errno;
78       close (fd);
79       errno = saved_errno;
80       return nfd;
81     }
82   return fd;
83 }
84
85 /* Duplicates a file handle, making the copy uninheritable and ensuring the
86    result is none of STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO.
87    Returns -1 for a file handle that is equivalent to closed.  */
88 static int
89 dup_safer_noinherit (int fd)
90 {
91   return fd_safer_noinherit (dup_noinherit (fd));
92 }
93
94 /* Undoes the effect of TEMPFD = dup_safer_noinherit (ORIGFD);  */
95 static void
96 undup_safer_noinherit (int tempfd, int origfd)
97 {
98   if (tempfd >= 0)
99     {
100       if (dup2 (tempfd, origfd) < 0)
101         error (EXIT_FAILURE, errno, _("cannot restore fd %d: dup2 failed"),
102                origfd);
103       close (tempfd);
104     }
105   else
106     {
107       /* origfd was closed or open to no handle at all.  Set it to a closed
108          state.  This is (nearly) equivalent to the original state.  */
109       close (origfd);
110     }
111 }
112
113 /* Prepares an argument vector before calling spawn().
114    Note that spawn() does not by itself call the command interpreter
115      (getenv ("COMSPEC") != NULL ? getenv ("COMSPEC") :
116       ({ OSVERSIONINFO v; v.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
117          GetVersionEx(&v);
118          v.dwPlatformId == VER_PLATFORM_WIN32_NT;
119       }) ? "cmd.exe" : "command.com").
120    Instead it simply concatenates the arguments, separated by ' ', and calls
121    CreateProcess().  We must quote the arguments since Win32 CreateProcess()
122    interprets characters like ' ', '\t', '\\', '"' (but not '<' and '>') in a
123    special way:
124    - Space and tab are interpreted as delimiters. They are not treated as
125      delimiters if they are surrounded by double quotes: "...".
126    - Unescaped double quotes are removed from the input. Their only effect is
127      that within double quotes, space and tab are treated like normal
128      characters.
129    - Backslashes not followed by double quotes are not special.
130    - But 2*n+1 backslashes followed by a double quote become
131      n backslashes followed by a double quote (n >= 0):
132        \" -> "
133        \\\" -> \"
134        \\\\\" -> \\"
135  */
136 #define SHELL_SPECIAL_CHARS "\"\\ \001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037"
137 #define SHELL_SPACE_CHARS " \001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037"
138 static char **
139 prepare_spawn (char **argv)
140 {
141   size_t argc;
142   char **new_argv;
143   size_t i;
144
145   /* Count number of arguments.  */
146   for (argc = 0; argv[argc] != NULL; argc++)
147     ;
148
149   /* Allocate new argument vector.  */
150   new_argv = XNMALLOC (1 + argc + 1, char *);
151
152   /* Add an element upfront that can be used when argv[0] turns out to be a
153      script, not a program.
154      On Unix, this would be "/bin/sh". On native Windows, "sh" is actually
155      "sh.exe".  We have to omit the directory part and rely on the search in
156      PATH, because the mingw "mount points" are not visible inside Win32
157      CreateProcess().  */
158   *new_argv++ = "sh.exe";
159
160   /* Put quoted arguments into the new argument vector.  */
161   for (i = 0; i < argc; i++)
162     {
163       const char *string = argv[i];
164
165       if (string[0] == '\0')
166         new_argv[i] = xstrdup ("\"\"");
167       else if (strpbrk (string, SHELL_SPECIAL_CHARS) != NULL)
168         {
169           bool quote_around = (strpbrk (string, SHELL_SPACE_CHARS) != NULL);
170           size_t length;
171           unsigned int backslashes;
172           const char *s;
173           char *quoted_string;
174           char *p;
175
176           length = 0;
177           backslashes = 0;
178           if (quote_around)
179             length++;
180           for (s = string; *s != '\0'; s++)
181             {
182               char c = *s;
183               if (c == '"')
184                 length += backslashes + 1;
185               length++;
186               if (c == '\\')
187                 backslashes++;
188               else
189                 backslashes = 0;
190             }
191           if (quote_around)
192             length += backslashes + 1;
193
194           quoted_string = (char *) xmalloc (length + 1);
195
196           p = quoted_string;
197           backslashes = 0;
198           if (quote_around)
199             *p++ = '"';
200           for (s = string; *s != '\0'; s++)
201             {
202               char c = *s;
203               if (c == '"')
204                 {
205                   unsigned int j;
206                   for (j = backslashes + 1; j > 0; j--)
207                     *p++ = '\\';
208                 }
209               *p++ = c;
210               if (c == '\\')
211                 backslashes++;
212               else
213                 backslashes = 0;
214             }
215           if (quote_around)
216             {
217               unsigned int j;
218               for (j = backslashes; j > 0; j--)
219                 *p++ = '\\';
220               *p++ = '"';
221             }
222           *p = '\0';
223
224           new_argv[i] = quoted_string;
225         }
226       else
227         new_argv[i] = (char *) string;
228     }
229   new_argv[argc] = NULL;
230
231   return new_argv;
232 }