Skip to content

Commit dd03d88

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 b9ea60c commit dd03d88

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
@@ -355,6 +355,7 @@ _PyTokenizer_FromFile(FILE *fp, const char* enc,
355355
return NULL;
356356
if ((tok->buf = (char *)PyMem_Malloc(BUFSIZ)) == NULL) {
357357
_PyTokenizer_Free(tok);
358+
PyErr_NoMemory();
358359
return NULL;
359360
}
360361
tok->cur = tok->inp = tok->buf;

Parser/tokenizer/helpers.c

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,7 @@ _PyTokenizer_new_string(const char *s, Py_ssize_t len, struct tok_state *tok)
183183
char* result = (char *)PyMem_Malloc(len + 1);
184184
if (!result) {
185185
tok->done = E_NOMEM;
186+
PyErr_NoMemory();
186187
return NULL;
187188
}
188189
memcpy(result, s, len);
@@ -211,6 +212,7 @@ _PyTokenizer_translate_newlines(const char *s, int exec_input, int preserve_crlf
211212
buf = PyMem_Malloc(needed_length);
212213
if (buf == NULL) {
213214
tok->done = E_NOMEM;
215+
PyErr_NoMemory();
214216
return NULL;
215217
}
216218
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)