Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
linux: Fix Wayland clipboard reads blocking indefinitely (#58826)
Smit Barmasebda5ac3626c6
diff --git a/crates/gpui_linux/src/linux/platform.rs b/crates/gpui_linux/src/linux/platform.rsindex 343600cd862..be41f241935 100644--- a/crates/gpui_linux/src/linux/platform.rs+++ b/crates/gpui_linux/src/linux/platform.rs@@ -9,7 +9,7 @@ use std::{ffi::OsString,fs::File,io::Read as _,- os::fd::{AsFd, FromRawFd, IntoRawFd},+ os::fd::{AsFd, AsRawFd},time::Duration,};@@ -752,11 +752,43 @@ pub(super) fn get_xkb_compose_state(cx: &xkb::Context) -> Option<xkb::compose::S}#[cfg(any(feature = "wayland", feature = "x11"))]-pub(super) unsafe fn read_fd(fd: filedescriptor::FileDescriptor) -> Result<Vec<u8>> {- let mut file = unsafe { File::from_raw_fd(fd.into_raw_fd()) };+pub(super) const PIPE_READ_TIMEOUT: Duration = Duration::from_secs(4);++#[cfg(any(feature = "wayland", feature = "x11"))]+pub(super) fn read_fd_with_timeout(+ mut fd: filedescriptor::FileDescriptor,+ timeout: Duration,+) -> Result<Vec<u8>> {+ fd.set_non_blocking(true)?;let mut buffer = Vec::new();- file.read_to_end(&mut buffer)?;- Ok(buffer)+ let mut chunk = [0u8; 8192];+ loop {+ let mut poll_fds = [filedescriptor::pollfd {+ fd: fd.as_raw_fd(),+ events: filedescriptor::POLLIN,+ revents: 0,+ }];+ let ready = match filedescriptor::poll(&mut poll_fds, Some(timeout)) {+ Ok(ready) => ready,+ Err(filedescriptor::Error::Poll(err))+ if err.kind() == std::io::ErrorKind::Interrupted =>+ {+ continue;+ }+ Err(err) => return Err(err.into()),+ };+ if ready == 0 {+ anyhow::bail!("timed out waiting for data on pipe after {timeout:?}");+ }+ match fd.read(&mut chunk) {+ Ok(0) => return Ok(buffer),+ Ok(len) => buffer.extend_from_slice(&chunk[..len]),+ Err(err)+ if err.kind() == std::io::ErrorKind::WouldBlock+ || err.kind() == std::io::ErrorKind::Interrupted => {}+ Err(err) => return Err(err.into()),+ }+ }}#[cfg(any(feature = "wayland", feature = "x11"))]@@ -1126,4 +1158,100 @@ mod tests {Point::new(px(5.0), px(5.1))),);}++ #[cfg(any(feature = "wayland", feature = "x11"))]+ mod read_fd_with_timeout {+ use super::super::{PIPE_READ_TIMEOUT, read_fd_with_timeout};+ use std::io::Write as _;+ use std::time::{Duration, Instant};++ #[test]+ fn reads_data_written_before_close() {+ let mut pipe = filedescriptor::Pipe::new().unwrap();+ pipe.write.write_all(b"hello clipboard").unwrap();+ drop(pipe.write);++ let bytes = read_fd_with_timeout(pipe.read, PIPE_READ_TIMEOUT).unwrap();+ assert_eq!(bytes, b"hello clipboard");+ }++ #[test]+ fn returns_empty_when_writer_closes_without_writing() {+ let pipe = filedescriptor::Pipe::new().unwrap();+ drop(pipe.write);++ let bytes = read_fd_with_timeout(pipe.read, PIPE_READ_TIMEOUT).unwrap();+ assert!(bytes.is_empty());+ }++ #[test]+ fn times_out_when_writer_never_writes() {+ let pipe = filedescriptor::Pipe::new().unwrap();+ let _open_writer = pipe.write;++ let timeout = Duration::from_millis(50);+ let started = Instant::now();+ let result = read_fd_with_timeout(pipe.read, timeout);+ let elapsed = started.elapsed();++ let err = result.unwrap_err();+ assert!(+ err.to_string().contains("timed out"),+ "unexpected error: {err}"+ );+ assert!(elapsed >= timeout, "returned before the timeout elapsed");+ }++ #[test]+ fn times_out_when_writer_stalls_after_partial_write() {+ let mut pipe = filedescriptor::Pipe::new().unwrap();+ pipe.write.write_all(b"partial").unwrap();+ let _open_writer = pipe.write;++ let err = read_fd_with_timeout(pipe.read, Duration::from_millis(50)).unwrap_err();+ assert!(+ err.to_string().contains("timed out"),+ "unexpected error: {err}"+ );+ }++ #[test]+ fn slow_writer_resets_deadline_between_chunks() {+ let pipe = filedescriptor::Pipe::new().unwrap();+ let chunks = 12;+ let gap = Duration::from_millis(40);+ let timeout = Duration::from_millis(400);++ let writer = std::thread::spawn({+ let mut write = pipe.write;+ move || {+ for _ in 0..chunks {+ std::thread::sleep(gap);+ write.write_all(&[b'x'; 1000]).unwrap();+ }+ }+ });+ // The total transfer (~480ms) exceeds the timeout; this only+ // passes because the timeout is re-armed per chunk.+ let bytes = read_fd_with_timeout(pipe.read, timeout).unwrap();+ writer.join().unwrap();+ assert_eq!(bytes, vec![b'x'; 1000 * chunks]);+ }++ #[test]+ fn reads_payload_larger_than_pipe_capacity() {+ let pipe = filedescriptor::Pipe::new().unwrap();+ // Exceeds the 64 KiB pipe capacity, forcing the writer to block.+ let payload = vec![b'z'; 1024 * 1024];++ let writer = std::thread::spawn({+ let mut write = pipe.write;+ let payload = payload.clone();+ move || write.write_all(&payload).unwrap()+ });+ let bytes = read_fd_with_timeout(pipe.read, PIPE_READ_TIMEOUT).unwrap();+ writer.join().unwrap();+ assert_eq!(bytes, payload);+ }+ }}diff --git a/crates/gpui_linux/src/linux/wayland/client.rs b/crates/gpui_linux/src/linux/wayland/client.rsindex a797d0d6d09..5decbc34e6f 100644--- a/crates/gpui_linux/src/linux/wayland/client.rs+++ b/crates/gpui_linux/src/linux/wayland/client.rs@@ -78,10 +78,10 @@ use super::{};use crate::linux::{- DOUBLE_CLICK_INTERVAL, LinuxClient, LinuxCommon, LinuxKeyboardLayout, SCROLL_LINES,- capslock_from_xkb, cursor_style_to_icon_names, get_xkb_compose_state, is_within_click_distance,- keystroke_from_xkb, keystroke_underlying_dead_key, modifiers_from_xkb, open_uri_internal,- read_fd, reveal_path_internal,+ DOUBLE_CLICK_INTERVAL, LinuxClient, LinuxCommon, LinuxKeyboardLayout, PIPE_READ_TIMEOUT,+ SCROLL_LINES, capslock_from_xkb, cursor_style_to_icon_names, get_xkb_compose_state,+ is_within_click_distance, keystroke_from_xkb, keystroke_underlying_dead_key,+ modifiers_from_xkb, open_uri_internal, read_fd_with_timeout, reveal_path_internal,wayland::{clipboard::{Clipboard, DataOffer, FILE_LIST_MIME_TYPE, TEXT_MIME_TYPES},cursor::Cursor,@@ -2286,7 +2286,7 @@ impl Dispatch<wl_data_device::WlDataDevice, ()> for WaylandClientStatePtr {drop(pipe.write);let read_task = state.common.background_executor.spawn(async {- let buffer = unsafe { read_fd(fd)? };+ let buffer = read_fd_with_timeout(fd, PIPE_READ_TIMEOUT)?;let text = String::from_utf8(buffer)?;anyhow::Ok(text)});diff --git a/crates/gpui_linux/src/linux/wayland/clipboard.rs b/crates/gpui_linux/src/linux/wayland/clipboard.rsindex 49c58724dad..dfedf53f6df 100644--- a/crates/gpui_linux/src/linux/wayland/clipboard.rs+++ b/crates/gpui_linux/src/linux/wayland/clipboard.rs@@ -10,7 +10,10 @@ use strum::IntoEnumIterator;use wayland_client::{Connection, protocol::wl_data_offer::WlDataOffer};use wayland_protocols::wp::primary_selection::zv1::client::zwp_primary_selection_offer_v1::ZwpPrimarySelectionOfferV1;-use crate::linux::{WaylandClientStatePtr, platform::read_fd};+use crate::linux::{+ WaylandClientStatePtr,+ platform::{PIPE_READ_TIMEOUT, read_fd_with_timeout},+};use gpui::{ClipboardEntry, ClipboardItem, Image, ImageFormat, hash};/// Text mime types that we'll offer to other programs.@@ -86,7 +89,7 @@ impl<T: ReceiveData> DataOffer<T> {connection.flush().unwrap();- match unsafe { read_fd(fd) } {+ match read_fd_with_timeout(fd, PIPE_READ_TIMEOUT) {Ok(bytes) => Some(bytes),Err(err) => {log::error!("error reading clipboard pipe: {err:?}");