add private GBuffer type
[glib.git] / glib / gspawn-win32.c
blobdc48a25c39d5ed652d6bc4bd66bd0cb1fa0b3886
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"
50 #include "galias.h"
52 #include <string.h>
53 #include <stdlib.h>
54 #include <stdio.h>
56 #include <windows.h>
57 #include <errno.h>
58 #include <fcntl.h>
59 #include <io.h>
60 #include <process.h>
61 #include <direct.h>
62 #include <wchar.h>
64 #ifdef G_SPAWN_WIN32_DEBUG
65 static int debug = 1;
66 #define SETUP_DEBUG() /* empty */
67 #else
68 static int debug = -1;
69 #define SETUP_DEBUG() \
70 G_STMT_START \
71 { \
72 if (debug == -1) \
73 { \
74 if (getenv ("G_SPAWN_WIN32_DEBUG") != NULL) \
75 debug = 1; \
76 else \
77 debug = 0; \
78 } \
79 } \
80 G_STMT_END
81 #endif
83 enum
85 CHILD_NO_ERROR,
86 CHILD_CHDIR_FAILED,
87 CHILD_SPAWN_FAILED,
90 enum {
91 ARG_CHILD_ERR_REPORT = 1,
92 ARG_HELPER_SYNC,
93 ARG_STDIN,
94 ARG_STDOUT,
95 ARG_STDERR,
96 ARG_WORKING_DIRECTORY,
97 ARG_CLOSE_DESCRIPTORS,
98 ARG_USE_PATH,
99 ARG_WAIT,
100 ARG_PROGRAM,
101 ARG_COUNT = ARG_PROGRAM
104 static int
105 dup_noninherited (int fd,
106 int mode)
108 HANDLE filehandle;
110 DuplicateHandle (GetCurrentProcess (), (LPHANDLE) _get_osfhandle (fd),
111 GetCurrentProcess (), &filehandle,
112 0, FALSE, DUPLICATE_SAME_ACCESS);
113 close (fd);
114 return _open_osfhandle ((gintptr) filehandle, mode | _O_NOINHERIT);
117 #ifndef GSPAWN_HELPER
119 #ifdef _WIN64
120 #define HELPER_PROCESS "gspawn-win64-helper"
121 #else
122 #define HELPER_PROCESS "gspawn-win32-helper"
123 #endif
125 static gchar *
126 protect_argv_string (const gchar *string)
128 const gchar *p = string;
129 gchar *retval, *q;
130 gint len = 0;
131 gboolean need_dblquotes = FALSE;
132 while (*p)
134 if (*p == ' ' || *p == '\t')
135 need_dblquotes = TRUE;
136 else if (*p == '"')
137 len++;
138 else if (*p == '\\')
140 const gchar *pp = p;
141 while (*pp && *pp == '\\')
142 pp++;
143 if (*pp == '"')
144 len++;
146 len++;
147 p++;
150 q = retval = g_malloc (len + need_dblquotes*2 + 1);
151 p = string;
153 if (need_dblquotes)
154 *q++ = '"';
156 while (*p)
158 if (*p == '"')
159 *q++ = '\\';
160 else if (*p == '\\')
162 const gchar *pp = p;
163 while (*pp && *pp == '\\')
164 pp++;
165 if (*pp == '"')
166 *q++ = '\\';
168 *q++ = *p;
169 p++;
172 if (need_dblquotes)
173 *q++ = '"';
174 *q++ = '\0';
176 return retval;
179 static gint
180 protect_argv (gchar **argv,
181 gchar ***new_argv)
183 gint i;
184 gint argc = 0;
186 while (argv[argc])
187 ++argc;
188 *new_argv = g_new (gchar *, argc+1);
190 /* Quote each argv element if necessary, so that it will get
191 * reconstructed correctly in the C runtime startup code. Note that
192 * the unquoting algorithm in the C runtime is really weird, and
193 * rather different than what Unix shells do. See stdargv.c in the C
194 * runtime sources (in the Platform SDK, in src/crt).
196 * Note that an new_argv[0] constructed by this function should
197 * *not* be passed as the filename argument to a spawn* or exec*
198 * family function. That argument should be the real file name
199 * without any quoting.
201 for (i = 0; i < argc; i++)
202 (*new_argv)[i] = protect_argv_string (argv[i]);
204 (*new_argv)[argc] = NULL;
206 return argc;
209 GQuark
210 g_spawn_error_quark (void)
212 return g_quark_from_static_string ("g-exec-error-quark");
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 extern gchar *_glib_get_dll_directory (void);
552 gchar *glib_dll_directory;
554 if (child_setup && !warned_about_child_setup)
556 warned_about_child_setup = TRUE;
557 g_warning ("passing a child setup function to the g_spawn functions is pointless on Windows and it is ignored");
560 argc = protect_argv (argv, &protected_argv);
562 if (!standard_input && !standard_output && !standard_error &&
563 (flags & G_SPAWN_CHILD_INHERITS_STDIN) &&
564 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL) &&
565 !(flags & G_SPAWN_STDERR_TO_DEV_NULL) &&
566 (working_directory == NULL || !*working_directory) &&
567 (flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN))
569 /* We can do without the helper process */
570 gboolean retval =
571 do_spawn_directly (exit_status, do_return_handle, flags,
572 argv, envp, protected_argv,
573 child_handle, error);
574 g_strfreev (protected_argv);
575 return retval;
578 if (standard_input && !make_pipe (stdin_pipe, error))
579 goto cleanup_and_fail;
581 if (standard_output && !make_pipe (stdout_pipe, error))
582 goto cleanup_and_fail;
584 if (standard_error && !make_pipe (stderr_pipe, error))
585 goto cleanup_and_fail;
587 if (!make_pipe (child_err_report_pipe, error))
588 goto cleanup_and_fail;
590 if (!make_pipe (helper_sync_pipe, error))
591 goto cleanup_and_fail;
593 new_argv = g_new (char *, argc + 1 + ARG_COUNT);
594 if (GetConsoleCursorInfo (GetStdHandle (STD_OUTPUT_HANDLE), &cursor_info))
595 helper_process = HELPER_PROCESS "-console.exe";
596 else
597 helper_process = HELPER_PROCESS ".exe";
599 glib_dll_directory = _glib_get_dll_directory ();
600 if (glib_dll_directory != NULL)
602 helper_process = g_build_filename (glib_dll_directory, helper_process, NULL);
603 g_free (glib_dll_directory);
605 else
606 helper_process = g_strdup (helper_process);
608 new_argv[0] = protect_argv_string (helper_process);
610 _g_sprintf (args[ARG_CHILD_ERR_REPORT], "%d", child_err_report_pipe[1]);
611 new_argv[ARG_CHILD_ERR_REPORT] = args[ARG_CHILD_ERR_REPORT];
613 /* Make the read end of the child error report pipe
614 * noninherited. Otherwise it will needlessly be inherited by the
615 * helper process, and the started actual user process. As such that
616 * shouldn't harm, but it is unnecessary.
618 child_err_report_pipe[0] = dup_noninherited (child_err_report_pipe[0], _O_RDONLY);
620 if (flags & G_SPAWN_FILE_AND_ARGV_ZERO)
622 /* Overload ARG_CHILD_ERR_REPORT to also encode the
623 * G_SPAWN_FILE_AND_ARGV_ZERO functionality.
625 strcat (args[ARG_CHILD_ERR_REPORT], "#");
628 _g_sprintf (args[ARG_HELPER_SYNC], "%d", helper_sync_pipe[0]);
629 new_argv[ARG_HELPER_SYNC] = args[ARG_HELPER_SYNC];
631 /* Make the write end of the sync pipe noninherited. Otherwise the
632 * helper process will inherit it, and thus if this process happens
633 * to crash before writing the sync byte to the pipe, the helper
634 * process won't read but won't get any EOF either, as it has the
635 * write end open itself.
637 helper_sync_pipe[1] = dup_noninherited (helper_sync_pipe[1], _O_WRONLY);
639 if (standard_input)
641 _g_sprintf (args[ARG_STDIN], "%d", stdin_pipe[0]);
642 new_argv[ARG_STDIN] = args[ARG_STDIN];
644 else if (flags & G_SPAWN_CHILD_INHERITS_STDIN)
646 /* Let stdin be alone */
647 new_argv[ARG_STDIN] = "-";
649 else
651 /* Keep process from blocking on a read of stdin */
652 new_argv[ARG_STDIN] = "z";
655 if (standard_output)
657 _g_sprintf (args[ARG_STDOUT], "%d", stdout_pipe[1]);
658 new_argv[ARG_STDOUT] = args[ARG_STDOUT];
660 else if (flags & G_SPAWN_STDOUT_TO_DEV_NULL)
662 new_argv[ARG_STDOUT] = "z";
664 else
666 new_argv[ARG_STDOUT] = "-";
669 if (standard_error)
671 _g_sprintf (args[ARG_STDERR], "%d", stderr_pipe[1]);
672 new_argv[ARG_STDERR] = args[ARG_STDERR];
674 else if (flags & G_SPAWN_STDERR_TO_DEV_NULL)
676 new_argv[ARG_STDERR] = "z";
678 else
680 new_argv[ARG_STDERR] = "-";
683 if (working_directory && *working_directory)
684 new_argv[ARG_WORKING_DIRECTORY] = protect_argv_string (working_directory);
685 else
686 new_argv[ARG_WORKING_DIRECTORY] = g_strdup ("-");
688 if (!(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN))
689 new_argv[ARG_CLOSE_DESCRIPTORS] = "y";
690 else
691 new_argv[ARG_CLOSE_DESCRIPTORS] = "-";
693 if (flags & G_SPAWN_SEARCH_PATH)
694 new_argv[ARG_USE_PATH] = "y";
695 else
696 new_argv[ARG_USE_PATH] = "-";
698 if (exit_status == NULL)
699 new_argv[ARG_WAIT] = "-";
700 else
701 new_argv[ARG_WAIT] = "w";
703 for (i = 0; i <= argc; i++)
704 new_argv[ARG_PROGRAM + i] = protected_argv[i];
706 SETUP_DEBUG();
708 if (debug)
710 g_print ("calling %s with argv:\n", helper_process);
711 for (i = 0; i < argc + 1 + ARG_COUNT; i++)
712 g_print ("argv[%d]: %s\n", i, (new_argv[i] ? new_argv[i] : "NULL"));
715 if (!utf8_charv_to_wcharv (new_argv, &wargv, &conv_error_index, &conv_error))
717 if (conv_error_index == ARG_WORKING_DIRECTORY)
718 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_CHDIR,
719 _("Invalid working directory: %s"),
720 conv_error->message);
721 else
722 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
723 _("Invalid string in argument vector at %d: %s"),
724 conv_error_index - ARG_PROGRAM, conv_error->message);
725 g_error_free (conv_error);
726 g_strfreev (protected_argv);
727 g_free (new_argv[0]);
728 g_free (new_argv[ARG_WORKING_DIRECTORY]);
729 g_free (new_argv);
730 g_free (helper_process);
732 goto cleanup_and_fail;
735 if (!utf8_charv_to_wcharv (envp, &wenvp, NULL, &conv_error))
737 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
738 _("Invalid string in environment: %s"),
739 conv_error->message);
740 g_error_free (conv_error);
741 g_strfreev (protected_argv);
742 g_free (new_argv[0]);
743 g_free (new_argv[ARG_WORKING_DIRECTORY]);
744 g_free (new_argv);
745 g_free (helper_process);
746 g_strfreev ((gchar **) wargv);
748 goto cleanup_and_fail;
751 whelper = g_utf8_to_utf16 (helper_process, -1, NULL, NULL, NULL);
752 g_free (helper_process);
754 if (wenvp != NULL)
755 rc = _wspawnvpe (P_NOWAIT, whelper, (const wchar_t **) wargv, (const wchar_t **) wenvp);
756 else
757 rc = _wspawnvp (P_NOWAIT, whelper, (const wchar_t **) wargv);
759 saved_errno = errno;
761 g_free (whelper);
762 g_strfreev ((gchar **) wargv);
763 g_strfreev ((gchar **) wenvp);
765 /* Close the other process's ends of the pipes in this process,
766 * otherwise the reader will never get EOF.
768 close_and_invalidate (&child_err_report_pipe[1]);
769 close_and_invalidate (&helper_sync_pipe[0]);
770 close_and_invalidate (&stdin_pipe[0]);
771 close_and_invalidate (&stdout_pipe[1]);
772 close_and_invalidate (&stderr_pipe[1]);
774 g_strfreev (protected_argv);
776 g_free (new_argv[0]);
777 g_free (new_argv[ARG_WORKING_DIRECTORY]);
778 g_free (new_argv);
780 /* Check if gspawn-win32-helper couldn't be run */
781 if (rc == -1 && saved_errno != 0)
783 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
784 _("Failed to execute helper program (%s)"),
785 g_strerror (saved_errno));
786 goto cleanup_and_fail;
789 if (exit_status != NULL)
791 /* Synchronous case. Pass helper's report pipe back to caller,
792 * which takes care of reading it after the grandchild has
793 * finished.
795 g_assert (err_report != NULL);
796 *err_report = child_err_report_pipe[0];
797 write (helper_sync_pipe[1], " ", 1);
798 close_and_invalidate (&helper_sync_pipe[1]);
800 else
802 /* Asynchronous case. We read the helper's report right away. */
803 if (!read_helper_report (child_err_report_pipe[0], helper_report, error))
804 goto cleanup_and_fail;
806 close_and_invalidate (&child_err_report_pipe[0]);
808 switch (helper_report[0])
810 case CHILD_NO_ERROR:
811 if (child_handle && do_return_handle)
813 /* rc is our HANDLE for gspawn-win32-helper. It has
814 * told us the HANDLE of its child. Duplicate that into
815 * a HANDLE valid in this process.
817 if (!DuplicateHandle ((HANDLE) rc, (HANDLE) helper_report[1],
818 GetCurrentProcess (), (LPHANDLE) child_handle,
819 0, TRUE, DUPLICATE_SAME_ACCESS))
821 char *emsg = g_win32_error_message (GetLastError ());
822 g_print("%s\n", emsg);
823 *child_handle = 0;
826 else if (child_handle)
827 *child_handle = 0;
828 write (helper_sync_pipe[1], " ", 1);
829 close_and_invalidate (&helper_sync_pipe[1]);
830 break;
832 default:
833 write (helper_sync_pipe[1], " ", 1);
834 close_and_invalidate (&helper_sync_pipe[1]);
835 set_child_error (helper_report, working_directory, error);
836 goto cleanup_and_fail;
840 /* Success against all odds! return the information */
842 if (standard_input)
843 *standard_input = stdin_pipe[1];
844 if (standard_output)
845 *standard_output = stdout_pipe[0];
846 if (standard_error)
847 *standard_error = stderr_pipe[0];
848 if (rc != -1)
849 CloseHandle ((HANDLE) rc);
851 return TRUE;
853 cleanup_and_fail:
855 if (rc != -1)
856 CloseHandle ((HANDLE) rc);
857 if (child_err_report_pipe[0] != -1)
858 close (child_err_report_pipe[0]);
859 if (child_err_report_pipe[1] != -1)
860 close (child_err_report_pipe[1]);
861 if (helper_sync_pipe[0] != -1)
862 close (helper_sync_pipe[0]);
863 if (helper_sync_pipe[1] != -1)
864 close (helper_sync_pipe[1]);
865 if (stdin_pipe[0] != -1)
866 close (stdin_pipe[0]);
867 if (stdin_pipe[1] != -1)
868 close (stdin_pipe[1]);
869 if (stdout_pipe[0] != -1)
870 close (stdout_pipe[0]);
871 if (stdout_pipe[1] != -1)
872 close (stdout_pipe[1]);
873 if (stderr_pipe[0] != -1)
874 close (stderr_pipe[0]);
875 if (stderr_pipe[1] != -1)
876 close (stderr_pipe[1]);
878 return FALSE;
881 gboolean
882 g_spawn_sync_utf8 (const gchar *working_directory,
883 gchar **argv,
884 gchar **envp,
885 GSpawnFlags flags,
886 GSpawnChildSetupFunc child_setup,
887 gpointer user_data,
888 gchar **standard_output,
889 gchar **standard_error,
890 gint *exit_status,
891 GError **error)
893 gint outpipe = -1;
894 gint errpipe = -1;
895 gint reportpipe = -1;
896 GIOChannel *outchannel = NULL;
897 GIOChannel *errchannel = NULL;
898 GPollFD outfd, errfd;
899 GPollFD fds[2];
900 gint nfds;
901 gint outindex = -1;
902 gint errindex = -1;
903 gint ret;
904 GString *outstr = NULL;
905 GString *errstr = NULL;
906 gboolean failed;
907 gint status;
909 g_return_val_if_fail (argv != NULL, FALSE);
910 g_return_val_if_fail (!(flags & G_SPAWN_DO_NOT_REAP_CHILD), FALSE);
911 g_return_val_if_fail (standard_output == NULL ||
912 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
913 g_return_val_if_fail (standard_error == NULL ||
914 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
916 /* Just to ensure segfaults if callers try to use
917 * these when an error is reported.
919 if (standard_output)
920 *standard_output = NULL;
922 if (standard_error)
923 *standard_error = NULL;
925 if (!do_spawn_with_pipes (&status,
926 FALSE,
927 working_directory,
928 argv,
929 envp,
930 flags,
931 child_setup,
932 NULL,
933 NULL,
934 standard_output ? &outpipe : NULL,
935 standard_error ? &errpipe : NULL,
936 &reportpipe,
937 error))
938 return FALSE;
940 /* Read data from child. */
942 failed = FALSE;
944 if (outpipe >= 0)
946 outstr = g_string_new (NULL);
947 outchannel = g_io_channel_win32_new_fd (outpipe);
948 g_io_channel_set_encoding (outchannel, NULL, NULL);
949 g_io_channel_set_buffered (outchannel, FALSE);
950 g_io_channel_win32_make_pollfd (outchannel,
951 G_IO_IN | G_IO_ERR | G_IO_HUP,
952 &outfd);
953 if (debug)
954 g_print ("outfd=%p\n", (HANDLE) outfd.fd);
957 if (errpipe >= 0)
959 errstr = g_string_new (NULL);
960 errchannel = g_io_channel_win32_new_fd (errpipe);
961 g_io_channel_set_encoding (errchannel, NULL, NULL);
962 g_io_channel_set_buffered (errchannel, FALSE);
963 g_io_channel_win32_make_pollfd (errchannel,
964 G_IO_IN | G_IO_ERR | G_IO_HUP,
965 &errfd);
966 if (debug)
967 g_print ("errfd=%p\n", (HANDLE) errfd.fd);
970 /* Read data until we get EOF on all pipes. */
971 while (!failed && (outpipe >= 0 || errpipe >= 0))
973 nfds = 0;
974 if (outpipe >= 0)
976 fds[nfds] = outfd;
977 outindex = nfds;
978 nfds++;
980 if (errpipe >= 0)
982 fds[nfds] = errfd;
983 errindex = nfds;
984 nfds++;
987 if (debug)
988 g_print ("g_spawn_sync: calling g_io_channel_win32_poll, nfds=%d\n",
989 nfds);
991 ret = g_io_channel_win32_poll (fds, nfds, -1);
993 if (ret < 0)
995 failed = TRUE;
997 g_set_error_literal (error, G_SPAWN_ERROR, G_SPAWN_ERROR_READ,
998 _("Unexpected error in g_io_channel_win32_poll() reading data from a child process"));
1000 break;
1003 if (outpipe >= 0 && (fds[outindex].revents & G_IO_IN))
1005 switch (read_data (outstr, outchannel, error))
1007 case READ_FAILED:
1008 if (debug)
1009 g_print ("g_spawn_sync: outchannel: READ_FAILED\n");
1010 failed = TRUE;
1011 break;
1012 case READ_EOF:
1013 if (debug)
1014 g_print ("g_spawn_sync: outchannel: READ_EOF\n");
1015 g_io_channel_unref (outchannel);
1016 outchannel = NULL;
1017 close_and_invalidate (&outpipe);
1018 break;
1019 default:
1020 if (debug)
1021 g_print ("g_spawn_sync: outchannel: OK\n");
1022 break;
1025 if (failed)
1026 break;
1029 if (errpipe >= 0 && (fds[errindex].revents & G_IO_IN))
1031 switch (read_data (errstr, errchannel, error))
1033 case READ_FAILED:
1034 if (debug)
1035 g_print ("g_spawn_sync: errchannel: READ_FAILED\n");
1036 failed = TRUE;
1037 break;
1038 case READ_EOF:
1039 if (debug)
1040 g_print ("g_spawn_sync: errchannel: READ_EOF\n");
1041 g_io_channel_unref (errchannel);
1042 errchannel = NULL;
1043 close_and_invalidate (&errpipe);
1044 break;
1045 default:
1046 if (debug)
1047 g_print ("g_spawn_sync: errchannel: OK\n");
1048 break;
1051 if (failed)
1052 break;
1056 if (reportpipe == -1)
1058 /* No helper process, exit status of actual spawned process
1059 * already available.
1061 if (exit_status)
1062 *exit_status = status;
1064 else
1066 /* Helper process was involved. Read its report now after the
1067 * grandchild has finished.
1069 gintptr helper_report[2];
1071 if (!read_helper_report (reportpipe, helper_report, error))
1072 failed = TRUE;
1073 else
1075 switch (helper_report[0])
1077 case CHILD_NO_ERROR:
1078 if (exit_status)
1079 *exit_status = helper_report[1];
1080 break;
1081 default:
1082 set_child_error (helper_report, working_directory, error);
1083 failed = TRUE;
1084 break;
1087 close_and_invalidate (&reportpipe);
1091 /* These should only be open still if we had an error. */
1093 if (outchannel != NULL)
1094 g_io_channel_unref (outchannel);
1095 if (errchannel != NULL)
1096 g_io_channel_unref (errchannel);
1097 if (outpipe >= 0)
1098 close_and_invalidate (&outpipe);
1099 if (errpipe >= 0)
1100 close_and_invalidate (&errpipe);
1102 if (failed)
1104 if (outstr)
1105 g_string_free (outstr, TRUE);
1106 if (errstr)
1107 g_string_free (errstr, TRUE);
1109 return FALSE;
1111 else
1113 if (standard_output)
1114 *standard_output = g_string_free (outstr, FALSE);
1116 if (standard_error)
1117 *standard_error = g_string_free (errstr, FALSE);
1119 return TRUE;
1123 gboolean
1124 g_spawn_async_with_pipes_utf8 (const gchar *working_directory,
1125 gchar **argv,
1126 gchar **envp,
1127 GSpawnFlags flags,
1128 GSpawnChildSetupFunc child_setup,
1129 gpointer user_data,
1130 GPid *child_handle,
1131 gint *standard_input,
1132 gint *standard_output,
1133 gint *standard_error,
1134 GError **error)
1136 g_return_val_if_fail (argv != NULL, FALSE);
1137 g_return_val_if_fail (standard_output == NULL ||
1138 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
1139 g_return_val_if_fail (standard_error == NULL ||
1140 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
1141 /* can't inherit stdin if we have an input pipe. */
1142 g_return_val_if_fail (standard_input == NULL ||
1143 !(flags & G_SPAWN_CHILD_INHERITS_STDIN), FALSE);
1145 return do_spawn_with_pipes (NULL,
1146 (flags & G_SPAWN_DO_NOT_REAP_CHILD),
1147 working_directory,
1148 argv,
1149 envp,
1150 flags,
1151 child_setup,
1152 child_handle,
1153 standard_input,
1154 standard_output,
1155 standard_error,
1156 NULL,
1157 error);
1160 gboolean
1161 g_spawn_command_line_sync_utf8 (const gchar *command_line,
1162 gchar **standard_output,
1163 gchar **standard_error,
1164 gint *exit_status,
1165 GError **error)
1167 gboolean retval;
1168 gchar **argv = 0;
1170 g_return_val_if_fail (command_line != NULL, FALSE);
1172 if (!g_shell_parse_argv (command_line,
1173 NULL, &argv,
1174 error))
1175 return FALSE;
1177 retval = g_spawn_sync_utf8 (NULL,
1178 argv,
1179 NULL,
1180 G_SPAWN_SEARCH_PATH,
1181 NULL,
1182 NULL,
1183 standard_output,
1184 standard_error,
1185 exit_status,
1186 error);
1187 g_strfreev (argv);
1189 return retval;
1192 gboolean
1193 g_spawn_command_line_async_utf8 (const gchar *command_line,
1194 GError **error)
1196 gboolean retval;
1197 gchar **argv = 0;
1199 g_return_val_if_fail (command_line != NULL, FALSE);
1201 if (!g_shell_parse_argv (command_line,
1202 NULL, &argv,
1203 error))
1204 return FALSE;
1206 retval = g_spawn_async_utf8 (NULL,
1207 argv,
1208 NULL,
1209 G_SPAWN_SEARCH_PATH,
1210 NULL,
1211 NULL,
1212 NULL,
1213 error);
1214 g_strfreev (argv);
1216 return retval;
1219 void
1220 g_spawn_close_pid (GPid pid)
1222 CloseHandle (pid);
1225 #if !defined (_WIN64)
1227 /* Binary compatibility versions that take system codepage pathnames,
1228 * argument vectors and environments. These get used only by code
1229 * built against 2.8.1 or earlier. Code built against 2.8.2 or later
1230 * will use the _utf8 versions above (see the #defines in gspawn.h).
1233 #undef g_spawn_async
1234 #undef g_spawn_async_with_pipes
1235 #undef g_spawn_sync
1236 #undef g_spawn_command_line_sync
1237 #undef g_spawn_command_line_async
1239 static gboolean
1240 setup_utf8_copies (const gchar *working_directory,
1241 gchar **utf8_working_directory,
1242 gchar **argv,
1243 gchar ***utf8_argv,
1244 gchar **envp,
1245 gchar ***utf8_envp,
1246 GError **error)
1248 gint i, argc, envc;
1250 if (working_directory == NULL)
1251 *utf8_working_directory = NULL;
1252 else
1254 GError *conv_error = NULL;
1256 *utf8_working_directory = g_locale_to_utf8 (working_directory, -1, NULL, NULL, &conv_error);
1257 if (*utf8_working_directory == NULL)
1259 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_CHDIR,
1260 _("Invalid working directory: %s"),
1261 conv_error->message);
1262 g_error_free (conv_error);
1263 return FALSE;
1267 argc = 0;
1268 while (argv[argc])
1269 ++argc;
1270 *utf8_argv = g_new (gchar *, argc + 1);
1271 for (i = 0; i < argc; i++)
1273 GError *conv_error = NULL;
1275 (*utf8_argv)[i] = g_locale_to_utf8 (argv[i], -1, NULL, NULL, &conv_error);
1276 if ((*utf8_argv)[i] == NULL)
1278 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
1279 _("Invalid string in argument vector at %d: %s"),
1280 i, conv_error->message);
1281 g_error_free (conv_error);
1283 g_strfreev (*utf8_argv);
1284 *utf8_argv = NULL;
1286 g_free (*utf8_working_directory);
1287 *utf8_working_directory = NULL;
1289 return FALSE;
1292 (*utf8_argv)[argc] = NULL;
1294 if (envp == NULL)
1296 *utf8_envp = NULL;
1298 else
1300 envc = 0;
1301 while (envp[envc])
1302 ++envc;
1303 *utf8_envp = g_new (gchar *, envc + 1);
1304 for (i = 0; i < envc; i++)
1306 GError *conv_error = NULL;
1308 (*utf8_envp)[i] = g_locale_to_utf8 (envp[i], -1, NULL, NULL, &conv_error);
1309 if ((*utf8_envp)[i] == NULL)
1311 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
1312 _("Invalid string in environment: %s"),
1313 conv_error->message);
1314 g_error_free (conv_error);
1316 g_strfreev (*utf8_envp);
1317 *utf8_envp = NULL;
1319 g_strfreev (*utf8_argv);
1320 *utf8_argv = NULL;
1322 g_free (*utf8_working_directory);
1323 *utf8_working_directory = NULL;
1325 return FALSE;
1328 (*utf8_envp)[envc] = NULL;
1330 return TRUE;
1333 static void
1334 free_utf8_copies (gchar *utf8_working_directory,
1335 gchar **utf8_argv,
1336 gchar **utf8_envp)
1338 g_free (utf8_working_directory);
1339 g_strfreev (utf8_argv);
1340 g_strfreev (utf8_envp);
1343 gboolean
1344 g_spawn_async_with_pipes (const gchar *working_directory,
1345 gchar **argv,
1346 gchar **envp,
1347 GSpawnFlags flags,
1348 GSpawnChildSetupFunc child_setup,
1349 gpointer user_data,
1350 GPid *child_handle,
1351 gint *standard_input,
1352 gint *standard_output,
1353 gint *standard_error,
1354 GError **error)
1356 gchar *utf8_working_directory;
1357 gchar **utf8_argv;
1358 gchar **utf8_envp;
1359 gboolean retval;
1361 if (!setup_utf8_copies (working_directory, &utf8_working_directory,
1362 argv, &utf8_argv,
1363 envp, &utf8_envp,
1364 error))
1365 return FALSE;
1367 retval = g_spawn_async_with_pipes_utf8 (utf8_working_directory,
1368 utf8_argv, utf8_envp,
1369 flags, child_setup, user_data,
1370 child_handle,
1371 standard_input, standard_output, standard_error,
1372 error);
1374 free_utf8_copies (utf8_working_directory, utf8_argv, utf8_envp);
1376 return retval;
1379 gboolean
1380 g_spawn_async (const gchar *working_directory,
1381 gchar **argv,
1382 gchar **envp,
1383 GSpawnFlags flags,
1384 GSpawnChildSetupFunc child_setup,
1385 gpointer user_data,
1386 GPid *child_handle,
1387 GError **error)
1389 return g_spawn_async_with_pipes (working_directory,
1390 argv, envp,
1391 flags,
1392 child_setup,
1393 user_data,
1394 child_handle,
1395 NULL, NULL, NULL,
1396 error);
1399 gboolean
1400 g_spawn_sync (const gchar *working_directory,
1401 gchar **argv,
1402 gchar **envp,
1403 GSpawnFlags flags,
1404 GSpawnChildSetupFunc child_setup,
1405 gpointer user_data,
1406 gchar **standard_output,
1407 gchar **standard_error,
1408 gint *exit_status,
1409 GError **error)
1411 gchar *utf8_working_directory;
1412 gchar **utf8_argv;
1413 gchar **utf8_envp;
1414 gboolean retval;
1416 if (!setup_utf8_copies (working_directory, &utf8_working_directory,
1417 argv, &utf8_argv,
1418 envp, &utf8_envp,
1419 error))
1420 return FALSE;
1422 retval = g_spawn_sync_utf8 (utf8_working_directory,
1423 utf8_argv, utf8_envp,
1424 flags, child_setup, user_data,
1425 standard_output, standard_error, exit_status,
1426 error);
1428 free_utf8_copies (utf8_working_directory, utf8_argv, utf8_envp);
1430 return retval;
1433 gboolean
1434 g_spawn_command_line_sync (const gchar *command_line,
1435 gchar **standard_output,
1436 gchar **standard_error,
1437 gint *exit_status,
1438 GError **error)
1440 gboolean retval;
1441 gchar **argv = 0;
1443 g_return_val_if_fail (command_line != NULL, FALSE);
1445 if (!g_shell_parse_argv (command_line,
1446 NULL, &argv,
1447 error))
1448 return FALSE;
1450 retval = g_spawn_sync (NULL,
1451 argv,
1452 NULL,
1453 G_SPAWN_SEARCH_PATH,
1454 NULL,
1455 NULL,
1456 standard_output,
1457 standard_error,
1458 exit_status,
1459 error);
1460 g_strfreev (argv);
1462 return retval;
1465 gboolean
1466 g_spawn_command_line_async (const gchar *command_line,
1467 GError **error)
1469 gboolean retval;
1470 gchar **argv = 0;
1472 g_return_val_if_fail (command_line != NULL, FALSE);
1474 if (!g_shell_parse_argv (command_line,
1475 NULL, &argv,
1476 error))
1477 return FALSE;
1479 retval = g_spawn_async (NULL,
1480 argv,
1481 NULL,
1482 G_SPAWN_SEARCH_PATH,
1483 NULL,
1484 NULL,
1485 NULL,
1486 error);
1487 g_strfreev (argv);
1489 return retval;
1492 #endif /* !_WIN64 */
1494 #endif /* !GSPAWN_HELPER */
1496 #define __G_SPAWN_C__
1497 #include "galiasdef.c"