1 /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2  * SPDX-License-Identifier: Apache-2.0"
3  *
4  * Written by Nir Drucker, Shay Gueron and Dusan Kostic,
5  * AWS Cryptographic Algorithms Group.
6  */
7 
8 #pragma once
9 
10 #include <oqs/common.h>
11 
12 #include "utilities.h"
13 
14 /* Runs _thecleanup function on _thealloc once _thealloc went out of scope */
15 #define DEFER_CLEANUP(_thealloc, _thecleanup) \
16   __attribute__((cleanup(_thecleanup))) _thealloc
17 
18 /* Create a cleanup function for pointers from function func, which accepts a
19  * pointer. This is useful for DEFER_CLEANUP, as it passes &_thealloc into
20  * _thecleanup function. This way,
21  * if _thealloc is a pointer _thecleanup would receive a pointer to a
22  * pointer.*/
23 #define DEFINE_POINTER_CLEANUP_FUNC(type, func) \
24   static inline void func##_pointer((type)*p)   \
25   {                                             \
26     if(p && *p) {                               \
27       func(*p);                                 \
28     }                                           \
29   }                                             \
30   struct __useless_struct_to_allow_trailing_semicolon__
31 
32 // len is bytes length of in
33 #define secure_clean OQS_MEM_cleanse
34 
35 #define CLEANUP_FUNC(name, type)               \
36   _INLINE_ void name##_cleanup(IN OUT type *o) \
37   {                                            \
38     secure_clean((uint8_t *)o, sizeof(*o));    \
39   }
40 
CLEANUP_FUNC(r,r_t)41 CLEANUP_FUNC(r, r_t)
42 CLEANUP_FUNC(m, m_t)
43 CLEANUP_FUNC(e, e_t)
44 CLEANUP_FUNC(sk, sk_t)
45 CLEANUP_FUNC(ss, ss_t)
46 CLEANUP_FUNC(ct, ct_t)
47 CLEANUP_FUNC(pad_r, pad_r_t)
48 CLEANUP_FUNC(pad_e, pad_e_t)
49 CLEANUP_FUNC(seed, seed_t)
50 CLEANUP_FUNC(syndrome, syndrome_t)
51 CLEANUP_FUNC(upc, upc_t)
52 CLEANUP_FUNC(func_k, func_k_t)
53 CLEANUP_FUNC(dbl_pad_r, dbl_pad_r_t)
54 
55 // The functions below require special handling because we deal
56 // with arrays and not structures.
57 
58 _INLINE_ void compressed_idx_d_ar_cleanup(IN OUT compressed_idx_d_ar_t *o)
59 {
60   for(int i = 0; i < N0; i++) {
61     secure_clean((uint8_t *)&(*o)[i], sizeof((*o)[0]));
62   }
63 }
64 
seeds_cleanup(IN OUT seeds_t * o)65 _INLINE_ void seeds_cleanup(IN OUT seeds_t *o)
66 {
67   for(int i = 0; i < NUM_OF_SEEDS; i++) {
68     seed_cleanup(&(o->seed[i]));
69   }
70 }
71