gdbusconnection: Fix signal subscription documentation
[glib.git] / glib / gspawn-win32.c
blobd98aba1269cfb779c9b04bf220c58a5b9e490aef
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 many 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 */
45 #include "config.h"
47 #include "glib.h"
48 #include "glib-private.h"
49 #include "gprintfint.h"
50 #include "glibintl.h"
51 #include "gthread.h"
53 #include <string.h>
54 #include <stdlib.h>
55 #include <stdio.h>
57 #include <windows.h>
58 #include <errno.h>
59 #include <fcntl.h>
60 #include <io.h>
61 #include <process.h>
62 #include <direct.h>
63 #include <wchar.h>
65 #ifndef GSPAWN_HELPER
66 #ifdef G_SPAWN_WIN32_DEBUG
67 static int debug = 1;
68 #define SETUP_DEBUG() /* empty */
69 #else
70 static int debug = -1;
71 #define SETUP_DEBUG() \
72 G_STMT_START \
73 { \
74 if (debug == -1) \
75 { \
76 if (getenv ("G_SPAWN_WIN32_DEBUG") != NULL) \
77 debug = 1; \
78 else \
79 debug = 0; \
80 } \
81 } \
82 G_STMT_END
83 #endif
84 #endif
86 enum
88 CHILD_NO_ERROR,
89 CHILD_CHDIR_FAILED,
90 CHILD_SPAWN_FAILED,
93 enum {
94 ARG_CHILD_ERR_REPORT = 1,
95 ARG_HELPER_SYNC,
96 ARG_STDIN,
97 ARG_STDOUT,
98 ARG_STDERR,
99 ARG_WORKING_DIRECTORY,
100 ARG_CLOSE_DESCRIPTORS,
101 ARG_USE_PATH,
102 ARG_WAIT,
103 ARG_PROGRAM,
104 ARG_COUNT = ARG_PROGRAM
107 static int
108 dup_noninherited (int fd,
109 int mode)
111 HANDLE filehandle;
113 DuplicateHandle (GetCurrentProcess (), (LPHANDLE) _get_osfhandle (fd),
114 GetCurrentProcess (), &filehandle,
115 0, FALSE, DUPLICATE_SAME_ACCESS);
116 close (fd);
117 return _open_osfhandle ((gintptr) filehandle, mode | _O_NOINHERIT);
120 #ifndef GSPAWN_HELPER
122 #ifdef _WIN64
123 #define HELPER_PROCESS "gspawn-win64-helper"
124 #else
125 #define HELPER_PROCESS "gspawn-win32-helper"
126 #endif
128 static gchar *
129 protect_argv_string (const gchar *string)
131 const gchar *p = string;
132 gchar *retval, *q;
133 gint len = 0;
134 gboolean need_dblquotes = FALSE;
135 while (*p)
137 if (*p == ' ' || *p == '\t')
138 need_dblquotes = TRUE;
139 else if (*p == '"')
140 len++;
141 else if (*p == '\\')
143 const gchar *pp = p;
144 while (*pp && *pp == '\\')
145 pp++;
146 if (*pp == '"')
147 len++;
149 len++;
150 p++;
153 q = retval = g_malloc (len + need_dblquotes*2 + 1);
154 p = string;
156 if (need_dblquotes)
157 *q++ = '"';
159 while (*p)
161 if (*p == '"')
162 *q++ = '\\';
163 else if (*p == '\\')
165 const gchar *pp = p;
166 while (*pp && *pp == '\\')
167 pp++;
168 if (*pp == '"')
169 *q++ = '\\';
171 *q++ = *p;
172 p++;
175 if (need_dblquotes)
176 *q++ = '"';
177 *q++ = '\0';
179 return retval;
182 static gint
183 protect_argv (gchar **argv,
184 gchar ***new_argv)
186 gint i;
187 gint argc = 0;
189 while (argv[argc])
190 ++argc;
191 *new_argv = g_new (gchar *, argc+1);
193 /* Quote each argv element if necessary, so that it will get
194 * reconstructed correctly in the C runtime startup code. Note that
195 * the unquoting algorithm in the C runtime is really weird, and
196 * rather different than what Unix shells do. See stdargv.c in the C
197 * runtime sources (in the Platform SDK, in src/crt).
199 * Note that an new_argv[0] constructed by this function should
200 * *not* be passed as the filename argument to a spawn* or exec*
201 * family function. That argument should be the real file name
202 * without any quoting.
204 for (i = 0; i < argc; i++)
205 (*new_argv)[i] = protect_argv_string (argv[i]);
207 (*new_argv)[argc] = NULL;
209 return argc;
212 G_DEFINE_QUARK (g-exec-error-quark, g_spawn_error)
213 G_DEFINE_QUARK (g-spawn-exit-error-quark, g_spawn_exit_error)
215 gboolean
216 g_spawn_async_utf8 (const gchar *working_directory,
217 gchar **argv,
218 gchar **envp,
219 GSpawnFlags flags,
220 GSpawnChildSetupFunc child_setup,
221 gpointer user_data,
222 GPid *child_handle,
223 GError **error)
225 g_return_val_if_fail (argv != NULL, FALSE);
227 return g_spawn_async_with_pipes_utf8 (working_directory,
228 argv, envp,
229 flags,
230 child_setup,
231 user_data,
232 child_handle,
233 NULL, NULL, NULL,
234 error);
237 /* Avoids a danger in threaded situations (calling close()
238 * on a file descriptor twice, and another thread has
239 * re-opened it since the first close)
241 static void
242 close_and_invalidate (gint *fd)
244 if (*fd < 0)
245 return;
247 close (*fd);
248 *fd = -1;
251 typedef enum
253 READ_FAILED = 0, /* FALSE */
254 READ_OK,
255 READ_EOF
256 } ReadResult;
258 static ReadResult
259 read_data (GString *str,
260 GIOChannel *iochannel,
261 GError **error)
263 GIOStatus giostatus;
264 gsize bytes;
265 gchar buf[4096];
267 again:
269 giostatus = g_io_channel_read_chars (iochannel, buf, sizeof (buf), &bytes, NULL);
271 if (bytes == 0)
272 return READ_EOF;
273 else if (bytes > 0)
275 g_string_append_len (str, buf, bytes);
276 return READ_OK;
278 else if (giostatus == G_IO_STATUS_AGAIN)
279 goto again;
280 else if (giostatus == G_IO_STATUS_ERROR)
282 g_set_error_literal (error, G_SPAWN_ERROR, G_SPAWN_ERROR_READ,
283 _("Failed to read data from child process"));
285 return READ_FAILED;
287 else
288 return READ_OK;
291 static gboolean
292 make_pipe (gint p[2],
293 GError **error)
295 if (_pipe (p, 4096, _O_BINARY) < 0)
297 int errsv = errno;
299 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
300 _("Failed to create pipe for communicating with child process (%s)"),
301 g_strerror (errsv));
302 return FALSE;
304 else
305 return TRUE;
308 /* The helper process writes a status report back to us, through a
309 * pipe, consisting of two ints.
311 static gboolean
312 read_helper_report (int fd,
313 gintptr report[2],
314 GError **error)
316 gint bytes = 0;
318 while (bytes < sizeof(gintptr)*2)
320 gint chunk;
322 if (debug)
323 g_print ("%s:read_helper_report: read %" G_GSIZE_FORMAT "...\n",
324 __FILE__,
325 sizeof(gintptr)*2 - bytes);
327 chunk = read (fd, ((gchar*)report) + bytes,
328 sizeof(gintptr)*2 - bytes);
330 if (debug)
331 g_print ("...got %d bytes\n", chunk);
333 if (chunk < 0)
335 int errsv = errno;
337 /* Some weird shit happened, bail out */
338 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
339 _("Failed to read from child pipe (%s)"),
340 g_strerror (errsv));
342 return FALSE;
344 else if (chunk == 0)
346 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
347 _("Failed to read from child pipe (%s)"),
348 "EOF");
349 break; /* EOF */
351 else
352 bytes += chunk;
355 if (bytes < sizeof(gintptr)*2)
356 return FALSE;
358 return TRUE;
361 static void
362 set_child_error (gintptr report[2],
363 const gchar *working_directory,
364 GError **error)
366 switch (report[0])
368 case CHILD_CHDIR_FAILED:
369 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_CHDIR,
370 _("Failed to change to directory '%s' (%s)"),
371 working_directory,
372 g_strerror (report[1]));
373 break;
374 case CHILD_SPAWN_FAILED:
375 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
376 _("Failed to execute child process (%s)"),
377 g_strerror (report[1]));
378 break;
379 default:
380 g_assert_not_reached ();
384 static gboolean
385 utf8_charv_to_wcharv (char **utf8_charv,
386 wchar_t ***wcharv,
387 int *error_index,
388 GError **error)
390 wchar_t **retval = NULL;
392 *wcharv = NULL;
393 if (utf8_charv != NULL)
395 int n = 0, i;
397 while (utf8_charv[n])
398 n++;
399 retval = g_new (wchar_t *, n + 1);
401 for (i = 0; i < n; i++)
403 retval[i] = g_utf8_to_utf16 (utf8_charv[i], -1, NULL, NULL, error);
404 if (retval[i] == NULL)
406 if (error_index)
407 *error_index = i;
408 while (i)
409 g_free (retval[--i]);
410 g_free (retval);
411 return FALSE;
415 retval[n] = NULL;
417 *wcharv = retval;
418 return TRUE;
421 static gboolean
422 do_spawn_directly (gint *exit_status,
423 gboolean do_return_handle,
424 GSpawnFlags flags,
425 gchar **argv,
426 char **envp,
427 char **protected_argv,
428 GPid *child_handle,
429 GError **error)
431 const int mode = (exit_status == NULL) ? P_NOWAIT : P_WAIT;
432 char **new_argv;
433 gintptr rc = -1;
434 int saved_errno;
435 GError *conv_error = NULL;
436 gint conv_error_index;
437 wchar_t *wargv0, **wargv, **wenvp;
439 new_argv = (flags & G_SPAWN_FILE_AND_ARGV_ZERO) ? protected_argv + 1 : protected_argv;
441 wargv0 = g_utf8_to_utf16 (argv[0], -1, NULL, NULL, &conv_error);
442 if (wargv0 == NULL)
444 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
445 _("Invalid program name: %s"),
446 conv_error->message);
447 g_error_free (conv_error);
449 return FALSE;
452 if (!utf8_charv_to_wcharv (new_argv, &wargv, &conv_error_index, &conv_error))
454 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
455 _("Invalid string in argument vector at %d: %s"),
456 conv_error_index, conv_error->message);
457 g_error_free (conv_error);
458 g_free (wargv0);
460 return FALSE;
463 if (!utf8_charv_to_wcharv (envp, &wenvp, NULL, &conv_error))
465 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
466 _("Invalid string in environment: %s"),
467 conv_error->message);
468 g_error_free (conv_error);
469 g_free (wargv0);
470 g_strfreev ((gchar **) wargv);
472 return FALSE;
475 if (flags & G_SPAWN_SEARCH_PATH)
476 if (wenvp != NULL)
477 rc = _wspawnvpe (mode, wargv0, (const wchar_t **) wargv, (const wchar_t **) wenvp);
478 else
479 rc = _wspawnvp (mode, wargv0, (const wchar_t **) wargv);
480 else
481 if (wenvp != NULL)
482 rc = _wspawnve (mode, wargv0, (const wchar_t **) wargv, (const wchar_t **) wenvp);
483 else
484 rc = _wspawnv (mode, wargv0, (const wchar_t **) wargv);
486 g_free (wargv0);
487 g_strfreev ((gchar **) wargv);
488 g_strfreev ((gchar **) wenvp);
490 saved_errno = errno;
492 if (rc == -1 && saved_errno != 0)
494 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
495 _("Failed to execute child process (%s)"),
496 g_strerror (saved_errno));
497 return FALSE;
500 if (exit_status == NULL)
502 if (child_handle && do_return_handle)
503 *child_handle = (GPid) rc;
504 else
506 CloseHandle ((HANDLE) rc);
507 if (child_handle)
508 *child_handle = 0;
511 else
512 *exit_status = rc;
514 return TRUE;
517 static gboolean
518 do_spawn_with_pipes (gint *exit_status,
519 gboolean do_return_handle,
520 const gchar *working_directory,
521 gchar **argv,
522 char **envp,
523 GSpawnFlags flags,
524 GSpawnChildSetupFunc child_setup,
525 GPid *child_handle,
526 gint *standard_input,
527 gint *standard_output,
528 gint *standard_error,
529 gint *err_report,
530 GError **error)
532 char **protected_argv;
533 char args[ARG_COUNT][10];
534 char **new_argv;
535 int i;
536 gintptr rc = -1;
537 int saved_errno;
538 int argc;
539 int stdin_pipe[2] = { -1, -1 };
540 int stdout_pipe[2] = { -1, -1 };
541 int stderr_pipe[2] = { -1, -1 };
542 int child_err_report_pipe[2] = { -1, -1 };
543 int helper_sync_pipe[2] = { -1, -1 };
544 gintptr helper_report[2];
545 static gboolean warned_about_child_setup = FALSE;
546 GError *conv_error = NULL;
547 gint conv_error_index;
548 gchar *helper_process;
549 CONSOLE_CURSOR_INFO cursor_info;
550 wchar_t *whelper, **wargv, **wenvp;
551 gchar *glib_dll_directory;
553 if (child_setup && !warned_about_child_setup)
555 warned_about_child_setup = TRUE;
556 g_warning ("passing a child setup function to the g_spawn functions is pointless on Windows and it is ignored");
559 argc = protect_argv (argv, &protected_argv);
561 if (!standard_input && !standard_output && !standard_error &&
562 (flags & G_SPAWN_CHILD_INHERITS_STDIN) &&
563 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL) &&
564 !(flags & G_SPAWN_STDERR_TO_DEV_NULL) &&
565 (working_directory == NULL || !*working_directory) &&
566 (flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN))
568 /* We can do without the helper process */
569 gboolean retval =
570 do_spawn_directly (exit_status, do_return_handle, flags,
571 argv, envp, protected_argv,
572 child_handle, error);
573 g_strfreev (protected_argv);
574 return retval;
577 if (standard_input && !make_pipe (stdin_pipe, error))
578 goto cleanup_and_fail;
580 if (standard_output && !make_pipe (stdout_pipe, error))
581 goto cleanup_and_fail;
583 if (standard_error && !make_pipe (stderr_pipe, error))
584 goto cleanup_and_fail;
586 if (!make_pipe (child_err_report_pipe, error))
587 goto cleanup_and_fail;
589 if (!make_pipe (helper_sync_pipe, error))
590 goto cleanup_and_fail;
592 new_argv = g_new (char *, argc + 1 + ARG_COUNT);
593 if (GetConsoleWindow () != NULL)
594 helper_process = HELPER_PROCESS "-console.exe";
595 else
596 helper_process = HELPER_PROCESS ".exe";
598 glib_dll_directory = _glib_get_dll_directory ();
599 if (glib_dll_directory != NULL)
601 helper_process = g_build_filename (glib_dll_directory, helper_process, NULL);
602 g_free (glib_dll_directory);
604 else
605 helper_process = g_strdup (helper_process);
607 new_argv[0] = protect_argv_string (helper_process);
609 _g_sprintf (args[ARG_CHILD_ERR_REPORT], "%d", child_err_report_pipe[1]);
610 new_argv[ARG_CHILD_ERR_REPORT] = args[ARG_CHILD_ERR_REPORT];
612 /* Make the read end of the child error report pipe
613 * noninherited. Otherwise it will needlessly be inherited by the
614 * helper process, and the started actual user process. As such that
615 * shouldn't harm, but it is unnecessary.
617 child_err_report_pipe[0] = dup_noninherited (child_err_report_pipe[0], _O_RDONLY);
619 if (flags & G_SPAWN_FILE_AND_ARGV_ZERO)
621 /* Overload ARG_CHILD_ERR_REPORT to also encode the
622 * G_SPAWN_FILE_AND_ARGV_ZERO functionality.
624 strcat (args[ARG_CHILD_ERR_REPORT], "#");
627 _g_sprintf (args[ARG_HELPER_SYNC], "%d", helper_sync_pipe[0]);
628 new_argv[ARG_HELPER_SYNC] = args[ARG_HELPER_SYNC];
630 /* Make the write end of the sync pipe noninherited. Otherwise the
631 * helper process will inherit it, and thus if this process happens
632 * to crash before writing the sync byte to the pipe, the helper
633 * process won't read but won't get any EOF either, as it has the
634 * write end open itself.
636 helper_sync_pipe[1] = dup_noninherited (helper_sync_pipe[1], _O_WRONLY);
638 if (standard_input)
640 _g_sprintf (args[ARG_STDIN], "%d", stdin_pipe[0]);
641 new_argv[ARG_STDIN] = args[ARG_STDIN];
643 else if (flags & G_SPAWN_CHILD_INHERITS_STDIN)
645 /* Let stdin be alone */
646 new_argv[ARG_STDIN] = "-";
648 else
650 /* Keep process from blocking on a read of stdin */
651 new_argv[ARG_STDIN] = "z";
654 if (standard_output)
656 _g_sprintf (args[ARG_STDOUT], "%d", stdout_pipe[1]);
657 new_argv[ARG_STDOUT] = args[ARG_STDOUT];
659 else if (flags & G_SPAWN_STDOUT_TO_DEV_NULL)
661 new_argv[ARG_STDOUT] = "z";
663 else
665 new_argv[ARG_STDOUT] = "-";
668 if (standard_error)
670 _g_sprintf (args[ARG_STDERR], "%d", stderr_pipe[1]);
671 new_argv[ARG_STDERR] = args[ARG_STDERR];
673 else if (flags & G_SPAWN_STDERR_TO_DEV_NULL)
675 new_argv[ARG_STDERR] = "z";
677 else
679 new_argv[ARG_STDERR] = "-";
682 if (working_directory && *working_directory)
683 new_argv[ARG_WORKING_DIRECTORY] = protect_argv_string (working_directory);
684 else
685 new_argv[ARG_WORKING_DIRECTORY] = g_strdup ("-");
687 if (!(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN))
688 new_argv[ARG_CLOSE_DESCRIPTORS] = "y";
689 else
690 new_argv[ARG_CLOSE_DESCRIPTORS] = "-";
692 if (flags & G_SPAWN_SEARCH_PATH)
693 new_argv[ARG_USE_PATH] = "y";
694 else
695 new_argv[ARG_USE_PATH] = "-";
697 if (exit_status == NULL)
698 new_argv[ARG_WAIT] = "-";
699 else
700 new_argv[ARG_WAIT] = "w";
702 for (i = 0; i <= argc; i++)
703 new_argv[ARG_PROGRAM + i] = protected_argv[i];
705 SETUP_DEBUG();
707 if (debug)
709 g_print ("calling %s with argv:\n", helper_process);
710 for (i = 0; i < argc + 1 + ARG_COUNT; i++)
711 g_print ("argv[%d]: %s\n", i, (new_argv[i] ? new_argv[i] : "NULL"));
714 if (!utf8_charv_to_wcharv (new_argv, &wargv, &conv_error_index, &conv_error))
716 if (conv_error_index == ARG_WORKING_DIRECTORY)
717 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_CHDIR,
718 _("Invalid working directory: %s"),
719 conv_error->message);
720 else
721 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
722 _("Invalid string in argument vector at %d: %s"),
723 conv_error_index - ARG_PROGRAM, conv_error->message);
724 g_error_free (conv_error);
725 g_strfreev (protected_argv);
726 g_free (new_argv[0]);
727 g_free (new_argv[ARG_WORKING_DIRECTORY]);
728 g_free (new_argv);
729 g_free (helper_process);
731 goto cleanup_and_fail;
734 if (!utf8_charv_to_wcharv (envp, &wenvp, NULL, &conv_error))
736 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
737 _("Invalid string in environment: %s"),
738 conv_error->message);
739 g_error_free (conv_error);
740 g_strfreev (protected_argv);
741 g_free (new_argv[0]);
742 g_free (new_argv[ARG_WORKING_DIRECTORY]);
743 g_free (new_argv);
744 g_free (helper_process);
745 g_strfreev ((gchar **) wargv);
747 goto cleanup_and_fail;
750 whelper = g_utf8_to_utf16 (helper_process, -1, NULL, NULL, NULL);
751 g_free (helper_process);
753 if (wenvp != NULL)
754 rc = _wspawnvpe (P_NOWAIT, whelper, (const wchar_t **) wargv, (const wchar_t **) wenvp);
755 else
756 rc = _wspawnvp (P_NOWAIT, whelper, (const wchar_t **) wargv);
758 saved_errno = errno;
760 g_free (whelper);
761 g_strfreev ((gchar **) wargv);
762 g_strfreev ((gchar **) wenvp);
764 /* Close the other process's ends of the pipes in this process,
765 * otherwise the reader will never get EOF.
767 close_and_invalidate (&child_err_report_pipe[1]);
768 close_and_invalidate (&helper_sync_pipe[0]);
769 close_and_invalidate (&stdin_pipe[0]);
770 close_and_invalidate (&stdout_pipe[1]);
771 close_and_invalidate (&stderr_pipe[1]);
773 g_strfreev (protected_argv);
775 g_free (new_argv[0]);
776 g_free (new_argv[ARG_WORKING_DIRECTORY]);
777 g_free (new_argv);
779 /* Check if gspawn-win32-helper couldn't be run */
780 if (rc == -1 && saved_errno != 0)
782 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
783 _("Failed to execute helper program (%s)"),
784 g_strerror (saved_errno));
785 goto cleanup_and_fail;
788 if (exit_status != NULL)
790 /* Synchronous case. Pass helper's report pipe back to caller,
791 * which takes care of reading it after the grandchild has
792 * finished.
794 g_assert (err_report != NULL);
795 *err_report = child_err_report_pipe[0];
796 write (helper_sync_pipe[1], " ", 1);
797 close_and_invalidate (&helper_sync_pipe[1]);
799 else
801 /* Asynchronous case. We read the helper's report right away. */
802 if (!read_helper_report (child_err_report_pipe[0], helper_report, error))
803 goto cleanup_and_fail;
805 close_and_invalidate (&child_err_report_pipe[0]);
807 switch (helper_report[0])
809 case CHILD_NO_ERROR:
810 if (child_handle && do_return_handle)
812 /* rc is our HANDLE for gspawn-win32-helper. It has
813 * told us the HANDLE of its child. Duplicate that into
814 * a HANDLE valid in this process.
816 if (!DuplicateHandle ((HANDLE) rc, (HANDLE) helper_report[1],
817 GetCurrentProcess (), (LPHANDLE) child_handle,
818 0, TRUE, DUPLICATE_SAME_ACCESS))
820 char *emsg = g_win32_error_message (GetLastError ());
821 g_print("%s\n", emsg);
822 *child_handle = 0;
825 else if (child_handle)
826 *child_handle = 0;
827 write (helper_sync_pipe[1], " ", 1);
828 close_and_invalidate (&helper_sync_pipe[1]);
829 break;
831 default:
832 write (helper_sync_pipe[1], " ", 1);
833 close_and_invalidate (&helper_sync_pipe[1]);
834 set_child_error (helper_report, working_directory, error);
835 goto cleanup_and_fail;
839 /* Success against all odds! return the information */
841 if (standard_input)
842 *standard_input = stdin_pipe[1];
843 if (standard_output)
844 *standard_output = stdout_pipe[0];
845 if (standard_error)
846 *standard_error = stderr_pipe[0];
847 if (rc != -1)
848 CloseHandle ((HANDLE) rc);
850 return TRUE;
852 cleanup_and_fail:
854 if (rc != -1)
855 CloseHandle ((HANDLE) rc);
856 if (child_err_report_pipe[0] != -1)
857 close (child_err_report_pipe[0]);
858 if (child_err_report_pipe[1] != -1)
859 close (child_err_report_pipe[1]);
860 if (helper_sync_pipe[0] != -1)
861 close (helper_sync_pipe[0]);
862 if (helper_sync_pipe[1] != -1)
863 close (helper_sync_pipe[1]);
864 if (stdin_pipe[0] != -1)
865 close (stdin_pipe[0]);
866 if (stdin_pipe[1] != -1)
867 close (stdin_pipe[1]);
868 if (stdout_pipe[0] != -1)
869 close (stdout_pipe[0]);
870 if (stdout_pipe[1] != -1)
871 close (stdout_pipe[1]);
872 if (stderr_pipe[0] != -1)
873 close (stderr_pipe[0]);
874 if (stderr_pipe[1] != -1)
875 close (stderr_pipe[1]);
877 return FALSE;
880 gboolean
881 g_spawn_sync_utf8 (const gchar *working_directory,
882 gchar **argv,
883 gchar **envp,
884 GSpawnFlags flags,
885 GSpawnChildSetupFunc child_setup,
886 gpointer user_data,
887 gchar **standard_output,
888 gchar **standard_error,
889 gint *exit_status,
890 GError **error)
892 gint outpipe = -1;
893 gint errpipe = -1;
894 gint reportpipe = -1;
895 GIOChannel *outchannel = NULL;
896 GIOChannel *errchannel = NULL;
897 GPollFD outfd, errfd;
898 GPollFD fds[2];
899 gint nfds;
900 gint outindex = -1;
901 gint errindex = -1;
902 gint ret;
903 GString *outstr = NULL;
904 GString *errstr = NULL;
905 gboolean failed;
906 gint status;
908 g_return_val_if_fail (argv != NULL, FALSE);
909 g_return_val_if_fail (!(flags & G_SPAWN_DO_NOT_REAP_CHILD), FALSE);
910 g_return_val_if_fail (standard_output == NULL ||
911 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
912 g_return_val_if_fail (standard_error == NULL ||
913 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
915 /* Just to ensure segfaults if callers try to use
916 * these when an error is reported.
918 if (standard_output)
919 *standard_output = NULL;
921 if (standard_error)
922 *standard_error = NULL;
924 if (!do_spawn_with_pipes (&status,
925 FALSE,
926 working_directory,
927 argv,
928 envp,
929 flags,
930 child_setup,
931 NULL,
932 NULL,
933 standard_output ? &outpipe : NULL,
934 standard_error ? &errpipe : NULL,
935 &reportpipe,
936 error))
937 return FALSE;
939 /* Read data from child. */
941 failed = FALSE;
943 if (outpipe >= 0)
945 outstr = g_string_new (NULL);
946 outchannel = g_io_channel_win32_new_fd (outpipe);
947 g_io_channel_set_encoding (outchannel, NULL, NULL);
948 g_io_channel_set_buffered (outchannel, FALSE);
949 g_io_channel_win32_make_pollfd (outchannel,
950 G_IO_IN | G_IO_ERR | G_IO_HUP,
951 &outfd);
952 if (debug)
953 g_print ("outfd=%p\n", (HANDLE) outfd.fd);
956 if (errpipe >= 0)
958 errstr = g_string_new (NULL);
959 errchannel = g_io_channel_win32_new_fd (errpipe);
960 g_io_channel_set_encoding (errchannel, NULL, NULL);
961 g_io_channel_set_buffered (errchannel, FALSE);
962 g_io_channel_win32_make_pollfd (errchannel,
963 G_IO_IN | G_IO_ERR | G_IO_HUP,
964 &errfd);
965 if (debug)
966 g_print ("errfd=%p\n", (HANDLE) errfd.fd);
969 /* Read data until we get EOF on all pipes. */
970 while (!failed && (outpipe >= 0 || errpipe >= 0))
972 nfds = 0;
973 if (outpipe >= 0)
975 fds[nfds] = outfd;
976 outindex = nfds;
977 nfds++;
979 if (errpipe >= 0)
981 fds[nfds] = errfd;
982 errindex = nfds;
983 nfds++;
986 if (debug)
987 g_print ("g_spawn_sync: calling g_io_channel_win32_poll, nfds=%d\n",
988 nfds);
990 ret = g_io_channel_win32_poll (fds, nfds, -1);
992 if (ret < 0)
994 failed = TRUE;
996 g_set_error_literal (error, G_SPAWN_ERROR, G_SPAWN_ERROR_READ,
997 _("Unexpected error in g_io_channel_win32_poll() reading data from a child process"));
999 break;
1002 if (outpipe >= 0 && (fds[outindex].revents & G_IO_IN))
1004 switch (read_data (outstr, outchannel, error))
1006 case READ_FAILED:
1007 if (debug)
1008 g_print ("g_spawn_sync: outchannel: READ_FAILED\n");
1009 failed = TRUE;
1010 break;
1011 case READ_EOF:
1012 if (debug)
1013 g_print ("g_spawn_sync: outchannel: READ_EOF\n");
1014 g_io_channel_unref (outchannel);
1015 outchannel = NULL;
1016 close_and_invalidate (&outpipe);
1017 break;
1018 default:
1019 if (debug)
1020 g_print ("g_spawn_sync: outchannel: OK\n");
1021 break;
1024 if (failed)
1025 break;
1028 if (errpipe >= 0 && (fds[errindex].revents & G_IO_IN))
1030 switch (read_data (errstr, errchannel, error))
1032 case READ_FAILED:
1033 if (debug)
1034 g_print ("g_spawn_sync: errchannel: READ_FAILED\n");
1035 failed = TRUE;
1036 break;
1037 case READ_EOF:
1038 if (debug)
1039 g_print ("g_spawn_sync: errchannel: READ_EOF\n");
1040 g_io_channel_unref (errchannel);
1041 errchannel = NULL;
1042 close_and_invalidate (&errpipe);
1043 break;
1044 default:
1045 if (debug)
1046 g_print ("g_spawn_sync: errchannel: OK\n");
1047 break;
1050 if (failed)
1051 break;
1055 if (reportpipe == -1)
1057 /* No helper process, exit status of actual spawned process
1058 * already available.
1060 if (exit_status)
1061 *exit_status = status;
1063 else
1065 /* Helper process was involved. Read its report now after the
1066 * grandchild has finished.
1068 gintptr helper_report[2];
1070 if (!read_helper_report (reportpipe, helper_report, error))
1071 failed = TRUE;
1072 else
1074 switch (helper_report[0])
1076 case CHILD_NO_ERROR:
1077 if (exit_status)
1078 *exit_status = helper_report[1];
1079 break;
1080 default:
1081 set_child_error (helper_report, working_directory, error);
1082 failed = TRUE;
1083 break;
1086 close_and_invalidate (&reportpipe);
1090 /* These should only be open still if we had an error. */
1092 if (outchannel != NULL)
1093 g_io_channel_unref (outchannel);
1094 if (errchannel != NULL)
1095 g_io_channel_unref (errchannel);
1096 if (outpipe >= 0)
1097 close_and_invalidate (&outpipe);
1098 if (errpipe >= 0)
1099 close_and_invalidate (&errpipe);
1101 if (failed)
1103 if (outstr)
1104 g_string_free (outstr, TRUE);
1105 if (errstr)
1106 g_string_free (errstr, TRUE);
1108 return FALSE;
1110 else
1112 if (standard_output)
1113 *standard_output = g_string_free (outstr, FALSE);
1115 if (standard_error)
1116 *standard_error = g_string_free (errstr, FALSE);
1118 return TRUE;
1122 gboolean
1123 g_spawn_async_with_pipes_utf8 (const gchar *working_directory,
1124 gchar **argv,
1125 gchar **envp,
1126 GSpawnFlags flags,
1127 GSpawnChildSetupFunc child_setup,
1128 gpointer user_data,
1129 GPid *child_handle,
1130 gint *standard_input,
1131 gint *standard_output,
1132 gint *standard_error,
1133 GError **error)
1135 g_return_val_if_fail (argv != NULL, FALSE);
1136 g_return_val_if_fail (standard_output == NULL ||
1137 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
1138 g_return_val_if_fail (standard_error == NULL ||
1139 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
1140 /* can't inherit stdin if we have an input pipe. */
1141 g_return_val_if_fail (standard_input == NULL ||
1142 !(flags & G_SPAWN_CHILD_INHERITS_STDIN), FALSE);
1144 return do_spawn_with_pipes (NULL,
1145 (flags & G_SPAWN_DO_NOT_REAP_CHILD),
1146 working_directory,
1147 argv,
1148 envp,
1149 flags,
1150 child_setup,
1151 child_handle,
1152 standard_input,
1153 standard_output,
1154 standard_error,
1155 NULL,
1156 error);
1159 gboolean
1160 g_spawn_command_line_sync_utf8 (const gchar *command_line,
1161 gchar **standard_output,
1162 gchar **standard_error,
1163 gint *exit_status,
1164 GError **error)
1166 gboolean retval;
1167 gchar **argv = 0;
1169 g_return_val_if_fail (command_line != NULL, FALSE);
1171 if (!g_shell_parse_argv (command_line,
1172 NULL, &argv,
1173 error))
1174 return FALSE;
1176 retval = g_spawn_sync_utf8 (NULL,
1177 argv,
1178 NULL,
1179 G_SPAWN_SEARCH_PATH,
1180 NULL,
1181 NULL,
1182 standard_output,
1183 standard_error,
1184 exit_status,
1185 error);
1186 g_strfreev (argv);
1188 return retval;
1191 gboolean
1192 g_spawn_command_line_async_utf8 (const gchar *command_line,
1193 GError **error)
1195 gboolean retval;
1196 gchar **argv = 0;
1198 g_return_val_if_fail (command_line != NULL, FALSE);
1200 if (!g_shell_parse_argv (command_line,
1201 NULL, &argv,
1202 error))
1203 return FALSE;
1205 retval = g_spawn_async_utf8 (NULL,
1206 argv,
1207 NULL,
1208 G_SPAWN_SEARCH_PATH,
1209 NULL,
1210 NULL,
1211 NULL,
1212 error);
1213 g_strfreev (argv);
1215 return retval;
1218 void
1219 g_spawn_close_pid (GPid pid)
1221 CloseHandle (pid);
1224 gboolean
1225 g_spawn_check_exit_status (gint exit_status,
1226 GError **error)
1228 gboolean ret = FALSE;
1230 if (exit_status != 0)
1232 g_set_error (error, G_SPAWN_EXIT_ERROR, exit_status,
1233 _("Child process exited with code %ld"),
1234 (long) exit_status);
1235 goto out;
1238 ret = TRUE;
1239 out:
1240 return ret;
1243 #if !defined (_WIN64)
1245 /* Binary compatibility versions that take system codepage pathnames,
1246 * argument vectors and environments. These get used only by code
1247 * built against 2.8.1 or earlier. Code built against 2.8.2 or later
1248 * will use the _utf8 versions above (see the #defines in gspawn.h).
1251 #undef g_spawn_async
1252 #undef g_spawn_async_with_pipes
1253 #undef g_spawn_sync
1254 #undef g_spawn_command_line_sync
1255 #undef g_spawn_command_line_async
1257 static gboolean
1258 setup_utf8_copies (const gchar *working_directory,
1259 gchar **utf8_working_directory,
1260 gchar **argv,
1261 gchar ***utf8_argv,
1262 gchar **envp,
1263 gchar ***utf8_envp,
1264 GError **error)
1266 gint i, argc, envc;
1268 if (working_directory == NULL)
1269 *utf8_working_directory = NULL;
1270 else
1272 GError *conv_error = NULL;
1274 *utf8_working_directory = g_locale_to_utf8 (working_directory, -1, NULL, NULL, &conv_error);
1275 if (*utf8_working_directory == NULL)
1277 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_CHDIR,
1278 _("Invalid working directory: %s"),
1279 conv_error->message);
1280 g_error_free (conv_error);
1281 return FALSE;
1285 argc = 0;
1286 while (argv[argc])
1287 ++argc;
1288 *utf8_argv = g_new (gchar *, argc + 1);
1289 for (i = 0; i < argc; i++)
1291 GError *conv_error = NULL;
1293 (*utf8_argv)[i] = g_locale_to_utf8 (argv[i], -1, NULL, NULL, &conv_error);
1294 if ((*utf8_argv)[i] == NULL)
1296 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
1297 _("Invalid string in argument vector at %d: %s"),
1298 i, conv_error->message);
1299 g_error_free (conv_error);
1301 g_strfreev (*utf8_argv);
1302 *utf8_argv = NULL;
1304 g_free (*utf8_working_directory);
1305 *utf8_working_directory = NULL;
1307 return FALSE;
1310 (*utf8_argv)[argc] = NULL;
1312 if (envp == NULL)
1314 *utf8_envp = NULL;
1316 else
1318 envc = 0;
1319 while (envp[envc])
1320 ++envc;
1321 *utf8_envp = g_new (gchar *, envc + 1);
1322 for (i = 0; i < envc; i++)
1324 GError *conv_error = NULL;
1326 (*utf8_envp)[i] = g_locale_to_utf8 (envp[i], -1, NULL, NULL, &conv_error);
1327 if ((*utf8_envp)[i] == NULL)
1329 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
1330 _("Invalid string in environment: %s"),
1331 conv_error->message);
1332 g_error_free (conv_error);
1334 g_strfreev (*utf8_envp);
1335 *utf8_envp = NULL;
1337 g_strfreev (*utf8_argv);
1338 *utf8_argv = NULL;
1340 g_free (*utf8_working_directory);
1341 *utf8_working_directory = NULL;
1343 return FALSE;
1346 (*utf8_envp)[envc] = NULL;
1348 return TRUE;
1351 static void
1352 free_utf8_copies (gchar *utf8_working_directory,
1353 gchar **utf8_argv,
1354 gchar **utf8_envp)
1356 g_free (utf8_working_directory);
1357 g_strfreev (utf8_argv);
1358 g_strfreev (utf8_envp);
1361 gboolean
1362 g_spawn_async_with_pipes (const gchar *working_directory,
1363 gchar **argv,
1364 gchar **envp,
1365 GSpawnFlags flags,
1366 GSpawnChildSetupFunc child_setup,
1367 gpointer user_data,
1368 GPid *child_handle,
1369 gint *standard_input,
1370 gint *standard_output,
1371 gint *standard_error,
1372 GError **error)
1374 gchar *utf8_working_directory;
1375 gchar **utf8_argv;
1376 gchar **utf8_envp;
1377 gboolean retval;
1379 if (!setup_utf8_copies (working_directory, &utf8_working_directory,
1380 argv, &utf8_argv,
1381 envp, &utf8_envp,
1382 error))
1383 return FALSE;
1385 retval = g_spawn_async_with_pipes_utf8 (utf8_working_directory,
1386 utf8_argv, utf8_envp,
1387 flags, child_setup, user_data,
1388 child_handle,
1389 standard_input, standard_output, standard_error,
1390 error);
1392 free_utf8_copies (utf8_working_directory, utf8_argv, utf8_envp);
1394 return retval;
1397 gboolean
1398 g_spawn_async (const gchar *working_directory,
1399 gchar **argv,
1400 gchar **envp,
1401 GSpawnFlags flags,
1402 GSpawnChildSetupFunc child_setup,
1403 gpointer user_data,
1404 GPid *child_handle,
1405 GError **error)
1407 return g_spawn_async_with_pipes (working_directory,
1408 argv, envp,
1409 flags,
1410 child_setup,
1411 user_data,
1412 child_handle,
1413 NULL, NULL, NULL,
1414 error);
1417 gboolean
1418 g_spawn_sync (const gchar *working_directory,
1419 gchar **argv,
1420 gchar **envp,
1421 GSpawnFlags flags,
1422 GSpawnChildSetupFunc child_setup,
1423 gpointer user_data,
1424 gchar **standard_output,
1425 gchar **standard_error,
1426 gint *exit_status,
1427 GError **error)
1429 gchar *utf8_working_directory;
1430 gchar **utf8_argv;
1431 gchar **utf8_envp;
1432 gboolean retval;
1434 if (!setup_utf8_copies (working_directory, &utf8_working_directory,
1435 argv, &utf8_argv,
1436 envp, &utf8_envp,
1437 error))
1438 return FALSE;
1440 retval = g_spawn_sync_utf8 (utf8_working_directory,
1441 utf8_argv, utf8_envp,
1442 flags, child_setup, user_data,
1443 standard_output, standard_error, exit_status,
1444 error);
1446 free_utf8_copies (utf8_working_directory, utf8_argv, utf8_envp);
1448 return retval;
1451 gboolean
1452 g_spawn_command_line_sync (const gchar *command_line,
1453 gchar **standard_output,
1454 gchar **standard_error,
1455 gint *exit_status,
1456 GError **error)
1458 gboolean retval;
1459 gchar **argv = 0;
1461 g_return_val_if_fail (command_line != NULL, FALSE);
1463 if (!g_shell_parse_argv (command_line,
1464 NULL, &argv,
1465 error))
1466 return FALSE;
1468 retval = g_spawn_sync (NULL,
1469 argv,
1470 NULL,
1471 G_SPAWN_SEARCH_PATH,
1472 NULL,
1473 NULL,
1474 standard_output,
1475 standard_error,
1476 exit_status,
1477 error);
1478 g_strfreev (argv);
1480 return retval;
1483 gboolean
1484 g_spawn_command_line_async (const gchar *command_line,
1485 GError **error)
1487 gboolean retval;
1488 gchar **argv = 0;
1490 g_return_val_if_fail (command_line != NULL, FALSE);
1492 if (!g_shell_parse_argv (command_line,
1493 NULL, &argv,
1494 error))
1495 return FALSE;
1497 retval = g_spawn_async (NULL,
1498 argv,
1499 NULL,
1500 G_SPAWN_SEARCH_PATH,
1501 NULL,
1502 NULL,
1503 NULL,
1504 error);
1505 g_strfreev (argv);
1507 return retval;
1510 #endif /* !_WIN64 */
1512 #endif /* !GSPAWN_HELPER */