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