Debian Codegraph @

pypy/module/_posixsubprocess/_posixsubprocess.c

raw symbols SCIP
1 /* This file is mostly a copy of CPython's Module/_posixsubprocess.c */
2 /* modified for PyPy: Removed dependency on Python API. */
3
4 /* Authors: Gregory P. Smith & Jeffrey Yasskin */
5 #if defined(HAVE_PIPE2) && !defined(_GNU_SOURCE)
6 # define _GNU_SOURCE
7 #endif
8 #include <errno.h>
9 #include <string.h>
10 #include <unistd.h>
11 #include <fcntl.h>
12 #include <signal.h>
13 #ifdef HAVE_SYS_TYPES_H
14 #include <sys/types.h>
15 #endif
16 #if defined(HAVE_SYS_STAT_H)
17 #include <sys/stat.h>
18 #endif
19 #ifdef HAVE_SYS_SYSCALL_H
20 #include <sys/syscall.h>
21 #endif
22 #if defined(HAVE_SYS_RESOURCE_H)
23 #include <sys/resource.h>
24 #endif
25 #ifdef HAVE_DIRENT_H
26 #include <dirent.h>
27 #endif
28
29 #include <grp.h>
30
31
32 #if defined(__ANDROID__) && __ANDROID_API__ < 21 && !defined(SYS_getdents64)
33 # include <sys/linux-syscalls.h>
34 # define SYS_getdents64 __NR_getdents64
35 #endif
36
37 #include "_posixsubprocess.h"
38
39 #if defined(sun)
40 /* readdir64 is used to work around Solaris 9 bug 6395699. */
41 # define readdir readdir64
42 # define dirent dirent64
43 # if !defined(HAVE_DIRFD)
44 /* Some versions of Solaris lack dirfd(). */
45 # define dirfd(dirp) ((dirp)->dd_fd)
46 # define HAVE_DIRFD
47 # endif
48 #endif
49
50 #if defined(__FreeBSD__) || (defined(__APPLE__) && defined(__MACH__))
51 # define FD_DIR "/dev/fd"
52 #else
53 # define FD_DIR "/proc/self/fd"
54 #endif
55
56 #define POSIX_CALL(call) do { if ((call) == -1) goto error; } while (0)
57
58 /* Convert ASCII to a positive int, no libc call. no overflow. -1 on error. */
59 static int
60 _pos_int_from_ascii(char *name)
61 {
62 int num = 0;
63 while (*name >= '0' && *name <= '9') {
64 num = num * 10 + (*name - '0');
65 ++name;
66 }
67 if (*name)
68 return -1; /* Non digit found, not a number. */
69 return num;
70 }
71
72 static
73 void local_pypysig_default(int signum)
74 {
75 /* copied from pyypsig_default */
76 #ifdef SA_RESTART
77 /* assume sigaction exists */
78 struct sigaction context;
79 context.sa_handler = SIG_DFL;
80 sigemptyset(&context.sa_mask);
81 context.sa_flags = 0;
82 sigaction(signum, &context, NULL);
83 #else
84 signal(signum, SIG_DFL);
85 #endif
86 #ifdef HAVE_SIGINTERRUPT
87 siginterrupt(signum, 1);
88 #endif
89 }
90
91 #if defined(__FreeBSD__)
92 /* When /dev/fd isn't mounted it is often a static directory populated
93 * with 0 1 2 or entries for 0 .. 63 on FreeBSD, NetBSD and OpenBSD.
94 * NetBSD and OpenBSD have a /proc fs available (though not necessarily
95 * mounted) and do not have fdescfs for /dev/fd. MacOS X has a devfs
96 * that properly supports /dev/fd.
97 */
98 static int
99 _is_fdescfs_mounted_on_dev_fd(void)
100 {
101 struct stat dev_stat;
102 struct stat dev_fd_stat;
103 if (stat("/dev", &dev_stat) != 0)
104 return 0;
105 if (stat(FD_DIR, &dev_fd_stat) != 0)
106 return 0;
107 if (dev_stat.st_dev == dev_fd_stat.st_dev)
108 return 0; /* / == /dev == /dev/fd means it is static. #fail */
109 return 1;
110 }
111 #endif
112
113
114 /* Is fd found in the sorted Python Sequence? */
115 static int
116 _is_fd_in_sorted_fd_sequence(int fd, long *fd_sequence, ssize_t seq_len)
117 {
118 /* Binary search. */
119 ssize_t search_min = 0;
120 ssize_t search_max = seq_len - 1;
121 if (search_max < 0)
122 return 0;
123 do {
124 ssize_t middle = (search_min + search_max) / 2;
125 long middle_fd = fd_sequence[middle];
126 if (fd == middle_fd)
127 return 1;
128 if (fd > middle_fd)
129 search_min = middle + 1;
130 else
131 search_max = middle - 1;
132 } while (search_min <= search_max);
133 return 0;
134 }
135
136
137 RPY_EXTERN
138 int rpy_set_inheritable(int fd, int inheritable); /* rposix.py */
139
140 static int
141 make_inheritable(long *py_fds_to_keep, ssize_t num_fds_to_keep,
142 int errpipe_write)
143 {
144 long i;
145
146 for (i = 0; i < num_fds_to_keep; ++i) {
147 long fd = py_fds_to_keep[i];
148 if (fd == errpipe_write) {
149 /* errpipe_write is part of py_fds_to_keep. It must be closed at
150 exec(), but kept open in the child process until exec() is
151 called. */
152 continue;
153 }
154 if (rpy_set_inheritable((int)fd, 1) < 0)
155 return -1;
156 }
157 return 0;
158 }
159
160
161 /* Get the maximum file descriptor that could be opened by this process.
162 * This function is async signal safe for use between fork() and exec().
163 */
164 static long
165 safe_get_max_fd(void)
166 {
167 long local_max_fd;
168 #if defined(__NetBSD__)
169 local_max_fd = fcntl(0, F_MAXFD);
170 if (local_max_fd >= 0)
171 return local_max_fd;
172 #endif
173 #if defined(HAVE_SYS_RESOURCE_H) && defined(__OpenBSD__)
174 struct rlimit rl;
175 /* Not on the POSIX async signal safe functions list but likely
176 * safe. TODO - Someone should audit OpenBSD to make sure. */
177 if (getrlimit(RLIMIT_NOFILE, &rl) >= 0)
178 return (long) rl.rlim_max;
179 #endif
180 #ifdef _SC_OPEN_MAX
181 local_max_fd = sysconf(_SC_OPEN_MAX);
182 if (local_max_fd == -1)
183 #endif
184 local_max_fd = 256; /* Matches legacy Lib/subprocess.py behavior. */
185 return local_max_fd;
186 }
187
188
189 /* Close all file descriptors in the range from start_fd and higher
190 * except for those in py_fds_to_keep. If the range defined by
191 * [start_fd, safe_get_max_fd()) is large this will take a long
192 * time as it calls close() on EVERY possible fd.
193 *
194 * It isn't possible to know for sure what the max fd to go up to
195 * is for processes with the capability of raising their maximum.
196 */
197 static void
198 _close_fds_by_brute_force(long start_fd, long *py_fds_to_keep,
199 ssize_t num_fds_to_keep)
200 {
201 long end_fd = safe_get_max_fd();
202 ssize_t keep_seq_idx;
203 int fd_num;
204 /* As py_fds_to_keep is sorted we can loop through the list closing
205 * fds inbetween any in the keep list falling within our range. */
206 for (keep_seq_idx = 0; keep_seq_idx < num_fds_to_keep; ++keep_seq_idx) {
207 int keep_fd = py_fds_to_keep[keep_seq_idx];
208 if (keep_fd < start_fd)
209 continue;
210 for (fd_num = start_fd; fd_num < keep_fd; ++fd_num) {
211 close(fd_num);
212 }
213 start_fd = keep_fd + 1;
214 }
215 if (start_fd <= end_fd) {
216 for (fd_num = start_fd; fd_num < end_fd; ++fd_num) {
217 close(fd_num);
218 }
219 }
220 }
221
222
223 #if defined(__linux__) && defined(HAVE_SYS_SYSCALL_H)
224 /* It doesn't matter if d_name has room for NAME_MAX chars; we're using this
225 * only to read a directory of short file descriptor number names. The kernel
226 * will return an error if we didn't give it enough space. Highly Unlikely.
227 * This structure is very old and stable: It will not change unless the kernel
228 * chooses to break compatibility with all existing binaries. Highly Unlikely.
229 */
230 struct linux_dirent64 {
231 unsigned long long d_ino;
232 long long d_off;
233 unsigned short d_reclen; /* Length of this linux_dirent */
234 unsigned char d_type;
235 char d_name[256]; /* Filename (null-terminated) */
236 };
237
238 /* Close all open file descriptors in the range from start_fd and higher
239 * Do not close any in the sorted py_fds_to_keep list.
240 *
241 * This version is async signal safe as it does not make any unsafe C library
242 * calls, malloc calls or handle any locks. It is _unfortunate_ to be forced
243 * to resort to making a kernel system call directly but this is the ONLY api
244 * available that does no harm. opendir/readdir/closedir perform memory
245 * allocation and locking so while they usually work they are not guaranteed
246 * to (especially if you have replaced your malloc implementation). A version
247 * of this function that uses those can be found in the _maybe_unsafe variant.
248 *
249 * This is Linux specific because that is all I am ready to test it on. It
250 * should be easy to add OS specific dirent or dirent64 structures and modify
251 * it with some cpp #define magic to work on other OSes as well if you want.
252 */
253 static void
254 _close_open_fds_safe(int start_fd, long *py_fds_to_keep,
255 ssize_t num_fds_to_keep)
256 {
257 int fd_dir_fd;
258 #ifdef O_CLOEXEC
259 fd_dir_fd = open(FD_DIR, O_RDONLY | O_CLOEXEC, 0);
260 #else
261 fd_dir_fd = open(FD_DIR, O_RDONLY, 0);
262 #ifdef FD_CLOEXEC
263 {
264 int old = fcntl(fd_dir_fd, F_GETFD);
265 if (old != -1)
266 fcntl(fd_dir_fd, F_SETFD, old | FD_CLOEXEC);
267 }
268 #endif
269 #endif
270 if (fd_dir_fd == -1) {
271 /* No way to get a list of open fds. */
272 _close_fds_by_brute_force(start_fd, py_fds_to_keep, num_fds_to_keep);
273 return;
274 } else {
275 char buffer[sizeof(struct linux_dirent64)];
276 int bytes;
277 while ((bytes = syscall(SYS_getdents64, fd_dir_fd,
278 (struct linux_dirent64 *)buffer,
279 sizeof(buffer))) > 0) {
280 struct linux_dirent64 *entry;
281 int offset;
282 for (offset = 0; offset < bytes; offset += entry->d_reclen) {
283 int fd;
284 entry = (struct linux_dirent64 *)(buffer + offset);
285 if ((fd = _pos_int_from_ascii(entry->d_name)) < 0)
286 continue; /* Not a number. */
287 if (fd != fd_dir_fd && fd >= start_fd &&
288 !_is_fd_in_sorted_fd_sequence(
289 fd, py_fds_to_keep, num_fds_to_keep)) {
290 close(fd);
291 }
292 }
293 }
294 close(fd_dir_fd);
295 }
296 }
297
298 #define _close_open_fds _close_open_fds_safe
299
300 #else /* NOT (defined(__linux__) && defined(HAVE_SYS_SYSCALL_H)) */
301
302
303 /* Close all open file descriptors from start_fd and higher.
304 * Do not close any in the sorted py_fds_to_keep list.
305 *
306 * This function violates the strict use of async signal safe functions. :(
307 * It calls opendir(), readdir() and closedir(). Of these, the one most
308 * likely to ever cause a problem is opendir() as it performs an internal
309 * malloc(). Practically this should not be a problem. The Java VM makes the
310 * same calls between fork and exec in its own UNIXProcess_md.c implementation.
311 *
312 * readdir_r() is not used because it provides no benefit. It is typically
313 * implemented as readdir() followed by memcpy(). See also:
314 * http://womble.decadent.org.uk/readdir_r-advisory.html
315 */
316 static void
317 _close_open_fds_maybe_unsafe(long start_fd,
318 long *py_fds_to_keep, ssize_t num_fds_to_keep)
319 {
320 DIR *proc_fd_dir;
321 #ifndef HAVE_DIRFD
322 while (_is_fd_in_sorted_fd_sequence(start_fd, py_fds_to_keep, num_fds_to_keep)) {
323 ++start_fd;
324 }
325 /* Close our lowest fd before we call opendir so that it is likely to
326 * reuse that fd otherwise we might close opendir's file descriptor in
327 * our loop. This trick assumes that fd's are allocated on a lowest
328 * available basis. */
329 close(start_fd);
330 ++start_fd;
331 #endif
332
333 #if defined(__FreeBSD__)
334 if (!_is_fdescfs_mounted_on_dev_fd())
335 proc_fd_dir = NULL;
336 else
337 #endif
338 proc_fd_dir = opendir(FD_DIR);
339 if (!proc_fd_dir) {
340 /* No way to get a list of open fds. */
341 _close_fds_by_brute_force(start_fd, py_fds_to_keep, num_fds_to_keep);
342 } else {
343 struct dirent *dir_entry;
344 #ifdef HAVE_DIRFD
345 int fd_used_by_opendir = dirfd(proc_fd_dir);
346 #else
347 int fd_used_by_opendir = start_fd - 1;
348 #endif
349 errno = 0;
350 while ((dir_entry = readdir(proc_fd_dir))) {
351 int fd;
352 if ((fd = _pos_int_from_ascii(dir_entry->d_name)) < 0)
353 continue; /* Not a number. */
354 if (fd != fd_used_by_opendir && fd >= start_fd &&
355 !_is_fd_in_sorted_fd_sequence(fd, py_fds_to_keep, num_fds_to_keep)) {
356 close(fd);
357 }
358 errno = 0;
359 }
360 if (errno) {
361 /* readdir error, revert behavior. Highly Unlikely. */
362 _close_fds_by_brute_force(
363 start_fd, py_fds_to_keep, num_fds_to_keep);
364 }
365 closedir(proc_fd_dir);
366 }
367 }
368
369 #define _close_open_fds _close_open_fds_maybe_unsafe
370
371 #endif /* else NOT (defined(__linux__) && defined(HAVE_SYS_SYSCALL_H)) */
372
373
374 /*
375 * This function is code executed in the child process immediately after fork
376 * to set things up and call exec().
377 *
378 * All of the code in this function must only use async-signal-safe functions,
379 * listed at `man 7 signal` or
380 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
381 *
382 * This restriction is documented at
383 * http://www.opengroup.org/onlinepubs/009695399/functions/fork.html.
384 */
385 void
386 pypy_subprocess_child_exec(
387 char *const exec_array[],
388 char *const argv[],
389 char *const envp[],
390 const char *cwd,
391 int p2cread, int p2cwrite,
392 int c2pread, int c2pwrite,
393 int errread, int errwrite,
394 int errpipe_read, int errpipe_write,
395 int close_fds, int restore_signals,
396 int call_setsid, pid_t pgid_to_set,
397 int call_setgid, gid_t gid,
398 int call_setgroups, size_t groups_size, const gid_t *groups,
399 int call_setuid, uid_t uid, int child_umask,
400 long *py_fds_to_keep,
401 ssize_t num_fds_to_keep,
402 int (*preexec_fn)(void*),
403 void *preexec_fn_arg)
404 {
405 int i, saved_errno, unused, reached_preexec = 0, failed_chdir = 0;
406 int result;
407 const char* err_msg = "";
408 /* Buffer large enough to hold a hex integer. We can't malloc. */
409 char hex_errno[sizeof(saved_errno)*2+1];
410
411 if (make_inheritable(py_fds_to_keep, num_fds_to_keep, errpipe_write) < 0)
412 goto error;
413
414 /* Close parent's pipe ends. */
415 if (p2cwrite != -1)
416 POSIX_CALL(close(p2cwrite));
417 if (c2pread != -1)
418 POSIX_CALL(close(c2pread));
419 if (errread != -1)
420 POSIX_CALL(close(errread));
421 POSIX_CALL(close(errpipe_read));
422
423 /* When duping fds, if there arises a situation where one of the fds is
424 either 0, 1 or 2, it is possible that it is overwritten (#12607). */
425 if (c2pwrite == 0) {
426 POSIX_CALL(c2pwrite = dup(c2pwrite));
427 /* issue32270 */
428 if (rpy_set_inheritable(c2pwrite, 0) < 0) {
429 goto error;
430 }
431 }
432 while (errwrite == 0 || errwrite == 1) {
433 POSIX_CALL(errwrite = dup(errwrite));
434 /* issue32270 */
435 if (rpy_set_inheritable(errwrite, 0) < 0) {
436 goto error;
437 }
438 }
439
440 /* Dup fds for child.
441 dup2() removes the CLOEXEC flag but we must do it ourselves if dup2()
442 would be a no-op (issue #10806). */
443 if (p2cread == 0) {
444 if (rpy_set_inheritable(p2cread, 1) < 0)
445 goto error;
446 }
447 else if (p2cread != -1)
448 POSIX_CALL(dup2(p2cread, 0)); /* stdin */
449
450 if (c2pwrite == 1) {
451 if (rpy_set_inheritable(c2pwrite, 1) < 0)
452 goto error;
453 }
454 else if (c2pwrite != -1)
455 POSIX_CALL(dup2(c2pwrite, 1)); /* stdout */
456
457 if (errwrite == 2) {
458 if (rpy_set_inheritable(errwrite, 1) < 0)
459 goto error;
460 }
461 else if (errwrite != -1)
462 POSIX_CALL(dup2(errwrite, 2)); /* stderr */
463
464 /* We no longer manually close p2cread, c2pwrite, and errwrite here as
465 * _close_open_fds takes care when it is not already non-inheritable. */
466
467 if (cwd) {
468 if (chdir(cwd) == -1) {
469 failed_chdir = 1;
470 goto error;
471 }
472 }
473
474 if (child_umask >= 0)
475 umask(child_umask); /* umask() always succeeds. */
476
477 if (restore_signals) {
478 /* inline _Py_RestoreSignals(); */
479 #ifdef SIGPIPE
480 local_pypysig_default(SIGPIPE);
481 #endif
482 #ifdef SIGXFZ
483 local_pypysig_default(SIGXFZ);
484 #endif
485 #ifdef SIGXFSZ
486 local_pypysig_default(SIGXFSZ);
487 #endif
488 }
489
490
491 #ifdef HAVE_SETSID
492 if (call_setsid)
493 POSIX_CALL(setsid());
494 #endif
495
496 #ifdef HAVE_SETPGID
497 if (pgid_to_set >= 0)
498 POSIX_CALL(setpgid(0, pgid_to_set));
499 #endif
500
501 #ifdef HAVE_SETGROUPS
502 if (call_setgroups)
503 POSIX_CALL(setgroups(groups_size, groups));
504 #endif /* HAVE_SETGROUPS */
505
506 #ifdef HAVE_SETREGID
507 if (call_setgid)
508 POSIX_CALL(setregid(gid, gid));
509 #endif /* HAVE_SETREGID */
510
511 #ifdef HAVE_SETREUID
512 if (call_setuid)
513 POSIX_CALL(setreuid(uid, uid));
514 #endif /* HAVE_SETREUID */
515
516 reached_preexec = 1;
517 if (preexec_fn != NULL) {
518 /* This is where the user has asked us to deadlock their program. */
519 result = preexec_fn(preexec_fn_arg);
520 if (result == 0) {
521 /* Stringifying the exception or traceback would involve
522 * memory allocation and thus potential for deadlock.
523 * We've already faced potential deadlock by calling back
524 * into Python in the first place, so it probably doesn't
525 * matter but we avoid it to minimize the possibility. */
526 err_msg = "Exception occurred in preexec_fn.";
527 errno = 0; /* We don't want to report an OSError. */
528 goto error;
529 }
530 }
531
532 /* close FDs after executing preexec_fn, which might open FDs */
533 if (close_fds) {
534 /* TODO HP-UX could use pstat_getproc() if anyone cares about it. */
535 _close_open_fds(3, py_fds_to_keep, num_fds_to_keep);
536 }
537
538 /* This loop matches the Lib/os.py _execvpe()'s PATH search when */
539 /* given the executable_list generated by Lib/subprocess.py. */
540 saved_errno = 0;
541 for (i = 0; exec_array[i] != NULL; ++i) {
542 const char *executable = exec_array[i];
543 if (envp) {
544 execve(executable, argv, envp);
545 } else {
546 execv(executable, argv);
547 }
548 if (errno != ENOENT && errno != ENOTDIR && saved_errno == 0) {
549 saved_errno = errno;
550 }
551 }
552 /* Report the first exec error, not the last. */
553 if (saved_errno)
554 errno = saved_errno;
555
556 error:
557 saved_errno = errno;
558 /* Report the posix error to our parent process. */
559 /* We ignore all write() return values as the total size of our writes is
560 * less than PIPEBUF and we cannot do anything about an error anyways. */
561 if (saved_errno) {
562 char *cur;
563 unused = write(errpipe_write, "OSError:", 8);
564 cur = hex_errno + sizeof(hex_errno);
565 while (saved_errno != 0 && cur > hex_errno) {
566 *--cur = "0123456789ABCDEF"[saved_errno % 16];
567 saved_errno /= 16;
568 }
569 unused = write(errpipe_write, cur, hex_errno + sizeof(hex_errno) - cur);
570 unused = write(errpipe_write, ":", 1);
571 if (!reached_preexec) {
572 /* Indicate to the parent that the error happened before exec(). */
573 if (failed_chdir)
574 unused = write(errpipe_write, "noexec:chdir", 12);
575 else
576 unused = write(errpipe_write, "noexec", 6);
577 }
578 /* We can't call strerror(saved_errno). It is not async signal safe.
579 * The parent process will look the error message up. */
580 } else {
581 unused = write(errpipe_write, "SubprocessError:0:", 18);
582 unused = write(errpipe_write, err_msg, strlen(err_msg));
583 }
584 if (unused) return; /* silly? yes! avoids gcc compiler warning. */
585 }
586
587
588 void
589 pypy_subprocess_init(void)
590 {
591 }