From 4100fa3795a53c05043bdb41dcf6f476b3e8309d Mon Sep 17 00:00:00 2001 From: Mark Colley <39366189+M-Colley@users.noreply.github.com> Date: Wed, 2 Dec 2026 14:01:52 +0000 Subject: [PATCH] fix: guard buffer finalization during GC and shutdown --- src/mss/buffer.py | 36 +++++++++++- src/mss/linux/xshmgetimage.py | 46 +++++++++------ src/tests/test_buffer.py | 107 ++++++++++++++++++++++++++++++++++ 3 files changed, 168 insertions(+), 21 deletions(-) diff --git a/src/mss/buffer.py b/src/mss/buffer.py index 2a3605f3..97652e5d 100644 --- a/src/mss/buffer.py +++ b/src/mss/buffer.py @@ -161,6 +161,7 @@ if TYPE_CHECKING: from collections.abc import Callable + from typing import ClassVar from typing_extensions import Buffer @@ -189,9 +190,11 @@ class _FinalizingBufferIntermediate: It is not appropriate for other uses! """ + _pending: ClassVar[dict[int, tuple[memoryview, Callable[[], object]]]] = {} + def __init__(self, data: Buffer, finalizer: Callable) -> None: self._mv: memoryview | None = memoryview(data) - self._finalizer = finalizer + self._finalizer: Callable | None = finalizer # The remainder of these shouldn't be necessary. As a consequence of the __buffer__ contract and the # implementation of finalizing_buffer, only one call to __buffer__ and one call to __release_buffer__ should be # made, and never simultaneously. But we still include them out of an abundance of caution. @@ -199,6 +202,19 @@ def __init__(self, data: Buffer, finalizer: Callable) -> None: self._release_invoked = False self._lock = Lock() + def __del__(self) -> None: + # When GC breaks a reference cycle containing this object while a memoryview still exports it, tp_clear may wipe + # instance attributes before __release_buffer__ runs. Stash the view and finalizer on the class until the + # memoryview releases the buffer. + if getattr(self, "_buffer_invoked", False) and not getattr(self, "_release_invoked", True): + mv = getattr(self, "_mv", None) + finalizer = getattr(self, "_finalizer", None) + if mv is not None and finalizer is not None: + self._pending[id(self)] = (mv, finalizer) + self._mv = None + self._finalizer = None + self._release_invoked = True + def __buffer__(self, _flags: int) -> memoryview: with self._lock: assert not self._buffer_invoked, "Buffer can only be requested once" # noqa: S101 @@ -207,7 +223,18 @@ def __buffer__(self, _flags: int) -> memoryview: return self._mv def __release_buffer__(self, _buffer: memoryview) -> None: - with self._lock: + pending_map = getattr(self, "_pending", None) + pending = pending_map.pop(id(self), None) if pending_map is not None else None + if pending is not None: + mv, finalizer = pending + mv.release() + finalizer() + return + lock = getattr(self, "_lock", None) + if lock is None: + _buffer.release() + return + with lock: assert not self._release_invoked, "Buffer can only be released once" # noqa: S101 self._release_invoked = True assert self._mv is not None, "Buffer has already been released" # noqa: S101 @@ -216,7 +243,10 @@ def __release_buffer__(self, _buffer: memoryview) -> None: # buffers.) self._mv.release() self._mv = None # Extra-defensive - self._finalizer() + finalizer = self._finalizer + self._finalizer = None + assert finalizer is not None # noqa: S101 + finalizer() def finalizing_buffer(data: Buffer, finalizer: Callable) -> memoryview: diff --git a/src/mss/linux/xshmgetimage.py b/src/mss/linux/xshmgetimage.py index d3cc2728..f67bcd03 100644 --- a/src/mss/linux/xshmgetimage.py +++ b/src/mss/linux/xshmgetimage.py @@ -15,6 +15,7 @@ import enum import os +import sys from dataclasses import dataclass from functools import partial from mmap import PROT_READ, PROT_WRITE, mmap # type: ignore[attr-defined] @@ -177,20 +178,25 @@ def _destroy_shm_slot(self, slot: _ShmSlot) -> None: skip explicit detach and let the server clean up the SHM resources when the connection is closed. """ - if slot.buf is None: + buf = getattr(slot, "buf", None) + if buf is None: return - with self._shm_lock: - # If we're about to close the X connection, there's no need to explicitly tell the server about the - # detaches. What's more, the connection might be in an error state. We'll let the server detach all the - # segments at once when we disconnect. However, if we're destroying our SHM slots because XShmGetImage was - # for some reason found to be unsuitable after we created them, then we should be nice and let the server - # clean up resources. - if not self._closing_conn: - assert self.conn is not None # noqa: S101 For MyPy - # One possibility might be to make this a best-effort shutdown, not a hard failure. However, I - # generally don't like suppressing errors if there's not a compelling reason. - xcb.shm_detach(self.conn, slot.shmseg) - slot.buf.close() + lock = getattr(self, "_shm_lock", None) + if lock is not None: + with lock: + # If we're about to close the X connection, there's no need to explicitly tell the server about the + # detaches. What's more, the connection might be in an error state. We'll let the server detach all + # the segments at once when we disconnect. However, if we're destroying our SHM slots because + # XShmGetImage was for some reason found to be unsuitable after we created them, then we should be nice + # and let the server clean up resources. + if not getattr(self, "_closing_conn", True): + conn = getattr(self, "conn", None) + # Skip XCB detach during interpreter shutdown because module globals in xcb/xcbgen may be cleared. + if conn is not None and xcb is not None and sys is not None and not sys.is_finalizing(): + # One possibility might be to make this a best-effort shutdown, not a hard failure. However, I + # generally don't like suppressing errors if there's not a compelling reason. + xcb.shm_detach(conn, slot.shmseg) + buf.close() slot.buf = None def _acquire_shm_slot(self, required_size: int) -> _ShmSlot: @@ -221,11 +227,15 @@ def _release_shm_slot(self, slot: _ShmSlot) -> None: This is called by the finalizer. It might be called during grab, if a copy is needed, or at any time later. """ - with self._shm_lock: - if not self._shm_closed: - self._free_shm_slots.append(slot) - return - # SHM is already closed. Destroy the slot now. + lock = getattr(self, "_shm_lock", None) + if lock is not None: + with lock: + if not getattr(self, "_shm_closed", True): + free_slots = getattr(self, "_free_shm_slots", None) + if free_slots is not None: + free_slots.append(slot) + return + # SHM is already closed (or cleared during GC/shutdown). Destroy the slot now. self._destroy_shm_slot(slot) def _cleanup_shm_slots(self) -> None: diff --git a/src/tests/test_buffer.py b/src/tests/test_buffer.py index 651469ec..724b179f 100644 --- a/src/tests/test_buffer.py +++ b/src/tests/test_buffer.py @@ -3,6 +3,11 @@ """ import gc +import mmap as mmap_mod +import sys +from functools import partial +from threading import RLock +from unittest.mock import Mock import pytest @@ -219,3 +224,105 @@ def finalizer() -> None: intermediate.__buffer__(0) assert finalizer_calls == 1 + + +@pytest.mark.skipif(not FAST_PATH_AVAILABLE, reason="Covers behavior only present in Python 3.12+") +def test_finalizing_buffer_cycle_collection_runs_finalizer(monkeypatch: pytest.MonkeyPatch) -> None: + """Collecting a reference cycle containing the view must still finalize without errors.""" + unraisable: list[sys.UnraisableHookArgs] = [] + monkeypatch.setattr(sys, "unraisablehook", unraisable.append) + + mm = mmap_mod.mmap(-1, 4096) + finalizer_calls = 0 + + def finalizer() -> None: + nonlocal finalizer_calls + finalizer_calls += 1 + mm.close() + + view = finalizing_buffer(memoryview(mm)[:16], finalizer) + cycle: list[object] = [view] + cycle.append(cycle) + del view, cycle + gc.collect() + + assert unraisable == [] + assert finalizer_calls == 1 + assert mm.closed + + +@pytest.mark.skipif(not FAST_PATH_AVAILABLE, reason="Covers behavior only present in Python 3.12+") +def test_xshm_release_after_gc_clear_issue_561(monkeypatch: pytest.MonkeyPatch) -> None: + """Regression test for issue #561: GC clearing MSSImplXShmGetImage before buffer release.""" + monkeypatch.setattr(mmap_mod, "PROT_READ", 1, raising=False) + monkeypatch.setattr(mmap_mod, "PROT_WRITE", 2, raising=False) + + from mss.linux import xcb # noqa: PLC0415 + from mss.linux.xshmgetimage import MSSImplXShmGetImage, _ShmSlot # noqa: PLC0415 + + unraisable: list[sys.UnraisableHookArgs] = [] + monkeypatch.setattr(sys, "unraisablehook", unraisable.append) + + mm = mmap_mod.mmap(-1, 4096) + slot = _ShmSlot(shmseg=xcb.ShmSeg(1), buf=mm, size=4096) + + impl = MSSImplXShmGetImage.__new__(MSSImplXShmGetImage) + impl._shm_lock = RLock() + impl._free_shm_slots = [] + impl._shm_closed = True + impl._closing_conn = True + impl.conn = None + + view = finalizing_buffer(memoryview(mm)[:16], partial(impl._release_shm_slot, slot)) + # Promote impl/view/slot to gen 2 so tp_clear runs on impl before the cycle list drops view. + gc.collect() + + cycle: list[object] = [impl, view] + cycle.append(cycle) + del impl, view, cycle, slot + gc.collect() + + assert unraisable == [] + assert mm.closed + + +def test_xshm_destroy_during_shutdown_skips_detach(monkeypatch: pytest.MonkeyPatch) -> None: + """Destroying a slot during interpreter shutdown must close the buffer without detaching.""" + monkeypatch.setattr(mmap_mod, "PROT_READ", 1, raising=False) + monkeypatch.setattr(mmap_mod, "PROT_WRITE", 2, raising=False) + + from mss.linux import xcb # noqa: PLC0415 + from mss.linux.xshmgetimage import MSSImplXShmGetImage, _ShmSlot # noqa: PLC0415 + + detach_mock = Mock() + monkeypatch.setattr(xcb, "shm_detach", detach_mock) + monkeypatch.setattr(sys, "is_finalizing", lambda: True) + + mm = mmap_mod.mmap(-1, 4096) + slot = _ShmSlot(shmseg=xcb.ShmSeg(1), buf=mm, size=4096) + + impl = MSSImplXShmGetImage.__new__(MSSImplXShmGetImage) + impl._shm_lock = RLock() + impl._free_shm_slots = [] + impl._shm_closed = True + impl._closing_conn = False + impl.conn = xcb.Connection() + + impl._release_shm_slot(slot) + + detach_mock.assert_not_called() + assert mm.closed + assert slot.buf is None + + +@pytest.mark.skipif(not FAST_PATH_AVAILABLE, reason="Covers behavior only present in Python 3.12+") +def test_intermediate_release_when_cleared_releases_inner_buffer() -> None: + """If instance and pending state are cleared during shutdown, releasing still frees the inner view.""" + mm = mmap_mod.mmap(-1, 4096) + intermediate = _FinalizingBufferIntermediate(memoryview(mm)[:16], lambda: None) + view = intermediate.__buffer__(0) + intermediate.__dict__.clear() + + intermediate.__release_buffer__(view) + mm.close() + assert mm.closed