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