Coverage Report

Created: 2026-01-17 07:10

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/irssi/subprojects/glib-2.74.3/glib/gspawn.c
Line
Count
Source
1
/* gspawn.c - Process launching
2
 *
3
 *  Copyright 2000 Red Hat, Inc.
4
 *  g_execvpe implementation based on GNU libc execvp:
5
 *   Copyright 1991, 92, 95, 96, 97, 98, 99 Free Software Foundation, Inc.
6
 *
7
 * SPDX-License-Identifier: LGPL-2.1-or-later
8
 *
9
 * This library is free software; you can redistribute it and/or
10
 * modify it under the terms of the GNU Lesser General Public
11
 * License as published by the Free Software Foundation; either
12
 * version 2.1 of the License, or (at your option) any later version.
13
 *
14
 * This library is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17
 * Lesser General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU Lesser General Public License
20
 * along with this library; if not, see <http://www.gnu.org/licenses/>.
21
 */
22
23
#include "config.h"
24
25
#include <sys/time.h>
26
#include <sys/types.h>
27
#include <sys/wait.h>
28
#include <unistd.h>
29
#include <errno.h>
30
#include <fcntl.h>
31
#include <signal.h>
32
#include <string.h>
33
#include <stdlib.h>   /* for fdwalk */
34
#include <dirent.h>
35
36
#ifdef HAVE_SPAWN_H
37
#include <spawn.h>
38
#endif /* HAVE_SPAWN_H */
39
40
#ifdef HAVE_CRT_EXTERNS_H
41
#include <crt_externs.h> /* for _NSGetEnviron */
42
#endif
43
44
#ifdef HAVE_SYS_SELECT_H
45
#include <sys/select.h>
46
#endif /* HAVE_SYS_SELECT_H */
47
48
#ifdef HAVE_SYS_RESOURCE_H
49
#include <sys/resource.h>
50
#endif /* HAVE_SYS_RESOURCE_H */
51
52
#if defined(__linux__) || defined(__DragonFly__)
53
#include <sys/syscall.h>  /* for syscall and SYS_getdents64 */
54
#endif
55
56
#include "gspawn.h"
57
#include "gspawn-private.h"
58
#include "gthread.h"
59
#include "gtrace-private.h"
60
#include "glib/gstdio.h"
61
62
#include "genviron.h"
63
#include "gmem.h"
64
#include "gshell.h"
65
#include "gstring.h"
66
#include "gstrfuncs.h"
67
#include "gtestutils.h"
68
#include "gutils.h"
69
#include "glibintl.h"
70
#include "glib-unix.h"
71
72
0
#define INHERITS_OR_NULL_STDIN  (G_SPAWN_STDIN_FROM_DEV_NULL | G_SPAWN_CHILD_INHERITS_STDIN)
73
0
#define INHERITS_OR_NULL_STDOUT (G_SPAWN_STDOUT_TO_DEV_NULL | G_SPAWN_CHILD_INHERITS_STDOUT)
74
0
#define INHERITS_OR_NULL_STDERR (G_SPAWN_STDERR_TO_DEV_NULL | G_SPAWN_CHILD_INHERITS_STDERR)
75
76
/* posix_spawn() is assumed the fastest way to spawn, but glibc's
77
 * implementation was buggy before glibc 2.24, so avoid it on old versions.
78
 */
79
#ifdef HAVE_POSIX_SPAWN
80
#ifdef __GLIBC__
81
82
#if __GLIBC_PREREQ(2,24)
83
#define POSIX_SPAWN_AVAILABLE
84
#endif
85
86
#else /* !__GLIBC__ */
87
/* Assume that all non-glibc posix_spawn implementations are fine. */
88
#define POSIX_SPAWN_AVAILABLE
89
#endif /* __GLIBC__ */
90
#endif /* HAVE_POSIX_SPAWN */
91
92
#ifdef HAVE__NSGETENVIRON
93
#define environ (*_NSGetEnviron())
94
#else
95
extern char **environ;
96
#endif
97
98
#ifndef O_CLOEXEC
99
#define O_CLOEXEC 0
100
#else
101
#define HAVE_O_CLOEXEC 1
102
#endif
103
104
/**
105
 * SECTION:spawn
106
 * @Short_description: process launching
107
 * @Title: Spawning Processes
108
 *
109
 * GLib supports spawning of processes with an API that is more
110
 * convenient than the bare UNIX fork() and exec().
111
 *
112
 * The g_spawn family of functions has synchronous (g_spawn_sync())
113
 * and asynchronous variants (g_spawn_async(), g_spawn_async_with_pipes()),
114
 * as well as convenience variants that take a complete shell-like
115
 * commandline (g_spawn_command_line_sync(), g_spawn_command_line_async()).
116
 *
117
 * See #GSubprocess in GIO for a higher-level API that provides
118
 * stream interfaces for communication with child processes.
119
 *
120
 * An example of using g_spawn_async_with_pipes():
121
 * |[<!-- language="C" -->
122
 * const gchar * const argv[] = { "my-favourite-program", "--args", NULL };
123
 * gint child_stdout, child_stderr;
124
 * GPid child_pid;
125
 * g_autoptr(GError) error = NULL;
126
 *
127
 * // Spawn child process.
128
 * g_spawn_async_with_pipes (NULL, argv, NULL, G_SPAWN_DO_NOT_REAP_CHILD, NULL,
129
 *                           NULL, &child_pid, NULL, &child_stdout,
130
 *                           &child_stderr, &error);
131
 * if (error != NULL)
132
 *   {
133
 *     g_error ("Spawning child failed: %s", error->message);
134
 *     return;
135
 *   }
136
 *
137
 * // Add a child watch function which will be called when the child process
138
 * // exits.
139
 * g_child_watch_add (child_pid, child_watch_cb, NULL);
140
 *
141
 * // You could watch for output on @child_stdout and @child_stderr using
142
 * // #GUnixInputStream or #GIOChannel here.
143
 *
144
 * static void
145
 * child_watch_cb (GPid     pid,
146
 *                 gint     status,
147
 *                 gpointer user_data)
148
 * {
149
 *   g_message ("Child %" G_PID_FORMAT " exited %s", pid,
150
 *              g_spawn_check_wait_status (status, NULL) ? "normally" : "abnormally");
151
 *
152
 *   // Free any resources associated with the child here, such as I/O channels
153
 *   // on its stdout and stderr FDs. If you have no code to put in the
154
 *   // child_watch_cb() callback, you can remove it and the g_child_watch_add()
155
 *   // call, but you must also remove the G_SPAWN_DO_NOT_REAP_CHILD flag,
156
 *   // otherwise the child process will stay around as a zombie until this
157
 *   // process exits.
158
 *
159
 *   g_spawn_close_pid (pid);
160
 * }
161
 * ]|
162
 */
163
164
165
static gint g_execute (const gchar  *file,
166
                       gchar       **argv,
167
                       gchar       **argv_buffer,
168
                       gsize         argv_buffer_len,
169
                       gchar       **envp,
170
                       const gchar  *search_path,
171
                       gchar        *search_path_buffer,
172
                       gsize         search_path_buffer_len);
173
174
static gboolean fork_exec (gboolean              intermediate_child,
175
                           const gchar          *working_directory,
176
                           const gchar * const  *argv,
177
                           const gchar * const  *envp,
178
                           gboolean              close_descriptors,
179
                           gboolean              search_path,
180
                           gboolean              search_path_from_envp,
181
                           gboolean              stdout_to_null,
182
                           gboolean              stderr_to_null,
183
                           gboolean              child_inherits_stdin,
184
                           gboolean              file_and_argv_zero,
185
                           gboolean              cloexec_pipes,
186
                           GSpawnChildSetupFunc  child_setup,
187
                           gpointer              user_data,
188
                           GPid                 *child_pid,
189
                           gint                 *stdin_pipe_out,
190
                           gint                 *stdout_pipe_out,
191
                           gint                 *stderr_pipe_out,
192
                           gint                  stdin_fd,
193
                           gint                  stdout_fd,
194
                           gint                  stderr_fd,
195
                           const gint           *source_fds,
196
                           const gint           *target_fds,
197
                           gsize                 n_fds,
198
                           GError              **error);
199
200
G_DEFINE_QUARK (g-exec-error-quark, g_spawn_error)
201
G_DEFINE_QUARK (g-spawn-exit-error-quark, g_spawn_exit_error)
202
203
/**
204
 * g_spawn_async:
205
 * @working_directory: (type filename) (nullable): child's current working
206
 *     directory, or %NULL to inherit parent's
207
 * @argv: (array zero-terminated=1) (element-type filename):
208
 *     child's argument vector
209
 * @envp: (array zero-terminated=1) (element-type filename) (nullable):
210
 *     child's environment, or %NULL to inherit parent's
211
 * @flags: flags from #GSpawnFlags
212
 * @child_setup: (scope async) (nullable): function to run in the child just before exec()
213
 * @user_data: (closure): user data for @child_setup
214
 * @child_pid: (out) (optional): return location for child process reference, or %NULL
215
 * @error: return location for error
216
 *
217
 * Executes a child program asynchronously.
218
 * 
219
 * See g_spawn_async_with_pipes() for a full description; this function
220
 * simply calls the g_spawn_async_with_pipes() without any pipes.
221
 *
222
 * You should call g_spawn_close_pid() on the returned child process
223
 * reference when you don't need it any more.
224
 * 
225
 * If you are writing a GTK application, and the program you are spawning is a
226
 * graphical application too, then to ensure that the spawned program opens its
227
 * windows on the right screen, you may want to use #GdkAppLaunchContext,
228
 * #GAppLaunchContext, or set the %DISPLAY environment variable.
229
 *
230
 * Note that the returned @child_pid on Windows is a handle to the child
231
 * process and not its identifier. Process handles and process identifiers
232
 * are different concepts on Windows.
233
 *
234
 * Returns: %TRUE on success, %FALSE if error is set
235
 **/
236
gboolean
237
g_spawn_async (const gchar          *working_directory,
238
               gchar               **argv,
239
               gchar               **envp,
240
               GSpawnFlags           flags,
241
               GSpawnChildSetupFunc  child_setup,
242
               gpointer              user_data,
243
               GPid                 *child_pid,
244
               GError              **error)
245
0
{
246
0
  return g_spawn_async_with_pipes (working_directory,
247
0
                                   argv, envp,
248
0
                                   flags,
249
0
                                   child_setup,
250
0
                                   user_data,
251
0
                                   child_pid,
252
0
                                   NULL, NULL, NULL,
253
0
                                   error);
254
0
}
255
256
/* Avoids a danger in threaded situations (calling close()
257
 * on a file descriptor twice, and another thread has
258
 * re-opened it since the first close)
259
 *
260
 * This function is called between fork() and exec() and hence must be
261
 * async-signal-safe (see signal-safety(7)).
262
 */
263
static void
264
close_and_invalidate (gint *fd)
265
0
{
266
0
  if (*fd < 0)
267
0
    return;
268
269
0
  g_close (*fd, NULL);
270
0
  *fd = -1;
271
0
}
272
273
/* Some versions of OS X define READ_OK in public headers */
274
#undef READ_OK
275
276
typedef enum
277
{
278
  READ_FAILED = 0, /* FALSE */
279
  READ_OK,
280
  READ_EOF
281
} ReadResult;
282
283
static ReadResult
284
read_data (GString *str,
285
           gint     fd,
286
           GError **error)
287
0
{
288
0
  gssize bytes;
289
0
  gchar buf[4096];
290
291
0
 again:
292
0
  bytes = read (fd, buf, 4096);
293
294
0
  if (bytes == 0)
295
0
    return READ_EOF;
296
0
  else if (bytes > 0)
297
0
    {
298
0
      g_string_append_len (str, buf, bytes);
299
0
      return READ_OK;
300
0
    }
301
0
  else if (errno == EINTR)
302
0
    goto again;
303
0
  else
304
0
    {
305
0
      int errsv = errno;
306
307
0
      g_set_error (error,
308
0
                   G_SPAWN_ERROR,
309
0
                   G_SPAWN_ERROR_READ,
310
0
                   _("Failed to read data from child process (%s)"),
311
0
                   g_strerror (errsv));
312
313
0
      return READ_FAILED;
314
0
    }
315
0
}
316
317
/**
318
 * g_spawn_sync:
319
 * @working_directory: (type filename) (nullable): child's current working
320
 *     directory, or %NULL to inherit parent's
321
 * @argv: (array zero-terminated=1) (element-type filename):
322
 *     child's argument vector, which must be non-empty and %NULL-terminated
323
 * @envp: (array zero-terminated=1) (element-type filename) (nullable):
324
 *     child's environment, or %NULL to inherit parent's
325
 * @flags: flags from #GSpawnFlags
326
 * @child_setup: (scope async) (nullable): function to run in the child just before exec()
327
 * @user_data: (closure): user data for @child_setup
328
 * @standard_output: (out) (array zero-terminated=1) (element-type guint8) (optional): return location for child output, or %NULL
329
 * @standard_error: (out) (array zero-terminated=1) (element-type guint8) (optional): return location for child error messages, or %NULL
330
 * @wait_status: (out) (optional): return location for child wait status, as returned by waitpid(), or %NULL
331
 * @error: return location for error, or %NULL
332
 *
333
 * Executes a child synchronously (waits for the child to exit before returning).
334
 *
335
 * All output from the child is stored in @standard_output and @standard_error,
336
 * if those parameters are non-%NULL. Note that you must set the  
337
 * %G_SPAWN_STDOUT_TO_DEV_NULL and %G_SPAWN_STDERR_TO_DEV_NULL flags when
338
 * passing %NULL for @standard_output and @standard_error.
339
 *
340
 * If @wait_status is non-%NULL, the platform-specific status of
341
 * the child is stored there; see the documentation of
342
 * g_spawn_check_wait_status() for how to use and interpret this.
343
 * On Unix platforms, note that it is usually not equal
344
 * to the integer passed to `exit()` or returned from `main()`.
345
 *
346
 * Note that it is invalid to pass %G_SPAWN_DO_NOT_REAP_CHILD in
347
 * @flags, and on POSIX platforms, the same restrictions as for
348
 * g_child_watch_source_new() apply.
349
 *
350
 * If an error occurs, no data is returned in @standard_output,
351
 * @standard_error, or @wait_status.
352
 *
353
 * This function calls g_spawn_async_with_pipes() internally; see that
354
 * function for full details on the other parameters and details on
355
 * how these functions work on Windows.
356
 * 
357
 * Returns: %TRUE on success, %FALSE if an error was set
358
 */
359
gboolean
360
g_spawn_sync (const gchar          *working_directory,
361
              gchar               **argv,
362
              gchar               **envp,
363
              GSpawnFlags           flags,
364
              GSpawnChildSetupFunc  child_setup,
365
              gpointer              user_data,
366
              gchar               **standard_output,
367
              gchar               **standard_error,
368
              gint                 *wait_status,
369
              GError              **error)     
