Skip to content

Commit

Permalink
[3.13] gh-128636: Fix crash in PyREPL when os.environ is overwritte…
Browse files Browse the repository at this point in the history
…n with an invalid value (GH-128653) (#129186)

gh-128636: Fix crash in PyREPL when `os.environ` is overwritten with an invalid value (GH-128653)
(cherry picked from commit ba9a4b6)

Co-authored-by: Tomas R <[email protected]>
  • Loading branch information
miss-islington and tomasr8 authored Jan 22, 2025
1 parent 67971cd commit 0b90dc8
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 5 deletions.
12 changes: 7 additions & 5 deletions Lib/_pyrepl/unix_console.py
Original file line number Diff line number Diff line change
Expand Up @@ -449,10 +449,12 @@ def getheightwidth(self):
"""
try:
return int(os.environ["LINES"]), int(os.environ["COLUMNS"])
except KeyError:
height, width = struct.unpack(
"hhhh", ioctl(self.input_fd, TIOCGWINSZ, b"\000" * 8)
)[0:2]
except (KeyError, TypeError, ValueError):
try:
size = ioctl(self.input_fd, TIOCGWINSZ, b"\000" * 8)
except OSError:
return 25, 80
height, width = struct.unpack("hhhh", size)[0:2]
if not height:
return 25, 80
return height, width
Expand All @@ -468,7 +470,7 @@ def getheightwidth(self):
"""
try:
return int(os.environ["LINES"]), int(os.environ["COLUMNS"])
except KeyError:
except (KeyError, TypeError, ValueError):
return 25, 80

def forgetinput(self):
Expand Down
13 changes: 13 additions & 0 deletions Lib/test/test_pyrepl/test_unix_console.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import itertools
import os
import sys
import unittest
from functools import partial
from test.support import os_helper
from unittest import TestCase
from unittest.mock import MagicMock, call, patch, ANY

Expand Down Expand Up @@ -312,3 +314,14 @@ def same_console(events):
)
console.restore()
con.restore()

def test_getheightwidth_with_invalid_environ(self, _os_write):
# gh-128636
console = UnixConsole()
with os_helper.EnvironmentVarGuard() as env:
env["LINES"] = ""
self.assertIsInstance(console.getheightwidth(), tuple)
env["COLUMNS"] = ""
self.assertIsInstance(console.getheightwidth(), tuple)
os.environ = []
self.assertIsInstance(console.getheightwidth(), tuple)
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix PyREPL failure when :data:`os.environ` is overwritten with an invalid
value.

0 comments on commit 0b90dc8

Please sign in to comment.