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