aarch32-rt-macros 0.2.0

Run-Time macros for aarch32-rt
Documentation
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
//! Macros for the aarch32-rt library
//!
//! Provides `#[entry]`, `#[exception(...)]` and `#[irq]` attribute macros.
//!
//! Do not use this crate directly.
//!
//! Based on <https://github.com/rust-embedded/cortex-m/tree/c-m-rt-v0.7.5/cortex-m-rt/macros>.

extern crate proc_macro;

use proc_macro::{TokenStream, TokenTree};
use proc_macro2::Span;
use quote::quote;
use syn::{
    parse, parse_macro_input, spanned::Spanned, AttrStyle, Attribute, Ident, ItemFn, ReturnType,
    Type, Visibility,
};

/// Creates an `unsafe` program entry point (i.e. a `kmain` function).
///
/// It's `unsafe` because you are not supposed to call it - it should only be
/// called from the start-up code once initialisation is complete.
///
/// When placed on a function like:
///
/// ```rust ignore
/// #[entry]
/// fn foo() -> ! {
///     panic!("On no")
/// }
/// ```
///
/// You get something like:
///
/// ```rust
/// #[doc(hidden)]
/// #[export_name = "kmain"]
/// pub unsafe extern "C" fn __aarch32_rt_kmain() -> ! {
///     foo()
/// }
///
/// fn foo() -> ! {
///     panic!("On no")
/// }
/// ```
///
/// The symbol `kmain` is what the assembly code in aarch32-rt start-up code
/// will jump to, and the `extern "C"` makes it sound to call from assembly.
#[proc_macro_attribute]
pub fn entry(args: TokenStream, input: TokenStream) -> TokenStream {
    let f = parse_macro_input!(input as ItemFn);

    // check the function signature.
    //
    // it should be `fn foo() -> !` or `unsafe fn foo() -> !`
    let valid_signature = f.sig.constness.is_none()
        && f.vis == Visibility::Inherited
        && f.sig.abi.is_none()
        && f.sig.inputs.is_empty()
        && f.sig.generics.params.is_empty()
        && f.sig.generics.where_clause.is_none()
        && f.sig.variadic.is_none()
        && match f.sig.output {
            ReturnType::Default => false,
            ReturnType::Type(_, ref ty) => matches!(**ty, Type::Never(_)),
        };

    if !valid_signature {
        return parse::Error::new(
            f.span(),
            "`#[entry]` function must have signature `[unsafe] fn() -> !`",
        )
        .to_compile_error()
        .into();
    }

    if !args.is_empty() {
        return parse::Error::new(Span::call_site(), "This attribute accepts no arguments")
            .to_compile_error()
            .into();
    }

    // This is the name that other Rust code needs to use to call this function -
    // we make it long an complicated because no-one is supposed to call this function.
    // The `__aarch32_rt` prefix re-inforces this.
    //
    // However, this is not the symbol that the linker sees - we override that to be
    // `kmain` because that's what the start-up assembly code is looking for. As you
    // cannot call that symbol without using `extern "C" { }`, it should be sufficiently
    // well hidden.
    let tramp_ident = Ident::new("__aarch32_rt_kmain", Span::call_site());
    let block = f.block;

    if let Err(error) = check_attr_whitelist(&f.attrs, VectorKind::Entry) {
        return error;
    }

    let (ref cfgs, ref attrs) = extract_cfgs(f.attrs.clone());

    quote!(
        #(#cfgs)*
        #(#attrs)*
        #[doc(hidden)]
        #[export_name = "kmain"]
        pub unsafe extern "C" fn #tramp_ident() -> ! {
            #block
        }
    )
    .into()
}

/// The set of exceptions we can handle.
#[derive(Debug, PartialEq)]
enum Exception {
    Undefined,
    SupervisorCall,
    PrefetchAbort,
    DataAbort,
    Irq,
}

impl std::fmt::Display for Exception {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Exception::Undefined => write!(f, "Undefined"),
            Exception::SupervisorCall => write!(f, "SupervisorCall"),
            Exception::PrefetchAbort => write!(f, "PrefetchAbort"),
            Exception::DataAbort => write!(f, "DataAbort"),
            Exception::Irq => write!(f, "Irq"),
        }
    }
}

/// Creates an `unsafe` exception handler.
///
/// It's `unsafe` because you are not supposed to call it - it should only be
/// called from assembly routines registered in the interrupt vector table.
///
/// When placed on a function like:
///
/// ```rust ignore
/// #[exception(Undefined)]
/// fn foo(addr: usize) -> ! {
///     panic!("On no")
/// }
/// ```
///
/// You get something like:
///
/// ```rust
/// #[doc(hidden)]
/// #[export_name = "_undefined_handler"]
/// pub unsafe extern "C" fn __aarch32_rt_undefined_handler(addr: usize) -> ! {
///     foo(addr)
/// }
///
/// fn foo(addr: usize) -> ! {
///     panic!("On no")
/// }
/// ```
///
/// The supported arguments are:
///
/// * Undefined (creates `_undefined_handler`)
/// * SupervisorCall (creates `_svc_handler`)
/// * PrefetchAbort (creates `_prefetch_abort_handler`)
/// * DataAbort (creates `_data_abort_handler`)
/// * Irq (creates `_irq_handler`) - although people should prefer `#[irq]`.
#[proc_macro_attribute]
pub fn exception(args: TokenStream, input: TokenStream) -> TokenStream {
    handle_vector(args, input, VectorKind::Exception)
}

