Skip to content

Fix event tap use-after-free when callback returns a copied CGEvent - #1143

Merged
lujjjh merged 1 commit into
mainfrom
fix/event-tap-copy-memory-management
Apr 11, 2026
Merged

lujjjh merged 1 commit into
mainfrom
fix/event-tap-copy-memory-management

Conversation

@lujjjh

@lujjjh lujjjh commented Apr 11, 2026

Copy link
Copy Markdown
Collaborator

Summary

  • Fix use-after-free in EventTap.callbackInvoker when a transformer returns a copy of the CGEvent instead of the original. Unmanaged.passUnretained caused ARC to deallocate the copy before the system could use it, resulting in "Invalid event returned by callback" and the event tap being silently disabled.
  • Use passRetained when the returned event is a different object (detected via ===), transferring ownership to the caller per the CGEventTapCallBack contract. Keep passUnretained for the original event to avoid leaks.
  • Add a periodic health check (every 5s) that re-enables the event tap if it is found disabled, as a defensive recovery mechanism.

Context

When horizontal smoothed scrolling is enabled and a scroll event contains both horizontal and vertical deltas (e.g. M720 Triathlon scroll wheel tilted during fast scrolling), SmoothedScrollingTransformer intercepts the horizontal component and returns a CGEvent.copy() with the horizontal delta zeroed out. This copy was returned via passUnretained, leading to a dangling pointer that macOS detected as invalid, disabling the event tap and breaking all event processing (reverse scrolling, linear scrolling, etc.) until app restart.

Test plan

  • Fast scroll with a Logitech mouse while slightly tilting the scroll wheel — verify reverse scrolling continues to work
  • Verify horizontal smoothed scrolling still works correctly
  • Verify no memory leaks with Instruments (Leaks template) during extended scrolling
  • Verify event tap recovers after simulated timeout disable

When a transformer (e.g. SmoothedScrollingTransformer) returns a copy of
the event instead of the original, `Unmanaged.passUnretained` caused the
copy to be deallocated by ARC before the system could use it. This led to
"Invalid event returned by callback" and the event tap being silently
disabled, breaking all event processing (e.g. reverse scrolling).

Fix: use `passRetained` when the returned event differs from the original,
transferring ownership to the system per the CGEventTapCallBack contract.

Also add a periodic health check that re-enables the tap if it is found
disabled, as a defensive recovery for any remaining edge cases.
@lujjjh
lujjjh force-pushed the fix/event-tap-copy-memory-management branch from 7683044 to 918b455 Compare April 11, 2026 07:12
@lujjjh lujjjh added the bug Something isn't working label Apr 11, 2026
@lujjjh
lujjjh merged commit 9cf8a89 into main Apr 11, 2026
1 check passed
@lujjjh
lujjjh deleted the fix/event-tap-copy-memory-management branch April 11, 2026 07:13
lujjjh pushed a commit that referenced this pull request Apr 17, 2026
## Problem

Fixes #1138

After a gesture fires (e.g., Mission Control swipe), the trigger
button's `mouseUp` event is consumed during cooldown but no release is
ever posted. This leaves macOS believing the button is permanently
pressed, causing:

- **Stuck dragging** in apps like Todoist
- **Persistent right-click menus** if right-click is the trigger  
- **Continuous scrolling** or other unwanted behavior
- Quitting LinearMouse immediately resolves the issue

Reproduced with Logitech MX Master 3 on macOS 26.x, but affects any
mouse using the gesture button feature.

## Root Cause

The state machine in `GestureButtonTransformer` has an asymmetry between
mouseDown and mouseUp handling:

1. `handleButtonDown` **passes mouseDown through** to the app → app sees
"button pressed"
2. `handleDragged` consumes drag events while tracking gesture movement
3. Gesture threshold met → gesture executes → state enters `.cooldown`
4. User releases button → **cooldown guard consumes mouseUp** (`return
nil`)
5. `handleButtonUp` is **never reached**
6. App never sees the button release → **button stuck**

