Debian Codegraph @

pypy/sandbox/pypy_interact.py

raw symbols SCIP
1 #! /usr/bin/env python
2
3 """Interacts with a PyPy subprocess translated with --sandbox.
4
5 Usage:
6 pypy_interact.py [options] <executable> <args...>
7
8 Options:
9 --tmp=DIR the real directory that corresponds to the virtual /tmp,
10 which is the virtual current dir (always read-only for now)
11 --heapsize=N limit memory usage to N bytes, or kilo- mega- giga-bytes
12 with the 'k', 'm' or 'g' suffix respectively.
13 --timeout=N limit execution time to N (real-time) seconds.
14 --log=FILE log all user input into the FILE.
15 --verbose log all proxied system calls.
16
17 Note that you can get readline-like behavior with a tool like 'ledit',
18 provided you use enough -u options:
19
20 ledit python -u pypy_interact.py pypy3-c-sandbox -u
21 """
22
23 import sys, os
24 sys.path.insert(0, os.path.realpath(os.path.join(os.path.dirname(__file__), '..', '..')))
25 from rpython.translator.sandbox.sandlib import SimpleIOSandboxedProc
26 from rpython.translator.sandbox.sandlib import VirtualizedSandboxedProc
27 from rpython.translator.sandbox.vfs import Dir, RealDir, RealFile
28 import pypy
29 LIB_ROOT = os.path.dirname(os.path.dirname(pypy.__file__))
30
31 class PyPySandboxedProc(VirtualizedSandboxedProc, SimpleIOSandboxedProc):
32 argv0 = '/bin/pypy3-c'
33 virtual_cwd = '/tmp'
34 virtual_env = {}
35 virtual_console_isatty = True
36
37 def __init__(self, executable, arguments, tmpdir=None, debug=True):
38 self.executable = executable = os.path.abspath(executable)
39 self.tmpdir = tmpdir
40 self.debug = debug
41 super(PyPySandboxedProc, self).__init__([self.argv0] + arguments,
42 executable=executable)
43
44 def build_virtual_root(self):
45 # build a virtual file system:
46 # * can access its own executable
47 # * can access the pure Python libraries
48 # * can access the temporary usession directory as /tmp
49 exclude = ['.pyc']
50 if self.tmpdir is None:
51 tmpdirnode = Dir({})
52 else:
53 tmpdirnode = RealDir(self.tmpdir, exclude=exclude)
54 libroot = str(LIB_ROOT)
55
56 return Dir({
57 'bin': Dir({
58 'pypy3-c': RealFile(self.executable, mode=0111),
59 'lib-python': RealDir(os.path.join(libroot, 'lib-python'),
60 exclude=exclude),
61 'lib_pypy': RealDir(os.path.join(libroot, 'lib_pypy'),
62 exclude=exclude),
63 }),
64 'tmp': tmpdirnode,
65 })
66
67 def main():
68 from getopt import getopt # and not gnu_getopt!
69 options, arguments = getopt(sys.argv[1:], 't:hv',
70 ['tmp=', 'heapsize=', 'timeout=', 'log=',
71 'verbose', 'help'])
72 tmpdir = None
73 timeout = None
74 logfile = None
75 debug = False
76 extraoptions = []
77
78 def help():
79 print >> sys.stderr, __doc__
80 sys.exit(2)
81
82 for option, value in options:
83 if option in ['-t', '--tmp']:
84 value = os.path.abspath(value)
85 if not os.path.isdir(value):
86 raise OSError("%r is not a directory" % (value,))
87 tmpdir = value
88 elif option == '--heapsize':
89 value = value.lower()
90 if value.endswith('k'):
91 bytes = int(value[:-1]) * 1024
92 elif value.endswith('m'):
93 bytes = int(value[:-1]) * 1024 * 1024
94 elif value.endswith('g'):
95 bytes = int(value[:-1]) * 1024 * 1024 * 1024
96 else:
97 bytes = int(value)
98 if bytes <= 0:
99 raise ValueError
100 if bytes > sys.maxint:
101 raise OverflowError("--heapsize maximum is %d" % sys.maxint)
102 extraoptions[:0] = ['--heapsize', str(bytes)]
103 elif option == '--timeout':
104 timeout = int(value)
105 elif option == '--log':
106 logfile = value
107 elif option in ['-v', '--verbose']:
108 debug = True
109 elif option in ['-h', '--help']:
110 help()
111 else:
112 raise ValueError(option)
113
114 if len(arguments) < 1:
115 help()
116
117 sandproc = PyPySandboxedProc(arguments[0], extraoptions + arguments[1:],
118 tmpdir=tmpdir, debug=debug)
119 if timeout is not None:
120 sandproc.settimeout(timeout, interrupt_main=True)
121 if logfile is not None:
122 sandproc.setlogfile(logfile)
123 try:
124 sandproc.interact()
125 finally:
126 sandproc.kill()
127
128 if __name__ == '__main__':
129 main()