/// Creates an `unsafe` interrupt handler.
///
/// It's `unsafe` because you are not supposed to call it - it should only be
/// called from assembly routines registered in the interrupt vector table.
///
/// When placed on a function like:
///
/// ```rust ignore
/// #[irq]
/// fn foo(addr: usize) -> ! {
///     panic!("On no")
/// }
/// ```
///
/// You get something like:
///
/// ```rust
/// #[doc(hidden)]
/// #[export_name = "_irq_handler"]
/// pub unsafe extern "C" fn __aarch32_rt_irq_handler(addr: usize) -> ! {
///     foo(addr)
/// }
///
/// fn foo(addr: usize) -> ! {
///     panic!("On no")
/// }
/// ```
///
/// This is preferred over `#[exception(Irq)` because most people
/// probably won't consider interrupts to be a form of exception.
#[proc_macro_attribute]
pub fn irq(args: TokenStream, input: TokenStream) -> TokenStream {
    handle_vector(args, input, VectorKind::Interrupt)
}

/// Note if we got `#[entry]`, `#[exception(...)]` or `#[irq]`
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
enum VectorKind {
    /// Corresponds to `#[entry]`
    Entry,
    /// Corresponds to `#[exception(...)]`
    Exception,
    /// Corresponds to `#[irq]`
    Interrupt,
}

