Skip to content

fix(interceptor): invalidate event tap CFMachPort on deinit - #999

Merged
Caldis merged 2 commits into
Caldis:masterfrom
MrMage:fix-interceptor-tap-leak
Aug 4, 2026
Merged

Caldis merged 2 commits into
Caldis:masterfrom
MrMage:fix-interceptor-tap-leak

Conversation

@MrMage

@MrMage MrMage commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

This PR fixes a resource leak in Interceptor that seems to be the cause of #970: after the Mac has been asleep (or users switch accounts) repeatedly, the whole system's input becomes laggy while Mos itself shows ~0% CPU, and killing Mos restores fluidity.

The same bug class was recently root-caused, fixed, and confirmed in Karabiner-Elements (pqrs-org/Karabiner-Elements#4505 — includes a video of the symptom) and in Easydict (tisfeng/Easydict#1170, maintainer-confirmed). Scripts to reproduce and observe the leak are at the bottom.

Fixes #970. Plausibly also related to the intermittent post-idle scroll delays in #627.

This fix and analysis were prepared with AI assistance (Claude), per CONTRIBUTING.md: I understand every changed line (except for the Chinese comments 😅), and all measurements/repro outputs below are from a real machine (macOS 26.5, Apple Silicon), reviewed by a human.

Motivation / mechanism

CoreGraphics holds internal references to the CFMachPort returned by CGEventTapCreate (observed retain count 4 immediately after creation), so releasing the client reference never deallocates it — and the WindowServer keeps the (disabled) event-tap registration until the process exits. The only correct disposal is an explicit CFMachPortInvalidate.

Interceptor.deinit currently does CGEvent.tapEnable(false) + CFRunLoopRemoveSource + nils the references — without the invalidate. Every deallocated Interceptor therefore leaks one zombie registration in the WindowServer's global tap table:

  • ScrollCore.disable() + ButtonCore.disable() destroy 5 interceptors on every willSleepNotification / sessionDidResignActiveNotification, recreated on wake — so each sleep/wake or fast-user-switch cycle leaks 5 registrations.
  • Additional smaller sources: KeyRecorder (one per shortcut-recording session), the monitor window's interceptors, and runtime Accessibility-permission loss/regain cycles.

Observed on my machine (Mos 4.2.x, macOS 26.5, uptime 6.5 days): 105–110 stale registrations (~16/day). WindowServer's per-event tap-table processing scales with table size; once the table is large (in my case other leaking apps contributed too), the whole Mac's input turns visibly laggy while the responsible apps sit at 0% CPU — exactly the profile in #970 (WindowServer at 77–100% of a core during window drags, Mos at ~0%). Killing the process reaps all its entries instantly, which is why "kill Mos in Activity Monitor" fixes it and a fresh Mos is fine again.

Standalone verification (no Mos involved): creating 1,000 disabled listen-only taps with the script below makes input noticeably sluggish within seconds; releasing them (or process exit) restores it. Repeating an Interceptor-style teardown (release without invalidate) in a loop grows the owning process's tap-table entry count by exactly 1 per cycle; with CFMachPortInvalidate the entry is reaped immediately.

What changed

  • Interceptor.deinit: CFMachPortInvalidate(tap) before dropping the reference (one line + comment). No behavior change on any input path — the tap is already disabled at this point; this only releases the WindowServer-side registration that was previously leaked.
  • Regression test MosTests/InterceptorTapLeakTests.swift: creates an Interceptor and asserts the process's own CGGetEventTapList registration count returns to baseline once it's gone. Because init creates the tap before the AXIsProcessTrusted guard in start() can throw, the permission-denied path (e.g. CI) creates-and-leaks too — so the test covers it with the same assertion instead of skipping; it only skips when tap creation itself fails.

Validation

  • xcodebuild -scheme Debug -configuration Debug build succeeds with the change, and the regression test was executed both ways (ad-hoc-signed locally, since the project pins the maintainer's signing team): fails on the unfixed Interceptor (XCTAssertEqual failed: ("0") is not equal to ("1") — one residual registration) and passes with the fix.
  • Mechanism verified standalone as described above; the deinit path with the fix is structurally identical to the verified clean variant.
  • Suggested check on a fixed build: run taplist.swift (below) before/after a few sleep/wake cycles — Mos's disabled-entry count should stay at 0 instead of growing by 5 per cycle.

Compatibility / risk

Disposal-only change at object teardown; no event-handling, permission, or configuration behavior is touched. pause()/start() cycles reuse the live tap and are unaffected (invalidate happens only in deinit).

Scripts

taplist.swift — enumerate the WindowServer tap table grouped by owning process (swift taplist.swift)
import AppKit
import CoreGraphics
import Darwin

var count: UInt32 = 0
CGGetEventTapList(0, nil, &count)
var taps = [CGEventTapInformation](repeating: CGEventTapInformation(), count: Int(count) + 16)
var actual: UInt32 = 0
let err = CGGetEventTapList(UInt32(taps.count), &taps, &actual)
taps = Array(taps.prefix(Int(actual)))

func processName(_ pid: pid_t) -> String {
    if let app = NSRunningApplication(processIdentifier: pid) { return app.localizedName ?? "pid\(pid)" }
    var buffer = [CChar](repeating: 0, count: 4096)
    if proc_name(pid, &buffer, UInt32(buffer.count)) > 0 { return String(cString: buffer) }
    // proc_name fails with EPERM for other users' (e.g. root) processes; sysctl works cross-user.
    var mib: [Int32] = [CTL_KERN, KERN_PROC, KERN_PROC_PID, pid]
    var info = kinfo_proc()
    var size = MemoryLayout<kinfo_proc>.stride
    if sysctl(&mib, 4, &info, &size, nil, 0) == 0, size > 0, info.kp_proc.p_pid == pid {
        let name = withUnsafeBytes(of: info.kp_proc.p_comm) { raw in
            String(decoding: raw.prefix(while: { $0 != 0 }), as: UTF8.self)
        }
        if !name.isEmpty { return "\(name) (pid \(pid))" }
    }
    return "pid\(pid)(gone)"
}

print("total taps: \(actual) (err=\(err.rawValue))")
var byProcess: [pid_t: (name: String, enabled: Int, disabled: Int)] = [:]
for t in taps {
    var entry = byProcess[t.tappingProcess] ?? (processName(t.tappingProcess), 0, 0)
    if t.enabled { entry.enabled += 1 } else { entry.disabled += 1 }
    byProcess[t.tappingProcess] = entry
}
for (pid, entry) in byProcess.sorted(by: { ($0.value.enabled + $0.value.disabled) > ($1.value.enabled + $1.value.disabled) }) {
    print(String(format: "pid %6d  %-40@  enabled=%d disabled=%d", pid, entry.name as NSString, entry.enabled, entry.disabled))
}

Observed on my machine (before restarting the two leaking apps):

total taps: 1038
pid  12213  Karabiner-Core-Service  enabled=1 disabled=953
pid  11799  Mos                     enabled=5 disabled=55
...
bloatgen.swift — demonstrate that stale disabled registrations alone degrade input (swift bloatgen.swift 1000 30)
import AppKit
import CoreGraphics

// Creates N disabled listen-only taps (the exact server-side state the leak
// produces), holds them so system impact can be observed, then invalidates
// everything and exits. Process death reaps all entries — cannot leave residue.
// Usage: swift bloatgen.swift [count] [holdSeconds]

let count = CommandLine.arguments.count > 1 ? (Int(CommandLine.arguments[1]) ?? 1000) : 1000
let holdSeconds = CommandLine.arguments.count > 2 ? (Int(CommandLine.arguments[2]) ?? 30) : 30

func totalTaps() -> Int {
    var count: UInt32 = 0
    CGGetEventTapList(0, nil, &count)
    return Int(count)
}

let callback: CGEventTapCallBack = { _, _, event, _ in Unmanaged.passUnretained(event) }
let mask: CGEventMask =
    (1 << CGEventType.mouseMoved.rawValue)
    | (1 << CGEventType.leftMouseDown.rawValue)
    | (1 << CGEventType.leftMouseUp.rawValue)
    | (1 << CGEventType.rightMouseDown.rawValue)
    | (1 << CGEventType.rightMouseUp.rawValue)
    | (1 << CGEventType.leftMouseDragged.rawValue)
    | (1 << CGEventType.scrollWheel.rawValue)

setvbuf(stdout, nil, _IOLBF, 0)
let baseline = totalTaps()
print("baseline tap table: \(baseline) entries")

var held: [CFMachPort] = []
held.reserveCapacity(count)
for i in 0..<count {
    guard let tap = CGEvent.tapCreate(
        tap: .cghidEventTap, place: .tailAppendEventTap, options: .listenOnly,
        eventsOfInterest: mask, callback: callback, userInfo: nil)
    else {
        print("tapCreate FAILED at #\(i + 1) — holding the \(held.count) created so far")
        break
    }
    CGEvent.tapEnable(tap: tap, enable: false)
    held.append(tap)
}
print("created \(held.count) disabled taps — table now: \(totalTaps())")
NSSound.beep()
print("HOLDING for \(holdSeconds)s — wiggle the trackpad / drag windows and observe…")
for remaining in stride(from: holdSeconds, to: 0, by: -5) {
    print("  …\(remaining)s left (table: \(totalTaps()))")
    Thread.sleep(forTimeInterval: min(5, Double(remaining)))
}
for tap in held { CFMachPortInvalidate(tap) }
held.removeAll()
NSSound.beep()
print("released — table back to: \(totalTaps()) entries (baseline was \(baseline))")

CoreGraphics 内部持有 CGEventTapCreate 返回的 CFMachPort 引用, 仅释放引用不会销毁它;
不调用 CFMachPortInvalidate 的话, WindowServer 会保留 (已禁用的) tap 注册直到进程退出。
ScrollCore/ButtonCore 每次休眠唤醒都重建 5 个 Interceptor, 僵尸注册以每天约 10-25 个的
速度累积, 数百个之后全系统输入明显变卡 (Caldis#970 的成因)。

附带回归测试: Interceptor 销毁后, 本进程在 WindowServer tap 表中的注册数应回到基线。
init 在权限检查前就创建 tap, 所以权限被拒的路径同样覆盖; 仅当 tap 创建本身失败时跳过。
已验证: 修复前测试失败 (残留 1 个注册), 修复后通过。

Co-Authored-By: Claude Fable 5 <[email protected]>
Copilot AI review requested due to automatic review settings July 28, 2026 16:02

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR addresses a CoreGraphics event tap resource leak in Interceptor by explicitly invalidating the underlying CFMachPort during teardown, preventing stale (disabled) WindowServer event-tap registrations from accumulating across sleep/wake or session switches (reported in #970).

Changes:

  • Invalidate the event tap CFMachPort in Interceptor.deinit to ensure WindowServer-side registration is released.
  • Add a regression test that tracks this process’s CGGetEventTapList count across Interceptor lifetime.
  • Wire the new test file into the Xcode test target.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.

File Description
Mos/Utils/Interceptor.swift Calls CFMachPortInvalidate during deinit to prevent leaked WindowServer tap registrations.
MosTests/InterceptorTapLeakTests.swift Adds a regression test asserting tap registrations return to baseline after Interceptor is released.
Mos.xcodeproj/project.pbxproj Adds the new test file to the MosTests build phase.

Comment thread MosTests/InterceptorTapLeakTests.swift Resolved
Copilot review: 忽略返回码时, 查询失败会被误读成 0 个注册, 让回归信号不可信。
首次查询失败 → XCTSkip; 之后失败 → 断言失败 (nil ≠ 期望值)。

Co-Authored-By: Claude Fable 5 <[email protected]>
@6westboy9

Copy link
Copy Markdown

Independent real-world confirmation of the leak mechanism described in this PR.
这是一份来自真实环境的独立证据,确认了本 PR 所描述的泄漏机制。

Environment / 环境

  • Mos 4.2.1 (20260531.1)
  • macOS 15.7.7 (24G720), Apple M1 Max
  • Clamshell mode with a 5K external display / 合盖连接 5K 外接显示器
  • Mos had been running for about 34 days, with repeated sleep/wake cycles / Mos 已连续运行约 34 天,期间经历多次睡眠与唤醒

During visible system input/UI lag—most obvious in Dock hover and magnification—CGGetEventTapList showed:
在系统输入与 UI 明显卡顿时(Dock 悬停与放大效果最明显),CGGetEventTapList 的结果为:

Before:             total=768; Mos=630 (enabled=5, disabled=625)
After quitting Mos: total=138
After relaunching:   total=143; Mos=5   (enabled=5, disabled=0)

No other input utility, Dock, WindowServer, or the Mac itself was restarted. The other 129 disabled registrations remained unchanged, but the Dock became smooth immediately after restarting Mos.
除 Mos 外,没有重启其他输入工具、Dock、WindowServer 或整台 Mac。其余 129 个失效注册保持不变,但 Mos 重启后 Dock 立即恢复流畅。

A WindowServer CPU resource report generated at the time of the symptom recorded 90 seconds of CPU over 140 seconds (64% average). Its heaviest stack was add_event_vector_to_tap(...), with a repeated chain reaching 127 levels. Mos’s 630 registrations are exactly 126 groups of five: one active group plus 125 stale groups, closely matching the teardown/recreation mechanism described in this PR.
卡顿发生时生成的 WindowServer CPU resource 报告显示:140 秒内占用 90 秒 CPU,平均 64%。最重的调用栈为 add_event_vector_to_tap(...),重复调用链深度达到 127 层。Mos 的 630 个注册恰好是 126 组、每组 5 个:1 组有效、125 组失效,与本 PR 描述的销毁/重建泄漏机制高度吻合。

This independently confirms the root-cause analysis and also shows that the issue affects macOS 15.7.x, not only macOS 26.x. I have not tested a build containing this patch yet, so this validates the mechanism rather than the patched binary itself.
这组结果独立确认了根因分析,也说明该问题不仅存在于 macOS 26.x,在 macOS 15.7.x 上同样会发生。目前尚未测试包含本补丁的构建,因此这里验证的是泄漏机制,而不是补丁构建本身。

@cpbotha

cpbotha commented Aug 4, 2026

Copy link
Copy Markdown

I confirm this bug independently: I diagnosed the same leak on macOS 26.6 with Mos 4.2.1, before I found this PR. CGGetEventTapList reported 1075 event taps, and Mos owned 335 of them, of which 5 were enabled. 335 divides by 5 exactly, so the count matches the group-of-five pattern in this PR: one live group, plus 66 stale groups. WindowServer held 91% of one CPU core while Mos itself showed 0.0%, which made the cause very hard to find. When I quit Mos, the tap count fell to 740, WindowServer fell to 62%, and most of the lag went away. (BTW, the other taps were held by Karabiner, which I also use!)

I would really love to see this fix merged.

Caldis commented Aug 4, 2026

Copy link
Copy Markdown
Owner

Thank you for the thorough investigation, reproduction, and regression test. I reviewed the code and history; this lifecycle bug appears to have existed for a long time, while later sleep/wake and button-feature iterations amplified how quickly it accumulated. The fix is well targeted. Merging it now—thanks again!

@Caldis

Caldis commented Aug 20, 2026

Copy link
Copy Markdown
Owner

@MrMage Your CFMachPort invalidation fix shipped in 4.3.0-beta (https://github.com/Caldis/Mos/releases/tag/4.3.0-beta-20260820.1), credited inline in the release notes. Thanks for catching a leak class that's easy to miss and hard to observe.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

盒盖待机一段时间后系统卡顿

5 participants