Permalink
Browse files

Set a default recursion limit to 50 frames

  • Loading branch information...
vstinner committed Mar 20, 2012
1 parent ae5a0bf commit fbdfa2539eb353e946c619406c7b6b6baa01adea
Showing with 43 additions and 0 deletions.
  1. +4 −0 doc/cpython.rst
  2. +3 −0 sandbox/__init__.py
  3. +1 −0 sandbox/config.py
  4. +13 −0 sandbox/recursion.py
  5. +22 −0 sandbox/test/test_recursion.py
View
@@ -1,3 +1,7 @@
+Python 2.x has a restriced mode. It is enabled when the builtins attribute of a
+frame is different from the interpreter builtins. The restricted mode is used
+by the Python rexec module.
+
``frame.f_restricted``: ``True if frame.builtins is not interpreter.builtins``
Restricted
View
@@ -49,4 +49,7 @@ def disable(self, sandbox):
from .code import DisableCode
Sandbox.PROTECTIONS.append(DisableCode)
+from .recursion import SetRecursionLimit
+Sandbox.PROTECTIONS.append(SetRecursionLimit)
+
from .timeout import Timeout
View
@@ -62,6 +62,7 @@ def __init__(self, *features, **kw):
- SandboxConfig('stdout', 'stderr')
- SandboxConfig('interpreter', cpython_restricted=True)
"""
+ self.recusion_limit = 50
# open() whitelist: see safe_open()
self._open_whitelist = set()
View
@@ -0,0 +1,13 @@
+import sys
+
+class SetRecursionLimit:
+ def __init__(self):
+ self.old_limit = sys.getrecursionlimit()
+
+ def enable(self, sandbox):
+ self.old_limit = sys.getrecursionlimit()
+ sys.setrecursionlimit(sandbox.config.recusion_limit)
+
+ def disable(self, sandbox):
+ sys.setrecursionlimit(self.old_limit)
+
@@ -0,0 +1,22 @@
+from sandbox import Sandbox
+from sandbox.test import createSandboxConfig
+import math
+
+def test_recusion():
+ def factorial(n):
+ if n >= 2:
+ return n * factorial(n - 1)
+ else:
+ return 1
+
+ config = createSandboxConfig()
+ max_frames = config.recusion_limit + 1
+ try:
+ Sandbox(config).call(factorial, max_frames)
+ except RuntimeError, err:
+ assert str(err) == 'maximum recursion depth exceeded'
+ else:
+ assert False
+
+ assert factorial(max_frames) == math.factorial(max_frames)
+

0 comments on commit fbdfa25

Please sign in to comment.