/// A common routine for handling exception or interrupt functions
fn handle_vector(args: TokenStream, input: TokenStream, kind: VectorKind) -> TokenStream {
    let f = parse_macro_input!(input as ItemFn);

    if let Err(error) = check_attr_whitelist(&f.attrs, kind) {
        return error;
    }

    let returns_never = match f.sig.output {
        ReturnType::Type(_, ref ty) => matches!(**ty, Type::Never(_)),
        _ => false,
    };

    let exception = match kind {
        VectorKind::Entry => {
            panic!("Don't handle #[entry] with `handle_vector`!");
        }
        VectorKind::Exception => {
            let mut args_iter = args.into_iter();
            let Some(TokenTree::Ident(exception_name)) = args_iter.next() else {
                return parse::Error::new(
                    Span::call_site(),
                    "This attribute requires the name of the exception as the first argument",
                )
                .to_compile_error()
                .into();
            };
            if args_iter.next().is_some() {
                return parse::Error::new(
                    Span::call_site(),
                    "This attribute accepts only one argument",
                )
                .to_compile_error()
                .into();
            }
            match exception_name.to_string().as_str() {
                "Undefined" => {
                    if !returns_never && f.sig.unsafety.is_none() {
                        return parse::Error::new(
                            exception_name.span().into(),
                            "Undefined handlers that don't return ! must be unsafe",
                        )
                        .to_compile_error()
                        .into();
                    }
                    Exception::Undefined
                }
                "SupervisorCall" => Exception::SupervisorCall,
                "PrefetchAbort" => {
                    if !returns_never && f.sig.unsafety.is_none() {
                        return parse::Error::new(
                            exception_name.span().into(),
                            "PrefetchAbort handlers that don't return ! must be unsafe",
                        )
                        .to_compile_error()
                        .into();
                    }
                    Exception::PrefetchAbort
                }
                "DataAbort" => {
                    if !returns_never && f.sig.unsafety.is_none() {
                        return parse::Error::new(
                            exception_name.span().into(),
                            "DataAbort handlers that don't return ! must be unsafe",
                        )
                        .to_compile_error()
                        .into();
                    }
                    Exception::DataAbort
                }
                "Irq" => Exception::Irq,
                _ => {
                    return parse::Error::new(
                        exception_name.span().into(),
                        "This is not a valid exception name",
                    )
                    .to_compile_error()
                    .into();
                }
            }
        }
        VectorKind::Interrupt => Exception::Irq,
    };

    let block = f.block;
    let (ref cfgs, ref attrs) = extract_cfgs(f.attrs.clone());

    let handler = match exception {
        // extern "C" fn _undefined_handler(addr: usize) -> !;
        // unsafe extern "C" fn _undefined_handler(addr: usize) -> usize;
        Exception::Undefined => {
            let tramp_ident = Ident::new("__aarch32_rt_undefined_handler", Span::call_site());
            if returns_never {
                quote!(
                    #(#cfgs)*
                    #(#attrs)*
                    #[doc(hidden)]
                    #[export_name = "_undefined_handler"]
                    pub unsafe extern "C" fn #tramp_ident(addr: usize) -> ! {
                        #block
                    }

                )
            } else {
                quote!(
                    #(#cfgs)*
                    #(#attrs)*
                    #[doc(hidden)]
                    #[export_name = "_undefined_handler"]
                    pub unsafe extern "C" fn #tramp_ident(addr: usize) -> usize {
                        #block
                    }

                )
            }
        }
        // extern "C" fn _prefetch_abort_handler(addr: usize) -> !;
        // unsafe extern "C" fn _prefetch_abort_handler(addr: usize) -> usize;
        Exception::PrefetchAbort => {
            let tramp_ident = Ident::new("__aarch32_rt_prefetch_abort_handler", Span::call_site());
            if returns_never {
                quote!(
                    #(#cfgs)*
                    #(#attrs)*
                    #[doc(hidden)]
                    #[export_name = "_prefetch_abort_handler"]
                    pub unsafe extern "C" fn #tramp_ident(addr: usize) -> ! {
                        #block
                    }
                )
            } else {
                quote!(
                    #(#cfgs)*
                    #(#attrs)*
                    #[doc(hidden)]
                    #[export_name = "_prefetch_abort_handler"]
                    pub unsafe extern "C" fn #tramp_ident(addr: usize) -> usize {
                        #block
                    }

                )
            }
        }
        // extern "C" fn _data_abort_handler(addr: usize) -> !;
        // unsafe extern "C" fn _data_abort_handler(addr: usize) -> usize;
        Exception::DataAbort => {
            let tramp_ident = Ident::new("__aarch32_rt_data_abort_handler", Span::call_site());
            if returns_never {
                quote!(
                    #(#cfgs)*
                    #(#attrs)*
                    #[doc(hidden)]
                    #[export_name = "_data_abort_handler"]
                    pub unsafe extern "C" fn #tramp_ident(addr: usize) -> ! {
                        #block
                    }

                )
            } else {
                quote!(
                    #(#cfgs)*
                    #(#attrs)*
                    #[doc(hidden)]
                    #[export_name = "_data_abort_handler"]
                    pub unsafe extern "C" fn #tramp_ident(addr: usize) -> usize {
                        #block
                    }
                )
            }
        }
        // extern "C" fn _svc_handler(addr: usize);
        Exception::SupervisorCall => {
            let tramp_ident = Ident::new("__aarch32_rt_svc_handler", Span::call_site());
            quote!(
                #(#cfgs)*
                #(#attrs)*
                #[doc(hidden)]
                #[export_name = "_svc_handler"]
                pub unsafe extern "C" fn #tramp_ident(arg: u32) {
                    #block
                }
            )
        }
        // extern "C" fn _irq_handler(addr: usize);
        Exception::Irq => {
            let tramp_ident = Ident::new("__aarch32_rt_irq_handler", Span::call_site());
            quote!(
                #(#cfgs)*
                #(#attrs)*
                #[doc(hidden)]
                #[export_name = "_irq_handler"]
                pub unsafe extern "C" fn #tramp_ident() {
                    #block
                }
            )
        }
    };

    quote!(
        #handler
    )
    .into()
}

/// Given a list of attributes, split them into `cfg` and non-`cfg`.
///
/// Returns `(cfgs, non_cfgs)`.
fn extract_cfgs(attrs: Vec<Attribute>) -> (Vec<Attribute>, Vec<Attribute>) {
    let mut cfgs = vec![];
    let mut not_cfgs = vec![];

    for attr in attrs {
        if eq(&attr, "cfg") {
            cfgs.push(attr);
        } else {
            not_cfgs.push(attr);
        }
    }

    (cfgs, not_cfgs)
}

/// Check whether any disallowed attributes have been applied to our entry/exception function.
fn check_attr_whitelist(attrs: &[Attribute], caller: VectorKind) -> Result<(), TokenStream> {
    let whitelist = &[
        "doc",
        "link_section",
        "cfg",
        "allow",
        "warn",
        "deny",
        "forbid",
        "cold",
        "naked",
        "expect",
    ];

    'o: for attr in attrs {
        for val in whitelist {
            if eq(attr, val) {
                continue 'o;
            }
        }

        let err_str = match caller {
            VectorKind::Entry => "this attribute is not allowed on an aarch32-rt entry point",
            VectorKind::Exception => {
                "this attribute is not allowed on an exception handler controlled by aarch32-rt"
            }
            VectorKind::Interrupt => {
                "this attribute is not allowed on an interrupt handler controlled by aarch32-rt"
            }
        };

        return Err(parse::Error::new(attr.span(), err_str)
            .to_compile_error()
            .into());
    }

    Ok(())
}

/// Returns `true` if `attr.path` matches `name`
fn eq(attr: &Attribute, name: &str) -> bool {
    attr.style == AttrStyle::Outer && attr.path().is_ident(name)
}