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