win32: Fix warning
[platform/upstream/glib.git] / glib / gspawn-win32-helper.c
1 /* gspawn-win32-helper.c - Helper program for process launching on Win32.
2  *
3  *  Copyright 2000 Red Hat, Inc.
4  *  Copyright 2000 Tor Lillqvist
5  *
6  * GLib is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public License as
8  * published by the Free Software Foundation; either version 2 of the
9  * License, or (at your option) any later version.
10  *
11  * GLib is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with GLib; see the file COPYING.LIB.  If not, write
18  * to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19  * Boston, MA 02111-1307, USA.
20  */
21
22 #include "config.h"
23
24 #include <fcntl.h>
25
26 /* For _CrtSetReportMode, we don't want Windows CRT (2005 and later)
27  * to terminate the process if a bad file descriptor is passed into
28  * _get_osfhandle.  The newer MS CRT's are picky
29  * on double close()'s and bad file descriptors.
30  */
31 #if (defined (_MSC_VER) && _MSC_VER >= 1400)
32 #include <crtdbg.h>
33 #endif
34
35 #undef G_LOG_DOMAIN
36 #include "glib.h"
37 #define GSPAWN_HELPER
38 #include "gspawn-win32.c"       /* For shared definitions */
39
40
41 static void
42 write_err_and_exit (gint    fd,
43                     gintptr msg)
44 {
45   gintptr en = errno;
46   
47   write (fd, &msg, sizeof(gintptr));
48   write (fd, &en, sizeof(gintptr));
49   
50   _exit (1);
51 }
52
53 #ifdef __GNUC__
54 #  ifndef _stdcall
55 #    define _stdcall  __attribute__((stdcall))
56 #  endif
57 #endif
58
59 /* We build gspawn-win32-helper.exe as a Windows GUI application
60  * to avoid any temporarily flashing console windows in case
61  * the gspawn function is invoked by a GUI program. Thus, no main()
62  * but a WinMain(). We do, however, still use argc and argv tucked
63  * away in the global __argc and __argv by the C runtime startup code.
64  */
65
66 /* Info peeked from mingw runtime's source code. __wgetmainargs() is a
67  * function to get the program's argv in wide char format.
68  */
69
70 typedef struct {
71   int newmode;
72 } _startupinfo;
73
74 extern void __wgetmainargs(int *argc,
75                            wchar_t ***wargv,
76                            wchar_t ***wenviron,
77                            int expand_wildcards,
78                            _startupinfo *startupinfo);
79
80 /* Copy of protect_argv that handles wchar_t strings */
81
82 static gint
83 protect_wargv (wchar_t  **wargv,
84                wchar_t ***new_wargv)
85 {
86   gint i;
87   gint argc = 0;
88   
89   while (wargv[argc])
90     ++argc;
91   *new_wargv = g_new (wchar_t *, argc+1);
92
93   /* Quote each argv element if necessary, so that it will get
94    * reconstructed correctly in the C runtime startup code.  Note that
95    * the unquoting algorithm in the C runtime is really weird, and
96    * rather different than what Unix shells do. See stdargv.c in the C
97    * runtime sources (in the Platform SDK, in src/crt).
98    *
99    * Note that an new_wargv[0] constructed by this function should
100    * *not* be passed as the filename argument to a _wspawn* or _wexec*
101    * family function. That argument should be the real file name
102    * without any quoting.
103    */
104   for (i = 0; i < argc; i++)
105     {
106       wchar_t *p = wargv[i];
107       wchar_t *q;
108       gint len = 0;
109       gboolean need_dblquotes = FALSE;
110       while (*p)
111         {
112           if (*p == ' ' || *p == '\t')
113             need_dblquotes = TRUE;
114           else if (*p == '"')
115             len++;
116           else if (*p == '\\')
117             {
118               wchar_t *pp = p;
119               while (*pp && *pp == '\\')
120                 pp++;
121               if (*pp == '"')
122                 len++;
123             }
124           len++;
125           p++;
126         }
127
128       q = (*new_wargv)[i] = g_new (wchar_t, len + need_dblquotes*2 + 1);
129       p = wargv[i];
130
131       if (need_dblquotes)
132         *q++ = '"';
133
134       while (*p)
135         {
136           if (*p == '"')
137             *q++ = '\\';
138           else if (*p == '\\')
139             {
140               wchar_t *pp = p;
141               while (*pp && *pp == '\\')
142                 pp++;
143               if (*pp == '"')
144                 *q++ = '\\';
145             }
146           *q++ = *p;
147           p++;
148         }
149
150       if (need_dblquotes)
151         *q++ = '"';
152       *q++ = '\0';
153     }
154   (*new_wargv)[argc] = NULL;
155
156   return argc;
157 }
158
159 #if (defined (_MSC_VER) && _MSC_VER >= 1400)
160 /*
161  * This is the (empty) invalid parameter handler
162  * that is used for Visual C++ 2005 (and later) builds
163  * so that we can use this instead of the system automatically
164  * aborting the process, as the newer MS CRTs are more picky
165  * about double close()'s and bad/invalid file descriptors.
166  *
167  * This is necessary as we use _get_oshandle() to check the validity
168  * of the file descriptors as we close them, so when an invalid file
169  * descriptor is passed into that function as we check on it, we get
170  * -1 as the result, instead of the gspawn helper program aborting.
171  */
172 void myInvalidParameterHandler(
173    const wchar_t * expression,
174    const wchar_t * function,
175    const wchar_t * file,
176    unsigned int line,
177    uintptr_t pReserved
178 )
179 {
180   return;
181 }
182 #endif
183
184
185 #ifndef HELPER_CONSOLE
186 int _stdcall
187 WinMain (struct HINSTANCE__ *hInstance,
188          struct HINSTANCE__ *hPrevInstance,
189          char               *lpszCmdLine,
190          int                 nCmdShow)
191 #else
192 int
193 main (int ignored_argc, char **ignored_argv)
194 #endif
195 {
196   int child_err_report_fd = -1;
197   int helper_sync_fd = -1;
198   int i;
199   int fd;
200   int mode;
201   gintptr handle;
202   int saved_errno;
203   gintptr no_error = CHILD_NO_ERROR;
204   gint argv_zero_offset = ARG_PROGRAM;
205   wchar_t **new_wargv;
206   int argc;
207   wchar_t **wargv, **wenvp;
208   _startupinfo si = { 0 };
209   char c;
210
211   /* store up the file descriptors to close */
212   GSList *fd_toclose = NULL;
213   GSList *last_item = NULL;
214
215 #if (defined (_MSC_VER) && _MSC_VER >= 1400)
216   /* set up our empty invalid parameter handler */
217   _invalid_parameter_handler oldHandler, newHandler;
218   newHandler = myInvalidParameterHandler;
219   oldHandler = _set_invalid_parameter_handler(newHandler);
220
221   /* Disable the message box for assertions. */
222   _CrtSetReportMode(_CRT_ASSERT, 0);
223 #endif
224
225
226   g_assert (__argc >= ARG_COUNT);
227
228   /* Fetch the wide-char argument vector */
229   __wgetmainargs (&argc, &wargv, &wenvp, 0, &si);
230
231   /* We still have the system codepage args in __argv. We can look
232    * at the first args in which gspawn-win32.c passes us flags and
233    * fd numbers in __argv, as we know those are just ASCII anyway.
234    */
235   g_assert (argc == __argc);
236
237   /* argv[ARG_CHILD_ERR_REPORT] is the file descriptor number onto
238    * which write error messages.
239    */
240   child_err_report_fd = atoi (__argv[ARG_CHILD_ERR_REPORT]);
241
242   /* Hack to implement G_SPAWN_FILE_AND_ARGV_ZERO. If
243    * argv[ARG_CHILD_ERR_REPORT] is suffixed with a '#' it means we get
244    * the program to run and its argv[0] separately.
245    */
246   if (__argv[ARG_CHILD_ERR_REPORT][strlen (__argv[ARG_CHILD_ERR_REPORT]) - 1] == '#')
247     argv_zero_offset++;
248
249   /* argv[ARG_HELPER_SYNC] is the file descriptor number we read a
250    * byte that tells us it is OK to exit. We have to wait until the
251    * parent allows us to exit, so that the parent has had time to
252    * duplicate the process handle we sent it. Duplicating a handle
253    * from another process works only if that other process exists.
254    */
255   helper_sync_fd = atoi (__argv[ARG_HELPER_SYNC]);
256
257   /* argv[ARG_STDIN..ARG_STDERR] are the file descriptor numbers that
258    * should be dup2'd to 0, 1 and 2. '-' if the corresponding fd
259    * should be left alone, and 'z' if it should be connected to the
260    * bit bucket NUL:.
261    */
262   if (__argv[ARG_STDIN][0] == '-')
263     ; /* Nothing */
264   else if (__argv[ARG_STDIN][0] == 'z')
265     {
266       fd = open ("NUL:", O_RDONLY);
267       if (fd != 0)
268         {
269           dup2 (fd, 0);
270           fd_toclose = g_slist_append (fd_toclose, GINT_TO_POINTER (fd));
271         }
272     }
273   else
274     {
275       fd = atoi (__argv[ARG_STDIN]);
276       if (fd != 0)
277         {
278           dup2 (fd, 0);
279           fd_toclose = g_slist_append (fd_toclose, GINT_TO_POINTER (fd));
280         }
281     }
282
283   if (__argv[ARG_STDOUT][0] == '-')
284     ; /* Nothing */
285   else if (__argv[ARG_STDOUT][0] == 'z')
286     {
287       fd = open ("NUL:", O_WRONLY);
288       if (fd != 1)
289         {
290           dup2 (fd, 1);
291           fd_toclose = g_slist_append (fd_toclose, GINT_TO_POINTER (fd));
292         }
293     }
294   else
295     {
296       fd = atoi (__argv[ARG_STDOUT]);
297       if (fd != 1)
298         {
299           dup2 (fd, 1);
300           fd_toclose = g_slist_append (fd_toclose, GINT_TO_POINTER (fd));
301         }
302     }
303
304   if (__argv[ARG_STDERR][0] == '-')
305     ; /* Nothing */
306   else if (__argv[ARG_STDERR][0] == 'z')
307     {
308       fd = open ("NUL:", O_WRONLY);
309       if (fd != 2)
310         {
311           dup2 (fd, 2);
312           fd_toclose = g_slist_append (fd_toclose, GINT_TO_POINTER (fd));
313         }
314     }
315   else
316     {
317       fd = atoi (__argv[ARG_STDERR]);
318       if (fd != 2)
319         {
320           dup2 (fd, 2);
321           fd_toclose = g_slist_append (fd_toclose, GINT_TO_POINTER (fd));
322         }
323     }
324
325   /* __argv[ARG_WORKING_DIRECTORY] is the directory in which to run the
326    * process.  If "-", don't change directory.
327    */
328   if (__argv[ARG_WORKING_DIRECTORY][0] == '-' &&
329       __argv[ARG_WORKING_DIRECTORY][1] == 0)
330     ; /* Nothing */
331   else if (_wchdir (wargv[ARG_WORKING_DIRECTORY]) < 0)
332     write_err_and_exit (child_err_report_fd, CHILD_CHDIR_FAILED);
333
334   /* __argv[ARG_CLOSE_DESCRIPTORS] is "y" if file descriptors from 3
335    *  upwards should be closed
336    */
337   if (__argv[ARG_CLOSE_DESCRIPTORS][0] == 'y')
338     for (i = 3; i < 1000; i++)  /* FIXME real limit? */
339       if (i != child_err_report_fd && i != helper_sync_fd)
340         if (_get_osfhandle (i) != -1)
341           fd_toclose = g_slist_append (fd_toclose, GINT_TO_POINTER (i));
342
343   /* ...so we won't get the nasty off-by-1 file descriptor leak */
344   fd_toclose = g_slist_append (fd_toclose, NULL);
345   last_item = g_slist_last (fd_toclose);
346
347   /* now close all the file descriptors as necessary */
348   if (fd_toclose != NULL && last_item != NULL)
349   {
350     for ( ; fd_toclose != last_item; fd_toclose = fd_toclose->next)
351       close (GPOINTER_TO_INT(fd_toclose->data));
352   }
353   g_slist_free (last_item);
354   g_slist_free (fd_toclose);
355
356
357   /* We don't want our child to inherit the error report and
358    * helper sync fds.
359    */
360   child_err_report_fd = dup_noninherited (child_err_report_fd, _O_WRONLY);
361   helper_sync_fd = dup_noninherited (helper_sync_fd, _O_RDONLY);
362
363   /* __argv[ARG_WAIT] is "w" to wait for the program to exit */
364   if (__argv[ARG_WAIT][0] == 'w')
365     mode = P_WAIT;
366   else
367     mode = P_NOWAIT;
368
369   /* __argv[ARG_USE_PATH] is "y" to use PATH, otherwise not */
370
371   /* __argv[ARG_PROGRAM] is executable file to run,
372    * __argv[argv_zero_offset]... is its argv. argv_zero_offset equals
373    * ARG_PROGRAM unless G_SPAWN_FILE_AND_ARGV_ZERO was used, in which
374    * case we have a separate executable name and argv[0].
375    */
376
377   /* For the program name passed to spawnv(), don't use the quoted
378    * version.
379    */
380   protect_wargv (wargv + argv_zero_offset, &new_wargv);
381
382   if (__argv[ARG_USE_PATH][0] == 'y')
383     handle = _wspawnvp (mode, wargv[ARG_PROGRAM], (const wchar_t **) new_wargv);
384   else
385     handle = _wspawnv (mode, wargv[ARG_PROGRAM], (const wchar_t **) new_wargv);
386
387   saved_errno = errno;
388
389   if (handle == -1 && saved_errno != 0)
390     write_err_and_exit (child_err_report_fd, CHILD_SPAWN_FAILED);
391
392   write (child_err_report_fd, &no_error, sizeof (no_error));
393   write (child_err_report_fd, &handle, sizeof (handle));
394
395   read (helper_sync_fd, &c, 1);
396
397   return 0;
398 }