blob: c277be85abd99943deba6085279ee01bd0e547ab [file] [log] [blame]
Gilles Peskine87270e52023-11-02 17:14:01 +01001/**
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 Peskine071d1442023-11-02 20:49:34 +010016#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 Peskine962c5da2023-11-02 22:44:32 +010022static 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 Peskine071d1442023-11-02 20:49:34 +010037void mbedtls_test_memory_poison(const unsigned char *ptr, size_t size)
38{
39 if (size == 0) {
40 return;
41 }
Gilles Peskine962c5da2023-11-02 22:44:32 +010042 align_for_asan(&ptr, &size);
Gilles Peskine071d1442023-11-02 20:49:34 +010043 __asan_poison_memory_region(ptr, size);
44}
45
46void mbedtls_test_memory_unpoison(const unsigned char *ptr, size_t size)
47{
48 if (size == 0) {
49 return;
50 }
Gilles Peskine962c5da2023-11-02 22:44:32 +010051 align_for_asan(&ptr, &size);
Gilles Peskine071d1442023-11-02 20:49:34 +010052 __asan_unpoison_memory_region(ptr, size);
53}
54#endif /* Asan */