Skip to main content

wl_client/proxy/low_level/
borrowed.rs

1use crate::Libwayland;
2use crate::Queue;
3use crate::builder::prelude::UntypedOwnedProxy;
4use crate::ffi::wl_argument;
5use crate::ffi::wl_interface;
6use crate::ffi::wl_proxy;
7use crate::proxy::low_level::check_dispatching_proxy;
8use crate::proxy::low_level::check_new_proxy;
9use crate::utils::sync_ptr::SyncPtr;
10use parking_lot::RwLock;
11use parking_lot::RwLockReadGuard;
12use std::ptr;
13use std::ptr::NonNull;
14use std::sync::atomic::AtomicPtr;
15use std::sync::atomic::AtomicU32;
16use std::sync::atomic::Ordering::Relaxed;
17
18#[cfg(test)]
19mod tests;
20
21/// A borrowed `wl_proxy` pointer.
22///
23/// Most of the time you will not work with this type directly and instead use one of
24/// the `*Ref` types generated by `wl-client-builder`.
25///
26/// This is a thin wrapper around a `wl_proxy` pointer plus a read-write lock. The
27/// contained proxy pointer is at all times either null or a valid pointer.
28///
29/// You can access the pointer by calling [`UntypedBorrowedProxy::wl_proxy`], however,
30/// this does not prevent concurrent destruction. That is, you might check that the
31/// returned pointer is not null and another thread might invalidate the pointer at the
32/// same time.
33///
34/// To prevent this, you can acquire the read lock mentioned above by calling
35/// [`UntypedBorrowedProxy::lock`]:
36///
37/// ```
38/// # use std::ptr::NonNull;
39/// # use wl_client::builder::prelude::{wl_proxy, UntypedBorrowedProxy};
40/// #
41/// fn pass_proxy_pointer_to_external_function(proxy: &UntypedBorrowedProxy) {
42///     let lock = proxy.lock();
43///     // SAFETY: The lock ensures that the proxy stays valid if it is not null.
44///     unsafe {
45///         external_function(lock.wl_proxy());
46///     }
47/// }
48///
49/// /// # Safety
50/// ///
51/// /// The proxy must be valid or null.
52/// unsafe fn external_function(proxy: Option<NonNull<wl_proxy>>) {
53///     todo!();
54/// }
55/// ```
56pub struct UntypedBorrowedProxy {
57    /// The proxy wrapped by this object. The value must only be modified while holding
58    /// the write lock. If immutable is true, then the value must not be modified.
59    pub(super) proxy: AtomicPtr<wl_proxy>,
60    pub(super) lock: RwLock<()>,
61    pub(super) libwayland: &'static Libwayland,
62    id: AtomicU32,
63    immutable: bool,
64}
65
66/// A transparent wrapper around [`UntypedBorrowedProxy`].
67///
68/// # Safety
69///
70/// This type must be a transparent wrapper around [`UntypedBorrowedProxy`].
71pub unsafe trait UntypedBorrowedProxyWrapper: Sized {}
72
73// SAFETY: Self is literally UntypedBorrowedProxy
74unsafe impl UntypedBorrowedProxyWrapper for UntypedBorrowedProxy {}
75
76const MIN_SERVER_ID: u32 = 0xff000000;
77const LAST_CLIENT_ID: u32 = MIN_SERVER_ID - 1;
78
79/// A lock that ensures that a [`UntypedBorrowedProxy`] is not changed.
80///
81/// You can acquire it by calling [`proxy::lock`](super::super::lock).
82///
83/// This lock can be acquired multiple times across multiple threads.
84pub struct BorrowedProxyLock<'a> {
85    _lock: Option<RwLockReadGuard<'a, ()>>,
86    proxy: SyncPtr<wl_proxy>,
87}
88
89impl BorrowedProxyLock<'_> {
90    /// Returns the `wl_proxy` pointer or `None` if the proxy is destroyed.
91    ///
92    /// If this function returns a pointer, then the pointer will remain valid while the
93    /// lock is being held.
94    ///
95    /// # Example
96    ///
97    /// ```
98    /// # use wl_client::{proxy, Libwayland};
99    /// use wl_client::test_protocols::core::wl_display::WlDisplay;
100    /// #
101    /// let lib = Libwayland::open().unwrap();
102    /// let con = lib.connect_to_default_display().unwrap();
103    /// let queue = con.create_queue(c"queue name");
104    /// let display: WlDisplay = queue.display();
105    ///
106    /// let sync = display.sync();
107    /// let lock = proxy::lock(&*sync);
108    /// assert!(lock.wl_proxy().is_some());
109    ///
110    /// // This would deadlock.
111    /// // proxy::destroy(&sync);
112    /// ```
113    pub fn wl_proxy(&self) -> Option<NonNull<wl_proxy>> {
114        NonNull::new(self.proxy.0)
115    }
116}
117
118impl UntypedBorrowedProxy {
119    /// Creates a new [`UntypedBorrowedProxy`] from an immutable pointer.
120    ///
121    /// The pointer contained in the new object stays valid for the lifetime of the
122    /// object.
123    ///
124    /// # Safety
125    ///
126    /// - `proxy` must be a valid pointer.
127    /// - `proxy` must stay valid for the lifetime of this object.
128    pub unsafe fn new_immutable(libwayland: &'static Libwayland, proxy: NonNull<wl_proxy>) -> Self {
129        // SAFETY: The requirement is forwarded to the caller.
130        unsafe { Self::new(libwayland, proxy, true) }
131    }
132
133    /// Creates a new [`UntypedBorrowedProxy`].
134    ///
135    /// # Safety
136    ///
137    /// - `proxy` must be a valid pointer.
138    /// - The proxy must be set to null before being invalidated.
139    pub(crate) unsafe fn new_internal(
140        libwayland: &'static Libwayland,
141        proxy: NonNull<wl_proxy>,
142    ) -> Self {
143        // SAFETY: The requirement is forwarded to the caller.
144        unsafe { Self::new(libwayland, proxy, false) }
145    }
146
147    /// Creates a new [`UntypedBorrowedProxy`].
148    ///
149    /// # Safety
150    ///
151    /// - The proxy must either be null or a valid pointer.
152    /// - This property must hold for the lifetime of this object.
153    unsafe fn new(
154        libwayland: &'static Libwayland,
155        proxy: NonNull<wl_proxy>,
156        immutable: bool,
157    ) -> Self {
158        Self {
159            proxy: AtomicPtr::new(proxy.as_ptr()),
160            lock: RwLock::new(()),
161            id: AtomicU32::new(LAST_CLIENT_ID),
162            libwayland,
163            immutable,
164        }
165    }
166
167    /// Locks the `wl_proxy` pointer in this object.
168    ///
169    /// While the pointer is locked, it does not change. Given the invariants of this type,
170    /// this implies that the pointer will either stay the same, valid pointer, or the
171    /// pointer will be the null pointer.
172    ///
173    /// This lock can be acquired multiple times concurrently.
174    ///
175    /// Trying to destroy the proxy while holding a lock will deadlock.
176    #[inline]
177    pub fn lock(&self) -> BorrowedProxyLock<'_> {
178        let lock = match self.immutable {
179            true => None,
180            false => Some(self.lock.read_recursive()),
181        };
182        // SAFETY: If the pointer is not immutable, then we're holding a read lock.
183        BorrowedProxyLock {
184            _lock: lock,
185            proxy: SyncPtr(self.proxy.load(Relaxed)),
186        }
187    }
188
189    /// Retrieve the `wl_proxy` pointer backing this object.
190    ///
191    /// In a multi-threaded application, the pointer can get invalidated at any time. To
192    /// prevent this, you might want to use [`UntypedBorrowedProxy::lock`] instead.
193    #[inline]
194    pub fn wl_proxy(&self) -> Option<NonNull<wl_proxy>> {
195        NonNull::new(self.proxy.load(Relaxed))
196    }
197
198    /// Returns the wayland object ID of this proxy.
199    ///
200    /// If the proxy has already been destroyed, this function returns either the original
201    /// ID or 0.
202    #[inline]
203    pub fn id(&self) -> u32 {
204        let mut id = self.id.load(Relaxed);
205        if id == LAST_CLIENT_ID {
206            id = self.id_slow();
207            self.id.store(id, Relaxed);
208        }
209        id
210    }
211
212    #[cold]
213    fn id_slow(&self) -> u32 {
214        let lock = self.lock();
215        if let Some(proxy) = lock.wl_proxy() {
216            // SAFETY: Since proxy is not null, the invariants guarantee that proxy is
217            //         valid.
218            unsafe { self.libwayland.wl_proxy_get_id(proxy.as_ptr()) }
219        } else {
220            0
221        }
222    }
223
224    /// Sends a request on this proxy.
225    ///
226    /// This function cannot be used if the request creates a new object. Use
227    /// [`UntypedBorrowedProxy::send_constructor`] for that purpose.
228    ///
229    /// # Panic
230    ///
231    /// Panics if this proxy has already been destroyed.
232    ///
233    /// # Safety
234    ///
235    /// - `opcode` must be a valid request opcode for the interface of the proxy.
236    /// - `args` must conform to the interface + opcode of the proxy.
237    /// - `args` must not contain any `new_id` element.
238    #[inline]
239    pub unsafe fn send_request(&self, opcode: u32, args: &mut [wl_argument]) {
240        let lock = self.lock();
241        let proxy = check_dispatching_proxy(lock.wl_proxy());
242        // SAFETY: - we've checked that proxy is not null, therefore the invariants
243        //           guarantee that it is a valid pointer
244        //         - the opcode and args requirements are forwarded to the caller
245        //         - in particular, interface is null and the args does not contain a
246        //           new_id element
247        //         - flags does not contain WL_MARSHAL_FLAG_DESTROY
248        unsafe {
249            self.libwayland.wl_proxy_marshal_array_flags(
250                proxy.as_ptr(),
251                opcode,
252                ptr::null(),
253                0,
254                0,
255                args.as_mut_ptr(),
256            );
257        }
258    }
259
260    /// Creates a new object by sending a request on this proxy.
261    ///
262    /// This function can only be used if the request creates a new object. Use
263    /// [`Self::send_request`] otherwise.
264    ///
265    /// The new object will be attached to the given queue.
266    ///
267    /// # Panic
268    ///
269    /// This function panics if
270    ///
271    /// - this proxy has already been destroyed, or
272    /// - the queue and this proxy don't belong to the same display.
273    ///
274    /// # Safety
275    ///
276    /// - `opcode` must be a valid request opcode for the interface of the proxy.
277    /// - `args` must conform to the interface + opcode of the proxy.
278    /// - `args` must contain exactly one `new_id` element.
279    /// - `interface` must be a valid `wl_interface`.
280    pub unsafe fn send_constructor(
281        &self,
282        queue: &Queue,
283        opcode: u32,
284        args: &mut [wl_argument],
285        interface: &'static wl_interface,
286        version: Option<u32>,
287    ) -> UntypedOwnedProxy {
288        let lib = self.libwayland;
289        let lock = self.lock();
290        let mut proxy = check_dispatching_proxy(lock.wl_proxy());
291        // SAFETY: - we've checked that proxy is not null, therefore the invariants
292        //           guarantee that it is a valid pointer
293        let version =
294            version.unwrap_or_else(|| unsafe { lib.wl_proxy_get_version(proxy.as_ptr()) });
295        // SAFETY: - we've checked that proxy is not null, therefore the invariants
296        //           guarantee that it is a valid pointer
297        let parent_queue = unsafe { lib.wl_proxy_get_queue(proxy.as_ptr()) };
298        let need_wrapper = parent_queue != queue.wl_event_queue().as_ptr();
299        if need_wrapper {
300            // SAFETY: - We've verified that the proxy is not null. UntypedBorrowedProxy
301            //           requires that the pointer is valid in this case.
302            let display = unsafe { self.libwayland.wl_proxy_get_display(proxy.as_ptr()) };
303            if display != queue.connection().wl_display().as_ptr() {
304                panic!("queue does not belong to same connection");
305            }
306            // SAFETY: - we've checked that proxy is not null, therefore the invariants
307            //           guarantee that it is a valid pointer
308            let proxy_ptr = unsafe { lib.wl_proxy_create_wrapper(proxy.as_ptr().cast()).cast() };
309            proxy = check_dispatching_proxy(NonNull::new(proxy_ptr));
310            // SAFETY: - we've checked that proxy is not null, therefore the invariants
311            //           guarantee that it is a valid pointer
312            //         - the invariants of queue guarantee that queue the wl_event_queue
313            //           is valid
314            //         - we've checked above that the display of the queue and the
315            //           display of the proxy are the same
316            //         - we will destroy the wrapper below
317            unsafe {
318                lib.wl_proxy_set_queue(proxy.as_ptr(), queue.wl_event_queue().as_ptr());
319            }
320        }
321        // SAFETY: - we've checked that proxy is not null, therefore the invariants
322        //           guarantee that it is a valid pointer
323        //         - the opcode, args, and interface requirements are forwarded to the
324        //           caller
325        //         - in particular, interface is a valid wl_interface and args contains
326        //           exactly one new_id element
327        //         - flags does not contain WL_MARSHAL_FLAG_DESTROY
328        let new_proxy = unsafe {
329            lib.wl_proxy_marshal_array_flags(
330                proxy.as_ptr(),
331                opcode,
332                interface,
333                version,
334                0,
335                args.as_mut_ptr(),
336            )
337        };
338        if need_wrapper {
339            // SAFETY: Since need_wrapper is true, wl_proxy_create_wrapper is the return
340            //         value of wl_proxy_create_wrapper above.
341            unsafe {
342                lib.wl_proxy_wrapper_destroy(proxy.as_ptr().cast());
343            }
344        }
345        let new_proxy = check_new_proxy(new_proxy);
346        // SAFETY: - we've just checked that new_proxy is not null
347        //         - since new_proxy was returned by wl_proxy_marshal_array_flags its a
348        //           valid, plain proxy that we have ownership of
349        //         - we hand over ownership to the UntypedOwnedProxy
350        //         - we made sure above that new_proxy would be created in `queue`
351        //         - the object was created with the interface `interface`
352        //         - since it was just created, it does not have an event handler assigned
353        unsafe { UntypedOwnedProxy::from_plain_wl_proxy(queue, new_proxy, interface) }
354    }
355
356    /// Returns the version of this proxy object.
357    ///
358    /// The version of the display object is always 0.
359    ///
360    /// # Panic
361    ///
362    /// Panics if the proxy is already destroyed.
363    pub fn version(&self) -> u32 {
364        let lock = self.lock();
365        let proxy = check_dispatching_proxy(lock.wl_proxy());
366        // SAFETY: - we've checked that proxy is not null, therefore the invariants
367        //           guarantee that it is a valid pointer
368        unsafe { self.libwayland.wl_proxy_get_version(proxy.as_ptr()) }
369    }
370}
371
372impl PartialEq for UntypedBorrowedProxy {
373    fn eq(&self, other: &Self) -> bool {
374        self.wl_proxy() == other.wl_proxy()
375    }
376}
377
378impl Eq for UntypedBorrowedProxy {}
379
380impl PartialEq<UntypedOwnedProxy> for UntypedBorrowedProxy {
381    fn eq(&self, other: &UntypedOwnedProxy) -> bool {
382        self.wl_proxy() == other.wl_proxy()
383    }
384}
385
386impl PartialEq<UntypedBorrowedProxy> for UntypedOwnedProxy {
387    fn eq(&self, other: &UntypedBorrowedProxy) -> bool {
388        self.wl_proxy() == other.wl_proxy()
389    }
390}