## Fix

Tag and return the **original** mouseUp event from `transform()` instead
of consuming it or creating a new event.

### Key design decisions

**Tag original event, don't create a new one:** The initial approach
(commit `22fe756`) used `releaseTriggerButton()` to create a new
`CGEvent` and post it via `CGEvent.post()`. Review feedback identified
two problems: (1) the `isLinearMouseSyntheticEvent` guard needed to
prevent re-entrance was too broad, and (2) creating new events risks the
`Unmanaged.passUnretained` use-after-free fixed in #1143. This commit
tags the original event (which the framework already retains) with
`isGestureCleanupRelease` and returns it directly — no re-entrance
possible, no ownership issues.

**Preserve cooldown on release:** The cooldown state now tracks
`released: Bool` instead of resetting to `.idle` on mouseUp. This
preserves the full cooldown window so rapid re-presses are still
suppressed.

**Dedicated cleanup flag:** The returned mouseUp flows through the
transformer pipeline into `ButtonActionsTransformer` and
`UniversalBackForwardTransformer`. Without protection, a completed
gesture on a shared trigger button would also fire the mapped action on
release. A dedicated `isGestureCleanupRelease` flag (separate from the
generic `isLinearMouseSyntheticEvent`) lets those transformers pass the
event through without firing actions.

## Changes

- **`GestureButtonTransformer.swift`**: Remove
`isLinearMouseSyntheticEvent` guard. Return original mouseUp tagged with
`isGestureCleanupRelease` instead of creating a new event. Track
`released` in cooldown state. Remove `releaseTriggerButton()` method.
- **`CGEvent+LinearMouseSynthetic.swift`**: Add
`isGestureCleanupRelease` flag with dedicated sentinel value
(`0x4745_5354_5552`).
- **`ButtonActionsTransformer.swift`**: Pass through gesture cleanup
releases without firing mapped actions.
- **`UniversalBackForwardTransformer.swift`**: Pass through gesture
cleanup releases without consuming them.

## Evidence

### Before (broken) — drag fails after gesture


https://github.com/user-attachments/assets/be2c675c-2a81-49cb-9806-0cd7111b37d1

### After (fix) — drag works after gesture


https://github.com/user-attachments/assets/0c095708-2779-4118-969b-848ca28cc150

## Pre-existing issues (not regressions)

These are pre-existing issues with the "shared trigger" case (same
button used for both gesture trigger and button mapping) that predate
this PR:

- **Modifier-hold cleanup on gesture completion:** When a gesture fires
on a button that also has a modifier-hold mapping, `keySimulator.up()`
is never called because the mouseUp was consumed during cooldown (even
before this PR). This leaves modifier keys stuck.

- **Repeat timer cleanup:** Similarly, repeat-enabled mappings sharing
the gesture trigger don't get their timer invalidated on gesture
completion.

- **UniversalBackForward conflict on mouseDown:** If a back/forward
button is used as a gesture trigger with `universalBackForward` enabled,
the mouseDown still fires a navigation swipe immediately (before gesture
tracking begins).

- **Dead `.triggered` state:** The `.triggered` state is set and
immediately overwritten by `.cooldown` in the same synchronous call, so
`handleButtonUp` never observes it. Could be removed as cleanup.

## Test plan

- [x] Enable gesture button with middle button as trigger
- [x] Perform a gesture (hold trigger + swipe up for Mission Control)
- [x] Verify trigger button is released after the gesture completes
- [x] Verify drag operations work in apps after performing a gesture
- [x] Verify gestures still fire correctly after multiple uses (no
use-after-free)
- [x] Verify cooldown still prevents accidental re-triggers
- [x] Verify normal click behavior when gesture doesn't fire (release
before threshold)
- [ ] Test with Logitech MX Master 3 using HID++ diverted gesture button
- [ ] If using a Kensington Slimblade or generic side-button mouse,
verify gesture triggers still work (synthetic button source)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant