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
#![recursion_limit = "128"]
extern crate proc_macro;
use proc_macro::TokenStream;
use proc_macro2::{TokenStream as TokenStream2, TokenTree};
use quote::{quote, ToTokens, TokenStreamExt};
use syn::{
parse::{Parse, ParseStream},
parse_macro_input,
spanned::Spanned,
DeriveInput, Error, Generics, Ident, ItemFn, ItemType, LitStr, Visibility,
};
struct TypeDefinition {
ident: Ident,
generics: Generics,
}
impl Parse for TypeDefinition {
fn parse(input: ParseStream) -> syn::Result<Self> {
if let Ok(d) = DeriveInput::parse(input) {
Ok(Self {
ident: d.ident,
generics: d.generics,
})
} else if let Ok(t) = ItemType::parse(input) {
Ok(Self {
ident: t.ident,
generics: t.generics,
})
} else {
Err(input.error("Input is not an alias, enum, struct or union definition"))
}
}
}
macro_rules! err {
($span:expr, $message:expr $(,)?) => {
Error::new($span.span(), $message).to_compile_error()
};
($span:expr, $message:expr, $($args:expr),*) => {
Error::new($span.span(), format!($message, $($args),*)).to_compile_error()
};
}
#[proc_macro_attribute]
pub fn unsafe_guid(args: TokenStream, input: TokenStream) -> TokenStream {
let (time_low, time_mid, time_high_and_version, clock_seq_and_variant, node) =
match parse_guid(parse_macro_input!(args as LitStr)) {
Ok(data) => data,
Err(tokens) => return tokens.into(),
};
let mut result: TokenStream2 = input.clone().into();
let type_definition = parse_macro_input!(input as TypeDefinition);
let ident = &type_definition.ident;
let (impl_generics, ty_generics, where_clause) = type_definition.generics.split_for_impl();
result.append_all(quote! {
unsafe impl #impl_generics ::uefi::Identify for #ident #ty_generics #where_clause {
#[doc(hidden)]
const GUID: ::uefi::Guid = ::uefi::Guid::from_values(
#time_low,
#time_mid,
#time_high_and_version,
#clock_seq_and_variant,
#node,
);
}
});
result.into()
}
fn parse_guid(guid_lit: LitStr) -> Result<(u32, u16, u16, u16, u64), TokenStream2> {
let guid_str = guid_lit.value();
if guid_str.len() != 36 {
return Err(err!(
guid_lit,
"\"{}\" is not a canonical GUID string (expected 36 bytes, found {})",
guid_str,
guid_str.len()
));
}
let mut offset = 1; let mut guid_hex_iter = guid_str.split('-');
let mut next_guid_int = |len: usize| -> Result<u64, TokenStream2> {
let guid_hex_component = guid_hex_iter.next().unwrap();
let lit = match guid_lit.to_token_stream().into_iter().next().unwrap() {
TokenTree::Literal(lit) => lit,
_ => unreachable!(),
};
let span = lit
.subspan(offset..offset + guid_hex_component.len())
.unwrap_or_else(|| lit.span());
if guid_hex_component.len() != len * 2 {
return Err(err!(
span,
"GUID component \"{}\" is not a {}-bit hexadecimal string",
guid_hex_component,
len * 8
));
}
offset += guid_hex_component.len() + 1; u64::from_str_radix(guid_hex_component, 16).map_err(|_| {
err!(
span,
"GUID component \"{}\" is not a hexadecimal number",
guid_hex_component
)
})
};
Ok((
next_guid_int(4)? as u32,
next_guid_int(2)? as u16,
next_guid_int(2)? as u16,
next_guid_int(2)? as u16,
next_guid_int(6)?,
))
}
#[proc_macro_derive(Protocol)]
pub fn derive_protocol(item: TokenStream) -> TokenStream {
let item = parse_macro_input!(item as DeriveInput);
let ident = item.ident.clone();
let (impl_generics, ty_generics, where_clause) = item.generics.split_for_impl();
let result = quote! {
impl #impl_generics ::uefi::proto::Protocol for #ident #ty_generics #where_clause {}
impl #impl_generics !Send for #ident #ty_generics #where_clause {}
impl #impl_generics !Sync for #ident #ty_generics #where_clause {}
};
result.into()
}
#[proc_macro_attribute]
pub fn entry(args: TokenStream, input: TokenStream) -> TokenStream {
let mut errors = TokenStream2::new();
if !args.is_empty() {
errors.append_all(err!(
TokenStream2::from(args),
"Entry attribute accepts no arguments"
));
}
let mut f = parse_macro_input!(input as ItemFn);
if let Some(ref abi) = f.sig.abi {
errors.append_all(err!(abi, "Entry method must have no ABI modifier"));
}
if let Some(asyncness) = f.sig.asyncness {
errors.append_all(err!(asyncness, "Entry method should not be async"));
}
if let Some(constness) = f.sig.constness {
errors.append_all(err!(constness, "Entry method should not be const"));
}
if !f.sig.generics.params.is_empty() {
errors.append_all(err!(
f.sig.generics.params,
"Entry method should not be generic"
));
}
if !errors.is_empty() {
return errors.into();
}
let unsafety = f.sig.unsafety.take();
f.vis = Visibility::Inherited;
let ident = &f.sig.ident;
let result = quote! {
#[export_name = "efi_main"]
#unsafety extern "efiapi" #f
const _: #unsafety extern "efiapi" fn(::uefi::Handle, ::uefi::table::SystemTable<::uefi::table::Boot>) -> ::uefi::Status = #ident;
};
result.into()
}
#[proc_macro]
pub fn cstr8(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let input: LitStr = parse_macro_input!(input);
let input = input.value();
match input
.chars()
.map(u8::try_from)
.collect::<Result<Vec<u8>, _>>()
{
Ok(c) => {
quote!(unsafe { ::uefi::CStr8::from_bytes_with_nul_unchecked(&[ #(#c),* , 0 ]) }).into()
}
Err(_) => syn::Error::new_spanned(input, "invalid character in string")
.into_compile_error()
.into(),
}
}
#[proc_macro]
pub fn cstr16(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let input: LitStr = parse_macro_input!(input);
let input = input.value();
match input
.chars()
.map(|c| u16::try_from(c as u32))
.collect::<Result<Vec<u16>, _>>()
{
Ok(c) => {
quote!(unsafe { ::uefi::CStr16::from_u16_with_nul_unchecked(&[ #(#c),* , 0 ]) }).into()
}
Err(_) => syn::Error::new_spanned(input, "invalid character in string")
.into_compile_error()
.into(),
}
}