wl_client/proxy/low_level/owned.rs
1use crate::ffi::WL_MARSHAL_FLAG_DESTROY;
2use crate::ffi::interface_compatible;
3use crate::ffi::wl_argument;
4use crate::ffi::wl_dispatcher_func_t;
5use crate::ffi::wl_interface;
6use crate::ffi::wl_message;
7use crate::ffi::wl_proxy;
8use crate::proxy::low_level::borrowed::UntypedBorrowedProxy;
9use crate::proxy::low_level::check_dispatching_proxy;
10use crate::proxy::low_level::check_new_proxy;
11use crate::proxy::low_level::owned::scope::Scope;
12use crate::proxy::low_level::owned::scope::ScopeData;
13use crate::queue::Queue;
14use crate::utils::sync_ptr::SyncNonNull;
15use crate::utils::sync_ptr::SyncPtr;
16use destruction::ProxyDataDestruction;
17use parking_lot::Mutex;
18use run_on_drop::on_drop;
19use std::any::Any;
20use std::any::TypeId;
21use std::cell::Cell;
22use std::collections::HashSet;
23use std::ffi::c_int;
24use std::ffi::c_void;
25use std::mem;
26use std::ops::Deref;
27use std::panic::AssertUnwindSafe;
28use std::panic::catch_unwind;
29use std::ptr;
30use std::ptr::NonNull;
31use std::sync::Arc;
32use std::sync::atomic::AtomicBool;
33use std::sync::atomic::AtomicPtr;
34use std::sync::atomic::AtomicUsize;
35use std::sync::atomic::Ordering::Acquire;
36use std::sync::atomic::Ordering::Relaxed;
37use std::sync::atomic::Ordering::Release;
38use std::sync::atomic::fence;
39
40pub(crate) mod destruction;
41pub(crate) mod scope;
42#[cfg(test)]
43mod tests;
44
45/// A owned `wl_proxy` pointer.
46///
47/// Most of the time you will not work with this type directly and instead use one of
48/// the types generated by `wl-client-builder`.
49#[derive(Eq, PartialEq)]
50pub struct UntypedOwnedProxy {
51 data: SyncNonNull<UntypedOwnedProxyData>,
52}
53
54struct UntypedOwnedProxyData {
55 /// This object is owned by a number of [`UntypedOwnedProxy`] objects. This field
56 /// contains the number of these objects. Additionally, if ever_had_event_handler is
57 /// true, then libwayland might be holding a pointer to this object and this object
58 /// must not be destroyed until we know that libwayland has ceased accessing the
59 /// pointer.
60 ref_count: AtomicUsize,
61 /// The queue that this proxy is attached to.
62 queue: Queue,
63 /// This field holds the wl_proxy. We're storing it in a [`UntypedBorrowedProxy`] so
64 /// that we can deref to [`UntypedBorrowedProxy`]. This [`UntypedBorrowedProxy`] is
65 /// mutable. The proxy is a wrapper if and only if `interface` is None.
66 proxy: UntypedBorrowedProxy,
67 /// This is Some if and only if the proxy is not a wrapper. In this case, this is the
68 /// interface of the proxy.
69 interface: Option<&'static wl_interface>,
70 /// This is true if a event handler has been attached to the proxy. We only allow
71 /// attaching a event handler once.
72 ever_had_event_handler: AtomicBool,
73 /// A pointer to event handler data. This is set once while holding the proxy pointer
74 /// read lock. It is accessed by event_handler_func and when destroying the event
75 /// handler. Visibility is ensured just like for the scope_data field below.
76 ///
77 /// The pointer gets invalidated when the event handler is destroyed which can happen
78 /// long before this object is dropped. In these cases, access to the event handler
79 /// is prevented in two ways: If the proxy has been destroyed, then event_handler_func
80 /// is no longer invoked and the code ensures that the event handler is not destroyed
81 /// before the last such invocation has completed. If the proxy has not been destroyed,
82 /// then the event dispatcher is event_handler_func_scoped and that function will
83 /// never again call into event_handler_func.
84 event_handler: AtomicPtr<u8>,
85 /// If this is not null, it is a function pointer to a function that can be used to
86 /// drop the event handler. This field is written at the same time as the
87 /// event_handler field is written. Visibility is ensured just like for event_handler.
88 /// It is set back to null while holding the proxy pointer write lock when creating
89 /// the [`ProxyDataDestruction`] for the event handler.
90 drop_event_handler: AtomicPtr<u8>,
91 /// This field is true if and only if this proxy is attached to a registry.
92 stored_in_registry: AtomicBool,
93 /// The scope that this proxy is attached to, if any. This ensures that the scope_data
94 /// field remains valid until this object is dropped.
95 scope_data_arc: Mutex<Option<Arc<ScopeData>>>,
96 /// A pointer to the data in the Arc stored in scope_data_arc, or null if the proxy is
97 /// not attached to a scope. This field is written at most once while holding the proxy
98 /// pointer read lock. It is accessed by event_handler_func_scoped and by code in this
99 /// file.
100 ///
101 /// The event handler is attached to this proxy while holding the dispatch lock which
102 /// is also held when the event handler is invoked. This ensures visibility in the
103 /// event handler.
104 ///
105 /// All code in this file that accesses this field does so while having exclusive
106 /// access to the proxy pointer, either by holding the proxy pointer write lock or in
107 /// the drop impl. This ensures visibility in those places.
108 ///
109 /// If it is not null, then this pointer remains valid until this object is dropped.
110 scope_data: AtomicPtr<ScopeData>,
111}
112
113/// A registry used for owned proxies that might have to be destroyed at some point.
114///
115/// This is used for proxies that have event handlers with a drop impl. Such event handlers can
116/// form a reference cycle with the proxy that has to be explicitly broken. All proxies
117/// in this registry will be explicitly destroyed when the connection object is dropped.
118/// Destroying the proxy drops the event handler which breaks the reference cycle.
119#[derive(Default)]
120pub(crate) struct OwnedProxyRegistry {
121 /// This set contains proxies that have a event handler with a drop impl attached. The
122 /// pointers in this set are always valid, but they are not strong references. You can
123 /// dereference them while holding this lock. To be able to use them outside of
124 /// holding the lock, you must increment the reference count from n>0 to n+1. Note
125 /// that the reference count can be n=0. Such pointers must be ignored.
126 proxies: Mutex<HashSet<SyncNonNull<UntypedOwnedProxyData>>>,
127}
128
129/// A transparent wrapper around [`UntypedOwnedProxy`].
130///
131/// # Safety
132///
133/// This type must be a transparent wrapper around [`UntypedOwnedProxy`].
134pub unsafe trait UntypedOwnedProxyWrapper: Clone {}
135
136// SAFETY: Self is literally UntypedOwnedProxy.
137unsafe impl UntypedOwnedProxyWrapper for UntypedOwnedProxy {}
138
139impl Deref for UntypedOwnedProxy {
140 type Target = UntypedBorrowedProxy;
141
142 fn deref(&self) -> &Self::Target {
143 &self.data().proxy
144 }
145}
146
147impl UntypedOwnedProxy {
148 /// Creates a new [`UntypedOwnedProxy`] from a plain `wl_proxy`.
149 ///
150 /// # Safety
151 ///
152 /// - `proxy` must be a valid pointer to a plain `wl_proxy`.
153 /// - `proxy` must remain valid for the lifetime of this object and its clones.
154 /// - `proxy` must not have an event handler or dispatcher assigned.
155 /// - `queue` must be the queue of the proxy.
156 /// - `interface` must be the interface of the proxy.
157 pub unsafe fn from_plain_wl_proxy(
158 queue: &Queue,
159 proxy: NonNull<wl_proxy>,
160 interface: &'static wl_interface,
161 ) -> Self {
162 // SAFETY: - proxy is a plain proxy and interface is its interface
163 // - proxy does not have an event handler assigned
164 // - queue is the queue of the queue
165 unsafe { Self::new(queue, proxy, Some(interface)) }
166 }
167
168 /// Creates a new [`UntypedOwnedProxy`] from a wrapper `wl_proxy`.
169 ///
170 /// # Safety
171 ///
172 /// - `proxy` must be a valid pointer to a wrapper `wl_proxy`.
173 /// - `proxy` must remain valid for the lifetime of this object and its clones.
174 /// - `queue` must be the queue of the proxy.
175 pub unsafe fn from_wrapper_wl_proxy(queue: &Queue, proxy: NonNull<wl_proxy>) -> Self {
176 // SAFETY: - proxy is a valid wrapper and as such does not have an event handler
177 // - queue is the queue of the proxy
178 unsafe { Self::new(queue, proxy, None) }
179 }
180
181 /// # Safety
182 ///
183 /// - proxy must be a valid pointer
184 /// - proxy must not have an event handler assigned
185 /// - this function takes ownership of the proxy
186 /// - the proxy's event handler must not be modified except through this object
187 /// - queue must be the queue of the proxy
188 /// - if interface is not None, it must be the interface of the wl_proxy
189 /// - if this is a wrapper, then interface must be None
190 /// - if this is not a wrapper, then interface must not be None
191 unsafe fn new(
192 queue: &Queue,
193 proxy: NonNull<wl_proxy>,
194 interface: Option<&'static wl_interface>,
195 ) -> Self {
196 let data = Box::new(UntypedOwnedProxyData {
197 ref_count: AtomicUsize::new(1),
198 queue: queue.clone(),
199 proxy: {
200 // SAFETY: - By the safety requirements of this function, proxy is a valid
201 // pointer.
202 // - Whenever we destroy the proxy we first set it to a null
203 // pointer.
204 unsafe { UntypedBorrowedProxy::new_internal(queue.libwayland(), proxy) }
205 },
206 interface,
207 ever_had_event_handler: Default::default(),
208 event_handler: Default::default(),
209 drop_event_handler: Default::default(),
210 stored_in_registry: Default::default(),
211 scope_data: Default::default(),
212 scope_data_arc: Default::default(),
213 });
214 Self {
215 data: SyncNonNull(NonNull::from(Box::leak(data))),
216 }
217 }
218
219 fn data(&self) -> &UntypedOwnedProxyData {
220 // SAFETY: self.data is always a valid pointer except during `drop`.
221 unsafe { self.data.as_ref() }
222 }
223
224 /// Destroys this object by sending a request on this proxy.
225 ///
226 /// After this function returns, the underlying `wl_proxy` has been destroyed.
227 ///
228 /// This function cannot be used if the request creates a new object. Use
229 /// [`UntypedOwnedProxy::send_constructor`] for that purpose.
230 ///
231 /// This function cannot be used if this is a wrapper.
232 ///
233 /// # Panic
234 ///
235 /// - This function panics if this proxy has already been destroyed.
236 /// - This function might panic if the proxy is attached to a local queue and the
237 /// current thread is not the thread in which the queue was created.
238 /// - This function panics if this proxy is a wrapper.
239 ///
240 /// # Safety
241 ///
242 /// - `opcode` must be a valid request opcode for the interface of the proxy.
243 /// - `args` must conform to the interface + opcode of the proxy.
244 /// - `args` must not contain any `new_id` element.
245 #[inline]
246 pub unsafe fn send_destructor(&self, opcode: u32, args: &mut [wl_argument]) {
247 let slf = self.data();
248 if slf.interface.is_none() {
249 panic!("Proxy is a wrapper");
250 }
251 let _write_lock = slf.proxy.lock.write();
252 // SAFETY: We're holding the write lock.
253 let proxy = slf.proxy.proxy.load(Relaxed);
254 let proxy = check_dispatching_proxy(NonNull::new(proxy));
255 // SAFETY: We're holding the write lock.
256 slf.proxy.proxy.store(ptr::null_mut(), Relaxed);
257 // SAFETY: - We've just checked that proxy is not null. By the invariants, the
258 // proxy is valid.
259 // - The opcode/args requirements are forwarded to the caller.
260 // - Flags are WL_MARSHAL_FLAG_DESTROY.
261 // - We've checked above that the proxy is not a wrapper.
262 // - We've set the proxy pointer to null.
263 unsafe {
264 slf.proxy.libwayland.wl_proxy_marshal_array_flags(
265 proxy.as_ptr(),
266 opcode,
267 ptr::null(),
268 0,
269 WL_MARSHAL_FLAG_DESTROY,
270 args.as_mut_ptr(),
271 );
272 }
273 // SAFETY: - We're holding the write lock of the proxy.
274 // - The proxy has been destroyed.
275 unsafe {
276 self.destroy_event_handler();
277 }
278 }
279
280 /// Creates a new object by sending a request on this proxy.
281 ///
282 /// If `DESTROY=true`, then the underlying `wl_proxy` has been destroyed after this
283 /// function returns.
284 ///
285 /// This function can only be used if the request creates a new object. Use
286 /// [`UntypedOwnedProxy::send_destructor`] or [`UntypedBorrowedProxy::send_request`]
287 /// otherwise.
288 ///
289 /// The new object will be attached to the queue of this proxy.
290 ///
291 /// # Panic
292 ///
293 /// - This function panics if this proxy has already been destroyed.
294 /// - If `DESTROY=true`, then this function might panic if the proxy is attached to a
295 /// local queue and the current thread is not the thread in which the queue was
296 /// created.
297 /// - If `DESTROY=true`, then this function panics if this proxy is a wrapper.
298 ///
299 /// # Safety
300 ///
301 /// - `opcode` must be a valid request opcode for the interface of the proxy.
302 /// - `args` must conform to the interface + opcode of the proxy.
303 /// - `args` must contain exactly one `new_id` element.
304 /// - `interface` must be a valid `wl_interface`.
305 pub unsafe fn send_constructor<const DESTROY: bool>(
306 &self,
307 opcode: u32,
308 args: &mut [wl_argument],
309 interface: &'static wl_interface,
310 version: Option<u32>,
311 ) -> Self {
312 let slf = self.data();
313 let (_read_lock, _write_lock);
314 if DESTROY {
315 if slf.interface.is_none() {
316 panic!("Proxy is a wrapper");
317 }
318 _write_lock = slf.proxy.lock.write();
319 } else {
320 _read_lock = slf.proxy.lock.read_recursive();
321 }
322 // SAFETY: We're holding at least a read lock.
323 let proxy = slf.proxy.proxy.load(Relaxed);
324 let proxy = check_dispatching_proxy(NonNull::new(proxy));
325 let version = version.unwrap_or_else(|| {
326 // SAFETY: - We're holding at least a read lock which ensures that the pointer
327 // stays valid.
328 // - We've just checked that the pointer is valid.
329 unsafe { slf.proxy.libwayland.wl_proxy_get_version(proxy.as_ptr()) }
330 });
331 let mut flags = 0;
332 if DESTROY {
333 flags |= WL_MARSHAL_FLAG_DESTROY;
334 // SAFETY: We're holding the write lock.
335 slf.proxy.proxy.store(ptr::null_mut(), Relaxed);
336 }
337 // SAFETY: - We've just checked that proxy is not null. By the invariants, the
338 // proxy is valid.
339 // - The opcode/args requirements are forwarded to the caller.
340 // - Flags are 0 or WL_MARSHAL_FLAG_DESTROY.
341 // - If flags contains WL_MARSHAL_FLAG_DESTROY then we've checked above
342 // that the proxy is not a wrapper and we've set the proxy pointer to
343 // null.
344 let new_proxy = unsafe {
345 slf.proxy.libwayland.wl_proxy_marshal_array_flags(
346 proxy.as_ptr(),
347 opcode,
348 interface,
349 version,
350 flags,
351 args.as_mut_ptr(),
352 )
353 };
354 if DESTROY {
355 // SAFETY: - We're holding the write lock of the proxy.
356 // - The proxy has been destroyed.
357 unsafe {
358 self.destroy_event_handler();
359 }
360 }
361 let new_proxy = check_new_proxy(new_proxy);
362 // SAFETY: - new_proxy was returned by libwayland and we've just checked that it
363 // is not null
364 // - we're passing ownership
365 // - proxy was just created so it doesn't have a dispatcher
366 // - wl_proxy_marshal_array_flags attaches new proxy to the same queue as
367 // the input proxy
368 // - wl_proxy_marshal_array_flags sets the interface of the proxy to the
369 // interface passed into the function
370 unsafe { UntypedOwnedProxy::from_plain_wl_proxy(&slf.queue, new_proxy, interface) }
371 }
372
373 pub(crate) fn set_event_handler<T>(&self, handler: T)
374 where
375 T: EventHandler + Send + 'static,
376 {
377 // SAFETY: T implements Send.
378 unsafe {
379 self.set_event_handler2(handler);
380 }
381 }
382
383 pub(crate) fn set_event_handler_local<T>(&self, handler: T)
384 where
385 T: EventHandler + 'static,
386 {
387 if self.data().queue.is_non_local() {
388 panic!("Queue is not a local queue");
389 }
390 // SAFETY: We've just checked that the queue is thread local.
391 unsafe {
392 self.set_event_handler2(handler);
393 }
394 }
395
396 /// # Safety
397 ///
398 /// If T does not implement Send, then the queue must be a local queue.
399 unsafe fn set_event_handler2<T>(&self, event_handler: T)
400 where
401 T: EventHandler + 'static,
402 {
403 // SAFETY: - all requirements except the callability of event_handler_func as part
404 // of a libwayland dispatch are trivially satisfied
405 // - libwayland only ever calls event handlers while preserving a
406 // valid pointer to the proxy and all pointers in args
407 // - set_event_handler4 checks that the interface of the proxy is
408 // T::WL_INTERFACE
409 // - libwayland ensures that opcode and args conform to the
410 // interface before calling the event handler
411 // - set_event_handler4 sets event_handler to a pointer to T
412 // - we only ever invalidate the self.event_handler or self.data
413 // pointers while the queue is idle and after having destroyed
414 // the proxy.
415 // - if T is not Send, then this function requires that this is a
416 // local queue which will panic when trying to call this function
417 // or any dispatching function on a thread other than the thread
418 // on which the queue was created
419 // - we always hold the queue lock while dispatching
420 unsafe {
421 self.set_event_handler3(event_handler, event_handler_func::<T>, None);
422 }
423 }
424
425 /// # Safety
426 ///
427 /// - if T does not implement Send, then the queue must be a local queue
428 /// - the safety requirements of event_handler_func must be satisfied whenever it is
429 /// called
430 /// - if scope is Some, then either
431 /// - the event handler must be destroyed before the end of 'scope, OR
432 /// - ScopeData::handle_destruction must never run the destructions
433 unsafe fn set_event_handler3<'scope, T>(
434 &self,
435 event_handler: T,
436 event_handler_func: wl_dispatcher_func_t,
437 scope: Option<&'scope Scope<'scope, '_>>,
438 ) where
439 T: EventHandler,
440 {
441 unsafe fn drop<T>(event_handler: *mut u8) {
442 // SAFETY: This function is called only to drop the boxed event_handler.
443 unsafe {
444 let _ = Box::from_raw(event_handler.cast::<T>());
445 }
446 }
447
448 let event_handler = Box::into_raw(Box::new(event_handler)).cast();
449 let dealloc = on_drop(move || {
450 // SAFETY: - This is only called if set_event_handler4 panics, otherwise the
451 // on_drop is forgotten.
452 // - If set_event_handler4 panics, then it has not assumed ownership
453 // of the event handler.
454 unsafe { drop::<T>(event_handler) }
455 });
456 // SAFETY: - interface is T::WL_INTERFACE
457 // - event_handler is a pointer to T
458 // - we've called Box::into_raw on the event handler so it stays valid
459 // valid pointer to the proxy and all pointers in args
460 // - drop_event_handler is a pointer to the deallocator
461 // - the other requirements are forwarded to the caller of this function
462 unsafe {
463 self.set_event_handler4(
464 T::WL_INTERFACE,
465 T::mutable_type(),
466 event_handler,
467 drop::<T> as *mut u8,
468 mem::needs_drop::<T>(),
469 event_handler_func,
470 scope,
471 )
472 }
473 dealloc.forget();
474 }
475
476 /// This function verifies the following:
477 ///
478 /// - `event_handler_func` is only called as part of a libwayland dispatch
479 /// - this proxy has the interface `interface`.
480 /// - if `mutable_data_type` is Some, then it is the type of `()` or the type returned
481 /// by [Queue::mut_data_type] of [Self::queue].
482 ///
483 /// # Safety
484 ///
485 /// There must be a type `T: EventHandler` such that
486 ///
487 /// - interface is T::WL_INTERFACE
488 /// - mutable_data_type is T::mutable_type()
489 /// - event_handler is a pointer to a T
490 /// - if T does not implement Send, then the queue must be a local queue
491 /// - event_handler must stay valid until drop_event handler is called
492 /// - drop_event_handler is a pointer to a unsafe fn(*mut u8)
493 /// that can be called once with event_handler
494 /// - the safety requirements of event_handler_func must be satisfied whenever it is
495 /// called by libwayland as part of a dispatch
496 /// - if scope is Some, then either
497 /// - the event handler must be destroyed before the end of 'scope, OR
498 /// - ScopeData::handle_destruction must never run the destructions
499 #[expect(clippy::too_many_arguments)]
500 unsafe fn set_event_handler4<'scope>(
501 &self,
502 interface: &'static wl_interface,
503 mutable_data_type: Option<(TypeId, &'static str)>,
504 event_handler: *mut u8,
505 drop_event_handler: *mut u8,
506 needs_drop: bool,
507 event_handler_func: wl_dispatcher_func_t,
508 scope: Option<&'scope Scope<'scope, '_>>,
509 ) {
510 let slf = self.data();
511 match slf.interface {
512 None => panic!("Proxy is a wrapper"),
513 Some(i) => {
514 // SAFETY: EventHandler::WL_INTERFACE and slf.interface are always valid
515 // interfaces.
516 let compatible = unsafe { interface_compatible(i, interface) };
517 if !compatible {
518 panic!("Proxy has an incompatible interface");
519 }
520 }
521 }
522 'check_mutable_data: {
523 let Some((mutable_data_type, mutable_data_type_name)) = mutable_data_type else {
524 break 'check_mutable_data;
525 };
526 if mutable_data_type == TypeId::of::<()>() {
527 break 'check_mutable_data;
528 }
529 let (mut_data_type, mut_data_type_name) = slf.queue.mut_data_type();
530 if Some(mutable_data_type) == mut_data_type {
531 break 'check_mutable_data;
532 }
533 if let Some(name) = mut_data_type_name {
534 panic!(
535 "This queue only supports mutable data of type `{name}` but the \
536 event handler requires type `{mutable_data_type_name}`",
537 );
538 } else {
539 panic!(
540 "This queue does not support mutable data but the event handler \
541 requires type `{mutable_data_type_name}`",
542 );
543 }
544 };
545 let lock = slf.proxy.lock();
546 let proxy = check_dispatching_proxy(lock.wl_proxy());
547 if slf.ever_had_event_handler.swap(true, Relaxed) {
548 panic!("Proxy already has an event handler");
549 }
550 if let Some(scope) = scope {
551 *slf.scope_data_arc.lock() = Some(scope.data.clone());
552 slf.scope_data
553 .store(ptr::from_ref(&*scope.data).cast_mut(), Relaxed);
554 }
555 if needs_drop {
556 slf.stored_in_registry.store(true, Relaxed);
557 // SAFETY: - self.data is only ever invalidated via self.create_destruction which
558 // will remove self.data from the registry.
559 // - we just wrote to the scope_data field in this thread.
560 unsafe {
561 self.modify_owned_registry(|r| {
562 r.insert(self.data);
563 });
564 }
565 }
566 let _queue_lock = slf.queue.lock_dispatch();
567 slf.event_handler.store(event_handler, Relaxed);
568 slf.drop_event_handler.store(drop_event_handler, Relaxed);
569 // SAFETY: - we're holding the proxy lock so the proxy is valid
570 // - we're holding the queue lock which is always held when
571 // accessing/modifying the unprotected fields of the wl_proxy
572 // - by the safety requirements of this function, the safety
573 // requirements of event_handler_func are satisfied whenever it is
574 // called by libwayland as part of a dispatch; and the function set
575 // through this call is only ever called as part of a dispatch.
576 unsafe {
577 slf.proxy.libwayland.wl_proxy_add_dispatcher(
578 proxy.as_ptr(),
579 Some(event_handler_func),
580 self.data.as_ptr() as *mut c_void,
581 ptr::null_mut(),
582 );
583 }
584 }
585
586 /// Returns the queue of this proxy.
587 ///
588 /// This is the same queue that was passed into the constructor of this object.
589 #[inline]
590 pub fn queue(&self) -> &Queue {
591 &self.data().queue
592 }
593
594 /// Destroys a proxy without sending a wayland message.
595 ///
596 /// This function only destroys the proxy in libwayland without sending a message to the
597 /// compositor.
598 ///
599 /// # Panic
600 ///
601 /// This function might panic if the proxy is attached to a local queue and the current
602 /// thread is not the thread in which the queue was created.
603 #[inline]
604 pub fn destroy(&self) {
605 let slf = self.data();
606 let _lock = slf.proxy.lock.write();
607 if slf.proxy.proxy.load(Relaxed).is_null() {
608 return;
609 }
610 // SAFETY: We're holding the write lock.
611 unsafe {
612 self.destroy_proxy();
613 }
614 // SAFETY: - We're holding the write lock of the proxy.
615 // - The proxy has been destroyed.
616 unsafe {
617 self.destroy_event_handler();
618 }
619 }
620
621 /// Destroys the proxy if it is not already destroyed.
622 ///
623 /// # Safety
624 ///
625 /// - The caller must have exclusive access to the proxy pointer.
626 unsafe fn destroy_proxy(&self) {
627 let slf = self.data();
628 // SAFETY: By the requirements of this function we have exclusive access to the
629 // pointer.
630 let proxy = slf.proxy.proxy.load(Relaxed);
631 if proxy.is_null() {
632 return;
633 }
634 // SAFETY: By the requirements of this function we have exclusive access to the
635 // pointer.
636 slf.proxy.proxy.store(ptr::null_mut(), Relaxed);
637 if slf.interface.is_none() {
638 // SAFETY: - By the requirements of the function, we have exclusive write
639 // access to the pointer.
640 // - We've just checked that the pointer is not null. By the
641 // invariants of UntypedBorrowedProxy, this means that the pointer
642 // is valid.
643 // - By the invariants of this type, since the interface is None,
644 // the proxy is a wrapper.
645 unsafe {
646 slf.proxy.libwayland.wl_proxy_wrapper_destroy(proxy.cast());
647 }
648 } else {
649 // SAFETY: - By the requirements of the function, we have exclusive write
650 // access to the pointer.
651 // - We've just checked that the pointer is not null. By the
652 // invariants of UntypedBorrowedProxy, this means that the pointer
653 // is valid.
654 // - By the invariants of this type, since the interface is Some,
655 // the proxy is not a wrapper.
656 unsafe {
657 slf.proxy.libwayland.wl_proxy_destroy(proxy);
658 }
659 }
660 }
661
662 /// Creates a [`ProxyDataDestruction`] destroying parts of this object.
663 ///
664 /// If the proxy has an event handler with a Drop impl attached, the destruction will
665 /// drop that event handler.
666 ///
667 /// If `destroy_proxy_data` is true, then the destruction will destroy the
668 /// [`UntypedOwnedProxyData`].
669 ///
670 /// # Safety
671 ///
672 /// - The caller must have exclusive access to the proxy pointer.
673 unsafe fn create_destruction(&self, destroy_proxy_data: bool) -> ProxyDataDestruction {
674 let slf = self.data();
675 let data = destroy_proxy_data.then_some(self.data);
676 let drop_event_handler = {
677 // SAFETY: - By the safety requirements of this function, the caller has
678 // exclusive access to the proxy pointer which ensures visibility
679 // of the drop_event_handler and event_handler fields.
680 let drop_event_handler = slf.drop_event_handler.load(Relaxed);
681 if drop_event_handler.is_null() {
682 None
683 } else {
684 slf.drop_event_handler.store(ptr::null_mut(), Relaxed);
685 Some((
686 SyncPtr(slf.event_handler.load(Relaxed)),
687 SyncPtr(drop_event_handler),
688 ))
689 }
690 };
691 let destruction = ProxyDataDestruction::new(data, drop_event_handler);
692 if slf.stored_in_registry.load(Relaxed) {
693 // SAFETY: - We've just created a destruction fo the event handler if it exists.
694 // - By the safety requirements of this function, the caller has
695 // exclusive access to the proxy pointer.
696 unsafe {
697 self.modify_owned_registry(|r| {
698 r.remove(&self.data);
699 });
700 }
701 slf.stored_in_registry.store(false, Relaxed);
702 }
703 destruction
704 }
705
706 /// # Safety
707 ///
708 /// - All pointers in the registry must be valid.
709 /// - If a proxy has an event handler, it must not be removed from the registry before
710 /// a destruction has been created for the event handler.
711 /// - The caller must have exclusive access to the proxy pointer or must ensure that
712 /// writes to the scope_data field happen before this call.
713 unsafe fn modify_owned_registry(
714 &self,
715 f: impl FnOnce(&mut HashSet<SyncNonNull<UntypedOwnedProxyData>>),
716 ) {
717 // SAFETY: The requirement is forwarded to the caller.
718 let scope = unsafe { self.scope() };
719 let mut registry = if let Some(scope) = scope {
720 scope.registry.proxies.lock()
721 } else {
722 self.data().queue.owned_proxy_registry().proxies.lock()
723 };
724 f(&mut registry)
725 }
726
727 /// # Safety
728 ///
729 /// - This must only be called from `drop` once the ref count reaches 0.
730 /// - The effects of other threads must have been made visible.
731 #[inline(never)]
732 unsafe fn drop_slow(&self) {
733 // SAFETY: Since the ref count has reached 0, there are no longer any accessible
734 // UntypedOwnedProxy referring to the UntypedOwnedProxyData. Since the
735 // UntypedOwnedProxyData contains the UntypedBorrowedProxy by value, there can
736 // be no other references to the proxy pointer.
737 unsafe {
738 self.destroy_proxy();
739 }
740 // SAFETY: We have exclusive access to the proxy pointer.
741 let destruction = unsafe { self.create_destruction(true) };
742 let slf = self.data();
743 // SAFETY: We have exclusive access to the proxy pointer.
744 let scope = unsafe { self.scope() };
745 if let Some(scope) = scope {
746 let _scope = slf.scope_data_arc.lock().clone();
747 // SAFETY: - scope() returns the scope that this proxy is attached to.
748 // - If the destruction contains an event handler, then, by the safety
749 // requirements of set_event_handler4, we know that
750 // - we are either within 'scope since otherwise
751 // destroy_event_handler would have been called and consumed the
752 // event handler earlier, OR
753 // - handle_destruction is a no-op.
754 // If handle_destruction never runs any of the destructions, there
755 // is nothing to show. Otherwise running the drop impl of the event
756 // handler is safe as soon as it is no longer referenced anywhere
757 // since the event handler outlives 'scope.
758 // - Since the proxy is destroyed, once there are no ongoing
759 // dispatches, there wont ever again be any dispatches.
760 // - The _scope variable above ensures that the scope remains valid
761 // for the duration of the function call.
762 unsafe {
763 scope.handle_destruction(destruction);
764 }
765 } else if slf.ever_had_event_handler.load(Relaxed) {
766 let queue = slf.queue.clone();
767 // SAFETY: - We've just destroyed the proxy above.
768 // - By the invariants, the proxy is attached to slf.queue.
769 // - When the queue runs the destruction, no dispatches will be
770 // running and all subsequent dispatches will happen after this line
771 // of code.
772 // - Therefore, libwayland will see that we've destroyed the proxy and
773 // will not call into the event handler.
774 unsafe {
775 queue.run_destruction_on_idle(destruction);
776 }
777 } else {
778 // SAFETY: - If ever_had_event_handler is false, then neither the queue nor
779 // libwayland ever had a reference to this object.
780 unsafe {
781 destruction.run();
782 }
783 }
784 }
785
786 /// # Safety
787 ///
788 /// - The caller must have exclusive access to the proxy pointer.
789 /// - If the proxy is not yet destroyed then it must have a scope and the event
790 /// handler must not be dispatched again.
791 #[inline(never)]
792 unsafe fn destroy_event_handler(&self) {
793 // SAFETY: By the safety requirements of this function, we have exclusive access
794 // to the proxy pointer.
795 let destruction = unsafe { self.create_destruction(false) };
796 if destruction.is_noop() {
797 return;
798 }
799 // SAFETY: By the safety requirements of this function, we have exclusive access
800 // to the proxy pointer.
801 let scope = unsafe { self.scope() };
802 if let Some(scope) = scope {
803 // SAFETY: - scope() returns the scope that this proxy is attached to.
804 // - Since the destruction is not a no-op, we know that this is the
805 // first call to destroy_event_handler.
806 // - By the safety requirements of set_event_handler4, we know that
807 // either we are within 'scope or the destruction is never run. If
808 // the destruction is never run, then there is nothing to show.
809 // Otherwise, since the event handler outlives 'scope, calling its
810 // drop impl is safe if it is no longer reference anywhere.
811 // - If the proxy is destroyed, then, once there are no ongoing
812 // dispatches, there wont ever again be any dispatches.
813 // - Otherwise, since the event handler is never again dispatched, once
814 // there are no ongoing dispatches, it is safe to destroy it.
815 unsafe {
816 scope.handle_destruction(destruction);
817 }
818 } else {
819 // SAFETY: - This function requires that the proxy is already destroyed.
820 // - By the invariants, the proxy is attached to self.data().queue.
821 // - When the queue runs the destruction, no dispatches will be
822 // running and all subsequent dispatches will happen after this line
823 // of code.
824 // - Therefore, libwayland will see that we've destroyed the proxy and
825 // will not call into the event handler.
826 // - This call cannot possibly invalidate self.data, even if dropping the
827 // event handler recursively drops an UntypedOwnedProxy, since we're holding
828 // on to an UntypedOwnedProxy. Therefore self.data().queue remains valid
829 // for the function call.
830 unsafe {
831 self.data().queue.run_destruction_on_idle(destruction);
832 }
833 }
834 }
835
836 /// # Safety
837 ///
838 /// - The caller must have exclusive access to the proxy pointer or must ensure that
839 /// writes to the scope_data field happen before this call.
840 unsafe fn scope(&self) -> Option<&ScopeData> {
841 NonNull::new(self.data().scope_data.load(Relaxed)).map(|s| {
842 // SAFETY: See the documentation of scope_data for why this is safe.
843 unsafe { s.as_ref() }
844 })
845 }
846}
847
848impl Clone for UntypedOwnedProxy {
849 fn clone(&self) -> Self {
850 let slf = self.data();
851 if slf.ref_count.fetch_add(1, Relaxed) > usize::MAX / 2 {
852 std::process::abort();
853 }
854 Self { data: self.data }
855 }
856}
857
858impl Drop for UntypedOwnedProxy {
859 #[inline]
860 fn drop(&mut self) {
861 let slf = self.data();
862 if slf.ref_count.fetch_sub(1, Release) == 1 {
863 fence(Acquire);
864 // SAFETY: - we're in the drop impl
865 // - the acquire fence ensures visibility
866 unsafe {
867 self.drop_slow();
868 }
869 }
870 }
871}
872
873impl OwnedProxyRegistry {
874 /// Destroys all proxies in this registry.
875 pub(crate) fn destroy_all(&self) {
876 for proxy in self.get_todos() {
877 proxy.destroy();
878 }
879 }
880
881 /// # Safety
882 ///
883 /// - All proxies in the registry must belong to a single scope.
884 /// - We must be within the lifetime of the scope.
885 /// - The queue lock must be held.
886 /// - For all of the event handlers attached to proxies in the registry:
887 /// - The event handlers must not current be being dispatched.
888 /// - The event handlers must not be dispatched in the future.
889 unsafe fn destroy_event_handlers(&self) {
890 for proxy in self.get_todos() {
891 let _write_lock = proxy.lock.write();
892 // SAFETY: - We're holding the write lock of the proxy.
893 // - By the safety requirements of this function, the event handlers
894 // are currently not being dispatched and will not be dispatched in
895 // the future.
896 unsafe {
897 proxy.destroy_event_handler();
898 }
899 }
900 }
901
902 fn get_todos(&self) -> Vec<UntypedOwnedProxy> {
903 let proxies = &mut *self.proxies.lock();
904 self.get_todos_locked(proxies)
905 }
906
907 fn get_todos_locked(
908 &self,
909 proxies: &mut HashSet<SyncNonNull<UntypedOwnedProxyData>>,
910 ) -> Vec<UntypedOwnedProxy> {
911 let mut todo = Vec::with_capacity(proxies.len());
912 for proxy in &*proxies {
913 // SAFETY: By the invariants, all pointers in the hash set are valid.
914 let data = unsafe { &*proxy.as_ptr() };
915 let mut ref_count = data.ref_count.load(Relaxed);
916 while ref_count != 0 {
917 if ref_count > usize::MAX / 2 {
918 std::process::abort();
919 }
920 let res = data.ref_count.compare_exchange_weak(
921 ref_count,
922 ref_count + 1,
923 Relaxed,
924 Relaxed,
925 );
926 match res {
927 Ok(_) => {
928 // SAFETY: We've just acquire a strong reference.
929 todo.push(UntypedOwnedProxy { data: *proxy });
930 break;
931 }
932 Err(c) => ref_count = c,
933 }
934 }
935 }
936 *proxies = HashSet::default();
937 todo
938 }
939}
940
941/// An event handler that can handle raw libwayland events.
942///
943/// # Safety
944///
945/// - `WL_INTERFACE` must be a valid wl_interface.
946/// - `mutable_type` must always return the same value.
947pub unsafe trait EventHandler {
948 /// The type of interface that can be handled by this event handler.
949 const WL_INTERFACE: &'static wl_interface;
950
951 /// Returns the mutable data type required by this event handler.
952 #[inline]
953 fn mutable_type() -> Option<(TypeId, &'static str)> {
954 None
955 }
956
957 /// Dispatches a raw libwayland event.
958 ///
959 /// # Safety
960 ///
961 /// - `slf` must have an interface compatible with `WL_INTERFACE`.
962 /// - `opcode` and `args` must conform to an event of `WL_INTERFACE`.
963 /// - Any objects contained in `args` must remain valid for the duration of the call.
964 /// - If `Self::mutable_data` returns `Some`, then `data` must be `&mut T` where `T`
965 /// has the type ID returned by `mutable_data`.
966 unsafe fn handle_event(
967 &self,
968 queue: &Queue,
969 data: *mut u8,
970 slf: &UntypedBorrowedProxy,
971 opcode: u32,
972 args: *mut wl_argument,
973 );
974}
975
976/// The event handler function.
977///
978/// This function is called by libwayland when dispatching an event for the proxy. This
979/// function is only called when the proxy's queue is explicitly being dispatched.
980///
981/// # Safety
982///
983/// - target must be a valid wl_proxy pointer
984/// - the interface of target must be compatible with T::WL_INTERFACE
985/// - event_handler_data must be a pointer to UntypedOwnedProxyData
986/// - the event_handler field in the UntypedOwnedProxy must contain a pointer to T
987/// - opcode and args must conform to T::WL_INTERFACE
988/// - all pointers must remain valid for the duration of this function call
989/// - the previous point includes pointers inside args
990/// - if T is not `Send`, then the current thread must be the thread on which the
991/// event handler was attached
992/// - the queue lock of the proxy must be held
993/// - this must only be called by libwayland as part of an event handler dispatch of the
994/// proxy stored in target
995unsafe extern "C" fn event_handler_func<T>(
996 event_handler_data: *const c_void,
997 target: *mut c_void,
998 opcode: u32,
999 _msg: *const wl_message,
1000 args: *mut wl_argument,
1001) -> c_int
1002where
1003 T: EventHandler,
1004{
1005 // SAFETY: By the safety requirements of this function, event_handler is a valid pointer
1006 // to UntypedOwnedProxyData.
1007 let proxy_data = unsafe { &*(event_handler_data as *const UntypedOwnedProxyData) };
1008 // SAFETY: Dito, target is and stays valid.
1009 let target = unsafe { NonNull::new_unchecked(target.cast()) };
1010 // SAFETY: Dito, target is and stays valid.
1011 let target =
1012 unsafe { UntypedBorrowedProxy::new_immutable(proxy_data.proxy.libwayland, target) };
1013 let event_handler = proxy_data.event_handler.load(Relaxed).cast::<T>();
1014 // SAFETY: - Dito, event_handler is a valid pointer to T
1015 // - Dito, this function is never called concurrently, therefore it doesn't matter if
1016 // T implements Sync.
1017 // - Dito, if T does not implement Send, then we're creating this reference only in the
1018 // same thread on which the event_handler was attached.
1019 let event_handler = unsafe { &*event_handler };
1020 // SAFETY: - Dito, the queue mutex is held.
1021 let data = unsafe { proxy_data.queue.data() };
1022 let res = catch_unwind(AssertUnwindSafe(|| {
1023 // SAFETY: - Dito, the interface of target is compatible with T::WL_INTERFACE
1024 // - Dito, target is a valid pointer and stays valid
1025 // - Dito, opcode and args conform to T::WL_INTERFACE
1026 // - Dito, we're being called by libwayland as part of a libwayland
1027 // dispatch. If `T::mutable_data` returns `Some`, then Queue::data
1028 // guarantees that `data` can be dereferenced to that type.
1029 unsafe {
1030 event_handler.handle_event(&proxy_data.queue, data, &target, opcode, args);
1031 }
1032 }));
1033 if let Err(e) = res {
1034 DISPATCH_PANIC.set(Some(e));
1035 }
1036 0
1037}
1038
1039thread_local! {
1040 pub(crate) static DISPATCH_PANIC: Cell<Option<Box<dyn Any + Send>>> = const { Cell::new(None) };
1041}