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