Skip to content

Commit

Permalink
pythongh-125666: Avoid PyREPL exiting when a null byte is in input (p…
Browse files Browse the repository at this point in the history
…ythonGH-125732)

(cherry picked from commit 44becb8)

Co-authored-by: devdanzin <[email protected]>
  • Loading branch information
devdanzin authored and miss-islington committed Oct 27, 2024
1 parent 9e37bfa commit 1c52aa2
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 1 deletion.
3 changes: 2 additions & 1 deletion Lib/code.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,8 @@ def _showtraceback(self, typ, value, tb, source):
# Set the line of text that the exception refers to
lines = source.splitlines()
if (source and typ is SyntaxError
and not value.text and len(lines) >= value.lineno):
and not value.text and value.lineno is not None
and len(lines) >= value.lineno):
value.text = lines[value.lineno - 1]
sys.last_exc = sys.last_value = value = value.with_traceback(tb)
if sys.excepthook is sys.__excepthook__:
Expand Down
9 changes: 9 additions & 0 deletions Lib/test/test_pyrepl/test_interact.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,15 @@ def test_runsource_shows_syntax_error_for_failed_compilation(self):
console.runsource(source)
mock_showsyntaxerror.assert_called_once()

def test_runsource_survives_null_bytes(self):
console = InteractiveColoredConsole()
source = "\x00\n"
f = io.StringIO()
with contextlib.redirect_stdout(f), contextlib.redirect_stderr(f):
result = console.runsource(source)
self.assertFalse(result)
self.assertIn("source code string cannot contain null bytes", f.getvalue())

def test_no_active_future(self):
console = InteractiveColoredConsole()
source = dedent("""\
Expand Down
5 changes: 5 additions & 0 deletions Lib/test/test_pyrepl/test_pyrepl.py
Original file line number Diff line number Diff line change
Expand Up @@ -1313,6 +1313,11 @@ def test_proper_tracebacklimit(self):
self.assertIn("in x3", output)
self.assertIn("in <module>", output)

def test_null_byte(self):
output, exit_code = self.run_repl("\x00\nexit()\n")
self.assertEqual(exit_code, 0)
self.assertNotIn("TypeError", output)

def test_readline_history_file(self):
# skip, if readline module is not available
readline = import_module('readline')
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Avoid the exiting the interpreter if a null byte is given as input in the new REPL.

0 comments on commit 1c52aa2

Please sign in to comment.