Skip to content

Commit 56cf72d

Browse files
[3.14] gh-144050: Fix stat.filemode pure Python file type detection (GH-144059) (GH-144073)
(cherry picked from commit fe62926) Co-authored-by: VanshAgarwal24036 <148854295+VanshAgarwal24036@users.noreply.github.com>
1 parent 1cfb419 commit 56cf72d

File tree

3 files changed

+15
-3
lines changed

3 files changed

+15
-3
lines changed

Lib/stat.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -166,9 +166,14 @@ def filemode(mode):
166166
perm = []
167167
for index, table in enumerate(_filemode_table):
168168
for bit, char in table:
169-
if mode & bit == bit:
170-
perm.append(char)
171-
break
169+
if index == 0:
170+
if S_IFMT(mode) == bit:
171+
perm.append(char)
172+
break
173+
else:
174+
if mode & bit == bit:
175+
perm.append(char)
176+
break
172177
else:
173178
if index == 0:
174179
# Unknown filetype

Lib/test/test_stat.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,11 @@ def test_mode(self):
163163
self.statmod.S_IFREG)
164164
self.assertEqual(self.statmod.S_IMODE(st_mode), 0o666)
165165

166+
def test_filemode_does_not_misclassify_random_bits(self):
167+
# gh-144050 regression test
168+
self.assertEqual(self.statmod.filemode(0o77777)[0], "?")
169+
self.assertEqual(self.statmod.filemode(0o177777)[0], "?")
170+
166171
@os_helper.skip_unless_working_chmod
167172
def test_directory(self):
168173
os.mkdir(TESTFN)
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix :func:`stat.filemode` in the pure-Python implementation to avoid misclassifying
2+
invalid mode values as block devices.

0 commit comments

Comments
 (0)