blob: 9da7f20a36ceea0ef90e1f4c6df60dac4b28466d [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
David Horstmann756b4dc2024-01-10 14:33:17 +000016#if defined(MBEDTLS_TEST_MEMORY_CAN_POISON)
Gilles Peskine071d1442023-11-02 20:49:34 +010017#include <sanitizer/asan_interface.h>
18#include <stdint.h>
19#endif
20
David Horstmann756b4dc2024-01-10 14:33:17 +000021#if defined(MBEDTLS_TEST_MEMORY_CAN_POISON)
22
David Horstmann7dfb6122024-01-23 15:35:20 +000023unsigned int mbedtls_test_memory_poisoning_count = 0;
David Horstmann756b4dc2024-01-10 14:33:17 +000024
Gilles Peskine962c5da2023-11-02 22:44:32 +010025static 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
Gilles Peskine071d1442023-11-02 20:49:34 +010040void mbedtls_test_memory_poison(const unsigned char *ptr, size_t size)
41{
David Horstmann6de58282024-01-17 14:23:20 +000042 if (mbedtls_test_memory_poisoning_count == 0) {
David Horstmann756b4dc2024-01-10 14:33:17 +000043 return;
44 }
Gilles Peskine071d1442023-11-02 20:49:34 +010045 if (size == 0) {
46 return;
47 }
Gilles Peskine962c5da2023-11-02 22:44:32 +010048 align_for_asan(&ptr, &size);
Gilles Peskine071d1442023-11-02 20:49:34 +010049 __asan_poison_memory_region(ptr, size);
50}
51
52void mbedtls_test_memory_unpoison(const unsigned char *ptr, size_t size)
53{
54 if (size == 0) {
55 return;
56 }
Gilles Peskine962c5da2023-11-02 22:44:32 +010057 align_for_asan(&ptr, &size);
Gilles Peskine071d1442023-11-02 20:49:34 +010058 __asan_unpoison_memory_region(ptr, size);
59}
David Horstmann756b4dc2024-01-10 14:33:17 +000060#endif /* Memory poisoning */