Coverage Report

Created: 2025-07-01 07:09

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