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