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