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 */
49 #include "gprintfint.h"
64 #ifdef G_SPAWN_WIN32_DEBUG
66 #define SETUP_DEBUG() /* empty */
69 static int debug = -1;
70 #define SETUP_DEBUG() \
75 if (getenv ("G_SPAWN_WIN32_DEBUG") != NULL) \
92 ARG_CHILD_ERR_REPORT = 1,
96 ARG_WORKING_DIRECTORY,
97 ARG_CLOSE_DESCRIPTORS,
101 ARG_COUNT = ARG_PROGRAM
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
110 protect_argv (gchar **argv,
118 *new_argv = g_new (gchar *, argc+1);
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).
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.
131 for (i = 0; i < argc; i++)
136 gboolean need_dblquotes = FALSE;
139 if (*p == ' ' || *p == '\t')
140 need_dblquotes = TRUE;
146 while (*pp && *pp == '\\')
155 q = (*new_argv)[i] = g_malloc (len + need_dblquotes*2 + 1);
168 while (*pp && *pp == '\\')
180 /* printf ("argv[%d]:%s, need_dblquotes:%s len:%d => %s\n", i, argv[i], need_dblquotes?"TRUE":"FALSE", len, (*new_argv)[i]); */
182 (*new_argv)[argc] = NULL;
187 #ifndef GSPAWN_HELPER
189 static gboolean make_pipe (gint p[2],
191 static gboolean do_spawn_with_pipes (gboolean dont_wait,
192 gboolean dont_return_handle,
193 const gchar *working_directory,
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,
205 gint *standard_input,
206 gint *standard_output,
207 gint *standard_error,
212 g_spawn_error_quark (void)
214 static GQuark quark = 0;
216 quark = g_quark_from_static_string ("g-exec-error-quark");
221 g_spawn_async (const gchar *working_directory,
225 GSpawnChildSetupFunc child_setup,
230 g_return_val_if_fail (argv != NULL, FALSE);
232 return g_spawn_async_with_pipes (working_directory,
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)
247 close_and_invalidate (gint *fd)
264 READ_FAILED = 0, /* FALSE */
270 read_data (GString *str,
271 GIOChannel *iochannel,
280 giostatus = g_io_channel_read_chars (iochannel, buf, sizeof (buf), &bytes, NULL);
286 g_string_append_len (str, buf, bytes);
289 else if (giostatus == G_IO_STATUS_AGAIN)
291 else if (giostatus == G_IO_STATUS_ERROR)
296 _("Failed to read data from child process"));
305 g_spawn_sync (const gchar *working_directory,
309 GSpawnChildSetupFunc child_setup,
311 gchar **standard_output,
312 gchar **standard_error,
319 GIOChannel *outchannel = NULL;
320 GIOChannel *errchannel = NULL;
321 GPollFD outfd, errfd;
327 GString *outstr = NULL;
328 GString *errstr = NULL;
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);
339 /* Just to ensure segfaults if callers try to use
340 * these when an error is reported.
343 *standard_output = NULL;
346 *standard_error = NULL;
348 if (!do_spawn_with_pipes (FALSE,
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,
363 standard_output ? &outpipe : NULL,
364 standard_error ? &errpipe : NULL,
369 /* Read data from child. */
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,
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,
393 /* Read data until we get EOF on both pipes. */
413 g_print ("%s:g_spawn_sync: calling g_io_channel_win32_poll, nfds=%d\n",
416 ret = g_io_channel_win32_poll (fds, nfds, -1);
425 _("Unexpected error in g_io_channel_win32_poll() reading data from a child process"));
430 if (outpipe >= 0 && (fds[outindex].revents & G_IO_IN))
432 switch (read_data (outstr, outchannel, error))
436 g_print ("g_spawn_sync: outchannel: READ_FAILED\n");
441 g_print ("g_spawn_sync: outchannel: READ_EOF\n");
442 g_io_channel_unref (outchannel);
444 close_and_invalidate (&outpipe);
448 g_print ("g_spawn_sync: outchannel: OK\n");
456 if (errpipe >= 0 && (fds[errindex].revents & G_IO_IN))
458 switch (read_data (errstr, errchannel, error))
462 g_print ("g_spawn_sync: errchannel: READ_FAILED\n");
467 g_print ("g_spawn_sync: errchannel: READ_EOF\n");
468 g_io_channel_unref (errchannel);
470 close_and_invalidate (&errpipe);
474 g_print ("g_spawn_sync: errchannel: OK\n");
483 /* These should only be open still if we had an error. */
485 if (outchannel != NULL)
486 g_io_channel_unref (outchannel);
487 if (errchannel != NULL)
488 g_io_channel_unref (errchannel);
490 close_and_invalidate (&outpipe);
492 close_and_invalidate (&errpipe);
494 g_spawn_close_pid(pid);
499 g_string_free (outstr, TRUE);
501 g_string_free (errstr, TRUE);
508 *exit_status = status;
511 *standard_output = g_string_free (outstr, FALSE);
514 *standard_error = g_string_free (errstr, FALSE);
521 g_spawn_async_with_pipes (const gchar *working_directory,
525 GSpawnChildSetupFunc child_setup,
528 gint *standard_input,
529 gint *standard_output,
530 gint *standard_error,
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);
542 return do_spawn_with_pipes (TRUE,
543 !(flags & G_SPAWN_DO_NOT_REAP_CHILD),
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,
564 g_spawn_command_line_sync (const gchar *command_line,
565 gchar **standard_output,
566 gchar **standard_error,
573 g_return_val_if_fail (command_line != NULL, FALSE);
575 if (!g_shell_parse_argv (command_line,
580 retval = g_spawn_sync (NULL,
596 g_spawn_command_line_async (const gchar *command_line,
602 g_return_val_if_fail (command_line != NULL, FALSE);
604 if (!g_shell_parse_argv (command_line,
609 retval = g_spawn_async (NULL,
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.
628 static gint shortcut_spawn_retval;
631 do_spawn (gboolean dont_wait,
632 gint child_err_report_fd,
636 const gchar *working_directory,
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,
648 gchar **protected_argv;
650 gchar args[ARG_COUNT][10];
657 argc = protect_argv (argv, &protected_argv);
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)
665 /* We can do without the helper process */
666 int mode = dont_wait ? P_NOWAIT : P_WAIT;
669 g_print ("doing without gspawn-win32-helper\n");
672 rc = spawnvp (mode, argv[0], file_and_argv_zero ? protected_argv + 1 : protected_argv);
674 rc = spawnv (mode, argv[0], file_and_argv_zero ? protected_argv + 1 : protected_argv);
676 for (i = 0; i < argc; i++)
677 g_free (protected_argv[i]);
678 g_free (protected_argv);
682 return DO_SPAWN_ERROR_NO_HELPER;
686 shortcut_spawn_retval = rc;
687 return DO_SPAWN_OK_NO_HELPER;
691 new_argv = g_new (gchar *, argc + 1 + ARG_COUNT);
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];
697 if (file_and_argv_zero)
699 /* Overload ARG_CHILD_ERR_REPORT to also encode the
700 * G_SPAWN_FILE_AND_ARGV_ZERO functionality.
702 strcat (args[ARG_CHILD_ERR_REPORT], "#");
707 _g_sprintf (args[ARG_STDIN], "%d", stdin_fd);
708 new_argv[ARG_STDIN] = args[ARG_STDIN];
710 else if (child_inherits_stdin)
712 /* Let stdin be alone */
713 new_argv[ARG_STDIN] = "-";
717 /* Keep process from blocking on a read of stdin */
718 new_argv[ARG_STDIN] = "z";
723 _g_sprintf (args[ARG_STDOUT], "%d", stdout_fd);
724 new_argv[ARG_STDOUT] = args[ARG_STDOUT];
726 else if (stdout_to_null)
728 new_argv[ARG_STDOUT] = "z";
732 new_argv[ARG_STDOUT] = "-";
737 _g_sprintf (args[ARG_STDERR], "%d", stderr_fd);
738 new_argv[ARG_STDERR] = args[ARG_STDERR];
740 else if (stderr_to_null)
742 new_argv[ARG_STDERR] = "z";
746 new_argv[ARG_STDERR] = "-";
749 if (working_directory && *working_directory)
750 /* The g_strdup() to lose the constness */
751 new_argv[ARG_WORKING_DIRECTORY] = g_strdup (working_directory);
753 new_argv[ARG_WORKING_DIRECTORY] = g_strdup ("-");
755 if (close_descriptors)
756 new_argv[ARG_CLOSE_DESCRIPTORS] = "y";
758 new_argv[ARG_CLOSE_DESCRIPTORS] = "-";
761 new_argv[ARG_USE_PATH] = "y";
763 new_argv[ARG_USE_PATH] = "-";
766 new_argv[ARG_WAIT] = "-";
768 new_argv[ARG_WAIT] = "w";
770 for (i = 0; i <= argc; i++)
771 new_argv[ARG_PROGRAM + i] = protected_argv[i];
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
780 (* child_setup) (user_data);
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"));
791 /* Let's hope envp hasn't mucked with PATH so that
792 * gspawn-win32-helper.exe isn't found.
794 rc = spawnvpe (P_NOWAIT, "gspawn-win32-helper", new_argv, envp);
796 rc = spawnvp (P_NOWAIT, "gspawn-win32-helper", new_argv);
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
802 close (child_err_report_fd);
810 for (i = 0; i < argc; i++)
811 g_free (protected_argv[i]);
812 g_free (protected_argv);
814 g_free (new_argv[ARG_WORKING_DIRECTORY]);
829 while (bytes < sizeof(gint)*n_ints_in_buf)
834 g_print ("%s:read_ints: trying to read %d bytes from pipe...\n",
836 sizeof(gint)*n_ints_in_buf - bytes);
838 chunk = read (fd, ((gchar*)buf) + bytes,
839 sizeof(gint)*n_ints_in_buf - bytes);
842 g_print ("... got %d bytes\n", chunk);
846 /* Some weird shit happened, bail out */
850 G_SPAWN_ERROR_FAILED,
851 _("Failed to read from child pipe (%s)"),
862 *n_ints_read = bytes/sizeof(gint);
868 do_spawn_with_pipes (gboolean dont_wait,
869 gboolean dont_return_handle,
870 const gchar *working_directory,
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,
882 gint *standard_input,
883 gint *standard_output,
884 gint *standard_error,
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 };
896 if (!make_pipe (child_err_report_pipe, error))
899 if (standard_input && !make_pipe (stdin_pipe, error))
900 goto cleanup_and_fail;
902 if (standard_output && !make_pipe (stdout_pipe, error))
903 goto cleanup_and_fail;
905 if (standard_error && !make_pipe (stderr_pipe, error))
906 goto cleanup_and_fail;
908 helper = do_spawn (dont_wait,
909 child_err_report_pipe[1],
920 child_inherits_stdin,
925 /* Check if gspawn-win32-helper couldn't be run */
926 if (helper == DO_SPAWN_ERROR_HELPER)
930 G_SPAWN_ERROR_FAILED,
931 _("Failed to execute helper program"));
932 goto cleanup_and_fail;
935 else if (helper == DO_SPAWN_OK_NO_HELPER)
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;
942 close_and_invalidate (&child_err_report_pipe[0]);
943 close_and_invalidate (&child_err_report_pipe[1]);
947 else if (helper == DO_SPAWN_ERROR_NO_HELPER)
951 G_SPAWN_ERROR_FAILED,
952 _("Failed to execute child process (%s)"),
955 goto cleanup_and_fail;
958 if (!read_ints (child_err_report_pipe[0],
962 goto cleanup_and_fail;
964 /* Error code from gspawn-win32-helper. */
968 if (child_handle && dont_wait && !dont_return_handle)
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.
974 if (!DuplicateHandle ((HANDLE) helper, (HANDLE) buf[1],
975 GetCurrentProcess (), (LPHANDLE) child_handle,
976 0, TRUE, DUPLICATE_SAME_ACCESS))
979 else if (child_handle)
983 case CHILD_CHDIR_FAILED:
987 _("Failed to change to directory '%s' (%s)"),
989 g_strerror (buf[1]));
990 goto cleanup_and_fail;
992 case CHILD_SPAWN_FAILED:
995 G_SPAWN_ERROR_FAILED,
996 _("Failed to execute child process (%s)"),
997 g_strerror (buf[1]));
998 goto cleanup_and_fail;
1001 /* Success against all odds! return the information */
1004 *standard_input = stdin_pipe[1];
1005 if (standard_output)
1006 *standard_output = stdout_pipe[0];
1008 *standard_error = stderr_pipe[0];
1010 *exit_status = buf[1];
1011 CloseHandle ((HANDLE) helper);
1013 close_and_invalidate (&child_err_report_pipe[0]);
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]);
1033 make_pipe (gint p[2],
1040 G_SPAWN_ERROR_FAILED,
1041 _("Failed to create pipe for communicating with child process (%s)"),
1042 g_strerror (errno));
1048 #endif /* !GSPAWN_HELPER */
1051 g_spawn_close_pid (GPid pid)