Skip to main content

dlopen_note/
lib.rs

1//! This crate provides the [`dlopen_note`] proc macro that can be used to attach dlopen
2//! metadata to an ELF binary.
3//!
4//! > Using dlopen() to load optional dependencies brings several advantages:
5//! > programs can gracefully downgrade a feature when a library is not available,
6//! > and the shared library is only loaded into the process (and its ELF
7//! > constructors are run) only when the requested feature is actually used. But
8//! > it also has some drawbacks, and the main one is that it is harder to track a
9//! > program’s dependencies, since unlike build-time dynamic linking there will
10//! > not be a mention in the ELF metadata. This specification aims to solve this
11//! > problem by providing a standardized specification for a custom ELF note that
12//! > can be used to list dlopen() dependencies.
13//!
14//! See <https://uapi-group.org/specifications/specs/elf_dlopen_metadata>.
15
16use {
17    proc_macro2::{Literal, Span},
18    quote::quote,
19    syn::{
20        Error, Ident, LitStr, Token, bracketed,
21        parse::{Parse, ParseStream},
22        parse_macro_input,
23    },
24};
25
26/// Creates a `.note.dlopen` section.
27///
28/// # Example
29///
30/// ```rust
31/// # use dlopen_note::dlopen_note;
32/// dlopen_note! {
33///     soname: ["libvulkan.so.1"],
34///     feature: "vulkan",
35///     description: "required for the vulkan renderer",
36///     priority: "recommended",
37/// }
38/// ```
39///
40/// # Syntax
41///
42/// The fields and their meaning are specified at [uapi-group.org].
43///
44/// In short:
45///
46/// - The supported fields are the ones that appear in the example above.
47/// - The `soname` field is required and must have at least one element.
48/// - The strings must not contain any control characters.
49/// - The `priority` must be `required`, `recommended`, or `suggested`.
50///
51/// [uapi-group.org]: https://uapi-group.org/specifications/specs/elf_dlopen_metadata
52#[proc_macro]
53pub fn dlopen_note(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
54    let input: Input = parse_macro_input!(input as Input);
55    let mut json = vec![];
56    json.extend_from_slice(br#"[{"soname":["#);
57    for (idx, name) in input.soname.iter().enumerate() {
58        if idx > 0 {
59            json.push(b',');
60        }
61        json.push(b'"');
62        json.extend_from_slice(&name.value);
63        json.push(b'"');
64    }
65    json.push(b']');
66    for (name, field) in [
67        ("feature", &input.feature),
68        ("description", &input.description),
69        ("priority", &input.priority),
70    ] {
71        if let Some(v) = field {
72            json.extend_from_slice(br#",""#);
73            json.extend_from_slice(name.as_ref());
74            json.extend_from_slice(br#"":""#);
75            json.extend_from_slice(&v.value);
76            json.extend_from_slice(br#"""#);
77        }
78    }
79    json.extend_from_slice(br#"}]"#);
80    json.push(0);
81    let len = Literal::usize_unsuffixed(json.len());
82    while json.len() % 4 != 0 {
83        json.push(0);
84    }
85    let size = Literal::usize_unsuffixed(json.len());
86    let json = Literal::byte_string(&json);
87    let out = quote! {
88        const _: () = {
89            #[repr(C)]
90            struct Note {
91                namesz: u32,
92                descsz: u32,
93                r#type: u32,
94                name: [u8; 4],
95                desc: [u8; #size],
96            }
97            #[used]
98            #[unsafe(link_section = ".note.dlopen")]
99            static DLOPEN_NOTE: Note = Note {
100                namesz: 4,
101                descsz: #len,
102                r#type: 0x407c0c0a,
103                name: *b"FDO\0",
104                desc: *#json,
105            };
106        };
107    };
108    out.into()
109}
110
111#[derive(Debug)]
112struct Input {
113    soname: Vec<JsonString>,
114    feature: Option<JsonString>,
115    description: Option<JsonString>,
116    priority: Option<JsonString>,
117}
118
119#[derive(Debug)]
120struct JsonString {
121    span: Span,
122    value: Vec<u8>,
123}
124
125impl Parse for Input {
126    fn parse(input: ParseStream) -> syn::Result<Self> {
127        let mut soname = None;
128        let mut feature = None;
129        let mut description = None;
130        let mut priority = None;
131        fn set<T>(key: Ident, option: &mut Option<T>, value: T) -> syn::Result<()> {
132            if option.replace(value).is_some() {
133                return Err(Error::new(key.span(), "duplicate key"));
134            }
135            Ok(())
136        }
137        loop {
138            let ident: Ident = input.parse()?;
139            input.parse::<Token![:]>()?;
140            if ident == "soname" {
141                let content;
142                bracketed!(content in input);
143                let vec: Vec<_> = content
144                    .parse_terminated(JsonString::parse, Token![,])?
145                    .into_iter()
146                    .collect();
147                if vec.is_empty() {
148                    return Err(Error::new(ident.span(), "at least one soname is required"));
149                }
150                set(ident, &mut soname, vec)?;
151            } else if ident == "feature" {
152                set(ident, &mut feature, input.parse()?)?;
153            } else if ident == "description" {
154                set(ident, &mut description, input.parse()?)?;
155            } else if ident == "priority" {
156                set(ident, &mut priority, input.parse()?)?;
157            } else {
158                return Err(Error::new(ident.span(), "unknown key"));
159            }
160            if input.parse::<Option<Token![,]>>()?.is_none() {
161                break;
162            }
163            if input.is_empty() {
164                break;
165            }
166        }
167        if !input.is_empty() {
168            return Err(input.error("expected a comma"));
169        }
170        let Some(soname) = soname else {
171            return Err(input.error("missing soname field"));
172        };
173        let input = Self {
174            soname,
175            feature,
176            description,
177            priority,
178        };
179        if let Some(v) = &input.priority
180            && !matches!(&*v.value, b"required" | b"recommended" | b"suggested")
181        {
182            return Err(Error::new(v.span, "unknown priority"));
183        }
184        Ok(input)
185    }
186}
187
188impl Parse for JsonString {
189    fn parse(input: ParseStream) -> syn::Result<Self> {
190        let lit: LitStr = input.parse()?;
191        let raw = lit.value();
192        let span = lit.span();
193        let mut cooked = String::with_capacity(raw.len());
194        for c in raw.chars() {
195            if c.is_control() {
196                return Err(Error::new(
197                    span,
198                    "strings cannot contain control characters",
199                ));
200            }
201            if c == '\\' || c == '"' {
202                cooked.push('\\');
203            }
204            cooked.push(c);
205        }
206        Ok(JsonString {
207            span,
208            value: cooked.into_bytes(),
209        })
210    }
211}