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