Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fix a potential crash in :func:`compile`, :func:`exec`, :func:`eval` and
:func:`ast.parse` when an allocation fails: the parser or compiler could
return without setting an exception.
14 changes: 13 additions & 1 deletion Parser/pegen.c
Original file line number Diff line number Diff line change
Expand Up @@ -940,6 +940,11 @@ _PyPegen_run_parser(Parser *p)
{
void *res = _PyPegen_parse(p);
assert(p->level == 0);
if (res != NULL && PyErr_Occurred()) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we have a way to test this? We can force the allocation failure with _testcapi.set_nomemory (there is precedent in test_exceptions.py) and assert that compile() raises MemoryError instead of crashing on the contract assert.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Never mind I think is fine

// Discard a result returned with an exception still pending
// (e.g. a MemoryError from a recovered-from allocation failure).
return NULL;
}
if (res == NULL) {
if ((p->flags & PyPARSE_ALLOW_INCOMPLETE_INPUT) && _is_end_of_source(p)) {
PyErr_Clear();
Expand Down Expand Up @@ -995,7 +1000,10 @@ _PyPegen_run_parser_from_file_pointer(FILE *fp, int start_rule, PyObject *filena
if (tok == NULL) {
if (PyErr_Occurred()) {
_PyTokenizer_raise_init_error(filename_ob);
return NULL;
}
else {
// The only silent tokenizer init failure is a failed allocation.
PyErr_NoMemory();
}
return NULL;
}
Expand Down Expand Up @@ -1054,6 +1062,10 @@ _PyPegen_run_parser_from_string(const char *str, int start_rule, PyObject *filen
if (PyErr_Occurred()) {
_PyTokenizer_raise_init_error(filename_ob);
}
else {
// The only silent tokenizer init failure is a failed allocation.
PyErr_NoMemory();
}
return NULL;
}
// This transfers the ownership to the tokenizer
Expand Down
1 change: 1 addition & 0 deletions Python/compile.c
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,7 @@ new_compiler(mod_ty mod, PyObject *filename, PyCompilerFlags *pflags,
{
compiler *c = PyMem_Calloc(1, sizeof(compiler));
if (c == NULL) {
PyErr_NoMemory();
return NULL;
}
if (compiler_setup(c, mod, filename, pflags, optimize, arena, module) < 0) {
Expand Down
Loading