1 /* gspawn-win32.c - Process launching on Win32
3 * Copyright 2000 Red Hat, Inc.
4 * Copyright 2003 Tor Lillqvist
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.
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.
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.
23 * Implementation details on Win32.
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.)
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.
39 * The structure of the source code in this file is a mess, I know.
42 /* Define this to get some logging all the time */
43 /* #define G_SPAWN_WIN32_DEBUG */
48 #include "gprintfint.h"
63 #ifdef G_SPAWN_WIN32_DEBUG
65 #define SETUP_DEBUG() /* empty */
68 static int debug = -1;
69 #define SETUP_DEBUG() \
74 if (getenv ("G_SPAWN_WIN32_DEBUG") != NULL) \
91 ARG_CHILD_ERR_REPORT = 1,
95 ARG_WORKING_DIRECTORY,
96 ARG_CLOSE_DESCRIPTORS,
100 ARG_COUNT = ARG_PROGRAM
103 /* Return codes from do_spawn() */
104 #define DO_SPAWN_ERROR_HELPER -1
105 #define DO_SPAWN_OK_NO_HELPER -2
106 #define DO_SPAWN_ERROR_NO_HELPER -3
109 protect_argv (gchar **argv,
117 *new_argv = g_new (gchar *, argc+1);
119 /* Quote each argv element if necessary, so that it will get
120 * reconstructed correctly in the C runtime startup code. Note that
121 * the unquoting algorithm in the C runtime is really weird, and
122 * rather different than what Unix shells do. See stdargv.c in the C
123 * runtime sources (in the Platform SDK, in src/crt).
125 * Note that an new_argv[0] constructed by this function should
126 * *not* be passed as the filename argument to a spawn* or exec*
127 * family function. That argument should be the real file name
128 * without any quoting.
130 for (i = 0; i < argc; i++)
135 gboolean need_dblquotes = FALSE;
138 if (*p == ' ' || *p == '\t')
139 need_dblquotes = TRUE;
145 while (*pp && *pp == '\\')
154 q = (*new_argv)[i] = g_malloc (len + need_dblquotes*2 + 1);
167 while (*pp && *pp == '\\')
179 /* printf ("argv[%d]:%s, need_dblquotes:%s len:%d => %s\n", i, argv[i], need_dblquotes?"TRUE":"FALSE", len, (*new_argv)[i]); */
181 (*new_argv)[argc] = NULL;
186 #ifndef GSPAWN_HELPER
188 static gboolean make_pipe (gint p[2],
190 static gboolean do_spawn_with_pipes (gboolean dont_wait,
191 gboolean dont_return_handle,
192 const gchar *working_directory,
195 gboolean close_descriptors,
196 gboolean search_path,
197 gboolean stdout_to_null,
198 gboolean stderr_to_null,
199 gboolean child_inherits_stdin,
200 gboolean file_and_argv_zero,
201 GSpawnChildSetupFunc child_setup,
204 gint *standard_input,
205 gint *standard_output,
206 gint *standard_error,
211 g_spawn_error_quark (void)
213 static GQuark quark = 0;
215 quark = g_quark_from_static_string ("g-exec-error-quark");
220 g_spawn_async (const gchar *working_directory,
224 GSpawnChildSetupFunc child_setup,
229 g_return_val_if_fail (argv != NULL, FALSE);
231 return g_spawn_async_with_pipes (working_directory,
241 /* Avoids a danger in threaded situations (calling close()
242 * on a file descriptor twice, and another thread has
243 * re-opened it since the first close)
246 close_and_invalidate (gint *fd)
263 READ_FAILED = 0, /* FALSE */
269 read_data (GString *str,
270 GIOChannel *iochannel,
279 giostatus = g_io_channel_read_chars (iochannel, buf, sizeof (buf), &bytes, NULL);
285 g_string_append_len (str, buf, bytes);
288 else if (giostatus == G_IO_STATUS_AGAIN)
290 else if (giostatus == G_IO_STATUS_ERROR)
295 _("Failed to read data from child process"));
304 g_spawn_sync (const gchar *working_directory,
308 GSpawnChildSetupFunc child_setup,
310 gchar **standard_output,
311 gchar **standard_error,
318 GIOChannel *outchannel = NULL;
319 GIOChannel *errchannel = NULL;
320 GPollFD outfd, errfd;
326 GString *outstr = NULL;
327 GString *errstr = NULL;
331 g_return_val_if_fail (argv != NULL, FALSE);
332 g_return_val_if_fail (!(flags & G_SPAWN_DO_NOT_REAP_CHILD), FALSE);
333 g_return_val_if_fail (standard_output == NULL ||
334 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
335 g_return_val_if_fail (standard_error == NULL ||
336 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
338 /* Just to ensure segfaults if callers try to use
339 * these when an error is reported.
342 *standard_output = NULL;
345 *standard_error = NULL;
347 if (!do_spawn_with_pipes (FALSE,
352 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
353 (flags & G_SPAWN_SEARCH_PATH) != 0,
354 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
355 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
356 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
357 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
362 standard_output ? &outpipe : NULL,
363 standard_error ? &errpipe : NULL,
368 /* Read data from child. */
374 outstr = g_string_new (NULL);
375 outchannel = g_io_channel_win32_new_fd (outpipe);
376 g_io_channel_set_encoding (outchannel, NULL, NULL);
377 g_io_channel_win32_make_pollfd (outchannel,
378 G_IO_IN | G_IO_ERR | G_IO_HUP,
384 errstr = g_string_new (NULL);
385 errchannel = g_io_channel_win32_new_fd (errpipe);
386 g_io_channel_set_encoding (errchannel, NULL, NULL);
387 g_io_channel_win32_make_pollfd (errchannel,
388 G_IO_IN | G_IO_ERR | G_IO_HUP,
392 /* Read data until we get EOF on both pipes. */
412 g_print ("%s:g_spawn_sync: calling g_io_channel_win32_poll, nfds=%d\n",
415 ret = g_io_channel_win32_poll (fds, nfds, -1);
424 _("Unexpected error in g_io_channel_win32_poll() reading data from a child process"));
429 if (outpipe >= 0 && (fds[outindex].revents & G_IO_IN))
431 switch (read_data (outstr, outchannel, error))
435 g_print ("g_spawn_sync: outchannel: READ_FAILED\n");
440 g_print ("g_spawn_sync: outchannel: READ_EOF\n");
441 g_io_channel_unref (outchannel);
443 close_and_invalidate (&outpipe);
447 g_print ("g_spawn_sync: outchannel: OK\n");
455 if (errpipe >= 0 && (fds[errindex].revents & G_IO_IN))
457 switch (read_data (errstr, errchannel, error))
461 g_print ("g_spawn_sync: errchannel: READ_FAILED\n");
466 g_print ("g_spawn_sync: errchannel: READ_EOF\n");
467 g_io_channel_unref (errchannel);
469 close_and_invalidate (&errpipe);
473 g_print ("g_spawn_sync: errchannel: OK\n");
482 /* These should only be open still if we had an error. */
484 if (outchannel != NULL)
485 g_io_channel_unref (outchannel);
486 if (errchannel != NULL)
487 g_io_channel_unref (errchannel);
489 close_and_invalidate (&outpipe);
491 close_and_invalidate (&errpipe);
493 g_spawn_close_pid(pid);
498 g_string_free (outstr, TRUE);
500 g_string_free (errstr, TRUE);
507 *exit_status = status;
510 *standard_output = g_string_free (outstr, FALSE);
513 *standard_error = g_string_free (errstr, FALSE);
520 g_spawn_async_with_pipes (const gchar *working_directory,
524 GSpawnChildSetupFunc child_setup,
527 gint *standard_input,
528 gint *standard_output,
529 gint *standard_error,
532 g_return_val_if_fail (argv != NULL, FALSE);
533 g_return_val_if_fail (standard_output == NULL ||
534 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
535 g_return_val_if_fail (standard_error == NULL ||
536 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
537 /* can't inherit stdin if we have an input pipe. */
538 g_return_val_if_fail (standard_input == NULL ||
539 !(flags & G_SPAWN_CHILD_INHERITS_STDIN), FALSE);
541 return do_spawn_with_pipes (TRUE,
542 !(flags & G_SPAWN_DO_NOT_REAP_CHILD),
546 !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
547 (flags & G_SPAWN_SEARCH_PATH) != 0,
548 (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
549 (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
550 (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
551 (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
563 g_spawn_command_line_sync (const gchar *command_line,
564 gchar **standard_output,
565 gchar **standard_error,
572 g_return_val_if_fail (command_line != NULL, FALSE);
574 if (!g_shell_parse_argv (command_line,
579 retval = g_spawn_sync (NULL,
595 g_spawn_command_line_async (const gchar *command_line,
601 g_return_val_if_fail (command_line != NULL, FALSE);
603 if (!g_shell_parse_argv (command_line,
608 retval = g_spawn_async (NULL,
621 /* This stinks, code reorg needed. Presumably do_spawn() should be
622 * inserted into its only caller, do_spawn_with_pipes(), and then code
623 * snippets from that function should be split out to separate
624 * functions if necessary.
627 static gint shortcut_spawn_retval;
630 do_spawn (gboolean dont_wait,
631 gint child_err_report_fd,
635 const gchar *working_directory,
638 gboolean close_descriptors,
639 gboolean search_path,
640 gboolean stdout_to_null,
641 gboolean stderr_to_null,
642 gboolean child_inherits_stdin,
643 gboolean file_and_argv_zero,
644 GSpawnChildSetupFunc child_setup,
647 gchar **protected_argv;
649 gchar args[ARG_COUNT][10];
656 argc = protect_argv (argv, &protected_argv);
658 if (stdin_fd == -1 && stdout_fd == -1 && stderr_fd == -1 &&
659 (working_directory == NULL || !*working_directory) &&
660 !close_descriptors &&
661 !stdout_to_null && !stderr_to_null &&
662 child_inherits_stdin)
664 /* We can do without the helper process */
665 int mode = dont_wait ? P_NOWAIT : P_WAIT;
668 g_print ("doing without gspawn-win32-helper\n");
671 rc = spawnvp (mode, argv[0], file_and_argv_zero ? protected_argv + 1 : protected_argv);
673 rc = spawnv (mode, argv[0], file_and_argv_zero ? protected_argv + 1 : protected_argv);
675 for (i = 0; i < argc; i++)
676 g_free (protected_argv[i]);
677 g_free (protected_argv);
681 return DO_SPAWN_ERROR_NO_HELPER;
685 shortcut_spawn_retval = rc;
686 return DO_SPAWN_OK_NO_HELPER;
690 new_argv = g_new (gchar *, argc + 1 + ARG_COUNT);
692 new_argv[0] = "gspawn-win32-helper";
693 _g_sprintf (args[ARG_CHILD_ERR_REPORT], "%d", child_err_report_fd);
694 new_argv[ARG_CHILD_ERR_REPORT] = args[ARG_CHILD_ERR_REPORT];
696 if (file_and_argv_zero)
698 /* Overload ARG_CHILD_ERR_REPORT to also encode the
699 * G_SPAWN_FILE_AND_ARGV_ZERO functionality.
701 strcat (args[ARG_CHILD_ERR_REPORT], "#");
706 _g_sprintf (args[ARG_STDIN], "%d", stdin_fd);
707 new_argv[ARG_STDIN] = args[ARG_STDIN];
709 else if (child_inherits_stdin)
711 /* Let stdin be alone */
712 new_argv[ARG_STDIN] = "-";
716 /* Keep process from blocking on a read of stdin */
717 new_argv[ARG_STDIN] = "z";
722 _g_sprintf (args[ARG_STDOUT], "%d", stdout_fd);
723 new_argv[ARG_STDOUT] = args[ARG_STDOUT];
725 else if (stdout_to_null)
727 new_argv[ARG_STDOUT] = "z";
731 new_argv[ARG_STDOUT] = "-";
736 _g_sprintf (args[ARG_STDERR], "%d", stderr_fd);
737 new_argv[ARG_STDERR] = args[ARG_STDERR];
739 else if (stderr_to_null)
741 new_argv[ARG_STDERR] = "z";
745 new_argv[ARG_STDERR] = "-";
748 if (working_directory && *working_directory)
749 /* The g_strdup() to lose the constness */
750 new_argv[ARG_WORKING_DIRECTORY] = g_strdup (working_directory);
752 new_argv[ARG_WORKING_DIRECTORY] = g_strdup ("-");
754 if (close_descriptors)
755 new_argv[ARG_CLOSE_DESCRIPTORS] = "y";
757 new_argv[ARG_CLOSE_DESCRIPTORS] = "-";
760 new_argv[ARG_USE_PATH] = "y";
762 new_argv[ARG_USE_PATH] = "-";
765 new_argv[ARG_WAIT] = "-";
767 new_argv[ARG_WAIT] = "w";
769 for (i = 0; i <= argc; i++)
770 new_argv[ARG_PROGRAM + i] = protected_argv[i];
772 /* Call user function just before we execute the helper program,
773 * which executes the program. Dunno what's the usefulness of this.
774 * A child setup function used on Unix probably isn't of much use
775 * as such on Win32, anyhow
779 (* child_setup) (user_data);
784 g_print ("calling gspawn-win32-helper with argv:\n");
785 for (i = 0; i < argc + 1 + ARG_COUNT; i++)
786 g_print ("argv[%d]: %s\n", i, (new_argv[i] ? new_argv[i] : "NULL"));
790 /* Let's hope envp hasn't mucked with PATH so that
791 * gspawn-win32-helper.exe isn't found.
793 rc = spawnvpe (P_NOWAIT, "gspawn-win32-helper", new_argv, envp);
795 rc = spawnvp (P_NOWAIT, "gspawn-win32-helper", new_argv);
797 /* Close the child_err_report_fd and the other process's ends of the
798 * pipes in this process, otherwise the reader will never get
801 close (child_err_report_fd);
809 for (i = 0; i < argc; i++)
810 g_free (protected_argv[i]);
811 g_free (protected_argv);
813 g_free (new_argv[ARG_WORKING_DIRECTORY]);
828 while (bytes < sizeof(gint)*n_ints_in_buf)
833 g_print ("%s:read_ints: trying to read %d bytes from pipe...\n",
835 sizeof(gint)*n_ints_in_buf - bytes);
837 chunk = read (fd, ((gchar*)buf) + bytes,
838 sizeof(gint)*n_ints_in_buf - bytes);
841 g_print ("... got %d bytes\n", chunk);
845 /* Some weird shit happened, bail out */
849 G_SPAWN_ERROR_FAILED,
850 _("Failed to read from child pipe (%s)"),
861 *n_ints_read = bytes/sizeof(gint);
867 do_spawn_with_pipes (gboolean dont_wait,
868 gboolean dont_return_handle,
869 const gchar *working_directory,
872 gboolean close_descriptors,
873 gboolean search_path,
874 gboolean stdout_to_null,
875 gboolean stderr_to_null,
876 gboolean child_inherits_stdin,
877 gboolean file_and_argv_zero,
878 GSpawnChildSetupFunc child_setup,
881 gint *standard_input,
882 gint *standard_output,
883 gint *standard_error,
887 gint stdin_pipe[2] = { -1, -1 };
888 gint stdout_pipe[2] = { -1, -1 };
889 gint stderr_pipe[2] = { -1, -1 };
890 gint child_err_report_pipe[2] = { -1, -1 };
895 if (!make_pipe (child_err_report_pipe, error))
898 if (standard_input && !make_pipe (stdin_pipe, error))
899 goto cleanup_and_fail;
901 if (standard_output && !make_pipe (stdout_pipe, error))
902 goto cleanup_and_fail;
904 if (standard_error && !make_pipe (stderr_pipe, error))
905 goto cleanup_and_fail;
907 helper = do_spawn (dont_wait,
908 child_err_report_pipe[1],
919 child_inherits_stdin,
924 /* Check if gspawn-win32-helper couldn't be run */
925 if (helper == DO_SPAWN_ERROR_HELPER)
929 G_SPAWN_ERROR_FAILED,
930 _("Failed to execute helper program"));
931 goto cleanup_and_fail;
934 else if (helper == DO_SPAWN_OK_NO_HELPER)
936 if (child_handle && dont_wait && !dont_return_handle)
937 *child_handle = (GPid) shortcut_spawn_retval;
938 else if (!dont_wait && exit_status)
939 *exit_status = shortcut_spawn_retval;
941 close_and_invalidate (&child_err_report_pipe[0]);
942 close_and_invalidate (&child_err_report_pipe[1]);
946 else if (helper == DO_SPAWN_ERROR_NO_HELPER)
950 G_SPAWN_ERROR_FAILED,
951 _("Failed to execute child process (%s)"),
954 goto cleanup_and_fail;
957 if (!read_ints (child_err_report_pipe[0],
961 goto cleanup_and_fail;
963 /* Error code from gspawn-win32-helper. */
967 if (child_handle && dont_wait && !dont_return_handle)
969 /* helper is our HANDLE for gspawn-win32-helper. It has
970 * told us the HANDLE of its child. Duplicate that into
971 * a HANDLE valid in this process.
973 if (!DuplicateHandle ((HANDLE) helper, (HANDLE) buf[1],
974 GetCurrentProcess (), (LPHANDLE) child_handle,
975 0, TRUE, DUPLICATE_SAME_ACCESS))
978 else if (child_handle)
982 case CHILD_CHDIR_FAILED:
986 _("Failed to change to directory '%s' (%s)"),
988 g_strerror (buf[1]));
989 goto cleanup_and_fail;
991 case CHILD_SPAWN_FAILED:
994 G_SPAWN_ERROR_FAILED,
995 _("Failed to execute child process (%s)"),
996 g_strerror (buf[1]));
997 goto cleanup_and_fail;
1000 /* Success against all odds! return the information */
1003 *standard_input = stdin_pipe[1];
1004 if (standard_output)
1005 *standard_output = stdout_pipe[0];
1007 *standard_error = stderr_pipe[0];
1009 *exit_status = buf[1];
1010 CloseHandle ((HANDLE) helper);
1012 close_and_invalidate (&child_err_report_pipe[0]);
1018 CloseHandle ((HANDLE) helper);
1019 close_and_invalidate (&child_err_report_pipe[0]);
1020 close_and_invalidate (&child_err_report_pipe[1]);
1021 close_and_invalidate (&stdin_pipe[0]);
1022 close_and_invalidate (&stdin_pipe[1]);
1023 close_and_invalidate (&stdout_pipe[0]);
1024 close_and_invalidate (&stdout_pipe[1]);
1025 close_and_invalidate (&stderr_pipe[0]);
1026 close_and_invalidate (&stderr_pipe[1]);
1032 make_pipe (gint p[2],
1039 G_SPAWN_ERROR_FAILED,
1040 _("Failed to create pipe for communicating with child process (%s)"),
1041 g_strerror (errno));
1047 #endif /* !GSPAWN_HELPER */
1050 g_spawn_close_pid (GPid pid)