Coverage Report

Created: 2025-08-08 06:10

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