Skip to content

Commit ba9a4b6

Browse files
authored
gh-128636: Fix crash in PyREPL when os.environ is overwritten with an invalid value (#128653)
1 parent 2ed5ee9 commit ba9a4b6

File tree

3 files changed

+22
-5
lines changed

3 files changed

+22
-5
lines changed

Lib/_pyrepl/unix_console.py

+7-5
Original file line numberDiff line numberDiff line change
@@ -449,10 +449,12 @@ def getheightwidth(self):
449449
"""
450450
try:
451451
return int(os.environ["LINES"]), int(os.environ["COLUMNS"])
452-
except KeyError:
453-
height, width = struct.unpack(
454-
"hhhh", ioctl(self.input_fd, TIOCGWINSZ, b"\000" * 8)
455-
)[0:2]
452+
except (KeyError, TypeError, ValueError):
453+
try:
454+
size = ioctl(self.input_fd, TIOCGWINSZ, b"\000" * 8)
455+
except OSError:
456+
return 25, 80
457+
height, width = struct.unpack("hhhh", size)[0:2]
456458
if not height:
457459
return 25, 80
458460
return height, width
@@ -468,7 +470,7 @@ def getheightwidth(self):
468470
"""
469471
try:
470472
return int(os.environ["LINES"]), int(os.environ["COLUMNS"])
471-
except KeyError:
473+
except (KeyError, TypeError, ValueError):
472474
return 25, 80
473475

474476
def forgetinput(self):

Lib/test/test_pyrepl/test_unix_console.py

+13
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
import itertools
2+
import os
23
import sys
34
import unittest
45
from functools import partial
6+
from test.support import os_helper
57
from unittest import TestCase
68
from unittest.mock import MagicMock, call, patch, ANY
79

@@ -312,3 +314,14 @@ def same_console(events):
312314
)
313315
console.restore()
314316
con.restore()
317+
318+
def test_getheightwidth_with_invalid_environ(self, _os_write):
319+
# gh-128636
320+
console = UnixConsole()
321+
with os_helper.EnvironmentVarGuard() as env:
322+
env["LINES"] = ""
323+
self.assertIsInstance(console.getheightwidth(), tuple)
324+
env["COLUMNS"] = ""
325+
self.assertIsInstance(console.getheightwidth(), tuple)
326+
os.environ = []
327+
self.assertIsInstance(console.getheightwidth(), tuple)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix PyREPL failure when :data:`os.environ` is overwritten with an invalid
2+
value.

0 commit comments

Comments
 (0)