370
0
{
371
0
  gint outpipe = -1;
372
0
  gint errpipe = -1;
373
0
  GPid pid;
374
0
  gint ret;
375
0
  GString *outstr = NULL;
376
0
  GString *errstr = NULL;
377
0
  gboolean failed;
378
0
  gint status;
379
  
380
0
  g_return_val_if_fail (argv != NULL, FALSE);
381
0
  g_return_val_if_fail (argv[0] != NULL, FALSE);
382
0
  g_return_val_if_fail (!(flags & G_SPAWN_DO_NOT_REAP_CHILD), FALSE);
383
0
  g_return_val_if_fail (standard_output == NULL ||
384
0
                        !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
385
0
  g_return_val_if_fail (standard_error == NULL ||
386
0
                        !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
387
  
388
  /* Just to ensure segfaults if callers try to use
389
   * these when an error is reported.
390
   */
391
0
  if (standard_output)
392
0
    *standard_output = NULL;
393
394
0
  if (standard_error)
395
0
    *standard_error = NULL;
396
  
397
0
  if (!fork_exec (FALSE,
398
0
                  working_directory,
399
0
                  (const gchar * const *) argv,
400
0
                  (const gchar * const *) envp,
401
0
                  !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
402
0
                  (flags & G_SPAWN_SEARCH_PATH) != 0,
403
0
                  (flags & G_SPAWN_SEARCH_PATH_FROM_ENVP) != 0,
404
0
                  (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
405
0
                  (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
406
0
                  (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
407
0
                  (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
408
0
                  (flags & G_SPAWN_CLOEXEC_PIPES) != 0,
409
0
                  child_setup,
410
0
                  user_data,
411
0
                  &pid,
412
0
                  NULL,
413
0
                  standard_output ? &outpipe : NULL,
414
0
                  standard_error ? &errpipe : NULL,
415
0
                  -1, -1, -1,
416
0
                  NULL, NULL, 0,
417
0
                  error))
418
0
    return FALSE;
419
420
  /* Read data from child. */
421
  
422
0
  failed = FALSE;
423
424
0
  if (outpipe >= 0)
425
0
    {
426
0
      outstr = g_string_new (NULL);
427
0
    }
428
      
429
0
  if (errpipe >= 0)
430
0
    {
431
0
      errstr = g_string_new (NULL);
432
0
    }
433
434
  /* Read data until we get EOF on both pipes. */
435
0
  while (!failed &&
436
0
         (outpipe >= 0 ||
437
0
          errpipe >= 0))
438
0
    {
439
      /* Any negative FD in the array is ignored, so we can use a fixed length.
440
       * We can use UNIX FDs here without worrying about Windows HANDLEs because
441
       * the Windows implementation is entirely in gspawn-win32.c. */
442
0
      GPollFD fds[] =
443
0
        {
444
0
          { outpipe, G_IO_IN | G_IO_HUP | G_IO_ERR, 0 },
445
0
          { errpipe, G_IO_IN | G_IO_HUP | G_IO_ERR, 0 },
446
0
        };
447
448
0
      ret = g_poll (fds, G_N_ELEMENTS (fds), -1  /* no timeout */);
449
450
0
      if (ret < 0)
451
0
        {
452
0
          int errsv = errno;
453
454
0
    if (errno == EINTR)
455
0
      continue;
456
457
0
          failed = TRUE;
458
459
0
          g_set_error (error,
460
0
                       G_SPAWN_ERROR,
461
0
                       G_SPAWN_ERROR_READ,
462
0
                       _("Unexpected error in reading data from a child process (%s)"),
463
0
                       g_strerror (errsv));
464
              
465
0
          break;
466
0
        }
467
468
0
      if (outpipe >= 0 && fds[0].revents != 0)
469
0
        {
470
0
          switch (read_data (outstr, outpipe, error))
471
0
            {
472
0
            case READ_FAILED:
473
0
              failed = TRUE;
474
0
              break;
475
0
            case READ_EOF:
476
0
              close_and_invalidate (&outpipe);
477
0
              outpipe = -1;
478
0
              break;
479
0
            default:
480
0
              break;
481
0
            }
482
483
0
          if (failed)
484
0
            break;
485
0
        }
486
487
0
      if (errpipe >= 0 && fds[1].revents != 0)
488
0
        {
489
0
          switch (read_data (errstr, errpipe, error))
490
0
            {
491
0
            case READ_FAILED:
492
0
              failed = TRUE;
493
0
              break;
494
0
            case READ_EOF:
495
0
              close_and_invalidate (&errpipe);
496
0
              errpipe = -1;
497
0
              break;
498
0
            default:
499
0
              break;
500
0
            }
501
502
0
          if (failed)
503
0
            break;
504
0
        }
505
0
    }
506
507
  /* These should only be open still if we had an error.  */
508
  
509
0
  if (outpipe >= 0)
510
0
    close_and_invalidate (&outpipe);
511
0
  if (errpipe >= 0)
512
0
    close_and_invalidate (&errpipe);
513
  
514
  /* Wait for child to exit, even if we have
515
   * an error pending.
516
   */
517
0
 again:
518
      
519
0
  ret = waitpid (pid, &status, 0);
520
521
0
  if (ret < 0)
522
0
    {
523
0
      if (errno == EINTR)
524
0
        goto again;
525
0
      else if (errno == ECHILD)
526
0
        {
527
0
          if (wait_status)
528
0
            {
529
0
              g_warning ("In call to g_spawn_sync(), wait status of a child process was requested but ECHILD was received by waitpid(). See the documentation of g_child_watch_source_new() for possible causes.");
530
0
            }
531
0
          else
532
0
            {
533
              /* We don't need the wait status. */
534
0
            }
535
0
        }
536
0
      else
537
0
        {
538
0
          if (!failed) /* avoid error pileups */
539
0
            {
540
0
              int errsv = errno;
541
542
0
              failed = TRUE;
543
                  
544
0
              g_set_error (error,
545
0
                           G_SPAWN_ERROR,
546
0
                           G_SPAWN_ERROR_READ,
547
0
                           _("Unexpected error in waitpid() (%s)"),
548
0
                           g_strerror (errsv));
549
0
            }
550
0
        }
551
0
    }
552
  
553
0
  if (failed)
554
0
    {
555
0
      if (outstr)
556
0
        g_string_free (outstr, TRUE);
557
0
      if (errstr)
558
0
        g_string_free (errstr, TRUE);
559
560
0
      return FALSE;
561
0
    }
562
0
  else
563
0
    {
564
0
      if (wait_status)
565
0
        *wait_status = status;
566
      
567
0
      if (standard_output)        
568
0
        *standard_output = g_string_free (outstr, FALSE);
569
570
0
      if (standard_error)
571
0
        *standard_error = g_string_free (errstr, FALSE);
572
573
0
      return TRUE;
574
0
    }
575
0
}
576
577
/**
578
 * g_spawn_async_with_pipes:
579
 * @working_directory: (type filename) (nullable): child's current working
580
 *     directory, or %NULL to inherit parent's, in the GLib file name encoding
581
 * @argv: (array zero-terminated=1) (element-type filename): child's argument
582
 *     vector, in the GLib file name encoding; it must be non-empty and %NULL-terminated
583
 * @envp: (array zero-terminated=1) (element-type filename) (nullable):
584
 *     child's environment, or %NULL to inherit parent's, in the GLib file
585
 *     name encoding
586
 * @flags: flags from #GSpawnFlags
587
 * @child_setup: (scope async) (nullable): function to run in the child just before exec()
588
 * @user_data: (closure): user data for @child_setup
589
 * @child_pid: (out) (optional): return location for child process ID, or %NULL
590
 * @standard_input: (out) (optional): return location for file descriptor to write to child's stdin, or %NULL
591
 * @standard_output: (out) (optional): return location for file descriptor to read child's stdout, or %NULL
592
 * @standard_error: (out) (optional): return location for file descriptor to read child's stderr, or %NULL
593
 * @error: return location for error
594
 *
595
 * Identical to g_spawn_async_with_pipes_and_fds() but with `n_fds` set to zero,
596
 * so no FD assignments are used.
597
 *
598
 * Returns: %TRUE on success, %FALSE if an error was set
599
 */
600
gboolean
601
g_spawn_async_with_pipes (const gchar          *working_directory,
602
                          gchar               **argv,
603
                          gchar               **envp,
604
                          GSpawnFlags           flags,
605
                          GSpawnChildSetupFunc  child_setup,
606
                          gpointer              user_data,
607
                          GPid                 *child_pid,
608
                          gint                 *standard_input,
609
                          gint                 *standard_output,
610
                          gint                 *standard_error,
611
                          GError              **error)
612
0
{
613
0
  return g_spawn_async_with_pipes_and_fds (working_directory,
614
0
                                           (const gchar * const *) argv,
615
0
                                           (const gchar * const *) envp,
616
0
                                           flags,
617
0
                                           child_setup, user_data,
618
0
                                           -1, -1, -1,
619
0
                                           NULL, NULL, 0,
620
0
                                           child_pid,
621
0
                                           standard_input,
622
0
                                           standard_output,
623
0
                                           standard_error,
624
0
                                           error);
625
0
}
626
627
/**
628
 * g_spawn_async_with_pipes_and_fds:
629
 * @working_directory: (type filename) (nullable): child's current working
630
 *     directory, or %NULL to inherit parent's, in the GLib file name encoding
631
 * @argv: (array zero-terminated=1) (element-type filename): child's argument
632
 *     vector, in the GLib file name encoding; it must be non-empty and %NULL-terminated
633
 * @envp: (array zero-terminated=1) (element-type filename) (nullable):
634
 *     child's environment, or %NULL to inherit parent's, in the GLib file
635
 *     name encoding
636
 * @flags: flags from #GSpawnFlags
637
 * @child_setup: (scope async) (nullable): function to run in the child just before `exec()`
638
 * @user_data: (closure): user data for @child_setup
639
 * @stdin_fd: file descriptor to use for child's stdin, or `-1`
640
 * @stdout_fd: file descriptor to use for child's stdout, or `-1`
641
 * @stderr_fd: file descriptor to use for child's stderr, or `-1`
642
 * @source_fds: (array length=n_fds) (nullable): array of FDs from the parent
643
 *    process to make available in the child process
644
 * @target_fds: (array length=n_fds) (nullable): array of FDs to remap
645
 *    @source_fds to in the child process
646
 * @n_fds: number of FDs in @source_fds and @target_fds
647
 * @child_pid_out: (out) (optional): return location for child process ID, or %NULL
648
 * @stdin_pipe_out: (out) (optional): return location for file descriptor to write to child's stdin, or %NULL
649
 * @stdout_pipe_out: (out) (optional): return location for file descriptor to read child's stdout, or %NULL
650
 * @stderr_pipe_out: (out) (optional): return location for file descriptor to read child's stderr, or %NULL
651
 * @error: return location for error
652
 *
653
 * Executes a child program asynchronously (your program will not
654
 * block waiting for the child to exit).
655
 *
656
 * The child program is specified by the only argument that must be
657
 * provided, @argv. @argv should be a %NULL-terminated array of strings,
658
 * to be passed as the argument vector for the child. The first string
659
 * in @argv is of course the name of the program to execute. By default,
660
 * the name of the program must be a full path. If @flags contains the
661
 * %G_SPAWN_SEARCH_PATH flag, the `PATH` environment variable is used to
662
 * search for the executable. If @flags contains the
663
 * %G_SPAWN_SEARCH_PATH_FROM_ENVP flag, the `PATH` variable from @envp
664
 * is used to search for the executable. If both the
665
 * %G_SPAWN_SEARCH_PATH and %G_SPAWN_SEARCH_PATH_FROM_ENVP flags are
666
 * set, the `PATH` variable from @envp takes precedence over the
667
 * environment variable.
668
 *
669
 * If the program name is not a full path and %G_SPAWN_SEARCH_PATH flag
670
 * is not used, then the program will be run from the current directory
671
 * (or @working_directory, if specified); this might be unexpected or even
672
 * dangerous in some cases when the current directory is world-writable.
673
 *
674
 * On Windows, note that all the string or string vector arguments to
675
 * this function and the other `g_spawn*()` functions are in UTF-8, the
676
 * GLib file name encoding. Unicode characters that are not part of
677
 * the system codepage passed in these arguments will be correctly
678
 * available in the spawned program only if it uses wide character API
679
 * to retrieve its command line. For C programs built with Microsoft's
680
 * tools it is enough to make the program have a `wmain()` instead of
681
 * `main()`. `wmain()` has a wide character argument vector as parameter.
682
 *
683
 * At least currently, mingw doesn't support `wmain()`, so if you use
684
 * mingw to develop the spawned program, it should call
685
 * g_win32_get_command_line() to get arguments in UTF-8.
686
 *
687
 * On Windows the low-level child process creation API `CreateProcess()`
688
 * doesn't use argument vectors, but a command line. The C runtime
689
 * library's `spawn*()` family of functions (which g_spawn_async_with_pipes()
690
 * eventually calls) paste the argument vector elements together into
691
 * a command line, and the C runtime startup code does a corresponding
692
 * reconstruction of an argument vector from the command line, to be
693
 * passed to `main()`. Complications arise when you have argument vector
694
 * elements that contain spaces or double quotes. The `spawn*()` functions
695
 * don't do any quoting or escaping, but on the other hand the startup
696
 * code does do unquoting and unescaping in order to enable receiving
697
 * arguments with embedded spaces or double quotes. To work around this
698
 * asymmetry, g_spawn_async_with_pipes() will do quoting and escaping on
699
 * argument vector elements that need it before calling the C runtime
700
 * `spawn()` function.
701
 *
702
 * The returned @child_pid on Windows is a handle to the child
703
 * process, not its identifier. Process handles and process
704
 * identifiers are different concepts on Windows.
705
 *
706
 * @envp is a %NULL-terminated array of strings, where each string
707
 * has the form `KEY=VALUE`. This will become the child's environment.
708
 * If @envp is %NULL, the child inherits its parent's environment.
709
 *
710
 * @flags should be the bitwise OR of any flags you want to affect the
711
 * function's behaviour. The %G_SPAWN_DO_NOT_REAP_CHILD means that the
712
 * child will not automatically be reaped; you must use a child watch
713
 * (g_child_watch_add()) to be notified about the death of the child process,
714
 * otherwise it will stay around as a zombie process until this process exits.
715
 * Eventually you must call g_spawn_close_pid() on the @child_pid, in order to
716
 * free resources which may be associated with the child process. (On Unix,
717
 * using a child watch is equivalent to calling waitpid() or handling
718
 * the `SIGCHLD` signal manually. On Windows, calling g_spawn_close_pid()
719
 * is equivalent to calling `CloseHandle()` on the process handle returned
720
 * in @child_pid). See g_child_watch_add().
721
 *
722
 * Open UNIX file descriptors marked as `FD_CLOEXEC` will be automatically
723
 * closed in the child process. %G_SPAWN_LEAVE_DESCRIPTORS_OPEN means that
724
 * other open file descriptors will be inherited by the child; otherwise all
725
 * descriptors except stdin/stdout/stderr will be closed before calling `exec()`
726
 * in the child. %G_SPAWN_SEARCH_PATH means that @argv[0] need not be an
727
 * absolute path, it will be looked for in the `PATH` environment
728
 * variable. %G_SPAWN_SEARCH_PATH_FROM_ENVP means need not be an
729
 * absolute path, it will be looked for in the `PATH` variable from
730
 * @envp. If both %G_SPAWN_SEARCH_PATH and %G_SPAWN_SEARCH_PATH_FROM_ENVP
731
 * are used, the value from @envp takes precedence over the environment.
732
 *
733
 * %G_SPAWN_CHILD_INHERITS_STDIN means that the child will inherit the parent's
734
 * standard input (by default, the child's standard input is attached to
735
 * `/dev/null`). %G_SPAWN_STDIN_FROM_DEV_NULL explicitly imposes the default
736
 * behavior. Both flags cannot be enabled at the same time and, in both cases,
737
 * the @stdin_pipe_out argument is ignored.
738
 *
739
 * %G_SPAWN_STDOUT_TO_DEV_NULL means that the child's standard output
740
 * will be discarded (by default, it goes to the same location as the parent's
741
 * standard output). %G_SPAWN_CHILD_INHERITS_STDOUT explicitly imposes the
742
 * default behavior. Both flags cannot be enabled at the same time and, in
743
 * both cases, the @stdout_pipe_out argument is ignored.
744
 *
745
 * %G_SPAWN_STDERR_TO_DEV_NULL means that the child's standard error
746
 * will be discarded (by default, it goes to the same location as the parent's
747
 * standard error). %G_SPAWN_CHILD_INHERITS_STDERR explicitly imposes the
748
 * default behavior. Both flags cannot be enabled at the same time and, in
749
 * both cases, the @stderr_pipe_out argument is ignored.
750
 *
751
 * It is valid to pass the same FD in multiple parameters (e.g. you can pass
752
 * a single FD for both @stdout_fd and @stderr_fd, and include it in
753
 * @source_fds too).
754
 *
755
 * @source_fds and @target_fds allow zero or more FDs from this process to be
756
 * remapped to different FDs in the spawned process. If @n_fds is greater than
757
 * zero, @source_fds and @target_fds must both be non-%NULL and the same length.
758
 * Each FD in @source_fds is remapped to the FD number at the same index in
759
 * @target_fds. The source and target FD may be equal to simply propagate an FD
760
 * to the spawned process. FD remappings are processed after standard FDs, so
761
 * any target FDs which equal @stdin_fd, @stdout_fd or @stderr_fd will overwrite
762
 * them in the spawned process.
763
 *
764
 * @source_fds is supported on Windows since 2.72.
765
 *
766
 * %G_SPAWN_FILE_AND_ARGV_ZERO means that the first element of @argv is
767
 * the file to execute, while the remaining elements are the actual
768
 * argument vector to pass to the file. Normally g_spawn_async_with_pipes()
769
 * uses @argv[0] as the file to execute, and passes all of @argv to the child.
770
 *
771
 * @child_setup and @user_data are a function and user data. On POSIX
772
 * platforms, the function is called in the child after GLib has
773
 * performed all the setup it plans to perform (including creating
774
 * pipes, closing file descriptors, etc.) but before calling `exec()`.
775
 * That is, @child_setup is called just before calling `exec()` in the
776
 * child. Obviously actions taken in this function will only affect
777
 * the child, not the parent.
778
 *
779
 * On Windows, there is no separate `fork()` and `exec()` functionality.
780
 * Child processes are created and run with a single API call,
781
 * `CreateProcess()`. There is no sensible thing @child_setup
782
 * could be used for on Windows so it is ignored and not called.
783
 *
784
 * If non-%NULL, @child_pid will on Unix be filled with the child's
785
 * process ID. You can use the process ID to send signals to the child,
786
 * or to use g_child_watch_add() (or `waitpid()`) if you specified the
787
 * %G_SPAWN_DO_NOT_REAP_CHILD flag. On Windows, @child_pid will be
788
 * filled with a handle to the child process only if you specified the
789
 * %G_SPAWN_DO_NOT_REAP_CHILD flag. You can then access the child
790
 * process using the Win32 API, for example wait for its termination
791
 * with the `WaitFor*()` functions, or examine its exit code with
792
 * `GetExitCodeProcess()`. You should close the handle with `CloseHandle()`
793
 * or g_spawn_close_pid() when you no longer need it.
794
 *
795
 * If non-%NULL, the @stdin_pipe_out, @stdout_pipe_out, @stderr_pipe_out
796
 * locations will be filled with file descriptors for writing to the child's
797
 * standard input or reading from its standard output or standard error.
798
 * The caller of g_spawn_async_with_pipes() must close these file descriptors
799
 * when they are no longer in use. If these parameters are %NULL, the
800
 * corresponding pipe won't be created.
801
 *
802
 * If @stdin_pipe_out is %NULL, the child's standard input is attached to
803
 * `/dev/null` unless %G_SPAWN_CHILD_INHERITS_STDIN is set.
804
 *
805
 * If @stderr_pipe_out is NULL, the child's standard error goes to the same
806
 * location as the parent's standard error unless %G_SPAWN_STDERR_TO_DEV_NULL
807
 * is set.
808
 *
809
 * If @stdout_pipe_out is NULL, the child's standard output goes to the same
810
 * location as the parent's standard output unless %G_SPAWN_STDOUT_TO_DEV_NULL
811
 * is set.
812
 *
813
 * @error can be %NULL to ignore errors, or non-%NULL to report errors.
814
 * If an error is set, the function returns %FALSE. Errors are reported
815
 * even if they occur in the child (for example if the executable in
816
 * `@argv[0]` is not found). Typically the `message` field of returned
817
 * errors should be displayed to users. Possible errors are those from
818
 * the %G_SPAWN_ERROR domain.
819
 *
820
 * If an error occurs, @child_pid, @stdin_pipe_out, @stdout_pipe_out,
821
 * and @stderr_pipe_out will not be filled with valid values.
822
 *
823
 * If @child_pid is not %NULL and an error does not occur then the returned
824
 * process reference must be closed using g_spawn_close_pid().
825
 *
826
 * On modern UNIX platforms, GLib can use an efficient process launching
827
 * codepath driven internally by `posix_spawn()`. This has the advantage of
828
 * avoiding the fork-time performance costs of cloning the parent process
829
 * address space, and avoiding associated memory overcommit checks that are
830
 * not relevant in the context of immediately executing a distinct process.
831
 * This optimized codepath will be used provided that the following conditions
832
 * are met:
833
 *
834
 * 1. %G_SPAWN_DO_NOT_REAP_CHILD is set
835
 * 2. %G_SPAWN_LEAVE_DESCRIPTORS_OPEN is set
836
 * 3. %G_SPAWN_SEARCH_PATH_FROM_ENVP is not set
837
 * 4. @working_directory is %NULL
838
 * 5. @child_setup is %NULL
839
 * 6. The program is of a recognised binary format, or has a shebang.
840
 *    Otherwise, GLib will have to execute the program through the
841
 *    shell, which is not done using the optimized codepath.
842
 *
843
 * If you are writing a GTK application, and the program you are spawning is a
844
 * graphical application too, then to ensure that the spawned program opens its
845
 * windows on the right screen, you may want to use #GdkAppLaunchContext,
846
 * #GAppLaunchContext, or set the `DISPLAY` environment variable.
847
 *
848
 * Returns: %TRUE on success, %FALSE if an error was set
849
 *
850
 * Since: 2.68
851
 */
852
gboolean
853
g_spawn_async_with_pipes_and_fds (const gchar           *working_directory,
854
                                  const gchar * const   *argv,
855
                                  const gchar * const   *envp,
856
                                  GSpawnFlags            flags,
857
                                  GSpawnChildSetupFunc   child_setup,
858
                                  gpointer               user_data,
859
                                  gint                   stdin_fd,
860
                                  gint                   stdout_fd,
861
                                  gint                   stderr_fd,
862
                                  const gint            *source_fds,
863
                                  const gint            *target_fds,
864
                                  gsize                  n_fds,
865
                                  GPid                  *child_pid_out,
866
                                  gint                  *stdin_pipe_out,
867
                                  gint                  *stdout_pipe_out,
868
                                  gint                  *stderr_pipe_out,
869
                                  GError               **error)
870
0
{
871
0
  g_return_val_if_fail (argv != NULL, FALSE);
872
0
  g_return_val_if_fail (argv[0] != NULL, FALSE);
873
  /* can’t both inherit and set pipes to /dev/null */
874
0
  g_return_val_if_fail ((flags & INHERITS_OR_NULL_STDIN) != INHERITS_OR_NULL_STDIN, FALSE);
875
0
  g_return_val_if_fail ((flags & INHERITS_OR_NULL_STDOUT) != INHERITS_OR_NULL_STDOUT, FALSE);
876
0
  g_return_val_if_fail ((flags & INHERITS_OR_NULL_STDERR) != INHERITS_OR_NULL_STDERR, FALSE);
877
  /* can’t use pipes and stdin/stdout/stderr FDs */
878
0
  g_return_val_if_fail (stdin_pipe_out == NULL || stdin_fd < 0, FALSE);
879
0
  g_return_val_if_fail (stdout_pipe_out == NULL || stdout_fd < 0, FALSE);
880
0
  g_return_val_if_fail (stderr_pipe_out == NULL || stderr_fd < 0, FALSE);
881
882
0
  if ((flags & INHERITS_OR_NULL_STDIN) != 0)
883
0
    stdin_pipe_out = NULL;
884
0
  if ((flags & INHERITS_OR_NULL_STDOUT) != 0)
885
0
    stdout_pipe_out = NULL;
886
0
  if ((flags & INHERITS_OR_NULL_STDERR) != 0)
887
0
    stderr_pipe_out = NULL;
888
889
0
  return fork_exec (!(flags & G_SPAWN_DO_NOT_REAP_CHILD),
890
0
                    working_directory,
891
0
                    (const gchar * const *) argv,
892
0
                    (const gchar * const *) envp,
893
0
                    !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
894
0
                    (flags & G_SPAWN_SEARCH_PATH) != 0,
895
0
                    (flags & G_SPAWN_SEARCH_PATH_FROM_ENVP) != 0,
896
0
                    (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
897
0
                    (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
898
0
                    (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
899
0
                    (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
900
0
                    (flags & G_SPAWN_CLOEXEC_PIPES) != 0,
901
0
                    child_setup,
902
0
                    user_data,
903
0
                    child_pid_out,
904
0
                    stdin_pipe_out,
905
0
                    stdout_pipe_out,
906
0
                    stderr_pipe_out,
907
0
                    stdin_fd,
908
0
                    stdout_fd,
909
0
                    stderr_fd,
910
0
                    source_fds,
911
0
                    target_fds,
912
0
                    n_fds,
913
0
                    error);
914
0
}
915
916
/**
917
 * g_spawn_async_with_fds:
918
 * @working_directory: (type filename) (nullable): child's current working directory, or %NULL to inherit parent's, in the GLib file name encoding
919
 * @argv: (array zero-terminated=1): child's argument vector, in the GLib file name encoding;
920
 *   it must be non-empty and %NULL-terminated
921
 * @envp: (array zero-terminated=1) (nullable): child's environment, or %NULL to inherit parent's, in the GLib file name encoding
922
 * @flags: flags from #GSpawnFlags
923
 * @child_setup: (scope async) (nullable): function to run in the child just before exec()
924
 * @user_data: (closure): user data for @child_setup
925
 * @child_pid: (out) (optional): return location for child process ID, or %NULL
926
 * @stdin_fd: file descriptor to use for child's stdin, or `-1`
927
 * @stdout_fd: file descriptor to use for child's stdout, or `-1`
928
 * @stderr_fd: file descriptor to use for child's stderr, or `-1`
929
 * @error: return location for error
930
 *
931
 * Executes a child program asynchronously.
932
 *
933
 * Identical to g_spawn_async_with_pipes_and_fds() but with `n_fds` set to zero,
934
 * so no FD assignments are used.
935
 *
936
 * Returns: %TRUE on success, %FALSE if an error was set
937
 *
938
 * Since: 2.58
939
 */
940
gboolean
941
g_spawn_async_with_fds (const gchar          *working_directory,
942
                        gchar               **argv,
943
                        gchar               **envp,
944
                        GSpawnFlags           flags,
945
                        GSpawnChildSetupFunc  child_setup,
946
                        gpointer              user_data,
947
                        GPid                 *child_pid,
948
                        gint                  stdin_fd,
949
                        gint                  stdout_fd,
950
                        gint                  stderr_fd,
951
                        GError              **error)
952
0
{
953
0
  g_return_val_if_fail (argv != NULL, FALSE);
954
0
  g_return_val_if_fail (argv[0] != NULL, FALSE);
955
0
  g_return_val_if_fail (stdout_fd < 0 ||
956
0
                        !(flags & G_SPAWN_STDOUT_TO_DEV_NULL), FALSE);
957
0
  g_return_val_if_fail (stderr_fd < 0 ||
958
0
                        !(flags & G_SPAWN_STDERR_TO_DEV_NULL), FALSE);
959
  /* can't inherit stdin if we have an input pipe. */
960
0
  g_return_val_if_fail (stdin_fd < 0 ||
961
0
                        !(flags & G_SPAWN_CHILD_INHERITS_STDIN), FALSE);
962
963
0
  return fork_exec (!(flags & G_SPAWN_DO_NOT_REAP_CHILD),
964
0
                    working_directory,
965
0
                    (const gchar * const *) argv,
966
0
                    (const gchar * const *) envp,
967
0
                    !(flags & G_SPAWN_LEAVE_DESCRIPTORS_OPEN),
968
0
                    (flags & G_SPAWN_SEARCH_PATH) != 0,
969
0
                    (flags & G_SPAWN_SEARCH_PATH_FROM_ENVP) != 0,
970
0
                    (flags & G_SPAWN_STDOUT_TO_DEV_NULL) != 0,
971
0
                    (flags & G_SPAWN_STDERR_TO_DEV_NULL) != 0,
972
0
                    (flags & G_SPAWN_CHILD_INHERITS_STDIN) != 0,
973
0
                    (flags & G_SPAWN_FILE_AND_ARGV_ZERO) != 0,
974
0
                    (flags & G_SPAWN_CLOEXEC_PIPES) != 0,
975
0
                    child_setup,
976
0
                    user_data,
977
0
                    child_pid,
978
0
                    NULL, NULL, NULL,
979
0
                    stdin_fd,
980
0
                    stdout_fd,
981
0
                    stderr_fd,
982
0
                    NULL, NULL, 0,
983
0
                    error);
984
0
}
985
986
/**
987
 * g_spawn_command_line_sync:
988
 * @command_line: (type filename): a command line
989
 * @standard_output: (out) (array zero-terminated=1) (element-type guint8) (optional): return location for child output
990
 * @standard_error: (out) (array zero-terminated=1) (element-type guint8) (optional): return location for child errors
991
 * @wait_status: (out) (optional): return location for child wait status, as returned by waitpid()
992
 * @error: return location for errors
993
 *
994
 * A simple version of g_spawn_sync() with little-used parameters
995
 * removed, taking a command line instead of an argument vector.
996
 *
997
 * See g_spawn_sync() for full details.
998
 *
999
 * The @command_line argument will be parsed by g_shell_parse_argv().
1000
 *
1001
 * Unlike g_spawn_sync(), the %G_SPAWN_SEARCH_PATH flag is enabled.
1002
 * Note that %G_SPAWN_SEARCH_PATH can have security implications, so
1003
 * consider using g_spawn_sync() directly if appropriate.
1004
 *
1005
 * Possible errors are those from g_spawn_sync() and those
1006
 * from g_shell_parse_argv().
1007
 *
1008
 * If @wait_status is non-%NULL, the platform-specific status of
1009
 * the child is stored there; see the documentation of
1010
 * g_spawn_check_wait_status() for how to use and interpret this.
1011
 * On Unix platforms, note that it is usually not equal
1012
 * to the integer passed to `exit()` or returned from `main()`.
1013
 * 
1014
 * On Windows, please note the implications of g_shell_parse_argv()
1015
 * parsing @command_line. Parsing is done according to Unix shell rules, not 
1016
 * Windows command interpreter rules.
1017
 * Space is a separator, and backslashes are
1018
 * special. Thus you cannot simply pass a @command_line containing
1019
 * canonical Windows paths, like "c:\\program files\\app\\app.exe", as
1020
 * the backslashes will be eaten, and the space will act as a
1021
 * separator. You need to enclose such paths with single quotes, like
1022
 * "'c:\\program files\\app\\app.exe' 'e:\\folder\\argument.txt'".
1023
 *
1024
 * Returns: %TRUE on success, %FALSE if an error was set
1025
 **/
1026
gboolean
1027
g_spawn_command_line_sync (const gchar  *command_line,
1028
                           gchar       **standard_output,
1029
                           gchar       **standard_error,
1030
                           gint         *wait_status,
1031
                           GError      **error)
1032
0
{
1033
0
  gboolean retval;
1034
0
  gchar **argv = NULL;
1035
1036
0
  g_return_val_if_fail (command_line != NULL, FALSE);
1037
  
1038
  /* This will return a runtime error if @command_line is the empty string. */
1039
0
  if (!g_shell_parse_argv (command_line,
1040
0
                           NULL, &argv,
1041
0
                           error))
1042
0
    return FALSE;
1043
  
1044
0
  retval = g_spawn_sync (NULL,
1045
0
                         argv,
1046
0
                         NULL,
1047
0
                         G_SPAWN_SEARCH_PATH,
1048
0
                         NULL,
1049
0
                         NULL,
1050
0
                         standard_output,
1051
0
                         standard_error,
1052
0
                         wait_status,
1053
0
                         error);
1054
0
  g_strfreev (argv);
1055
1056
0
  return retval;
1057
0
}
1058
1059
/**
1060
 * g_spawn_command_line_async:
1061
 * @command_line: (type filename): a command line
1062
 * @error: return location for errors
1063
 * 
1064
 * A simple version of g_spawn_async() that parses a command line with
1065
 * g_shell_parse_argv() and passes it to g_spawn_async().
1066
 *
1067
 * Runs a command line in the background. Unlike g_spawn_async(), the
1068
 * %G_SPAWN_SEARCH_PATH flag is enabled, other flags are not. Note
1069
 * that %G_SPAWN_SEARCH_PATH can have security implications, so
1070
 * consider using g_spawn_async() directly if appropriate. Possible
1071
 * errors are those from g_shell_parse_argv() and g_spawn_async().
1072
 * 
1073
 * The same concerns on Windows apply as for g_spawn_command_line_sync().
1074
 *
1075
 * Returns: %TRUE on success, %FALSE if error is set
1076
 **/
1077
gboolean
1078
g_spawn_command_line_async (const gchar *command_line,
1079
                            GError     **error)
1080
0
{
1081
0
  gboolean retval;
1082
0
  gchar **argv = NULL;
1083
1084
0
  g_return_val_if_fail (command_line != NULL, FALSE);
1085
1086
  /* This will return a runtime error if @command_line is the empty string. */
1087
0
  if (!g_shell_parse_argv (command_line,
1088
0
                           NULL, &argv,
1089
0
                           error))
1090
0
    return FALSE;
1091
  
1092
0
  retval = g_spawn_async (NULL,
1093
0
                          argv,
1094
0
                          NULL,
1095
0
                          G_SPAWN_SEARCH_PATH,
1096
0
                          NULL,
1097
0
                          NULL,
1098
0
                          NULL,
1099
0
                          error);
1100
0
  g_strfreev (argv);
1101
1102
0
  return retval;
1103
0
}
1104
1105
/**
1106
 * g_spawn_check_wait_status:
1107
 * @wait_status: A platform-specific wait status as returned from g_spawn_sync()
1108
 * @error: a #GError
1109
 *
1110
 * Set @error if @wait_status indicates the child exited abnormally
1111
 * (e.g. with a nonzero exit code, or via a fatal signal).
1112
 *
1113
 * The g_spawn_sync() and g_child_watch_add() family of APIs return the
1114
 * status of subprocesses encoded in a platform-specific way.
1115
 * On Unix, this is guaranteed to be in the same format waitpid() returns,
1116
 * and on Windows it is guaranteed to be the result of GetExitCodeProcess().
1117
 *
1118
 * Prior to the introduction of this function in GLib 2.34, interpreting
1119
 * @wait_status required use of platform-specific APIs, which is problematic
1120
 * for software using GLib as a cross-platform layer.
1121
 *
1122
 * Additionally, many programs simply want to determine whether or not
1123
 * the child exited successfully, and either propagate a #GError or
1124
 * print a message to standard error. In that common case, this function
1125
 * can be used. Note that the error message in @error will contain
1126
 * human-readable information about the wait status.
1127
 *
1128
 * The @domain and @code of @error have special semantics in the case
1129
 * where the process has an "exit code", as opposed to being killed by
1130
 * a signal. On Unix, this happens if WIFEXITED() would be true of
1131
 * @wait_status. On Windows, it is always the case.
1132
 *
1133
 * The special semantics are that the actual exit code will be the
1134
 * code set in @error, and the domain will be %G_SPAWN_EXIT_ERROR.
1135
 * This allows you to differentiate between different exit codes.
1136
 *
1137
 * If the process was terminated by some means other than an exit
1138
 * status (for example if it was killed by a signal), the domain will be
1139
 * %G_SPAWN_ERROR and the code will be %G_SPAWN_ERROR_FAILED.
1140
 *
1141
 * This function just offers convenience; you can of course also check
1142
 * the available platform via a macro such as %G_OS_UNIX, and use
1143
 * WIFEXITED() and WEXITSTATUS() on @wait_status directly. Do not attempt
1144
 * to scan or parse the error message string; it may be translated and/or
1145
 * change in future versions of GLib.
1146
 *
1147
 * Prior to version 2.70, g_spawn_check_exit_status() provides the same
1148
 * functionality, although under a misleading name.
1149
 *
1150
 * Returns: %TRUE if child exited successfully, %FALSE otherwise (and
1151
 *   @error will be set)
1152
 *
1153
 * Since: 2.70
1154
 */
1155
gboolean
1156
g_spawn_check_wait_status (gint      wait_status,
1157
         GError  **error)
1158
0
{
1159
0
  gboolean ret = FALSE;
1160
1161
0
  if (WIFEXITED (wait_status))
1162
0
    {
1163
0
      if (WEXITSTATUS (wait_status) != 0)
1164
0
  {
1165
0
    g_set_error (error, G_SPAWN_EXIT_ERROR, WEXITSTATUS (wait_status),
1166
0
           _("Child process exited with code %ld"),
1167
0
           (long) WEXITSTATUS (wait_status));
1168
0
    goto out;
1169
0
  }
1170
0
    }
1171
0
  else if (WIFSIGNALED (wait_status))
1172
0
    {
1173
0
      g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
1174
0
       _("Child process killed by signal %ld"),
1175
0
       (long) WTERMSIG (wait_status));
1176
0
      goto out;
1177
0
    }
1178
0
  else if (WIFSTOPPED (wait_status))
1179
0
    {
1180
0
      g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
1181
0
       _("Child process stopped by signal %ld"),
1182
0
       (long) WSTOPSIG (wait_status));
1183
0
      goto out;
1184
0
    }
1185
0
  else
1186
0
    {
1187
0
      g_set_error (error, G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED,
1188
0
       _("Child process exited abnormally"));
1189
0
      goto out;
1190
0
    }
1191
1192
0
  ret = TRUE;
1193
0
 out:
1194
0
  return ret;
1195
0
}
1196
1197
/**
1198
 * g_spawn_check_exit_status:
1199
 * @wait_status: A status as returned from g_spawn_sync()
1200
 * @error: a #GError
1201
 *
1202
 * An old name for g_spawn_check_wait_status(), deprecated because its
1203
 * name is misleading.
1204
 *
1205
 * Despite the name of the function, @wait_status must be the wait status
1206
 * as returned by g_spawn_sync(), g_subprocess_get_status(), `waitpid()`,
1207
 * etc. On Unix platforms, it is incorrect for it to be the exit status
1208
 * as passed to `exit()` or returned by g_subprocess_get_exit_status() or
1209
 * `WEXITSTATUS()`.
1210
 *
1211
 * Returns: %TRUE if child exited successfully, %FALSE otherwise (and
1212
 *     @error will be set)
1213
 *
1214
 * Since: 2.34
1215
 *
1216
 * Deprecated: 2.70: Use g_spawn_check_wait_status() instead, and check whether your code is conflating wait and exit statuses.
1217
 */
1218
gboolean
1219
g_spawn_check_exit_status (gint      wait_status,
1220
                           GError  **error)
1221
0
{
1222
0
  return g_spawn_check_wait_status (wait_status, error);
1223
0
}
1224
1225
/* This function is called between fork() and exec() and hence must be
1226
 * async-signal-safe (see signal-safety(7)). */
1227
static gssize
1228
write_all (gint fd, gconstpointer vbuf, gsize to_write)
1229
0
{
1230
0
  gchar *buf = (gchar *) vbuf;
1231
  
1232
0
  while (to_write > 0)
1233
0
    {
1234
0
      gssize count = write (fd, buf, to_write);
1235
0
      if (count < 0)
1236
0
        {
1237
0
          if (errno != EINTR)
1238
0
            return FALSE;
1239
0
        }
1240
0
      else
1241
0
        {
1242
0
          to_write -= count;
1243
0
          buf += count;
1244
0
        }
1245
0
    }
1246
  
1247
0
  return TRUE;
1248
0
}
1249
1250
/* This function is called between fork() and exec() and hence must be
1251
 * async-signal-safe (see signal-safety(7)). */
1252
G_NORETURN
1253
static void
1254
write_err_and_exit (gint fd, gint msg)
1255
0
{
1256
0
  gint en = errno;
1257
  
1258
0
  write_all (fd, &msg, sizeof(msg));
1259
0
  write_all (fd, &en, sizeof(en));
1260
  
1261
0
  _exit (1);
1262
0
}
1263
1264
/* This function is called between fork() and exec() and hence must be
1265
 * async-signal-safe (see signal-safety(7)). */
1266
static int
1267
set_cloexec (void *data, gint fd)
1268
0
{
1269
0
  if (fd >= GPOINTER_TO_INT (data))
1270
0
    fcntl (fd, F_SETFD, FD_CLOEXEC);
1271
1272
0
  return 0;
1273
0
}
1274
1275
/* This function is called between fork() and exec() and hence must be
1276
 * async-signal-safe (see signal-safety(7)). */
1277
static void
1278
unset_cloexec (int fd)
1279
0
{
1280
0
  int flags;
1281
0
  int result;
1282
1283
0
  flags = fcntl (fd, F_GETFD, 0);
1284
1285
0
  if (flags != -1)
1286
0
    {
1287
0
      int errsv;
1288
0
      flags &= (~FD_CLOEXEC);
1289
0
      do
1290
0
        {
1291
0
          result = fcntl (fd, F_SETFD, flags);
1292
0
          errsv = errno;
1293
0
        }
1294
0
      while (result == -1 && errsv == EINTR);
1295
0
    }
1296
0
}
1297
1298
/* This function is called between fork() and exec() and hence must be
1299
 * async-signal-safe (see signal-safety(7)). */
1300
static int
1301
dupfd_cloexec (int old_fd, int new_fd_min)
1302
0
{
1303
0
  int fd, errsv;
1304
0
#ifdef F_DUPFD_CLOEXEC
1305
0
  do
1306
0
    {
1307
0
      fd = fcntl (old_fd, F_DUPFD_CLOEXEC, new_fd_min);
1308
0
      errsv = errno;
1309
0
    }
1310
0
  while (fd == -1 && errsv == EINTR);
1311
#else
1312
  /* OS X Snow Lion and earlier don't have F_DUPFD_CLOEXEC:
1313
   * https://bugzilla.gnome.org/show_bug.cgi?id=710962
1314
   */
1315
  int result, flags;
1316
  do
1317
    {
1318
      fd = fcntl (old_fd, F_DUPFD, new_fd_min);
1319
      errsv = errno;
1320
    }
1321
  while (fd == -1 && errsv == EINTR);
1322
  flags = fcntl (fd, F_GETFD, 0);
1323
  if (flags != -1)
1324
    {
1325
      flags |= FD_CLOEXEC;
1326
      do
1327
        {
1328
          result = fcntl (fd, F_SETFD, flags);
1329
          errsv = errno;
1330
        }
1331
      while (result == -1 && errsv == EINTR);
1332
    }
1333
#endif
1334
0
  return fd;
1335
0
}
1336
1337
/* This function is called between fork() and exec() and hence must be
1338
 * async-signal-safe (see signal-safety(7)). */
1339
G_GNUC_UNUSED static int
1340
close_func (void *data, int fd)
1341
0
{
1342
0
  if (fd >= GPOINTER_TO_INT (data))
1343
0
    g_close (fd, NULL);
1344
1345
0
  return 0;
1346
0
}
1347
1348
#ifdef __linux__
1349
struct linux_dirent64
1350
{
1351
  guint64        d_ino;    /* 64-bit inode number */
1352
  guint64        d_off;    /* 64-bit offset to next structure */
1353
  unsigned short d_reclen; /* Size of this dirent */
1354
  unsigned char  d_type;   /* File type */
1355
  char           d_name[]; /* Filename (null-terminated) */
1356
};
1357
1358
/* This function is called between fork() and exec() and hence must be
1359
 * async-signal-safe (see signal-safety(7)). */
1360
static gint
1361
filename_to_fd (const char *p)
1362
0
{
1363
0
  char c;
1364
0
  int fd = 0;
1365
0
  const int cutoff = G_MAXINT / 10;
1366
0
  const int cutlim = G_MAXINT % 10;
1367
1368
0
  if (*p == '\0')
1369
0
    return -1;
1370
1371
0
  while ((c = *p++) != '\0')
1372
0
    {
1373
0
      if (c < '0' || c > '9')
1374
0
        return -1;
1375
0
      c -= '0';
1376
1377
      /* Check for overflow. */
1378
0
      if (fd > cutoff || (fd == cutoff && c > cutlim))
1379
0
        return -1;
1380
1381
0
      fd = fd * 10 + c;
1382
0
    }
1383
1384
0
  return fd;
1385
0
}
1386
#endif
1387
1388
/* This function is called between fork() and exec() and hence must be
1389
 * async-signal-safe (see signal-safety(7)). */
1390
static int
1391
safe_fdwalk (int (*cb)(void *data, int fd), void *data)
1392
0
{
1393
#if 0
1394
  /* Use fdwalk function provided by the system if it is known to be
1395
   * async-signal safe.
1396
   *
1397
   * Currently there are no operating systems known to provide a safe
1398
   * implementation, so this section is not used for now.
1399
   */
1400
  return fdwalk (cb, data);
1401
#else
1402
  /* Fallback implementation of fdwalk. It should be async-signal safe, but it
1403
   * may be slow on non-Linux operating systems, especially on systems allowing
1404
   * very high number of open file descriptors.
1405
   */
1406
0
  gint open_max = -1;
1407
0
  gint fd;
1408
0
  gint res = 0;
1409
  
1410
#if 0 && defined(HAVE_SYS_RESOURCE_H)
1411
  struct rlimit rl;
1412
#endif
1413
1414
0
#ifdef __linux__
1415
  /* Avoid use of opendir/closedir since these are not async-signal-safe. */
1416
0
  int dir_fd = open ("/proc/self/fd", O_RDONLY | O_DIRECTORY);
1417
0
  if (dir_fd >= 0)
1418
0
    {
1419
0
      char buf[4096];
1420
0
      int pos, nread;
1421
0
      struct linux_dirent64 *de;
1422
1423
0
      while ((nread = syscall (SYS_getdents64, dir_fd, buf, sizeof(buf))) > 0)
1424
0
        {
1425
0
          for (pos = 0; pos < nread; pos += de->d_reclen)
1426
0
            {
1427
0
              de = (struct linux_dirent64 *)(buf + pos);
1428
1429
0
              fd = filename_to_fd (de->d_name);
1430
0
              if (fd < 0 || fd == dir_fd)
1431
0
                  continue;
1432
1433
0
              if ((res = cb (data, fd)) != 0)
1434
0
                  break;
1435
0
            }
1436
0
        }
1437
1438
0
      g_close (dir_fd, NULL);
1439
0
      return res;
1440
0
    }
1441
1442
  /* If /proc is not mounted or not accessible we fall back to the old
1443
   * rlimit trick. */
1444
1445
0
#endif
1446
1447
#if defined(__sun__) && defined(F_PREVFD) && defined(F_NEXTFD)
1448
/*
1449
 * Solaris 11.4 has a signal-safe way which allows
1450
 * us to find all file descriptors in a process.
1451
 *
1452
 * fcntl(fd, F_NEXTFD, maxfd)
1453
 * - returns the first allocated file descriptor <= maxfd  > fd.
1454
 *
1455
 * fcntl(fd, F_PREVFD)
1456
 * - return highest allocated file descriptor < fd.
1457
 */
1458
1459
  open_max = fcntl (INT_MAX, F_PREVFD); /* find the maximum fd */
1460
  if (open_max < 0) /* No open files */
1461
    return 0;
1462
1463
  for (fd = -1; (fd = fcntl (fd, F_NEXTFD, open_max)) != -1; )
1464
    if ((res = cb (data, fd)) != 0 || fd == open_max)
1465
      break;
1466
#else
1467
1468
#if 0 && defined(HAVE_SYS_RESOURCE_H)
1469
  /* Use getrlimit() function provided by the system if it is known to be
1470
   * async-signal safe.
1471
   *
1472
   * Currently there are no operating systems known to provide a safe
1473
   * implementation, so this section is not used for now.
1474
   */
1475
  if (getrlimit (RLIMIT_NOFILE, &rl) == 0 && rl.rlim_max != RLIM_INFINITY)
1476
    open_max = rl.rlim_max;
1477
#endif
1478
#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__APPLE__)
1479
  /* Use sysconf() function provided by the system if it is known to be
1480
   * async-signal safe.
1481
   *
1482
   * FreeBSD: sysconf() is included in the list of async-signal safe functions
1483
   * found in https://man.freebsd.org/sigaction(2).
1484
   *
1485
   * OpenBSD: sysconf() is included in the list of async-signal safe functions
1486
   * found in https://man.openbsd.org/sigaction.2.
1487
   * 
1488
   * Apple: sysconf() is included in the list of async-signal safe functions
1489
   * found in https://opensource.apple.com/source/xnu/xnu-517.12.7/bsd/man/man2/sigaction.2
1490
   */
1491
  if (open_max < 0)
1492
    open_max = sysconf (_SC_OPEN_MAX);
1493
#endif
1494
  /* Hardcoded fallback: the default process hard limit in Linux as of 2020 */
1495
0
  if (open_max < 0)
1496
0
    open_max = 4096;
1497
1498
0
  for (fd = 0; fd < open_max; fd++)
1499
0
      if ((res = cb (data, fd)) != 0)
1500
0
          break;
1501
0
#endif
1502
1503
0
  return res;
1504
0
#endif
1505
0
}
1506
1507
/* This function is called between fork() and exec() and hence must be
1508
 * async-signal-safe (see signal-safety(7)). */
1509
static int
1510
safe_fdwalk_set_cloexec (int lowfd)
1511
0
{
1512
#if defined(HAVE_CLOSE_RANGE) && defined(CLOSE_RANGE_CLOEXEC)
1513
  /* close_range() is available in Linux since kernel 5.9, and on FreeBSD at
1514
   * around the same time. It was designed for use in async-signal-safe
1515
   * situations: https://bugs.python.org/issue38061
1516
   *
1517
   * The `CLOSE_RANGE_CLOEXEC` flag was added in Linux 5.11, and is not yet
1518
   * present in FreeBSD.
1519
   *
1520
   * Handle ENOSYS in case it’s supported in libc but not the kernel; if so,
1521
   * fall back to safe_fdwalk(). Handle EINVAL in case `CLOSE_RANGE_CLOEXEC`
1522
   * is not supported. */
1523
  int ret = close_range (lowfd, G_MAXUINT, CLOSE_RANGE_CLOEXEC);
1524
  if (ret == 0 || !(errno == ENOSYS || errno == EINVAL))
1525
    return ret;
1526
#endif  /* HAVE_CLOSE_RANGE */
1527
0
  return safe_fdwalk (set_cloexec, GINT_TO_POINTER (lowfd));
1528
0
}
1529
1530
/* This function is called between fork() and exec() and hence must be
1531
 * async-signal-safe (see signal-safety(7)).
1532
 *
1533
 * On failure, `-1` will be returned and errno will be set. */
1534
static int
1535
safe_closefrom (int lowfd)
1536
0
{
1537
#if defined(__FreeBSD__) || defined(__OpenBSD__) || \
1538
  (defined(__sun__) && defined(F_CLOSEFROM))
1539
  /* Use closefrom function provided by the system if it is known to be
1540
   * async-signal safe.
1541
   *
1542
   * FreeBSD: closefrom is included in the list of async-signal safe functions
1543
   * found in https://man.freebsd.org/sigaction(2).
1544
   *
1545
   * OpenBSD: closefrom is not included in the list, but a direct system call
1546
   * should be safe to use.
1547
   *
1548
   * In Solaris as of 11.3 SRU 31, closefrom() is also a direct system call.
1549
   * On such systems, F_CLOSEFROM is defined.
1550
   */
1551
  (void) closefrom (lowfd);
1552
  return 0;
1553
#elif defined(__DragonFly__)
1554
  /* It is unclear whether closefrom function included in DragonFlyBSD libc_r
1555
   * is safe to use because it calls a lot of library functions. It is also
1556
   * unclear whether libc_r itself is still being used. Therefore, we do a
1557
   * direct system call here ourselves to avoid possible issues.
1558
   */
1559
  (void) syscall (SYS_closefrom, lowfd);
1560
  return 0;
1561
#elif defined(F_CLOSEM)
1562
  /* NetBSD and AIX have a special fcntl command which does the same thing as
1563
   * closefrom. NetBSD also includes closefrom function, which seems to be a
1564
   * simple wrapper of the fcntl command.
1565
   */
1566
  return fcntl (lowfd, F_CLOSEM);
1567
#else
1568
1569
#if defined(HAVE_CLOSE_RANGE)
1570
  /* close_range() is available in Linux since kernel 5.9, and on FreeBSD at
1571
   * around the same time. It was designed for use in async-signal-safe
1572
   * situations: https://bugs.python.org/issue38061
1573
   *
1574
   * Handle ENOSYS in case it’s supported in libc but not the kernel; if so,
1575
   * fall back to safe_fdwalk(). */
1576
  int ret = close_range (lowfd, G_MAXUINT, 0);
1577
  if (ret == 0 || errno != ENOSYS)
1578
    return ret;
1579
#endif  /* HAVE_CLOSE_RANGE */
1580
0
  return safe_fdwalk (close_func, GINT_TO_POINTER (lowfd));
1581
0
#endif
1582
0
}
1583
1584
/* This function is called between fork() and exec() and hence must be
1585
 * async-signal-safe (see signal-safety(7)). */
1586
static gint
1587
safe_dup2 (gint fd1, gint fd2)
1588
0
{
1589
0
  gint ret;
1590
1591
0
  do
1592
0
    ret = dup2 (fd1, fd2);
1593
0
  while (ret < 0 && (errno == EINTR || errno == EBUSY));
1594
1595
0
  return ret;
1596
0
}
1597
1598
/* This function is called between fork() and exec() and hence must be
1599
 * async-signal-safe (see signal-safety(7)). */
1600
static gint
1601
safe_open (const char *path, gint mode)
1602
0
{
1603
0
  gint ret;
1604
1605
0
  do
1606
0
    ret = open (path, mode);
1607
0
  while (ret < 0 && errno == EINTR);
1608
1609
0
  return ret;
1610
0
}
1611
1612
enum
1613
{
1614
  CHILD_CHDIR_FAILED,
1615
  CHILD_EXEC_FAILED,
1616
  CHILD_OPEN_FAILED,
1617
  CHILD_DUP2_FAILED,
1618
  CHILD_FORK_FAILED,
1619
  CHILD_CLOSE_FAILED,
1620
};
1621
1622
/* This function is called between fork() and exec() and hence must be
1623
 * async-signal-safe (see signal-safety(7)) until it calls exec().
1624
 *
1625
 * All callers must guarantee that @argv and @argv[0] are non-NULL. */
1626
static void
1627
do_exec (gint                  child_err_report_fd,
1628
         gint                  stdin_fd,
1629
         gint                  stdout_fd,
1630
         gint                  stderr_fd,
1631
         gint                 *source_fds,
1632
         const gint           *target_fds,
1633
         gsize                 n_fds,
1634
         const gchar          *working_directory,
1635
         const gchar * const  *argv,
1636
         gchar               **argv_buffer,
1637
         gsize                 argv_buffer_len,
1638
         const gchar * const  *envp,
1639
         gboolean              close_descriptors,
1640
         const gchar          *search_path,
1641
         gchar                *search_path_buffer,
1642
         gsize                 search_path_buffer_len,
1643
         gboolean              stdout_to_null,
1644
         gboolean              stderr_to_null,
1645
         gboolean              child_inherits_stdin,
1646
         gboolean              file_and_argv_zero,
1647
         GSpawnChildSetupFunc  child_setup,
1648
         gpointer              user_data)
1649
0
{
1650
0
  gsize i;
1651
0
  gint max_target_fd = 0;
1652
1653
0
  if (working_directory && chdir (working_directory) < 0)
1654
0
    write_err_and_exit (child_err_report_fd,
1655
0
                        CHILD_CHDIR_FAILED);
1656
  
1657
  /* Redirect pipes as required */
1658
0
  if (stdin_fd >= 0)
1659
0
    {
1660
0
      if (safe_dup2 (stdin_fd, 0) < 0)
1661
0
        write_err_and_exit (child_err_report_fd,
1662
0
                            CHILD_DUP2_FAILED);
1663
1664
0
      if (!((stdout_fd >= 0 || stdout_to_null) && stdin_fd == 1) &&
1665
0
          !((stderr_fd >= 0 || stderr_to_null) && stdin_fd == 2))
1666
0
        set_cloexec (GINT_TO_POINTER(0), stdin_fd);
1667
0
    }
1668
0
  else if (!child_inherits_stdin)
1669
0
    {
1670
      /* Keep process from blocking on a read of stdin */
1671
0
      gint read_null = safe_open ("/dev/null", O_RDONLY);
1672
0
      if (read_null < 0)
1673
0
        write_err_and_exit (child_err_report_fd,
1674
0
                            CHILD_OPEN_FAILED);
1675
0
      if (safe_dup2 (read_null, 0) < 0)
1676
0
        write_err_and_exit (child_err_report_fd,
1677
0
                            CHILD_DUP2_FAILED);
1678
0
      close_and_invalidate (&read_null);
1679
0
    }
1680
1681
0
  if (stdout_fd >= 0)
1682
0
    {
1683
0
      if (safe_dup2 (stdout_fd, 1) < 0)
1684
0
        write_err_and_exit (child_err_report_fd,
1685
0
                            CHILD_DUP2_FAILED);
1686
1687
0
      if (!((stdin_fd >= 0 || !child_inherits_stdin) && stdout_fd == 0) &&
1688
0
          !((stderr_fd >= 0 || stderr_to_null) && stdout_fd == 2))
1689
0
        set_cloexec (GINT_TO_POINTER(0), stdout_fd);
1690
0
    }
1691
0
  else if (stdout_to_null)
1692
0
    {
1693
0
      gint write_null = safe_open ("/dev/null", O_WRONLY);
1694
0
      if (write_null < 0)
1695
0
        write_err_and_exit (child_err_report_fd,
1696
0
                            CHILD_OPEN_FAILED);
1697
0
      if (safe_dup2 (write_null, 1) < 0)
1698
0
        write_err_and_exit (child_err_report_fd,
1699
0
                            CHILD_DUP2_FAILED);
1700
0
      close_and_invalidate (&write_null);
1701
0
    }
1702
1703
0
  if (stderr_fd >= 0)
1704
0
    {
1705
0
      if (safe_dup2 (stderr_fd, 2) < 0)
1706
0
        write_err_and_exit (child_err_report_fd,
1707
0
                            CHILD_DUP2_FAILED);
1708
1709
0
      if (!((stdin_fd >= 0 || !child_inherits_stdin) && stderr_fd == 0) &&
1710
0
          !((stdout_fd >= 0 || stdout_to_null) && stderr_fd == 1))
1711
0
        set_cloexec (GINT_TO_POINTER(0), stderr_fd);
1712
0
    }
1713
0
  else if (stderr_to_null)
1714
0
    {
1715
0
      gint write_null = safe_open ("/dev/null", O_WRONLY);
1716
0
      if (write_null < 0)
1717
0
        write_err_and_exit (child_err_report_fd,
1718
0
                            CHILD_OPEN_FAILED);
1719
0
      if (safe_dup2 (write_null, 2) < 0)
1720
0
        write_err_and_exit (child_err_report_fd,
1721
0
                            CHILD_DUP2_FAILED);
1722
0
      close_and_invalidate (&write_null);
1723
0
    }
1724
1725
  /* Close all file descriptors but stdin, stdout and stderr, and any of source_fds,
1726
   * before we exec. Note that this includes
1727
   * child_err_report_fd, which keeps the parent from blocking
1728
   * forever on the other end of that pipe.
1729
   */
1730
0
  if (close_descriptors)
1731
0
    {
1732
0
      if (child_setup == NULL && n_fds == 0)
1733
0
        {
1734
0
          if (safe_dup2 (child_err_report_fd, 3) < 0)
1735
0
            write_err_and_exit (child_err_report_fd, CHILD_DUP2_FAILED);
1736
0
          set_cloexec (GINT_TO_POINTER (0), 3);
1737
0
          if (safe_closefrom (4) < 0)
1738
0
            write_err_and_exit (child_err_report_fd, CHILD_CLOSE_FAILED);
1739
0
          child_err_report_fd = 3;
1740
0
        }
1741
0
      else
1742
0
        {
1743
0
          if (safe_fdwalk_set_cloexec (3) < 0)
1744
0
            write_err_and_exit (child_err_report_fd, CHILD_CLOSE_FAILED);
1745
0
        }
1746
0
    }
1747
0
  else
1748
0
    {
1749
      /* We need to do child_err_report_fd anyway */
1750
0
      set_cloexec (GINT_TO_POINTER (0), child_err_report_fd);
1751
0
    }
1752
1753
  /*
1754
   * Work through the @source_fds and @target_fds mapping.
1755
   *
1756
   * Based on code originally derived from
1757
   * gnome-terminal:src/terminal-screen.c:terminal_screen_child_setup(),
1758
   * used under the LGPLv2+ with permission from author. (The code has
1759
   * since migrated to vte:src/spawn.cc:SpawnContext::exec and is no longer
1760
   * terribly similar to what we have here.)
1761
   */
1762
1763
0
  if (n_fds > 0)
1764
0
    {
1765
0
      for (i = 0; i < n_fds; i++)
1766
0
        max_target_fd = MAX (max_target_fd, target_fds[i]);
1767
1768
0
      if (max_target_fd == G_MAXINT)
1769
0
        {
1770
0
          errno = EINVAL;
1771
0
          write_err_and_exit (child_err_report_fd, CHILD_DUP2_FAILED);
1772
0
        }
1773
1774
      /* If we're doing remapping fd assignments, we need to handle
1775
       * the case where the user has specified e.g. 5 -> 4, 4 -> 6.
1776
       * We do this by duping all source fds, taking care to ensure the new
1777
       * fds are larger than any target fd to avoid introducing new conflicts.
1778
       */
1779
0
      for (i = 0; i < n_fds; i++)
1780
0
        {
1781
0
          if (source_fds[i] != target_fds[i])
1782
0
            {
1783
0
              source_fds[i] = dupfd_cloexec (source_fds[i], max_target_fd + 1);
1784
0
              if (source_fds[i] < 0)
1785
0
                write_err_and_exit (child_err_report_fd, CHILD_DUP2_FAILED);
1786
0
            }
1787
0
        }
1788
1789
0
      for (i = 0; i < n_fds; i++)
1790
0
        {
1791
          /* For basic fd assignments (where source == target), we can just
1792
           * unset FD_CLOEXEC.
1793
           */
1794
0
          if (source_fds[i] == target_fds[i])
1795
0
            {
1796
0
              unset_cloexec (source_fds[i]);
1797
0
            }
1798
0
          else
1799
0
            {
1800
              /* If any of the @target_fds conflict with @child_err_report_fd,
1801
               * dup it so it doesn’t get conflated.
1802
               */
1803
0
              if (target_fds[i] == child_err_report_fd)
1804
0
                {
1805
0
                  child_err_report_fd = dupfd_cloexec (child_err_report_fd, max_target_fd + 1);
1806
0
                  if (child_err_report_fd < 0)
1807
0
                    write_err_and_exit (child_err_report_fd, CHILD_DUP2_FAILED);
1808
0
                }
1809
1810
0
              if (safe_dup2 (source_fds[i], target_fds[i]) < 0)
1811
0
                write_err_and_exit (child_err_report_fd, CHILD_DUP2_FAILED);
1812
1813
0
              close_and_invalidate (&source_fds[i]);
1814
0
            }
1815
0
        }
1816
0
    }
1817
1818
  /* Call user function just before we exec */
1819
0
  if (child_setup)
1820
0
    {
1821
0
      (* child_setup) (user_data);
1822
0
    }
1823
1824
0
  g_execute (argv[0],
1825
0
             (gchar **) (file_and_argv_zero ? argv + 1 : argv),
1826
0
             argv_buffer, argv_buffer_len,
1827
0
             (gchar **) envp, search_path, search_path_buffer, search_path_buffer_len);
1828
1829
  /* Exec failed */
1830
0
  write_err_and_exit (child_err_report_fd,
1831
0
                      CHILD_EXEC_FAILED);
1832
0
}
1833
1834
static gboolean
1835
read_ints (int      fd,
1836
           gint*    buf,
1837
           gint     n_ints_in_buf,    
1838
           gint    *n_ints_read,      
1839
           GError **error)
1840
0
{
1841
0
  gsize bytes = 0;    
1842
  
1843
0
  while (TRUE)
1844
0
    {
1845
0
      gssize chunk;    
1846
1847
0
      if (bytes >= sizeof(gint)*2)
1848
0
        break; /* give up, who knows what happened, should not be
1849
                * possible.
1850
                */
1851
          
1852
0
    again:
1853
0
      chunk = read (fd,
1854
0
                    ((gchar*)buf) + bytes,
1855
0
                    sizeof(gint) * n_ints_in_buf - bytes);
1856
0
      if (chunk < 0 && errno == EINTR)
1857
0
        goto again;
1858
          
1859
0
      if (chunk < 0)
1860
0
        {
1861
0
          int errsv = errno;
1862
1863
          /* Some weird shit happened, bail out */
1864
0
          g_set_error (error,
1865
0
                       G_SPAWN_ERROR,
1866
0
                       G_SPAWN_ERROR_FAILED,
1867
0
                       _("Failed to read from child pipe (%s)"),
1868
0
                       g_strerror (errsv));
1869
1870
0
          return FALSE;
1871
0
        }
1872
0
      else if (chunk == 0)
1873
0
        break; /* EOF */
1874
0
      else /* chunk > 0 */
1875
0
  bytes += chunk;
1876
0
    }
1877
1878
0
  *n_ints_read = (gint)(bytes / sizeof(gint));
1879
1880
0
  return TRUE;
1881
0
}
1882
1883
#ifdef POSIX_SPAWN_AVAILABLE
1884
static gboolean
1885
do_posix_spawn (const gchar * const *argv,
1886
                const gchar * const *envp,
1887
                gboolean    search_path,
1888
                gboolean    stdout_to_null,
1889
                gboolean    stderr_to_null,
1890
                gboolean    child_inherits_stdin,
1891
                gboolean    file_and_argv_zero,
1892
                GPid       *child_pid,
1893
                gint       *child_close_fds,
1894
                gint        stdin_fd,
1895
                gint        stdout_fd,
1896
                gint        stderr_fd,
1897
                const gint *source_fds,
1898
                const gint *target_fds,
1899
                gsize       n_fds)
1900
0
{
1901
0
  pid_t pid;
1902
0
  gint *duped_source_fds = NULL;
1903
0
  gint max_target_fd = 0;
1904
0
  const gchar * const *argv_pass;
1905
0
  posix_spawnattr_t attr;
1906
0
  posix_spawn_file_actions_t file_actions;
1907
0
  gint parent_close_fds[3];
1908
0
  gsize num_parent_close_fds = 0;
1909
0
  GSList *child_close = NULL;
1910
0
  GSList *elem;
1911
0
  sigset_t mask;
1912
0
  gsize i;
1913
0
  int r;
1914
1915
0
  g_assert (argv != NULL && argv[0] != NULL);
1916
1917
0
  if (*argv[0] == '\0')
1918
0
    {
1919
      /* We check the simple case first. */
1920
0
      return ENOENT;
1921
0
    }
1922
1923
0
  r = posix_spawnattr_init (&attr);
1924
0
  if (r != 0)
1925
0
    return r;
1926
1927
0
  if (child_close_fds)
1928
0
    {
1929
0
      int i = -1;
1930
0
      while (child_close_fds[++i] != -1)
1931
0
        child_close = g_slist_prepend (child_close,
1932
0
                                       GINT_TO_POINTER (child_close_fds[i]));
1933
0
    }
1934
1935
0
  r = posix_spawnattr_setflags (&attr, POSIX_SPAWN_SETSIGDEF);
1936
0
  if (r != 0)
1937
0
    goto out_free_spawnattr;
1938
1939
  /* Reset some signal handlers that we may use */
1940
0
  sigemptyset (&mask);
1941
0
  sigaddset (&mask, SIGCHLD);
1942
0
  sigaddset (&mask, SIGINT);
1943
0
  sigaddset (&mask, SIGTERM);
1944
0
  sigaddset (&mask, SIGHUP);
1945
1946
0
  r = posix_spawnattr_setsigdefault (&attr, &mask);
1947
0
  if (r != 0)
1948
0
    goto out_free_spawnattr;
1949
1950
0
  r = posix_spawn_file_actions_init (&file_actions);
1951
0
  if (r != 0)
1952
0
    goto out_free_spawnattr;
1953
1954
  /* Redirect pipes as required */
1955
1956
0
  if (stdin_fd >= 0)
1957
0
    {
1958
0
      r = posix_spawn_file_actions_adddup2 (&file_actions, stdin_fd, 0);
1959
0
      if (r != 0)
1960
0
        goto out_close_fds;
1961
1962
0
      if (!g_slist_find (child_close, GINT_TO_POINTER (stdin_fd)))
1963
0
        child_close = g_slist_prepend (child_close, GINT_TO_POINTER (stdin_fd));
1964
0
    }
1965
0
  else if (!child_inherits_stdin)
1966
0
    {
1967
      /* Keep process from blocking on a read of stdin */
1968
0
      gint read_null = safe_open ("/dev/null", O_RDONLY | O_CLOEXEC);
1969
0
      g_assert (read_null != -1);
1970
0
      parent_close_fds[num_parent_close_fds++] = read_null;
1971
1972
#ifndef HAVE_O_CLOEXEC
1973
      fcntl (read_null, F_SETFD, FD_CLOEXEC);
1974
#endif
1975
1976
0
      r = posix_spawn_file_actions_adddup2 (&file_actions, read_null, 0);
1977
0
      if (r != 0)
1978
0
        goto out_close_fds;
1979
0
    }
1980
1981
0
  if (stdout_fd >= 0)
1982
0
    {
1983
0
      r = posix_spawn_file_actions_adddup2 (&file_actions, stdout_fd, 1);
1984
0
      if (r != 0)
1985
0
        goto out_close_fds;
1986
1987
0
      if (!g_slist_find (child_close, GINT_TO_POINTER (stdout_fd)))
1988
0
        child_close = g_slist_prepend (child_close, GINT_TO_POINTER (stdout_fd));
1989
0
    }
1990
0
  else if (stdout_to_null)
1991
0
    {
1992
0
      gint write_null = safe_open ("/dev/null", O_WRONLY | O_CLOEXEC);
1993
0
      g_assert (write_null != -1);
1994
0
      parent_close_fds[num_parent_close_fds++] = write_null;
1995
1996
#ifndef HAVE_O_CLOEXEC
1997
      fcntl (write_null, F_SETFD, FD_CLOEXEC);
1998
#endif
1999
2000
0
      r = posix_spawn_file_actions_adddup2 (&file_actions, write_null, 1);
2001
0
      if (r != 0)
2002
0
        goto out_close_fds;
2003
0
    }
2004
2005
0
  if (stderr_fd >= 0)
2006
0
    {
2007
0
      r = posix_spawn_file_actions_adddup2 (&file_actions, stderr_fd, 2);
2008
0
      if (r != 0)
2009
0
        goto out_close_fds;
2010
2011
0
      if (!g_slist_find (child_close, GINT_TO_POINTER (stderr_fd)))
2012
0
        child_close = g_slist_prepend (child_close, GINT_TO_POINTER (stderr_fd));
2013
0
    }
2014
0
  else if (stderr_to_null)
2015
0
    {
2016
0
      gint write_null = safe_open ("/dev/null", O_WRONLY | O_CLOEXEC);
2017
0
      g_assert (write_null != -1);
2018
0
      parent_close_fds[num_parent_close_fds++] = write_null;
2019
2020
#ifndef HAVE_O_CLOEXEC
2021
      fcntl (write_null, F_SETFD, FD_CLOEXEC);
2022
#endif
2023
2024
0
      r = posix_spawn_file_actions_adddup2 (&file_actions, write_null, 2);
2025
0
      if (r != 0)
2026
0
        goto out_close_fds;
2027
0
    }
2028
2029
  /* If source_fds[i] != target_fds[i], we need to handle the case
2030
   * where the user has specified, e.g., 5 -> 4, 4 -> 6. We do this
2031
   * by duping the source fds, taking care to ensure the new fds are
2032
   * larger than any target fd to avoid introducing new conflicts.
2033
   *
2034
   * If source_fds[i] == target_fds[i], then we just need to leak
2035
   * the fd into the child process, which we *could* do by temporarily
2036
   * unsetting CLOEXEC and then setting it again after we spawn if
2037
   * it was originally set. POSIX requires that the addup2 action unset
2038
   * CLOEXEC if source and target are identical, so you'd think doing it
2039
   * manually wouldn't be needed, but unfortunately as of 2021 many
2040
   * libcs still don't do so. Example nonconforming libcs:
2041
   *  Bionic: https://android.googlesource.com/platform/bionic/+/f6e5b582604715729b09db3e36a7aeb8c24b36a4/libc/bionic/spawn.cpp#71
2042
   *  uclibc-ng: https://cgit.uclibc-ng.org/cgi/cgit/uclibc-ng.git/tree/librt/spawn.c?id=7c36bcae09d66bbaa35cbb02253ae0556f42677e#n88
2043
   *
2044
   * Anyway, unsetting CLOEXEC ourselves would open a small race window
2045
   * where the fd could be inherited into a child process if another
2046
   * thread spawns something at the same time, because we have not
2047
   * called fork() and are multithreaded here. This race is avoidable by
2048
   * using dupfd_cloexec, which we already have to do to handle the
2049
   * source_fds[i] != target_fds[i] case. So let's always do it!
2050
   */
2051
2052
0
  for (i = 0; i < n_fds; i++)
2053
0
    max_target_fd = MAX (max_target_fd, target_fds[i]);
2054
2055
0
  if (max_target_fd == G_MAXINT)
2056
0
    goto out_close_fds;
2057
2058
0
  duped_source_fds = g_new (gint, n_fds);
2059
0
  for (i = 0; i < n_fds; i++)
2060
0
    {
2061
0
      duped_source_fds[i] = dupfd_cloexec (source_fds[i], max_target_fd + 1);
2062
0
      if (duped_source_fds[i] < 0)
2063
0
        goto out_close_fds;
2064
0
    }
2065
2066
0
  for (i = 0; i < n_fds; i++)
2067
0
    {
2068
0
      r = posix_spawn_file_actions_adddup2 (&file_actions, duped_source_fds[i], target_fds[i]);
2069
0
      if (r != 0)
2070
0
        goto out_close_fds;
2071
0
    }
2072
2073
  /* Intentionally close the fds in the child as the last file action,
2074
   * having been careful not to add the same fd to this list twice.
2075
   *
2076
   * This is important to allow (e.g.) for the same fd to be passed as stdout
2077
   * and stderr (we must not close it before we have dupped it in both places,
2078
   * and we must not attempt to close it twice).
2079
   */
2080
0
  for (elem = child_close; elem != NULL; elem = elem->next)
2081
0
    {
2082
0
      r = posix_spawn_file_actions_addclose (&file_actions,
2083
0
                                             GPOINTER_TO_INT (elem->data));
2084
0
      if (r != 0)
2085
0
        goto out_close_fds;
2086
0
    }
2087
2088
0
  argv_pass = file_and_argv_zero ? argv + 1 : argv;
2089
0
  if (envp == NULL)
2090
0
    envp = (const gchar * const *) environ;
2091
2092
  /* Don't search when it contains a slash. */
2093
0
  if (!search_path || strchr (argv[0], '/') != NULL)
2094
0
    r = posix_spawn (&pid, argv[0], &file_actions, &attr, (char * const *) argv_pass, (char * const *) envp);
2095
0
  else
2096
0
    r = posix_spawnp (&pid, argv[0], &file_actions, &attr, (char * const *) argv_pass, (char * const *) envp);
2097
2098
0
  if (r == 0 && child_pid != NULL)
2099
0
    *child_pid = pid;
2100
2101
0
out_close_fds:
2102
0
  for (i = 0; i < num_parent_close_fds; i++)
2103
0
    close_and_invalidate (&parent_close_fds [i]);
2104
2105
0
  if (duped_source_fds != NULL)
2106
0
    {
2107
0
      for (i = 0; i < n_fds; i++)
2108
0
        close_and_invalidate (&duped_source_fds[i]);
2109
0
      g_free (duped_source_fds);
2110
0
    }
2111
2112
0
  posix_spawn_file_actions_destroy (&file_actions);
2113
0
out_free_spawnattr:
2114
0
  posix_spawnattr_destroy (&attr);
2115
0
  g_slist_free (child_close);
2116
2117
0
  return r;
2118
0
}
2119
#endif /* POSIX_SPAWN_AVAILABLE */
2120
2121
static gboolean
2122
fork_exec (gboolean              intermediate_child,
2123
           const gchar          *working_directory,
2124
           const gchar * const  *argv,
2125
           const gchar * const  *envp,
2126
           gboolean              close_descriptors,
2127
           gboolean              search_path,
2128
           gboolean              search_path_from_envp,
2129
           gboolean              stdout_to_null,
2130
           gboolean              stderr_to_null,
2131
           gboolean              child_inherits_stdin,
2132
           gboolean              file_and_argv_zero,
2133
           gboolean              cloexec_pipes,
2134
           GSpawnChildSetupFunc  child_setup,
2135
           gpointer              user_data,
2136
           GPid                 *child_pid,
2137
           gint                 *stdin_pipe_out,
2138
           gint                 *stdout_pipe_out,
2139
           gint                 *stderr_pipe_out,
2140
           gint                  stdin_fd,
2141
           gint                  stdout_fd,
2142
           gint                  stderr_fd,
2143
           const gint           *source_fds,
2144
           const gint           *target_fds,
2145
           gsize                 n_fds,
2146
           GError              **error)
2147
0
{
2148
0
  GPid pid = -1;
2149
0
  gint child_err_report_pipe[2] = { -1, -1 };
2150
0
  gint child_pid_report_pipe[2] = { -1, -1 };
2151
0
  guint pipe_flags = cloexec_pipes ? FD_CLOEXEC : 0;
2152
0
  gint status;
2153
0
  const gchar *chosen_search_path;
2154
0
  gchar *search_path_buffer = NULL;
2155
0
  gchar *search_path_buffer_heap = NULL;
2156
0
  gsize search_path_buffer_len = 0;
2157
0
  gchar **argv_buffer = NULL;
2158
0
  gchar **argv_buffer_heap = NULL;
2159
0
  gsize argv_buffer_len = 0;
2160
0
  gint stdin_pipe[2] = { -1, -1 };
2161
0
  gint stdout_pipe[2] = { -1, -1 };
2162
0
  gint stderr_pipe[2] = { -1, -1 };
2163
0
  gint child_close_fds[4] = { -1, -1, -1, -1 };
2164
0
  gint n_child_close_fds = 0;
2165
0
  gint *source_fds_copy = NULL;
2166
2167
0
  g_assert (argv != NULL && argv[0] != NULL);
2168
0
  g_assert (stdin_pipe_out == NULL || stdin_fd < 0);
2169
0
  g_assert (stdout_pipe_out == NULL || stdout_fd < 0);
2170
0
  g_assert (stderr_pipe_out == NULL || stderr_fd < 0);
2171
2172
  /* If pipes have been requested, open them */
2173
0
  if (stdin_pipe_out != NULL)
2174
0
    {
2175
0
      if (!g_unix_open_pipe (stdin_pipe, pipe_flags, error))
2176
0
        goto cleanup_and_fail;
2177
0
      child_close_fds[n_child_close_fds++] = stdin_pipe[1];
2178
0
      stdin_fd = stdin_pipe[0];
2179
0
    }
2180
2181
0
  if (stdout_pipe_out != NULL)
2182
0
    {
2183
0
      if (!g_unix_open_pipe (stdout_pipe, pipe_flags, error))
2184
0
        goto cleanup_and_fail;
2185
0
      child_close_fds[n_child_close_fds++] = stdout_pipe[0];
2186
0
      stdout_fd = stdout_pipe[1];
2187
0
    }
2188
2189
0
  if (stderr_pipe_out != NULL)
2190
0
    {
2191
0
      if (!g_unix_open_pipe (stderr_pipe, pipe_flags, error))
2192
0
        goto cleanup_and_fail;
2193
0
      child_close_fds[n_child_close_fds++] = stderr_pipe[0];
2194
0
      stderr_fd = stderr_pipe[1];
2195
0
    }
2196
2197
0
  child_close_fds[n_child_close_fds++] = -1;
2198
2199
0
#ifdef POSIX_SPAWN_AVAILABLE
2200
0
  if (!intermediate_child && working_directory == NULL && !close_descriptors &&
2201
0
      !search_path_from_envp && child_setup == NULL)
2202
0
    {
2203
0
      g_trace_mark (G_TRACE_CURRENT_TIME, 0,
2204
0
                    "GLib", "posix_spawn",
2205
0
                    "%s", argv[0]);
2206
2207
0
      status = do_posix_spawn (argv,
2208
0
                               envp,
2209
0
                               search_path,
2210
0
                               stdout_to_null,
2211
0
                               stderr_to_null,
2212
0
                               child_inherits_stdin,
2213
0
                               file_and_argv_zero,
2214
0
                               child_pid,
2215
0
                               child_close_fds,
2216
0
                               stdin_fd,
2217
0
                               stdout_fd,
2218
0
                               stderr_fd,
2219
0
                               source_fds,
2220
0
                               target_fds,
2221
0
                               n_fds);
2222
0
      if (status == 0)
2223
0
        goto success;
2224
2225
0
      if (status != ENOEXEC)
2226
0
        {
2227
0
          g_set_error (error,
2228
0
                       G_SPAWN_ERROR,
2229
0
                       G_SPAWN_ERROR_FAILED,
2230
0
                       _("Failed to spawn child process “%s” (%s)"),
2231
0
                       argv[0],
2232
0
                       g_strerror (status));
2233
0
          goto cleanup_and_fail;
2234
0
       }
2235
2236
      /* posix_spawn is not intended to support script execution. It does in
2237
       * some situations on some glibc versions, but that will be fixed.
2238
       * So if it fails with ENOEXEC, we fall through to the regular
2239
       * gspawn codepath so that script execution can be attempted,
2240
       * per standard gspawn behaviour. */
2241
0
      g_debug ("posix_spawn failed (ENOEXEC), fall back to regular gspawn");
2242
0
    }
2243
0
  else
2244
0
    {
2245
0
      g_trace_mark (G_TRACE_CURRENT_TIME, 0,
2246
0
                    "GLib", "fork",
2247
0
                    "posix_spawn avoided %s%s%s%s%s",
2248
0
                    !intermediate_child ? "" : "(automatic reaping requested) ",
2249
0
                    working_directory == NULL ? "" : "(workdir specified) ",
2250
0
                    !close_descriptors ? "" : "(fd close requested) ",
2251
0
                    !search_path_from_envp ? "" : "(using envp for search path) ",
2252
0
                    child_setup == NULL ? "" : "(child_setup specified) ");
2253
0
    }
2254
0
#endif /* POSIX_SPAWN_AVAILABLE */
2255
2256
  /* Choose a search path. This has to be done before calling fork()
2257
   * as getenv() isn’t async-signal-safe (see `man 7 signal-safety`). */
2258
0
  chosen_search_path = NULL;
2259
0
  if (search_path_from_envp)
2260
0
    chosen_search_path = g_environ_getenv ((gchar **) envp, "PATH");
2261
0
  if (search_path && chosen_search_path == NULL)
2262
0
    chosen_search_path = g_getenv ("PATH");
2263
2264
0
  if ((search_path || search_path_from_envp) && chosen_search_path == NULL)
2265
0
    {
2266
      /* There is no 'PATH' in the environment.  The default
2267
       * * search path in libc is the current directory followed by
2268
       * * the path 'confstr' returns for '_CS_PATH'.
2269
       * */
2270
2271
      /* In GLib we put . last, for security, and don't use the
2272
       * * unportable confstr(); UNIX98 does not actually specify
2273
       * * what to search if PATH is unset. POSIX may, dunno.
2274
       * */
2275
2276
0
      chosen_search_path = "/bin:/usr/bin:.";
2277
0
    }
2278
2279
0
  if (search_path || search_path_from_envp)
2280
0
    g_assert (chosen_search_path != NULL);
2281
0
  else
2282
0
    g_assert (chosen_search_path == NULL);
2283
2284
  /* Allocate a buffer which the fork()ed child can use to assemble potential
2285
   * paths for the binary to exec(), combining the argv[0] and elements from
2286
   * the chosen_search_path. This can’t be done in the child because malloc()
2287
   * (or alloca()) are not async-signal-safe (see `man 7 signal-safety`).
2288
   *
2289
   * Add 2 for the nul terminator and a leading `/`. */
2290
0
  if (chosen_search_path != NULL)
2291
0
    {
2292
0
      search_path_buffer_len = strlen (chosen_search_path) + strlen (argv[0]) + 2;
2293
0
      if (search_path_buffer_len < 4000)
2294
0
        {
2295
          /* Prefer small stack allocations to avoid valgrind leak warnings
2296
           * in forked child. The 4000B cutoff is arbitrary. */
2297
0
          search_path_buffer = g_alloca (search_path_buffer_len);
2298
0
        }
2299
0
      else
2300
0
        {
2301
0
          search_path_buffer_heap = g_malloc (search_path_buffer_len);
2302
0
          search_path_buffer = search_path_buffer_heap;
2303
0
        }
2304
0
    }
2305
2306
0
  if (search_path || search_path_from_envp)
2307
0
    g_assert (search_path_buffer != NULL);
2308
0
  else
2309
0
    g_assert (search_path_buffer == NULL);
2310
2311
  /* And allocate a buffer which is 2 elements longer than @argv, so that if
2312
   * script_execute() has to be called later on, it can build a wrapper argv
2313
   * array in this buffer. */
2314
0
  argv_buffer_len = g_strv_length ((gchar **) argv) + 2;
2315
0
  if (argv_buffer_len < 4000 / sizeof (gchar *))
2316
0
    {
2317
      /* Prefer small stack allocations to avoid valgrind leak warnings
2318
       * in forked child. The 4000B cutoff is arbitrary. */
2319
0
      argv_buffer = g_newa (gchar *, argv_buffer_len);
2320
0
    }
2321
0
  else
2322
0
    {
2323
0
      argv_buffer_heap = g_new (gchar *, argv_buffer_len);
2324
0
      argv_buffer = argv_buffer_heap;
2325
0
    }
2326
2327
  /* And one to hold a copy of @source_fds for later manipulation in do_exec(). */
2328
0
  source_fds_copy = g_new (int, n_fds);
2329
0
  if (n_fds > 0)
2330
0
    memcpy (source_fds_copy, source_fds, sizeof (*source_fds) * n_fds);
2331
2332
0
  if (!g_unix_open_pipe (child_err_report_pipe, pipe_flags, error))
2333
0
    goto cleanup_and_fail;
2334
2335
0
  if (intermediate_child && !g_unix_open_pipe (child_pid_report_pipe, pipe_flags, error))
2336
0
    goto cleanup_and_fail;
2337
  
2338
0
  pid = fork ();
2339
2340
0
  if (pid < 0)
2341
0
    {
2342
0
      int errsv = errno;
2343
2344
0
      g_set_error (error,
2345
0
                   G_SPAWN_ERROR,
2346
0
                   G_SPAWN_ERROR_FORK,
2347
0
                   _("Failed to fork (%s)"),
2348
0
                   g_strerror (errsv));
2349
2350
0
      goto cleanup_and_fail;
2351
0
    }
2352
0
  else if (pid == 0)
2353
0
    {
2354
      /* Immediate child. This may or may not be the child that
2355
       * actually execs the new process.
2356
       */
2357
2358
      /* Reset some signal handlers that we may use */
2359
0
      signal (SIGCHLD, SIG_DFL);
2360
0
      signal (SIGINT, SIG_DFL);
2361
0
      signal (SIGTERM, SIG_DFL);
2362
0
      signal (SIGHUP, SIG_DFL);
2363
      
2364
      /* Be sure we crash if the parent exits
2365
       * and we write to the err_report_pipe
2366
       */
2367
0
      signal (SIGPIPE, SIG_DFL);
2368
2369
      /* Close the parent's end of the pipes;
2370
       * not needed in the close_descriptors case,
2371
       * though
2372
       */
2373
0
      close_and_invalidate (&child_err_report_pipe[0]);
2374
0
      close_and_invalidate (&child_pid_report_pipe[0]);
2375
0
      if (child_close_fds[0] != -1)
2376
0
        {
2377
0
           int i = -1;
2378
0
           while (child_close_fds[++i] != -1)
2379
0
             close_and_invalidate (&child_close_fds[i]);
2380
0
        }
2381
      
2382
0
      if (intermediate_child)
2383
0
        {
2384
          /* We need to fork an intermediate child that launches the
2385
           * final child. The purpose of the intermediate child
2386
           * is to exit, so we can waitpid() it immediately.
2387
           * Then the grandchild will not become a zombie.
2388
           */
2389
0
          GPid grandchild_pid;
2390
2391
0
          grandchild_pid = fork ();
2392
2393
0
          if (grandchild_pid < 0)
2394
0
            {
2395
              /* report -1 as child PID */
2396
0
              write_all (child_pid_report_pipe[1], &grandchild_pid,
2397
0
                         sizeof(grandchild_pid));
2398
              
2399
0
              write_err_and_exit (child_err_report_pipe[1],
2400
0
                                  CHILD_FORK_FAILED);              
2401
0
            }
2402
0
          else if (grandchild_pid == 0)
2403
0
            {
2404
0
              close_and_invalidate (&child_pid_report_pipe[1]);
2405
0
              do_exec (child_err_report_pipe[1],
2406
0
                       stdin_fd,
2407
0
                       stdout_fd,
2408
0
                       stderr_fd,
2409
0
                       source_fds_copy,
2410
0
                       target_fds,
2411
0
                       n_fds,
2412
0
                       working_directory,
2413
0
                       argv,
2414
0
                       argv_buffer,
2415
0
                       argv_buffer_len,
2416
0
                       envp,
2417
0
                       close_descriptors,
2418
0
                       chosen_search_path,
2419
0
                       search_path_buffer,
2420
0
                       search_path_buffer_len,
2421
0
                       stdout_to_null,
2422
0
                       stderr_to_null,
2423
0
                       child_inherits_stdin,
2424
0
                       file_and_argv_zero,
2425
0
                       child_setup,
2426
0
                       user_data);
2427
0
            }
2428
0
          else
2429
0
            {
2430
0
              write_all (child_pid_report_pipe[1], &grandchild_pid, sizeof(grandchild_pid));
2431
0
              close_and_invalidate (&child_pid_report_pipe[1]);
2432
              
2433
0
              _exit (0);
2434
0
            }
2435
0
        }
2436
0
      else
2437
0
        {
2438
          /* Just run the child.
2439
           */
2440
2441
0
          do_exec (child_err_report_pipe[1],
2442
0
                   stdin_fd,
2443
0
                   stdout_fd,
2444
0
                   stderr_fd,
2445
0
                   source_fds_copy,
2446
0
                   target_fds,
2447
0
                   n_fds,
2448
0
                   working_directory,
2449
0
                   argv,
2450
0
                   argv_buffer,
2451
0
                   argv_buffer_len,
2452
0
                   envp,
2453
0
                   close_descriptors,
2454
0
                   chosen_search_path,
2455
0
                   search_path_buffer,
2456
0
                   search_path_buffer_len,
2457
0
                   stdout_to_null,
2458
0
                   stderr_to_null,
2459
0
                   child_inherits_stdin,
2460
0
                   file_and_argv_zero,
2461
0
                   child_setup,
2462
0
                   user_data);
2463
0
        }
2464
0
    }
2465
0
  else
2466
0
    {
2467
      /* Parent */
2468
      
2469
0
      gint buf[2];
2470
0
      gint n_ints = 0;    
2471
2472
      /* Close the uncared-about ends of the pipes */
2473
0
      close_and_invalidate (&child_err_report_pipe[1]);
2474
0
      close_and_invalidate (&child_pid_report_pipe[1]);
2475
2476
      /* If we had an intermediate child, reap it */
2477
0
      if (intermediate_child)
2478
0
        {
2479
0
        wait_again:
2480
0
          if (waitpid (pid, &status, 0) < 0)
2481
0
            {
2482
0
              if (errno == EINTR)
2483
0
                goto wait_again;
2484
0
              else if (errno == ECHILD)
2485
0
                ; /* do nothing, child already reaped */
2486
0
              else
2487
0
                g_warning ("waitpid() should not fail in 'fork_exec'");
2488
0
            }
2489
0
        }
2490
      
2491
2492
0
      if (!read_ints (child_err_report_pipe[0],
2493
0
                      buf, 2, &n_ints,
2494
0
                      error))
2495
0
        goto cleanup_and_fail;
2496
        
2497
0
      if (n_ints >= 2)
2498
0
        {
2499
          /* Error from the child. */
2500
2501
0
          switch (buf[0])
2502
0
            {
2503
0
            case CHILD_CHDIR_FAILED:
2504
0
              g_set_error (error,
2505
0
                           G_SPAWN_ERROR,
2506
0
                           G_SPAWN_ERROR_CHDIR,
2507
0
                           _("Failed to change to directory “%s” (%s)"),
2508
0
                           working_directory,
2509
0
                           g_strerror (buf[1]));
2510
2511
0
              break;
2512
              
2513
0
            case CHILD_EXEC_FAILED:
2514
0
              g_set_error (error,
2515
0
                           G_SPAWN_ERROR,
2516
0
                           _g_spawn_exec_err_to_g_error (buf[1]),
2517
0
                           _("Failed to execute child process “%s” (%s)"),
2518
0
                           argv[0],
2519
0
                           g_strerror (buf[1]));
2520
2521
0
              break;
2522
2523
0
            case CHILD_OPEN_FAILED:
2524
0
              g_set_error (error,
2525
0
                           G_SPAWN_ERROR,
2526
0
                           G_SPAWN_ERROR_FAILED,
2527
0
                           _("Failed to open file to remap file descriptor (%s)"),
2528
0
                           g_strerror (buf[1]));
2529
0
              break;
2530
2531
0
            case CHILD_DUP2_FAILED:
2532
0
              g_set_error (error,
2533
0
                           G_SPAWN_ERROR,
2534
0
                           G_SPAWN_ERROR_FAILED,
2535
0
                           _("Failed to duplicate file descriptor for child process (%s)"),
2536
0
                           g_strerror (buf[1]));
2537
2538
0
              break;
2539
2540
0
            case CHILD_FORK_FAILED:
2541
0
              g_set_error (error,
2542
0
                           G_SPAWN_ERROR,
2543
0
                           G_SPAWN_ERROR_FORK,
2544
0
                           _("Failed to fork child process (%s)"),
2545
0
                           g_strerror (buf[1]));
2546
0
              break;
2547
2548
0
            case CHILD_CLOSE_FAILED:
2549
0
              g_set_error (error,
2550
0
                           G_SPAWN_ERROR,
2551
0
                           G_SPAWN_ERROR_FAILED,
2552
0
                           _("Failed to close file descriptor for child process (%s)"),
2553
0
                           g_strerror (buf[1]));
2554
0
              break;
2555
2556
0
            default:
2557
0
              g_set_error (error,
2558
0
                           G_SPAWN_ERROR,
2559
0
                           G_SPAWN_ERROR_FAILED,
2560
0
                           _("Unknown error executing child process “%s”"),
2561
0
                           argv[0]);
2562
0
              break;
2563
0
            }
2564
2565
0
          goto cleanup_and_fail;
2566
0
        }
2567
2568
      /* Get child pid from intermediate child pipe. */
2569
0
      if (intermediate_child)
2570
0
        {
2571
0
          n_ints = 0;
2572
          
2573
0
          if (!read_ints (child_pid_report_pipe[0],
2574
0
                          buf, 1, &n_ints, error))
2575
0
            goto cleanup_and_fail;
2576
2577
0
          if (n_ints < 1)
2578
0
            {
2579
0
              int errsv = errno;
2580
2581
0
              g_set_error (error,
2582
0
                           G_SPAWN_ERROR,
2583
0
                           G_SPAWN_ERROR_FAILED,
2584
0
                           _("Failed to read enough data from child pid pipe (%s)"),
2585
0
                           g_strerror (errsv));
2586
0
              goto cleanup_and_fail;
2587
0
            }
2588
0
          else
2589
0
            {
2590
              /* we have the child pid */
2591
0
              pid = buf[0];
2592
0
            }
2593
0
        }
2594
      
2595
      /* Success against all odds! return the information */
2596
0
      close_and_invalidate (&child_err_report_pipe[0]);
2597
0
      close_and_invalidate (&child_pid_report_pipe[0]);
2598
2599
0
      g_free (search_path_buffer_heap);
2600
0
      g_free (argv_buffer_heap);
2601
0
      g_free (source_fds_copy);
2602
2603
0
      if (child_pid)
2604
0
        *child_pid = pid;
2605
2606
0
      goto success;
2607
0
    }
2608
2609
0
success:
2610
  /* Close the uncared-about ends of the pipes */
2611
0
  close_and_invalidate (&stdin_pipe[0]);
2612
0
  close_and_invalidate (&stdout_pipe[1]);
2613
0
  close_and_invalidate (&stderr_pipe[1]);
2614
2615
0
  if (stdin_pipe_out != NULL)
2616
0
    *stdin_pipe_out = g_steal_fd (&stdin_pipe[1]);
2617
2618
0
  if (stdout_pipe_out != NULL)
2619
0
    *stdout_pipe_out = g_steal_fd (&stdout_pipe[0]);
2620
2621
0
  if (stderr_pipe_out != NULL)
2622
0
    *stderr_pipe_out = g_steal_fd (&stderr_pipe[0]);
2623
2624
0
  return TRUE;
2625
2626
0
 cleanup_and_fail:
2627
2628
  /* There was an error from the Child, reap the child to avoid it being
2629
     a zombie.
2630
   */
2631
2632
0
  if (pid > 0)
2633
0
  {
2634
0
    wait_failed:
2635
0
     if (waitpid (pid, NULL, 0) < 0)
2636
0
       {
2637
0
          if (errno == EINTR)
2638
0
            goto wait_failed;
2639
0
          else if (errno == ECHILD)
2640
0
            ; /* do nothing, child already reaped */
2641
0
          else
2642
0
            g_warning ("waitpid() should not fail in 'fork_exec'");
2643
0
       }
2644
0
   }
2645
2646
0
  close_and_invalidate (&stdin_pipe[0]);
2647
0
  close_and_invalidate (&stdin_pipe[1]);
2648
0
  close_and_invalidate (&stdout_pipe[0]);
2649
0
  close_and_invalidate (&stdout_pipe[1]);
2650
0
  close_and_invalidate (&stderr_pipe[0]);
2651
0
  close_and_invalidate (&stderr_pipe[1]);
2652
2653
0
  close_and_invalidate (&child_err_report_pipe[0]);
2654
0
  close_and_invalidate (&child_err_report_pipe[1]);
2655
0
  close_and_invalidate (&child_pid_report_pipe[0]);
2656
0
  close_and_invalidate (&child_pid_report_pipe[1]);
2657
2658
0
  g_clear_pointer (&search_path_buffer_heap, g_free);
2659
0
  g_clear_pointer (&argv_buffer_heap, g_free);
2660
0
  g_clear_pointer (&source_fds_copy, g_free);
2661
2662
0
  return FALSE;
2663
0
}
2664
2665
/* Based on execvp from GNU C Library */
2666
2667
/* This function is called between fork() and exec() and hence must be
2668
 * async-signal-safe (see signal-safety(7)) until it calls exec(). */
2669
static gboolean
2670
script_execute (const gchar *file,
2671
                gchar      **argv,
2672
                gchar      **argv_buffer,
2673
                gsize        argv_buffer_len,
2674
                gchar      **envp)
2675
0
{
2676
  /* Count the arguments.  */
2677
0
  gsize argc = 0;
2678
0
  while (argv[argc])
2679
0
    ++argc;
2680
2681
  /* Construct an argument list for the shell. */
2682
0
  if (argc + 2 > argv_buffer_len)
2683
0
    return FALSE;
2684
2685
0
  argv_buffer[0] = (char *) "/bin/sh";
2686
0
  argv_buffer[1] = (char *) file;
2687
0
  while (argc > 0)
2688
0
    {
2689
0
      argv_buffer[argc + 1] = argv[argc];
2690
0
      --argc;
2691
0
    }
2692
2693
  /* Execute the shell. */
2694
0
  if (envp)
2695
0
    execve (argv_buffer[0], argv_buffer, envp);
2696
0
  else
2697
0
    execv (argv_buffer[0], argv_buffer);
2698
2699
0
  return TRUE;
2700
0
}
2701
2702
/* This function is called between fork() and exec() and hence must be
2703
 * async-signal-safe (see signal-safety(7)). */
2704
static gchar*
2705
my_strchrnul (const gchar *str, gchar c)
2706
0
{
2707
0
  gchar *p = (gchar*) str;
2708
0
  while (*p && (*p != c))
2709
0
    ++p;
2710
2711
0
  return p;
2712
0
}
2713
2714
/* This function is called between fork() and exec() and hence must be
2715
 * async-signal-safe (see signal-safety(7)) until it calls exec(). */
2716
static gint
2717
g_execute (const gchar  *file,
2718
           gchar       **argv,
2719
           gchar       **argv_buffer,
2720
           gsize         argv_buffer_len,
2721
           gchar       **envp,
2722
           const gchar  *search_path,
2723
           gchar        *search_path_buffer,
2724
           gsize         search_path_buffer_len)
2725
0
{
2726
0
  if (file == NULL || *file == '\0')
2727
0
    {
2728
      /* We check the simple case first. */
2729
0
      errno = ENOENT;
2730
0
      return -1;
2731
0
    }
2732
2733
0
  if (search_path == NULL || strchr (file, '/') != NULL)
2734
0
    {
2735
      /* Don't search when it contains a slash. */
2736
0
      if (envp)
2737
0
        execve (file, argv, envp);
2738
0
      else
2739
0
        execv (file, argv);
2740
      
2741
0
      if (errno == ENOEXEC &&
2742
0
          !script_execute (file, argv, argv_buffer, argv_buffer_len, envp))
2743
0
        {
2744
0
          errno = ENOMEM;
2745
0
          return -1;
2746
0
        }
2747
0
    }
2748
0
  else
2749
0
    {
2750
0
      gboolean got_eacces = 0;
2751
0
      const gchar *path, *p;
2752
0
      gchar *name;
2753
0
      gsize len;
2754
0
      gsize pathlen;
2755
2756
0
      path = search_path;
2757
0
      len = strlen (file) + 1;
2758
0
      pathlen = strlen (path);
2759
0
      name = search_path_buffer;
2760
2761
0
      if (search_path_buffer_len < pathlen + len + 1)
2762
0
        {
2763
0
          errno = ENOMEM;
2764
0
          return -1;
2765
0
        }
2766
2767
      /* Copy the file name at the top, including '\0'  */
2768
0
      memcpy (name + pathlen + 1, file, len);
2769
0
      name = name + pathlen;
2770
      /* And add the slash before the filename  */
2771
0
      *name = '/';
2772
2773
0
      p = path;
2774
0
      do
2775
0
  {
2776
0
    char *startp;
2777
2778
0
    path = p;
2779
0
    p = my_strchrnul (path, ':');
2780
2781
0
    if (p == path)
2782
      /* Two adjacent colons, or a colon at the beginning or the end
2783
             * of 'PATH' means to search the current directory.
2784
             */
2785
0
      startp = name + 1;
2786
0
    else
2787
0
      startp = memcpy (name - (p - path), path, p - path);
2788
2789
    /* Try to execute this name.  If it works, execv will not return.  */
2790
0
          if (envp)
2791
0
            execve (startp, argv, envp);
2792
0
          else
2793
0
            execv (startp, argv);
2794
          
2795
0
          if (errno == ENOEXEC &&
2796
0
              !script_execute (startp, argv, argv_buffer, argv_buffer_len, envp))
2797
0
            {
2798
0
              errno = ENOMEM;
2799
0
              return -1;
2800
0
            }
2801
2802
0
    switch (errno)
2803
0
      {
2804
0
      case EACCES:
2805
        /* Record the we got a 'Permission denied' error.  If we end
2806
               * up finding no executable we can use, we want to diagnose
2807
               * that we did find one but were denied access.
2808
               */
2809
0
        got_eacces = TRUE;
2810
2811
0
              G_GNUC_FALLTHROUGH;
2812
0
      case ENOENT:
2813
0
#ifdef ESTALE
2814
0
      case ESTALE:
2815
0
#endif
2816
0
#ifdef ENOTDIR
2817
0
      case ENOTDIR:
2818
0
#endif
2819
        /* Those errors indicate the file is missing or not executable
2820
               * by us, in which case we want to just try the next path
2821
               * directory.
2822
               */
2823
0
        break;
2824
2825
0
      case ENODEV:
2826
0
      case ETIMEDOUT:
2827
        /* Some strange filesystems like AFS return even
2828
         * stranger error numbers.  They cannot reasonably mean anything
2829
         * else so ignore those, too.
2830
         */
2831
0
        break;
2832
2833
0
      default:
2834
        /* Some other error means we found an executable file, but
2835
               * something went wrong executing it; return the error to our
2836
               * caller.
2837
               */
2838
0
        return -1;
2839
0
      }
2840
0
  }
2841
0
      while (*p++ != '\0');
2842
2843
      /* We tried every element and none of them worked.  */
2844
0
      if (got_eacces)
2845
  /* At least one failure was due to permissions, so report that
2846
         * error.
2847
         */
2848
0
        errno = EACCES;
2849
0
    }
2850
2851
  /* Return the error from the last attempt (probably ENOENT).  */
2852
0
  return -1;
2853
0
}
2854
2855
/**
2856
 * g_spawn_close_pid:
2857
 * @pid: The process reference to close
2858
 *
2859
 * On some platforms, notably Windows, the #GPid type represents a resource
2860
 * which must be closed to prevent resource leaking. g_spawn_close_pid()
2861
 * is provided for this purpose. It should be used on all platforms, even
2862
 * though it doesn't do anything under UNIX.
2863
 **/
2864
void
2865
g_spawn_close_pid (GPid pid)
2866
0
{
2867
0
}