• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * \file macros.h
3  *
4  * \brief   This file contains generic macros for the purpose of testing.
5  */
6 
7 /*
8  *  Copyright The Mbed TLS Contributors
9  *  SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
10  */
11 
12 #ifndef TEST_MACROS_H
13 #define TEST_MACROS_H
14 
15 #if !defined(MBEDTLS_CONFIG_FILE)
16 #include "mbedtls/config.h"
17 #else
18 #include MBEDTLS_CONFIG_FILE
19 #endif
20 
21 #include <stdlib.h>
22 
23 #include "mbedtls/platform.h"
24 
25 #if defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C)
26 #include "mbedtls/memory_buffer_alloc.h"
27 #endif
28 
29 /**
30  * \brief   This macro tests the expression passed to it as a test step or
31  *          individual test in a test case.
32  *
33  *          It allows a library function to return a value and return an error
34  *          code that can be tested.
35  *
36  *          When MBEDTLS_CHECK_PARAMS is enabled, calls to the parameter failure
37  *          callback, MBEDTLS_PARAM_FAILED(), will be assumed to be a test
38  *          failure.
39  *
40  *          This macro is not suitable for negative parameter validation tests,
41  *          as it assumes the test step will not create an error.
42  *
43  *          Failing the test means:
44  *          - Mark this test case as failed.
45  *          - Print a message identifying the failure.
46  *          - Jump to the \c exit label.
47  *
48  *          This macro expands to an instruction, not an expression.
49  *          It may jump to the \c exit label.
50  *
51  * \param   TEST    The test expression to be tested.
52  */
53 #define TEST_ASSERT(TEST)                                 \
54     do {                                                    \
55         if (!(TEST))                                       \
56         {                                                    \
57             mbedtls_test_fail( #TEST, __LINE__, __FILE__);   \
58             goto exit;                                        \
59         }                                                    \
60     } while (0)
61 
62 /** This macro asserts fails the test with given output message.
63  *
64  * \param   MESSAGE The message to be outputed on assertion
65  */
66 #define TEST_FAIL(MESSAGE)                           \
67     do {                                                  \
68         mbedtls_test_fail(MESSAGE, __LINE__, __FILE__);   \
69         goto exit;                                        \
70     } while (0)
71 
72 /** Evaluate two integer expressions and fail the test case if they have
73  * different values.
74  *
75  * The two expressions should have the same signedness, otherwise the
76  * comparison is not meaningful if the signed value is negative.
77  *
78  * \param expr1     An integral-typed expression to evaluate.
79  * \param expr2     Another integral-typed expression to evaluate.
80  */
81 #define TEST_EQUAL(expr1, expr2)                                      \
82     do {                                                                \
83         if (!mbedtls_test_equal( #expr1 " == " #expr2, __LINE__, __FILE__, \
84                                  expr1, expr2))                      \
85         goto exit;                                                  \
86     } while (0)
87 
88 /** Evaluate two unsigned integer expressions and fail the test case
89  * if they are not in increasing order (left <= right).
90  *
91  * \param expr1     An integral-typed expression to evaluate.
92  * \param expr2     Another integral-typed expression to evaluate.
93  */
94 #define TEST_LE_U(expr1, expr2)                                       \
95     do {                                                                \
96         if (!mbedtls_test_le_u( #expr1 " <= " #expr2, __LINE__, __FILE__, \
97                                 expr1, expr2))                      \
98         goto exit;                                                  \
99     } while (0)
100 
101 /** Evaluate two signed integer expressions and fail the test case
102  * if they are not in increasing order (left <= right).
103  *
104  * \param expr1     An integral-typed expression to evaluate.
105  * \param expr2     Another integral-typed expression to evaluate.
106  */
107 #define TEST_LE_S(expr1, expr2)                                       \
108     do {                                                                \
109         if (!mbedtls_test_le_s( #expr1 " <= " #expr2, __LINE__, __FILE__, \
110                                 expr1, expr2))                      \
111         goto exit;                                                  \
112     } while (0)
113 
114 /** Allocate memory dynamically and fail the test case if this fails.
115  * The allocated memory will be filled with zeros.
116  *
117  * You must set \p pointer to \c NULL before calling this macro and
118  * put `mbedtls_free(pointer)` in the test's cleanup code.
119  *
120  * If \p item_count is zero, the resulting \p pointer will be \c NULL.
121  * This is usually what we want in tests since API functions are
122  * supposed to accept null pointers when a buffer size is zero.
123  *
124  * This macro expands to an instruction, not an expression.
125  * It may jump to the \c exit label.
126  *
127  * \param pointer    An lvalue where the address of the allocated buffer
128  *                   will be stored.
129  *                   This expression may be evaluated multiple times.
130  * \param item_count Number of elements to allocate.
131  *                   This expression may be evaluated multiple times.
132  *
133  */
134 #define TEST_CALLOC(pointer, item_count)                    \
135     do {                                                    \
136         TEST_ASSERT((pointer) == NULL);                     \
137         if ((item_count) != 0) {                            \
138             (pointer) = mbedtls_calloc(sizeof(*(pointer)),  \
139                                        (item_count));       \
140             TEST_ASSERT((pointer) != NULL);                 \
141         }                                                   \
142     } while (0)
143 
144 /* For backwards compatibility */
145 #define ASSERT_ALLOC(pointer, item_count) TEST_CALLOC(pointer, item_count)
146 
147 /** Allocate memory dynamically. If the allocation fails, skip the test case.
148  *
149  * This macro behaves like #TEST_CALLOC, except that if the allocation
150  * fails, it marks the test as skipped rather than failed.
151  */
152 #define TEST_CALLOC_OR_SKIP(pointer, item_count)            \
153     do {                                                    \
154         TEST_ASSERT((pointer) == NULL);                     \
155         if ((item_count) != 0) {                            \
156             (pointer) = mbedtls_calloc(sizeof(*(pointer)),  \
157                                        (item_count));       \
158             TEST_ASSUME((pointer) != NULL);                 \
159         }                                                   \
160     } while (0)
161 
162 /* For backwards compatibility */
163 #define ASSERT_ALLOC_WEAK(pointer, item_count) TEST_CALLOC_OR_SKIP(pointer, item_count)
164 
165 /** Compare two buffers and fail the test case if they differ.
166  *
167  * This macro expands to an instruction, not an expression.
168  * It may jump to the \c exit label.
169  *
170  * \param p1        Pointer to the start of the first buffer.
171  * \param size1     Size of the first buffer in bytes.
172  *                  This expression may be evaluated multiple times.
173  * \param p2        Pointer to the start of the second buffer.
174  * \param size2     Size of the second buffer in bytes.
175  *                  This expression may be evaluated multiple times.
176  */
177 #define TEST_MEMORY_COMPARE(p1, size1, p2, size2)              \
178     do {                                                       \
179         TEST_EQUAL((size1), (size2));                          \
180         if ((size1) != 0) {                                    \
181             TEST_ASSERT(memcmp((p1), (p2), (size1)) == 0);     \
182         }                                                      \
183     } while (0)
184 
185 /* For backwards compatibility */
186 #define ASSERT_COMPARE(p1, size1, p2, size2) TEST_MEMORY_COMPARE(p1, size1, p2, size2)
187 
188 /**
189  * \brief   This macro tests the expression passed to it and skips the
190  *          running test if it doesn't evaluate to 'true'.
191  *
192  * \param   TEST    The test expression to be tested.
193  */
194 #define TEST_ASSUME(TEST)                                 \
195     do {                                                    \
196         if (!(TEST))                                      \
197         {                                                   \
198             mbedtls_test_skip( #TEST, __LINE__, __FILE__); \
199             goto exit;                                      \
200         }                                                   \
201     } while (0)
202 
203 #if defined(MBEDTLS_CHECK_PARAMS) && !defined(MBEDTLS_PARAM_FAILED_ALT)
204 /**
205  * \brief   This macro tests the statement passed to it as a test step or
206  *          individual test in a test case. The macro assumes the test will fail
207  *          and will generate an error.
208  *
209  *          It allows a library function to return a value and tests the return
210  *          code on return to confirm the given error code was returned.
211  *
212  *          When MBEDTLS_CHECK_PARAMS is enabled, calls to the parameter failure
213  *          callback, MBEDTLS_PARAM_FAILED(), are assumed to indicate the
214  *          expected failure, and the test will pass.
215  *
216  *          This macro is intended for negative parameter validation tests,
217  *          where the failing function may return an error value or call
218  *          MBEDTLS_PARAM_FAILED() to indicate the error.
219  *
220  * \param   PARAM_ERROR_VALUE   The expected error code.
221  *
222  * \param   TEST                The test expression to be tested.
223  */
224 #define TEST_INVALID_PARAM_RET(PARAM_ERR_VALUE, TEST)                 \
225     do {                                                                \
226         mbedtls_test_param_failed_expect_call();                       \
227         if (((TEST) != (PARAM_ERR_VALUE)) ||                      \
228             (mbedtls_test_param_failed_check_expected_call() != 0)) \
229         {                                                               \
230             mbedtls_test_fail( #TEST, __LINE__, __FILE__);             \
231             goto exit;                                                  \
232         }                                                               \
233         mbedtls_test_param_failed_check_expected_call();               \
234     } while (0)
235 
236 /**
237  * \brief   This macro tests the statement passed to it as a test step or
238  *          individual test in a test case. The macro assumes the test will fail
239  *          and will generate an error.
240  *
241  *          It assumes the library function under test cannot return a value and
242  *          assumes errors can only be indicated byt calls to
243  *          MBEDTLS_PARAM_FAILED().
244  *
245  *          When MBEDTLS_CHECK_PARAMS is enabled, calls to the parameter failure
246  *          callback, MBEDTLS_PARAM_FAILED(), are assumed to indicate the
247  *          expected failure. If MBEDTLS_CHECK_PARAMS is not enabled, no test
248  *          can be made.
249  *
250  *          This macro is intended for negative parameter validation tests,
251  *          where the failing function can only return an error by calling
252  *          MBEDTLS_PARAM_FAILED() to indicate the error.
253  *
254  * \param   TEST                The test expression to be tested.
255  */
256 #define TEST_INVALID_PARAM(TEST)                                       \
257     do {                                                                 \
258         memcpy(jmp_tmp, mbedtls_test_param_failed_get_state_buf(),     \
259                sizeof(jmp_tmp));                                     \
260         if (setjmp(mbedtls_test_param_failed_get_state_buf()) == 0) \
261         {                                                                \
262             TEST;                                                        \
263             mbedtls_test_fail( #TEST, __LINE__, __FILE__);              \
264             goto exit;                                                   \
265         }                                                                \
266         mbedtls_test_param_failed_reset_state();                        \
267     } while (0)
268 #endif /* MBEDTLS_CHECK_PARAMS && !MBEDTLS_PARAM_FAILED_ALT */
269 
270 /**
271  * \brief   This macro tests the statement passed to it as a test step or
272  *          individual test in a test case. The macro assumes the test will not fail.
273  *
274  *          It assumes the library function under test cannot return a value and
275  *          assumes errors can only be indicated by calls to
276  *          MBEDTLS_PARAM_FAILED().
277  *
278  *          When MBEDTLS_CHECK_PARAMS is enabled, calls to the parameter failure
279  *          callback, MBEDTLS_PARAM_FAILED(), are assumed to indicate the
280  *          expected failure. If MBEDTLS_CHECK_PARAMS is not enabled, no test
281  *          can be made.
282  *
283  *          This macro is intended to test that functions returning void
284  *          accept all of the parameter values they're supposed to accept - eg
285  *          that they don't call MBEDTLS_PARAM_FAILED() when a parameter
286  *          that's allowed to be NULL happens to be NULL.
287  *
288  *          Note: for functions that return something other that void,
289  *          checking that they accept all the parameters they're supposed to
290  *          accept is best done by using TEST_ASSERT() and checking the return
291  *          value as well.
292  *
293  *          Note: this macro is available even when #MBEDTLS_CHECK_PARAMS is
294  *          disabled, as it makes sense to check that the functions accept all
295  *          legal values even if this option is disabled - only in that case,
296  *          the test is more about whether the function segfaults than about
297  *          whether it invokes MBEDTLS_PARAM_FAILED().
298  *
299  * \param   TEST                The test expression to be tested.
300  */
301 #define TEST_VALID_PARAM(TEST)                                    \
302     TEST_ASSERT((TEST, 1));
303 
304 #define TEST_HELPER_ASSERT(a) if (!(a))                          \
305     {                                                                   \
306         mbedtls_fprintf(stderr, "Assertion Failed at %s:%d - %s\n",    \
307                         __FILE__, __LINE__, #a);              \
308         mbedtls_exit(1);                                              \
309     }
310 
311 /** \def ARRAY_LENGTH
312  * Return the number of elements of a static or stack array.
313  *
314  * \param array         A value of array (not pointer) type.
315  *
316  * \return The number of elements of the array.
317  */
318 /* A correct implementation of ARRAY_LENGTH, but which silently gives
319  * a nonsensical result if called with a pointer rather than an array. */
320 #define ARRAY_LENGTH_UNSAFE(array)            \
321     (sizeof(array) / sizeof(*(array)))
322 
323 #if defined(__GNUC__)
324 /* Test if arg and &(arg)[0] have the same type. This is true if arg is
325  * an array but not if it's a pointer. */
326 #define IS_ARRAY_NOT_POINTER(arg)                                     \
327     (!__builtin_types_compatible_p(__typeof__(arg),                \
328                                    __typeof__(&(arg)[0])))
329 /* A compile-time constant with the value 0. If `const_expr` is not a
330  * compile-time constant with a nonzero value, cause a compile-time error. */
331 #define STATIC_ASSERT_EXPR(const_expr)                                \
332     (0 && sizeof(struct { unsigned int STATIC_ASSERT : 1 - 2 * !(const_expr); }))
333 
334 /* Return the scalar value `value` (possibly promoted). This is a compile-time
335  * constant if `value` is. `condition` must be a compile-time constant.
336  * If `condition` is false, arrange to cause a compile-time error. */
337 #define STATIC_ASSERT_THEN_RETURN(condition, value)   \
338     (STATIC_ASSERT_EXPR(condition) ? 0 : (value))
339 
340 #define ARRAY_LENGTH(array)                                           \
341     (STATIC_ASSERT_THEN_RETURN(IS_ARRAY_NOT_POINTER(array),         \
342                                ARRAY_LENGTH_UNSAFE(array)))
343 
344 #else
345 /* If we aren't sure the compiler supports our non-standard tricks,
346  * fall back to the unsafe implementation. */
347 #define ARRAY_LENGTH(array) ARRAY_LENGTH_UNSAFE(array)
348 #endif
349 
350 /** Return the smaller of two values.
351  *
352  * \param x         An integer-valued expression without side effects.
353  * \param y         An integer-valued expression without side effects.
354  *
355  * \return The smaller of \p x and \p y.
356  */
357 #define MIN(x, y) ((x) < (y) ? (x) : (y))
358 
359 /** Return the larger of two values.
360  *
361  * \param x         An integer-valued expression without side effects.
362  * \param y         An integer-valued expression without side effects.
363  *
364  * \return The larger of \p x and \p y.
365  */
366 #define MAX(x, y) ((x) > (y) ? (x) : (y))
367 
368 /*
369  * 32-bit integer manipulation macros (big endian)
370  */
371 #ifndef GET_UINT32_BE
372 #define GET_UINT32_BE(n, b, i)                            \
373     {                                                       \
374         (n) = ((uint32_t) (b)[(i)] << 24)             \
375               | ((uint32_t) (b)[(i) + 1] << 16)             \
376               | ((uint32_t) (b)[(i) + 2] <<  8)             \
377               | ((uint32_t) (b)[(i) + 3]);            \
378     }
379 #endif
380 
381 #ifndef PUT_UINT32_BE
382 #define PUT_UINT32_BE(n, b, i)                            \
383     {                                                       \
384         (b)[(i)] = (unsigned char) ((n) >> 24);       \
385         (b)[(i) + 1] = (unsigned char) ((n) >> 16);       \
386         (b)[(i) + 2] = (unsigned char) ((n) >>  8);       \
387         (b)[(i) + 3] = (unsigned char) ((n));       \
388     }
389 #endif
390 
391 #endif /* TEST_MACROS_H */
392