这是我对这个问题的看法。要求用户脚本在vanilla CPython中运行意味着你需要为你的迷你语言编写解释器,或将其编译为Python字节码(或使用Python作为源语言),然后在执行之前“清理”字节码。
我假设用户可以用Python编写他们的脚本,并且源代码和字节码可以通过从解析树过滤不安全的语法和/或从字节码中删除不安全的操作码的某种组合来得到足够的净化。
解决方案的第二部分要求用户脚本字节码被一个看门狗任务周期性地中断,以确保用户脚本不超过一些操作码限制,并且所有这些都在vanilla CPython上运行。
我的尝试总结,主要关注问题的第二部分。
- 用户脚本用Python编写。
- 使用byteplay过滤和修改字节码。
- 仪表用户的字节码以插入操作码计数器和调用函数的调用,该函数上下文切换到看门狗任务。
- 使用greenlet执行用户的字节码,使用yield在用户的脚本和看门狗协程之间切换。
- 看门狗强制执行预设的操作码数量限制,如果超出则引发错误。
希望这至少朝着正确的方向前进。当你到达时,我很想听听你的解决方案。
lowperf.py
的源代码:
import ast
import dis
import sys
from pprint import pprint
import byteplay
import greenlet
INCREMENT = [
(byteplay.LOAD_GLOBAL, '__op_counter'),
(byteplay.LOAD_CONST, 1),
(byteplay.INPLACE_ADD, None),
(byteplay.STORE_GLOBAL, '__op_counter')
]
YIELD = [
(byteplay.LOAD_GLOBAL, '__yield'),
(byteplay.LOAD_GLOBAL, '__op_counter'),
(byteplay.CALL_FUNCTION, 1),
(byteplay.POP_TOP, None)
]
def instrument(orig):
"""
Instrument bytecode. We place a call to our yield function before
jumps and returns. You could choose alternate places depending on
your use case.
"""
line_count = 0
res = []
for op, arg in orig.code:
line_count += 1
if op == byteplay.LOAD_CONST and isinstance(arg, byteplay.Code):
code = instrument(arg)
res.append((op, code))
continue
if op == byteplay.SetLineno:
res += INCREMENT
line_count += 1
res.append((op, arg))
if op in (byteplay.JUMP_ABSOLUTE, byteplay.RETURN_VALUE) \
or line_count > 10:
res += YIELD
line_count = 0
return byteplay.Code(res, orig.freevars, orig.args, orig.varargs,
orig.varkwargs, orig.newlocals, orig.name, orig.filename,
orig.firstlineno, orig.docstring)
def transform(path):
"""
Transform the Python source into a form safe to execute and return
the bytecode.
"""
data = open(path, 'rb').read()
suite = compile(data, path, 'exec')
orig = byteplay.Code.from_code(suite)
return instrument(orig)
def execute(path, limit = 40):
"""
This transforms the user's source code into bytecode, instrumenting
it, then kicks off the watchdog and user script tasklets.
"""
code = transform(path)
target = greenlet.greenlet(run_task)
def watcher_task(op_count):
"""
Task which is yielded to by the user script, making sure it doesn't
use too many resources.
"""
while 1:
if op_count > limit:
raise RuntimeError("script used too many resources")
op_count = target.switch()
watcher = greenlet.greenlet(watcher_task)
target.switch(code, watcher.switch)
def run_task(code, yield_func):
"This is the greenlet task which runs our user's script."
globals_ = {'__yield': yield_func, '__op_counter': 0}
eval(code.to_code(), globals_, globals_)
execute(sys.argv[1])
这里是一个示例用户脚本 user.py
:
def otherfunc(b):
return b * 7
def myfunc(a):
for i in range(0, 20):
print i, otherfunc(i + a + 3)
myfunc(2)
这是一个样例运行:
% python lowperf.py user.py
0 35
1 42
2 49
3 56
4 63
5 70
6 77
7 84
8 91
9 98
10 105
11 112
Traceback (most recent call last):
File "lowperf.py", line 114, in <module>
execute(sys.argv[1])
File "lowperf.py", line 105, in execute
target.switch(code, watcher.switch)
File "lowperf.py", line 101, in watcher_task
raise RuntimeError("script used too many resources")
RuntimeError: script used too many resources