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