Skip to content

Commit 44becb8

Browse files
authored
gh-125666: Avoid PyREPL exiting when a null byte is in input (#125732)
1 parent 51b012b commit 44becb8

File tree

4 files changed

+17
-1
lines changed

4 files changed

+17
-1
lines changed

Lib/code.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,8 @@ def _showtraceback(self, typ, value, tb, source):
136136
# Set the line of text that the exception refers to
137137
lines = source.splitlines()
138138
if (source and typ is SyntaxError
139-
and not value.text and len(lines) >= value.lineno):
139+
and not value.text and value.lineno is not None
140+
and len(lines) >= value.lineno):
140141
value.text = lines[value.lineno - 1]
141142
sys.last_exc = sys.last_value = value
142143
if sys.excepthook is sys.__excepthook__:

Lib/test/test_pyrepl/test_interact.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,15 @@ def test_runsource_shows_syntax_error_for_failed_compilation(self):
117117
console.runsource(source)
118118
mock_showsyntaxerror.assert_called_once()
119119

120+
def test_runsource_survives_null_bytes(self):
121+
console = InteractiveColoredConsole()
122+
source = "\x00\n"
123+
f = io.StringIO()
124+
with contextlib.redirect_stdout(f), contextlib.redirect_stderr(f):
125+
result = console.runsource(source)
126+
self.assertFalse(result)
127+
self.assertIn("source code string cannot contain null bytes", f.getvalue())
128+
120129
def test_no_active_future(self):
121130
console = InteractiveColoredConsole()
122131
source = dedent("""\

Lib/test/test_pyrepl/test_pyrepl.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1313,6 +1313,11 @@ def test_proper_tracebacklimit(self):
13131313
self.assertIn("in x3", output)
13141314
self.assertIn("in <module>", output)
13151315

1316+
def test_null_byte(self):
1317+
output, exit_code = self.run_repl("\x00\nexit()\n")
1318+
self.assertEqual(exit_code, 0)
1319+
self.assertNotIn("TypeError", output)
1320+
13161321
def test_readline_history_file(self):
13171322
# skip, if readline module is not available
13181323
readline = import_module('readline')
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Avoid the exiting the interpreter if a null byte is given as input in the new REPL.

0 commit comments

Comments
 (0)