Skip to content

Commit 2c3310e

Browse files
lysnikolaoupablogsal
authored andcommitted
gh-103656: Transfer f-string buffers to parser to avoid use-after-free (GH-103896)
Co-authored-by: Pablo Galindo <pablogsal@gmail.com>
1 parent bfa3659 commit 2c3310e

File tree

9 files changed

+146
-66
lines changed

9 files changed

+146
-66
lines changed

Grammar/python.gram

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -881,14 +881,13 @@ fstring_middle[expr_ty]:
881881
| fstring_replacement_field
882882
| t=FSTRING_MIDDLE { _PyPegen_constant_from_token(p, t) }
883883
fstring_replacement_field[expr_ty]:
884-
| '{' a=(yield_expr | star_expressions) debug_expr="="? conversion=[fstring_conversion] format=[fstring_full_format_spec] '}' {
885-
_PyPegen_formatted_value(p, a, debug_expr, conversion, format, EXTRA)
886-
}
884+
| '{' a=(yield_expr | star_expressions) debug_expr="="? conversion=[fstring_conversion] format=[fstring_full_format_spec] rbrace='}' {
885+
_PyPegen_formatted_value(p, a, debug_expr, conversion, format, rbrace, EXTRA) }
887886
| invalid_replacement_field
888-
fstring_conversion[expr_ty]:
887+
fstring_conversion[ResultTokenWithMetadata*]:
889888
| conv_token="!" conv=NAME { _PyPegen_check_fstring_conversion(p, conv_token, conv) }
890-
fstring_full_format_spec[expr_ty]:
891-
| ':' spec=fstring_format_spec* { spec ? _PyAST_JoinedStr((asdl_expr_seq*)spec, EXTRA) : NULL }
889+
fstring_full_format_spec[ResultTokenWithMetadata*]:
890+
| colon=':' spec=fstring_format_spec* { _PyPegen_setup_full_format_spec(p, colon, (asdl_expr_seq *) spec, EXTRA) }
892891
fstring_format_spec[expr_ty]:
893892
| t=FSTRING_MIDDLE { _PyPegen_constant_from_token(p, t) }
894893
| fstring_replacement_field

Lib/test/test_fstring.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1535,5 +1535,19 @@ def test_not_closing_quotes(self):
15351535
self.assertAllRaise(SyntaxError, "unterminated triple-quoted f-string literal",
15361536
['f"""', "f'''"])
15371537

1538+
def test_syntax_error_after_debug(self):
1539+
self.assertAllRaise(SyntaxError, "f-string: expecting a valid expression after '{'",
1540+
[
1541+
"f'{1=}{;'",
1542+
"f'{1=}{+;'",
1543+
"f'{1=}{2}{;'",
1544+
"f'{1=}{3}{;'",
1545+
])
1546+
self.assertAllRaise(SyntaxError, "f-string: expecting '=', or '!', or ':', or '}'",
1547+
[
1548+
"f'{1=}{1;'",
1549+
"f'{1=}{1;}'",
1550+
])
1551+
15381552
if __name__ == '__main__':
15391553
unittest.main()

Parser/action_helpers.c

Lines changed: 51 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -965,17 +965,43 @@ _PyPegen_check_legacy_stmt(Parser *p, expr_ty name) {
965965
return 0;
966966
}
967967

