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