Include glibintl.h, not gi18n.h, noticed by Dan Winship.
[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 #include "glibintl.h"
63
64 #ifdef G_SPAWN_WIN32_DEBUG
65   static int debug = 1;
66   #define SETUP_DEBUG() /* empty */
67 #else
68   static int debug = -1;
69   #define SETUP_DEBUG()                                 \
70     G_STMT_START                                        \
71       {                                                 \
72         if (debug == -1)                                \
73           {                                             \
74             if (getenv ("G_SPAWN_WIN32_DEBUG") != NULL) \
75               debug = 1;                                \
76             else                                        \
77               debug = 0;                                \
78           }                                             \
79       }                                                 \
80     G_STMT_END
81 #endif
82
83 enum
84 {
85   CHILD_NO_ERROR,
86   CHILD_CHDIR_FAILED,
87   CHILD_SPAWN_FAILED,
88 };
89
90 enum {
91   ARG_CHILD_ERR_REPORT = 1,
92   ARG_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 gint
104 protect_argv (gchar  **argv,
105               gchar ***new_argv)
106 {
107   gint i;
108   gint argc = 0;
109   
110   while (argv[argc])
111     ++argc;
112   *new_argv = g_new (gchar *, argc+1);
113
114   /* Quote each argv element if necessary, so that it will get
115    * reconstructed correctly in the C runtime startup code.  Note that
116    * the unquoting algorithm in the C runtime is really weird, and
117    * rather different than what Unix shells do. See stdargv.c in the C
118    * runtime sources (in the Platform SDK, in src/crt).
119    *
120    * Note that an new_argv[0] constructed by this function should
121    * *not* be passed as the filename argument to a spawn* or exec*
122    * family function. That argument should be the real file name
123    * without any quoting.
124    */
125   for (i = 0; i < argc; i++)
126     {
127       gchar *p = argv[i];
128       gchar *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               gchar *pp = p;
140               while (*pp && *pp == '\\')
141                 pp++;
142               if (*pp == '"')
143                 len++;
144             }
145           len++;
146           p++;
147         }
148
149       q = (*new_argv)[i] = g_malloc (len + need_dblquotes*2 + 1);
150       p = argv[i];
151
152       if (need_dblquotes)
153         *q++ = '"';
154
155       while (*p)
156         {
157           if (*p == '"')
158             *q++ = '\\';
159           else if (*p == '\\')
160             {
161               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       /* printf ("argv[%d]:%s, need_dblquotes:%s len:%d => %s\n", i, argv[i], need_dblquotes?"TRUE":"FALSE", len, (*new_argv)[i]); */
175     }
176   (*new_argv)[argc] = NULL;
177
178   return argc;
179 }
180
181 #ifndef GSPAWN_HELPER
182
183 #define HELPER_PROCESS "gspawn-win32-helper"
184
185 GQuark
186 g_spawn_error_quark (void)
187 {
188   static GQuark quark = 0;
189   if (quark == 0)
190     quark = g_quark_from_static_string ("g-exec-error-quark");
191   return quark;
192 }
193
194 gboolean
195 g_spawn_async (const gchar          *working_directory,
196                gchar               **argv,
197                gchar               **envp,
198                GSpawnFlags           flags,
199                GSpawnChildSetupFunc  child_setup,
200                gpointer              user_data,
201                GPid                 *child_handle,
202                GError              **error)
203 {
204   g_return_val_if_fail (argv != NULL, FALSE);
205   
206   return g_spawn_async_with_pipes (working_directory,
207                                    argv, envp,
208                                    flags,
209                                    child_setup,
210                                    user_data,
211                                    child_handle,
212                                    NULL, NULL, NULL,
213                                    error);
214 }
215
216 /* Avoids a danger in threaded situations (calling close()
217  * on a file descriptor twice, and another thread has
218  * re-opened it since the first close)
219  */
220 static void
221 close_and_invalidate (gint *fd)
222 {
223   if (*fd < 0)
224     return;
225
226   close (*fd);
227   *fd = -1;
228 }
229
230 typedef enum
231 {
232   READ_FAILED = 0, /* FALSE */
233   READ_OK,
234   READ_EOF
235 } ReadResult;
236
237 static ReadResult
238 read_data (GString     *str,
239            GIOChannel  *iochannel,
240            GError     **error)
241 {
242   GIOStatus giostatus;
243   gssize bytes;
244   gchar buf[4096];
245
246  again:
247   
248   giostatus = g_io_channel_read_chars (iochannel, buf, sizeof (buf), &bytes, NULL);
249
250   if (bytes == 0)
251     return READ_EOF;
252   else if (bytes > 0)
253     {
254       g_string_append_len (str, buf, bytes);
255       return READ_OK;
256     }
257   else if (giostatus == G_IO_STATUS_AGAIN)
258     goto again;
259   else if (giostatus == G_IO_STATUS_ERROR)
260     {
261       g_set_error (error,
262                    G_SPAWN_ERROR,
263                    G_SPAWN_ERROR_READ,
264                    _("Failed to read data from child process"));
265       
266       return READ_FAILED;
267     }
268   else
269     return READ_OK;
270 }
271
272 static gboolean
273 make_pipe (gint     p[2],
274            GError **error)
275 {
276   if (pipe (p) < 0)
277     {
278       g_set_error (error,
279                    G_SPAWN_ERROR,
280                    G_SPAWN_ERROR_FAILED,
281                    _("Failed to create pipe for communicating with child process (%s)"),
282                    g_strerror (errno));
283       return FALSE;
284     }
285   else
286     return TRUE;
287 }
288
289 /* The helper process writes a status report back to us, through a
290  * pipe, consisting of two ints.
291  */
292 static gboolean
293 read_helper_report (int      fd,
294                     gint     report[2],
295                     GError **error)
296 {
297   gint bytes = 0;
298   
299   while (bytes < sizeof(gint)*2)
300     {
301       gint chunk;
302
303       if (debug)
304         g_print ("%s:read_helper_report: read %d...\n",
305                  __FILE__,
306                  sizeof(gint)*2 - bytes);
307
308       chunk = read (fd, ((gchar*)report) + bytes,
309                     sizeof(gint)*2 - bytes);
310
311       if (debug)
312         g_print ("...got %d bytes\n", chunk);
313           
314       if (chunk < 0)
315         {
316           /* Some weird shit happened, bail out */
317               
318           g_set_error (error,
319                        G_SPAWN_ERROR,
320                        G_SPAWN_ERROR_FAILED,
321                        _("Failed to read from child pipe (%s)"),
322                        g_strerror (errno));
323
324           return FALSE;
325         }
326       else if (chunk == 0)
327         break; /* EOF */
328       else
329         bytes += chunk;
330     }
331
332   if (bytes < sizeof(gint)*2)
333     return FALSE;
334
335   return TRUE;
336 }
337
338 static void
339 set_child_error (gint         report[2],
340                  const gchar *working_directory,
341                  GError     **error)
342 {
343   switch (report[0])
344     {
345     case CHILD_CHDIR_FAILED:
346       g_set_error (error,
347                    G_SPAWN_ERROR,
348                    G_SPAWN_ERROR_CHDIR,
349                    _("Failed to change to directory '%s' (%s)"),
350                    working_directory,
351                    g_strerror (report[1]));
352       break;
353     case CHILD_SPAWN_FAILED:
354       g_set_error (error,
355                    G_SPAWN_ERROR,
356                    G_SPAWN_ERROR_FAILED,
357                    _("Failed to execute child process (%s)"),
358                    g_strerror (report[1]));
359       break;
360     default:
361       g_assert_not_reached ();
362     }
363 }
364
365 static gboolean
366 do_spawn_with_pipes (gboolean              dont_wait,
367                      gboolean              dont_return_handle,
368                      const gchar          *working_directory,
369                      gchar               **argv,
370                      char                **envp,
371                      GSpawnFlags           flags,
372                      GSpawnChildSetupFunc  child_setup,
373                      gpointer              user_data,
374                      GPid                 *child_handle,
375                      gint                 *standard_input,
376                      gint                 *standard_output,
377                      gint                 *standard_error,
378                      gint                 *exit_status,
379                      gint                 *err_report,
380                      GError              **error)     
381 {
382   char **protected_argv;
383   char args[ARG_COUNT][10];
384   char **new_argv;
385   int i;
386   int rc = -1;
387   int saved_errno;
388   int argc;
389   int stdin_pipe[2] = { -1, -1 };
390   int stdout_pipe[2] = { -1, -1 };
391   int stderr_pipe[2] = { -1, -1 };
392   int child_err_report_pipe[2] = { -1, -1 };
393   int helper_report[2];
394   
395   SETUP_DEBUG();
396
397   argc = protect_argv (argv, &protected_argv);
398
399   if (!standard_input && !standard_output && !standard_error &&
400       (flags & G_SPAWN_CHILD_INHERITS_STDIN) &&
401       !(flags & G_SPAWN_STDOUT_TO_DEV_NULL) &&
402       !(flags & G_SPAWN_STDERR_TO_DEV_NULL) &&
403       (working_directory == NULL || !*working_directory) &&
404       (flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN))
405     {
406       /* We can do without the helper process */
407       int mode = dont_wait ? P_NOWAIT : P_WAIT;
408
409       if (debug)
410         g_print ("doing without " HELPER_PROCESS "\n");
411
412       /* Call user function just before we spawn the program. Dunno
413        * what's the usefulness of this. A child setup function used on
414        * Unix probably isn't of much use as such on Win32, anyhow.
415        */
416       if (child_setup)
417         (* child_setup) (user_data);
418
419       new_argv = (flags & G_SPAWN_FILE_AND_ARGV_ZERO) ? protected_argv + 1 : protected_argv;
420       if (flags & G_SPAWN_SEARCH_PATH)
421         if (envp != NULL)
422           rc = spawnvpe (mode, argv[0], (const char **) new_argv, (const char **) envp);
423         else
424           rc = spawnvp (mode, argv[0], (const char **) new_argv);
425       else
426         if (envp != NULL)
427           rc = spawnve (mode, argv[0], (const char **) new_argv, (const char **) envp);
428         else
429           rc = spawnv (mode, argv[0], (const char **) new_argv);
430
431       saved_errno = errno;
432
433       for (i = 0; i < argc; i++)
434         g_free (protected_argv[i]);
435       g_free (protected_argv);
436
437       if (rc == -1 && saved_errno != 0)
438         {
439           g_set_error (error,
440                        G_SPAWN_ERROR,
441                        G_SPAWN_ERROR_FAILED,
442                        _("Failed to execute child process (%s)"),
443                        g_strerror (errno));
444           goto cleanup_and_fail;
445         }
446
447       if (dont_wait)
448         {
449           if (child_handle && !dont_return_handle)
450             *child_handle = (GPid) rc;
451           else
452             {
453               CloseHandle (rc);
454               if (child_handle)
455                 *child_handle = 0;
456             }
457         }
458       else if (exit_status)
459         *exit_status = rc;
460       
461       return TRUE;
462     }
463
464   new_argv = g_new (char *, argc + 1 + ARG_COUNT);
465
466   if (standard_input && !make_pipe (stdin_pipe, error))
467     goto cleanup_and_fail;
468   
469   if (standard_output && !make_pipe (stdout_pipe, error))
470     goto cleanup_and_fail;
471   
472   if (standard_error && !make_pipe (stderr_pipe, error))
473     goto cleanup_and_fail;
474   
475   if (!make_pipe (child_err_report_pipe, error))
476     goto cleanup_and_fail;
477   
478   new_argv[0] = HELPER_PROCESS;
479   _g_sprintf (args[ARG_CHILD_ERR_REPORT], "%d", child_err_report_pipe[1]);
480   new_argv[ARG_CHILD_ERR_REPORT] = args[ARG_CHILD_ERR_REPORT];
481   
482   if (flags & G_SPAWN_FILE_AND_ARGV_ZERO)
483     {
484       /* Overload ARG_CHILD_ERR_REPORT to also encode the
485        * G_SPAWN_FILE_AND_ARGV_ZERO functionality.
486        */
487       strcat (args[ARG_CHILD_ERR_REPORT], "#");
488     }
489   
490   if (standard_input)
491     {
492       _g_sprintf (args[ARG_STDIN], "%d", stdin_pipe[0]);
493       new_argv[ARG_STDIN] = args[ARG_STDIN];
494     }
495   else if (flags & G_SPAWN_CHILD_INHERITS_STDIN)
496     {
497       /* Let stdin be alone */
498       new_argv[ARG_STDIN] = "-";
499     }
500   else
501     {
502       /* Keep process from blocking on a read of stdin */
503       new_argv[ARG_STDIN] = "z";
504     }
505   
506   if (standard_output)
507     {
508       _g_sprintf (args[ARG_STDOUT], "%d", stdout_pipe[1]);
509       new_argv[ARG_STDOUT] = args[ARG_STDOUT];
510     }
511   else if (flags & G_SPAWN_STDOUT_TO_DEV_NULL)
512     {
513       new_argv[ARG_STDOUT] = "z";
514     }
515   else
516     {
517       new_argv[ARG_STDOUT] = "-";
518     }
519   
520   if (standard_error)
521     {
522       _g_sprintf (args[ARG_STDERR], "%d", stderr_pipe[1]);
523       new_argv[ARG_STDERR] = args[ARG_STDERR];
524     }
525   else if (flags & G_SPAWN_STDERR_TO_DEV_NULL)
526     {
527       new_argv[ARG_STDERR] = "z";
528     }
529   else
530     {
531       new_argv[ARG_STDERR] = "-";
532     }
533   
534   if (working_directory && *working_directory)
535     /* The g_strdup() to lose the constness */
536     new_argv[ARG_WORKING_DIRECTORY] = g_strdup (working_directory);
537   else
538     new_argv[ARG_WORKING_DIRECTORY] = g_strdup ("-");
539   
540   if (!(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN))
541     new_argv[ARG_CLOSE_DESCRIPTORS] = "y";
542   else
543     new_argv[ARG_CLOSE_DESCRIPTORS] = "-";
544
545   if (flags & G_SPAWN_SEARCH_PATH)
546     new_argv[ARG_USE_PATH] = "y";
547   else
548     new_argv[ARG_USE_PATH] = "-";
549
550   if (dont_wait)
551     new_argv[ARG_WAIT] = "-";
552   else
553     new_argv[ARG_WAIT] = "w";
554
555   for (i = 0; i <= argc; i++)
556     new_argv[ARG_PROGRAM + i] = protected_argv[i];
557
558   if (debug)
559     {
560       g_print ("calling " HELPER_PROCESS " with argv:\n");
561       for (i = 0; i < argc + 1 + ARG_COUNT; i++)
562         g_print ("argv[%d]: %s\n", i, (new_argv[i] ? new_argv[i] : "NULL"));
563     }
564
565   if (child_setup)
566     (* child_setup) (user_data);
567
568   if (envp != NULL)
569     /* Let's hope envp hasn't mucked with PATH so that
570      * gspawn-win32-helper.exe isn't found.
571      */
572     rc = spawnvpe (P_NOWAIT, HELPER_PROCESS, (const char **) new_argv, (const char **) envp);
573   else
574     rc = spawnvp (P_NOWAIT, HELPER_PROCESS, (const char **) new_argv);
575
576   saved_errno = errno;
577
578   /* Close thed the other process's ends of the pipes in this
579    * process, otherwise the reader will never get EOF.
580    */
581   close_and_invalidate (&child_err_report_pipe[1]);
582   close_and_invalidate (&stdin_pipe[0]);
583   close_and_invalidate (&stdout_pipe[1]);
584   close_and_invalidate (&stderr_pipe[1]);
585
586   for (i = 0; i < argc; i++)
587     g_free (protected_argv[i]);
588   g_free (protected_argv);
589
590   g_free (new_argv[ARG_WORKING_DIRECTORY]);
591   g_free (new_argv);
592
593   /* Check if gspawn-win32-helper couldn't be run */
594   if (rc == -1 && saved_errno != 0)
595     {
596       g_set_error (error,
597                    G_SPAWN_ERROR,
598                    G_SPAWN_ERROR_FAILED,
599                    _("Failed to execute helper program"));
600       goto cleanup_and_fail;
601     }
602
603   if (!dont_wait)
604     {
605       /* Synchronous case. Pass helper's report pipe back to caller,
606        * which takes care of reading it after the grandchild has
607        * finished.
608        */
609       g_assert (err_report != NULL);
610       *err_report = child_err_report_pipe[0];
611     }
612   else
613     {
614       /* Asynchronous case. We read the helper's report right away. */
615       if (!read_helper_report (child_err_report_pipe[0], helper_report, error))
616         goto cleanup_and_fail;
617         
618       close (child_err_report_pipe[0]);
619
620       switch (helper_report[0])
621         {
622         case CHILD_NO_ERROR:
623           if (child_handle && dont_wait && !dont_return_handle)
624             {
625               /* rc is our HANDLE for gspawn-win32-helper. It has
626                * told us the HANDLE of its child. Duplicate that into
627                * a HANDLE valid in this process.
628                */
629               if (!DuplicateHandle ((HANDLE) rc, (HANDLE) helper_report[1],
630                                     GetCurrentProcess (), (LPHANDLE) child_handle,
631                                     0, TRUE, DUPLICATE_SAME_ACCESS))
632                 *child_handle = 0;
633             }
634           else if (child_handle)
635             *child_handle = 0;
636           if (exit_status)
637             *exit_status = helper_report[1];
638           break;
639           
640         default:
641           set_child_error (helper_report, working_directory, error);
642           goto cleanup_and_fail;
643         }
644     }
645
646   /* Success against all odds! return the information */
647       
648   if (standard_input)
649     *standard_input = stdin_pipe[1];
650   if (standard_output)
651     *standard_output = stdout_pipe[0];
652   if (standard_error)
653     *standard_error = stderr_pipe[0];
654   if (rc != -1)
655     CloseHandle ((HANDLE) rc);
656   
657   return TRUE;
658
659  cleanup_and_fail:
660   if (rc != -1)
661     CloseHandle ((HANDLE) rc);
662   if (child_err_report_pipe[0] != -1)
663     close (child_err_report_pipe[0]);
664   if (child_err_report_pipe[1] != -1)
665     close (child_err_report_pipe[1]);
666   if (stdin_pipe[0] != -1)
667     close (stdin_pipe[0]);
668   if (stdin_pipe[1] != -1)
669     close (stdin_pipe[1]);
670   if (stdout_pipe[0] != -1)
671     close (stdout_pipe[0]);
672   if (stdout_pipe[1] != -1)
673     close (stdout_pipe[1]);
674   if (stderr_pipe[0] != -1)
675     close (stderr_pipe[0]);
676   if (stderr_pipe[1] != -1)
677     close (stderr_pipe[1]);
678
679   return FALSE;
680 }
681
682 gboolean
683 g_spawn_sync (const gchar          *working_directory,
684               gchar               **argv,
685               gchar               **envp,
686               GSpawnFlags           flags,
687               GSpawnChildSetupFunc  child_setup,
688               gpointer              user_data,
689               gchar               **standard_output,
690               gchar               **standard_error,
691               gint                 *exit_status,
692               GError              **error)     
693 {
694   gint outpipe = -1;
695   gint errpipe = -1;
696   gint reportpipe = -1;
697   GIOChannel *outchannel = NULL;
698   GIOChannel *errchannel = NULL;
699   GPollFD outfd, errfd;
700   GPollFD fds[2];
701   gint nfds;
702   gint outindex = -1;
703   gint errindex = -1;
704   gint ret;
705   GString *outstr = NULL;
706   GString *errstr = NULL;
707   gboolean failed;
708   gint status;
709   
710   g_return_val_if_fail (argv != NULL, FALSE);
711   g_return_val_if_fail (!(flags & G_SPAWN_DO_NOT_REAP_CHILD), FALSE);
712   g_return_val_if_fail (standard_output == NULL ||
713                         !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
714   g_return_val_if_fail (standard_error == NULL ||
715                         !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
716   
717   /* Just to ensure segfaults if callers try to use
718    * these when an error is reported.
719    */
720   if (standard_output)
721     *standard_output = NULL;
722
723   if (standard_error)
724     *standard_error = NULL;
725   
726   if (!do_spawn_with_pipes (FALSE,
727                             TRUE,
728                             working_directory,
729                             argv,
730                             envp,
731                             flags,
732                             child_setup,
733                             user_data,
734                             NULL,
735                             NULL,
736                             standard_output ? &outpipe : NULL,
737                             standard_error ? &errpipe : NULL,
738                             &status,
739                             &reportpipe,
740                             error))
741     return FALSE;
742
743   /* Read data from child. */
744   
745   failed = FALSE;
746
747   if (outpipe >= 0)
748     {
749       outstr = g_string_new (NULL);
750       outchannel = g_io_channel_win32_new_fd (outpipe);
751       g_io_channel_set_encoding (outchannel, NULL, NULL);
752       g_io_channel_win32_make_pollfd (outchannel,
753                                       G_IO_IN | G_IO_ERR | G_IO_HUP,
754                                       &outfd);
755     }
756       
757   if (errpipe >= 0)
758     {
759       errstr = g_string_new (NULL);
760       errchannel = g_io_channel_win32_new_fd (errpipe);
761       g_io_channel_set_encoding (errchannel, NULL, NULL);
762       g_io_channel_win32_make_pollfd (errchannel,
763                                       G_IO_IN | G_IO_ERR | G_IO_HUP,
764                                       &errfd);
765     }
766
767   /* Read data until we get EOF on all pipes. */
768   while (!failed && (outpipe >= 0 || errpipe >= 0))
769     {
770       nfds = 0;
771       if (outpipe >= 0)
772         {
773           fds[nfds] = outfd;
774           outindex = nfds;
775           nfds++;
776         }
777       if (errpipe >= 0)
778         {
779           fds[nfds] = errfd;
780           errindex = nfds;
781           nfds++;
782         }
783
784       if (debug)
785         g_print ("g_spawn_sync: calling g_io_channel_win32_poll, nfds=%d\n",
786                  nfds);
787
788       ret = g_io_channel_win32_poll (fds, nfds, -1);
789
790       if (ret < 0)
791         {
792           failed = TRUE;
793
794           g_set_error (error,
795                        G_SPAWN_ERROR,
796                        G_SPAWN_ERROR_READ,
797                        _("Unexpected error in g_io_channel_win32_poll() reading data from a child process"));
798           
799           break;
800         }
801
802       if (outpipe >= 0 && (fds[outindex].revents & G_IO_IN))
803         {
804           switch (read_data (outstr, outchannel, error))
805             {
806             case READ_FAILED:
807               if (debug)
808                 g_print ("g_spawn_sync: outchannel: READ_FAILED\n");
809               failed = TRUE;
810               break;
811             case READ_EOF:
812               if (debug)
813                 g_print ("g_spawn_sync: outchannel: READ_EOF\n");
814               g_io_channel_unref (outchannel);
815               outchannel = NULL;
816               close_and_invalidate (&outpipe);
817               break;
818             default:
819               if (debug)
820                 g_print ("g_spawn_sync: outchannel: OK\n");
821               break;
822             }
823
824           if (failed)
825             break;
826         }
827
828       if (errpipe >= 0 && (fds[errindex].revents & G_IO_IN))
829         {
830           switch (read_data (errstr, errchannel, error))
831             {
832             case READ_FAILED:
833               if (debug)
834                 g_print ("g_spawn_sync: errchannel: READ_FAILED\n");
835               failed = TRUE;
836               break;
837             case READ_EOF:
838               if (debug)
839                 g_print ("g_spawn_sync: errchannel: READ_EOF\n");
840               g_io_channel_unref (errchannel);
841               errchannel = NULL;
842               close_and_invalidate (&errpipe);
843               break;
844             default:
845               if (debug)
846                 g_print ("g_spawn_sync: errchannel: OK\n");
847               break;
848             }
849
850           if (failed)
851             break;
852         }
853     }
854
855   if (reportpipe == -1)
856     {
857       /* No helper process, exit status of actual spawned process
858        * already available.
859        */
860       if (exit_status)
861         *exit_status = status;
862     }
863   else
864     {
865       /* Helper process was involved. Read its report now after the
866        * grandchild has finished.
867        */
868       gint helper_report[2];
869
870       if (!read_helper_report (reportpipe, helper_report, error))
871         failed = TRUE;
872       else
873         {
874           switch (helper_report[0])
875             {
876             case CHILD_NO_ERROR:
877               if (exit_status)
878                 *exit_status = helper_report[1];
879               break;
880             default:
881               set_child_error (helper_report, working_directory, error);
882               failed = TRUE;
883               break;
884             }
885         }
886       close_and_invalidate (&reportpipe);
887     }
888
889
890   /* These should only be open still if we had an error.  */
891   
892   if (outchannel != NULL)
893     g_io_channel_unref (outchannel);
894   if (errchannel != NULL)
895     g_io_channel_unref (errchannel);
896   if (outpipe >= 0)
897     close_and_invalidate (&outpipe);
898   if (errpipe >= 0)
899     close_and_invalidate (&errpipe);
900   
901   if (failed)
902     {
903       if (outstr)
904         g_string_free (outstr, TRUE);
905       if (errstr)
906         g_string_free (errstr, TRUE);
907
908       return FALSE;
909     }
910   else
911     {
912       if (standard_output)        
913         *standard_output = g_string_free (outstr, FALSE);
914
915       if (standard_error)
916         *standard_error = g_string_free (errstr, FALSE);
917
918       return TRUE;
919     }
920 }
921
922 gboolean
923 g_spawn_async_with_pipes (const gchar          *working_directory,
924                           gchar               **argv,
925                           gchar               **envp,
926                           GSpawnFlags           flags,
927                           GSpawnChildSetupFunc  child_setup,
928                           gpointer              user_data,
929                           GPid                 *child_handle,
930                           gint                 *standard_input,
931                           gint                 *standard_output,
932                           gint                 *standard_error,
933                           GError              **error)
934 {
935   g_return_val_if_fail (argv != NULL, FALSE);
936   g_return_val_if_fail (standard_output == NULL ||
937                         !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
938   g_return_val_if_fail (standard_error == NULL ||
939                         !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
940   /* can't inherit stdin if we have an input pipe. */
941   g_return_val_if_fail (standard_input == NULL ||
942                         !(flags & G_SPAWN_CHILD_INHERITS_STDIN), FALSE);
943   
944   return do_spawn_with_pipes (TRUE,
945                               !(flags & G_SPAWN_DO_NOT_REAP_CHILD),
946                               working_directory,
947                               argv,
948                               envp,
949                               flags,
950                               child_setup,
951                               user_data,
952                               child_handle,
953                               standard_input,
954                               standard_output,
955                               standard_error,
956                               NULL,
957                               NULL,
958                               error);
959 }
960
961 gboolean
962 g_spawn_command_line_sync (const gchar  *command_line,
963                            gchar       **standard_output,
964                            gchar       **standard_error,
965                            gint         *exit_status,
966                            GError      **error)
967 {
968   gboolean retval;
969   gchar **argv = 0;
970
971   g_return_val_if_fail (command_line != NULL, FALSE);
972   
973   if (!g_shell_parse_argv (command_line,
974                            NULL, &argv,
975                            error))
976     return FALSE;
977   
978   retval = g_spawn_sync (NULL,
979                          argv,
980                          NULL,
981                          G_SPAWN_SEARCH_PATH,
982                          NULL,
983                          NULL,
984                          standard_output,
985                          standard_error,
986                          exit_status,
987                          error);
988   g_strfreev (argv);
989
990   return retval;
991 }
992
993 gboolean
994 g_spawn_command_line_async (const gchar *command_line,
995                             GError     **error)
996 {
997   gboolean retval;
998   gchar **argv = 0;
999
1000   g_return_val_if_fail (command_line != NULL, FALSE);
1001
1002   if (!g_shell_parse_argv (command_line,
1003                            NULL, &argv,
1004                            error))
1005     return FALSE;
1006   
1007   retval = g_spawn_async (NULL,
1008                           argv,
1009                           NULL,
1010                           G_SPAWN_SEARCH_PATH,
1011                           NULL,
1012                           NULL,
1013                           NULL,
1014                           error);
1015   g_strfreev (argv);
1016
1017   return retval;
1018 }
1019
1020 #endif /* !GSPAWN_HELPER */
1021
1022 void
1023 g_spawn_close_pid (GPid pid)
1024 {
1025     CloseHandle (pid);
1026 }
1027
1028 #define __G_SPAWN_C__
1029 #include "galiasdef.c"