Fix problems on 64-bit Windows. Avoid warnings, some of which indicated
[platform/upstream/glib.git] / glib / gspawn-win32.c
1 /* gspawn-win32.c - Process launching on Win32
2  *
3  *  Copyright 2000 Red Hat, Inc.
4  *  Copyright 2003 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 /*
23  * Implementation details on Win32.
24  *
25  * - There is no way to set the no-inherit flag for
26  *   a "file descriptor" in the MS C runtime. The flag is there,
27  *   and the dospawn() function uses it, but unfortunately
28  *   this flag can only be set when opening the file.
29  * - As there is no fork(), we cannot reliably change directory
30  *   before starting the child process. (There might be several threads
31  *   running, and the current directory is common for all threads.)
32  *
33  * Thus, we must in many cases use a helper program to handle closing
34  * of (inherited) file descriptors and changing of directory. The
35  * helper process is also needed if the standard input, standard
36  * output, or standard error of the process to be run are supposed to
37  * be redirected somewhere.
38  *
39  * The structure of the source code in this file is a mess, I know.
40  */
41
42 /* Define this to get some logging all the time */
43 /* #define G_SPAWN_WIN32_DEBUG */
44
45 #include "config.h"
46
47 #include "glib.h"
48 #include "gprintfint.h"
49 #include "glibintl.h"
50 #include "galias.h"
51
52 #include <string.h>
53 #include <stdlib.h>
54 #include <stdio.h>
55
56 #include <windows.h>
57 #include <errno.h>
58 #include <fcntl.h>
59 #include <io.h>
60 #include <process.h>
61 #include <direct.h>
62 #include <wchar.h>
63
64 #ifdef G_SPAWN_WIN32_DEBUG
65   static int debug = 1;
66   #define SETUP_DEBUG() /* empty */
67 #else
68   static int debug = -1;
69   #define SETUP_DEBUG()                                 \
70     G_STMT_START                                        \
71       {                                                 \
72         if (debug == -1)                                \
73           {                                             \
74             if (getenv ("G_SPAWN_WIN32_DEBUG") != NULL) \
75               debug = 1;                                \
76             else                                        \
77               debug = 0;                                \
78           }                                             \
79       }                                                 \
80     G_STMT_END
81 #endif
82
83 enum
84 {
85   CHILD_NO_ERROR,
86   CHILD_CHDIR_FAILED,
87   CHILD_SPAWN_FAILED,
88 };
89
90 enum {
91   ARG_CHILD_ERR_REPORT = 1,
92   ARG_HELPER_SYNC,
93   ARG_STDIN,
94   ARG_STDOUT,
95   ARG_STDERR,
96   ARG_WORKING_DIRECTORY,
97   ARG_CLOSE_DESCRIPTORS,
98   ARG_USE_PATH,
99   ARG_WAIT,
100   ARG_PROGRAM,
101   ARG_COUNT = ARG_PROGRAM
102 };
103
104 static int
105 dup_noninherited (int fd,
106                   int mode)
107 {
108   HANDLE filehandle;
109
110   DuplicateHandle (GetCurrentProcess (), (LPHANDLE) _get_osfhandle (fd),
111                    GetCurrentProcess (), &filehandle,
112                    0, FALSE, DUPLICATE_SAME_ACCESS);
113   close (fd);
114   return _open_osfhandle ((gssize) filehandle, mode | _O_NOINHERIT);
115 }
116
117 #ifndef GSPAWN_HELPER
118
119 #ifdef _WIN64
120 #define HELPER_PROCESS "gspawn-win64-helper"
121 #else
122 #define HELPER_PROCESS "gspawn-win32-helper"
123 #endif
124
125 static gchar *
126 protect_argv_string (const gchar *string)
127 {
128   const gchar *p = string;
129   gchar *retval, *q;
130   gint len = 0;
131   gboolean need_dblquotes = FALSE;
132   while (*p)
133     {
134       if (*p == ' ' || *p == '\t')
135         need_dblquotes = TRUE;
136       else if (*p == '"')
137         len++;
138       else if (*p == '\\')
139         {
140           const gchar *pp = p;
141           while (*pp && *pp == '\\')
142             pp++;
143           if (*pp == '"')
144             len++;
145         }
146       len++;
147       p++;
148     }
149   
150   q = retval = g_malloc (len + need_dblquotes*2 + 1);
151   p = string;
152
153   if (need_dblquotes)
154     *q++ = '"';
155   
156   while (*p)
157     {
158       if (*p == '"')
159         *q++ = '\\';
160       else if (*p == '\\')
161         {
162           const gchar *pp = p;
163           while (*pp && *pp == '\\')
164             pp++;
165           if (*pp == '"')
166             *q++ = '\\';
167         }
168       *q++ = *p;
169       p++;
170     }
171   
172   if (need_dblquotes)
173     *q++ = '"';
174   *q++ = '\0';
175
176   return retval;
177 }
178
179 static gint
180 protect_argv (gchar  **argv,
181               gchar ***new_argv)
182 {
183   gint i;
184   gint argc = 0;
185   
186   while (argv[argc])
187     ++argc;
188   *new_argv = g_new (gchar *, argc+1);
189
190   /* Quote each argv element if necessary, so that it will get
191    * reconstructed correctly in the C runtime startup code.  Note that
192    * the unquoting algorithm in the C runtime is really weird, and
193    * rather different than what Unix shells do. See stdargv.c in the C
194    * runtime sources (in the Platform SDK, in src/crt).
195    *
196    * Note that an new_argv[0] constructed by this function should
197    * *not* be passed as the filename argument to a spawn* or exec*
198    * family function. That argument should be the real file name
199    * without any quoting.
200    */
201   for (i = 0; i < argc; i++)
202     (*new_argv)[i] = protect_argv_string (argv[i]);
203
204   (*new_argv)[argc] = NULL;
205
206   return argc;
207 }
208
209 GQuark
210 g_spawn_error_quark (void)
211 {
212   return g_quark_from_static_string ("g-exec-error-quark");
213 }
214
215 gboolean
216 g_spawn_async_utf8 (const gchar          *working_directory,
217                     gchar               **argv,
218                     gchar               **envp,
219                     GSpawnFlags           flags,
220                     GSpawnChildSetupFunc  child_setup,
221                     gpointer              user_data,
222                     GPid                 *child_handle,
223                     GError              **error)
224 {
225   g_return_val_if_fail (argv != NULL, FALSE);
226   
227   return g_spawn_async_with_pipes_utf8 (working_directory,
228                                         argv, envp,
229                                         flags,
230                                         child_setup,
231                                         user_data,
232                                         child_handle,
233                                         NULL, NULL, NULL,
234                                         error);
235 }
236
237 /* Avoids a danger in threaded situations (calling close()
238  * on a file descriptor twice, and another thread has
239  * re-opened it since the first close)
240  */
241 static void
242 close_and_invalidate (gint *fd)
243 {
244   if (*fd < 0)
245     return;
246
247   close (*fd);
248   *fd = -1;
249 }
250
251 typedef enum
252 {
253   READ_FAILED = 0, /* FALSE */
254   READ_OK,
255   READ_EOF
256 } ReadResult;
257
258 static ReadResult
259 read_data (GString     *str,
260            GIOChannel  *iochannel,
261            GError     **error)
262 {
263   GIOStatus giostatus;
264   gsize bytes;
265   gchar buf[4096];
266
267  again:
268   
269   giostatus = g_io_channel_read_chars (iochannel, buf, sizeof (buf), &bytes, NULL);
270
271   if (bytes == 0)
272     return READ_EOF;
273   else if (bytes > 0)
274     {
275       g_string_append_len (str, buf, bytes);
276       return READ_OK;
277     }
278   else if (giostatus == G_IO_STATUS_AGAIN)
279     goto again;
280   else if (giostatus == G_IO_STATUS_ERROR)
281     {
282       g_set_error_literal (error, G_SPAWN_ERROR, G_SPAWN_ERROR_READ,
283                            _("Failed to read data from child process"));
284       
285       return READ_FAILED;
286     }
287   else
288     return READ_OK;
289 }
290
291 static gboolean
292 make_pipe (gint     p[2],
293            GError **error)
294 {
295   if (_pipe (p, 4096, _O_BINARY) < 0)
296     {
297       g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
298                    _("Failed to create pipe for communicating with child process (%s)"),
299                    g_strerror (errno));
300       return FALSE;
301     }
302   else
303     return TRUE;
304 }
305
306 /* The helper process writes a status report back to us, through a
307  * pipe, consisting of two ints.
308  */
309 static gboolean
310 read_helper_report (int      fd,
311                     gssize   report[2],
312                     GError **error)
313 {
314   gint bytes = 0;
315   
316   while (bytes < sizeof(gssize)*2)
317     {
318       gint chunk;
319
320       if (debug)
321         g_print ("%s:read_helper_report: read %" G_GSIZE_FORMAT "...\n",
322                  __FILE__,
323                  sizeof(gssize)*2 - bytes);
324
325       chunk = read (fd, ((gchar*)report) + bytes,
326                     sizeof(gssize)*2 - bytes);
327
328       if (debug)
329         g_print ("...got %d bytes\n", chunk);
330           
331       if (chunk < 0)
332         {
333           /* Some weird shit happened, bail out */
334               
335           g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
336                        _("Failed to read from child pipe (%s)"),
337                        g_strerror (errno));
338
339           return FALSE;
340         }
341       else if (chunk == 0)
342         {
343           g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
344                        _("Failed to read from child pipe (%s)"),
345                        "EOF");
346           break; /* EOF */
347         }
348       else
349         bytes += chunk;
350     }
351
352   if (bytes < sizeof(gssize)*2)
353     return FALSE;
354
355   return TRUE;
356 }
357
358 static void
359 set_child_error (gssize       report[2],
360                  const gchar *working_directory,
361                  GError     **error)
362 {
363   switch (report[0])
364     {
365     case CHILD_CHDIR_FAILED:
366       g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_CHDIR,
367                    _("Failed to change to directory '%s' (%s)"),
368                    working_directory,
369                    g_strerror (report[1]));
370       break;
371     case CHILD_SPAWN_FAILED:
372       g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
373                    _("Failed to execute child process (%s)"),
374                    g_strerror (report[1]));
375       break;
376     default:
377       g_assert_not_reached ();
378     }
379 }
380
381 static gboolean
382 utf8_charv_to_wcharv (char     **utf8_charv,
383                       wchar_t ***wcharv,
384                       int       *error_index,
385                       GError   **error)
386 {
387   wchar_t **retval = NULL;
388
389   *wcharv = NULL;
390   if (utf8_charv != NULL)
391     {
392       int n = 0, i;
393
394       while (utf8_charv[n])
395         n++;
396       retval = g_new (wchar_t *, n + 1);
397
398       for (i = 0; i < n; i++)
399         {
400           retval[i] = g_utf8_to_utf16 (utf8_charv[i], -1, NULL, NULL, error);
401           if (retval[i] == NULL)
402             {
403               if (error_index)
404                 *error_index = i;
405               while (i)
406                 g_free (retval[--i]);
407               g_free (retval);
408               return FALSE;
409             }
410         }
411             
412       retval[n] = NULL;
413     }
414   *wcharv = retval;
415   return TRUE;
416 }
417
418 static gboolean
419 do_spawn_directly (gint                 *exit_status,
420                    gboolean              do_return_handle,
421                    GSpawnFlags           flags,
422                    gchar               **argv,
423                    char                **envp,
424                    char                **protected_argv,
425                    GSpawnChildSetupFunc  child_setup,
426                    gpointer              user_data,
427                    GPid                 *child_handle,
428                    GError              **error)     
429 {
430   const int mode = (exit_status == NULL) ? P_NOWAIT : P_WAIT;
431   char **new_argv;
432   gssize rc = -1;
433   int saved_errno;
434   GError *conv_error = NULL;
435   gint conv_error_index;
436   wchar_t *wargv0, **wargv, **wenvp;
437
438   new_argv = (flags & G_SPAWN_FILE_AND_ARGV_ZERO) ? protected_argv + 1 : protected_argv;
439       
440   wargv0 = g_utf8_to_utf16 (argv[0], -1, NULL, NULL, &conv_error);
441   if (wargv0 == NULL)
442     {
443       g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
444                    _("Invalid program name: %s"),
445                    conv_error->message);
446       g_error_free (conv_error);
447       
448       return FALSE;
449     }
450   
451   if (!utf8_charv_to_wcharv (new_argv, &wargv, &conv_error_index, &conv_error))
452     {
453       g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
454                    _("Invalid string in argument vector at %d: %s"),
455                    conv_error_index, conv_error->message);
456       g_error_free (conv_error);
457       g_free (wargv0);
458
459       return FALSE;
460     }
461
462   if (!utf8_charv_to_wcharv (envp, &wenvp, NULL, &conv_error))
463     {
464       g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
465                    _("Invalid string in environment: %s"),
466                    conv_error->message);
467       g_error_free (conv_error);
468       g_free (wargv0);
469       g_strfreev ((gchar **) wargv);
470
471       return FALSE;
472     }
473
474   if (child_setup)
475     (* child_setup) (user_data);
476
477   if (flags & G_SPAWN_SEARCH_PATH)
478     if (wenvp != NULL)
479       rc = _wspawnvpe (mode, wargv0, (const wchar_t **) wargv, (const wchar_t **) wenvp);
480     else
481       rc = _wspawnvp (mode, wargv0, (const wchar_t **) wargv);
482   else
483     if (wenvp != NULL)
484       rc = _wspawnve (mode, wargv0, (const wchar_t **) wargv, (const wchar_t **) wenvp);
485     else
486       rc = _wspawnv (mode, wargv0, (const wchar_t **) wargv);
487
488   g_free (wargv0);
489   g_strfreev ((gchar **) wargv);
490   g_strfreev ((gchar **) wenvp);
491
492   saved_errno = errno;
493
494   if (rc == -1 && saved_errno != 0)
495     {
496       g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
497                    _("Failed to execute child process (%s)"),
498                    g_strerror (saved_errno));
499       return FALSE;
500     }
501
502   if (exit_status == NULL)
503     {
504       if (child_handle && do_return_handle)
505         *child_handle = (GPid) rc;
506       else
507         {
508           CloseHandle ((HANDLE) rc);
509           if (child_handle)
510             *child_handle = 0;
511         }
512     }
513   else
514     *exit_status = rc;
515
516   return TRUE;
517 }
518
519 static gboolean
520 do_spawn_with_pipes (gint                 *exit_status,
521                      gboolean              do_return_handle,
522                      const gchar          *working_directory,
523                      gchar               **argv,
524                      char                **envp,
525                      GSpawnFlags           flags,
526                      GSpawnChildSetupFunc  child_setup,
527                      gpointer              user_data,
528                      GPid                 *child_handle,
529                      gint                 *standard_input,
530                      gint                 *standard_output,
531                      gint                 *standard_error,
532                      gint                 *err_report,
533                      GError              **error)     
534 {
535   char **protected_argv;
536   char args[ARG_COUNT][10];
537   char **new_argv;
538   int i;
539   gssize rc = -1;
540   int saved_errno;
541   int argc;
542   int stdin_pipe[2] = { -1, -1 };
543   int stdout_pipe[2] = { -1, -1 };
544   int stderr_pipe[2] = { -1, -1 };
545   int child_err_report_pipe[2] = { -1, -1 };
546   int helper_sync_pipe[2] = { -1, -1 };
547   gssize helper_report[2];
548   static gboolean warned_about_child_setup = FALSE;
549   GError *conv_error = NULL;
550   gint conv_error_index;
551   gchar *helper_process;
552   CONSOLE_CURSOR_INFO cursor_info;
553   wchar_t *whelper, **wargv, **wenvp;
554   extern gchar *_glib_get_installation_directory (void);
555   gchar *glib_top;
556
557   if (child_setup && !warned_about_child_setup)
558     {
559       warned_about_child_setup = TRUE;
560       g_warning ("passing a child setup function to the g_spawn functions is pointless and dangerous on Win32");
561     }
562
563   argc = protect_argv (argv, &protected_argv);
564
565   if (!standard_input && !standard_output && !standard_error &&
566       (flags & G_SPAWN_CHILD_INHERITS_STDIN) &&
567       !(flags & G_SPAWN_STDOUT_TO_DEV_NULL) &&
568       !(flags & G_SPAWN_STDERR_TO_DEV_NULL) &&
569       (working_directory == NULL || !*working_directory) &&
570       (flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN))
571     {
572       /* We can do without the helper process */
573       gboolean retval =
574         do_spawn_directly (exit_status, do_return_handle, flags,
575                            argv, envp, protected_argv,
576                            child_setup, user_data, child_handle,
577                            error);
578       g_strfreev (protected_argv);
579       return retval;
580     }
581
582   if (standard_input && !make_pipe (stdin_pipe, error))
583     goto cleanup_and_fail;
584   
585   if (standard_output && !make_pipe (stdout_pipe, error))
586     goto cleanup_and_fail;
587   
588   if (standard_error && !make_pipe (stderr_pipe, error))
589     goto cleanup_and_fail;
590   
591   if (!make_pipe (child_err_report_pipe, error))
592     goto cleanup_and_fail;
593   
594   if (!make_pipe (helper_sync_pipe, error))
595     goto cleanup_and_fail;
596   
597   new_argv = g_new (char *, argc + 1 + ARG_COUNT);
598   if (GetConsoleCursorInfo (GetStdHandle (STD_OUTPUT_HANDLE), &cursor_info))
599     helper_process = HELPER_PROCESS "-console.exe";
600   else
601     helper_process = HELPER_PROCESS ".exe";
602   
603   glib_top = _glib_get_installation_directory ();
604   if (glib_top != NULL)
605     {
606       helper_process = g_build_filename (glib_top, "bin", helper_process, NULL);
607       g_free (glib_top);
608     }
609   else
610     helper_process = g_strdup (helper_process);
611
612   new_argv[0] = protect_argv_string (helper_process);
613
614   _g_sprintf (args[ARG_CHILD_ERR_REPORT], "%d", child_err_report_pipe[1]);
615   new_argv[ARG_CHILD_ERR_REPORT] = args[ARG_CHILD_ERR_REPORT];
616   
617   /* Make the read end of the child error report pipe
618    * noninherited. Otherwise it will needlessly be inherited by the
619    * helper process, and the started actual user process. As such that
620    * shouldn't harm, but it is unnecessary.
621    */
622   child_err_report_pipe[0] = dup_noninherited (child_err_report_pipe[0], _O_RDONLY);
623
624   if (flags & G_SPAWN_FILE_AND_ARGV_ZERO)
625     {
626       /* Overload ARG_CHILD_ERR_REPORT to also encode the
627        * G_SPAWN_FILE_AND_ARGV_ZERO functionality.
628        */
629       strcat (args[ARG_CHILD_ERR_REPORT], "#");
630     }
631   
632   _g_sprintf (args[ARG_HELPER_SYNC], "%d", helper_sync_pipe[0]);
633   new_argv[ARG_HELPER_SYNC] = args[ARG_HELPER_SYNC];
634   
635   /* Make the write end of the sync pipe noninherited. Otherwise the
636    * helper process will inherit it, and thus if this process happens
637    * to crash before writing the sync byte to the pipe, the helper
638    * process won't read but won't get any EOF either, as it has the
639    * write end open itself.
640    */
641   helper_sync_pipe[1] = dup_noninherited (helper_sync_pipe[1], _O_WRONLY);
642
643   if (standard_input)
644     {
645       _g_sprintf (args[ARG_STDIN], "%d", stdin_pipe[0]);
646       new_argv[ARG_STDIN] = args[ARG_STDIN];
647     }
648   else if (flags & G_SPAWN_CHILD_INHERITS_STDIN)
649     {
650       /* Let stdin be alone */
651       new_argv[ARG_STDIN] = "-";
652     }
653   else
654     {
655       /* Keep process from blocking on a read of stdin */
656       new_argv[ARG_STDIN] = "z";
657     }
658   
659   if (standard_output)
660     {
661       _g_sprintf (args[ARG_STDOUT], "%d", stdout_pipe[1]);
662       new_argv[ARG_STDOUT] = args[ARG_STDOUT];
663     }
664   else if (flags & G_SPAWN_STDOUT_TO_DEV_NULL)
665     {
666       new_argv[ARG_STDOUT] = "z";
667     }
668   else
669     {
670       new_argv[ARG_STDOUT] = "-";
671     }
672   
673   if (standard_error)
674     {
675       _g_sprintf (args[ARG_STDERR], "%d", stderr_pipe[1]);
676       new_argv[ARG_STDERR] = args[ARG_STDERR];
677     }
678   else if (flags & G_SPAWN_STDERR_TO_DEV_NULL)
679     {
680       new_argv[ARG_STDERR] = "z";
681     }
682   else
683     {
684       new_argv[ARG_STDERR] = "-";
685     }
686   
687   if (working_directory && *working_directory)
688     new_argv[ARG_WORKING_DIRECTORY] = protect_argv_string (working_directory);
689   else
690     new_argv[ARG_WORKING_DIRECTORY] = g_strdup ("-");
691   
692   if (!(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN))
693     new_argv[ARG_CLOSE_DESCRIPTORS] = "y";
694   else
695     new_argv[ARG_CLOSE_DESCRIPTORS] = "-";
696
697   if (flags & G_SPAWN_SEARCH_PATH)
698     new_argv[ARG_USE_PATH] = "y";
699   else
700     new_argv[ARG_USE_PATH] = "-";
701
702   if (exit_status == NULL)
703     new_argv[ARG_WAIT] = "-";
704   else
705     new_argv[ARG_WAIT] = "w";
706
707   for (i = 0; i <= argc; i++)
708     new_argv[ARG_PROGRAM + i] = protected_argv[i];
709
710   SETUP_DEBUG();
711
712   if (debug)
713     {
714       g_print ("calling %s with argv:\n", helper_process);
715       for (i = 0; i < argc + 1 + ARG_COUNT; i++)
716         g_print ("argv[%d]: %s\n", i, (new_argv[i] ? new_argv[i] : "NULL"));
717     }
718
719   if (!utf8_charv_to_wcharv (new_argv, &wargv, &conv_error_index, &conv_error))
720     {
721       if (conv_error_index == ARG_WORKING_DIRECTORY)
722         g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_CHDIR,
723                      _("Invalid working directory: %s"),
724                      conv_error->message);
725       else
726         g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
727                      _("Invalid string in argument vector at %d: %s"),
728                      conv_error_index - ARG_PROGRAM, conv_error->message);
729       g_error_free (conv_error);
730       g_strfreev (protected_argv);
731       g_free (new_argv[0]);
732       g_free (new_argv[ARG_WORKING_DIRECTORY]);
733       g_free (new_argv);
734       g_free (helper_process);
735
736       goto cleanup_and_fail;
737     }
738
739   if (!utf8_charv_to_wcharv (envp, &wenvp, NULL, &conv_error))
740     {
741       g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
742                    _("Invalid string in environment: %s"),
743                    conv_error->message);
744       g_error_free (conv_error);
745       g_strfreev (protected_argv);
746       g_free (new_argv[0]);
747       g_free (new_argv[ARG_WORKING_DIRECTORY]);
748       g_free (new_argv);
749       g_free (helper_process);
750       g_strfreev ((gchar **) wargv);
751  
752       goto cleanup_and_fail;
753     }
754
755   if (child_setup)
756     (* child_setup) (user_data);
757
758   whelper = g_utf8_to_utf16 (helper_process, -1, NULL, NULL, NULL);
759   g_free (helper_process);
760
761   if (wenvp != NULL)
762     rc = _wspawnvpe (P_NOWAIT, whelper, (const wchar_t **) wargv, (const wchar_t **) wenvp);
763   else
764     rc = _wspawnvp (P_NOWAIT, whelper, (const wchar_t **) wargv);
765
766   saved_errno = errno;
767
768   g_free (whelper);
769   g_strfreev ((gchar **) wargv);
770   g_strfreev ((gchar **) wenvp);
771
772   /* Close the other process's ends of the pipes in this process,
773    * otherwise the reader will never get EOF.
774    */
775   close_and_invalidate (&child_err_report_pipe[1]);
776   close_and_invalidate (&helper_sync_pipe[0]);
777   close_and_invalidate (&stdin_pipe[0]);
778   close_and_invalidate (&stdout_pipe[1]);
779   close_and_invalidate (&stderr_pipe[1]);
780
781   g_strfreev (protected_argv);
782
783   g_free (new_argv[0]);
784   g_free (new_argv[ARG_WORKING_DIRECTORY]);
785   g_free (new_argv);
786
787   /* Check if gspawn-win32-helper couldn't be run */
788   if (rc == -1 && saved_errno != 0)
789     {
790       g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
791                    _("Failed to execute helper program (%s)"),
792                    g_strerror (saved_errno));
793       goto cleanup_and_fail;
794     }
795
796   if (exit_status != NULL)
797     {
798       /* Synchronous case. Pass helper's report pipe back to caller,
799        * which takes care of reading it after the grandchild has
800        * finished.
801        */
802       g_assert (err_report != NULL);
803       *err_report = child_err_report_pipe[0];
804       write (helper_sync_pipe[1], " ", 1);
805       close_and_invalidate (&helper_sync_pipe[1]);
806     }
807   else
808     {
809       /* Asynchronous case. We read the helper's report right away. */
810       if (!read_helper_report (child_err_report_pipe[0], helper_report, error))
811         goto cleanup_and_fail;
812         
813       close_and_invalidate (&child_err_report_pipe[0]);
814
815       switch (helper_report[0])
816         {
817         case CHILD_NO_ERROR:
818           if (child_handle && do_return_handle)
819             {
820               /* rc is our HANDLE for gspawn-win32-helper. It has
821                * told us the HANDLE of its child. Duplicate that into
822                * a HANDLE valid in this process.
823                */
824               if (!DuplicateHandle ((HANDLE) rc, (HANDLE) helper_report[1],
825                                     GetCurrentProcess (), (LPHANDLE) child_handle,
826                                     0, TRUE, DUPLICATE_SAME_ACCESS))
827                 {
828                   char *emsg = g_win32_error_message (GetLastError ());
829                   g_print("%s\n", emsg);
830                   *child_handle = 0;
831                 }
832             }
833           else if (child_handle)
834             *child_handle = 0;
835           write (helper_sync_pipe[1], " ", 1);
836           close_and_invalidate (&helper_sync_pipe[1]);
837           break;
838           
839         default:
840           write (helper_sync_pipe[1], " ", 1);
841           close_and_invalidate (&helper_sync_pipe[1]);
842           set_child_error (helper_report, working_directory, error);
843           goto cleanup_and_fail;
844         }
845     }
846
847   /* Success against all odds! return the information */
848       
849   if (standard_input)
850     *standard_input = stdin_pipe[1];
851   if (standard_output)
852     *standard_output = stdout_pipe[0];
853   if (standard_error)
854     *standard_error = stderr_pipe[0];
855   if (rc != -1)
856     CloseHandle ((HANDLE) rc);
857   
858   return TRUE;
859
860  cleanup_and_fail:
861
862   if (rc != -1)
863     CloseHandle ((HANDLE) rc);
864   if (child_err_report_pipe[0] != -1)
865     close (child_err_report_pipe[0]);
866   if (child_err_report_pipe[1] != -1)
867     close (child_err_report_pipe[1]);
868   if (helper_sync_pipe[0] != -1)
869     close (helper_sync_pipe[0]);
870   if (helper_sync_pipe[1] != -1)
871     close (helper_sync_pipe[1]);
872   if (stdin_pipe[0] != -1)
873     close (stdin_pipe[0]);
874   if (stdin_pipe[1] != -1)
875     close (stdin_pipe[1]);
876   if (stdout_pipe[0] != -1)
877     close (stdout_pipe[0]);
878   if (stdout_pipe[1] != -1)
879     close (stdout_pipe[1]);
880   if (stderr_pipe[0] != -1)
881     close (stderr_pipe[0]);
882   if (stderr_pipe[1] != -1)
883     close (stderr_pipe[1]);
884
885   return FALSE;
886 }
887
888 gboolean
889 g_spawn_sync_utf8 (const gchar          *working_directory,
890                    gchar               **argv,
891                    gchar               **envp,
892                    GSpawnFlags           flags,
893                    GSpawnChildSetupFunc  child_setup,
894                    gpointer              user_data,
895                    gchar               **standard_output,
896                    gchar               **standard_error,
897                    gint                 *exit_status,
898                    GError              **error)     
899 {
900   gint outpipe = -1;
901   gint errpipe = -1;
902   gint reportpipe = -1;
903   GIOChannel *outchannel = NULL;
904   GIOChannel *errchannel = NULL;
905   GPollFD outfd, errfd;
906   GPollFD fds[2];
907   gint nfds;
908   gint outindex = -1;
909   gint errindex = -1;
910   gint ret;
911   GString *outstr = NULL;
912   GString *errstr = NULL;
913   gboolean failed;
914   gint status;
915   
916   g_return_val_if_fail (argv != NULL, FALSE);
917   g_return_val_if_fail (!(flags & G_SPAWN_DO_NOT_REAP_CHILD), FALSE);
918   g_return_val_if_fail (standard_output == NULL ||
919                         !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
920   g_return_val_if_fail (standard_error == NULL ||
921                         !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
922   
923   /* Just to ensure segfaults if callers try to use
924    * these when an error is reported.
925    */
926   if (standard_output)
927     *standard_output = NULL;
928
929   if (standard_error)
930     *standard_error = NULL;
931   
932   if (!do_spawn_with_pipes (&status,
933                             FALSE,
934                             working_directory,
935                             argv,
936                             envp,
937                             flags,
938                             child_setup,
939                             user_data,
940                             NULL,
941                             NULL,
942                             standard_output ? &outpipe : NULL,
943                             standard_error ? &errpipe : NULL,
944                             &reportpipe,
945                             error))
946     return FALSE;
947
948   /* Read data from child. */
949   
950   failed = FALSE;
951
952   if (outpipe >= 0)
953     {
954       outstr = g_string_new (NULL);
955       outchannel = g_io_channel_win32_new_fd (outpipe);
956       g_io_channel_set_encoding (outchannel, NULL, NULL);
957       g_io_channel_set_buffered (outchannel, FALSE);
958       g_io_channel_win32_make_pollfd (outchannel,
959                                       G_IO_IN | G_IO_ERR | G_IO_HUP,
960                                       &outfd);
961       if (debug)
962         g_print ("outfd=%p\n", (HANDLE) outfd.fd);
963     }
964       
965   if (errpipe >= 0)
966     {
967       errstr = g_string_new (NULL);
968       errchannel = g_io_channel_win32_new_fd (errpipe);
969       g_io_channel_set_encoding (errchannel, NULL, NULL);
970       g_io_channel_set_buffered (errchannel, FALSE);
971       g_io_channel_win32_make_pollfd (errchannel,
972                                       G_IO_IN | G_IO_ERR | G_IO_HUP,
973                                       &errfd);
974       if (debug)
975         g_print ("errfd=%p\n", (HANDLE) errfd.fd);
976     }
977
978   /* Read data until we get EOF on all pipes. */
979   while (!failed && (outpipe >= 0 || errpipe >= 0))
980     {
981       nfds = 0;
982       if (outpipe >= 0)
983         {
984           fds[nfds] = outfd;
985           outindex = nfds;
986           nfds++;
987         }
988       if (errpipe >= 0)
989         {
990           fds[nfds] = errfd;
991           errindex = nfds;
992           nfds++;
993         }
994
995       if (debug)
996         g_print ("g_spawn_sync: calling g_io_channel_win32_poll, nfds=%d\n",
997                  nfds);
998
999       ret = g_io_channel_win32_poll (fds, nfds, -1);
1000
1001       if (ret < 0)
1002         {
1003           failed = TRUE;
1004
1005           g_set_error_literal (error, G_SPAWN_ERROR, G_SPAWN_ERROR_READ,
1006                                _("Unexpected error in g_io_channel_win32_poll() reading data from a child process"));
1007           
1008           break;
1009         }
1010
1011       if (outpipe >= 0 && (fds[outindex].revents & G_IO_IN))
1012         {
1013           switch (read_data (outstr, outchannel, error))
1014             {
1015             case READ_FAILED:
1016               if (debug)
1017                 g_print ("g_spawn_sync: outchannel: READ_FAILED\n");
1018               failed = TRUE;
1019               break;
1020             case READ_EOF:
1021               if (debug)
1022                 g_print ("g_spawn_sync: outchannel: READ_EOF\n");
1023               g_io_channel_unref (outchannel);
1024               outchannel = NULL;
1025               close_and_invalidate (&outpipe);
1026               break;
1027             default:
1028               if (debug)
1029                 g_print ("g_spawn_sync: outchannel: OK\n");
1030               break;
1031             }
1032
1033           if (failed)
1034             break;
1035         }
1036
1037       if (errpipe >= 0 && (fds[errindex].revents & G_IO_IN))
1038         {
1039           switch (read_data (errstr, errchannel, error))
1040             {
1041             case READ_FAILED:
1042               if (debug)
1043                 g_print ("g_spawn_sync: errchannel: READ_FAILED\n");
1044               failed = TRUE;
1045               break;
1046             case READ_EOF:
1047               if (debug)
1048                 g_print ("g_spawn_sync: errchannel: READ_EOF\n");
1049               g_io_channel_unref (errchannel);
1050               errchannel = NULL;
1051               close_and_invalidate (&errpipe);
1052               break;
1053             default:
1054               if (debug)
1055                 g_print ("g_spawn_sync: errchannel: OK\n");
1056               break;
1057             }
1058
1059           if (failed)
1060             break;
1061         }
1062     }
1063
1064   if (reportpipe == -1)
1065     {
1066       /* No helper process, exit status of actual spawned process
1067        * already available.
1068        */
1069       if (exit_status)
1070         *exit_status = status;
1071     }
1072   else
1073     {
1074       /* Helper process was involved. Read its report now after the
1075        * grandchild has finished.
1076        */
1077       gssize helper_report[2];
1078
1079       if (!read_helper_report (reportpipe, helper_report, error))
1080         failed = TRUE;
1081       else
1082         {
1083           switch (helper_report[0])
1084             {
1085             case CHILD_NO_ERROR:
1086               if (exit_status)
1087                 *exit_status = helper_report[1];
1088               break;
1089             default:
1090               set_child_error (helper_report, working_directory, error);
1091               failed = TRUE;
1092               break;
1093             }
1094         }
1095       close_and_invalidate (&reportpipe);
1096     }
1097
1098
1099   /* These should only be open still if we had an error.  */
1100   
1101   if (outchannel != NULL)
1102     g_io_channel_unref (outchannel);
1103   if (errchannel != NULL)
1104     g_io_channel_unref (errchannel);
1105   if (outpipe >= 0)
1106     close_and_invalidate (&outpipe);
1107   if (errpipe >= 0)
1108     close_and_invalidate (&errpipe);
1109   
1110   if (failed)
1111     {
1112       if (outstr)
1113         g_string_free (outstr, TRUE);
1114       if (errstr)
1115         g_string_free (errstr, TRUE);
1116
1117       return FALSE;
1118     }
1119   else
1120     {
1121       if (standard_output)        
1122         *standard_output = g_string_free (outstr, FALSE);
1123
1124       if (standard_error)
1125         *standard_error = g_string_free (errstr, FALSE);
1126
1127       return TRUE;
1128     }
1129 }
1130
1131 gboolean
1132 g_spawn_async_with_pipes_utf8 (const gchar          *working_directory,
1133                                gchar               **argv,
1134                                gchar               **envp,
1135                                GSpawnFlags           flags,
1136                                GSpawnChildSetupFunc  child_setup,
1137                                gpointer              user_data,
1138                                GPid                 *child_handle,
1139                                gint                 *standard_input,
1140                                gint                 *standard_output,
1141                                gint                 *standard_error,
1142                                GError              **error)
1143 {
1144   g_return_val_if_fail (argv != NULL, FALSE);
1145   g_return_val_if_fail (standard_output == NULL ||
1146                         !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
1147   g_return_val_if_fail (standard_error == NULL ||
1148                         !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
1149   /* can't inherit stdin if we have an input pipe. */
1150   g_return_val_if_fail (standard_input == NULL ||
1151                         !(flags & G_SPAWN_CHILD_INHERITS_STDIN), FALSE);
1152   
1153   return do_spawn_with_pipes (NULL,
1154                               (flags & G_SPAWN_DO_NOT_REAP_CHILD),
1155                               working_directory,
1156                               argv,
1157                               envp,
1158                               flags,
1159                               child_setup,
1160                               user_data,
1161                               child_handle,
1162                               standard_input,
1163                               standard_output,
1164                               standard_error,
1165                               NULL,
1166                               error);
1167 }
1168
1169 gboolean
1170 g_spawn_command_line_sync_utf8 (const gchar  *command_line,
1171                                 gchar       **standard_output,
1172                                 gchar       **standard_error,
1173                                 gint         *exit_status,
1174                                 GError      **error)
1175 {
1176   gboolean retval;
1177   gchar **argv = 0;
1178
1179   g_return_val_if_fail (command_line != NULL, FALSE);
1180   
1181   if (!g_shell_parse_argv (command_line,
1182                            NULL, &argv,
1183                            error))
1184     return FALSE;
1185   
1186   retval = g_spawn_sync_utf8 (NULL,
1187                               argv,
1188                               NULL,
1189                               G_SPAWN_SEARCH_PATH,
1190                               NULL,
1191                               NULL,
1192                               standard_output,
1193                               standard_error,
1194                               exit_status,
1195                               error);
1196   g_strfreev (argv);
1197
1198   return retval;
1199 }
1200
1201 gboolean
1202 g_spawn_command_line_async_utf8 (const gchar *command_line,
1203                                  GError     **error)
1204 {
1205   gboolean retval;
1206   gchar **argv = 0;
1207
1208   g_return_val_if_fail (command_line != NULL, FALSE);
1209
1210   if (!g_shell_parse_argv (command_line,
1211                            NULL, &argv,
1212                            error))
1213     return FALSE;
1214   
1215   retval = g_spawn_async_utf8 (NULL,
1216                                argv,
1217                                NULL,
1218                                G_SPAWN_SEARCH_PATH,
1219                                NULL,
1220                                NULL,
1221                                NULL,
1222                                error);
1223   g_strfreev (argv);
1224
1225   return retval;
1226 }
1227
1228 void
1229 g_spawn_close_pid (GPid pid)
1230 {
1231     CloseHandle (pid);
1232 }
1233
1234 #if !defined (_WIN64)
1235
1236 /* Binary compatibility versions that take system codepage pathnames,
1237  * argument vectors and environments. These get used only by code
1238  * built against 2.8.1 or earlier. Code built against 2.8.2 or later
1239  * will use the _utf8 versions above (see the #defines in gspawn.h).
1240  */
1241
1242 #undef g_spawn_async
1243 #undef g_spawn_async_with_pipes
1244 #undef g_spawn_sync
1245 #undef g_spawn_command_line_sync
1246 #undef g_spawn_command_line_async
1247
1248 static gboolean
1249 setup_utf8_copies (const gchar *working_directory,
1250                    gchar      **utf8_working_directory,
1251                    gchar      **argv,
1252                    gchar     ***utf8_argv,
1253                    gchar      **envp,
1254                    gchar     ***utf8_envp,
1255                    GError     **error)
1256 {
1257   gint i, argc, envc;
1258
1259   if (working_directory == NULL)
1260     *utf8_working_directory = NULL;
1261   else
1262     {
1263       GError *conv_error = NULL;
1264       
1265       *utf8_working_directory = g_locale_to_utf8 (working_directory, -1, NULL, NULL, &conv_error);
1266       if (*utf8_working_directory == NULL)
1267         {
1268           g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_CHDIR,
1269                        _("Invalid working directory: %s"),
1270                        conv_error->message);
1271           g_error_free (conv_error);
1272           return FALSE;
1273         }
1274     }
1275
1276   argc = 0;
1277   while (argv[argc])
1278     ++argc;
1279   *utf8_argv = g_new (gchar *, argc + 1);
1280   for (i = 0; i < argc; i++)
1281     {
1282       GError *conv_error = NULL;
1283
1284       (*utf8_argv)[i] = g_locale_to_utf8 (argv[i], -1, NULL, NULL, &conv_error);
1285       if ((*utf8_argv)[i] == NULL)
1286         {
1287           g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
1288                        _("Invalid string in argument vector at %d: %s"),
1289                        i, conv_error->message);
1290           g_error_free (conv_error);
1291           
1292           g_strfreev (*utf8_argv);
1293           *utf8_argv = NULL;
1294
1295           g_free (*utf8_working_directory);
1296           *utf8_working_directory = NULL;
1297
1298           return FALSE;
1299         }
1300     }
1301   (*utf8_argv)[argc] = NULL;
1302
1303   if (envp == NULL)
1304     {
1305       *utf8_envp = NULL;
1306     }
1307   else
1308     {
1309       envc = 0;
1310       while (envp[envc])
1311         ++envc;
1312       *utf8_envp = g_new (gchar *, envc + 1);
1313       for (i = 0; i < envc; i++)
1314         {
1315           GError *conv_error = NULL;
1316
1317           (*utf8_envp)[i] = g_locale_to_utf8 (envp[i], -1, NULL, NULL, &conv_error);
1318           if ((*utf8_envp)[i] == NULL)
1319             {   
1320               g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
1321                            _("Invalid string in environment: %s"),
1322                            conv_error->message);
1323               g_error_free (conv_error);
1324
1325               g_strfreev (*utf8_envp);
1326               *utf8_envp = NULL;
1327
1328               g_strfreev (*utf8_argv);
1329               *utf8_argv = NULL;
1330
1331               g_free (*utf8_working_directory);
1332               *utf8_working_directory = NULL;
1333
1334               return FALSE;
1335             }
1336         }
1337       (*utf8_envp)[envc] = NULL;
1338     }
1339   return TRUE;
1340 }
1341
1342 static void
1343 free_utf8_copies (gchar  *utf8_working_directory,
1344                   gchar **utf8_argv,
1345                   gchar **utf8_envp)
1346 {
1347   g_free (utf8_working_directory);
1348   g_strfreev (utf8_argv);
1349   g_strfreev (utf8_envp);
1350 }
1351
1352 gboolean
1353 g_spawn_async_with_pipes (const gchar          *working_directory,
1354                           gchar               **argv,
1355                           gchar               **envp,
1356                           GSpawnFlags           flags,
1357                           GSpawnChildSetupFunc  child_setup,
1358                           gpointer              user_data,
1359                           GPid                 *child_handle,
1360                           gint                 *standard_input,
1361                           gint                 *standard_output,
1362                           gint                 *standard_error,
1363                           GError              **error)
1364 {
1365   gchar *utf8_working_directory;
1366   gchar **utf8_argv;
1367   gchar **utf8_envp;
1368   gboolean retval;
1369
1370   if (!setup_utf8_copies (working_directory, &utf8_working_directory,
1371                           argv, &utf8_argv,
1372                           envp, &utf8_envp,
1373                           error))
1374     return FALSE;
1375
1376   retval = g_spawn_async_with_pipes_utf8 (utf8_working_directory,
1377                                           utf8_argv, utf8_envp,
1378                                           flags, child_setup, user_data,
1379                                           child_handle,
1380                                           standard_input, standard_output, standard_error,
1381                                           error);
1382
1383   free_utf8_copies (utf8_working_directory, utf8_argv, utf8_envp);
1384
1385   return retval;
1386 }
1387
1388 gboolean
1389 g_spawn_async (const gchar          *working_directory,
1390                gchar               **argv,
1391                gchar               **envp,
1392                GSpawnFlags           flags,
1393                GSpawnChildSetupFunc  child_setup,
1394                gpointer              user_data,
1395                GPid                 *child_handle,
1396                GError              **error)
1397 {
1398   return g_spawn_async_with_pipes (working_directory,
1399                                    argv, envp,
1400                                    flags,
1401                                    child_setup,
1402                                    user_data,
1403                                    child_handle,
1404                                    NULL, NULL, NULL,
1405                                    error);
1406 }
1407
1408 gboolean
1409 g_spawn_sync (const gchar          *working_directory,
1410               gchar               **argv,
1411               gchar               **envp,
1412               GSpawnFlags           flags,
1413               GSpawnChildSetupFunc  child_setup,
1414               gpointer              user_data,
1415               gchar               **standard_output,
1416               gchar               **standard_error,
1417               gint                 *exit_status,
1418               GError              **error)     
1419 {
1420   gchar *utf8_working_directory;
1421   gchar **utf8_argv;
1422   gchar **utf8_envp;
1423   gboolean retval;
1424
1425   if (!setup_utf8_copies (working_directory, &utf8_working_directory,
1426                           argv, &utf8_argv,
1427                           envp, &utf8_envp,
1428                           error))
1429     return FALSE;
1430
1431   retval = g_spawn_sync_utf8 (utf8_working_directory,
1432                               utf8_argv, utf8_envp,
1433                               flags, child_setup, user_data,
1434                               standard_output, standard_error, exit_status,
1435                               error);
1436
1437   free_utf8_copies (utf8_working_directory, utf8_argv, utf8_envp);
1438
1439   return retval;
1440 }
1441
1442 gboolean
1443 g_spawn_command_line_sync (const gchar  *command_line,
1444                            gchar       **standard_output,
1445                            gchar       **standard_error,
1446                            gint         *exit_status,
1447                            GError      **error)
1448 {
1449   gboolean retval;
1450   gchar **argv = 0;
1451
1452   g_return_val_if_fail (command_line != NULL, FALSE);
1453   
1454   if (!g_shell_parse_argv (command_line,
1455                            NULL, &argv,
1456                            error))
1457     return FALSE;
1458   
1459   retval = g_spawn_sync (NULL,
1460                          argv,
1461                          NULL,
1462                          G_SPAWN_SEARCH_PATH,
1463                          NULL,
1464                          NULL,
1465                          standard_output,
1466                          standard_error,
1467                          exit_status,
1468                          error);
1469   g_strfreev (argv);
1470
1471   return retval;
1472 }
1473
1474 gboolean
1475 g_spawn_command_line_async (const gchar *command_line,
1476                             GError     **error)
1477 {
1478   gboolean retval;
1479   gchar **argv = 0;
1480
1481   g_return_val_if_fail (command_line != NULL, FALSE);
1482
1483   if (!g_shell_parse_argv (command_line,
1484                            NULL, &argv,
1485                            error))
1486     return FALSE;
1487   
1488   retval = g_spawn_async (NULL,
1489                           argv,
1490                           NULL,
1491                           G_SPAWN_SEARCH_PATH,
1492                           NULL,
1493                           NULL,
1494                           NULL,
1495                           error);
1496   g_strfreev (argv);
1497
1498   return retval;
1499 }
1500
1501 #endif  /* !_WIN64 */
1502
1503 #endif /* !GSPAWN_HELPER */
1504
1505 #define __G_SPAWN_C__
1506 #include "galiasdef.c"