interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / vendor / uefi-macros / src / lib.rs

232 lines · 7326 bytes Raw Blame History
1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3//! Procedural macros for the `uefi` crate.
4
5#![recursion_limit = "128"]
6#![deny(
7 clippy::all,
8 clippy::absolute_paths,
9 clippy::missing_const_for_fn,
10 clippy::must_use_candidate,
11 clippy::missing_safety_doc,
12 clippy::ptr_as_ptr,
13 clippy::ref_as_ptr,
14 clippy::undocumented_unsafe_blocks,
15 clippy::use_self,
16 missing_debug_implementations,
17 missing_docs,
18 unsafe_op_in_unsafe_fn,
19 unused
20)]
21
22use proc_macro::TokenStream;
23
24use proc_macro2::TokenStream as TokenStream2;
25use quote::{TokenStreamExt, quote, quote_spanned};
26use syn::spanned::Spanned;
27use syn::{
28 Error, Expr, ExprLit, ExprPath, ItemFn, ItemStruct, Lit, Visibility, parse_macro_input,
29 parse_quote, parse_quote_spanned,
30};
31
32macro_rules! err {
33 ($span:expr, $message:expr $(,)?) => {
34 Error::new($span.span(), $message).to_compile_error()
35 };
36}
37
38/// Attribute macro for marking structs as UEFI protocols.
39///
40/// The macro can only be applied to a struct, and takes one argument, either a
41/// GUID string or the path to a `Guid` constant.
42///
43/// The macro implements the [`Protocol`] trait and the `unsafe` [`Identify`]
44/// trait for the struct. See the [`Protocol`] trait for details of how it is
45/// used.
46///
47/// # Safety
48///
49/// The caller must ensure that the correct GUID is attached to the
50/// type. An incorrect GUID could lead to invalid casts and other
51/// unsound behavior.
52///
53/// # Example
54///
55/// ```
56/// use uefi::{Guid, Identify, guid};
57/// use uefi::proto::unsafe_protocol;
58///
59/// #[unsafe_protocol("12345678-9abc-def0-1234-56789abcdef0")]
60/// struct ExampleProtocol1 {}
61///
62/// const PROTO_GUID: Guid = guid!("12345678-9abc-def0-1234-56789abcdef0");
63/// #[unsafe_protocol(PROTO_GUID)]
64/// struct ExampleProtocol2 {}
65///
66/// assert_eq!(ExampleProtocol1::GUID, PROTO_GUID);
67/// assert_eq!(ExampleProtocol2::GUID, PROTO_GUID);
68/// ```
69///
70/// [`Identify`]: https://docs.rs/uefi/latest/uefi/data_types/trait.Identify.html
71/// [`Protocol`]: https://docs.rs/uefi/latest/uefi/proto/trait.Protocol.html
72/// [send-and-sync]: https://doc.rust-lang.org/nomicon/send-and-sync.html
73#[proc_macro_attribute]
74pub fn unsafe_protocol(args: TokenStream, input: TokenStream) -> TokenStream {
75 let expr = parse_macro_input!(args as Expr);
76
77 let guid_val = match expr {
78 Expr::Lit(ExprLit {
79 lit: Lit::Str(lit), ..
80 }) => {
81 quote!(::uefi::guid!(#lit))
82 }
83 Expr::Path(ExprPath { path, .. }) => quote!(#path),
84 _ => err!(
85 expr,
86 "macro input must be either a string literal or path to a constant"
87 ),
88 };
89
90 let item_struct = parse_macro_input!(input as ItemStruct);
91
92 let ident = &item_struct.ident;
93 let (impl_generics, ty_generics, where_clause) = item_struct.generics.split_for_impl();
94
95 quote! {
96 #item_struct
97
98 unsafe impl #impl_generics ::uefi::Identify for #ident #ty_generics #where_clause {
99 const GUID: ::uefi::Guid = #guid_val;
100 }
101
102 impl #impl_generics ::uefi::proto::Protocol for #ident #ty_generics #where_clause {}
103 }
104 .into()
105}
106
107/// Custom attribute for a UEFI executable entry point.
108///
109/// This attribute modifies a function to mark it as the entry point for
110/// a UEFI executable. The function:
111/// * Must return [`Status`].
112/// * Must have zero parameters.
113/// * Can optionally be `unsafe`.
114///
115/// The global system table pointer and global image handle will be set
116/// automatically.
117///
118/// # Examples
119///
120/// ```no_run
121/// #![no_main]
122///
123/// use uefi::prelude::*;
124///
125/// #[entry]
126/// fn main() -> Status {
127/// Status::SUCCESS
128/// }
129/// ```
130///
131/// [`Status`]: https://docs.rs/uefi/latest/uefi/struct.Status.html
132#[proc_macro_attribute]
133pub fn entry(args: TokenStream, input: TokenStream) -> TokenStream {
134 // This code is inspired by the approach in this embedded Rust crate:
135 // https://github.com/rust-embedded/cortex-m-rt/blob/965bf1e3291571e7e3b34834864117dc020fb391/macros/src/lib.rs#L85
136
137 let mut errors = TokenStream2::new();
138
139 if !args.is_empty() {
140 errors.append_all(err!(
141 TokenStream2::from(args),
142 "Entry attribute accepts no arguments"
143 ));
144 }
145
146 let mut f = parse_macro_input!(input as ItemFn);
147
148 if let Some(ref abi) = f.sig.abi {
149 errors.append_all(err!(abi, "Entry function must have no ABI modifier"));
150 }
151 if let Some(asyncness) = f.sig.asyncness {
152 errors.append_all(err!(asyncness, "Entry function should not be async"));
153 }
154 if let Some(constness) = f.sig.constness {
155 errors.append_all(err!(constness, "Entry function should not be const"));
156 }
157 if !f.sig.generics.params.is_empty() {
158 errors.append_all(err!(
159 f.sig.generics.params,
160 "Entry function should not be generic"
161 ));
162 }
163 if !f.sig.inputs.is_empty() {
164 errors.append_all(err!(f.sig.inputs, "Entry function must have no arguments"));
165 }
166
167 // Show most errors all at once instead of one by one.
168 if !errors.is_empty() {
169 return errors.into();
170 }
171
172 let signature_span = f.sig.span();
173
174 // Fill in the image handle and system table arguments automatically.
175 let image_handle_ident = quote!(internal_image_handle);
176 let system_table_ident = quote!(internal_system_table);
177 f.sig.inputs = parse_quote_spanned!(
178 signature_span=>
179 #image_handle_ident: ::uefi::Handle,
180 #system_table_ident: *const ::core::ffi::c_void,
181 );
182
183 // Insert code at the beginning of the entry function to set the global
184 // image handle and system table pointer.
185 f.block.stmts.insert(
186 0,
187 parse_quote! {
188 unsafe {
189 ::uefi::boot::set_image_handle(#image_handle_ident);
190 ::uefi::table::set_system_table(#system_table_ident.cast());
191 }
192 },
193 );
194
195 // Set the required ABI.
196 f.sig.abi = Some(parse_quote_spanned!(signature_span=> extern "efiapi"));
197
198 // Strip any visibility modifiers.
199 f.vis = Visibility::Inherited;
200
201 let safety = &f.sig.safety;
202 let fn_ident = &f.sig.ident;
203 let fn_output = &f.sig.output;
204
205 // Get the expected argument types for the main function.
206 let expected_args = quote!(::uefi::Handle, *const core::ffi::c_void);
207
208 let fn_type_check = quote_spanned! {signature_span=>
209 // Cast from the function type to a function pointer with the same
210 // signature first, then try to assign that to an unnamed constant with
211 // the desired function pointer type.
212 //
213 // The cast is used to avoid an "expected fn pointer, found fn item"
214 // error if the signature is wrong, since that's not what we are
215 // interested in here. Instead we want to tell the user what
216 // specifically in the function signature is incorrect.
217 const _:
218 // The expected fn pointer type.
219 #safety extern "efiapi" fn(#expected_args) -> ::uefi::Status =
220 // Cast from a fn item to a function pointer.
221 #fn_ident as #safety extern "efiapi" fn(#expected_args) #fn_output;
222 };
223
224 let result = quote! {
225 #fn_type_check
226
227 #[unsafe(export_name = "efi_main")]
228 #f
229
230 };
231 result.into()
232}