Skip to content

Commit 697e78c

Browse files
authored
[3.10] gh-94360: Fix a tokenizer crash when reading encoded files with syntax errors from stdin (GH-94386) (GH-94574)
Signed-off-by: Pablo Galindo <[email protected]> Co-authored-by: Pablo Galindo Salgado <[email protected]> Co-authored-by: Łukasz Langa <[email protected]> (cherry picked from commit 36fcde6)
1 parent 922075c commit 697e78c

File tree

3 files changed

+15
-5
lines changed

3 files changed

+15
-5
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fixed a tokenizer crash when reading encoded files with syntax errors from
2+
``stdin`` with non utf-8 encoded text. Patch by Pablo Galindo

Parser/pegen.c

+4-4
Original file line numberDiff line numberDiff line change
@@ -446,12 +446,12 @@ get_error_line(Parser *p, Py_ssize_t lineno)
446446
Py_ssize_t relative_lineno = p->starting_lineno ? lineno - p->starting_lineno + 1 : lineno;
447447

448448
for (int i = 0; i < relative_lineno - 1; i++) {
449-
char *new_line = strchr(cur_line, '\n') + 1;
450-
assert(new_line != NULL && new_line <= buf_end);
451-
if (new_line == NULL || new_line > buf_end) {
449+
char *new_line = strchr(cur_line, '\n');
450+
assert(new_line != NULL && new_line + 1 < buf_end);
451+
if (new_line == NULL || new_line + 1 > buf_end) {
452452
break;
453453
}
454-
cur_line = new_line;
454+
cur_line = new_line + 1;
455455
}
456456

457457
char *next_newline;

Parser/tokenizer.c

+9-1
Original file line numberDiff line numberDiff line change
@@ -328,6 +328,10 @@ tok_concatenate_interactive_new_line(struct tok_state *tok, const char *line) {
328328

329329
Py_ssize_t current_size = tok->interactive_src_end - tok->interactive_src_start;
330330
Py_ssize_t line_size = strlen(line);
331+
char last_char = line[line_size > 0 ? line_size - 1 : line_size];
332+
if (last_char != '\n') {
333+
line_size += 1;
334+
}
331335
char* new_str = tok->interactive_src_start;
332336

333337
new_str = PyMem_Realloc(new_str, current_size + line_size + 1);
@@ -341,7 +345,11 @@ tok_concatenate_interactive_new_line(struct tok_state *tok, const char *line) {
341345
return -1;
342346
}
343347
strcpy(new_str + current_size, line);
344-
348+
if (last_char != '\n') {
349+
/* Last line does not end in \n, fake one */
350+
new_str[current_size + line_size - 1] = '\n';
351+
new_str[current_size + line_size] = '\0';
352+
}
345353
tok->interactive_src_start = new_str;
346354
tok->interactive_src_end = new_str + current_size + line_size;
347355
return 0;

0 commit comments

Comments
 (0)