Merge branch 'doc-types' into 'master'
[glib.git] / glib / gspawn-win32.c
blobb0cf5ab7ae789db9de37b063cb79c78f1c8303a2
1 /* gspawn-win32.c - Process launching on Win32
3 * Copyright 2000 Red Hat, Inc.
4 * Copyright 2003 Tor Lillqvist
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library 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 License
17 * along with this library; if not, see <http://www.gnu.org/licenses/>.
21 * Implementation details on Win32.
23 * - There is no way to set the no-inherit flag for
24 * a "file descriptor" in the MS C runtime. The flag is there,
25 * and the dospawn() function uses it, but unfortunately
26 * this flag can only be set when opening the file.
27 * - As there is no fork(), we cannot reliably change directory
28 * before starting the child process. (There might be several threads
29 * running, and the current directory is common for all threads.)
31 * Thus, we must in many cases use a helper program to handle closing
32 * of (inherited) file descriptors and changing of directory. The
33 * helper process is also needed if the standard input, standard
34 * output, or standard error of the process to be run are supposed to
35 * be redirected somewhere.
37 * The structure of the source code in this file is a mess, I know.
40 /* Define this to get some logging all the time */
41 /* #define G_SPAWN_WIN32_DEBUG */
43 #include "config.h"
45 #include "glib.h"
46 #include "glib-private.h"
47 #include "gprintfint.h"
48 #include "glibintl.h"
49 #include "gspawn-private.h"
50 #include "gthread.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 #ifndef GSPAWN_HELPER
65 #ifdef G_SPAWN_WIN32_DEBUG
66 static int debug = 1;
67 #define SETUP_DEBUG() /* empty */
68 #else
69 static int debug = -1;
70 #define SETUP_DEBUG() \
71 G_STMT_START \
72 { \
73 if (debug == -1) \
74 { \
75 if (getenv ("G_SPAWN_WIN32_DEBUG") != NULL) \
76 debug = 1; \
77 else \
78 debug = 0; \
79 } \
80 } \
81 G_STMT_END
82 #endif
83 #endif
85 enum
87 CHILD_NO_ERROR,
88 CHILD_CHDIR_FAILED,
89 CHILD_SPAWN_FAILED,
90 CHILD_SPAWN_NOENT,
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 (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 (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;
321 int errsv;
323 if (debug)
324 g_print ("%s:read_helper_report: read %" G_GSIZE_FORMAT "...\n",
325 __FILE__,
326 sizeof(gintptr)*2 - bytes);
328 chunk = read (fd, ((gchar*)report) + bytes,
329 sizeof(gintptr)*2 - bytes);
330 errsv = errno;
332 if (debug)
333 g_print ("...got %d bytes\n", chunk);
335 if (chunk < 0)
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 case CHILD_SPAWN_NOENT:
380 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_NOENT,
381 _("Failed to execute child process (%s)"),
382 g_strerror (report[1]));
383 break;
384 default:
385 g_assert_not_reached ();
389 static gboolean
390 utf8_charv_to_wcharv (char **utf8_charv,
391 wchar_t ***wcharv,
392 int *error_index,
393 GError **error)
395 wchar_t **retval = NULL;
397 *wcharv = NULL;
398 if (utf8_charv != NULL)
400 int n = 0, i;
402 while (utf8_charv[n])
403 n++;
404 retval = g_new (wchar_t *, n + 1);
406 for (i = 0; i < n; i++)
408 retval[i] = g_utf8_to_utf16 (utf8_charv[i], -1, NULL, NULL, error);
409 if (retval[i] == NULL)
411 if (error_index)
412 *error_index = i;
413 while (i)
414 g_free (retval[--i]);
415 g_free (retval);
416 return FALSE;
420 retval[n] = NULL;
422 *wcharv = retval;
423 return TRUE;
426 static gboolean
427 do_spawn_directly (gint *exit_status,
428 gboolean do_return_handle,
429 GSpawnFlags flags,
430 gchar **argv,
431 char **envp,
432 char **protected_argv,
433 GPid *child_handle,
434 GError **error)
436 const int mode = (exit_status == NULL) ? P_NOWAIT : P_WAIT;
437 char **new_argv;
438 gintptr rc = -1;
439 int errsv;
440 GError *conv_error = NULL;
441 gint conv_error_index;
442 wchar_t *wargv0, **wargv, **wenvp;
444 new_argv = (flags & G_SPAWN_FILE_AND_ARGV_ZERO) ? protected_argv + 1 : protected_argv;
446 wargv0 = g_utf8_to_utf16 (argv[0], -1, NULL, NULL, &conv_error);
447 if (wargv0 == NULL)
449 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
450 _("Invalid program name: %s"),
451 conv_error->message);
452 g_error_free (conv_error);
454 return FALSE;
457 if (!utf8_charv_to_wcharv (new_argv, &wargv, &conv_error_index, &conv_error))
459 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
460 _("Invalid string in argument vector at %d: %s"),
461 conv_error_index, conv_error->message);
462 g_error_free (conv_error);
463 g_free (wargv0);
465 return FALSE;
468 if (!utf8_charv_to_wcharv (envp, &wenvp, NULL, &conv_error))
470 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
471 _("Invalid string in environment: %s"),
472 conv_error->message);
473 g_error_free (conv_error);
474 g_free (wargv0);
475 g_strfreev ((gchar **) wargv);
477 return FALSE;
480 if (flags & G_SPAWN_SEARCH_PATH)
481 if (wenvp != NULL)
482 rc = _wspawnvpe (mode, wargv0, (const wchar_t **) wargv, (const wchar_t **) wenvp);
483 else
484 rc = _wspawnvp (mode, wargv0, (const wchar_t **) wargv);
485 else
486 if (wenvp != NULL)
487 rc = _wspawnve (mode, wargv0, (const wchar_t **) wargv, (const wchar_t **) wenvp);
488 else
489 rc = _wspawnv (mode, wargv0, (const wchar_t **) wargv);
491 errsv = errno;
493 g_free (wargv0);
494 g_strfreev ((gchar **) wargv);
495 g_strfreev ((gchar **) wenvp);
497 if (rc == -1 && errsv != 0)
499 g_set_error (error, G_SPAWN_ERROR, _g_spawn_exec_err_to_g_error (errsv),
500 _("Failed to execute child process (%s)"),
501 g_strerror (errsv));
502 return FALSE;
505 if (exit_status == NULL)
507 if (child_handle && do_return_handle)
508 *child_handle = (GPid) rc;
509 else
511 CloseHandle ((HANDLE) rc);
512 if (child_handle)
513 *child_handle = 0;
516 else
517 *exit_status = rc;
519 return TRUE;
522 static gboolean
523 do_spawn_with_fds (gint *exit_status,
524 gboolean do_return_handle,
525 const gchar *working_directory,
526 gchar **argv,
527 char **envp,
528 GSpawnFlags flags,
529 GSpawnChildSetupFunc child_setup,
530 GPid *child_handle,
531 gint stdin_fd,
532 gint stdout_fd,
533 gint stderr_fd,
534 gint *err_report,
535 GError **error)
537 char **protected_argv;
538 char args[ARG_COUNT][10];
539 char **new_argv;
540 int i;
541 gintptr rc = -1;
542 int errsv;
543 int argc;
544 int child_err_report_pipe[2] = { -1, -1 };
545 int helper_sync_pipe[2] = { -1, -1 };
546 gintptr helper_report[2];
547 static gboolean warned_about_child_setup = FALSE;
548 GError *conv_error = NULL;
549 gint conv_error_index;
550 gchar *helper_process;
551 wchar_t *whelper, **wargv, **wenvp;
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 (stdin_fd == -1 && stdout_fd == -1 && stderr_fd == -1 &&
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 (!make_pipe (child_err_report_pipe, error))
579 goto cleanup_and_fail;
581 if (!make_pipe (helper_sync_pipe, error))
582 goto cleanup_and_fail;
584 new_argv = g_new (char *, argc + 1 + ARG_COUNT);
585 if (GetConsoleWindow () != NULL)
586 helper_process = HELPER_PROCESS "-console.exe";
587 else
588 helper_process = HELPER_PROCESS ".exe";
590 glib_dll_directory = _glib_get_dll_directory ();
591 if (glib_dll_directory != NULL)
593 helper_process = g_build_filename (glib_dll_directory, helper_process, NULL);
594 g_free (glib_dll_directory);
596 else
597 helper_process = g_strdup (helper_process);
599 new_argv[0] = protect_argv_string (helper_process);
601 _g_sprintf (args[ARG_CHILD_ERR_REPORT], "%d", child_err_report_pipe[1]);
602 new_argv[ARG_CHILD_ERR_REPORT] = args[ARG_CHILD_ERR_REPORT];
604 /* Make the read end of the child error report pipe
605 * noninherited. Otherwise it will needlessly be inherited by the
606 * helper process, and the started actual user process. As such that
607 * shouldn't harm, but it is unnecessary.
609 child_err_report_pipe[0] = dup_noninherited (child_err_report_pipe[0], _O_RDONLY);
611 if (flags & G_SPAWN_FILE_AND_ARGV_ZERO)
613 /* Overload ARG_CHILD_ERR_REPORT to also encode the
614 * G_SPAWN_FILE_AND_ARGV_ZERO functionality.
616 strcat (args[ARG_CHILD_ERR_REPORT], "#");
619 _g_sprintf (args[ARG_HELPER_SYNC], "%d", helper_sync_pipe[0]);
620 new_argv[ARG_HELPER_SYNC] = args[ARG_HELPER_SYNC];
622 /* Make the write end of the sync pipe noninherited. Otherwise the
623 * helper process will inherit it, and thus if this process happens
624 * to crash before writing the sync byte to the pipe, the helper
625 * process won't read but won't get any EOF either, as it has the
626 * write end open itself.
628 helper_sync_pipe[1] = dup_noninherited (helper_sync_pipe[1], _O_WRONLY);
630 if (stdin_fd != -1)
632 _g_sprintf (args[ARG_STDIN], "%d", stdin_fd);
633 new_argv[ARG_STDIN] = args[ARG_STDIN];
635 else if (flags & G_SPAWN_CHILD_INHERITS_STDIN)
637 /* Let stdin be alone */
638 new_argv[ARG_STDIN] = "-";
640 else
642 /* Keep process from blocking on a read of stdin */
643 new_argv[ARG_STDIN] = "z";
646 if (stdout_fd != -1)
648 _g_sprintf (args[ARG_STDOUT], "%d", stdout_fd);
649 new_argv[ARG_STDOUT] = args[ARG_STDOUT];
651 else if (flags & G_SPAWN_STDOUT_TO_DEV_NULL)
653 new_argv[ARG_STDOUT] = "z";
655 else
657 new_argv[ARG_STDOUT] = "-";
660 if (stdout_fd != -1)
662 _g_sprintf (args[ARG_STDERR], "%d", stderr_fd);
663 new_argv[ARG_STDERR] = args[ARG_STDERR];
665 else if (flags & G_SPAWN_STDERR_TO_DEV_NULL)
667 new_argv[ARG_STDERR] = "z";
669 else
671 new_argv[ARG_STDERR] = "-";
674 if (working_directory && *working_directory)
675 new_argv[ARG_WORKING_DIRECTORY] = protect_argv_string (working_directory);
676 else
677 new_argv[ARG_WORKING_DIRECTORY] = g_strdup ("-");
679 if (!(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN))
680 new_argv[ARG_CLOSE_DESCRIPTORS] = "y";
681 else
682 new_argv[ARG_CLOSE_DESCRIPTORS] = "-";
684 if (flags & G_SPAWN_SEARCH_PATH)
685 new_argv[ARG_USE_PATH] = "y";
686 else
687 new_argv[ARG_USE_PATH] = "-";
689 if (exit_status == NULL)
690 new_argv[ARG_WAIT] = "-";
691 else
692 new_argv[ARG_WAIT] = "w";
694 for (i = 0; i <= argc; i++)
695 new_argv[ARG_PROGRAM + i] = protected_argv[i];
697 SETUP_DEBUG();
699 if (debug)
701 g_print ("calling %s with argv:\n", helper_process);
702 for (i = 0; i < argc + 1 + ARG_COUNT; i++)
703 g_print ("argv[%d]: %s\n", i, (new_argv[i] ? new_argv[i] : "NULL"));
706 if (!utf8_charv_to_wcharv (new_argv, &wargv, &conv_error_index, &conv_error))
708 if (conv_error_index == ARG_WORKING_DIRECTORY)
709 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_CHDIR,
710 _("Invalid working directory: %s"),
711 conv_error->message);
712 else
713 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
714 _("Invalid string in argument vector at %d: %s"),
715 conv_error_index - ARG_PROGRAM, conv_error->message);
716 g_error_free (conv_error);
717 g_strfreev (protected_argv);
718 g_free (new_argv[0]);
719 g_free (new_argv[ARG_WORKING_DIRECTORY]);
720 g_free (new_argv);
721 g_free (helper_process);
723 goto cleanup_and_fail;
726 if (!utf8_charv_to_wcharv (envp, &wenvp, NULL, &conv_error))
728 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
729 _("Invalid string in environment: %s"),
730 conv_error->message);
731 g_error_free (conv_error);
732 g_strfreev (protected_argv);
733 g_free (new_argv[0]);
734 g_free (new_argv[ARG_WORKING_DIRECTORY]);
735 g_free (new_argv);
736 g_free (helper_process);
737 g_strfreev ((gchar **) wargv);
739 goto cleanup_and_fail;
742 whelper = g_utf8_to_utf16 (helper_process, -1, NULL, NULL, NULL);
743 g_free (helper_process);
745 if (wenvp != NULL)
746 rc = _wspawnvpe (P_NOWAIT, whelper, (const wchar_t **) wargv, (const wchar_t **) wenvp);
747 else
748 rc = _wspawnvp (P_NOWAIT, whelper, (const wchar_t **) wargv);
750 errsv = errno;
752 g_free (whelper);
753 g_strfreev ((gchar **) wargv);
754 g_strfreev ((gchar **) wenvp);
756 /* Close the other process's ends of the pipes in this process,
757 * otherwise the reader will never get EOF.
759 close_and_invalidate (&child_err_report_pipe[1]);
760 close_and_invalidate (&helper_sync_pipe[0]);
762 g_strfreev (protected_argv);
764 g_free (new_argv[0]);
765 g_free (new_argv[ARG_WORKING_DIRECTORY]);
766 g_free (new_argv);
768 /* Check if gspawn-win32-helper couldn't be run */
769 if (rc == -1 && errsv != 0)
771 g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
772 _("Failed to execute helper program (%s)"),
773 g_strerror (errsv));
774 goto cleanup_and_fail;
777 if (exit_status != NULL)
779 /* Synchronous case. Pass helper's report pipe back to caller,
780 * which takes care of reading it after the grandchild has
781 * finished.
783 g_assert (err_report != NULL);
784 *err_report = child_err_report_pipe[0];
785 write (helper_sync_pipe[1], " ", 1);
786 close_and_invalidate (&helper_sync_pipe[1]);
788 else
790 /* Asynchronous case. We read the helper's report right away. */
791 if (!read_helper_report (child_err_report_pipe[0], helper_report, error))
792 goto cleanup_and_fail;
794 close_and_invalidate (&child_err_report_pipe[0]);
796 switch (helper_report[0])
798 case CHILD_NO_ERROR:
799 if (child_handle && do_return_handle)
801 /* rc is our HANDLE for gspawn-win32-helper. It has
802 * told us the HANDLE of its child. Duplicate that into
803 * a HANDLE valid in this process.
805 if (!DuplicateHandle ((HANDLE) rc, (HANDLE) helper_report[1],
806 GetCurrentProcess (), (LPHANDLE) child_handle,
807 0, TRUE, DUPLICATE_SAME_ACCESS))
809 char *emsg = g_win32_error_message (GetLastError ());
810 g_print("%s\n", emsg);
811 *child_handle = 0;
814 else if (child_handle)
815 *child_handle = 0;
816 write (helper_sync_pipe[1], " ", 1);
817 close_and_invalidate (&helper_sync_pipe[1]);
818 break;
820 default:
821 write (helper_sync_pipe[1], " ", 1);
822 close_and_invalidate (&helper_sync_pipe[1]);
823 set_child_error (helper_report, working_directory, error);
824 goto cleanup_and_fail;
828 /* Success against all odds! return the information */
830 if (rc != -1)
831 CloseHandle ((HANDLE) rc);
833 return TRUE;
835 cleanup_and_fail:
837 if (rc != -1)
838 CloseHandle ((HANDLE) rc);
839 if (child_err_report_pipe[0] != -1)
840 close (child_err_report_pipe[0]);
841 if (child_err_report_pipe[1] != -1)
842 close (child_err_report_pipe[1]);
843 if (helper_sync_pipe[0] != -1)
844 close (helper_sync_pipe[0]);
845 if (helper_sync_pipe[1] != -1)
846 close (helper_sync_pipe[1]);
848 return FALSE;
851 static gboolean
852 do_spawn_with_pipes (gint *exit_status,
853 gboolean do_return_handle,
854 const gchar *working_directory,
855 gchar **argv,
856 char **envp,
857 GSpawnFlags flags,
858 GSpawnChildSetupFunc child_setup,
859 GPid *child_handle,
860 gint *standard_input,
861 gint *standard_output,
862 gint *standard_error,
863 gint *err_report,
864 GError **error)
866 int stdin_pipe[2] = { -1, -1 };
867 int stdout_pipe[2] = { -1, -1 };
868 int stderr_pipe[2] = { -1, -1 };
870 if (standard_input && !make_pipe (stdin_pipe, error))
871 goto cleanup_and_fail;
873 if (standard_output && !make_pipe (stdout_pipe, error))
874 goto cleanup_and_fail;
876 if (standard_error && !make_pipe (stderr_pipe, error))
877 goto cleanup_and_fail;
879 if (!do_spawn_with_fds (exit_status,
880 do_return_handle,
881 working_directory,
882 argv,
883 envp,
884 flags,
885 child_setup,
886 child_handle,
887 stdin_pipe[0],
888 stdout_pipe[1],
889 stderr_pipe[1],
890 err_report,
891 error))
892 goto cleanup_and_fail;
894 /* Close the other process's ends of the pipes in this process,
895 * otherwise the reader will never get EOF.
897 close_and_invalidate (&stdin_pipe[0]);
898 close_and_invalidate (&stdout_pipe[1]);
899 close_and_invalidate (&stderr_pipe[1]);
901 if (standard_input)
902 *standard_input = stdin_pipe[1];
903 if (standard_output)
904 *standard_output = stdout_pipe[0];
905 if (standard_error)
906 *standard_error = stderr_pipe[0];
908 return TRUE;
910 cleanup_and_fail:
912 if (stdin_pipe[0] != -1)
913 close (stdin_pipe[0]);
914 if (stdin_pipe[1] != -1)
915 close (stdin_pipe[1]);
916 if (stdout_pipe[0] != -1)
917 close (stdout_pipe[0]);
918 if (stdout_pipe[1] != -1)
919 close (stdout_pipe[1]);
920 if (stderr_pipe[0] != -1)
921 close (stderr_pipe[0]);
922 if (stderr_pipe[1] != -1)
923 close (stderr_pipe[1]);
925 return FALSE;
928 gboolean
929 g_spawn_sync (const gchar *working_directory,
930 gchar **argv,
931 gchar **envp,
932 GSpawnFlags flags,
933 GSpawnChildSetupFunc child_setup,
934 gpointer user_data,
935 gchar **standard_output,
936 gchar **standard_error,
937 gint *exit_status,
938 GError **error)
940 gint outpipe = -1;
941 gint errpipe = -1;
942 gint reportpipe = -1;
943 GIOChannel *outchannel = NULL;
944 GIOChannel *errchannel = NULL;
945 GPollFD outfd, errfd;
946 GPollFD fds[2];
947 gint nfds;
948 gint outindex = -1;
949 gint errindex = -1;
950 gint ret;
951 GString *outstr = NULL;
952 GString *errstr = NULL;
953 gboolean failed;
954 gint status;
956 g_return_val_if_fail (argv != NULL, FALSE);
957 g_return_val_if_fail (!(flags & G_SPAWN_DO_NOT_REAP_CHILD), FALSE);
958 g_return_val_if_fail (standard_output == NULL ||
959 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
960 g_return_val_if_fail (standard_error == NULL ||
961 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
963 /* Just to ensure segfaults if callers try to use
964 * these when an error is reported.
966 if (standard_output)
967 *standard_output = NULL;
969 if (standard_error)
970 *standard_error = NULL;
972 if (!do_spawn_with_pipes (&status,
973 FALSE,
974 working_directory,
975 argv,
976 envp,
977 flags,
978 child_setup,
979 NULL,
980 NULL,
981 standard_output ? &outpipe : NULL,
982 standard_error ? &errpipe : NULL,
983 &reportpipe,
984 error))
985 return FALSE;
987 /* Read data from child. */
989 failed = FALSE;
991 if (outpipe >= 0)
993 outstr = g_string_new (NULL);
994 outchannel = g_io_channel_win32_new_fd (outpipe);
995 g_io_channel_set_encoding (outchannel, NULL, NULL);
996 g_io_channel_set_buffered (outchannel, FALSE);
997 g_io_channel_win32_make_pollfd (outchannel,
998 G_IO_IN | G_IO_ERR | G_IO_HUP,
999 &outfd);
1000 if (debug)
1001 g_print ("outfd=%p\n", (HANDLE) outfd.fd);
1004 if (errpipe >= 0)
1006 errstr = g_string_new (NULL);
1007 errchannel = g_io_channel_win32_new_fd (errpipe);
1008 g_io_channel_set_encoding (errchannel, NULL, NULL);
1009 g_io_channel_set_buffered (errchannel, FALSE);
1010 g_io_channel_win32_make_pollfd (errchannel,
1011 G_IO_IN | G_IO_ERR | G_IO_HUP,
1012 &errfd);
1013 if (debug)
1014 g_print ("errfd=%p\n", (HANDLE) errfd.fd);
1017 /* Read data until we get EOF on all pipes. */
1018 while (!failed && (outpipe >= 0 || errpipe >= 0))
1020 nfds = 0;
1021 if (outpipe >= 0)
1023 fds[nfds] = outfd;
1024 outindex = nfds;
1025 nfds++;
1027 if (errpipe >= 0)
1029 fds[nfds] = errfd;
1030 errindex = nfds;
1031 nfds++;
1034 if (debug)
1035 g_print ("g_spawn_sync: calling g_io_channel_win32_poll, nfds=%d\n",
1036 nfds);
1038 ret = g_io_channel_win32_poll (fds, nfds, -1);
1040 if (ret < 0)
1042 failed = TRUE;
1044 g_set_error_literal (error, G_SPAWN_ERROR, G_SPAWN_ERROR_READ,
1045 _("Unexpected error in g_io_channel_win32_poll() reading data from a child process"));
1047 break;
1050 if (outpipe >= 0 && (fds[outindex].revents & G_IO_IN))
1052 switch (read_data (outstr, outchannel, error))
1054 case READ_FAILED:
1055 if (debug)
1056 g_print ("g_spawn_sync: outchannel: READ_FAILED\n");
1057 failed = TRUE;
1058 break;
1059 case READ_EOF:
1060 if (debug)
1061 g_print ("g_spawn_sync: outchannel: READ_EOF\n");
1062 g_io_channel_unref (outchannel);
1063 outchannel = NULL;
1064 close_and_invalidate (&outpipe);
1065 break;
1066 default:
1067 if (debug)
1068 g_print ("g_spawn_sync: outchannel: OK\n");
1069 break;
1072 if (failed)
1073 break;
1076 if (errpipe >= 0 && (fds[errindex].revents & G_IO_IN))
1078 switch (read_data (errstr, errchannel, error))
1080 case READ_FAILED:
1081 if (debug)
1082 g_print ("g_spawn_sync: errchannel: READ_FAILED\n");
1083 failed = TRUE;
1084 break;
1085 case READ_EOF:
1086 if (debug)
1087 g_print ("g_spawn_sync: errchannel: READ_EOF\n");
1088 g_io_channel_unref (errchannel);
1089 errchannel = NULL;
1090 close_and_invalidate (&errpipe);
1091 break;
1092 default:
1093 if (debug)
1094 g_print ("g_spawn_sync: errchannel: OK\n");
1095 break;
1098 if (failed)
1099 break;
1103 if (reportpipe == -1)
1105 /* No helper process, exit status of actual spawned process
1106 * already available.
1108 if (exit_status)
1109 *exit_status = status;
1111 else
1113 /* Helper process was involved. Read its report now after the
1114 * grandchild has finished.
1116 gintptr helper_report[2];
1118 if (!read_helper_report (reportpipe, helper_report, error))
1119 failed = TRUE;
1120 else
1122 switch (helper_report[0])
1124 case CHILD_NO_ERROR:
1125 if (exit_status)
1126 *exit_status = helper_report[1];
1127 break;
1128 default:
1129 set_child_error (helper_report, working_directory, error);
1130 failed = TRUE;
1131 break;
1134 close_and_invalidate (&reportpipe);
1138 /* These should only be open still if we had an error. */
1140 if (outchannel != NULL)
1141 g_io_channel_unref (outchannel);
1142 if (errchannel != NULL)
1143 g_io_channel_unref (errchannel);
1144 if (outpipe >= 0)
1145 close_and_invalidate (&outpipe);
1146 if (errpipe >= 0)
1147 close_and_invalidate (&errpipe);
1149 if (failed)
1151 if (outstr)
1152 g_string_free (outstr, TRUE);
1153 if (errstr)
1154 g_string_free (errstr, TRUE);
1156 return FALSE;
1158 else
1160 if (standard_output)
1161 *standard_output = g_string_free (outstr, FALSE);
1163 if (standard_error)
1164 *standard_error = g_string_free (errstr, FALSE);
1166 return TRUE;
1170 gboolean
1171 g_spawn_async_with_pipes (const gchar *working_directory,
1172 gchar **argv,
1173 gchar **envp,
1174 GSpawnFlags flags,
1175 GSpawnChildSetupFunc child_setup,
1176 gpointer user_data,
1177 GPid *child_handle,
1178 gint *standard_input,
1179 gint *standard_output,
1180 gint *standard_error,
1181 GError **error)
1183 g_return_val_if_fail (argv != NULL, FALSE);
1184 g_return_val_if_fail (standard_output == NULL ||
1185 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
1186 g_return_val_if_fail (standard_error == NULL ||
1187 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
1188 /* can't inherit stdin if we have an input pipe. */
1189 g_return_val_if_fail (standard_input == NULL ||
1190 !(flags & G_SPAWN_CHILD_INHERITS_STDIN), FALSE);
1192 return do_spawn_with_pipes (NULL,
1193 (flags & G_SPAWN_DO_NOT_REAP_CHILD),
1194 working_directory,
1195 argv,
1196 envp,
1197 flags,
1198 child_setup,
1199 child_handle,
1200 standard_input,
1201 standard_output,
1202 standard_error,
1203 NULL,
1204 error);
1207 gboolean
1208 g_spawn_async_with_fds (const gchar *working_directory,
1209 gchar **argv,
1210 gchar **envp,
1211 GSpawnFlags flags,
1212 GSpawnChildSetupFunc child_setup,
1213 gpointer user_data,
1214 GPid *child_handle,
1215 gint stdin_fd,
1216 gint stdout_fd,
1217 gint stderr_fd,
1218 GError **error)
1220 g_return_val_if_fail (argv != NULL, FALSE);
1221 g_return_val_if_fail (stdin_fd == -1 ||
1222 !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
1223 g_return_val_if_fail (stderr_fd == -1 ||
1224 !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
1225 /* can't inherit stdin if we have an input pipe. */
1226 g_return_val_if_fail (stdin_fd == -1 ||
1227 !(flags & G_SPAWN_CHILD_INHERITS_STDIN), FALSE);
1229 return do_spawn_with_fds (NULL,
1230 (flags & G_SPAWN_DO_NOT_REAP_CHILD),
1231 working_directory,
1232 argv,
1233 envp,
1234 flags,
1235 child_setup,
1236 child_handle,
1237 stdin_fd,
1238 stdout_fd,
1239 stderr_fd,
1240 NULL,
1241 error);
1244 gboolean
1245 g_spawn_command_line_sync (const gchar *command_line,
1246 gchar **standard_output,
1247 gchar **standard_error,
1248 gint *exit_status,
1249 GError **error)
1251 gboolean retval;
1252 gchar **argv = 0;
1254 g_return_val_if_fail (command_line != NULL, FALSE);
1256 if (!g_shell_parse_argv (command_line,
1257 NULL, &argv,
1258 error))
1259 return FALSE;
1261 retval = g_spawn_sync (NULL,
1262 argv,
1263 NULL,
1264 G_SPAWN_SEARCH_PATH,
1265 NULL,
1266 NULL,
1267 standard_output,
1268 standard_error,
1269 exit_status,
1270 error);
1271 g_strfreev (argv);
1273 return retval;
1276 gboolean
1277 g_spawn_command_line_async (const gchar *command_line,
1278 GError **error)
1280 gboolean retval;
1281 gchar **argv = 0;
1283 g_return_val_if_fail (command_line != NULL, FALSE);
1285 if (!g_shell_parse_argv (command_line,
1286 NULL, &argv,
1287 error))
1288 return FALSE;
1290 retval = g_spawn_async (NULL,
1291 argv,
1292 NULL,
1293 G_SPAWN_SEARCH_PATH,
1294 NULL,
1295 NULL,
1296 NULL,
1297 error);
1298 g_strfreev (argv);
1300 return retval;
1303 void
1304 g_spawn_close_pid (GPid pid)
1306 CloseHandle (pid);
1309 gboolean
1310 g_spawn_check_exit_status (gint exit_status,
1311 GError **error)
1313 gboolean ret = FALSE;
1315 if (exit_status != 0)
1317 g_set_error (error, G_SPAWN_EXIT_ERROR, exit_status,
1318 _("Child process exited with code %ld"),
1319 (long) exit_status);
1320 goto out;
1323 ret = TRUE;
1324 out:
1325 return ret;
1328 #ifdef G_OS_WIN32
1330 /* Binary compatibility versions. Not for newly compiled code. */
1332 _GLIB_EXTERN gboolean g_spawn_async_utf8 (const gchar *working_directory,
1333 gchar **argv,
1334 gchar **envp,
1335 GSpawnFlags flags,
1336 GSpawnChildSetupFunc child_setup,
1337 gpointer user_data,
1338 GPid *child_pid,
1339 GError **error);
1340 _GLIB_EXTERN gboolean g_spawn_async_with_pipes_utf8 (const gchar *working_directory,
1341 gchar **argv,
1342 gchar **envp,
1343 GSpawnFlags flags,
1344 GSpawnChildSetupFunc child_setup,
1345 gpointer user_data,
1346 GPid *child_pid,
1347 gint *standard_input,
1348 gint *standard_output,
1349 gint *standard_error,
1350 GError **error);
1351 _GLIB_EXTERN gboolean g_spawn_sync_utf8 (const gchar *working_directory,
1352 gchar **argv,
1353 gchar **envp,
1354 GSpawnFlags flags,
1355 GSpawnChildSetupFunc child_setup,
1356 gpointer user_data,
1357 gchar **standard_output,
1358 gchar **standard_error,
1359 gint *exit_status,
1360 GError **error);
1361 _GLIB_EXTERN gboolean g_spawn_command_line_sync_utf8 (const gchar *command_line,
1362 gchar **standard_output,
1363 gchar **standard_error,
1364 gint *exit_status,
1365 GError **error);
1366 _GLIB_EXTERN gboolean g_spawn_command_line_async_utf8 (const gchar *command_line,
1367 GError **error);
1369 gboolean
1370 g_spawn_async_utf8 (const gchar *working_directory,
1371 gchar **argv,
1372 gchar **envp,
1373 GSpawnFlags flags,
1374 GSpawnChildSetupFunc child_setup,
1375 gpointer user_data,
1376 GPid *child_handle,
1377 GError **error)
1379 return g_spawn_async (working_directory,
1380 argv,
1381 envp,
1382 flags,
1383 child_setup,
1384 user_data,
1385 child_handle,
1386 error);
1389 gboolean
1390 g_spawn_async_with_pipes_utf8 (const gchar *working_directory,
1391 gchar **argv,
1392 gchar **envp,
1393 GSpawnFlags flags,
1394 GSpawnChildSetupFunc child_setup,
1395 gpointer user_data,
1396 GPid *child_handle,
1397 gint *standard_input,
1398 gint *standard_output,
1399 gint *standard_error,
1400 GError **error)
1402 return g_spawn_async_with_pipes (working_directory,
1403 argv,
1404 envp,
1405 flags,
1406 child_setup,
1407 user_data,
1408 child_handle,
1409 standard_input,
1410 standard_output,
1411 standard_error,
1412 error);
1415 gboolean
1416 g_spawn_sync_utf8 (const gchar *working_directory,
1417 gchar **argv,
1418 gchar **envp,
1419 GSpawnFlags flags,
1420 GSpawnChildSetupFunc child_setup,
1421 gpointer user_data,
1422 gchar **standard_output,
1423 gchar **standard_error,
1424 gint *exit_status,
1425 GError **error)
1427 return g_spawn_sync (working_directory,
1428 argv,
1429 envp,
1430 flags,
1431 child_setup,
1432 user_data,
1433 standard_output,
1434 standard_error,
1435 exit_status,
1436 error);
1439 gboolean
1440 g_spawn_command_line_sync_utf8 (const gchar *command_line,
1441 gchar **standard_output,
1442 gchar **standard_error,
1443 gint *exit_status,
1444 GError **error)
1446 return g_spawn_command_line_sync (command_line,
1447 standard_output,
1448 standard_error,
1449 exit_status,
1450 error);
1453 gboolean
1454 g_spawn_command_line_async_utf8 (const gchar *command_line,
1455 GError **error)
1457 return g_spawn_command_line_async (command_line, error);
1460 #endif /* G_OS_WIN32 */
1462 #endif /* !GSPAWN_HELPER */