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"
64 #ifdef G_SPAWN_WIN32_DEBUG
66 #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
104 protect_argv (gchar **argv,
112 *new_argv = g_new (gchar *, argc+1);
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).
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.
125 for (i = 0; i < argc; i++)
130 gboolean need_dblquotes = FALSE;
133 if (*p == ' ' || *p == '\t')
134 need_dblquotes = TRUE;
140 while (*pp && *pp == '\\')
149 q = (*new_argv)[i] = g_malloc (len + need_dblquotes*2 + 1);
162 while (*pp && *pp == '\\')
174 /* printf ("argv[%d]:%s, need_dblquotes:%s len:%d => %s\n", i, argv[i], need_dblquotes?"TRUE":"FALSE", len, (*new_argv)[i]); */
176 (*new_argv)[argc] = NULL;
181 #ifndef GSPAWN_HELPER
183 #define HELPER_PROCESS "gspawn-win32-helper"
186 g_spawn_error_quark (void)
188 static GQuark quark = 0;
190 quark = g_quark_from_static_string ("g-exec-error-quark");
195 g_spawn_async (const gchar *working_directory,
199 GSpawnChildSetupFunc child_setup,
204 g_return_val_if_fail (argv != NULL, FALSE);
206 return g_spawn_async_with_pipes (working_directory,
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)
221 close_and_invalidate (gint *fd)
232 READ_FAILED = 0, /* FALSE */
238 read_data (GString *str,
239 GIOChannel *iochannel,
248 giostatus = g_io_channel_read_chars (iochannel, buf, sizeof (buf), &bytes, NULL);
254 g_string_append_len (str, buf, bytes);
257 else if (giostatus == G_IO_STATUS_AGAIN)
259 else if (giostatus == G_IO_STATUS_ERROR)
264 _("Failed to read data from child process"));
273 make_pipe (gint p[2],
280 G_SPAWN_ERROR_FAILED,
281 _("Failed to create pipe for communicating with child process (%s)"),
289 /* The helper process writes a status report back to us, through a
290 * pipe, consisting of two ints.
293 read_helper_report (int fd,
299 while (bytes < sizeof(gint)*2)
304 g_print ("%s:read_helper_report: read %d...\n",
306 sizeof(gint)*2 - bytes);
308 chunk = read (fd, ((gchar*)report) + bytes,
309 sizeof(gint)*2 - bytes);
312 g_print ("...got %d bytes\n", chunk);
316 /* Some weird shit happened, bail out */
320 G_SPAWN_ERROR_FAILED,
321 _("Failed to read from child pipe (%s)"),
332 if (bytes < sizeof(gint)*2)
339 set_child_error (gint report[2],
340 const gchar *working_directory,
345 case CHILD_CHDIR_FAILED:
349 _("Failed to change to directory '%s' (%s)"),
351 g_strerror (report[1]));
353 case CHILD_SPAWN_FAILED:
356 G_SPAWN_ERROR_FAILED,
357 _("Failed to execute child process (%s)"),
358 g_strerror (report[1]));
361 g_assert_not_reached ();
366 do_spawn_with_pipes (gboolean dont_wait,
367 gboolean dont_return_handle,
368 const gchar *working_directory,
372 GSpawnChildSetupFunc child_setup,
375 gint *standard_input,
376 gint *standard_output,
377 gint *standard_error,
382 char **protected_argv;
383 char args[ARG_COUNT][10];
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];
397 argc = protect_argv (argv, &protected_argv);
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))
406 /* We can do without the helper process */
407 int mode = dont_wait ? P_NOWAIT : P_WAIT;
410 g_print ("doing without " HELPER_PROCESS "\n");
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.
417 (* child_setup) (user_data);
419 new_argv = (flags & G_SPAWN_FILE_AND_ARGV_ZERO) ? protected_argv + 1 : protected_argv;
420 if (flags & G_SPAWN_SEARCH_PATH)
422 rc = spawnvpe (mode, argv[0], (const char **) new_argv, (const char **) envp);
424 rc = spawnvp (mode, argv[0], (const char **) new_argv);
427 rc = spawnve (mode, argv[0], (const char **) new_argv, (const char **) envp);
429 rc = spawnv (mode, argv[0], (const char **) new_argv);
433 for (i = 0; i < argc; i++)
434 g_free (protected_argv[i]);
435 g_free (protected_argv);
437 if (rc == -1 && saved_errno != 0)
441 G_SPAWN_ERROR_FAILED,
442 _("Failed to execute child process (%s)"),
444 goto cleanup_and_fail;
449 if (child_handle && !dont_return_handle)
450 *child_handle = (GPid) rc;
458 else if (exit_status)
464 new_argv = g_new (char *, argc + 1 + ARG_COUNT);
466 if (standard_input && !make_pipe (stdin_pipe, error))
467 goto cleanup_and_fail;
469 if (standard_output && !make_pipe (stdout_pipe, error))
470 goto cleanup_and_fail;
472 if (standard_error && !make_pipe (stderr_pipe, error))
473 goto cleanup_and_fail;
475 if (!make_pipe (child_err_report_pipe, error))
476 goto cleanup_and_fail;
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];
482 if (flags & G_SPAWN_FILE_AND_ARGV_ZERO)
484 /* Overload ARG_CHILD_ERR_REPORT to also encode the
485 * G_SPAWN_FILE_AND_ARGV_ZERO functionality.
487 strcat (args[ARG_CHILD_ERR_REPORT], "#");
492 _g_sprintf (args[ARG_STDIN], "%d", stdin_pipe[0]);
493 new_argv[ARG_STDIN] = args[ARG_STDIN];
495 else if (flags & G_SPAWN_CHILD_INHERITS_STDIN)
497 /* Let stdin be alone */
498 new_argv[ARG_STDIN] = "-";
502 /* Keep process from blocking on a read of stdin */
503 new_argv[ARG_STDIN] = "z";
508 _g_sprintf (args[ARG_STDOUT], "%d", stdout_pipe[1]);
509 new_argv[ARG_STDOUT] = args[ARG_STDOUT];
511 else if (flags & G_SPAWN_STDOUT_TO_DEV_NULL)
513 new_argv[ARG_STDOUT] = "z";
517 new_argv[ARG_STDOUT] = "-";
522 _g_sprintf (args[ARG_STDERR], "%d", stderr_pipe[1]);
523 new_argv[ARG_STDERR] = args[ARG_STDERR];
525 else if (flags & G_SPAWN_STDERR_TO_DEV_NULL)
527 new_argv[ARG_STDERR] = "z";
531 new_argv[ARG_STDERR] = "-";
534 if (working_directory && *working_directory)
535 /* The g_strdup() to lose the constness */
536 new_argv[ARG_WORKING_DIRECTORY] = g_strdup (working_directory);
538 new_argv[ARG_WORKING_DIRECTORY] = g_strdup ("-");
540 if (!(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN))
541 new_argv[ARG_CLOSE_DESCRIPTORS] = "y";
543 new_argv[ARG_CLOSE_DESCRIPTORS] = "-";
545 if (flags & G_SPAWN_SEARCH_PATH)
546 new_argv[ARG_USE_PATH] = "y";
548 new_argv[ARG_USE_PATH] = "-";
551 new_argv[ARG_WAIT] = "-";
553 new_argv[ARG_WAIT] = "w";
555 for (i = 0; i <= argc; i++)
556 new_argv[ARG_PROGRAM + i] = protected_argv[i];
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"));
566 (* child_setup) (user_data);
569 /* Let's hope envp hasn't mucked with PATH so that
570 * gspawn-win32-helper.exe isn't found.
572 rc = spawnvpe (P_NOWAIT, HELPER_PROCESS, (const char **) new_argv, (const char **) envp);
574 rc = spawnvp (P_NOWAIT, HELPER_PROCESS, (const char **) new_argv);
578 /* Close thed the other process's ends of the pipes in this
579 * process, otherwise the reader will never get EOF.
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]);
586 for (i = 0; i < argc; i++)
587 g_free (protected_argv[i]);
588 g_free (protected_argv);
590 g_free (new_argv[ARG_WORKING_DIRECTORY]);
593 /* Check if gspawn-win32-helper couldn't be run */
594 if (rc == -1 && saved_errno != 0)
598 G_SPAWN_ERROR_FAILED,
599 _("Failed to execute helper program"));
600 goto cleanup_and_fail;
605 /* Synchronous case. Pass helper's report pipe back to caller,
606 * which takes care of reading it after the grandchild has
609 g_assert (err_report != NULL);
610 *err_report = child_err_report_pipe[0];
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;
618 close (child_err_report_pipe[0]);
620 switch (helper_report[0])
623 if (child_handle && dont_wait && !dont_return_handle)
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.
629 if (!DuplicateHandle ((HANDLE) rc, (HANDLE) helper_report[1],
630 GetCurrentProcess (), (LPHANDLE) child_handle,
631 0, TRUE, DUPLICATE_SAME_ACCESS))
634 else if (child_handle)
637 *exit_status = helper_report[1];
641 set_child_error (helper_report, working_directory, error);
642 goto cleanup_and_fail;
646 /* Success against all odds! return the information */
649 *standard_input = stdin_pipe[1];
651 *standard_output = stdout_pipe[0];
653 *standard_error = stderr_pipe[0];
655 CloseHandle ((HANDLE) rc);
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]);
683 g_spawn_sync (const gchar *working_directory,
687 GSpawnChildSetupFunc child_setup,
689 gchar **standard_output,
690 gchar **standard_error,
696 gint reportpipe = -1;
697 GIOChannel *outchannel = NULL;
698 GIOChannel *errchannel = NULL;
699 GPollFD outfd, errfd;
705 GString *outstr = NULL;
706 GString *errstr = NULL;
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);
717 /* Just to ensure segfaults if callers try to use
718 * these when an error is reported.
721 *standard_output = NULL;
724 *standard_error = NULL;
726 if (!do_spawn_with_pipes (FALSE,
736 standard_output ? &outpipe : NULL,
737 standard_error ? &errpipe : NULL,
743 /* Read data from child. */
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,
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,
767 /* Read data until we get EOF on all pipes. */
768 while (!failed && (outpipe >= 0 || errpipe >= 0))
785 g_print ("g_spawn_sync: calling g_io_channel_win32_poll, nfds=%d\n",
788 ret = g_io_channel_win32_poll (fds, nfds, -1);
797 _("Unexpected error in g_io_channel_win32_poll() reading data from a child process"));
802 if (outpipe >= 0 && (fds[outindex].revents & G_IO_IN))
804 switch (read_data (outstr, outchannel, error))
808 g_print ("g_spawn_sync: outchannel: READ_FAILED\n");
813 g_print ("g_spawn_sync: outchannel: READ_EOF\n");
814 g_io_channel_unref (outchannel);
816 close_and_invalidate (&outpipe);
820 g_print ("g_spawn_sync: outchannel: OK\n");
828 if (errpipe >= 0 && (fds[errindex].revents & G_IO_IN))
830 switch (read_data (errstr, errchannel, error))
834 g_print ("g_spawn_sync: errchannel: READ_FAILED\n");
839 g_print ("g_spawn_sync: errchannel: READ_EOF\n");
840 g_io_channel_unref (errchannel);
842 close_and_invalidate (&errpipe);
846 g_print ("g_spawn_sync: errchannel: OK\n");
855 if (reportpipe == -1)
857 /* No helper process, exit status of actual spawned process
861 *exit_status = status;
865 /* Helper process was involved. Read its report now after the
866 * grandchild has finished.
868 gint helper_report[2];
870 if (!read_helper_report (reportpipe, helper_report, error))
874 switch (helper_report[0])
878 *exit_status = helper_report[1];
881 set_child_error (helper_report, working_directory, error);
886 close_and_invalidate (&reportpipe);
890 /* These should only be open still if we had an error. */
892 if (outchannel != NULL)
893 g_io_channel_unref (outchannel);
894 if (errchannel != NULL)
895 g_io_channel_unref (errchannel);
897 close_and_invalidate (&outpipe);
899 close_and_invalidate (&errpipe);
904 g_string_free (outstr, TRUE);
906 g_string_free (errstr, TRUE);
913 *standard_output = g_string_free (outstr, FALSE);
916 *standard_error = g_string_free (errstr, FALSE);
923 g_spawn_async_with_pipes (const gchar *working_directory,
927 GSpawnChildSetupFunc child_setup,
930 gint *standard_input,
931 gint *standard_output,
932 gint *standard_error,
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);
944 return do_spawn_with_pipes (TRUE,
945 !(flags & G_SPAWN_DO_NOT_REAP_CHILD),
962 g_spawn_command_line_sync (const gchar *command_line,
963 gchar **standard_output,
964 gchar **standard_error,
971 g_return_val_if_fail (command_line != NULL, FALSE);
973 if (!g_shell_parse_argv (command_line,
978 retval = g_spawn_sync (NULL,
994 g_spawn_command_line_async (const gchar *command_line,
1000 g_return_val_if_fail (command_line != NULL, FALSE);
1002 if (!g_shell_parse_argv (command_line,
1007 retval = g_spawn_async (NULL,
1010 G_SPAWN_SEARCH_PATH,
1020 #endif /* !GSPAWN_HELPER */
1023 g_spawn_close_pid (GPid pid)
1028 #define __G_SPAWN_C__
1029 #include "galiasdef.c"