Skip to content

Commit aab01e3

Browse files
authored
gh-96670: Raise SyntaxError when parsing NULL bytes (#97594)
1 parent dd53b79 commit aab01e3

File tree

10 files changed

+65
-21
lines changed

10 files changed

+65
-21
lines changed

Diff for: Doc/whatsnew/3.12.rst

+6
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,12 @@ Other Language Changes
8686
* :class:`memoryview` now supports the half-float type (the "e" format code).
8787
(Contributed by Dong-hee Na and Antoine Pitrou in :gh:`90751`.)
8888

89+
* The parser now raises :exc:`SyntaxError` when parsing source code containing
90+
null bytes. (Contributed by Pablo Galindo in :gh:`96670`.)
91+
92+
* :func:`ast.parse` now raises :exc:`SyntaxError` instead of :exc:`ValueError`
93+
when parsing source code containing null bytes. (Contributed by Pablo Galindo
94+
in :gh:`96670`.)
8995

9096
New Modules
9197
===========

Diff for: Include/cpython/fileobject.h

+1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
#endif
44

55
PyAPI_FUNC(char *) Py_UniversalNewlineFgets(char *, int, FILE*, PyObject *);
6+
PyAPI_FUNC(char *) _Py_UniversalNewlineFgetsWithSize(char *, int, FILE*, PyObject *, size_t*);
67

78
/* The std printer acts as a preliminary sys.stderr until the new io
89
infrastructure is in place. */

Diff for: Lib/test/test_ast.py

+4
Original file line numberDiff line numberDiff line change
@@ -844,6 +844,10 @@ def check_limit(prefix, repeated):
844844
check_limit("a", "[0]")
845845
check_limit("a", "*a")
846846

847+
def test_null_bytes(self):
848+
with self.assertRaises(SyntaxError,
849+
msg="source code string cannot contain null bytes"):
850+
ast.parse("a\0b")
847851

848852
class ASTHelpers_Test(unittest.TestCase):
849853
maxDiff = None

Diff for: Lib/test/test_builtin.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -334,11 +334,10 @@ def test_compile(self):
334334
self.assertRaises(TypeError, compile)
335335
self.assertRaises(ValueError, compile, 'print(42)\n', '<string>', 'badmode')
336336
self.assertRaises(ValueError, compile, 'print(42)\n', '<string>', 'single', 0xff)
337-
self.assertRaises(ValueError, compile, chr(0), 'f', 'exec')
338337
self.assertRaises(TypeError, compile, 'pass', '?', 'exec',
339338
mode='eval', source='0', filename='tmp')
340339
compile('print("\xe5")\n', '', 'exec')
341-
self.assertRaises(ValueError, compile, chr(0), 'f', 'exec')
340+
self.assertRaises(SyntaxError, compile, chr(0), 'f', 'exec')
342341
self.assertRaises(ValueError, compile, str('a = 1'), 'f', 'bad')
343342

344343
# test the optimize argument

Diff for: Lib/test/test_cmd_line_script.py

+12
Original file line numberDiff line numberDiff line change
@@ -657,6 +657,18 @@ def test_syntaxerror_invalid_escape_sequence_multi_line(self):
657657
],
658658
)
659659

660+
def test_syntaxerror_null_bytes(self):
661+
script = "x = '\0' nothing to see here\n';import os;os.system('echo pwnd')\n"
662+
with os_helper.temp_dir() as script_dir:
663+
script_name = _make_test_script(script_dir, 'script', script)
664+
exitcode, stdout, stderr = assert_python_failure(script_name)
665+
self.assertEqual(
666+
stderr.splitlines()[-2:],
667+
[ b" x = '",
668+
b'SyntaxError: source code cannot contain null bytes'
669+
],
670+
)
671+
660672
def test_consistent_sys_path_for_direct_execution(self):
661673
# This test case ensures that the following all give the same
662674
# sys.path configuration:

Diff for: Lib/test/test_compile.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -544,7 +544,7 @@ def test_particularly_evil_undecodable(self):
544544
with open(fn, "wb") as fp:
545545
fp.write(src)
546546
res = script_helper.run_python_until_end(fn)[0]
547-
self.assertIn(b"Non-UTF-8", res.err)
547+
self.assertIn(b"source code cannot contain null bytes", res.err)
548548

549549
def test_yet_more_evil_still_undecodable(self):
550550
# Issue #25388
@@ -554,7 +554,7 @@ def test_yet_more_evil_still_undecodable(self):
554554
with open(fn, "wb") as fp:
555555
fp.write(src)
556556
res = script_helper.run_python_until_end(fn)[0]
557-
self.assertIn(b"Non-UTF-8", res.err)
557+
self.assertIn(b"source code cannot contain null bytes", res.err)
558558

