Skip to content

Commit eecf3f0

Browse files
grantlouishermanmiss-islington
authored andcommitted
gh-150207: Raise MemoryError on tokenizer allocation failure instead of crashing (GH-150275)
(cherry picked from commit 262625f) Co-authored-by: Grant Herman <grantlouisherman041@gmail.com>
1 parent 4a3d6f9 commit eecf3f0

5 files changed

Lines changed: 9 additions & 1 deletion

File tree

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix a crash when a memory allocation fails during tokenizer initialization. A proper :exc:`MemoryError` is now raised instead.

Parser/lexer/state.c

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,11 @@ _PyTokenizer_tok_new(void)
1515
struct tok_state *tok = (struct tok_state *)PyMem_Calloc(
1616
1,
1717
sizeof(struct tok_state));
18-
if (tok == NULL)
18+
if (tok == NULL) {
19+
PyErr_NoMemory();
1920
return NULL;
21+
}
22+
2023
tok->buf = tok->cur = tok->inp = NULL;
2124
tok->fp_interactive = 0;
2225
tok->interactive_src_start = NULL;

Parser/tokenizer/file_tokenizer.c

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -378,6 +378,7 @@ _PyTokenizer_FromFile(FILE *fp, const char* enc,
378378
return NULL;
379379
if ((tok->buf = (char *)PyMem_Malloc(BUFSIZ)) == NULL) {
380380
_PyTokenizer_Free(tok);
381+
PyErr_NoMemory();
381382
return NULL;
382383
}
383384
tok->cur = tok->inp = tok->buf;

Parser/tokenizer/helpers.c

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,7 @@ _PyTokenizer_new_string(const char *s, Py_ssize_t len, struct tok_state *tok)
193193
char* result = (char *)PyMem_Malloc(len + 1);
194194
if (!result) {
195195
tok->done = E_NOMEM;
196+
PyErr_NoMemory();
196197
return NULL;
197198
}
198199
memcpy(result, s, len);
@@ -221,6 +222,7 @@ _PyTokenizer_translate_newlines(const char *s, int exec_input, int preserve_crlf
221222
buf = PyMem_Malloc(needed_length);
222223
if (buf == NULL) {
223224
tok->done = E_NOMEM;
225+
PyErr_NoMemory();
224226
return NULL;
225227
}
226228
for (current = buf; *s; s++, current++) {

Parser/tokenizer/readline_tokenizer.c

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,7 @@ _PyTokenizer_FromReadline(PyObject* readline, const char* enc,
114114
return NULL;
115115
if ((tok->buf = (char *)PyMem_Malloc(BUFSIZ)) == NULL) {
116116
_PyTokenizer_Free(tok);
117+
PyErr_NoMemory();
117118
return NULL;
118119
}
119120
tok->cur = tok->inp = tok->buf;

0 commit comments

Comments
 (0)