1 /**
2 * \file common.h
3 *
4 * \brief Utility macros for internal use in the library
5 */
6 /*
7 * Copyright The Mbed TLS Contributors
8 * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
9 */
10
11 #ifndef MBEDTLS_LIBRARY_COMMON_H
12 #define MBEDTLS_LIBRARY_COMMON_H
13
14 #include "mbedtls/build_info.h"
15 #include "alignment.h"
16
17 #include <assert.h>
18 #include <stddef.h>
19 #include <stdint.h>
20 #include <stddef.h>
21
22 #if defined(__ARM_NEON)
23 #include <arm_neon.h>
24 #define MBEDTLS_HAVE_NEON_INTRINSICS
25 #elif defined(MBEDTLS_PLATFORM_IS_WINDOWS_ON_ARM64)
26 #include <arm64_neon.h>
27 #define MBEDTLS_HAVE_NEON_INTRINSICS
28 #endif
29
30 /** Helper to define a function as static except when building invasive tests.
31 *
32 * If a function is only used inside its own source file and should be
33 * declared `static` to allow the compiler to optimize for code size,
34 * but that function has unit tests, define it with
35 * ```
36 * MBEDTLS_STATIC_TESTABLE int mbedtls_foo(...) { ... }
37 * ```
38 * and declare it in a header in the `library/` directory with
39 * ```
40 * #if defined(MBEDTLS_TEST_HOOKS)
41 * int mbedtls_foo(...);
42 * #endif
43 * ```
44 */
45 #if defined(MBEDTLS_TEST_HOOKS)
46 #define MBEDTLS_STATIC_TESTABLE
47 #else
48 #define MBEDTLS_STATIC_TESTABLE static
49 #endif
50
51 #if defined(MBEDTLS_TEST_HOOKS)
52 extern void (*mbedtls_test_hook_test_fail)(const char *test, int line, const char *file);
53 #define MBEDTLS_TEST_HOOK_TEST_ASSERT(TEST) \
54 do { \
55 if ((!(TEST)) && ((*mbedtls_test_hook_test_fail) != NULL)) \
56 { \
57 (*mbedtls_test_hook_test_fail)( #TEST, __LINE__, __FILE__); \
58 } \
59 } while (0)
60 #else
61 #define MBEDTLS_TEST_HOOK_TEST_ASSERT(TEST)
62 #endif /* defined(MBEDTLS_TEST_HOOKS) */
63
64 /** \def ARRAY_LENGTH
65 * Return the number of elements of a static or stack array.
66 *
67 * \param array A value of array (not pointer) type.
68 *
69 * \return The number of elements of the array.
70 */
71 /* A correct implementation of ARRAY_LENGTH, but which silently gives
72 * a nonsensical result if called with a pointer rather than an array. */
73 #define ARRAY_LENGTH_UNSAFE(array) \
74 (sizeof(array) / sizeof(*(array)))
75
76 #if defined(__GNUC__)
77 /* Test if arg and &(arg)[0] have the same type. This is true if arg is
78 * an array but not if it's a pointer. */
79 #define IS_ARRAY_NOT_POINTER(arg) \
80 (!__builtin_types_compatible_p(__typeof__(arg), \
81 __typeof__(&(arg)[0])))
82 /* A compile-time constant with the value 0. If `const_expr` is not a
83 * compile-time constant with a nonzero value, cause a compile-time error. */
84 #define STATIC_ASSERT_EXPR(const_expr) \
85 (0 && sizeof(struct { unsigned int STATIC_ASSERT : 1 - 2 * !(const_expr); }))
86
87 /* Return the scalar value `value` (possibly promoted). This is a compile-time
88 * constant if `value` is. `condition` must be a compile-time constant.
89 * If `condition` is false, arrange to cause a compile-time error. */
90 #define STATIC_ASSERT_THEN_RETURN(condition, value) \
91 (STATIC_ASSERT_EXPR(condition) ? 0 : (value))
92
93 #define ARRAY_LENGTH(array) \
94 (STATIC_ASSERT_THEN_RETURN(IS_ARRAY_NOT_POINTER(array), \
95 ARRAY_LENGTH_UNSAFE(array)))
96
97 #else
98 /* If we aren't sure the compiler supports our non-standard tricks,
99 * fall back to the unsafe implementation. */
100 #define ARRAY_LENGTH(array) ARRAY_LENGTH_UNSAFE(array)
101 #endif
102 /** Allow library to access its structs' private members.
103 *
104 * Although structs defined in header files are publicly available,
105 * their members are private and should not be accessed by the user.
106 */
107 #define MBEDTLS_ALLOW_PRIVATE_ACCESS
108
109 /**
110 * \brief Securely zeroize a buffer then free it.
111 *
112 * Similar to making consecutive calls to
113 * \c mbedtls_platform_zeroize() and \c mbedtls_free(), but has
114 * code size savings, and potential for optimisation in the future.
115 *
116 * Guaranteed to be a no-op if \p buf is \c NULL and \p len is 0.
117 *
118 * \param buf Buffer to be zeroized then freed.
119 * \param len Length of the buffer in bytes
120 */
121 void mbedtls_zeroize_and_free(void *buf, size_t len);
122
123 /** Return an offset into a buffer.
124 *
125 * This is just the addition of an offset to a pointer, except that this
126 * function also accepts an offset of 0 into a buffer whose pointer is null.
127 * (`p + n` has undefined behavior when `p` is null, even when `n == 0`.
128 * A null pointer is a valid buffer pointer when the size is 0, for example
129 * as the result of `malloc(0)` on some platforms.)
130 *
131 * \param p Pointer to a buffer of at least n bytes.
132 * This may be \p NULL if \p n is zero.
133 * \param n An offset in bytes.
134 * \return Pointer to offset \p n in the buffer \p p.
135 * Note that this is only a valid pointer if the size of the
136 * buffer is at least \p n + 1.
137 */
mbedtls_buffer_offset( unsigned char *p, size_t n)138 static inline unsigned char *mbedtls_buffer_offset(
139 unsigned char *p, size_t n)
140 {
141 return p == NULL ? NULL : p + n;
142 }
143
144 /** Return an offset into a read-only buffer.
145 *
146 * Similar to mbedtls_buffer_offset(), but for const pointers.
147 *
148 * \param p Pointer to a buffer of at least n bytes.
149 * This may be \p NULL if \p n is zero.
150 * \param n An offset in bytes.
151 * \return Pointer to offset \p n in the buffer \p p.
152 * Note that this is only a valid pointer if the size of the
153 * buffer is at least \p n + 1.
154 */
mbedtls_buffer_offset_const( const unsigned char *p, size_t n)155 static inline const unsigned char *mbedtls_buffer_offset_const(
156 const unsigned char *p, size_t n)
157 {
158 return p == NULL ? NULL : p + n;
159 }
160
161 void mbedtls_xor(unsigned char *r, const unsigned char *a, const unsigned char *b, size_t n);
162
163 void mbedtls_xor_no_simd(unsigned char *r,
164 const unsigned char *a,
165 const unsigned char *b,
166 size_t n);
167
168 /* Fix MSVC C99 compatible issue
169 * MSVC support __func__ from visual studio 2015( 1900 )
170 * Use MSVC predefine macro to avoid name check fail.
171 */
172 #if (defined(_MSC_VER) && (_MSC_VER <= 1900))
173 #define /*no-check-names*/ __func__ __FUNCTION__
174 #endif
175
176 /* Define `asm` for compilers which don't define it. */
177 /* *INDENT-OFF* */
178 #ifndef asm
179 #if defined(__IAR_SYSTEMS_ICC__)
180 #define asm __asm
181 #else
182 #define asm __asm__
183 #endif
184 #endif
185 /* *INDENT-ON* */
186
187 /*
188 * Define the constraint used for read-only pointer operands to aarch64 asm.
189 *
190 * This is normally the usual "r", but for aarch64_32 (aka ILP32,
191 * as found in watchos), "p" is required to avoid warnings from clang.
192 *
193 * Note that clang does not recognise '+p' or '=p', and armclang
194 * does not recognise 'p' at all. Therefore, to update a pointer from
195 * aarch64 assembly, it is necessary to use something like:
196 *
197 * uintptr_t uptr = (uintptr_t) ptr;
198 * asm( "ldr x4, [%x0], #8" ... : "+r" (uptr) : : )
199 * ptr = (void*) uptr;
200 *
201 * Note that the "x" in "%x0" is neccessary; writing "%0" will cause warnings.
202 */
203 #if defined(__aarch64__) && defined(MBEDTLS_HAVE_ASM)
204 #if UINTPTR_MAX == 0xfffffffful
205 /* ILP32: Specify the pointer operand slightly differently, as per #7787. */
206 #define MBEDTLS_ASM_AARCH64_PTR_CONSTRAINT "p"
207 #elif UINTPTR_MAX == 0xfffffffffffffffful
208 /* Normal case (64-bit pointers): use "r" as the constraint for pointer operands to asm */
209 #define MBEDTLS_ASM_AARCH64_PTR_CONSTRAINT "r"
210 #else
211 #error "Unrecognised pointer size for aarch64"
212 #endif
213 #endif
214
215 /* Always provide a static assert macro, so it can be used unconditionally.
216 * It will expand to nothing on some systems.
217 * Can be used outside functions (but don't add a trailing ';' in that case:
218 * the semicolon is included here to avoid triggering -Wextra-semi when
219 * MBEDTLS_STATIC_ASSERT() expands to nothing).
220 * Can't use the C11-style `defined(static_assert)` on FreeBSD, since it
221 * defines static_assert even with -std=c99, but then complains about it.
222 */
223 #if defined(static_assert) && !defined(__FreeBSD__)
224 #define MBEDTLS_STATIC_ASSERT(expr, msg) static_assert(expr, msg);
225 #else
226 #define MBEDTLS_STATIC_ASSERT(expr, msg)
227 #endif
228
229 #if defined(__has_builtin)
230 #define MBEDTLS_HAS_BUILTIN(x) __has_builtin(x)
231 #else
232 #define MBEDTLS_HAS_BUILTIN(x) 0
233 #endif
234
235 /* Define compiler branch hints */
236 #if MBEDTLS_HAS_BUILTIN(__builtin_expect)
237 #define MBEDTLS_LIKELY(x) __builtin_expect(!!(x), 1)
238 #define MBEDTLS_UNLIKELY(x) __builtin_expect(!!(x), 0)
239 #else
240 #define MBEDTLS_LIKELY(x) x
241 #define MBEDTLS_UNLIKELY(x) x
242 #endif
243
244 /* MBEDTLS_ASSUME may be used to provide additional information to the compiler
245 * which can result in smaller code-size. */
246 #if MBEDTLS_HAS_BUILTIN(__builtin_assume)
247 /* clang provides __builtin_assume */
248 #define MBEDTLS_ASSUME(x) __builtin_assume(x)
249 #elif MBEDTLS_HAS_BUILTIN(__builtin_unreachable)
250 /* gcc and IAR can use __builtin_unreachable */
251 #define MBEDTLS_ASSUME(x) do { if (!(x)) __builtin_unreachable(); } while (0)
252 #elif defined(_MSC_VER)
253 /* Supported by MSVC since VS 2005 */
254 #define MBEDTLS_ASSUME(x) __assume(x)
255 #else
256 #define MBEDTLS_ASSUME(x) do { } while (0)
257 #endif
258
259 /* For gcc -Os, override with -O2 for a given function.
260 *
261 * This will not affect behaviour for other optimisation settings, e.g. -O0.
262 */
263 #if defined(MBEDTLS_COMPILER_IS_GCC) && defined(__OPTIMIZE_SIZE__)
264 #define MBEDTLS_OPTIMIZE_FOR_PERFORMANCE __attribute__((optimize("-O2")))
265 #else
266 #define MBEDTLS_OPTIMIZE_FOR_PERFORMANCE
267 #endif
268
269 /* Suppress compiler warnings for unused functions and variables. */
270 #if !defined(MBEDTLS_MAYBE_UNUSED) && defined(__has_attribute)
271 # if __has_attribute(unused)
272 # define MBEDTLS_MAYBE_UNUSED __attribute__((unused))
273 # endif
274 #endif
275 #if !defined(MBEDTLS_MAYBE_UNUSED) && defined(__GNUC__)
276 # define MBEDTLS_MAYBE_UNUSED __attribute__((unused))
277 #endif
278 #if !defined(MBEDTLS_MAYBE_UNUSED) && defined(__IAR_SYSTEMS_ICC__) && defined(__VER__)
279 /* IAR does support __attribute__((unused)), but only if the -e flag (extended language support)
280 * is given; the pragma always works.
281 * Unfortunately the pragma affects the rest of the file where it is used, but this is harmless.
282 * Check for version 5.2 or later - this pragma may be supported by earlier versions, but I wasn't
283 * able to find documentation).
284 */
285 # if (__VER__ >= 5020000)
286 # define MBEDTLS_MAYBE_UNUSED _Pragma("diag_suppress=Pe177")
287 # endif
288 #endif
289 #if !defined(MBEDTLS_MAYBE_UNUSED) && defined(_MSC_VER)
290 # define MBEDTLS_MAYBE_UNUSED __pragma(warning(suppress:4189))
291 #endif
292 #if !defined(MBEDTLS_MAYBE_UNUSED)
293 # define MBEDTLS_MAYBE_UNUSED
294 #endif
295
296 #endif /* MBEDTLS_LIBRARY_COMMON_H */
297