Skip to main content

optee_utee_macros/
lib.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18extern crate alloc;
19extern crate proc_macro;
20
21use proc_macro::TokenStream;
22use quote::quote;
23use syn::parse_macro_input;
24use syn::spanned::Spanned;
25
26/// Attribute to declare the entry point of creating TA.
27///
28/// # Examples
29///
30/// ``` ignore
31/// #[ta_create]
32/// fn ta_create() -> Result<()> { }
33/// ```
34#[proc_macro_attribute]
35pub fn ta_create(_args: TokenStream, input: TokenStream) -> TokenStream {
36    let f = parse_macro_input!(input as syn::ItemFn);
37    let f_sig = &f.sig;
38    let f_ident = &f_sig.ident;
39
40    // check the function signature
41    let valid_signature = f_sig.constness.is_none()
42        && matches!(f.vis, syn::Visibility::Inherited)
43        && f_sig.abi.is_none()
44        && f_sig.inputs.is_empty()
45        && f_sig.generics.where_clause.is_none()
46        && f_sig.variadic.is_none();
47
48    if !valid_signature {
49        return syn::parse::Error::new(
50            f.span(),
51            "`#[ta_crate]` function must have signature `fn() -> optee_utee::Result<()>`",
52        )
53        .to_compile_error()
54        .into();
55    }
56
57    quote!(
58        #[unsafe(no_mangle)]
59        pub extern "C" fn TA_CreateEntryPoint() -> optee_utee::raw::TEE_Result {
60            match #f_ident() {
61                Ok(_) => optee_utee::raw::TEE_SUCCESS,
62                Err(e) => e.raw_code()
63            }
64        }
65
66        #f
67    )
68    .into()
69}
70
71/// Attribute to declare the entry point of destroying TA.
72///
73/// # Examples
74///
75/// ``` ignore
76/// #[ta_destroy]
77/// fn ta_destroy() { }
78/// ```
79#[proc_macro_attribute]
80pub fn ta_destroy(_args: TokenStream, input: TokenStream) -> TokenStream {
81    let f = parse_macro_input!(input as syn::ItemFn);
82    let f_sig = &f.sig;
83    let f_ident = &f_sig.ident;
84
85    // check the function signature
86    let valid_signature = f_sig.constness.is_none()
87        && matches!(f.vis, syn::Visibility::Inherited)
88        && f_sig.abi.is_none()
89        && f_sig.inputs.is_empty()
90        && f_sig.generics.where_clause.is_none()
91        && f_sig.variadic.is_none()
92        && matches!(f_sig.output, syn::ReturnType::Default);
93
94    if !valid_signature {
95        return syn::parse::Error::new(
96            f.span(),
97            "`#[ta_destroy]` function must have signature `fn()`",
98        )
99        .to_compile_error()
100        .into();
101    }
102
103    quote!(
104        #[unsafe(no_mangle)]
105        pub extern "C" fn TA_DestroyEntryPoint() {
106            #f_ident()
107        }
108
109        #f
110    )
111    .into()
112}
113
114/// Attribute to declare the entry point of opening a session.
115///
116/// The `params` argument may be any type that implements
117/// `optee_utee::FromRawParameters` (`optee_utee::ParametersAny`, a 4-tuple
118/// of typed wrappers, `optee_utee::Parameters`, etc.)
119///
120/// A session context `&mut T` can be defined as an optional second parameter;
121/// `T` must implement `Default`.
122///
123/// # Examples
124///
125/// ```ignore
126/// // Old deprecated Parameters
127/// #[ta_open_session]
128/// fn open_session(params: &mut Parameters) -> Result<()> { }
129///
130/// // New typed parameters
131/// use optee_utee::prelude::*;
132/// #[ta_open_session]
133/// fn open_session(params: &mut (
134///     ParameterNone,
135///     ParameterMemrefInput<'_>,
136///     ParameterValueOutput<'_>,
137///     ParameterMemrefOutput<'_>,
138/// )) -> Result<()> { }
139/// // use ParametersAny and check types with match later.
140/// #[ta_open_session]
141/// fn open_session(
142///     cmd_id: u32,
143///     params: &mut ParametersAny,
144/// ) -> Result<()> { }
145///
146/// // With session context
147/// #[ta_open_session]
148/// fn open_session(
149///     params: &mut Parameters,
150///     sess_ctx: &mut T,
151/// ) -> Result<()> { }
152/// ```
153#[proc_macro_attribute]
154pub fn ta_open_session(_args: TokenStream, input: TokenStream) -> TokenStream {
155    let f = parse_macro_input!(input as syn::ItemFn);
156    let f_sig = &f.sig;
157    let f_ident = &f_sig.ident;
158
159    // check the function signature
160    let valid_signature = f_sig.constness.is_none()
161        && matches!(f.vis, syn::Visibility::Inherited)
162        && f_sig.abi.is_none()
163        && (f_sig.inputs.len() == 1 || f_sig.inputs.len() == 2)
164        && f_sig.generics.where_clause.is_none()
165        && f_sig.variadic.is_none();
166
167    if !valid_signature {
168        return syn::parse::Error::new(
169            f.span(),
170            "`#[ta_open_session]` function must have signature `fn(&mut P) -> Result<()>` or `fn(&mut P, &mut T) -> Result<()>`",
171        )
172        .to_compile_error()
173        .into();
174    }
175
176    match f_sig.inputs.len() {
177        1 => {
178            let tokens = quote!(
179                #[doc(hidden)]
180                trait __OpteeUteeSessionContext {
181                    type Context;
182                }
183                #[doc(hidden)]
184                struct __OpteeUteeSessionContextFromOpenSession;
185                impl __OpteeUteeSessionContext for __OpteeUteeSessionContextFromOpenSession {
186                    type Context = core::ffi::c_void;
187                }
188
189                #[unsafe(no_mangle)]
190                pub extern "C" fn TA_OpenSessionEntryPoint(
191                    param_types: optee_utee::RawParamTypes,
192                    params: &mut optee_utee::RawParams,
193                    _: *mut *mut core::ffi::c_void,
194                ) -> optee_utee::raw::TEE_Result {
195                    let mut parameters = match unsafe {
196                        optee_utee::FromRawParameters::from_raw(param_types, params)
197                    } {
198                        Ok(p) => p,
199                        Err(e) => return e.raw_code(),
200                    };
201                    match #f_ident(&mut parameters) {
202                        Ok(_) => optee_utee::raw::TEE_SUCCESS,
203                        Err(e) => e.raw_code()
204                    }
205                }
206
207                #f
208            );
209            tokens.into()
210        }
211
212        2 => {
213            let ctx_type = match extract_fn_arg_mut_ref_type(&f_sig.inputs[1]) {
214                Ok(v) => v,
215                Err(e) => return e.to_compile_error().into(),
216            };
217
218            quote!(
219                #[doc(hidden)]
220                trait __OpteeUteeSessionContext {
221                    type Context;
222                }
223                #[doc(hidden)]
224                struct __OpteeUteeSessionContextFromOpenSession;
225                impl __OpteeUteeSessionContext for __OpteeUteeSessionContextFromOpenSession {
226                    type Context = #ctx_type;
227                }
228
229                #[unsafe(no_mangle)]
230                pub unsafe extern "C" fn TA_OpenSessionEntryPoint(
231                    param_types: optee_utee::RawParamTypes,
232                    params: &mut optee_utee::RawParams,
233                    sess_ctx: *mut *mut core::ffi::c_void,
234                ) -> optee_utee::raw::TEE_Result {
235                    let mut parameters = match unsafe {
236                        optee_utee::FromRawParameters::from_raw(param_types, params)
237                    } {
238                        Ok(p) => p,
239                        Err(e) => return e.raw_code(),
240                    };
241                    let mut ctx: #ctx_type = Default::default();
242                    match #f_ident(&mut parameters, &mut ctx) {
243                        Ok(_) =>
244                        {
245                            *sess_ctx = alloc::boxed::Box::into_raw(alloc::boxed::Box::new(ctx)) as _;
246                            optee_utee::raw::TEE_SUCCESS
247                        }
248                        Err(e) => e.raw_code()
249                    }
250                }
251
252                #f
253            )
254            .into()
255        }
256        _ => unreachable!(),
257    }
258}
259
260/// Attribute to declare the entry point of closing a session. Session context
261/// raw pointer (`*mut T`) can be defined as an optional parameter.
262///
263/// # Examples
264///
265/// ``` ignore
266/// #[ta_close_session]
267/// fn close_session(sess_ctx: &mut T) { }
268///
269/// #[ta_close_session]
270/// fn close_session() { }
271/// ```
272#[proc_macro_attribute]
273pub fn ta_close_session(_args: TokenStream, input: TokenStream) -> TokenStream {
274    let f = parse_macro_input!(input as syn::ItemFn);
275    let f_sig = &f.sig;
276    let f_ident = &f_sig.ident;
277
278    // check the function signature
279    let valid_signature = f_sig.constness.is_none()
280        && matches!(f.vis, syn::Visibility::Inherited)
281        && f_sig.abi.is_none()
282        && (f_sig.inputs.is_empty() || f_sig.inputs.len() == 1)
283        && f_sig.generics.where_clause.is_none()
284        && f_sig.variadic.is_none()
285        && matches!(f_sig.output, syn::ReturnType::Default);
286
287    if !valid_signature {
288        return syn::parse::Error::new(
289            f.span(),
290            "`#[ta_close_session]` function must have signature `fn(&mut T)` or `fn()`",
291        )
292        .to_compile_error()
293        .into();
294    }
295
296    match f_sig.inputs.len() {
297        0 => quote!(
298            #[doc(hidden)]
299            #[allow(dead_code)]
300            fn __optee_utee_close_session_context_type_must_match_ta_open_session() {
301                fn session_context_type_must_match_ta_open_session<T>()
302                where
303                    T: __OpteeUteeSessionContext<Context = core::ffi::c_void>,
304                {}
305                session_context_type_must_match_ta_open_session::<
306                    __OpteeUteeSessionContextFromOpenSession,
307                >();
308            }
309
310            #[unsafe(no_mangle)]
311            pub extern "C" fn TA_CloseSessionEntryPoint(_: *mut core::ffi::c_void) {
312                #f_ident()
313            }
314
315            #f
316        )
317        .into(),
318        1 => {
319            let ctx_type = match extract_fn_arg_mut_ref_type(&f_sig.inputs[0]) {
320                Ok(v) => v,
321                Err(e) => return e.to_compile_error().into(),
322            };
323
324            quote!(
325                #[doc(hidden)]
326                #[allow(dead_code)]
327                fn __optee_utee_close_session_context_type_must_match_ta_open_session() {
328                    fn session_context_type_must_match_ta_open_session<T>()
329                    where
330                        T: __OpteeUteeSessionContext<Context = #ctx_type>,
331                    {}
332                    session_context_type_must_match_ta_open_session::<
333                        __OpteeUteeSessionContextFromOpenSession,
334                    >();
335                }
336
337                // To eliminate the clippy error: this public function might dereference a raw pointer but is not marked `unsafe`
338                // we just expand the unsafe block, but the session-related macros need refactoring in the future
339                #[unsafe(no_mangle)]
340                pub unsafe extern "C" fn TA_CloseSessionEntryPoint(sess_ctx: *mut core::ffi::c_void) {
341                    if sess_ctx.is_null() {
342                        panic!("sess_ctx is null");
343                    }
344                    let mut b = alloc::boxed::Box::from_raw(sess_ctx as *mut #ctx_type);
345                    #f_ident(&mut b);
346                    drop(b);
347                }
348
349                #f
350            )
351            .into()
352        }
353        _ => unreachable!(),
354    }
355}
356
357/// Attribute to declare the entry point of invoking commands.
358///
359/// The `params` argument may be any type that implements
360/// `optee_utee::FromRawParameters` (`optee_utee::ParametersAny`, a 4-tuple
361/// of typed wrappers, `optee_utee::Parameters`, etc.)
362///
363/// A session context `&mut T` can be defined as an optional first parameter
364/// (before `cmd_id`).
365///
366/// # Examples
367///
368/// ```ignore
369/// // Old deprecated Parameters (no session context)
370/// #[ta_invoke_command]
371/// fn invoke_command(cmd_id: u32, params: &mut Parameters) -> Result<()> { }
372///
373/// // New typed parameters
374/// use optee_utee::prelude::*;
375///
376/// // 4-tuple of typed wrappers
377/// #[ta_invoke_command]
378/// fn invoke_command(
379///     cmd_id: u32,
380///     params: &mut (
381///         ParameterNone,
382///         ParameterMemrefInput<'_>,
383///         ParameterValueOutput<'_>,
384///         ParameterMemrefOutput<'_>,
385///     ),
386/// ) -> Result<()> { }
387/// // use ParametersAny and check types with match later.
388/// #[ta_invoke_command]
389/// fn invoke_command(
390///     cmd_id: u32,
391///     params: &mut ParametersAny,
392/// ) -> Result<()> { }
393/// // With session context
394/// #[ta_invoke_command]
395/// fn invoke_command(
396///     sess_ctx: &mut T,
397///     cmd_id: u32,
398///     params: &mut Parameters,
399/// ) -> Result<()> { }
400/// ```
401#[proc_macro_attribute]
402pub fn ta_invoke_command(_args: TokenStream, input: TokenStream) -> TokenStream {
403    let f = parse_macro_input!(input as syn::ItemFn);
404    let f_sig = &f.sig;
405    let f_ident = &f_sig.ident;
406
407    // check the function signature
408    let valid_signature = f_sig.constness.is_none()
409        && matches!(f.vis, syn::Visibility::Inherited)
410        && f_sig.abi.is_none()
411        && (f_sig.inputs.len() == 2 || f_sig.inputs.len() == 3)
412        && f_sig.generics.where_clause.is_none()
413        && f_sig.variadic.is_none();
414
415    if !valid_signature {
416        return syn::parse::Error::new(
417            f.span(),
418            "`#[ta_invoke_command]` function must have signature `fn(u32, &mut P) -> Result<()>` or `fn(&mut T, u32, &mut P) -> Result<()>`",
419        )
420        .to_compile_error()
421        .into();
422    }
423
424    match f_sig.inputs.len() {
425        2 => {
426            let tokens = quote!(
427                #[doc(hidden)]
428                #[allow(dead_code)]
429                fn __optee_utee_invoke_session_context_type_must_match_ta_open_session() {
430                    fn session_context_type_must_match_ta_open_session<T>()
431                    where
432                        T: __OpteeUteeSessionContext<Context = core::ffi::c_void>,
433                    {}
434                    session_context_type_must_match_ta_open_session::<
435                        __OpteeUteeSessionContextFromOpenSession,
436                    >();
437                }
438
439                #[unsafe(no_mangle)]
440                pub extern "C" fn TA_InvokeCommandEntryPoint(
441                    _: *mut core::ffi::c_void,
442                    cmd_id: u32,
443                    param_types: optee_utee::RawParamTypes,
444                    params: &mut optee_utee::RawParams,
445                ) -> optee_utee::raw::TEE_Result {
446                    let mut parameters = match unsafe {
447                        optee_utee::FromRawParameters::from_raw(param_types, params)
448                    } {
449                        Ok(p) => p,
450                        Err(e) => return e.raw_code(),
451                    };
452                    match #f_ident(cmd_id, &mut parameters) {
453                        Ok(_) => {
454                            optee_utee::raw::TEE_SUCCESS
455                        },
456                        Err(e) => e.raw_code()
457                    }
458                }
459
460                #f
461            );
462            tokens.into()
463        }
464        3 => {
465            let ctx_type = match extract_fn_arg_mut_ref_type(&f_sig.inputs[0]) {
466                Ok(v) => v,
467                Err(e) => return e.to_compile_error().into(),
468            };
469
470            quote!(
471                #[doc(hidden)]
472                #[allow(dead_code)]
473                fn __optee_utee_invoke_session_context_type_must_match_ta_open_session() {
474                    fn session_context_type_must_match_ta_open_session<T>()
475                    where
476                        T: __OpteeUteeSessionContext<Context = #ctx_type>,
477                    {}
478                    session_context_type_must_match_ta_open_session::<
479                        __OpteeUteeSessionContextFromOpenSession,
480                    >();
481                }
482
483                #[unsafe(no_mangle)]
484                pub unsafe extern "C" fn TA_InvokeCommandEntryPoint(
485                    sess_ctx: *mut core::ffi::c_void,
486                    cmd_id: u32,
487                    param_types: optee_utee::RawParamTypes,
488                    params: &mut optee_utee::RawParams,
489                ) -> optee_utee::raw::TEE_Result {
490                    if sess_ctx.is_null() {
491                        return optee_utee::raw::TEE_ERROR_SECURITY;
492                    }
493                    let mut parameters = match unsafe {
494                        optee_utee::FromRawParameters::from_raw(param_types, params)
495                    } {
496                        Ok(p) => p,
497                        Err(e) => return e.raw_code(),
498                    };
499                    let mut b = alloc::boxed::Box::from_raw(sess_ctx as *mut #ctx_type);
500                    match #f_ident(&mut b, cmd_id, &mut parameters) {
501                        Ok(_) => {
502                            core::mem::forget(b);
503                            optee_utee::raw::TEE_SUCCESS
504                        },
505                        Err(e) => {
506                            core::mem::forget(b);
507                            e.raw_code()
508                        }
509                    }
510                }
511
512                #f
513            )
514            .into()
515        }
516        _ => unreachable!(),
517    }
518}
519
520fn extract_fn_arg_mut_ref_type(fn_arg: &syn::FnArg) -> Result<&syn::Type, syn::parse::Error> {
521    if let syn::FnArg::Typed(ty) = fn_arg
522        && let syn::Type::Reference(type_ref) = ty.ty.as_ref()
523        && type_ref.mutability.is_some()
524    {
525        return Ok(&*type_ref.elem);
526    };
527    Err(syn::parse::Error::new(
528        fn_arg.span(),
529        "this argument should have signature `_: &mut T`",
530    ))
531}