Skip to main content

glean_sym/
lib.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5#[cfg(feature = "active")]
6use std::sync::LazyLock;
7
8#[doc(hidden)]
9pub extern crate serde as __serde;
10
11#[doc(hidden)]
12pub mod __serde_helper {
13    /// Deserialize value to a `Vec<T>`.
14    ///
15    /// If the value was `null`  return an empty vector.
16    pub fn vec_null<'de, D: serde::Deserializer<'de>, T: serde::Deserialize<'de>>(
17        d: D,
18    ) -> Result<Vec<T>, D::Error> {
19        let res: Option<Vec<T>> = serde::Deserialize::deserialize(d)?;
20        Ok(res.unwrap_or_default())
21    }
22}
23
24// Re-export types that are used by the glean_parser-generated code.
25#[doc(hidden)]
26pub mod __export {
27    pub use once_cell::sync::Lazy;
28}
29
30#[cfg(feature = "active")]
31const FFI_CONTRACT_VERSION: u32 = include!("contract_version.txt");
32
33// Based on https://searchfox.org/firefox-main/rev/6193f8fd1172486e3ce941b8de251b9d1a4dfa0b/toolkit/crashreporter/client/app/src/net/libcurl.rs#84
34#[cfg(feature = "active")]
35macro_rules! library_binding {
36    ( $localname:ident members[$($members:tt)*] load[$($load:tt)*] fn $name:ident $args:tt $( -> $ret:ty )? ; $($rest:tt)* ) => {
37        library_binding! {
38            $localname
39            members[
40                $($members)*
41                pub(crate) $name: libloading::Symbol<'static, unsafe extern "C" fn $args $(->$ret)?>,
42            ]
43            load[
44                $($load)*
45                $name: unsafe {
46                    let symbol = $localname.get::<unsafe extern "C" fn $args $(->$ret)?>(stringify!($name).as_bytes())
47                    .map_err(|e| std::io::Error::new(std::io::ErrorKind::NotFound, e))?;
48                    // All symbols refer to library, so `'static` lifetimes are safe (`library`
49                    // will outlive them).
50                    std::mem::transmute::<_, libloading::Symbol<'static, _>>(symbol)
51                },
52            ]
53            $($rest)*
54        }
55    };
56    ( $localname:ident members[$($members:tt)*] load[$($load:tt)*] ) => {
57        pub struct GleanSym {
58            $($members)*
59            _library: libloading::Library,
60        }
61
62        impl GleanSym {
63            #[cfg(all(unix, not(target_os = "ios")))]
64            pub fn load() -> std::io::Result<Self> {
65                let name = libloading::library_filename("xul");
66                let library = match unsafe { libloading::Library::new(name) } {
67                        Ok(lib) => Some(lib),
68                        Err(_e) => None,
69                };
70                let $localname = library.ok_or_else(|| {
71                    std::io::Error::new(std::io::ErrorKind::NotFound, "failed to find glean library")
72                })?;
73
74                let handle = GleanSym { $($load)* _library: $localname };
75                handle.check()?;
76                Ok(handle)
77            }
78
79            #[cfg(target_os = "ios")]
80            pub fn load() -> std::io::Result<Self> {
81                // On iOS we compile it all together and can look up symbols without loading a library
82                let $localname: libloading::Library = libloading::os::unix::Library::this().into();
83                let handle = GleanSym { $($load)* _library: $localname };
84                handle.check()?;
85                Ok(handle)
86            }
87
88            #[cfg(not(unix))]
89            pub fn load() -> std::io::Result<Self> {
90                compile_error!("This crate is not implemented for Windows");
91            }
92
93            fn check(&self) -> std::io::Result<()> {
94                let ffi_contract_version = unsafe { (self.ffi_glean_core_uniffi_contract_version)() };
95                if crate::FFI_CONTRACT_VERSION == ffi_contract_version {
96                    Ok(())
97                } else {
98                    Err(std::io::Error::other("contract version mismatch"))
99                }
100            }
101        }
102    };
103    ( $($rest:tt)* ) => {
104        library_binding! {
105            library members[] load[] $($rest)*
106        }
107    }
108}
109
110pub mod metrics;
111pub mod types;
112#[cfg(feature = "active")]
113mod util;
114
115pub use types::PingType;
116
117#[cfg(feature = "active")]
118static GLEAN: LazyLock<metrics::GleanSym> = LazyLock::new(|| metrics::GleanSym::load().unwrap());
119
120// This boilerplate is usually generated by `uniffi::setup_scaffolding!()`
121// along with all the extra FFI functions, like wrappers around Rust buffer allocation, async handling, etc.
122// We don't want to export those, so we do only the minimal part to support what `glean-sym` calls when used in other
123// crates.
124
125/// The crate-specific tag to implement traits.
126#[doc(hidden)]
127pub struct UniFfiTag;
128
129/// The namespace glean-sym FFI items are placed in.
130/// Required by UniFFI to match up items.
131#[allow(clippy::large_const_arrays)] // this is moved into the `static` below, we can't make it a static itself.
132#[cfg(feature = "active")]
133const UNIFFI_META_CONST_NAMESPACE_GLEAN_SYM: ::uniffi::MetadataBuffer =
134    ::uniffi::MetadataBuffer::from_code(::uniffi::metadata::codes::NAMESPACE)
135        .concat_str("glean_sym")
136        .concat_str("glean_sym");
137#[doc(hidden)]
138#[unsafe(no_mangle)]
139#[cfg(feature = "active")]
140pub static UNIFFI_META_NAMESPACE_GLEAN_SYM: [::std::primitive::u8;
141    UNIFFI_META_CONST_NAMESPACE_GLEAN_SYM.size] =
142    UNIFFI_META_CONST_NAMESPACE_GLEAN_SYM.into_array();