Gilles Peskine | 87270e5 | 2023-11-02 17:14:01 +0100 | [diff] [blame] | 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 | |
Gilles Peskine | 071d144 | 2023-11-02 20:49:34 +0100 | [diff] [blame] | 16 | #if defined(MBEDTLS_TEST_HAVE_ASAN) |
| 17 | #include <sanitizer/asan_interface.h> |
| 18 | #include <stdint.h> |
| 19 | #endif |
| 20 | |
| 21 | #if defined(MBEDTLS_TEST_HAVE_ASAN) |
Gilles Peskine | 962c5da | 2023-11-02 22:44:32 +0100 | [diff] [blame^] | 22 | static void align_for_asan(const unsigned char **p_ptr, size_t *p_size) |
| 23 | { |
| 24 | uintptr_t start = (uintptr_t) *p_ptr; |
| 25 | uintptr_t end = start + (uintptr_t) *p_size; |
| 26 | /* ASan can only poison regions with 8-byte alignment, and only poisons a |
| 27 | * region if it's fully within the requested range. We want to poison the |
| 28 | * whole requested region and don't mind a few extra bytes. Therefore, |
| 29 | * align start down to an 8-byte boundary, and end up to an 8-byte |
| 30 | * boundary. */ |
| 31 | start = start & ~(uintptr_t) 7; |
| 32 | end = (end + 7) & ~(uintptr_t) 7; |
| 33 | *p_ptr = (const unsigned char *) start; |
| 34 | *p_size = end - start; |
| 35 | } |
| 36 | |
Gilles Peskine | 071d144 | 2023-11-02 20:49:34 +0100 | [diff] [blame] | 37 | void mbedtls_test_memory_poison(const unsigned char *ptr, size_t size) |
| 38 | { |
| 39 | if (size == 0) { |
| 40 | return; |
| 41 | } |
Gilles Peskine | 962c5da | 2023-11-02 22:44:32 +0100 | [diff] [blame^] | 42 | align_for_asan(&ptr, &size); |
Gilles Peskine | 071d144 | 2023-11-02 20:49:34 +0100 | [diff] [blame] | 43 | __asan_poison_memory_region(ptr, size); |
| 44 | } |
| 45 | |
| 46 | void mbedtls_test_memory_unpoison(const unsigned char *ptr, size_t size) |
| 47 | { |
| 48 | if (size == 0) { |
| 49 | return; |
| 50 | } |
Gilles Peskine | 962c5da | 2023-11-02 22:44:32 +0100 | [diff] [blame^] | 51 | align_for_asan(&ptr, &size); |
Gilles Peskine | 071d144 | 2023-11-02 20:49:34 +0100 | [diff] [blame] | 52 | __asan_unpoison_memory_region(ptr, size); |
| 53 | } |
| 54 | #endif /* Asan */ |