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