Use G_DEFINE_QUARK for GLib's own quarks
[glib.git] / glib / gspawn-win32.c
blobe5d0a16987f96be1253379a1449f26c306dfb3a9
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 "gprintfint.h"
49 #include "glibintl.h"
51 #include <string.h>
52 #include <stdlib.h>
53 #include <stdio.h>
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 #include <wchar.h>
63 #ifdef G_SPAWN_WIN32_DEBUG
64 static int debug = 1;
65 #define SETUP_DEBUG() /* empty */
66 #else
67 static int debug = -1;
68 #define SETUP_DEBUG() \
69 G_STMT_START \
70 { \
71 if (debug == -1) \
72 { \
73 if (getenv ("G_SPAWN_WIN32_DEBUG") != NULL) \
74 debug = 1; \
75 else \
76 debug = 0; \
77 } \
78 } \
79 G_STMT_END
80 #endif
82 enum
84 CHILD_NO_ERROR,
85 CHILD_CHDIR_FAILED,
86 CHILD_SPAWN_FAILED,
89 enum {
90 ARG_CHILD_ERR_REPORT = 1,
91 ARG_HELPER_SYNC,
92 ARG_STDIN,
93 ARG_STDOUT,
94 ARG_STDERR,
95 ARG_WORKING_DIRECTORY,
96 ARG_CLOSE_DESCRIPTORS,
97 ARG_USE_PATH,
98 ARG_WAIT,
99 ARG_PROGRAM,
100 ARG_COUNT = ARG_PROGRAM
103 static int
104 dup_noninherited (int fd,
105 int mode)
107 HANDLE filehandle;
109 DuplicateHandle (GetCurrentProcess (), (LPHANDLE) _get_osfhandle (fd),
110 GetCurrentProcess (), &filehandle,
111 0, FALSE, DUPLICATE_SAME_ACCESS);
112 close (fd);
113 return _open_osfhandle ((gintptr) filehandle, mode | _O_NOINHERIT);
116 #ifndef GSPAWN_HELPER
118 #ifdef _WIN64
119 #define HELPER_PROCESS "gspawn-win64-helper"
120 #else
121 #define HELPER_PROCESS "gspawn-win32-helper"
122 #endif
124 static gchar *
125 protect_argv_string (const gchar *string)
127 const gchar *p = string;
128 gchar *retval, *q;
129 gint len = 0;
130 gboolean need_dblquotes = FALSE;
131 while (*p)
133 if (*p == ' ' || *p == '\t')
134 need_dblquotes = TRUE;
135 else if (*p == '"')
136 len++;
137 else if (*p == '\\')
139 const gchar *pp = p;
140 while (*pp && *pp == '\\')
141 pp++;
142 if (*pp == '"')
143 len++;
145 len++;
146 p++;
149 q = retval = g_malloc (len + need_dblquotes*2 + 1);
150 p = string;
152 if (need_dblquotes)
153 *q++ = '"';
155 while (*p)
157 if (*p == '"')
158 *q++ = '\\';
159 else if (*p == '\\')
161 const gchar *pp = p;
162 while (*pp && *pp == '\\')
163 pp++;
164 if (*pp == '"')
165 *q++ = '\\';
167 *q++ = *p;
168 p++;
171 if (need_dblquotes)
172 *q++ = '"';
173 *q++ = '\0';
175 return retval;
178 static gint
179 protect_argv (gchar **argv,
180 gchar ***new_argv)
182 gint i;
183 gint argc = 0;
185 while (argv[argc])
186 ++argc;
187 *new_argv = g_new (gchar *, argc+1);
189 /* Quote each argv element if necessary, so that it will get
190 * reconstructed correctly in the C runtime startup code. Note that
191 * the unquoting algorithm in the C runtime is really weird, and
192 * rather different than what Unix shells do. See stdargv.c in the C
193 * runtime sources (in the Platform SDK, in src/crt).
195 * Note that an new_argv[0] constructed by this function should
196 * *not* be passed as the filename argument to a spawn* or exec*
197 * family function. That argument should be the real file name
198 * without any quoting.
200 for (i = 0; i < argc; i++)
201 (*new_argv)[i] = protect_argv_string (argv[i]);
203 (*new_argv)[argc] = NULL;
205 return argc;
208 G_DEFINE_QUARK ("g-exec-error-quark", g_spawn_error)
209 G_DEFINE_QUARK ("g-spawn-exit-error-quark", g_spawn_exit_error)
211 gboolean
212 g_spawn_async_utf8 (const gchar *working_directory,
213 gchar **argv,
214 gchar **envp,
215 GSpawnFlags flags,
216 GSpawnChildSetupFunc child_setup,
217 gpointer user_data,
218 GPid *child_handle,
219 GError **error)
221 g_return_val_if_fail (argv != NULL, FALSE);
223 return g_spawn_async_with_pipes_utf8 (working_directory,
224 argv, envp,
225 flags,
226 child_setup,
227 user_data,
228 child_handle,
229 NULL, NULL, NULL,
230 error);
233 /* Avoids a danger in threaded situations (calling close()
234 * on a file descriptor twice, and another thread has
235 * re-opened it since the first close)
237 static void
238 close_and_invalidate (gint *fd)
240 if (*fd < 0)
241 return;
243 close (*fd);
244 *fd = -1;
247 typedef enum
249 READ_FAILED = 0, /* FALSE */
250 READ_OK,
251 READ_EOF
252 } ReadResult;
254 static ReadResult
255 read_data (GString *str,
256 GIOChannel *iochannel,
257 GError **error)
259 GIOStatus giostatus;
260 gsize bytes;
261 gchar buf[4096];
263 again:
265 giostatus = g_io_channel_read_chars (iochannel, buf, sizeof (buf), &bytes, NULL);
267 if (bytes == 0)
268 return READ_EOF;
269 else if (bytes > 0)
271 g_string_append_len (str, buf, bytes);
272 return READ_OK;
274 else if (giostatus == G_IO_STATUS_AGAIN)
275 goto again;
276 else if (giostatus == G_IO_STATUS_ERROR)
278 g_set_error_literal (error, G_SPAWN_ERROR, G_SPAWN_ERROR_READ,
279 _("Failed to read data from child process"));
281 return READ_FAILED;
283 else
284 return READ_OK;
287 static gboolean
288 make_pipe (gint p[2],
289 GError **error)
291 if (_pipe (p, 4096, _O_BINARY) < 0)
293 int errsv = errno;
295 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
296 _("Failed to create pipe for communicating with child process (%s)"),
297 g_strerror (errsv));
298 return FALSE;
300 else
301 return TRUE;
304 /* The helper process writes a status report back to us, through a
305 * pipe, consisting of two ints.
307 static gboolean
308 read_helper_report (int fd,
309 gintptr report[2],
310 GError **error)
312 gint bytes = 0;
314 while (bytes < sizeof(gintptr)*2)
316 gint chunk;
318 if (debug)
319 g_print ("%s:read_helper_report: read %" G_GSIZE_FORMAT "...\n",
320 __FILE__,
321 sizeof(gintptr)*2 - bytes);
323 chunk = read (fd, ((gchar*)report) + bytes,
324 sizeof(gintptr)*2 - bytes);
326 if (debug)
327 g_print ("...got %d bytes\n", chunk);
329 if (chunk < 0)
331 int errsv = errno;
333 /* Some weird shit happened, bail out */
334 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
335 _("Failed to read from child pipe (%s)"),
336 g_strerror (errsv));
338 return FALSE;
340 else if (chunk == 0)
342 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
343 _("Failed to read from child pipe (%s)"),
344 "EOF");
345 break; /* EOF */
347 else
348 bytes += chunk;
351 if (bytes < sizeof(gintptr)*2)
352 return FALSE;
354 return TRUE;
357 static void
358 set_child_error (gintptr report[2],
359 const gchar *working_directory,
360 GError **error)
362 switch (report[0])
364 case CHILD_CHDIR_FAILED:
365 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_CHDIR,
366 _("Failed to change to directory '%s' (%s)"),
367 working_directory,
368 g_strerror (report[1]));
369 break;
370 case CHILD_SPAWN_FAILED:
371 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
372 _("Failed to execute child process (%s)"),
373 g_strerror (report[1]));
374 break;
375 default:
376 g_assert_not_reached ();
380 static gboolean
381 utf8_charv_to_wcharv (char **utf8_charv,
382 wchar_t ***wcharv,
383 int *error_index,
384 GError **error)
386 wchar_t **retval = NULL;
388 *wcharv = NULL;
389 if (utf8_charv != NULL)
391 int n = 0, i;
393 while (utf8_charv[n])
394 n++;
395 retval = g_new (wchar_t *, n + 1);
397 for (i = 0; i < n; i++)
399 retval[i] = g_utf8_to_utf16 (utf8_charv[i], -1, NULL, NULL, error);
400 if (retval[i] == NULL)
402 if (error_index)
403 *error_index = i;
404 while (i)
405 g_free (retval[--i]);
406 g_free (retval);
407 return FALSE;
411 retval[n] = NULL;
413 *wcharv = retval;
414 return TRUE;
417 static gboolean
418 do_spawn_directly (gint *exit_status,
419 gboolean do_return_handle,
420 GSpawnFlags flags,
421 gchar **argv,
422 char **envp,
423 char **protected_argv,
424 GPid *child_handle,
425 GError **error)
427 const int mode = (exit_status == NULL) ? P_NOWAIT : P_WAIT;
428 char **new_argv;
429 gintptr rc = -1;
430 int saved_errno;
431 GError *conv_error = NULL;
432 gint conv_error_index;
433 wchar_t *wargv0, **wargv, **wenvp;
435 new_argv = (flags & G_SPAWN_FILE_AND_ARGV_ZERO) ? protected_argv + 1 : protected_argv;
437 wargv0 = g_utf8_to_utf16 (argv[0], -1, NULL, NULL, &conv_error);
438 if (wargv0 == NULL)
440 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
441 _("Invalid program name: %s"),
442 conv_error->message);
443 g_error_free (conv_error);
445 return FALSE;
448 if (!utf8_charv_to_wcharv (new_argv, &wargv, &conv_error_index, &conv_error))
450 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
451 _("Invalid string in argument vector at %d: %s"),
452 conv_error_index, conv_error->message);
453 g_error_free (conv_error);
454 g_free (wargv0);
456 return FALSE;
459 if (!utf8_charv_to_wcharv (envp, &wenvp, NULL, &conv_error))
461 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
462 _("Invalid string in environment: %s"),
463 conv_error->message);
464 g_error_free (conv_error);
465 g_free (wargv0);
466 g_strfreev ((gchar **) wargv);
468 return FALSE;
471 if (flags & G_SPAWN_SEARCH_PATH)
472 if (wenvp != NULL)
473 rc = _wspawnvpe (mode, wargv0, (const wchar_t **) wargv, (const wchar_t **) wenvp);
474 else
475 rc = _wspawnvp (mode, wargv0, (const wchar_t **) wargv);
476 else
477 if (wenvp != NULL)
478 rc = _wspawnve (mode, wargv0, (const wchar_t **) wargv, (const wchar_t **) wenvp);
479 else
480 rc = _wspawnv (mode, wargv0, (const wchar_t **) wargv);
482 g_free (wargv0);
483 g_strfreev ((gchar **) wargv);
484 g_strfreev ((gchar **) wenvp);
486 saved_errno = errno;
488 if (rc == -1 && saved_errno != 0)
490 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
491 _("Failed to execute child process (%s)"),
492 g_strerror (saved_errno));
493 return FALSE;
496 if (exit_status == NULL)
498 if (child_handle && do_return_handle)
499 *child_handle = (GPid) rc;
500 else
502 CloseHandle ((HANDLE) rc);
503 if (child_handle)
504 *child_handle = 0;
507 else
508 *exit_status = rc;
510 return TRUE;
513 static gboolean
514 do_spawn_with_pipes (gint *exit_status,
515 gboolean do_return_handle,
516 const gchar *working_directory,
517 gchar **argv,
518 char **envp,
519 GSpawnFlags flags,
520 GSpawnChildSetupFunc child_setup,
521 GPid *child_handle,
522 gint *standard_input,
523 gint *standard_output,
524 gint *standard_error,
525 gint *err_report,
526 GError **error)
528 char **protected_argv;
529 char args[ARG_COUNT][10];
530 char **new_argv;
531 int i;
532 gintptr rc = -1;
533 int saved_errno;
534 int argc;
535 int stdin_pipe[2] = { -1, -1 };
536 int stdout_pipe[2] = { -1, -1 };
537 int stderr_pipe[2] = { -1, -1 };
538 int child_err_report_pipe[2] = { -1, -1 };
539 int helper_sync_pipe[2] = { -1, -1 };
540 gintptr helper_report[2];
541 static gboolean warned_about_child_setup = FALSE;
542 GError *conv_error = NULL;
543 gint conv_error_index;
544 gchar *helper_process;
545 CONSOLE_CURSOR_INFO cursor_info;
546 wchar_t *whelper, **wargv, **wenvp;
547 extern gchar *_glib_get_dll_directory (void);
548 gchar *glib_dll_directory;
550 if (child_setup && !warned_about_child_setup)
552 warned_about_child_setup = TRUE;
553 g_warning ("passing a child setup function to the g_spawn functions is pointless on Windows and it is ignored");
556 argc = protect_argv (argv, &protected_argv);
558 if (!standard_input && !standard_output && !standard_error &&
559 (flags & G_SPAWN_CHILD_INHERITS_STDIN) &&
560 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL) &&
561 !(flags & G_SPAWN_STDERR_TO_DEV_NULL) &&
562 (working_directory == NULL || !*working_directory) &&
563 (flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN))
565 /* We can do without the helper process */
566 gboolean retval =
567 do_spawn_directly (exit_status, do_return_handle, flags,
568 argv, envp, protected_argv,
569 child_handle, error);
570 g_strfreev (protected_argv);
571 return retval;
574 if (standard_input && !make_pipe (stdin_pipe, error))
575 goto cleanup_and_fail;
577 if (standard_output && !make_pipe (stdout_pipe, error))
578 goto cleanup_and_fail;
580 if (standard_error && !make_pipe (stderr_pipe, error))
581 goto cleanup_and_fail;
583 if (!make_pipe (child_err_report_pipe, error))
584 goto cleanup_and_fail;
586 if (!make_pipe (helper_sync_pipe, error))
587 goto cleanup_and_fail;
589 new_argv = g_new (char *, argc + 1 + ARG_COUNT);
590 if (GetConsoleCursorInfo (GetStdHandle (STD_OUTPUT_HANDLE), &cursor_info))
591 helper_process = HELPER_PROCESS "-console.exe";
592 else
593 helper_process = HELPER_PROCESS ".exe";
595 glib_dll_directory = _glib_get_dll_directory ();
596 if (glib_dll_directory != NULL)
598 helper_process = g_build_filename (glib_dll_directory, helper_process, NULL);
599 g_free (glib_dll_directory);
601 else
602 helper_process = g_strdup (helper_process);
604 new_argv[0] = protect_argv_string (helper_process);
606 _g_sprintf (args[ARG_CHILD_ERR_REPORT], "%d", child_err_report_pipe[1]);
607 new_argv[ARG_CHILD_ERR_REPORT] = args[ARG_CHILD_ERR_REPORT];
609 /* Make the read end of the child error report pipe
610 * noninherited. Otherwise it will needlessly be inherited by the
611 * helper process, and the started actual user process. As such that
612 * shouldn't harm, but it is unnecessary.
614 child_err_report_pipe[0] = dup_noninherited (child_err_report_pipe[0], _O_RDONLY);
616 if (flags & G_SPAWN_FILE_AND_ARGV_ZERO)
618 /* Overload ARG_CHILD_ERR_REPORT to also encode the
619 * G_SPAWN_FILE_AND_ARGV_ZERO functionality.
621 strcat (args[ARG_CHILD_ERR_REPORT], "#");
624 _g_sprintf (args[ARG_HELPER_SYNC], "%d", helper_sync_pipe[0]);
625 new_argv[ARG_HELPER_SYNC] = args[ARG_HELPER_SYNC];
627 /* Make the write end of the sync pipe noninherited. Otherwise the
628 * helper process will inherit it, and thus if this process happens
629 * to crash before writing the sync byte to the pipe, the helper
630 * process won't read but won't get any EOF either, as it has the
631 * write end open itself.
633 helper_sync_pipe[1] = dup_noninherited (helper_sync_pipe[1], _O_WRONLY);
635 if (standard_input)
637 _g_sprintf (args[ARG_STDIN], "%d", stdin_pipe[0]);
638 new_argv[ARG_STDIN] = args[ARG_STDIN];
640 else if (flags & G_SPAWN_CHILD_INHERITS_STDIN)
642 /* Let stdin be alone */
643 new_argv[ARG_STDIN] = "-";
645 else
647 /* Keep process from blocking on a read of stdin */
648 new_argv[ARG_STDIN] = "z";
651 if (standard_output)
653 _g_sprintf (args[ARG_STDOUT], "%d", stdout_pipe[1]);
654 new_argv[ARG_STDOUT] = args[ARG_STDOUT];
656 else if (flags & G_SPAWN_STDOUT_TO_DEV_NULL)
658 new_argv[ARG_STDOUT] = "z";
660 else
662 new_argv[ARG_STDOUT] = "-";
665 if (standard_error)
667 _g_sprintf (args[ARG_STDERR], "%d", stderr_pipe[1]);
668 new_argv[ARG_STDERR] = args[ARG_STDERR];
670 else if (flags & G_SPAWN_STDERR_TO_DEV_NULL)
672 new_argv[ARG_STDERR] = "z";
674 else
676 new_argv[ARG_STDERR] = "-";
679 if (working_directory && *working_directory)
680 new_argv[ARG_WORKING_DIRECTORY] = protect_argv_string (working_directory);
681 else
682 new_argv[ARG_WORKING_DIRECTORY] = g_strdup ("-");
684 if (!(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN))
685 new_argv[ARG_CLOSE_DESCRIPTORS] = "y";
686 else
687 new_argv[ARG_CLOSE_DESCRIPTORS] = "-";
689 if (flags & G_SPAWN_SEARCH_PATH)
690 new_argv[ARG_USE_PATH] = "y";
691 else
692 new_argv[ARG_USE_PATH] = "-";
694 if (exit_status == NULL)
695 new_argv[ARG_WAIT] = "-";
696 else
697 new_argv[ARG_WAIT] = "w";
699 for (i = 0; i <= argc; i++)
700 new_argv[ARG_PROGRAM + i] = protected_argv[i];
702 SETUP_DEBUG();
704 if (debug)
706 g_print ("calling %s with argv:\n", helper_process);
707 for (i = 0; i < argc + 1 + ARG_COUNT; i++)
708 g_print ("argv[%d]: %s\n", i, (new_argv[i] ? new_argv[i] : "NULL"));
711 if (!utf8_charv_to_wcharv (new_argv, &wargv, &conv_error_index, &conv_error))
713 if (conv_error_index == ARG_WORKING_DIRECTORY)
714 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_CHDIR,
715 _("Invalid working directory: %s"),
716 conv_error->message);
717 else
718 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
719 _("Invalid string in argument vector at %d: %s"),
720 conv_error_index - ARG_PROGRAM, conv_error->message);
721 g_error_free (conv_error);
722 g_strfreev (protected_argv);
723 g_free (new_argv[0]);
724 g_free (new_argv[ARG_WORKING_DIRECTORY]);
725 g_free (new_argv);
726 g_free (helper_process);
728 goto cleanup_and_fail;
731 if (!utf8_charv_to_wcharv (envp, &wenvp, NULL, &conv_error))
733 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
734 _("Invalid string in environment: %s"),
735 conv_error->message);
736 g_error_free (conv_error);
737 g_strfreev (protected_argv);
738 g_free (new_argv[0]);
739 g_free (new_argv[ARG_WORKING_DIRECTORY]);
740 g_free (new_argv);
741 g_free (helper_process);
742 g_strfreev ((gchar **) wargv);
744 goto cleanup_and_fail;
747 whelper = g_utf8_to_utf16 (helper_process, -1, NULL, NULL, NULL);
748 g_free (helper_process);
750 if (wenvp != NULL)
751 rc = _wspawnvpe (P_NOWAIT, whelper, (const wchar_t **) wargv, (const wchar_t **) wenvp);
752 else
753 rc = _wspawnvp (P_NOWAIT, whelper, (const wchar_t **) wargv);
755 saved_errno = errno;
757 g_free (whelper);
758 g_strfreev ((gchar **) wargv);
759 g_strfreev ((gchar **) wenvp);
761 /* Close the other process's ends of the pipes in this process,
762 * otherwise the reader will never get EOF.
764 close_and_invalidate (&child_err_report_pipe[1]);
765 close_and_invalidate (&helper_sync_pipe[0]);
766 close_and_invalidate (&stdin_pipe[0]);
767 close_and_invalidate (&stdout_pipe[1]);
768 close_and_invalidate (&stderr_pipe[1]);
770 g_strfreev (protected_argv);
772 g_free (new_argv[0]);
773 g_free (new_argv[ARG_WORKING_DIRECTORY]);
774 g_free (new_argv);
776 /* Check if gspawn-win32-helper couldn't be run */
777 if (rc == -1 && saved_errno != 0)
779 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
780 _("Failed to execute helper program (%s)"),
781 g_strerror (saved_errno));
782 goto cleanup_and_fail;
785 if (exit_status != NULL)
787 /* Synchronous case. Pass helper's report pipe back to caller,
788 * which takes care of reading it after the grandchild has
789 * finished.
791 g_assert (err_report != NULL);
792 *err_report = child_err_report_pipe[0];
793 write (helper_sync_pipe[1], " ", 1);
794 close_and_invalidate (&helper_sync_pipe[1]);
796 else
798 /* Asynchronous case. We read the helper's report right away. */
799 if (!read_helper_report (child_err_report_pipe[0], helper_report, error))
800 goto cleanup_and_fail;
802 close_and_invalidate (&child_err_report_pipe[0]);
804 switch (helper_report[0])
806 case CHILD_NO_ERROR:
807 if (child_handle && do_return_handle)
809 /* rc is our HANDLE for gspawn-win32-helper. It has
810 * told us the HANDLE of its child. Duplicate that into
811 * a HANDLE valid in this process.
813 if (!DuplicateHandle ((HANDLE) rc, (HANDLE) helper_report[1],
814 GetCurrentProcess (), (LPHANDLE) child_handle,
815 0, TRUE, DUPLICATE_SAME_ACCESS))
817 char *emsg = g_win32_error_message (GetLastError ());
818 g_print("%s\n", emsg);
819 *child_handle = 0;
822 else if (child_handle)
823 *child_handle = 0;
824 write (helper_sync_pipe[1], " ", 1);
825 close_and_invalidate (&helper_sync_pipe[1]);
826 break;
828 default:
829 write (helper_sync_pipe[1], " ", 1);
830 close_and_invalidate (&helper_sync_pipe[1]);
831 set_child_error (helper_report, working_directory, error);
832 goto cleanup_and_fail;
836 /* Success against all odds! return the information */
838 if (standard_input)
839 *standard_input = stdin_pipe[1];
840 if (standard_output)
841 *standard_output = stdout_pipe[0];
842 if (standard_error)
843 *standard_error = stderr_pipe[0];
844 if (rc != -1)
845 CloseHandle ((HANDLE) rc);
847 return TRUE;
849 cleanup_and_fail:
851 if (rc != -1)
852 CloseHandle ((HANDLE) rc);
853 if (child_err_report_pipe[0] != -1)
854 close (child_err_report_pipe[0]);
855 if (child_err_report_pipe[1] != -1)
856 close (child_err_report_pipe[1]);
857 if (helper_sync_pipe[0] != -1)
858 close (helper_sync_pipe[0]);
859 if (helper_sync_pipe[1] != -1)
860 close (helper_sync_pipe[1]);
861 if (stdin_pipe[0] != -1)
862 close (stdin_pipe[0]);
863 if (stdin_pipe[1] != -1)
864 close (stdin_pipe[1]);
865 if (stdout_pipe[0] != -1)
866 close (stdout_pipe[0]);
867 if (stdout_pipe[1] != -1)
868 close (stdout_pipe[1]);
869 if (stderr_pipe[0] != -1)
870 close (stderr_pipe[0]);
871 if (stderr_pipe[1] != -1)
872 close (stderr_pipe[1]);
874 return FALSE;
877 gboolean
878 g_spawn_sync_utf8 (const gchar *working_directory,
879 gchar **argv,
880 gchar **envp,
881 GSpawnFlags flags,
882 GSpawnChildSetupFunc child_setup,
883 gpointer user_data,
884 gchar **standard_output,
885 gchar **standard_error,
886 gint *exit_status,
887 GError **error)
889 gint outpipe = -1;
890 gint errpipe = -1;
891 gint reportpipe = -1;
892 GIOChannel *outchannel = NULL;
893 GIOChannel *errchannel = NULL;
894 GPollFD outfd, errfd;
895 GPollFD fds[2];
896 gint nfds;
897 gint outindex = -1;
898 gint errindex = -1;
899 gint ret;
900 GString *outstr = NULL;
901 GString *errstr = NULL;
902 gboolean failed;
903 gint status;
905 g_return_val_if_fail (argv != NULL, FALSE);
906 g_return_val_if_fail (!(flags & G_SPAWN_DO_NOT_REAP_CHILD), FALSE);
907 g_return_val_if_fail (standard_output == NULL ||
908 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
909 g_return_val_if_fail (standard_error == NULL ||
910 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
912 /* Just to ensure segfaults if callers try to use
913 * these when an error is reported.
915 if (standard_output)
916 *standard_output = NULL;
918 if (standard_error)
919 *standard_error = NULL;
921 if (!do_spawn_with_pipes (&status,
922 FALSE,
923 working_directory,
924 argv,
925 envp,
926 flags,
927 child_setup,
928 NULL,
929 NULL,
930 standard_output ? &outpipe : NULL,
931 standard_error ? &errpipe : NULL,
932 &reportpipe,
933 error))
934 return FALSE;
936 /* Read data from child. */
938 failed = FALSE;
940 if (outpipe >= 0)
942 outstr = g_string_new (NULL);
943 outchannel = g_io_channel_win32_new_fd (outpipe);
944 g_io_channel_set_encoding (outchannel, NULL, NULL);
945 g_io_channel_set_buffered (outchannel, FALSE);
946 g_io_channel_win32_make_pollfd (outchannel,
947 G_IO_IN | G_IO_ERR | G_IO_HUP,
948 &outfd);
949 if (debug)
950 g_print ("outfd=%p\n", (HANDLE) outfd.fd);
953 if (errpipe >= 0)
955 errstr = g_string_new (NULL);
956 errchannel = g_io_channel_win32_new_fd (errpipe);
957 g_io_channel_set_encoding (errchannel, NULL, NULL);
958 g_io_channel_set_buffered (errchannel, FALSE);
959 g_io_channel_win32_make_pollfd (errchannel,
960 G_IO_IN | G_IO_ERR | G_IO_HUP,
961 &errfd);
962 if (debug)
963 g_print ("errfd=%p\n", (HANDLE) errfd.fd);
966 /* Read data until we get EOF on all pipes. */
967 while (!failed && (outpipe >= 0 || errpipe >= 0))
969 nfds = 0;
970 if (outpipe >= 0)
972 fds[nfds] = outfd;
973 outindex = nfds;
974 nfds++;
976 if (errpipe >= 0)
978 fds[nfds] = errfd;
979 errindex = nfds;
980 nfds++;
983 if (debug)
984 g_print ("g_spawn_sync: calling g_io_channel_win32_poll, nfds=%d\n",
985 nfds);
987 ret = g_io_channel_win32_poll (fds, nfds, -1);
989 if (ret < 0)
991 failed = TRUE;
993 g_set_error_literal (error, G_SPAWN_ERROR, G_SPAWN_ERROR_READ,
994 _("Unexpected error in g_io_channel_win32_poll() reading data from a child process"));
996 break;
999 if (outpipe >= 0 && (fds[outindex].revents & G_IO_IN))
1001 switch (read_data (outstr, outchannel, error))
1003 case READ_FAILED:
1004 if (debug)
1005 g_print ("g_spawn_sync: outchannel: READ_FAILED\n");
1006 failed = TRUE;
1007 break;
1008 case READ_EOF:
1009 if (debug)
1010 g_print ("g_spawn_sync: outchannel: READ_EOF\n");
1011 g_io_channel_unref (outchannel);
1012 outchannel = NULL;
1013 close_and_invalidate (&outpipe);
1014 break;
1015 default:
1016 if (debug)
1017 g_print ("g_spawn_sync: outchannel: OK\n");
1018 break;
1021 if (failed)
1022 break;
1025 if (errpipe >= 0 && (fds[errindex].revents & G_IO_IN))
1027 switch (read_data (errstr, errchannel, error))
1029 case READ_FAILED:
1030 if (debug)
1031 g_print ("g_spawn_sync: errchannel: READ_FAILED\n");
1032 failed = TRUE;
1033 break;
1034 case READ_EOF:
1035 if (debug)
1036 g_print ("g_spawn_sync: errchannel: READ_EOF\n");
1037 g_io_channel_unref (errchannel);
1038 errchannel = NULL;
1039 close_and_invalidate (&errpipe);
1040 break;
1041 default:
1042 if (debug)
1043 g_print ("g_spawn_sync: errchannel: OK\n");
1044 break;
1047 if (failed)
1048 break;
1052 if (reportpipe == -1)
1054 /* No helper process, exit status of actual spawned process
1055 * already available.
1057 if (exit_status)
1058 *exit_status = status;
1060 else
1062 /* Helper process was involved. Read its report now after the
1063 * grandchild has finished.
1065 gintptr helper_report[2];
1067 if (!read_helper_report (reportpipe, helper_report, error))
1068 failed = TRUE;
1069 else
1071 switch (helper_report[0])
1073 case CHILD_NO_ERROR:
1074 if (exit_status)
1075 *exit_status = helper_report[1];
1076 break;
1077 default:
1078 set_child_error (helper_report, working_directory, error);
1079 failed = TRUE;
1080 break;
1083 close_and_invalidate (&reportpipe);
1087 /* These should only be open still if we had an error. */
1089 if (outchannel != NULL)
1090 g_io_channel_unref (outchannel);
1091 if (errchannel != NULL)
1092 g_io_channel_unref (errchannel);
1093 if (outpipe >= 0)
1094 close_and_invalidate (&outpipe);
1095 if (errpipe >= 0)
1096 close_and_invalidate (&errpipe);
1098 if (failed)
1100 if (outstr)
1101 g_string_free (outstr, TRUE);
1102 if (errstr)
1103 g_string_free (errstr, TRUE);
1105 return FALSE;
1107 else
1109 if (standard_output)
1110 *standard_output = g_string_free (outstr, FALSE);
1112 if (standard_error)
1113 *standard_error = g_string_free (errstr, FALSE);
1115 return TRUE;
1119 gboolean
1120 g_spawn_async_with_pipes_utf8 (const gchar *working_directory,
1121 gchar **argv,
1122 gchar **envp,
1123 GSpawnFlags flags,
1124 GSpawnChildSetupFunc child_setup,
1125 gpointer user_data,
1126 GPid *child_handle,
1127 gint *standard_input,
1128 gint *standard_output,
1129 gint *standard_error,
1130 GError **error)
1132 g_return_val_if_fail (argv != NULL, FALSE);
1133 g_return_val_if_fail (standard_output == NULL ||
1134 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
1135 g_return_val_if_fail (standard_error == NULL ||
1136 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
1137 /* can't inherit stdin if we have an input pipe. */
1138 g_return_val_if_fail (standard_input == NULL ||
1139 !(flags & G_SPAWN_CHILD_INHERITS_STDIN), FALSE);
1141 return do_spawn_with_pipes (NULL,
1142 (flags & G_SPAWN_DO_NOT_REAP_CHILD),
1143 working_directory,
1144 argv,
1145 envp,
1146 flags,
1147 child_setup,
1148 child_handle,
1149 standard_input,
1150 standard_output,
1151 standard_error,
1152 NULL,
1153 error);
1156 gboolean
1157 g_spawn_command_line_sync_utf8 (const gchar *command_line,
1158 gchar **standard_output,
1159 gchar **standard_error,
1160 gint *exit_status,
1161 GError **error)
1163 gboolean retval;
1164 gchar **argv = 0;
1166 g_return_val_if_fail (command_line != NULL, FALSE);
1168 if (!g_shell_parse_argv (command_line,
1169 NULL, &argv,
1170 error))
1171 return FALSE;
1173 retval = g_spawn_sync_utf8 (NULL,
1174 argv,
1175 NULL,
1176 G_SPAWN_SEARCH_PATH,
1177 NULL,
1178 NULL,
1179 standard_output,
1180 standard_error,
1181 exit_status,
1182 error);
1183 g_strfreev (argv);
1185 return retval;
1188 gboolean
1189 g_spawn_command_line_async_utf8 (const gchar *command_line,
1190 GError **error)
1192 gboolean retval;
1193 gchar **argv = 0;
1195 g_return_val_if_fail (command_line != NULL, FALSE);
1197 if (!g_shell_parse_argv (command_line,
1198 NULL, &argv,
1199 error))
1200 return FALSE;
1202 retval = g_spawn_async_utf8 (NULL,
1203 argv,
1204 NULL,
1205 G_SPAWN_SEARCH_PATH,
1206 NULL,
1207 NULL,
1208 NULL,
1209 error);
1210 g_strfreev (argv);
1212 return retval;
1215 void
1216 g_spawn_close_pid (GPid pid)
1218 CloseHandle (pid);
1221 gboolean
1222 g_spawn_check_exit_status (gint exit_status,
1223 GError **error)
1225 gboolean ret = FALSE;
1227 if (exit_status != 0)
1229 g_set_error (error, G_SPAWN_EXIT_ERROR, exit_status,
1230 _("Child process exited with code %ld"),
1231 (long) exit_status);
1232 goto out;
1235 ret = TRUE;
1236 out:
1237 return ret;
1240 #if !defined (_WIN64)
1242 /* Binary compatibility versions that take system codepage pathnames,
1243 * argument vectors and environments. These get used only by code
1244 * built against 2.8.1 or earlier. Code built against 2.8.2 or later
1245 * will use the _utf8 versions above (see the #defines in gspawn.h).
1248 #undef g_spawn_async
1249 #undef g_spawn_async_with_pipes
1250 #undef g_spawn_sync
1251 #undef g_spawn_command_line_sync
1252 #undef g_spawn_command_line_async
1254 static gboolean
1255 setup_utf8_copies (const gchar *working_directory,
1256 gchar **utf8_working_directory,
1257 gchar **argv,
1258 gchar ***utf8_argv,
1259 gchar **envp,
1260 gchar ***utf8_envp,
1261 GError **error)
1263 gint i, argc, envc;
1265 if (working_directory == NULL)
1266 *utf8_working_directory = NULL;
1267 else
1269 GError *conv_error = NULL;
1271 *utf8_working_directory = g_locale_to_utf8 (working_directory, -1, NULL, NULL, &conv_error);
1272 if (*utf8_working_directory == NULL)
1274 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_CHDIR,
1275 _("Invalid working directory: %s"),
1276 conv_error->message);
1277 g_error_free (conv_error);
1278 return FALSE;
1282 argc = 0;
1283 while (argv[argc])
1284 ++argc;
1285 *utf8_argv = g_new (gchar *, argc + 1);
1286 for (i = 0; i < argc; i++)
1288 GError *conv_error = NULL;
1290 (*utf8_argv)[i] = g_locale_to_utf8 (argv[i], -1, NULL, NULL, &conv_error);
1291 if ((*utf8_argv)[i] == NULL)
1293 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
1294 _("Invalid string in argument vector at %d: %s"),
1295 i, conv_error->message);
1296 g_error_free (conv_error);
1298 g_strfreev (*utf8_argv);
1299 *utf8_argv = NULL;
1301 g_free (*utf8_working_directory);
1302 *utf8_working_directory = NULL;
1304 return FALSE;
1307 (*utf8_argv)[argc] = NULL;
1309 if (envp == NULL)
1311 *utf8_envp = NULL;
1313 else
1315 envc = 0;
1316 while (envp[envc])
1317 ++envc;
1318 *utf8_envp = g_new (gchar *, envc + 1);
1319 for (i = 0; i < envc; i++)
1321 GError *conv_error = NULL;
1323 (*utf8_envp)[i] = g_locale_to_utf8 (envp[i], -1, NULL, NULL, &conv_error);
1324 if ((*utf8_envp)[i] == NULL)
1326 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
1327 _("Invalid string in environment: %s"),
1328 conv_error->message);
1329 g_error_free (conv_error);
1331 g_strfreev (*utf8_envp);
1332 *utf8_envp = NULL;
1334 g_strfreev (*utf8_argv);
1335 *utf8_argv = NULL;
1337 g_free (*utf8_working_directory);
1338 *utf8_working_directory = NULL;
1340 return FALSE;
1343 (*utf8_envp)[envc] = NULL;
1345 return TRUE;
1348 static void
1349 free_utf8_copies (gchar *utf8_working_directory,
1350 gchar **utf8_argv,
1351 gchar **utf8_envp)
1353 g_free (utf8_working_directory);
1354 g_strfreev (utf8_argv);
1355 g_strfreev (utf8_envp);
1358 gboolean
1359 g_spawn_async_with_pipes (const gchar *working_directory,
1360 gchar **argv,
1361 gchar **envp,
1362 GSpawnFlags flags,
1363 GSpawnChildSetupFunc child_setup,
1364 gpointer user_data,
1365 GPid *child_handle,
1366 gint *standard_input,
1367 gint *standard_output,
1368 gint *standard_error,
1369 GError **error)
1371 gchar *utf8_working_directory;
1372 gchar **utf8_argv;
1373 gchar **utf8_envp;
1374 gboolean retval;
1376 if (!setup_utf8_copies (working_directory, &utf8_working_directory,
1377 argv, &utf8_argv,
1378 envp, &utf8_envp,
1379 error))
1380 return FALSE;
1382 retval = g_spawn_async_with_pipes_utf8 (utf8_working_directory,
1383 utf8_argv, utf8_envp,
1384 flags, child_setup, user_data,
1385 child_handle,
1386 standard_input, standard_output, standard_error,
1387 error);
1389 free_utf8_copies (utf8_working_directory, utf8_argv, utf8_envp);
1391 return retval;
1394 gboolean
1395 g_spawn_async (const gchar *working_directory,
1396 gchar **argv,
1397 gchar **envp,
1398 GSpawnFlags flags,
1399 GSpawnChildSetupFunc child_setup,
1400 gpointer user_data,
1401 GPid *child_handle,
1402 GError **error)
1404 return g_spawn_async_with_pipes (working_directory,
1405 argv, envp,
1406 flags,
1407 child_setup,
1408 user_data,
1409 child_handle,
1410 NULL, NULL, NULL,
1411 error);
1414 gboolean
1415 g_spawn_sync (const gchar *working_directory,
1416 gchar **argv,
1417 gchar **envp,
1418 GSpawnFlags flags,
1419 GSpawnChildSetupFunc child_setup,
1420 gpointer user_data,
1421 gchar **standard_output,
1422 gchar **standard_error,
1423 gint *exit_status,
1424 GError **error)
1426 gchar *utf8_working_directory;
1427 gchar **utf8_argv;
1428 gchar **utf8_envp;
1429 gboolean retval;
1431 if (!setup_utf8_copies (working_directory, &utf8_working_directory,
1432 argv, &utf8_argv,
1433 envp, &utf8_envp,
1434 error))
1435 return FALSE;
1437 retval = g_spawn_sync_utf8 (utf8_working_directory,
1438 utf8_argv, utf8_envp,
1439 flags, child_setup, user_data,
1440 standard_output, standard_error, exit_status,
1441 error);
1443 free_utf8_copies (utf8_working_directory, utf8_argv, utf8_envp);
1445 return retval;
1448 gboolean
1449 g_spawn_command_line_sync (const gchar *command_line,
1450 gchar **standard_output,
1451 gchar **standard_error,
1452 gint *exit_status,
1453 GError **error)
1455 gboolean retval;
1456 gchar **argv = 0;
1458 g_return_val_if_fail (command_line != NULL, FALSE);
1460 if (!g_shell_parse_argv (command_line,
1461 NULL, &argv,
1462 error))
1463 return FALSE;
1465 retval = g_spawn_sync (NULL,
1466 argv,
1467 NULL,
1468 G_SPAWN_SEARCH_PATH,
1469 NULL,
1470 NULL,
1471 standard_output,
1472 standard_error,
1473 exit_status,
1474 error);
1475 g_strfreev (argv);
1477 return retval;
1480 gboolean
1481 g_spawn_command_line_async (const gchar *command_line,
1482 GError **error)
1484 gboolean retval;
1485 gchar **argv = 0;
1487 g_return_val_if_fail (command_line != NULL, FALSE);
1489 if (!g_shell_parse_argv (command_line,
1490 NULL, &argv,
1491 error))
1492 return FALSE;
1494 retval = g_spawn_async (NULL,
1495 argv,
1496 NULL,
1497 G_SPAWN_SEARCH_PATH,
1498 NULL,
1499 NULL,
1500 NULL,
1501 error);
1502 g_strfreev (argv);
1504 return retval;
1507 #endif /* !_WIN64 */
1509 #endif /* !GSPAWN_HELPER */