# gpui_macos: Replace per-window CVDisplayLinks with a per-display registry \(\#60696\) · gitcafe/zed

[View on GitCafe](https://git.cafe/gitcafe/zed/commit/96ce8f2a05f8912851e5d20d808fe21f4134bd45)

Repository: [gitcafe/zed](https://git.cafe/gitcafe/zed)

Visibility: public

Requested revision: 96ce8f2a05f8912851e5d20d808fe21f4134bd45

Requested commit: 96ce8f2a05f8912851e5d20d808fe21f4134bd45

Commit: 96ce8f2a05f8912851e5d20d808fe21f4134bd45

Tree: ab69f00634924506205c31b488390429ee4d0844

Author: Richard Feldman

Committer: GitHub

## Message

```
gpui_macos: Replace per-window CVDisplayLinks with a per-display registry (#60696)

Fixes ZED-7XR

CVDisplayLink has no safe teardown: `CVDisplayLinkStop` only flags the
io thread to exit "soon" and returns, `CVDisplayLinkRelease` frees the
link immediately, and there is no way to learn when a final output
callback has finished. This produced two distinct use-after-free crash
classes on the display-link thread: the io thread reading the freed
link's internals (`CVHWTime::reset`, worked around by leaking the link
in #32116), and a straggler output callback dereferencing the freed
dispatch source through its context pointer
(`dispatch_source_merge_data`, ZED-7XR). Because we tore down a
`DisplayLink` on every resize tick, window activation, and occlusion
change, the existing workaround also leaked a stopped CVDisplayLink per
teardown, unboundedly.

This replaces per-window links with a static registry holding one
immortal `CVDisplayLink` per display. Windows subscribe to their
display's link with the dispatch source that paces their frames; the
output callback's context is a display id rather than a pointer, so the
only memory it ever dereferences is the registry itself, under its lock.
Links start and stop at subscriber-count edges (so multiple windows on
one display can't interleave starts/stops incorrectly), and a window's
dispatch source lives for the life of the window, is removed from the
registry on close, and is then genuinely released. Both crash classes
become unreachable — the link because it is never released, the source
because a straggler callback either finds it live in the registry or
doesn't find it at all — and there are no leaks and no `mem::forget`.
Since we never hold the registry lock across CoreVideo calls, no lock
cycle through CVDisplayLink's undocumented internal locks is possible;
the module doc comment spells out the invariants.

This supersedes #60481, which fixed ZED-7XR by leaking the dispatch
source on teardown.

Release Notes:

- Fixed a rare crash on macOS when closing, resizing, or switching
between windows, and eliminated a memory leak in display-link teardown
```

## Parents

- [084b5d21f67cdbe06edd2822ce34e58b3cd774f7](https://git.cafe/gitcafe/zed/commit/084b5d21f67cdbe06edd2822ce34e58b3cd774f7?format=markdown)

[Source at this commit](https://git.cafe/gitcafe/zed/tree/96ce8f2a05f8912851e5d20d808fe21f4134bd45?format=markdown)
