• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #include <fcntl.h>
2 #include <unistd.h>
3 #include <errno.h>
4 #include <string.h>
5 #include <spawn.h>
6 #include <unsupported_api.h>
7 #include "stdio_impl.h"
8 #include "syscall.h"
9 
10 extern char **__environ;
11 
popen(const char * cmd,const char * mode)12 FILE *popen(const char *cmd, const char *mode)
13 {
14 	int p[2], op, e;
15 	pid_t pid;
16 	FILE *f;
17 	posix_spawn_file_actions_t fa;
18 
19 	unsupported_api(__FUNCTION__);
20 	if (*mode == 'r') {
21 		op = 0;
22 	} else if (*mode == 'w') {
23 		op = 1;
24 	} else {
25 		errno = EINVAL;
26 		return 0;
27 	}
28 
29 	if (pipe2(p, O_CLOEXEC)) return NULL;
30 	f = fdopen(p[op], mode);
31 	if (!f) {
32 		__syscall(SYS_close, p[0]);
33 		__syscall(SYS_close, p[1]);
34 		return NULL;
35 	}
36 	FLOCK(f);
37 
38 	/* If the child's end of the pipe happens to already be on the final
39 	 * fd number to which it will be assigned (either 0 or 1), it must
40 	 * be moved to a different fd. Otherwise, there is no safe way to
41 	 * remove the close-on-exec flag in the child without also creating
42 	 * a file descriptor leak race condition in the parent. */
43 	if (p[1-op] == 1-op) {
44 		int tmp = fcntl(1-op, F_DUPFD_CLOEXEC, 0);
45 		if (tmp < 0) {
46 			e = errno;
47 			goto fail;
48 		}
49 		__syscall(SYS_close, p[1-op]);
50 		p[1-op] = tmp;
51 	}
52 
53 	e = ENOMEM;
54 	if (!posix_spawn_file_actions_init(&fa)) {
55 		if (!posix_spawn_file_actions_adddup2(&fa, p[1-op], 1-op)) {
56 			if (!(e = posix_spawn(&pid, "/bin/sh", &fa, 0,
57 			    (char *[]){ "sh", "-c", (char *)cmd, 0 }, __environ))) {
58 				posix_spawn_file_actions_destroy(&fa);
59 				f->pipe_pid = pid;
60 				if (!strchr(mode, 'e'))
61 					fcntl(p[op], F_SETFD, 0);
62 				__syscall(SYS_close, p[1-op]);
63 				FUNLOCK(f);
64 				return f;
65 			}
66 		}
67 		posix_spawn_file_actions_destroy(&fa);
68 	}
69 fail:
70 	fclose(f);
71 	__syscall(SYS_close, p[1-op]);
72 
73 	errno = e;
74 	return 0;
75 }
76