Coverage Report

Created: 2025-08-11 06:28

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