Debian Codegraph @

pypy/module/_posixsubprocess/interp_subprocess.py

raw symbols SCIP
1 import os
2
3 import py
4 from rpython.rtyper.lltypesystem import lltype, rffi
5 from rpython.rtyper.tool import rffi_platform as platform
6 from rpython.translator import cdir
7 from rpython.translator.tool.cbuild import ExternalCompilationInfo
8 from rpython.rlib import rposix
9
10 from pypy.interpreter.error import (
11 OperationError, oefmt, wrap_oserror)
12 from pypy.interpreter.gateway import unwrap_spec
13 from pypy.module.posix.interp_posix import run_fork_hooks
14
15 thisdir = py.path.local(__file__).dirpath()
16
17 class CConfig:
18 _compilation_info_ = ExternalCompilationInfo(
19 includes=['unistd.h', 'sys/syscall.h', 'sys/stat.h', 'grp.h'])
20 HAVE_SYS_SYSCALL_H = platform.Has("syscall")
21 HAVE_SYS_STAT_H = platform.Has("stat")
22 HAVE_SETSID = platform.Has("setsid")
23 HAVE_SETGROUPS = platform.Has("setgroups")
24 NGROUPS_MAX = platform.DefinedConstantInteger('NGROUPS_MAX')
25 HAVE_SETREGID = platform.Has("setregid")
26 HAVE_SETREUID = platform.Has("setreuid")
27 HAVE_SETPGID = platform.Has("setpgid")
28
29 uid_t = platform.SimpleType("uid_t", ctype_hint=rffi.UINT_real)
30 gid_t = platform.SimpleType("gid_t", ctype_hint=rffi.UINT_real)
31 pid_t = platform.SimpleType("pid_t", ctype_hint=rffi.INT_real)
32
33 config = platform.configure(CConfig)
34
35 eci = ExternalCompilationInfo(
36 includes=[thisdir.join('_posixsubprocess.h')],
37 include_dirs=[str(thisdir), cdir],
38 separate_module_files=[thisdir.join('_posixsubprocess.c')])
39
40 compile_extra = []
41 if config['HAVE_SYS_SYSCALL_H']:
42 compile_extra.append("-DHAVE_SYS_SYSCALL_H")
43 if config['HAVE_SYS_STAT_H']:
44 compile_extra.append("-DHAVE_SYS_STAT_H")
45 if config['HAVE_SETSID']:
46 compile_extra.append("-DHAVE_SETSID")
47 HAVE_SETGROUPS = config['HAVE_SETGROUPS']
48 if HAVE_SETGROUPS:
49 compile_extra.append("-DHAVE_SETGROUPS")
50 HAVE_SETREGID = config['HAVE_SETREGID']
51 if HAVE_SETREGID:
52 compile_extra.append("-DHAVE_SETREGID")
53 HAVE_SETREUID = config['HAVE_SETREUID']
54 if HAVE_SETREUID:
55 compile_extra.append("-DHAVE_SETREUID")
56 HAVE_SETPGID = config['HAVE_SETPGID']
57 if HAVE_SETPGID:
58 compile_extra.append("-DHAVE_SETPGID")
59 gid_t = config['gid_t']
60 uid_t = config['uid_t']
61 pid_t = config['pid_t']
62 if config["NGROUPS_MAX"] is not None:
63 MAX_GROUPS = config['NGROUPS_MAX']
64 else:
65 MAX_GROUPS = 64
66
67 class CConfig:
68 _compilation_info_ = ExternalCompilationInfo(includes=['dirent.h'])
69 HAVE_DIRENT_H = platform.Has("opendir")
70
71 config = platform.configure(CConfig)
72
73 if config['HAVE_DIRENT_H']:
74 compile_extra.append("-DHAVE_DIRENT_H")
75
76 eci = eci.merge(
77 rposix.eci_inheritable,
78 ExternalCompilationInfo(
79 compile_extra=compile_extra))
80
81 c_child_exec = rffi.llexternal(
82 'pypy_subprocess_child_exec',
83 [rffi.CCHARPP, rffi.CCHARPP, rffi.CCHARPP, rffi.CCHARP,
84 rffi.INT, rffi.INT, rffi.INT, rffi.INT, rffi.INT, rffi.INT,
85 rffi.INT, rffi.INT, rffi.INT, rffi.INT, rffi.INT,
86 rffi.INT, gid_t, pid_t, # call_setgid, gid, pgid_to_set,
87 rffi.INT, rffi.SIZE_T, rffi.CArrayPtr(gid_t), # call_setgroups, groups_size, groups
88 rffi.INT, uid_t, rffi.INT, # call_setuid, uid child_umask
89 rffi.CArrayPtr(rffi.LONG), lltype.Signed,
90 lltype.Ptr(lltype.FuncType([rffi.VOIDP], rffi.INT_real)), rffi.VOIDP],
91 lltype.Void,
92 compilation_info=eci,
93 releasegil=True)
94 c_init = rffi.llexternal(
95 'pypy_subprocess_init',
96 [], lltype.Void,
97 compilation_info=eci,
98 releasegil=True)
99
100
101 class PreexecCallback:
102 def __init__(self):
103 self.space = None
104 self.w_preexec_fn = None
105
106 @staticmethod
107 def run_function(unused):
108 self = preexec
109 if self.w_preexec_fn:
110 try:
111 self.space.call_function(self.w_preexec_fn)
112 except OperationError:
113 return rffi.cast(rffi.INT_real, 0)
114 return rffi.cast(rffi.INT_real, 1)
115 preexec = PreexecCallback()
116
117
118 def build_fd_sequence(space, w_fd_list):
119 result = [space.int_w(w_fd)
120 for w_fd in space.unpackiterable(w_fd_list)]
121 prev_fd = -1
122 for fd in result:
123 if fd < 0 or fd < prev_fd or fd > 1 << 30:
124 raise oefmt(space.w_ValueError, "bad value(s) in fds_to_keep")
125 return result
126
127
128 def seqstr2charpp(space, w_seqstr):
129 """Sequence of bytes -> char**, NULL terminated"""
130 w_iter = space.iter(w_seqstr)
131 return rffi.liststr2charpp([space.bytes0_w(space.next(w_iter))
132 for i in range(space.len_w(w_seqstr))])
133
134
135 @unwrap_spec(p2cread=int, p2cwrite=int, c2pread=int, c2pwrite=int,
136 errread=int, errwrite=int, errpipe_read=int, errpipe_write=int,
137 restore_signals=int, call_setsid=int, child_umask=int,
138 allow_vfork=int)
139 def fork_exec(space, w_process_args, w_executable_list,
140 w_close_fds, w_fds_to_keep, w_cwd, w_env_list,
141 p2cread, p2cwrite, c2pread, c2pwrite,
142 errread, errwrite, errpipe_read, errpipe_write,
143 restore_signals, call_setsid, w_pgid_to_set,
144 w_gid, w_groups_list, w_uid, child_umask,
145 w_preexec_fn, allow_vfork):
146 """\
147 fork_exec(args, executable_list, close_fds, cwd, env,
148 p2cread, p2cwrite, c2pread, c2pwrite,
149 errread, errwrite, errpipe_read, errpipe_write,
150 restore_signals, call_setsid, pgid_to_set,
151 preexec_fn, allow_vfork)
152
153 Forks a child process, closes parent file descriptors as appropriate in the
154 child and dups the few that are needed before calling exec() in the child
155 process.
156
157 The preexec_fn, if supplied, will be called immediately before exec.
158 WARNING: preexec_fn is NOT SAFE if your application uses threads.
159 It may trigger infrequent, difficult to debug deadlocks.
160
161 If an error occurs in the child process before the exec, it is
162 serialized and written to the errpipe_write fd per subprocess.py.
163
164 Returns: the child process's PID.
165
166 Raises: Only on an error in the parent process.
167
168 Note: PyPy does not use vfork, so allow_vfork is a NOOP argument
169 """
170 close_fds = space.is_true(w_close_fds)
171 if close_fds and errpipe_write < 3: # precondition
172 raise oefmt(space.w_ValueError, "errpipe_write must be >= 3")
173 fds_to_keep = build_fd_sequence(space, w_fds_to_keep)
174
175 # No need to disable GC in PyPy:
176 # - gc.disable() only disables __del__ anyway.
177 # - appelvel __del__ are only called at specific points of the
178 # interpreter.
179
180 l_exec_array = lltype.nullptr(rffi.CCHARPP.TO)
181 l_argv = lltype.nullptr(rffi.CCHARPP.TO)
182 l_envp = lltype.nullptr(rffi.CCHARPP.TO)
183 l_cwd = lltype.nullptr(rffi.CCHARP.TO)
184 l_fds_to_keep = lltype.nullptr(rffi.CArrayPtr(rffi.LONG).TO)
185 l_groups = lltype.nullptr(rffi.CArrayPtr(gid_t).TO)
186
187 # Convert args and env into appropriate arguments for exec()
188 # These conversions are done in the parent process to avoid allocating
189 # or freeing memory in the child process.
190 try:
191 l_exec_array = seqstr2charpp(space, w_executable_list)
192
193 if not space.is_none(w_process_args):
194 w_iter = space.iter(w_process_args)
195 argv = [space.fsencode_w(space.next(w_iter))
196 for i in range(space.len_w(w_process_args))]
197 l_argv = rffi.liststr2charpp(argv)
198
199 if not space.is_none(w_env_list):
200 l_envp = seqstr2charpp(space, w_env_list)
201
202 l_fds_to_keep = lltype.malloc(rffi.CArrayPtr(rffi.LONG).TO,
203 len(fds_to_keep) + 1, flavor='raw')
204 for i in range(len(fds_to_keep)):
205 l_fds_to_keep[i] = fds_to_keep[i]
206
207 if not space.is_none(w_preexec_fn):
208 preexec.space = space
209 preexec.w_preexec_fn = w_preexec_fn
210 need_after_fork = 1
211 else:
212 preexec.w_preexec_fn = None
213 need_after_fork = 0
214
215 if not space.is_none(w_cwd):
216 cwd = space.fsencode_w(w_cwd)
217 l_cwd = rffi.str2charp(cwd)
218
219 call_setgroups = 0
220 num_groups = 0
221 if not space.is_none(w_groups_list):
222 if not HAVE_SETGROUPS:
223 raise oefmt(space.w_SystemError, "bad internal call, setgroups not supported")
224 groups_w = space.unpackiterable(w_groups_list)
225
226 if len(groups_w) > MAX_GROUPS:
227 raise oefmt(space.w_ValueError, "too many groups")
228 l_groups = lltype.malloc(rffi.CArrayPtr(gid_t).TO,
229 len(groups_w), flavor='raw')
230 for i, w_group in enumerate(groups_w):
231 try:
232 gid_val = space.int_w(w_group)
233 except OperationError as e:
234 if e.match(space, space.w_OverflowError):
235 raise oefmt(space.w_ValueError,
236 "group id is greater than maximum")
237 raise
238 if gid_val < 0:
239 raise oefmt(space.w_ValueError, "group id is negative")
240 l_groups[i] = rffi.cast(gid_t, gid_val)
241 num_groups = len(groups_w)
242 call_setgroups = 1
243
244 call_setgid = 0
245 gid = rffi.cast(gid_t, 0)
246 if not space.is_none(w_gid):
247 if not HAVE_SETREGID:
248 raise oefmt(space.w_SystemError, "bad internal call, setregid not supported")
249 call_setgid = 1
250 gid = rffi.cast(gid_t, space.c_uid_t_w(w_gid))
251
252 call_setuid = 0
253 uid = rffi.cast(uid_t, 0)
254 if not space.is_none(w_uid):
255 if not HAVE_SETREUID:
256 raise oefmt(space.w_SystemError, "bad internal call, setreuid not supported")
257 call_setuid = 1
258 uid = rffi.cast(uid_t, space.c_uid_t_w(w_uid))
259
260 pgid_to_set = rffi.cast(pid_t, -1)
261 if not space.is_none(w_pgid_to_set):
262 if not HAVE_SETPGID:
263 raise oefmt(space.w_SystemError, "bad internal call, setpgid not supported")
264 pgid_to_set = rffi.cast(pid_t, space.int_w(w_pgid_to_set))
265
266 if need_after_fork:
267 run_fork_hooks('before', space)
268
269 try:
270 try:
271 pid = os.fork()
272 except OSError as e:
273 raise wrap_oserror(space, e)
274
275 if pid == 0:
276 # Child process
277 # Code from here to _exit() must only use
278 # async-signal-safe functions, listed at `man 7 signal`
279 # http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
280 if not space.is_none(w_preexec_fn):
281 # We'll be calling back into Python later so we need
282 # to do this. This call may not be async-signal-safe
283 # but neither is calling back into Python. The user
284 # asked us to use hope as a strategy to avoid
285 # deadlock...
286 run_fork_hooks('child', space)
287
288 c_child_exec(
289 l_exec_array, l_argv, l_envp, l_cwd,
290 p2cread, p2cwrite, c2pread, c2pwrite,
291 errread, errwrite, errpipe_read, errpipe_write,
292 close_fds, restore_signals, call_setsid, pgid_to_set,
293 call_setgid, gid, call_setgroups, num_groups, l_groups,
294 call_setuid, uid, child_umask,
295 l_fds_to_keep, len(fds_to_keep),
296 PreexecCallback.run_function, None)
297 os._exit(255)
298 finally:
299 # parent process
300 if need_after_fork:
301 run_fork_hooks('parent', space)
302
303 finally:
304 preexec.w_preexec_fn = None
305
306 if l_cwd:
307 rffi.free_charp(l_cwd)
308 if l_envp:
309 rffi.free_charpp(l_envp)
310 if l_argv:
311 rffi.free_charpp(l_argv)
312 if l_exec_array:
313 rffi.free_charpp(l_exec_array)
314 if l_fds_to_keep:
315 lltype.free(l_fds_to_keep, flavor='raw')
316 if l_groups:
317 lltype.free(l_groups, flavor='raw')
318
319 return space.newint(pid)