Skip to main content

wl_client/
libwayland.rs

1use crate::ffi::wl_argument;
2use crate::ffi::wl_dispatcher_func_t;
3use crate::ffi::wl_display;
4use crate::ffi::wl_event_queue;
5use crate::ffi::wl_interface;
6use crate::ffi::wl_proxy;
7use libloading::Library;
8use parking_lot::Mutex;
9use std::ffi::c_char;
10use std::ffi::c_int;
11use std::ffi::c_void;
12use std::io;
13use std::mem;
14use std::sync::LazyLock;
15
16/// A reference to the `libwayland-client.so` dynamic library.
17///
18/// You can obtain a reference by calling [`Self::open`].
19pub struct Libwayland {
20    syms: Symbols,
21    syms_opt: SymbolsOpt,
22}
23
24/// # Safety
25///
26/// The types and names must match the libwayland ABI.
27macro_rules! unsafe_symbols {
28    (
29        $symbols:ident;
30        $(
31            $name:ident: $ty:ty,
32        )*
33    ) => {
34        struct $symbols {
35            $($name: $ty,)*
36        }
37
38        impl $symbols {
39            /// # Safety
40            ///
41            /// `lib` must be libwayland-client.so.
42            unsafe fn load(lib: &Library) -> Result<Self, libloading::Error> {
43                macro_rules! get {
44                    ($v:ident: Option<$ty2:ty>) => {
45                        $v.ok().map(|v| *v)
46                    };
47                    ($v:ident: $ty2:ty) => {
48                        *$v?
49                    };
50                }
51                Ok(Self {
52                    $(
53                        $name: {
54                            // SAFETY: By the requirements of this macro, $name has the
55                            //         requested type.
56                            let v = unsafe {
57                                lib.get(concat!(stringify!($name), "\0").as_bytes())
58                            };
59                            get!(v: $ty)
60                        },
61                    )*
62                })
63            }
64        }
65    };
66}
67
68/// # Safety
69///
70/// - The types and names must match the libwayland API.
71/// - Each function must document the safety requirements of the libwayland function.
72macro_rules! unsafe_fwd {
73    (
74        $(
75            $(
76                #[$attr:meta]
77            )*
78            fn $name:ident($($arg:ident: $ty:ty),+$(,)?) $(-> $ret:ty)?;
79        )*
80    ) => {
81        // SAFETY: The requirement is forwarded to the caller.
82        unsafe_symbols! {
83            Symbols;
84            $(
85                $name: unsafe extern "C" fn($($arg: $ty,)*) $(-> $ret)?,
86            )*
87        }
88        impl Libwayland {
89            $(
90                $(
91                    #[$attr]
92                )*
93                #[inline(always)]
94                pub(crate) unsafe fn $name(&self $(, $arg: $ty)*) $(-> $ret)? {
95                    // SAFETY: - $name matches the API of libwayland
96                    //         - All safety requirements of the libwayland function are
97                    //           forwarded to the caller of this function.
98                    unsafe {
99                        (self.syms.$name)($($arg,)*)
100                    }
101                }
102            )*
103        }
104    };
105}
106
107// SAFETY: There functions are as described in wayland-client-core.h.
108unsafe_symbols! {
109    SymbolsOpt;
110    wl_display_create_queue_with_name: Option<
111        unsafe extern "C" fn(display: *mut wl_display, name: *const c_char) -> *mut wl_event_queue,
112    >,
113    wl_proxy_get_queue: Option<unsafe extern "C" fn(proxy: *mut wl_proxy) -> *mut wl_event_queue>,
114    wl_proxy_get_display: Option<unsafe extern "C" fn(proxy: *mut wl_proxy) -> *mut wl_display>,
115}
116
117// SAFETY: - There functions are as described in wayland-client-core.h.
118//         - The safety requirements are documented as far as I know them.
119unsafe_fwd! {
120    /// Destroys a queue.
121    ///
122    /// # Safety
123    ///
124    /// - queue must be a valid pointer
125    /// - all attached proxies must leak
126    fn wl_event_queue_destroy(queue: *mut wl_event_queue);
127
128    /// Sends a request.
129    ///
130    /// If flags contains WL_MARSHAL_FLAG_DESTROY, then this function destroys the proxy.
131    ///
132    /// If interface is not null, then this function returns a new non-wrapper proxy with
133    /// that interface.
134    ///
135    /// # Safety
136    ///
137    /// - proxy must be a valid pointer
138    /// - opcode must be a valid request opcode for the interface of the proxy
139    /// - args must be a pointer to an array of wl_arguments
140    /// - the array must conform to the interface + opcode of the proxy
141    /// - if interface is not null, it must be a valid pointer to a valid interface definition
142    /// - if interface is not null, then args must contain exactly on new_id element
143    /// - if interface is null, then args must not contain any new_id element
144    /// - flags must be 0 or WL_MARSHAL_FLAG_DESTROY
145    /// - if flags contains WL_MARSHAL_FLAG_DESTROY, then proxy must not be a wrapper
146    fn wl_proxy_marshal_array_flags(
147        proxy: *mut wl_proxy,
148        opcode: u32,
149        interface: *const wl_interface,
150        version: u32,
151        flags: u32,
152        args: *mut wl_argument,
153    ) -> *mut wl_proxy;
154
155    /// Creates a new wrapper proxy.
156    ///
157    /// # Safety
158    ///
159    /// - proxy must be a valid pointer.
160    fn wl_proxy_create_wrapper(proxy: *mut c_void) -> *mut c_void;
161
162    /// Destroys a wrapper proxy.
163    ///
164    /// # Safety
165    ///
166    /// - proxy must be a valid pointer to a wrapper
167    fn wl_proxy_wrapper_destroy(proxy: *mut c_void);
168
169    /// Destroys a non-wrapper proxy.
170    ///
171    /// # Safety
172    ///
173    /// - proxy must be a valid pointer to a wrapper
174    fn wl_proxy_destroy(proxy: *mut wl_proxy);
175
176    /// Sets the dispatcher of the proxy.
177    ///
178    /// # Safety
179    ///
180    /// - proxy must be a valid pointer to a non-wrapper
181    /// - this modifies the unprotected, mutable fields of the wl_proxy and access must be
182    ///   externally synchronized
183    /// - the caller must ensure that the safety requirements of the dispatcher_func are
184    ///   satisfied whenever it is called
185    fn wl_proxy_add_dispatcher(
186        proxy: *mut wl_proxy,
187        dispatcher_func: Option<wl_dispatcher_func_t>,
188        dispatcher_data: *const c_void,
189        data: *mut c_void,
190    );
191
192    /// Returns the ID of the proxy.
193    ///
194    /// # Safety
195    ///
196    /// - proxy must be a valid pointer
197    fn wl_proxy_get_id(proxy: *mut wl_proxy) -> u32;
198
199    /// Returns the version of the proxy.
200    ///
201    /// # Safety
202    ///
203    /// - proxy must be a valid pointer
204    fn wl_proxy_get_version(proxy: *mut wl_proxy) -> u32;
205
206    /// Sets the queue of the proxy.
207    ///
208    /// # Safety
209    ///
210    /// - proxy must be a valid pointer
211    /// - queue must be a valid pointer
212    /// - the queue must not be destroyed while it has proxies attached
213    /// - the queue and the proxy must belong to the same wl_display
214    fn wl_proxy_set_queue(proxy: *mut wl_proxy, queue: *mut wl_event_queue);
215
216    /// Connects to the wayland socket from the environment.
217    ///
218    /// # Safety
219    ///
220    /// - name must be null or a c string
221    fn wl_display_connect(name: *const c_char) -> *mut wl_display;
222
223    /// Connects to an existing file descriptor.
224    ///
225    /// # Safety
226    ///
227    /// - `fd` must be a valid file descriptor.
228    /// - This function takes ownership of the file descriptor.
229    fn wl_display_connect_to_fd(fd: c_int) -> *mut wl_display;
230
231    /// Disconnects the display.
232    ///
233    /// # Safety
234    ///
235    /// - display must be a valid pointer
236    /// - all queues and proxies must have been destroyed or must leak
237    fn wl_display_disconnect(display: *mut wl_display);
238
239    /// Dispatches a queue.
240    ///
241    /// # Safety
242    ///
243    /// - display and queue must be valid pointers
244    /// - the queue must belong to the display
245    /// - this accesses the unprotected, mutable fields of all proxies that were attached
246    ///   to the queue before the start of the previous queue dispatch.
247    ///   access must be externally synchronized.
248    fn wl_display_dispatch_queue_pending(
249        display: *mut wl_display,
250        queue: *mut wl_event_queue,
251    ) -> c_int;
252
253    /// Flushes the display.
254    ///
255    /// # Safety
256    ///
257    /// - display must be a valid pointer
258    fn wl_display_flush(display: *mut wl_display) -> c_int;
259
260    /// Creates a ticket to read from the display fd.
261    ///
262    /// # Safety
263    ///
264    /// - display must be a valid pointer
265    /// - queue must be a valid pointer
266    /// - the queue must belong to the display
267    fn wl_display_prepare_read_queue(
268        display: *mut wl_display,
269        queue: *mut wl_event_queue,
270    ) -> c_int;
271
272    /// Creates a ticket to read from the display fd.
273    ///
274    /// # Safety
275    ///
276    /// - display must be a valid pointer
277    fn wl_display_prepare_read(
278        display: *mut wl_display,
279    ) -> c_int;
280
281    /// Consumes a ticket to read from the display fd without reading from the display fd.
282    ///
283    /// # Safety
284    ///
285    /// - display must be a valid pointer
286    /// - the caller must own a ticket
287    fn wl_display_cancel_read(display: *mut wl_display);
288
289    /// Consumes a ticket to read from the display fd and reads from the display fd.
290    ///
291    /// # Safety
292    ///
293    /// - display must be a valid pointer
294    /// - the caller must own a ticket
295    fn wl_display_read_events(display: *mut wl_display) -> c_int;
296
297    /// Returns the file descriptor of the display.
298    ///
299    /// # Safety
300    ///
301    /// - display must be a valid pointer
302    fn wl_display_get_fd(display: *mut wl_display) -> c_int;
303
304    /// Creates a new queue.
305    ///
306    /// # Safety
307    ///
308    /// - display must be a valid pointer
309    fn wl_display_create_queue(display: *mut wl_display) -> *mut wl_event_queue;
310
311    /// Returns the errno of the last error that occurred.
312    ///
313    /// # Safety
314    ///
315    /// - display must be a valid pointer
316    fn wl_display_get_error(display: *mut wl_display) -> c_int;
317}
318
319impl Libwayland {
320    /// Obtains a reference to `libwayland-client.so`.
321    #[inline]
322    pub fn open() -> io::Result<&'static Self> {
323        static LIB: LazyLock<Result<Libwayland, Mutex<Option<libloading::Error>>>> =
324            LazyLock::new(|| Libwayland::open_new().map_err(|e| Mutex::new(Some(e))));
325        #[cold]
326        fn map_error(e: &Mutex<Option<libloading::Error>>) -> io::Error {
327            match e.lock().take() {
328                Some(e) => io::Error::new(io::ErrorKind::NotFound, e),
329                None => io::Error::from(io::ErrorKind::NotFound),
330            }
331        }
332        match &*LIB {
333            Ok(l) => Ok(l),
334            Err(e) => Err(map_error(e)),
335        }
336    }
337
338    #[cold]
339    fn open_new() -> Result<Self, libloading::Error> {
340        // SAFETY: No way to verify this. We just have to hope that libwayland-client.so
341        //         is the libwayland-client.so that we've bound against.
342        let lib = unsafe { Library::new("libwayland-client.so.0")? };
343        // SAFETY: lib is libwayland-client.so.
344        let syms = unsafe { Symbols::load(&lib)? };
345        // SAFETY: lib is libwayland-client.so.
346        let syms_opt = unsafe { SymbolsOpt::load(&lib)? };
347        mem::forget(lib);
348        Ok(Libwayland { syms, syms_opt })
349    }
350
351    /// Creates a new queue.
352    ///
353    /// # Safety
354    ///
355    /// - display must be a valid pointer
356    /// - name must be null or a valid c string
357    pub(crate) unsafe fn wl_display_create_queue_with_name(
358        &self,
359        display: *mut wl_display,
360        name: *const c_char,
361    ) -> *mut wl_event_queue {
362        if let Some(f) = self.syms_opt.wl_display_create_queue_with_name {
363            // SAFETY: The requirements are forwarded to the caller of this function.
364            unsafe { f(display, name) }
365        } else {
366            // SAFETY: The requirements are forwarded to the caller of this function.
367            unsafe { self.wl_display_create_queue(display) }
368        }
369    }
370}
371
372mod polyfills {
373    use crate::Libwayland;
374    use crate::ffi::wl_display;
375    use crate::ffi::wl_event_queue;
376    use crate::ffi::wl_interface;
377    use crate::ffi::wl_proxy;
378    use std::ffi::c_void;
379
380    #[repr(C)]
381    struct real_wl_object {
382        _interface: *const wl_interface,
383        _implementation: *const c_void,
384        _id: u32,
385    }
386
387    #[repr(C)]
388    struct real_wl_proxy {
389        _object: real_wl_object,
390        display: *mut wl_display,
391        queue: *mut wl_event_queue,
392    }
393
394    impl Libwayland {
395        /// Get the queue of a proxy.
396        ///
397        /// # Safety
398        ///
399        /// - proxy must be a valid pointer
400        #[inline]
401        pub(crate) unsafe fn wl_proxy_get_queue(
402            &self,
403            proxy: *mut wl_proxy,
404        ) -> *mut wl_event_queue {
405            if let Some(f) = self.syms_opt.wl_proxy_get_queue {
406                // SAFETY: The requirements are forwarded to the caller of this function.
407                return unsafe { f(proxy) };
408            }
409            let proxy = proxy.cast::<real_wl_proxy>();
410            // SAFETY: We have a hard dependency on wl_proxy_marshal_array_flags which was
411            //         added in 2021. wl_proxy_get_queue was added in 2023. Between these
412            //         two dates, the layout of wl_proxy has always been as described above.
413            //         (Modulo trailing fields after the queue field.)
414            // NOTE: We cannot use this code for all versions of libwayland since the layout
415            //       might change in the future.
416            unsafe { (*proxy).queue }
417        }
418
419        /// Get the display of a proxy.
420        ///
421        /// # Safety
422        ///
423        /// - proxy must be a valid pointer
424        #[inline]
425        pub(crate) unsafe fn wl_proxy_get_display(&self, proxy: *mut wl_proxy) -> *mut wl_display {
426            if let Some(f) = self.syms_opt.wl_proxy_get_display {
427                // SAFETY: The requirements are forwarded to the caller of this function.
428                return unsafe { f(proxy) };
429            }
430            let proxy = proxy.cast::<real_wl_proxy>();
431            // SAFETY: We have a hard dependency on wl_proxy_marshal_array_flags which was
432            //         added in 2021. wl_proxy_get_display was added in 2023. Between these
433            //         two dates, the layout of wl_proxy has always been as described above.
434            //         (Modulo trailing fields after the queue field.)
435            // NOTE: We cannot use this code for all versions of libwayland since the layout
436            //       might change in the future.
437            unsafe { (*proxy).display }
438        }
439    }
440}