559559
@support.cpython_only
560560
@unittest.skipIf(support.is_wasi, "exhausts limited stack on WASI")
@@ -591,9 +591,9 @@ def check_limit(prefix, repeated, mode="single"):
591591
def test_null_terminated(self):
592592
# The source code is null-terminated internally, but bytes-like
593593
# objects are accepted, which could be not terminated.
594-
with self.assertRaisesRegex(ValueError, "cannot contain null"):
594+
with self.assertRaisesRegex(SyntaxError, "cannot contain null"):
595595
compile("123\x00", "<dummy>", "eval")
596-
with self.assertRaisesRegex(ValueError, "cannot contain null"):
596+
with self.assertRaisesRegex(SyntaxError, "cannot contain null"):
597597
compile(memoryview(b"123\x00"), "<dummy>", "eval")
598598
code = compile(memoryview(b"123\x00")[1:-1], "<dummy>", "eval")
599599
self.assertEqual(eval(code), 23)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
The parser now raises :exc:`SyntaxError` when parsing source code containing
2+
null bytes. Patch by Pablo Galindo

Diff for: Objects/fileobject.c

+19-10
Original file line numberDiff line numberDiff line change
@@ -230,16 +230,8 @@ _PyLong_FileDescriptor_Converter(PyObject *o, void *ptr)
230230
return 1;
231231
}
232232

233-
/*
234-
** Py_UniversalNewlineFgets is an fgets variation that understands
235-
** all of \r, \n and \r\n conventions.
236-
** The stream should be opened in binary mode.
237-
** The fobj parameter exists solely for legacy reasons and must be NULL.
238-
** Note that we need no error handling: fgets() treats error and eof
239-
** identically.
240-
*/
241233
char *
242-
Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj)
234+
_Py_UniversalNewlineFgetsWithSize(char *buf, int n, FILE *stream, PyObject *fobj, size_t* size)
243235
{
244236
char *p = buf;
245237
int c;
@@ -265,11 +257,28 @@ Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj)
265257
}
266258
FUNLOCKFILE(stream);
267259
*p = '\0';
268-
if (p == buf)
260+
if (p == buf) {
269261
return NULL;
262+
}
263+
*size = p - buf;
270264
return buf;
271265
}
272266

267+
/*
268+
** Py_UniversalNewlineFgets is an fgets variation that understands
269+
** all of \r, \n and \r\n conventions.
270+
** The stream should be opened in binary mode.
271+
** The fobj parameter exists solely for legacy reasons and must be NULL.
272+
** Note that we need no error handling: fgets() treats error and eof
273+
** identically.
274+
*/
275+
276+
char *
277+
Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj) {
278+
size_t size;
279+
return _Py_UniversalNewlineFgetsWithSize(buf, n, stream, fobj, &size);
280+
}
281+
273282
/* **************************** std printer ****************************
274283
* The stdprinter is used during the boot strapping phase as a preliminary
275284
* file like object for sys.stderr.

Diff for: Parser/tokenizer.c

+15-4
Original file line numberDiff line numberDiff line change
@@ -378,6 +378,11 @@ tok_reserve_buf(struct tok_state *tok, Py_ssize_t size)
378378
return 1;
379379
}
380380

381+
static inline int
382+
contains_null_bytes(const char* str, size_t size) {
383+
return memchr(str, 0, size) != NULL;
384+
}
385+
381386
static int
382387
tok_readline_recode(struct tok_state *tok) {
383388
PyObject *line;
@@ -829,17 +834,17 @@ tok_readline_raw(struct tok_state *tok)
829834
if (!tok_reserve_buf(tok, BUFSIZ)) {
830835
return 0;
831836
}
832-
char *line = Py_UniversalNewlineFgets(tok->inp,
833-
(int)(tok->end - tok->inp),
834-
tok->fp, NULL);
837+
int n_chars = (int)(tok->end - tok->inp);
838+
size_t line_size = 0;
839+
char *line = _Py_UniversalNewlineFgetsWithSize(tok->inp, n_chars, tok->fp, NULL, &line_size);
835840
if (line == NULL) {
836841
return 1;
837842
}
838843
if (tok->fp_interactive &&
839844
tok_concatenate_interactive_new_line(tok, line) == -1) {
840845
return 0;
841846
}
842-
tok->inp = strchr(tok->inp, '\0');
847+
tok->inp += line_size;
843848
if (tok->inp == tok->buf) {
844849
return 0;
845850
}
@@ -1075,6 +1080,12 @@ tok_nextc(struct tok_state *tok)
10751080
return EOF;
10761081
}
10771082
tok->line_start = tok->cur;
1083+
1084+
if (contains_null_bytes(tok->line_start, tok->inp - tok->line_start)) {
1085+
syntaxerror(tok, "source code cannot contain null bytes");
1086+
tok->cur = tok->inp;
1087+
return EOF;
1088+
}
10781089
}
10791090
Py_UNREACHABLE();
10801091
}

Diff for: Python/pythonrun.c

+1-1
Original file line numberDiff line numberDiff line change
@@ -1858,7 +1858,7 @@ _Py_SourceAsString(PyObject *cmd, const char *funcname, const char *what, PyComp
18581858
}
18591859

18601860
if (strlen(str) != (size_t)size) {
1861-
PyErr_SetString(PyExc_ValueError,
1861+
PyErr_SetString(PyExc_SyntaxError,
18621862
"source code string cannot contain null bytes");
18631863
Py_CLEAR(*cmd_copy);
18641864
return NULL;

0 commit comments

Comments
 (0)