-
-
Notifications
You must be signed in to change notification settings - Fork 30.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Compiling recursive Python ASTs crash the interpreter #55314
Comments
You don't want to know why I was thinking about this... $ ./python
Python 3.2rc2+ (py3k:88302, Feb 1 2011, 19:02:10)
[GCC 4.4.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import ast
>>> e = ast.UnaryOp(op=ast.Not(), lineno=0, col_offset=0)
>>> e.operand = e
>>> compile(ast.Expression(e), "<test>", "eval")
Segmentation fault |
Looks like a stack overflow caused by an infinite recursion. I am not sure if it is possible to add cycle detection code without sacrificing performance or setting some arbitrary limits. I wonder: Why ast nodes need to be mutable? |
2011/2/3 Alexander Belopolsky <report@bugs.python.org>:
Yes, it's definitely low priority. It's probably easier to crash the
So people can change them. |
On Thu, Feb 3, 2011 at 12:08 PM, Benjamin Peterson
Well, they are hashable, so this needs to be done carefully. Is this |
2011/2/3 Alexander Belopolsky <report@bugs.python.org>:
>
> Alexander Belopolsky <belopolsky@users.sourceforge.net> added the comment:
>
> On Thu, Feb 3, 2011 at 12:08 PM, Benjamin Peterson
> <report@bugs.python.org> wrote:
> ..
>>> I wonder: Why ast nodes need to be mutable?
>>
>> So people can change them.
>
> Well, they are hashable, so this needs to be done carefully. Is this
> necessary for AST-based optimizations? Does Python actually change
> AST after it has been created? Note that for some optimizations it
> may be more appropriate to build a new tree rather than mutate the old
> one. Depending on the algorithm, you may or may not need to change
> the nodes after they have been created in the process. Other people are, though. The hash is by identity anyway. |
1 similar comment
2011/2/3 Alexander Belopolsky <report@bugs.python.org>:
>
> Alexander Belopolsky <belopolsky@users.sourceforge.net> added the comment:
>
> On Thu, Feb 3, 2011 at 12:08 PM, Benjamin Peterson
> <report@bugs.python.org> wrote:
> ..
>>> I wonder: Why ast nodes need to be mutable?
>>
>> So people can change them.
>
> Well, they are hashable, so this needs to be done carefully. Is this
> necessary for AST-based optimizations? Does Python actually change
> AST after it has been created? Note that for some optimizations it
> may be more appropriate to build a new tree rather than mutate the old
> one. Depending on the algorithm, you may or may not need to change
> the nodes after they have been created in the process. Other people are, though. The hash is by identity anyway. |
Alex: If the node attributes were not mutable, it would be extremely awkward, not to say inefficient, to mutate an already existing AST as returned by ast.parse(). The AST objects in the _ast module aren't what Python works with internally, anyway. When calling ast.parse(), the AST is converted to Python objects (these are defined in Python-ast.c), and compile()ing such an object converts them back to the internal tree representation. This conversion is where recursions would need to be handled. |
i haven't confirmed if it is this exact bug but I believe a coworker just ran into something similar. he wrote code to use the ast to remove docstrings from code before passing it to compile() (as that saves a noticable amount of memory). in the case the ast for code like: def foo():
"""this is a docstring.""" Removing the docstring and passing such a thing to compile triggers a problem. A workaround was to add a pass in such cases: if (node.body and isinstance(node.body[0], ast.Expr) and regardless, it'd be better if compile() *never* crashed on strange input. |
Have him try on 3.3. This should be less of an issue there where there is an AST validator. It doesn't fix this bug, but it does fix most accidental AST construction bugs. |
We can probably implement something like this to prevent this happening
diff --git a/Parser/asdl_c.py b/Parser/asdl_c.py
index daac0966f5..f9da52da7f 100755
--- a/Parser/asdl_c.py
+++ b/Parser/asdl_c.py
@@ -559,6 +559,11 @@ class Obj2ModVisitor(PickleVisitor):
self.emit("asdl_seq_SET(%s, i, val);" % field.name, depth+2)
self.emit("}", depth+1)
else:
+ self.emit("if (obj == tmp) {", depth+1)
+ self.emit("PyErr_SetString(PyExc_RuntimeError, \"Recursing fields "
+ "are not supported for AST nodes.\");", depth+2, reflow=False)
+ self.emit("goto failed;", depth+2)
+ self.emit("}", depth+1)
self.emit("res = obj2ast_%s(tmp, &%s, arena);" %
(field.type, field.name), depth+1)
self.emit("if (res != 0) goto failed;", depth+1) |
What about indirect cycles like below:
(I tested, this also crashes) |
With 3.9 on Windows, using Benjamin's example, I do not get the Windows equivalent of a seg fault. However, execution stops at compile with no exception, including SystemExit. These examples amount to limited fuzz testing of compile(). I think it should raise something like "SyntaxError: recursive ast" or even 'bad ast' if malformed non-recursive asts have the same issue. |
I can still reproduce on Linux, $ python
Python 3.10.0a0 (heads/bpo-xxxxx:f2947e354c, May 21 2020, 18:54:57)
[GCC 9.2.1 20191008] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import ast
>>> e = ast.UnaryOp(op=ast.Not(), lineno=0, col_offset=0)
>>> e.operand = e
>>> compile(ast.Expression(e), "<test>", "eval")
[1] 15320 segmentation fault (core dumped) python
I dont think it would be easy to locate such errors before they happen, instead I propose (actually already proposed in PR 20594) to add recursion guards to places where this might happen. This can prevent crashes on both direct and indirect cycles >>> import ast
>>> e = ast.UnaryOp(op=ast.Not(), lineno=0, col_offset=0)
>>> e.operand = e
>>> compile(ast.Expression(e), "<test>", "eval")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RecursionError: maximum recursion depth exceeded while traversing 'expr' node
>>> e = ast.UnaryOp(op=ast.Not(), lineno=0, col_offset=0)
>>> f = ast.UnaryOp(op=ast.Not(), lineno=0, col_offset=0)
>>> e.operand = f
>>> f.operand = e
>>> compile(ast.Expression(e), "<test>", "eval")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RecursionError: maximum recursion depth exceeded while traversing 'expr' node |
The newly added test One of the buildbots reflects this too: https://buildbot.python.org/all/#/builders/146/builds/337/steps/4/logs/stdio I can avoid the crash by lowering the recursion limit in Python from 1000 to 500. The stack size for a window build is currently set to 2MB, which is usually lesser than *nix 8MB. So I think an easy solution is to increase the stack size for windows builds. I'm guessing release builds aren't affected because some of the Py_EnterRecursiveCall helper functions are probably inlined and thus use less of the stack. Opinions are greatly appreciated. |
Batuhan, can you take a look? |
Yes. |
I don't think that we should make a global change for this case, AFAIK some of the core parts of the interpreter maintain their own recursion checks with different handling of windows limits. E.g; Lines 25 to 40 in fa106a6
We might need to end up with the same motion and do the handling by ourselves. Wdyt @pablogsal @kj? |
After playing with it for a couple hours and without much success of creating a test environment (only using buildbots), I decided not to introduce hard limits. Even though they make the original tests to pass, they don't solve the problem overall and also more important part is that the 'hard limits' might cause regressions for people who do compile(<AST>) calls. For normal windows builds (as @kj noted) something might work in the current revision and we might just break it with introducing hard limits. Since the trees are tend to get really branchy, I don't think it is a good idea. I'm open to any proposals/plans Extra: In the worst case that we can't come up with something (the AST converter functions are really long 2000+ LoC C functions so it is possible that there might be stuff that eats a lot of space on the stack), we can either we might need to revert this though as is it is not a regression. It used to crash with the same exact error, just outside of the test suite, and now since it works for linux/macos/others + windows for release builds I wonder whether can just skip the test on windows and keep it as is in the worst scenario). |
Well, is not that the test is flaky technically, this means that the feature doesn't work on Windows (non release builds). So the reasoning has to be why we want/need to not support this on Windows. Otherwise we need to customize the limit on debug builds. |
The issue has been solved, all buildbots should now pass. Will continue to monitor the situation. Thanks for the report @kj! |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: