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