GSubprocess win32 fixups
[platform/upstream/glib.git] / gio / gsubprocess.c
1 /* GIO - GLib Input, Output and Streaming Library
2  *
3  * Copyright © 2012, 2013 Red Hat, Inc.
4  * Copyright © 2012, 2013 Canonical Limited
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Lesser General Public License as published
8  * by the Free Software Foundation; either version 2 of the licence or (at
9  * your option) any later version.
10  *
11  * See the included COPYING file for more information.
12  *
13  * Authors: Colin Walters <walters@verbum.org>
14  *          Ryan Lortie <desrt@desrt.ca>
15  */
16
17 /**
18  * SECTION:gsubprocess
19  * @title: GSubprocess
20  * @short_description: Child processes
21  * @see_also: #GSubprocessLauncher
22  *
23  * #GSubprocess allows the creation of and interaction with child
24  * processes.
25  *
26  * Processes can be communicated with using standard GIO-style APIs (ie:
27  * #GInputStream, #GOutputStream).  There are GIO-style APIs to wait for
28  * process termination (ie: cancellable and with an asynchronous
29  * variant).
30  *
31  * There is an API to force a process to terminate, as well as a
32  * race-free API for sending UNIX signals to a subprocess.
33  *
34  * One major advantage that GIO brings over the core GLib library is
35  * comprehensive API for asynchronous I/O, such
36  * g_output_stream_splice_async().  This makes GSubprocess
37  * significantly more powerful and flexible than equivalent APIs in
38  * some other languages such as the <literal>subprocess.py</literal>
39  * included with Python.  For example, using #GSubprocess one could
40  * create two child processes, reading standard output from the first,
41  * processing it, and writing to the input stream of the second, all
42  * without blocking the main loop.
43  *
44  * A powerful g_subprocess_communicate() API is provided similar to the
45  * <literal>communicate()</literal> method of
46  * <literal>subprocess.py</literal>.  This enables very easy interaction
47  * with a subprocess that has been opened with pipes.
48  *
49  * #GSubprocess defaults to tight control over the file descriptors open
50  * in the child process, avoiding dangling-fd issues that are caused by
51  * a simple fork()/exec().  The only open file descriptors in the
52  * spawned process are ones that were explicitly specified by the
53  * #GSubprocess API (unless %G_SUBPROCESS_FLAGS_INHERIT_FDS was
54  * specified).
55  *
56  * #GSubprocess will quickly reap all child processes as they exit,
57  * avoiding "zombie processes" remaining around for long periods of
58  * time.  g_subprocess_wait() can be used to wait for this to happen,
59  * but it will happen even without the call being explicitly made.
60  *
61  * As a matter of principle, #GSubprocess has no API that accepts
62  * shell-style space-separated strings.  It will, however, match the
63  * typical shell behaviour of searching the PATH for executables that do
64  * not contain a directory separator in their name.
65  *
66  * #GSubprocess attempts to have a very simple API for most uses (ie:
67  * spawning a subprocess with arguments and support for most typical
68  * kinds of input and output redirection).  See g_subprocess_new(). The
69  * #GSubprocessLauncher API is provided for more complicated cases
70  * (advanced types of redirection, environment variable manipulation,
71  * change of working directory, child setup functions, etc).
72  *
73  * A typical use of #GSubprocess will involve calling
74  * g_subprocess_new(), followed by g_subprocess_wait() or
75  * g_subprocess_wait_sync().  After the process exits, the status can be
76  * checked using functions such as g_subprocess_get_if_exited() (which
77  * are similar to the familiar WIFEXITED-style POSIX macros).
78  *
79  * Since: 2.40
80  **/
81
82 #include "config.h"
83
84 #include "gsubprocess.h"
85 #include "gsubprocesslauncher-private.h"
86 #include "gasyncresult.h"
87 #include "giostream.h"
88 #include "gmemoryinputstream.h"
89 #include "glibintl.h"
90 #include "glib-private.h"
91
92 #include <string.h>
93 #ifdef G_OS_UNIX
94 #include <gio/gunixoutputstream.h>
95 #include <gio/gfiledescriptorbased.h>
96 #include <gio/gunixinputstream.h>
97 #include <gstdio.h>
98 #include <glib-unix.h>
99 #include <fcntl.h>
100 #endif
101 #ifdef G_OS_WIN32
102 #include <windows.h>
103 #include <io.h>
104 #include "giowin32-priv.h"
105 #endif
106
107 #ifndef O_BINARY
108 #define O_BINARY 0
109 #endif
110
111 #define COMMUNICATE_READ_SIZE 4096
112
113 /* A GSubprocess can have two possible states: running and not.
114  *
115  * These two states are reflected by the value of 'pid'.  If it is
116  * non-zero then the process is running, with that pid.
117  *
118  * When a GSubprocess is first created with g_object_new() it is not
119  * running.  When it is finalized, it is also not running.
120  *
121  * During initable_init(), if the g_spawn() is successful then we
122  * immediately register a child watch and take an extra ref on the
123  * subprocess.  That reference doesn't drop until the child has quit,
124  * which is why finalize can only happen in the non-running state.  In
125  * the event that the g_spawn() failed we will still be finalizing a
126  * non-running GSubprocess (before returning from g_subprocess_new())
127  * with NULL.
128  *
129  * We make extensive use of the glib worker thread to guarantee
130  * race-free operation.  As with all child watches, glib calls waitpid()
131  * in the worker thread.  It reports the child exiting to us via the
132  * worker thread (which means that we can do synchronous waits without
133  * running a separate loop).  We also send signals to the child process
134  * via the worker thread so that we don't race with waitpid() and
135  * accidentally send a signal to an already-reaped child.
136  */
137 static void initable_iface_init (GInitableIface         *initable_iface);
138
139 typedef GObjectClass GSubprocessClass;
140
141 struct _GSubprocess
142 {
143   GObject parent;
144
145   /* only used during construction */
146   GSubprocessLauncher *launcher;
147   GSubprocessFlags flags;
148   gchar **argv;
149
150   /* state tracking variables */
151   gchar identifier[24];
152   int status;
153   GPid pid;
154
155   /* list of GTask */
156   GMutex pending_waits_lock;
157   GSList *pending_waits;
158
159   /* These are the streams created if a pipe is requested via flags. */
160   GOutputStream *stdin_pipe;
161   GInputStream  *stdout_pipe;
162   GInputStream  *stderr_pipe;
163 };
164
165 G_DEFINE_TYPE_WITH_CODE (GSubprocess, g_subprocess, G_TYPE_OBJECT,
166                          G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init));
167
168 enum
169 {
170   PROP_0,
171   PROP_FLAGS,
172   PROP_ARGV,
173   N_PROPS
174 };
175
176 #ifdef G_OS_UNIX
177 typedef struct
178 {
179   gint                 fds[3];
180   GSpawnChildSetupFunc child_setup_func;
181   gpointer             child_setup_data;
182   GArray              *basic_fd_assignments;
183   GArray              *needdup_fd_assignments;
184 } ChildData;
185
186 static void
187 unset_cloexec (int fd)
188 {
189   int flags;
190   int result;
191
192   flags = fcntl (fd, F_GETFD, 0);
193
194   if (flags != -1)
195     {
196       flags &= (~FD_CLOEXEC);
197       do
198         result = fcntl (fd, F_SETFD, flags);
199       while (result == -1 && errno == EINTR);
200     }
201 }
202
203 /**
204  * Based on code derived from
205  * gnome-terminal:src/terminal-screen.c:terminal_screen_child_setup(),
206  * used under the LGPLv2+ with permission from author.
207  */
208 static void
209 child_setup (gpointer user_data)
210 {
211   ChildData *child_data = user_data;
212   gint i;
213   gint result;
214
215   /* We're on the child side now.  "Rename" the file descriptors in
216    * child_data.fds[] to stdin/stdout/stderr.
217    *
218    * We don't close the originals.  It's possible that the originals
219    * should not be closed and if they should be closed then they should
220    * have been created O_CLOEXEC.
221    */
222   for (i = 0; i < 3; i++)
223     if (child_data->fds[i] != -1 && child_data->fds[i] != i)
224       {
225         do
226           result = dup2 (child_data->fds[i], i);
227         while (result == -1 && errno == EINTR);
228       }
229
230   /* Basic fd assignments we can just unset FD_CLOEXEC */
231   if (child_data->basic_fd_assignments)
232     {
233       for (i = 0; i < child_data->basic_fd_assignments->len; i++)
234         {
235           gint fd = g_array_index (child_data->basic_fd_assignments, int, i);
236
237           unset_cloexec (fd);
238         }
239     }
240
241   /* If we're doing remapping fd assignments, we need to handle
242    * the case where the user has specified e.g.:
243    * 5 -> 4, 4 -> 6
244    *
245    * We do this by duping the source fds temporarily.
246    */ 
247   if (child_data->needdup_fd_assignments)
248     {
249       for (i = 0; i < child_data->needdup_fd_assignments->len; i += 2)
250         {
251           gint parent_fd = g_array_index (child_data->needdup_fd_assignments, int, i);
252           gint new_parent_fd;
253
254           do
255             new_parent_fd = fcntl (parent_fd, F_DUPFD_CLOEXEC, 3);
256           while (parent_fd == -1 && errno == EINTR);
257
258           g_array_index (child_data->needdup_fd_assignments, int, i) = new_parent_fd;
259         }
260       for (i = 0; i < child_data->needdup_fd_assignments->len; i += 2)
261         {
262           gint parent_fd = g_array_index (child_data->needdup_fd_assignments, int, i);
263           gint child_fd = g_array_index (child_data->needdup_fd_assignments, int, i+1);
264
265           if (parent_fd == child_fd)
266             {
267               unset_cloexec (parent_fd);
268             }
269           else
270             {
271               do
272                 result = dup2 (parent_fd, child_fd);
273               while (result == -1 && errno == EINTR);
274               (void) close (parent_fd);
275             }
276         }
277     }
278
279   if (child_data->child_setup_func)
280     child_data->child_setup_func (child_data->child_setup_data);
281 }
282 #endif
283
284 static GInputStream *
285 platform_input_stream_from_spawn_fd (gint fd)
286 {
287   if (fd < 0)
288     return NULL;
289
290 #ifdef G_OS_UNIX
291   return g_unix_input_stream_new (fd, TRUE);
292 #else
293   return g_win32_input_stream_new_from_fd (fd, TRUE);
294 #endif
295 }
296
297 static GOutputStream *
298 platform_output_stream_from_spawn_fd (gint fd)
299 {
300   if (fd < 0)
301     return NULL;
302
303 #ifdef G_OS_UNIX
304   return g_unix_output_stream_new (fd, TRUE);
305 #else
306   return g_win32_output_stream_new_from_fd (fd, TRUE);
307 #endif
308 }
309
310 #ifdef G_OS_UNIX
311 static gint
312 unix_open_file (const char  *filename,
313                 gint         mode,
314                 GError     **error)
315 {
316   gint my_fd;
317
318   my_fd = g_open (filename, mode | O_BINARY | O_CLOEXEC, 0666);
319
320   /* If we return -1 we should also set the error */
321   if (my_fd < 0)
322     {
323       gint saved_errno = errno;
324       char *display_name;
325
326       display_name = g_filename_display_name (filename);
327       g_set_error (error, G_IO_ERROR, g_io_error_from_errno (saved_errno),
328                    _("Error opening file '%s': %s"), display_name,
329                    g_strerror (saved_errno));
330       g_free (display_name);
331       /* fall through... */
332     }
333
334   return my_fd;
335 }
336 #endif
337
338 static void
339 g_subprocess_set_property (GObject      *object,
340                            guint         prop_id,
341                            const GValue *value,
342                            GParamSpec   *pspec)
343 {
344   GSubprocess *self = G_SUBPROCESS (object);
345
346   switch (prop_id)
347     {
348     case PROP_FLAGS:
349       self->flags = g_value_get_flags (value);
350       break;
351
352     case PROP_ARGV:
353       self->argv = g_value_dup_boxed (value);
354       break;
355
356     default:
357       g_assert_not_reached ();
358     }
359 }
360
361 static gboolean
362 g_subprocess_exited (GPid     pid,
363                      gint     status,
364                      gpointer user_data)
365 {
366   GSubprocess *self = user_data;
367   GSList *tasks;
368
369   g_assert (self->pid == pid);
370
371   g_mutex_lock (&self->pending_waits_lock);
372   self->status = status;
373   tasks = self->pending_waits;
374   self->pending_waits = NULL;
375   self->pid = 0;
376   g_mutex_unlock (&self->pending_waits_lock);
377
378   /* Signal anyone in g_subprocess_wait_async() to wake up now */
379   while (tasks)
380     {
381       g_task_return_boolean (tasks->data, TRUE);
382       tasks = g_slist_delete_link (tasks, tasks);
383     }
384
385   g_spawn_close_pid (pid);
386
387   return FALSE;
388 }
389
390 static gboolean
391 initable_init (GInitable     *initable,
392                GCancellable  *cancellable,
393                GError       **error)
394 {
395   GSubprocess *self = G_SUBPROCESS (initable);
396 #ifdef G_OS_UNIX
397   ChildData child_data = { { -1, -1, -1 }, 0 };
398 #endif
399   gint *pipe_ptrs[3] = { NULL, NULL, NULL };
400   gint pipe_fds[3] = { -1, -1, -1 };
401   gint close_fds[3] = { -1, -1, -1 };
402   GSpawnFlags spawn_flags = 0;
403   gboolean success = FALSE;
404   gint i;
405
406   /* this is a programmer error */
407   if (!self->argv || !self->argv[0] || !self->argv[0][0])
408     return FALSE;
409
410   if (g_cancellable_set_error_if_cancelled (cancellable, error))
411     return FALSE;
412
413   /* We must setup the three fds that will end up in the child as stdin,
414    * stdout and stderr.
415    *
416    * First, stdin.
417    */
418   if (self->flags & G_SUBPROCESS_FLAGS_STDIN_INHERIT)
419     spawn_flags |= G_SPAWN_CHILD_INHERITS_STDIN;
420   else if (self->flags & G_SUBPROCESS_FLAGS_STDIN_PIPE)
421     pipe_ptrs[0] = &pipe_fds[0];
422 #ifdef G_OS_UNIX
423   else if (self->launcher)
424     {
425       if (self->launcher->stdin_fd != -1)
426         child_data.fds[0] = self->launcher->stdin_fd;
427       else if (self->launcher->stdin_path != NULL)
428         {
429           child_data.fds[0] = close_fds[0] = unix_open_file (self->launcher->stdin_path, O_RDONLY, error);
430           if (child_data.fds[0] == -1)
431             goto out;
432         }
433     }
434 #endif
435
436   /* Next, stdout. */
437   if (self->flags & G_SUBPROCESS_FLAGS_STDOUT_SILENCE)
438     spawn_flags |= G_SPAWN_STDOUT_TO_DEV_NULL;
439   else if (self->flags & G_SUBPROCESS_FLAGS_STDOUT_PIPE)
440     pipe_ptrs[1] = &pipe_fds[1];
441 #ifdef G_OS_UNIX
442   else if (self->launcher)
443     {
444       if (self->launcher->stdout_fd != -1)
445         child_data.fds[1] = self->launcher->stdout_fd;
446       else if (self->launcher->stdout_path != NULL)
447         {
448           child_data.fds[1] = close_fds[1] = unix_open_file (self->launcher->stdout_path, O_CREAT | O_WRONLY, error);
449           if (child_data.fds[1] == -1)
450             goto out;
451         }
452     }
453 #endif
454
455   /* Finally, stderr. */
456   if (self->flags & G_SUBPROCESS_FLAGS_STDERR_SILENCE)
457     spawn_flags |= G_SPAWN_STDERR_TO_DEV_NULL;
458   else if (self->flags & G_SUBPROCESS_FLAGS_STDERR_PIPE)
459     pipe_ptrs[2] = &pipe_fds[2];
460 #ifdef G_OS_UNIX
461   else if (self->flags & G_SUBPROCESS_FLAGS_STDERR_MERGE)
462     /* This will work because stderr gets setup after stdout. */
463     child_data.fds[2] = 1;
464   else if (self->launcher)
465     {
466       if (self->launcher->stderr_fd != -1)
467         child_data.fds[2] = self->launcher->stderr_fd;
468       else if (self->launcher->stderr_path != NULL)
469         {
470           child_data.fds[2] = close_fds[2] = unix_open_file (self->launcher->stderr_path, O_CREAT | O_WRONLY, error);
471           if (child_data.fds[2] == -1)
472             goto out;
473         }
474     }
475 #endif
476
477 #ifdef G_OS_UNIX
478   if (self->launcher)
479     {
480       child_data.basic_fd_assignments = self->launcher->basic_fd_assignments;
481       child_data.needdup_fd_assignments = self->launcher->needdup_fd_assignments;
482     }
483 #endif
484
485   /* argv0 has no '/' in it?  We better do a PATH lookup. */
486   if (strchr (self->argv[0], G_DIR_SEPARATOR) == NULL)
487     {
488       if (self->launcher && self->launcher->path_from_envp)
489         spawn_flags |= G_SPAWN_SEARCH_PATH_FROM_ENVP;
490       else
491         spawn_flags |= G_SPAWN_SEARCH_PATH;
492     }
493
494   if (self->flags & G_SUBPROCESS_FLAGS_INHERIT_FDS)
495     spawn_flags |= G_SPAWN_LEAVE_DESCRIPTORS_OPEN;
496
497   spawn_flags |= G_SPAWN_DO_NOT_REAP_CHILD;
498   spawn_flags |= G_SPAWN_CLOEXEC_PIPES;
499
500 #ifdef G_OS_UNIX
501   child_data.child_setup_func = self->launcher ? self->launcher->child_setup_func : NULL;
502   child_data.child_setup_data = self->launcher ? self->launcher->child_setup_user_data : NULL;
503 #endif
504
505   success = g_spawn_async_with_pipes (self->launcher ? self->launcher->cwd : NULL,
506                                       self->argv,
507                                       self->launcher ? self->launcher->envp : NULL,
508                                       spawn_flags,
509 #ifdef G_OS_UNIX
510                                       child_setup, &child_data,
511 #else
512                                       NULL, NULL,
513 #endif
514                                       &self->pid,
515                                       pipe_ptrs[0], pipe_ptrs[1], pipe_ptrs[2],
516                                       error);
517   g_assert (success == (self->pid != 0));
518
519   {
520     guint64 identifier;
521     gint s;
522
523 #ifdef G_OS_WIN32
524     identifier = (guint64) GetProcessId (self->pid);
525 #else
526     identifier = (guint64) self->pid;
527 #endif
528
529     s = snprintf (self->identifier, sizeof self->identifier, "%"G_GUINT64_FORMAT, identifier);
530     g_assert (0 < s && s < sizeof self->identifier);
531   }
532
533   /* Start attempting to reap the child immediately */
534   if (success)
535     {
536       GMainContext *worker_context;
537       GSource *source;
538
539       worker_context = GLIB_PRIVATE_CALL (g_get_worker_context) ();
540       source = g_child_watch_source_new (self->pid);
541       g_source_set_callback (source, (GSourceFunc) g_subprocess_exited, g_object_ref (self), g_object_unref);
542       g_source_attach (source, worker_context);
543       g_source_unref (source);
544     }
545
546 #ifdef G_OS_UNIX
547 out:
548 #endif
549   /* we don't need this past init... */
550   self->launcher = NULL;
551
552   for (i = 0; i < 3; i++)
553     if (close_fds[i] != -1)
554       close (close_fds[i]);
555
556   self->stdin_pipe = platform_output_stream_from_spawn_fd (pipe_fds[0]);
557   self->stdout_pipe = platform_input_stream_from_spawn_fd (pipe_fds[1]);
558   self->stderr_pipe = platform_input_stream_from_spawn_fd (pipe_fds[2]);
559
560   return success;
561 }
562
563 static void
564 g_subprocess_finalize (GObject *object)
565 {
566   GSubprocess *self = G_SUBPROCESS (object);
567
568   g_assert (self->pending_waits == NULL);
569   g_assert (self->pid == 0);
570
571   g_clear_object (&self->stdin_pipe);
572   g_clear_object (&self->stdout_pipe);
573   g_clear_object (&self->stderr_pipe);
574   g_free (self->argv);
575
576   G_OBJECT_CLASS (g_subprocess_parent_class)->finalize (object);
577 }
578
579 static void
580 g_subprocess_init (GSubprocess  *self)
581 {
582 }
583
584 static void
585 initable_iface_init (GInitableIface *initable_iface)
586 {
587   initable_iface->init = initable_init;
588 }
589
590 static void
591 g_subprocess_class_init (GSubprocessClass *class)
592 {
593   GObjectClass *gobject_class = G_OBJECT_CLASS (class);
594
595   gobject_class->finalize = g_subprocess_finalize;
596   gobject_class->set_property = g_subprocess_set_property;
597
598   g_object_class_install_property (gobject_class, PROP_FLAGS,
599                                    g_param_spec_flags ("flags", P_("Flags"), P_("Subprocess flags"),
600                                                        G_TYPE_SUBPROCESS_FLAGS, 0, G_PARAM_WRITABLE |
601                                                        G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS));
602   g_object_class_install_property (gobject_class, PROP_ARGV,
603                                    g_param_spec_boxed ("argv", P_("Arguments"), P_("Argument vector"),
604                                                        G_TYPE_STRV, G_PARAM_WRITABLE |
605                                                        G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS));
606 }
607
608 /**
609  * g_subprocess_new: (skip)
610  * @flags: flags that define the behaviour of the subprocess
611  * @error: (allow-none): return location for an error, or %NULL
612  * @argv0: first commandline argument to pass to the subprocess,
613  *     followed by more arguments, followed by %NULL
614  *
615  * Create a new process with the given flags and varargs argument list.
616  *
617  * The argument list must be terminated with %NULL.
618  *
619  * Returns: A newly created #GSubprocess, or %NULL on error (and @error
620  *   will be set)
621  *
622  * Since: 2.40
623  */
624 GSubprocess *
625 g_subprocess_new (GSubprocessFlags   flags,
626                   GError           **error,
627                   const gchar       *argv0,
628                   ...)
629 {
630   GSubprocess *result;
631   GPtrArray *args;
632   const gchar *arg;
633   va_list ap;
634
635   g_return_val_if_fail (argv0 != NULL && argv0[0] != '\0', NULL);
636   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
637
638   args = g_ptr_array_new ();
639
640   va_start (ap, argv0);
641   g_ptr_array_add (args, (gchar *) argv0);
642   while ((arg = va_arg (ap, const gchar *)))
643     g_ptr_array_add (args, (gchar *) arg);
644   g_ptr_array_add (args, NULL);
645
646   result = g_subprocess_newv ((const gchar * const *) args->pdata, flags, error);
647
648   g_ptr_array_free (args, TRUE);
649
650   return result;
651 }
652
653 /**
654  * g_subprocess_newv:
655  * @argv: commandline arguments for the subprocess
656  * @flags: flags that define the behaviour of the subprocess
657  * @error: (allow-none): return location for an error, or %NULL
658  *
659  * Create a new process with the given flags and argument list.
660  *
661  * The argument list is expected to be %NULL-terminated.
662  *
663  * Returns: A newly created #GSubprocess, or %NULL on error (and @error
664  *   will be set)
665  *
666  * Since: 2.40
667  * Rename to: g_subprocess_new
668  */
669 GSubprocess *
670 g_subprocess_newv (const gchar * const  *argv,
671                    GSubprocessFlags      flags,
672                    GError              **error)
673 {
674   g_return_val_if_fail (argv != NULL && argv[0] != NULL && argv[0][0] != '\0', NULL);
675
676   return g_initable_new (G_TYPE_SUBPROCESS, NULL, error,
677                          "argv", argv,
678                          "flags", flags,
679                          NULL);
680 }
681
682 const gchar *
683 g_subprocess_get_identifier (GSubprocess *subprocess)
684 {
685   g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), NULL);
686
687   if (subprocess->pid)
688     return subprocess->identifier;
689   else
690     return NULL;
691 }
692
693 /**
694  * g_subprocess_get_stdin_pipe:
695  * @subprocess: a #GSubprocess
696  *
697  * Gets the #GOutputStream that you can write to in order to give data
698  * to the stdin of @subprocess.
699  *
700  * The process must have been created with
701  * %G_SUBPROCESS_FLAGS_STDIN_PIPE.
702  *
703  * Returns: the stdout pipe
704  *
705  * Since: 2.40
706  **/
707 GOutputStream *
708 g_subprocess_get_stdin_pipe (GSubprocess *subprocess)
709 {
710   g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), NULL);
711   g_return_val_if_fail (subprocess->stdin_pipe, NULL);
712
713   return subprocess->stdin_pipe;
714 }
715
716 /**
717  * g_subprocess_get_stdout_pipe:
718  * @subprocess: a #GSubprocess
719  *
720  * Gets the #GInputStream from which to read the stdout output of
721  * @subprocess.
722  *
723  * The process must have been created with
724  * %G_SUBPROCESS_FLAGS_STDOUT_PIPE.
725  *
726  * Returns: the stdout pipe
727  *
728  * Since: 2.40
729  **/
730 GInputStream *
731 g_subprocess_get_stdout_pipe (GSubprocess *subprocess)
732 {
733   g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), NULL);
734   g_return_val_if_fail (subprocess->stdout_pipe, NULL);
735
736   return subprocess->stdout_pipe;
737 }
738
739 /**
740  * g_subprocess_get_stderr_pipe:
741  * @subprocess: a #GSubprocess
742  *
743  * Gets the #GInputStream from which to read the stderr output of
744  * @subprocess.
745  *
746  * The process must have been created with
747  * %G_SUBPROCESS_FLAGS_STDERR_PIPE.
748  *
749  * Returns: the stderr pipe
750  *
751  * Since: 2.40
752  **/
753 GInputStream *
754 g_subprocess_get_stderr_pipe (GSubprocess *subprocess)
755 {
756   g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), NULL);
757   g_return_val_if_fail (subprocess->stderr_pipe, NULL);
758
759   return subprocess->stderr_pipe;
760 }
761
762 static void
763 g_subprocess_wait_cancelled (GCancellable *cancellable,
764                              gpointer      user_data)
765 {
766   GTask *task = user_data;
767   GSubprocess *self;
768
769   self = g_task_get_source_object (task);
770
771   g_mutex_lock (&self->pending_waits_lock);
772   self->pending_waits = g_slist_remove (self->pending_waits, task);
773   g_mutex_unlock (&self->pending_waits_lock);
774
775   g_task_return_boolean (task, FALSE);
776   g_object_unref (task);
777 }
778
779 /**
780  * g_subprocess_wait_async:
781  * @subprocess: a #GSubprocess
782  * @cancellable: a #GCancellable, or %NULL
783  * @callback: a #GAsyncReadyCallback to call when the operation is complete
784  * @user_data: user_data for @callback
785  *
786  * Wait for the subprocess to terminate.
787  *
788  * This is the asynchronous version of g_subprocess_wait().
789  *
790  * Since: 2.40
791  */
792 void
793 g_subprocess_wait_async (GSubprocess         *subprocess,
794                          GCancellable        *cancellable,
795                          GAsyncReadyCallback  callback,
796                          gpointer             user_data)
797 {
798   GTask *task;
799
800   task = g_task_new (subprocess, cancellable, callback, user_data);
801
802   g_mutex_lock (&subprocess->pending_waits_lock);
803   if (subprocess->pid)
804     {
805       /* Only bother with cancellable if we're putting it in the list.
806        * If not, it's going to dispatch immediately anyway and we will
807        * see the cancellation in the _finish().
808        */
809       if (cancellable)
810         g_signal_connect_object (cancellable, "cancelled", G_CALLBACK (g_subprocess_wait_cancelled), task, 0);
811
812       subprocess->pending_waits = g_slist_prepend (subprocess->pending_waits, task);
813       task = NULL;
814     }
815   g_mutex_unlock (&subprocess->pending_waits_lock);
816
817   /* If we still have task then it's because did_exit is already TRUE */
818   if (task != NULL)
819     {
820       g_task_return_boolean (task, TRUE);
821       g_object_unref (task);
822     }
823 }
824
825 /**
826  * g_subprocess_wait_finish:
827  * @subprocess: a #GSubprocess
828  * @result: the #GAsyncResult passed to your #GAsyncReadyCallback
829  * @error: a pointer to a %NULL #GError, or %NULL
830  *
831  * Collects the result of a previous call to
832  * g_subprocess_wait_async().
833  *
834  * Returns: %TRUE if successful, or %FALSE with @error set
835  *
836  * Since: 2.40
837  */
838 gboolean
839 g_subprocess_wait_finish (GSubprocess   *subprocess,
840                           GAsyncResult  *result,
841                           GError       **error)
842 {
843   return g_task_propagate_boolean (G_TASK (result), error);
844 }
845
846 /* Some generic helpers for emulating synchronous operations using async
847  * operations.
848  */
849 static void
850 g_subprocess_sync_setup (void)
851 {
852   g_main_context_push_thread_default (g_main_context_new ());
853 }
854
855 static void
856 g_subprocess_sync_done (GObject      *source_object,
857                         GAsyncResult *result,
858                         gpointer      user_data)
859 {
860   GAsyncResult **result_ptr = user_data;
861
862   *result_ptr = g_object_ref (result);
863 }
864
865 static void
866 g_subprocess_sync_complete (GAsyncResult **result)
867 {
868   GMainContext *context = g_main_context_get_thread_default ();
869
870   while (!*result)
871     g_main_context_iteration (context, TRUE);
872
873   g_main_context_pop_thread_default (context);
874   g_main_context_unref (context);
875 }
876
877 /**
878  * g_subprocess_wait:
879  * @subprocess: a #GSubprocess
880  * @cancellable: a #GCancellable
881  * @error: a #GError
882  *
883  * Synchronously wait for the subprocess to terminate.
884  *
885  * After the process terminates you can query its exit status with
886  * functions such as g_subprocess_get_if_exited() and
887  * g_subprocess_get_exit_status().
888  *
889  * This function does not fail in the case of the subprocess having
890  * abnormal termination.  See g_subprocess_wait_check() for that.
891  *
892  * Returns: %TRUE on success, %FALSE if @cancellable was cancelled
893  *
894  * Since: 2.40
895  */
896 gboolean
897 g_subprocess_wait (GSubprocess   *subprocess,
898                    GCancellable  *cancellable,
899                    GError       **error)
900 {
901   GAsyncResult *result = NULL;
902   gboolean success;
903
904   g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
905
906   /* Synchronous waits are actually the 'more difficult' case because we
907    * need to deal with the possibility of cancellation.  That more or
908    * less implies that we need a main context (to dispatch either of the
909    * possible reasons for the operation ending).
910    *
911    * So we make one and then do this async...
912    */
913
914   if (g_cancellable_set_error_if_cancelled (cancellable, error))
915     return FALSE;
916
917   /* We can shortcut in the case that the process already quit (but only
918    * after we checked the cancellable).
919    */
920   if (subprocess->pid == 0)
921     return TRUE;
922
923   /* Otherwise, we need to do this the long way... */
924   g_subprocess_sync_setup ();
925   g_subprocess_wait_async (subprocess, cancellable, g_subprocess_sync_done, &result);
926   g_subprocess_sync_complete (&result);
927   success = g_subprocess_wait_finish (subprocess, result, error);
928   g_object_unref (result);
929
930   return success;
931 }
932
933 /**
934  * g_subprocess_wait_check:
935  * @subprocess: a #GSubprocess
936  * @cancellable: a #GCancellable
937  * @error: a #GError
938  *
939  * Combines g_subprocess_wait() with g_spawn_check_exit_status().
940  *
941  * Returns: %TRUE on success, %FALSE if process exited abnormally, or
942  * @cancellable was cancelled
943  *
944  * Since: 2.40
945  */
946 gboolean
947 g_subprocess_wait_check (GSubprocess   *subprocess,
948                          GCancellable  *cancellable,
949                          GError       **error)
950 {
951   return g_subprocess_wait (subprocess, cancellable, error) &&
952          g_spawn_check_exit_status (subprocess->status, error);
953 }
954
955 /**
956  * g_subprocess_wait_check_async:
957  * @subprocess: a #GSubprocess
958  * @cancellable: a #GCancellable, or %NULL
959  * @callback: a #GAsyncReadyCallback to call when the operation is complete
960  * @user_data: user_data for @callback
961  *
962  * Combines g_subprocess_wait_async() with g_spawn_check_exit_status().
963  *
964  * This is the asynchronous version of g_subprocess_wait_check().
965  *
966  * Since: 2.40
967  */
968 void
969 g_subprocess_wait_check_async (GSubprocess         *subprocess,
970                                GCancellable        *cancellable,
971                                GAsyncReadyCallback  callback,
972                                gpointer             user_data)
973 {
974   g_subprocess_wait_async (subprocess, cancellable, callback, user_data);
975 }
976
977 /**
978  * g_subprocess_wait_check_finish:
979  * @subprocess: a #GSubprocess
980  * @result: the #GAsyncResult passed to your #GAsyncReadyCallback
981  * @error: a pointer to a %NULL #GError, or %NULL
982  *
983  * Collects the result of a previous call to
984  * g_subprocess_wait_check_async().
985  *
986  * Returns: %TRUE if successful, or %FALSE with @error set
987  *
988  * Since: 2.40
989  */
990 gboolean
991 g_subprocess_wait_check_finish (GSubprocess   *subprocess,
992                                 GAsyncResult  *result,
993                                 GError       **error)
994 {
995   return g_subprocess_wait_finish (subprocess, result, error) &&
996          g_spawn_check_exit_status (subprocess->status, error);
997 }
998
999 #ifdef G_OS_UNIX
1000 typedef struct
1001 {
1002   GSubprocess *subprocess;
1003   gint signalnum;
1004 } SignalRecord;
1005
1006 static gboolean
1007 g_subprocess_actually_send_signal (gpointer user_data)
1008 {
1009   SignalRecord *signal_record = user_data;
1010
1011   /* The pid is set to zero from the worker thread as well, so we don't
1012    * need to take a lock in order to prevent it from changing under us.
1013    */
1014   if (signal_record->subprocess->pid)
1015     kill (signal_record->subprocess->pid, signal_record->signalnum);
1016
1017   g_object_unref (signal_record->subprocess);
1018
1019   g_slice_free (SignalRecord, signal_record);
1020
1021   return FALSE;
1022 }
1023
1024 static void
1025 g_subprocess_dispatch_signal (GSubprocess *subprocess,
1026                               gint         signalnum)
1027 {
1028   SignalRecord signal_record = { g_object_ref (subprocess), signalnum };
1029
1030   g_return_if_fail (G_IS_SUBPROCESS (subprocess));
1031
1032   /* This MUST be a lower priority than the priority that the child
1033    * watch source uses in initable_init().
1034    *
1035    * Reaping processes, reporting the results back to GSubprocess and
1036    * sending signals is all done in the glib worker thread.  We cannot
1037    * have a kill() done after the reap and before the report without
1038    * risking killing a process that's no longer there so the kill()
1039    * needs to have the lower priority.
1040    *
1041    * G_PRIORITY_HIGH_IDLE is lower priority than G_PRIORITY_DEFAULT.
1042    */
1043   g_main_context_invoke_full (GLIB_PRIVATE_CALL (g_get_worker_context) (),
1044                               G_PRIORITY_HIGH_IDLE,
1045                               g_subprocess_actually_send_signal,
1046                               g_slice_dup (SignalRecord, &signal_record),
1047                               NULL);
1048 }
1049
1050 /**
1051  * g_subprocess_send_signal:
1052  * @subprocess: a #GSubprocess
1053  * @signal_num: the signal number to send
1054  *
1055  * Sends the UNIX signal @signal_num to the subprocess, if it is still
1056  * running.
1057  *
1058  * This API is race-free.  If the subprocess has terminated, it will not
1059  * be signalled.
1060  *
1061  * This API is not available on Windows.
1062  *
1063  * Since: 2.40
1064  **/
1065 void
1066 g_subprocess_send_signal (GSubprocess *subprocess,
1067                           gint         signal_num)
1068 {
1069   g_return_if_fail (G_IS_SUBPROCESS (subprocess));
1070
1071   g_subprocess_dispatch_signal (subprocess, signal_num);
1072 }
1073 #endif
1074
1075 /**
1076  * g_subprocess_force_exit:
1077  * @subprocess: a #GSubprocess
1078  *
1079  * Use an operating-system specific method to attempt an immediate,
1080  * forceful termination of the process.  There is no mechanism to
1081  * determine whether or not the request itself was successful;
1082  * however, you can use g_subprocess_wait() to monitor the status of
1083  * the process after calling this function.
1084  *
1085  * On Unix, this function sends %SIGKILL.
1086  *
1087  * Since: 2.40
1088  **/
1089 void
1090 g_subprocess_force_exit (GSubprocess *subprocess)
1091 {
1092   g_return_if_fail (G_IS_SUBPROCESS (subprocess));
1093
1094 #ifdef G_OS_UNIX
1095   g_subprocess_dispatch_signal (subprocess, SIGKILL);
1096 #else
1097   TerminateProcess (subprocess->pid, 1);
1098 #endif
1099 }
1100
1101 /**
1102  * g_subprocess_get_status:
1103  * @subprocess: a #GSubprocess
1104  *
1105  * Gets the raw status code of the process, as from waitpid().
1106  *
1107  * This value has no particular meaning, but it can be used with the
1108  * macros defined by the system headers such as WIFEXITED.  It can also
1109  * be used with g_spawn_check_exit_status().
1110  *
1111  * It is more likely that you want to use g_subprocess_get_if_exited()
1112  * followed by g_subprocess_get_exit_status().
1113  *
1114  * It is an error to call this function before g_subprocess_wait() has
1115  * returned.
1116  *
1117  * Returns: the (meaningless) waitpid() exit status from the kernel
1118  *
1119  * Since: 2.40
1120  **/
1121 gint
1122 g_subprocess_get_status (GSubprocess *subprocess)
1123 {
1124   g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1125   g_return_val_if_fail (subprocess->pid == 0, FALSE);
1126
1127   return subprocess->status;
1128 }
1129
1130 /**
1131  * g_subprocess_get_successful:
1132  * @subprocess: a #GSubprocess
1133  *
1134  * Checks if the process was "successful".  A process is considered
1135  * successful if it exited cleanly with an exit status of 0, either by
1136  * way of the exit() system call or return from main().
1137  *
1138  * It is an error to call this function before g_subprocess_wait() has
1139  * returned.
1140  *
1141  * Returns: %TRUE if the process exited cleanly with a exit status of 0
1142  *
1143  * Since: 2.40
1144  **/
1145 gboolean
1146 g_subprocess_get_successful (GSubprocess *subprocess)
1147 {
1148   g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1149   g_return_val_if_fail (subprocess->pid == 0, FALSE);
1150
1151 #ifdef G_OS_UNIX
1152   return WIFEXITED (subprocess->status) && WEXITSTATUS (subprocess->status) == 0;
1153 #else
1154   return subprocess->status == 0;
1155 #endif
1156 }
1157
1158 /**
1159  * g_subprocess_get_if_exited:
1160  * @subprocess: a #GSubprocess
1161  *
1162  * Check if the given subprocess exited normally (ie: by way of exit()
1163  * or return from main()).
1164  *
1165  * This is equivalent to the system WIFEXITED macro.
1166  *
1167  * It is an error to call this function before g_subprocess_wait() has
1168  * returned.
1169  *
1170  * Returns: %TRUE if the case of a normal exit
1171  *
1172  * Since: 2.40
1173  **/
1174 gboolean
1175 g_subprocess_get_if_exited (GSubprocess *subprocess)
1176 {
1177   g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1178   g_return_val_if_fail (subprocess->pid == 0, FALSE);
1179
1180 #ifdef G_OS_UNIX
1181   return WIFEXITED (subprocess->status);
1182 #else
1183   return TRUE;
1184 #endif
1185 }
1186
1187 /**
1188  * g_subprocess_get_exit_status:
1189  * @subprocess: a #GSubprocess
1190  *
1191  * Check the exit status of the subprocess, given that it exited
1192  * normally.  This is the value passed to the exit() system call or the
1193  * return value from main.
1194  *
1195  * This is equivalent to the system WEXITSTATUS macro.
1196  *
1197  * It is an error to call this function before g_subprocess_wait() and
1198  * unless g_subprocess_get_if_exited() returned %TRUE.
1199  *
1200  * Returns: the exit status
1201  *
1202  * Since: 2.40
1203  **/
1204 gint
1205 g_subprocess_get_exit_status (GSubprocess *subprocess)
1206 {
1207   g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), 1);
1208   g_return_val_if_fail (subprocess->pid == 0, 1);
1209
1210 #ifdef G_OS_UNIX
1211   g_return_val_if_fail (WIFEXITED (subprocess->status), 1);
1212
1213   return WEXITSTATUS (subprocess->status);
1214 #else
1215   return subprocess->status;
1216 #endif
1217 }
1218
1219 /**
1220  * g_subprocess_get_if_signaled:
1221  * @subprocess: a #GSubprocess
1222  *
1223  * Check if the given subprocess terminated in response to a signal.
1224  *
1225  * This is equivalent to the system WIFSIGNALED macro.
1226  *
1227  * It is an error to call this function before g_subprocess_wait() has
1228  * returned.
1229  *
1230  * Returns: %TRUE if the case of termination due to a signal
1231  *
1232  * Since: 2.40
1233  **/
1234 gboolean
1235 g_subprocess_get_if_signaled (GSubprocess *subprocess)
1236 {
1237   g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1238   g_return_val_if_fail (subprocess->pid == 0, FALSE);
1239
1240 #ifdef G_OS_UNIX
1241   return WIFSIGNALED (subprocess->status);
1242 #else
1243   return FALSE;
1244 #endif
1245 }
1246
1247 /**
1248  * g_subprocess_get_term_sig:
1249  * @subprocess: a #GSubprocess
1250  *
1251  * Get the signal number that caused the subprocess to terminate, given
1252  * that it terminated due to a signal.
1253  *
1254  * This is equivalent to the system WTERMSIG macro.
1255  *
1256  * It is an error to call this function before g_subprocess_wait() and
1257  * unless g_subprocess_get_if_signaled() returned %TRUE.
1258  *
1259  * Returns: the signal causing termination
1260  *
1261  * Since: 2.40
1262  **/
1263 gint
1264 g_subprocess_get_term_sig (GSubprocess *subprocess)
1265 {
1266   g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), 0);
1267   g_return_val_if_fail (subprocess->pid == 0, 0);
1268
1269 #ifdef G_OS_UNIX
1270   g_return_val_if_fail (WIFSIGNALED (subprocess->status), 0);
1271
1272   return WTERMSIG (subprocess->status);
1273 #else
1274   g_critical ("g_subprocess_get_term_sig() called on Windows, where "
1275               "g_subprocess_get_if_signaled() always returns FALSE...");
1276   return 0;
1277 #endif
1278 }
1279
1280 /*< private >*/
1281 void
1282 g_subprocess_set_launcher (GSubprocess         *subprocess,
1283                            GSubprocessLauncher *launcher)
1284 {
1285   subprocess->launcher = launcher;
1286 }
1287
1288
1289 /* g_subprocess_communicate implementation below:
1290  *
1291  * This is a tough problem.  We have to watch 5 things at the same time:
1292  *
1293  *  - writing to stdin made progress
1294  *  - reading from stdout made progress
1295  *  - reading from stderr made progress
1296  *  - process terminated
1297  *  - cancellable being cancelled by caller
1298  *
1299  * We use a GMainContext for all of these (either as async function
1300  * calls or as a GSource (in the case of the cancellable).  That way at
1301  * least we don't have to worry about threading.
1302  *
1303  * For the sync case we use the usual trick of creating a private main
1304  * context and iterating it until completion.
1305  *
1306  * It's very possible that the process will dump a lot of data to stdout
1307  * just before it quits, so we can easily have data to read from stdout
1308  * and see the process has terminated at the same time.  We want to make
1309  * sure that we read all of the data from the pipes first, though, so we
1310  * do IO operations at a higher priority than the wait operation (which
1311  * is at G_IO_PRIORITY_DEFAULT).  Even in the case that we have to do
1312  * multiple reads to get this data, the pipe() will always be polling
1313  * as ready and with the async result for the read at a higher priority,
1314  * the main context will not dispatch the completion for the wait().
1315  *
1316  * We keep our own private GCancellable.  In the event that any of the
1317  * above suffers from an error condition (including the user cancelling
1318  * their cancellable) we immediately dispatch the GTask with the error
1319  * result and fire our cancellable to cleanup any pending operations.
1320  * In the case that the error is that the user's cancellable was fired,
1321  * it's vaguely wasteful to report an error because GTask will handle
1322  * this automatically, so we just return FALSE.
1323  *
1324  * We let each pending sub-operation take a ref on the GTask of the
1325  * communicate operation.  We have to be careful that we don't report
1326  * the task completion more than once, though, so we keep a flag for
1327  * that.
1328  */
1329 typedef struct
1330 {
1331   const gchar *stdin_data;
1332   gsize stdin_length;
1333   gsize stdin_offset;
1334
1335   gboolean add_nul;
1336
1337   GInputStream *stdin_buf;
1338   GMemoryOutputStream *stdout_buf;
1339   GMemoryOutputStream *stderr_buf;
1340
1341   GCancellable *cancellable;
1342   GSource      *cancellable_source;
1343
1344   guint         outstanding_ops;
1345   gboolean      reported_error;
1346 } CommunicateState;
1347
1348 static void
1349 g_subprocess_communicate_made_progress (GObject      *source_object,
1350                                         GAsyncResult *result,
1351                                         gpointer      user_data)
1352 {
1353   CommunicateState *state;
1354   GSubprocess *subprocess;
1355   GError *error = NULL;
1356   gpointer source;
1357   GTask *task;
1358
1359   g_assert (source_object != NULL);
1360
1361   task = user_data;
1362   subprocess = g_task_get_source_object (task);
1363   state = g_task_get_task_data (task);
1364   source = source_object;
1365
1366   state->outstanding_ops--;
1367
1368   if (source == subprocess->stdin_pipe ||
1369       source == state->stdout_buf ||
1370       source == state->stderr_buf)
1371     {
1372       if (!g_output_stream_splice_finish ((GOutputStream*)source, result, &error))
1373         goto out;
1374
1375       if (source == state->stdout_buf ||
1376           source == state->stderr_buf)
1377         {
1378           /* This is a memory stream, so it can't be cancelled or return
1379            * an error really.
1380            */
1381           if (state->add_nul)
1382             {
1383               gsize bytes_written;
1384               if (!g_output_stream_write_all (source, "\0", 1, &bytes_written,
1385                                               NULL, &error))
1386                 goto out;
1387             }
1388           if (!g_output_stream_close (source, NULL, &error))
1389             goto out;
1390         }
1391     }
1392   else if (source == subprocess)
1393     {
1394       (void) g_subprocess_wait_finish (subprocess, result, &error);
1395     }
1396   else
1397     g_assert_not_reached ();
1398
1399  out:
1400   if (error)
1401     {
1402       /* Only report the first error we see.
1403        *
1404        * We might be seeing an error as a result of the cancellation
1405        * done when the process quits.
1406        */
1407       if (!state->reported_error)
1408         {
1409           state->reported_error = TRUE;
1410           g_cancellable_cancel (state->cancellable);
1411           g_task_return_error (task, error);
1412         }
1413       else
1414         g_error_free (error);
1415     }
1416   else if (state->outstanding_ops == 0)
1417     {
1418       g_task_return_boolean (task, TRUE);
1419     }
1420
1421   /* And drop the original ref */
1422   g_object_unref (task);
1423 }
1424
1425 static gboolean
1426 g_subprocess_communicate_cancelled (gpointer user_data)
1427 {
1428   CommunicateState *state = user_data;
1429
1430   g_cancellable_cancel (state->cancellable);
1431
1432   return FALSE;
1433 }
1434
1435 static void
1436 g_subprocess_communicate_state_free (gpointer data)
1437 {
1438   CommunicateState *state = data;
1439
1440   g_clear_object (&state->stdin_buf);
1441   g_clear_object (&state->stdout_buf);
1442   g_clear_object (&state->stderr_buf);
1443
1444   if (!g_source_is_destroyed (state->cancellable_source))
1445     g_source_destroy (state->cancellable_source);
1446   g_source_unref (state->cancellable_source);
1447
1448   g_slice_free (CommunicateState, state);
1449 }
1450
1451 static CommunicateState *
1452 g_subprocess_communicate_internal (GSubprocess         *subprocess,
1453                                    gboolean             add_nul,
1454                                    GBytes              *stdin_buf,
1455                                    GCancellable        *cancellable,
1456                                    GAsyncReadyCallback  callback,
1457                                    gpointer             user_data)
1458 {
1459   CommunicateState *state;
1460   GTask *task;
1461
1462   task = g_task_new (subprocess, cancellable, callback, user_data);
1463   state = g_slice_new0 (CommunicateState);
1464   g_task_set_task_data (task, state, g_subprocess_communicate_state_free);
1465
1466   state->cancellable = g_cancellable_new ();
1467   state->add_nul = add_nul;
1468
1469   if (cancellable)
1470     {
1471       state->cancellable_source = g_cancellable_source_new (cancellable);
1472       /* No ref held here, but we unref the source from state's free function */
1473       g_source_set_callback (state->cancellable_source, g_subprocess_communicate_cancelled, state, NULL);
1474       g_source_attach (state->cancellable_source, g_main_context_get_thread_default ());
1475     }
1476
1477   if (subprocess->stdin_pipe)
1478     {
1479       g_assert (stdin_buf != NULL);
1480       state->stdin_buf = g_memory_input_stream_new_from_bytes (stdin_buf);
1481       g_output_stream_splice_async (subprocess->stdin_pipe, (GInputStream*)state->stdin_buf,
1482                                     G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE | G_OUTPUT_STREAM_SPLICE_CLOSE_TARGET,
1483                                     G_PRIORITY_DEFAULT, state->cancellable,
1484                                     g_subprocess_communicate_made_progress, g_object_ref (task));
1485       state->outstanding_ops++;
1486     }
1487
1488   if (subprocess->stdout_pipe)
1489     {
1490       state->stdout_buf = (GMemoryOutputStream*)g_memory_output_stream_new_resizable ();
1491       g_output_stream_splice_async ((GOutputStream*)state->stdout_buf, subprocess->stdout_pipe,
1492                                     G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE,
1493                                     G_PRIORITY_DEFAULT, state->cancellable,
1494                                     g_subprocess_communicate_made_progress, g_object_ref (task));
1495       state->outstanding_ops++;
1496     }
1497
1498   if (subprocess->stderr_pipe)
1499     {
1500       state->stderr_buf = (GMemoryOutputStream*)g_memory_output_stream_new_resizable ();
1501       g_output_stream_splice_async ((GOutputStream*)state->stderr_buf, subprocess->stderr_pipe,
1502                                     G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE,
1503                                     G_PRIORITY_DEFAULT, state->cancellable,
1504                                     g_subprocess_communicate_made_progress, g_object_ref (task));
1505       state->outstanding_ops++;
1506     }
1507
1508   g_subprocess_wait_async (subprocess, state->cancellable,
1509                            g_subprocess_communicate_made_progress, g_object_ref (task));
1510   state->outstanding_ops++;
1511
1512   return state;
1513 }
1514
1515 /**
1516  * g_subprocess_communicate:
1517  * @subprocess: a #GSubprocess
1518  * @stdin_buf: data to send to the stdin of the subprocess, or %NULL
1519  * @cancellable: a #GCancellable
1520  * @stdout_buf: (out): data read from the subprocess stdout
1521  * @stderr_buf: (out): data read from the subprocess stderr
1522  * @error: a pointer to a %NULL #GError pointer, or %NULL
1523  *
1524  * Communicate with the subprocess until it terminates, and all input
1525  * and output has been completed.
1526  *
1527  * If @stdin is given, the subprocess must have been created with
1528  * %G_SUBPROCESS_FLAGS_STDIN_PIPE.  The given data is fed to the
1529  * stdin of the subprocess and the pipe is closed (ie: EOF).
1530  *
1531  * At the same time (as not to cause blocking when dealing with large
1532  * amounts of data), if %G_SUBPROCESS_FLAGS_STDOUT_PIPE or
1533  * %G_SUBPROCESS_FLAGS_STDERR_PIPE were used, reads from those
1534  * streams.  The data that was read is returned in @stdout and/or
1535  * the @stderr.
1536  *
1537  * If the subprocess was created with %G_SUBPROCESS_FLAGS_STDOUT_PIPE,
1538  * @stdout_buf will contain the data read from stdout.  Otherwise, for
1539  * subprocesses not created with %G_SUBPROCESS_FLAGS_STDOUT_PIPE,
1540  * @stdout_buf will be set to %NULL.  Similar provisions apply to
1541  * @stderr_buf and %G_SUBPROCESS_FLAGS_STDERR_PIPE.
1542  *
1543  * As usual, any output variable may be given as %NULL to ignore it.
1544  *
1545  * If you desire the stdout and stderr data to be interleaved, create
1546  * the subprocess with %G_SUBPROCESS_FLAGS_STDOUT_PIPE and
1547  * %G_SUBPROCESS_FLAGS_STDERR_MERGE.  The merged result will be returned
1548  * in @stdout_buf and @stderr_buf will be set to %NULL.
1549  *
1550  * In case of any error (including cancellation), %FALSE will be
1551  * returned with @error set.  Some or all of the stdin data may have
1552  * been written.  Any stdout or stderr data that has been read will be
1553  * discarded. None of the out variables (aside from @error) will have
1554  * been set to anything in particular and should not be inspected.
1555  *
1556  * In the case that %TRUE is returned, the subprocess has exited and the
1557  * exit status inspection APIs (eg: g_subprocess_get_if_exited(),
1558  * g_subprocess_get_exit_status()) may be used.
1559  *
1560  * You should not attempt to use any of the subprocess pipes after
1561  * starting this function, since they may be left in strange states,
1562  * even if the operation was cancelled.  You should especially not
1563  * attempt to interact with the pipes while the operation is in progress
1564  * (either from another thread or if using the asynchronous version).
1565  *
1566  * Returns: %TRUE if successful
1567  *
1568  * Since: 2.40
1569  **/
1570 gboolean
1571 g_subprocess_communicate (GSubprocess   *subprocess,
1572                           GBytes        *stdin_buf,
1573                           GCancellable  *cancellable,
1574                           GBytes       **stdout_buf,
1575                           GBytes       **stderr_buf,
1576                           GError       **error)
1577 {
1578   GAsyncResult *result = NULL;
1579   gboolean success;
1580
1581   g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1582   g_return_val_if_fail (stdin_buf == NULL || (subprocess->flags & G_SUBPROCESS_FLAGS_STDIN_PIPE), FALSE);
1583   g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE);
1584   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1585
1586   g_subprocess_sync_setup ();
1587   g_subprocess_communicate_internal (subprocess, FALSE, stdin_buf, cancellable,
1588                                      g_subprocess_sync_done, &result);
1589   g_subprocess_sync_complete (&result);
1590   success = g_subprocess_communicate_finish (subprocess, result, stdout_buf, stderr_buf, error);
1591   g_object_unref (result);
1592
1593   return success;
1594 }
1595
1596 /**
1597  * g_subprocess_communicate_async:
1598  * @subprocess: Self
1599  * @stdin_buf: Input data
1600  * @cancellable: Cancellable
1601  * @callback: Callback
1602  * @user_data: User data
1603  *
1604  * Asynchronous version of g_subprocess_communicate().  Complete
1605  * invocation with g_subprocess_communicate_finish().
1606  */
1607 void
1608 g_subprocess_communicate_async (GSubprocess         *subprocess,
1609                                 GBytes              *stdin_buf,
1610                                 GCancellable        *cancellable,
1611                                 GAsyncReadyCallback  callback,
1612                                 gpointer             user_data)
1613 {
1614   g_return_if_fail (G_IS_SUBPROCESS (subprocess));
1615   g_return_if_fail (stdin_buf == NULL || (subprocess->flags & G_SUBPROCESS_FLAGS_STDIN_PIPE));
1616   g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));
1617
1618   g_subprocess_communicate_internal (subprocess, FALSE, stdin_buf, cancellable, callback, user_data);
1619 }
1620
1621 /**
1622  * g_subprocess_communicate_finish:
1623  * @subprocess: Self
1624  * @result: Result
1625  * @stdout_buf: (out): Return location for stdout data
1626  * @stderr_buf: (out): Return location for stderr data
1627  * @error: Error
1628  *
1629  * Complete an invocation of g_subprocess_communicate_async().
1630  */
1631 gboolean
1632 g_subprocess_communicate_finish (GSubprocess   *subprocess,
1633                                  GAsyncResult  *result,
1634                                  GBytes       **stdout_buf,
1635                                  GBytes       **stderr_buf,
1636                                  GError       **error)
1637 {
1638   gboolean success;
1639   CommunicateState *state;
1640
1641   g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1642   g_return_val_if_fail (g_task_is_valid (result, subprocess), FALSE);
1643   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1644
1645   g_object_ref (result);
1646
1647   state = g_task_get_task_data ((GTask*)result);
1648   success = g_task_propagate_boolean ((GTask*)result, error);
1649
1650   if (success)
1651     {
1652       if (stdout_buf)
1653         *stdout_buf = g_memory_output_stream_steal_as_bytes (state->stdout_buf);
1654       if (stderr_buf)
1655         *stderr_buf = g_memory_output_stream_steal_as_bytes (state->stderr_buf);
1656     }
1657
1658   g_object_unref (result);
1659   return success;
1660 }
1661
1662 /**
1663  * g_subprocess_communicate_utf8:
1664  * @subprocess: a #GSubprocess
1665  * @stdin_buf: data to send to the stdin of the subprocess, or %NULL
1666  * @cancellable: a #GCancellable
1667  * @stdout_buf: (out): data read from the subprocess stdout
1668  * @stderr_buf: (out): data read from the subprocess stderr
1669  * @error: a pointer to a %NULL #GError pointer, or %NULL
1670  *
1671  * Like g_subprocess_communicate(), but validates the output of the
1672  * process as UTF-8, and returns it as a regular NUL terminated string.
1673  */
1674 gboolean
1675 g_subprocess_communicate_utf8 (GSubprocess   *subprocess,
1676                                const char    *stdin_buf,
1677                                GCancellable  *cancellable,
1678                                char         **stdout_buf,
1679                                char         **stderr_buf,
1680                                GError       **error)
1681 {
1682   GAsyncResult *result = NULL;
1683   gboolean success;
1684   GBytes *stdin_bytes;
1685
1686   g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1687   g_return_val_if_fail (stdin_buf == NULL || (subprocess->flags & G_SUBPROCESS_FLAGS_STDIN_PIPE), FALSE);
1688   g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE);
1689   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1690
1691   stdin_bytes = g_bytes_new (stdin_buf, strlen (stdin_buf));
1692
1693   g_subprocess_sync_setup ();
1694   g_subprocess_communicate_internal (subprocess, TRUE, stdin_bytes, cancellable,
1695                                      g_subprocess_sync_done, &result);
1696   g_subprocess_sync_complete (&result);
1697   success = g_subprocess_communicate_utf8_finish (subprocess, result, stdout_buf, stderr_buf, error);
1698   g_object_unref (result);
1699
1700   g_bytes_unref (stdin_bytes);
1701   return success;
1702 }
1703
1704 /**
1705  * g_subprocess_communicate_utf8_async:
1706  * @subprocess: Self
1707  * @stdin_buf: Input data
1708  * @cancellable: Cancellable
1709  * @callback: Callback
1710  * @user_data: User data
1711  *
1712  * Asynchronous version of g_subprocess_communicate_utf().  Complete
1713  * invocation with g_subprocess_communicate_utf8_finish().
1714  */
1715 void
1716 g_subprocess_communicate_utf8_async (GSubprocess         *subprocess,
1717                                      const char          *stdin_buf,
1718                                      GCancellable        *cancellable,
1719                                      GAsyncReadyCallback  callback,
1720                                      gpointer             user_data)
1721 {
1722   GBytes *stdin_bytes;
1723
1724   g_return_if_fail (G_IS_SUBPROCESS (subprocess));
1725   g_return_if_fail (stdin_buf == NULL || (subprocess->flags & G_SUBPROCESS_FLAGS_STDIN_PIPE));
1726   g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));
1727
1728   stdin_bytes = g_bytes_new (stdin_buf, strlen (stdin_buf));
1729   g_subprocess_communicate_internal (subprocess, TRUE, stdin_bytes, cancellable, callback, user_data);
1730   g_bytes_unref (stdin_bytes);
1731 }
1732
1733 static gboolean
1734 communicate_result_validate_utf8 (const char            *stream_name,
1735                                   char                 **return_location,
1736                                   GMemoryOutputStream   *buffer,
1737                                   GError               **error)
1738 {
1739   if (return_location == NULL)
1740     return TRUE;
1741
1742   if (buffer)
1743     {
1744       const char *end;
1745       *return_location = g_memory_output_stream_steal_data (buffer);
1746       if (!g_utf8_validate (*return_location, -1, &end))
1747         {
1748           g_free (*return_location);
1749           g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
1750                        "Invalid UTF-8 in child %s at offset %lu",
1751                        stream_name,
1752                        (unsigned long) (end - *return_location));
1753           return FALSE;
1754         }
1755     }
1756   else
1757     *return_location = NULL;
1758
1759   return TRUE;
1760 }
1761
1762 /**
1763  * g_subprocess_communicate_utf8_finish:
1764  * @subprocess: Self
1765  * @result: Result
1766  * @stdout_buf: (out): Return location for stdout data
1767  * @stderr_buf: (out): Return location for stderr data
1768  * @error: Error
1769  *
1770  * Complete an invocation of g_subprocess_communicate_utf8_async().
1771  */
1772 gboolean
1773 g_subprocess_communicate_utf8_finish (GSubprocess   *subprocess,
1774                                       GAsyncResult  *result,
1775                                       char         **stdout_buf,
1776                                       char         **stderr_buf,
1777                                       GError       **error)
1778 {
1779   gboolean ret = FALSE;
1780   CommunicateState *state;
1781
1782   g_return_val_if_fail (G_IS_SUBPROCESS (subprocess), FALSE);
1783   g_return_val_if_fail (g_task_is_valid (result, subprocess), FALSE);
1784   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1785
1786   g_object_ref (result);
1787
1788   state = g_task_get_task_data ((GTask*)result);
1789   if (!g_task_propagate_boolean ((GTask*)result, error))
1790     goto out;
1791
1792   /* TODO - validate UTF-8 while streaming, rather than all at once.
1793    */
1794   if (!communicate_result_validate_utf8 ("stdout", stdout_buf,
1795                                          state->stdout_buf,
1796                                          error))
1797     goto out;
1798   if (!communicate_result_validate_utf8 ("stderr", stderr_buf,
1799                                          state->stderr_buf,
1800                                          error))
1801     goto out;
1802
1803   ret = TRUE;
1804  out:
1805   g_object_unref (result);
1806   return ret;
1807 }