-
Notifications
You must be signed in to change notification settings - Fork 0
/
sandbox.py
57 lines (51 loc) · 1.63 KB
/
sandbox.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import bfinterpreter
import time
class SandboxError(object):
pass
class Sandbox(object):
"""
This is a sandbox for running limited brainfuck programs
"""
def __init__(self, max_time=None, max_mem=None):
"""
Setup the sandbox.
This can accept a maximum time for running, a maximum memory
allocation allowed.
"""
if (max_time==None):
self.max_time=10000
else:
self.max_time = max_time
if (max_mem==None):
self.max_mem=10000
else:
self.max_mem = max_mem
self.start_time = None
def run(self, code=None):
"""
Run some code in this sandbox
"""
if (code==None):
return False
self.bfi = bfinterpreter.BFInterpreter(1000)
self.bfi. preprocess_program(code)
self.start_time = int(time.time())
while len(self.bfi.program)>(self.bfi.instruction_pointer):
if (not self.exceeded()):
self.bfi.step()
else:
return False
return True
def exceeded(self):
"""
Return true if this code has exceeded it's memory or time allowance
"""
return (self.max_mem < len(self.bfi.tape)+len(self.bfi.program)) or (self.max_time < (int(time.time()) - self.start_time))
def top_of_tape(self, n=None):
"""
Get the first n elements of the tape.
"""
if (n==None):
raise SandboxError("No value given")
else:
return self.bfi.tape[0:n]