Skip to content

Commit ea5b545

Browse files
authored
[3.6] bpo-30696: Fix the REPL looping endlessly when no memory (GH-4160). (#4379)
(cherry picked from commit e0582a3)
1 parent 4e09deb commit ea5b545

File tree

4 files changed

+107
-19
lines changed

4 files changed

+107
-19
lines changed

Doc/c-api/veryhigh.rst

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,8 @@ the same library that the Python runtime is using.
141141
Read and execute statements from a file associated with an interactive device
142142
until EOF is reached. The user will be prompted using ``sys.ps1`` and
143143
``sys.ps2``. *filename* is decoded from the filesystem encoding
144-
(:func:`sys.getfilesystemencoding`). Returns ``0`` at EOF.
144+
(:func:`sys.getfilesystemencoding`). Returns ``0`` at EOF or a negative
145+
number upon failure.
145146
146147
147148
.. c:var:: int (*PyOS_InputHook)(void)

Lib/test/test_repl.py

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
"""Test the interactive interpreter."""
2+
3+
import sys
4+
import os
5+
import unittest
6+
import subprocess
7+
from textwrap import dedent
8+
from test.support import cpython_only, SuppressCrashReport
9+
from test.support.script_helper import kill_python
10+
11+
def spawn_repl(*args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **kw):
12+
"""Run the Python REPL with the given arguments.
13+
14+
kw is extra keyword args to pass to subprocess.Popen. Returns a Popen
15+
object.
16+
"""
17+
18+
# To run the REPL without using a terminal, spawn python with the command
19+
# line option '-i' and the process name set to '<stdin>'.
20+
# The directory of argv[0] must match the directory of the Python
21+
# executable for the Popen() call to python to succeed as the directory
22+
# path may be used by Py_GetPath() to build the default module search
23+
# path.
24+
stdin_fname = os.path.join(os.path.dirname(sys.executable), "<stdin>")
25+
cmd_line = [stdin_fname, '-E', '-i']
26+
cmd_line.extend(args)
27+
28+
# Set TERM=vt100, for the rationale see the comments in spawn_python() of
29+
# test.support.script_helper.
30+
env = kw.setdefault('env', dict(os.environ))
31+
env['TERM'] = 'vt100'
32+
return subprocess.Popen(cmd_line, executable=sys.executable,
33+
stdin=subprocess.PIPE,
34+
stdout=stdout, stderr=stderr,
35+
**kw)
36+
37+
class TestInteractiveInterpreter(unittest.TestCase):
38+
39+
@cpython_only
40+
def test_no_memory(self):
41+
# Issue #30696: Fix the interactive interpreter looping endlessly when
42+
# no memory. Check also that the fix does not break the interactive
43+
# loop when an exception is raised.
44+
user_input = """
45+
import sys, _testcapi
46+
1/0
47+
print('After the exception.')
48+
_testcapi.set_nomemory(0)
49+
sys.exit(0)
50+
"""
51+
user_input = dedent(user_input)
52+
user_input = user_input.encode()
53+
p = spawn_repl()
54+
with SuppressCrashReport():
55+
p.stdin.write(user_input)
56+
output = kill_python(p)
57+
self.assertIn(b'After the exception.', output)
58+
# Exit code 120: Py_FinalizeEx() failed to flush stdout and stderr.
59+
self.assertIn(p.returncode, (1, 120))
60+
61+
if __name__ == "__main__":
62+
unittest.main()
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix the interactive interpreter looping endlessly when no memory.

Python/pythonrun.c

Lines changed: 42 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
6161
PyCompilerFlags *);
6262
static void err_input(perrdetail *);
6363
static void err_free(perrdetail *);
64+
static int PyRun_InteractiveOneObjectEx(FILE *, PyObject *, PyCompilerFlags *);
6465

6566
/* Parse input from a file and execute it */
6667

