1 /**
2  * \file memory.c
3  *
4  * \brief   Helper functions related to testing memory management.
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 #include <test/helpers.h>
13 #include <test/macros.h>
14 #include <test/memory.h>
15 
16 #if defined(MBEDTLS_TEST_MEMORY_CAN_POISON)
17 #include <sanitizer/asan_interface.h>
18 #include <stdint.h>
19 #endif
20 
21 #if defined(MBEDTLS_TEST_MEMORY_CAN_POISON)
22 
23 _Thread_local unsigned int mbedtls_test_memory_poisoning_count = 0;
24 
align_for_asan(const unsigned char ** p_ptr,size_t * p_size)25 static void align_for_asan(const unsigned char **p_ptr, size_t *p_size)
26 {
27     uintptr_t start = (uintptr_t) *p_ptr;
28     uintptr_t end = start + (uintptr_t) *p_size;
29     /* ASan can only poison regions with 8-byte alignment, and only poisons a
30      * region if it's fully within the requested range. We want to poison the
31      * whole requested region and don't mind a few extra bytes. Therefore,
32      * align start down to an 8-byte boundary, and end up to an 8-byte
33      * boundary. */
34     start = start & ~(uintptr_t) 7;
35     end = (end + 7) & ~(uintptr_t) 7;
36     *p_ptr = (const unsigned char *) start;
37     *p_size = end - start;
38 }
39 
mbedtls_test_memory_poison(const unsigned char * ptr,size_t size)40 void mbedtls_test_memory_poison(const unsigned char *ptr, size_t size)
41 {
42     if (mbedtls_test_memory_poisoning_count == 0) {
43         return;
44     }
45     if (size == 0) {
46         return;
47     }
48     align_for_asan(&ptr, &size);
49     __asan_poison_memory_region(ptr, size);
50 }
51 
mbedtls_test_memory_unpoison(const unsigned char * ptr,size_t size)52 void mbedtls_test_memory_unpoison(const unsigned char *ptr, size_t size)
53 {
54     if (size == 0) {
55         return;
56     }
57     align_for_asan(&ptr, &size);
58     __asan_unpoison_memory_region(ptr, size);
59 }
60 #endif /* Memory poisoning */
61