Skip to content

Commit ae132ed

Browse files
authored
gh-129766: Fix crash on calling warnings._release_lock with no lock (#129771)
1 parent e2064d6 commit ae132ed

File tree

3 files changed

+19
-3
lines changed

3 files changed

+19
-3
lines changed

Lib/test/test_warnings/__init__.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1432,6 +1432,17 @@ class PyEnvironmentVariableTests(EnvironmentVariableTests, unittest.TestCase):
14321432
module = py_warnings
14331433

14341434

1435+
class LocksTest(unittest.TestCase):
1436+
@support.cpython_only
1437+
@unittest.skipUnless(c_warnings, 'C module is required')
1438+
def test_release_lock_no_lock(self):
1439+
with self.assertRaisesRegex(
1440+
RuntimeError,
1441+
'cannot release un-acquired lock',
1442+
):
1443+
c_warnings._release_lock()
1444+
1445+
14351446
class _DeprecatedTest(BaseTest, unittest.TestCase):
14361447

14371448
"""Test _deprecated()."""
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix crash in :mod:`warnings`, when calling ``_release_lock()`` with no
2+
existing lock.

Python/_warnings.c

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -240,12 +240,12 @@ warnings_lock(PyInterpreterState *interp)
240240
_PyRecursiveMutex_Lock(&st->lock);
241241
}
242242

243-
static inline void
243+
static inline int
244244
warnings_unlock(PyInterpreterState *interp)
245245
{
246246
WarningsState *st = warnings_get_state(interp);
247247
assert(st != NULL);
248-
_PyRecursiveMutex_Unlock(&st->lock);
248+
return _PyRecursiveMutex_TryUnlock(&st->lock);
249249
}
250250

251251
static inline bool
@@ -284,7 +284,10 @@ warnings_release_lock_impl(PyObject *module)
284284
if (interp == NULL) {
285285
return NULL;
286286
}
287-
warnings_unlock(interp);
287+
if (warnings_unlock(interp) < 0) {
288+
PyErr_SetString(PyExc_RuntimeError, "cannot release un-acquired lock");
289+
return NULL;
290+
}
288291
Py_RETURN_NONE;
289292
}
290293

0 commit comments

Comments
 (0)