1 /**
2  * \file constant_flow.h
3  *
4  * \brief   This file contains tools to ensure tested code has constant flow.
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_CONSTANT_FLOW_H
13 #define TEST_CONSTANT_FLOW_H
14 
15 #include "mbedtls/build_info.h"
16 
17 /*
18  * This file defines the two macros
19  *
20  *  #define TEST_CF_SECRET(ptr, size)
21  *  #define TEST_CF_PUBLIC(ptr, size)
22  *
23  * that can be used in tests to mark a memory area as secret (no branch or
24  * memory access should depend on it) or public (default, only needs to be
25  * marked explicitly when it was derived from secret data).
26  *
27  * Arguments:
28  * - ptr: a pointer to the memory area to be marked
29  * - size: the size in bytes of the memory area
30  *
31  * Implementation:
32  * The basic idea is that of ctgrind <https://github.com/agl/ctgrind>: we can
33  * re-use tools that were designed for checking use of uninitialized memory.
34  * This file contains two implementations: one based on MemorySanitizer, the
35  * other on valgrind's memcheck. If none of them is enabled, dummy macros that
36  * do nothing are defined for convenience.
37  *
38  * \note #TEST_CF_SECRET must be called directly from within a .function file,
39  *       not indirectly via a macro defined under tests/include or a function
40  *       under tests/src. This is because we only run Valgrind for constant
41  *       flow on test suites that have greppable annotations inside them (see
42  *       `skip_suites_without_constant_flow` in `tests/scripts/all.sh`).
43  */
44 
45 #if defined(MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN)
46 #include <sanitizer/msan_interface.h>
47 
48 /* Use macros to avoid messing up with origin tracking */
49 #define TEST_CF_SECRET  __msan_allocated_memory
50 // void __msan_allocated_memory(const volatile void* data, size_t size);
51 #define TEST_CF_PUBLIC  __msan_unpoison
52 // void __msan_unpoison(const volatile void *a, size_t size);
53 
54 #elif defined(MBEDTLS_TEST_CONSTANT_FLOW_VALGRIND)
55 #include <valgrind/memcheck.h>
56 
57 #define TEST_CF_SECRET  VALGRIND_MAKE_MEM_UNDEFINED
58 // VALGRIND_MAKE_MEM_UNDEFINED(_qzz_addr, _qzz_len)
59 #define TEST_CF_PUBLIC  VALGRIND_MAKE_MEM_DEFINED
60 // VALGRIND_MAKE_MEM_DEFINED(_qzz_addr, _qzz_len)
61 
62 #else /* MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN ||
63          MBEDTLS_TEST_CONSTANT_FLOW_VALGRIND */
64 
65 #define TEST_CF_SECRET(ptr, size)
66 #define TEST_CF_PUBLIC(ptr, size)
67 
68 #endif /* MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN ||
69           MBEDTLS_TEST_CONSTANT_FLOW_VALGRIND */
70 
71 #endif /* TEST_CONSTANT_FLOW_H */
72