@@ -86,6 +87,7 @@ PyRun_InteractiveLoopFlags(FILE *fp, const char *filename_str, PyCompilerFlags *
8687
PyObject *filename, *v;
8788
int ret, err;
8889
PyCompilerFlags local_flags;
90+
int nomem_count = 0;
8991

9092
filename = PyUnicode_DecodeFSDefault(filename_str);
9193
if (filename == NULL) {
@@ -107,19 +109,29 @@ PyRun_InteractiveLoopFlags(FILE *fp, const char *filename_str, PyCompilerFlags *
107109
_PySys_SetObjectId(&PyId_ps2, v = PyUnicode_FromString("... "));
108110
Py_XDECREF(v);
109111
}
110-
err = -1;
111-
for (;;) {
112-
ret = PyRun_InteractiveOneObject(fp, filename, flags);
113-
_PY_DEBUG_PRINT_TOTAL_REFS();
114-
if (ret == E_EOF) {
115-
err = 0;
116-
break;
112+
err = 0;
113+
do {
114+
ret = PyRun_InteractiveOneObjectEx(fp, filename, flags);
115+
if (ret == -1 && PyErr_Occurred()) {
116+
/* Prevent an endless loop after multiple consecutive MemoryErrors
117+
* while still allowing an interactive command to fail with a
118+
* MemoryError. */
119+
if (PyErr_ExceptionMatches(PyExc_MemoryError)) {
120+
if (++nomem_count > 16) {
121+
PyErr_Clear();
122+
err = -1;
123+
break;
124+
}
125+
} else {
126+
nomem_count = 0;
127+
}
128+
PyErr_Print();
129+
flush_io();
130+
} else {
131+
nomem_count = 0;
117132
}
118-
/*
119-
if (ret == E_NOMEM)
120-
break;
121-
*/
122-
}
133+
_PY_DEBUG_PRINT_TOTAL_REFS();
134+
} while (ret != E_EOF);
123135
Py_DECREF(filename);
124136
return err;
125137
}
@@ -148,8 +160,11 @@ static int PARSER_FLAGS(PyCompilerFlags *flags)
148160
PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
149161
#endif
150162

151-
int
152-
PyRun_InteractiveOneObject(FILE *fp, PyObject *filename, PyCompilerFlags *flags)
163+
/* A PyRun_InteractiveOneObject() auxiliary function that does not print the
164+
* error on failure. */
165+
static int
166+
PyRun_InteractiveOneObjectEx(FILE *fp, PyObject *filename,
167+
PyCompilerFlags *flags)
153168
{
154169
PyObject *m, *d, *v, *w, *oenc = NULL, *mod_name;
155170
mod_ty mod;
@@ -161,7 +176,6 @@ PyRun_InteractiveOneObject(FILE *fp, PyObject *filename, PyCompilerFlags *flags)
161176

162177
mod_name = _PyUnicode_FromId(&PyId___main__); /* borrowed */
163178
if (mod_name == NULL) {
164-
PyErr_Print();
165179
return -1;
166180
}
167181

@@ -221,7 +235,6 @@ PyRun_InteractiveOneObject(FILE *fp, PyObject *filename, PyCompilerFlags *flags)
221235
PyErr_Clear();
222236
return E_EOF;
223237
}
224-
PyErr_Print();
225238
return -1;
226239
}
227240
m = PyImport_AddModuleObject(mod_name);
@@ -233,15 +246,26 @@ PyRun_InteractiveOneObject(FILE *fp, PyObject *filename, PyCompilerFlags *flags)
233246
v = run_mod(mod, filename, d, d, flags, arena);
234247
PyArena_Free(arena);
235248
if (v == NULL) {
236-
PyErr_Print();
237-
flush_io();
238249
return -1;
239250
}
240251
Py_DECREF(v);
241252
flush_io();
242253
return 0;
243254
}
244255

256+
int
257+
PyRun_InteractiveOneObject(FILE *fp, PyObject *filename, PyCompilerFlags *flags)
258+
{
259+
int res;
260+
261+
res = PyRun_InteractiveOneObjectEx(fp, filename, flags);
262+
if (res == -1) {
263+
PyErr_Print();
264+
flush_io();
265+
}
266+
return res;
267+
}
268+
245269
int
246270
PyRun_InteractiveOneFlags(FILE *fp, const char *filename_str, PyCompilerFlags *flags)
247271
{

0 commit comments

Comments
 (0)