968-
expr_ty
969-
_PyPegen_check_fstring_conversion(Parser *p, Token* symbol, expr_ty conv) {
970-
if (symbol->lineno != conv->lineno || symbol->end_col_offset != conv->col_offset) {
968+
static ResultTokenWithMetadata *
969+
result_token_with_metadata(Parser *p, void *result, PyObject *metadata)
970+
{
971+
ResultTokenWithMetadata *res = _PyArena_Malloc(p->arena, sizeof(ResultTokenWithMetadata));
972+
if (res == NULL) {
973+
return NULL;
974+
}
975+
res->metadata = metadata;
976+
res->result = result;
977+
return res;
978+
}
979+
980+
ResultTokenWithMetadata *
981+
_PyPegen_check_fstring_conversion(Parser *p, Token* conv_token, expr_ty conv)
982+
{
983+
if (conv_token->lineno != conv->lineno || conv_token->end_col_offset != conv->col_offset) {
971984
return RAISE_SYNTAX_ERROR_KNOWN_RANGE(
972-
symbol, conv,
985+
conv_token, conv,
973986
"f-string: conversion type must come right after the exclamanation mark"
974987
);
975988
}
976-
return conv;
989+
return result_token_with_metadata(p, conv, conv_token->metadata);
977990
}
978991

992+
ResultTokenWithMetadata *
993+
_PyPegen_setup_full_format_spec(Parser *p, Token *colon, asdl_expr_seq *spec, int lineno, int col_offset,
994+
int end_lineno, int end_col_offset, PyArena *arena)
995+
{
996+
if (!spec) {
997+
return NULL;
998+
}
999+
expr_ty res = _PyAST_JoinedStr(spec, lineno, col_offset, end_lineno, end_col_offset, p->arena);
1000+
if (!res) {
1001+
return NULL;
1002+
}
1003+
return result_token_with_metadata(p, res, colon->metadata);
1004+
}
9791005

9801006
const char *
9811007
_PyPegen_get_expr_name(expr_ty e)
@@ -1197,27 +1223,6 @@ _PyPegen_nonparen_genexp_in_call(Parser *p, expr_ty args, asdl_comprehension_seq
11971223

11981224
// Fstring stuff
11991225

1200-
static expr_ty
1201-
decode_fstring_buffer(Parser *p, int lineno, int col_offset, int end_lineno,
1202-
int end_col_offset)
1203-
{
1204-
tokenizer_mode *tok_mode = &(p->tok->tok_mode_stack[p->tok->tok_mode_stack_index]);
1205-
assert(tok_mode->last_expr_buffer != NULL);
1206-
assert(tok_mode->last_expr_size >= 0 && tok_mode->last_expr_end >= 0);
1207-
1208-
PyObject *res = PyUnicode_DecodeUTF8(
1209-
tok_mode->last_expr_buffer,
1210-
tok_mode->last_expr_size - tok_mode->last_expr_end,
1211-
NULL
1212-
);
1213-
if (!res || _PyArena_AddPyObject(p->arena, res) < 0) {
1214-
Py_XDECREF(res);
1215-
return NULL;
1216-
}
1217-
1218-
return _PyAST_Constant(res, NULL, lineno, col_offset, end_lineno, end_col_offset, p->arena);
1219-
}
1220-
12211226
static expr_ty
12221227
_PyPegen_decode_fstring_part(Parser* p, int is_raw, expr_ty constant) {
12231228
assert(PyUnicode_CheckExact(constant->v.Constant.value));
@@ -1386,19 +1391,20 @@ expr_ty _PyPegen_constant_from_string(Parser* p, Token* tok) {
13861391
return _PyAST_Constant(s, kind, tok->lineno, tok->col_offset, tok->end_lineno, tok->end_col_offset, p->arena);
13871392
}
13881393

1389-
expr_ty _PyPegen_formatted_value(Parser *p, expr_ty expression, Token *debug, expr_ty conversion,
1390-
expr_ty format, int lineno, int col_offset, int end_lineno, int end_col_offset,
1391-
PyArena *arena) {
1394+
expr_ty _PyPegen_formatted_value(Parser *p, expr_ty expression, Token *debug, ResultTokenWithMetadata *conversion,
1395+
ResultTokenWithMetadata *format, Token *closing_brace, int lineno, int col_offset,
1396+
int end_lineno, int end_col_offset, PyArena *arena) {
13921397
int conversion_val = -1;
13931398
if (conversion != NULL) {
1394-
assert(conversion->kind == Name_kind);
1395-
Py_UCS4 first = PyUnicode_READ_CHAR(conversion->v.Name.id, 0);
1399+
expr_ty conversion_expr = (expr_ty) conversion->result;
1400+
assert(conversion_expr->kind == Name_kind);
1401+
Py_UCS4 first = PyUnicode_READ_CHAR(conversion_expr->v.Name.id, 0);
13961402

1397-
if (PyUnicode_GET_LENGTH(conversion->v.Name.id) > 1 ||
1403+
if (PyUnicode_GET_LENGTH(conversion_expr->v.Name.id) > 1 ||
13981404
!(first == 's' || first == 'r' || first == 'a')) {
1399-
RAISE_SYNTAX_ERROR_KNOWN_LOCATION(conversion,
1405+
RAISE_SYNTAX_ERROR_KNOWN_LOCATION(conversion_expr,
14001406
"f-string: invalid conversion character %R: expected 's', 'r', or 'a'",
1401-
conversion->v.Name.id);
1407+
conversion_expr->v.Name.id);
14021408
return NULL;
14031409
}
14041410

@@ -1410,30 +1416,34 @@ expr_ty _PyPegen_formatted_value(Parser *p, expr_ty expression, Token *debug, ex
14101416
}
14111417

14121418
expr_ty formatted_value = _PyAST_FormattedValue(
1413-
expression, conversion_val, format,
1419+
expression, conversion_val, format ? (expr_ty) format->result : NULL,
14141420
lineno, col_offset, end_lineno,
14151421
end_col_offset, arena
14161422
);
14171423

14181424
if (debug) {
14191425
/* Find the non whitespace token after the "=" */
14201426
int debug_end_line, debug_end_offset;
1427+
PyObject *debug_metadata;
14211428

14221429
if (conversion) {
1423-
debug_end_line = conversion->lineno;
1424-
debug_end_offset = conversion->col_offset;
1430+
debug_end_line = ((expr_ty) conversion->result)->lineno;
1431+
debug_end_offset = ((expr_ty) conversion->result)->col_offset;
1432+
debug_metadata = conversion->metadata;
14251433
}
14261434
else if (format) {
1427-
debug_end_line = format->lineno;
1428-
debug_end_offset = format->col_offset + 1; // HACK: ??
1435+
debug_end_line = ((expr_ty) format->result)->lineno;
1436+
debug_end_offset = ((expr_ty) format->result)->col_offset + 1;
1437+
debug_metadata = format->metadata;
14291438
}
14301439
else {
14311440
debug_end_line = end_lineno;
14321441
debug_end_offset = end_col_offset;
1442+
debug_metadata = closing_brace->metadata;
14331443
}
14341444

1435-
expr_ty debug_text = decode_fstring_buffer(p, lineno, col_offset + 1,
1436-
debug_end_line, debug_end_offset - 1);
1445+
expr_ty debug_text = _PyAST_Constant(debug_metadata, NULL, lineno, col_offset + 1, debug_end_line,
1446+
debug_end_offset - 1, p->arena);
14371447
if (!debug_text) {
14381448
return NULL;
14391449
}

Parser/parser.c

Lines changed: 12 additions & 12 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Parser/pegen.c

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,16 @@ initialize_token(Parser *p, Token *parser_token, struct token *new_token, int to
155155
return -1;
156156
}
157157

158+
parser_token->metadata = NULL;
159+
if (new_token->metadata != NULL) {
160+
if (_PyArena_AddPyObject(p->arena, new_token->metadata) < 0) {
161+
Py_DECREF(parser_token->metadata);
162+
return -1;
163+
}
164+
parser_token->metadata = new_token->metadata;
165+
new_token->metadata = NULL;
166+
}
167+
158168
parser_token->level = new_token->level;
159169
parser_token->lineno = new_token->lineno;
160170
parser_token->col_offset = p->tok->lineno == p->starting_lineno ? p->starting_col_offset + new_token->col_offset
@@ -198,6 +208,7 @@ int
198208
_PyPegen_fill_token(Parser *p)
199209
{
200210
struct token new_token;
211+
new_token.metadata = NULL;
201212
int type = _PyTokenizer_Get(p->tok, &new_token);
202213

203214
// Record and skip '# type: ignore' comments
@@ -206,14 +217,14 @@ _PyPegen_fill_token(Parser *p)
206217
char *tag = PyMem_Malloc(len + 1);
207218
if (tag == NULL) {
208219
PyErr_NoMemory();
209-
return -1;
220+
goto error;
210221
}
211222
strncpy(tag, new_token.start, len);
212223
tag[len] = '\0';
213224
// Ownership of tag passes to the growable array
214225
if (!growable_comment_array_add(&p->type_ignore_comments, p->tok->lineno, tag)) {
215226
PyErr_NoMemory();
216-
return -1;
227+
goto error;
217228
}
218229
type = _PyTokenizer_Get(p->tok, &new_token);
219230
}
@@ -234,11 +245,14 @@ _PyPegen_fill_token(Parser *p)
234245

235246
// Check if we are at the limit of the token array capacity and resize if needed
236247
if ((p->fill == p->size) && (_resize_tokens_array(p) != 0)) {
237-
return -1;
248+
goto error;
238249
}
239250

240251
Token *t = p->tokens[p->fill];
241252
return initialize_token(p, t, &new_token, type);
253+
error:
254+
Py_XDECREF(new_token.metadata);
255+
return -1;
242256
}
243257

244258
#if defined(Py_DEBUG)

Parser/pegen.h

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ typedef struct {
3939
int level;
4040
int lineno, col_offset, end_lineno, end_col_offset;
4141
Memo *memo;
42+
PyObject *metadata;
4243
} Token;
4344

4445
typedef struct {
@@ -118,6 +119,11 @@ typedef struct {
118119
int is_keyword;
119120
} KeywordOrStarred;
120121

122+
typedef struct {
123+
void *result;
124+
PyObject *metadata;
125+
} ResultTokenWithMetadata;
126+
121127
// Internal parser functions
122128
#if defined(Py_DEBUG)
123129
void _PyPegen_clear_memo_statistics(void);
@@ -310,7 +316,8 @@ StarEtc *_PyPegen_star_etc(Parser *, arg_ty, asdl_seq *, arg_ty);
310316
arguments_ty _PyPegen_make_arguments(Parser *, asdl_arg_seq *, SlashWithDefault *,
311317
asdl_arg_seq *, asdl_seq *, StarEtc *);
312318
arguments_ty _PyPegen_empty_arguments(Parser *);
313-
expr_ty _PyPegen_formatted_value(Parser *, expr_ty, Token *, expr_ty, expr_ty, int, int, int, int, PyArena *);
319+
expr_ty _PyPegen_formatted_value(Parser *, expr_ty, Token *, ResultTokenWithMetadata *, ResultTokenWithMetadata *, Token *,
320+
int, int, int, int, PyArena *);
314321
AugOperator *_PyPegen_augoperator(Parser*, operator_ty type);
315322
stmt_ty _PyPegen_function_def_decorators(Parser *, asdl_expr_seq *, stmt_ty);
316323
stmt_ty _PyPegen_class_def_decorators(Parser *, asdl_expr_seq *, stmt_ty);
@@ -329,7 +336,9 @@ expr_ty _PyPegen_ensure_real(Parser *p, expr_ty);
329336
asdl_seq *_PyPegen_join_sequences(Parser *, asdl_seq *, asdl_seq *);
330337
int _PyPegen_check_barry_as_flufl(Parser *, Token *);
331338
int _PyPegen_check_legacy_stmt(Parser *p, expr_ty t);
332-
expr_ty _PyPegen_check_fstring_conversion(Parser *p, Token *, expr_ty t);
339+
ResultTokenWithMetadata *_PyPegen_check_fstring_conversion(Parser *p, Token *, expr_ty t);
340+
ResultTokenWithMetadata *_PyPegen_setup_full_format_spec(Parser *, Token *, asdl_expr_seq *, int, int,
341+
int, int, PyArena *);
333342
mod_ty _PyPegen_make_module(Parser *, asdl_stmt_seq *);
334343
void *_PyPegen_arguments_parsing_error(Parser *, expr_ty);
335344
expr_ty _PyPegen_get_last_comprehension_item(comprehension_ty comprehension);

0 commit comments

Comments
 (0)