File: test_memory.c

package info (click to toggle)
modsecurity 3.0.14-1
  • links: PTS
  • area: main
  • in suites: forky, sid, trixie
  • size: 88,920 kB
  • sloc: ansic: 174,512; sh: 43,569; cpp: 26,214; python: 15,734; makefile: 3,864; yacc: 2,947; lex: 1,359; perl: 1,243; php: 42; tcl: 4
file content (60 lines) | stat: -rw-r--r-- 1,640 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/**
 * \file memory.c
 *
 * \brief   Helper functions related to testing memory management.
 */

/*
 *  Copyright The Mbed TLS Contributors
 *  SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
 */

#include <test/helpers.h>
#include <test/macros.h>
#include <test/memory.h>

#if defined(MBEDTLS_TEST_MEMORY_CAN_POISON)
#include <sanitizer/asan_interface.h>
#include <stdint.h>
#endif

#if defined(MBEDTLS_TEST_MEMORY_CAN_POISON)

_Thread_local unsigned int mbedtls_test_memory_poisoning_count = 0;

static void align_for_asan(const unsigned char **p_ptr, size_t *p_size)
{
    uintptr_t start = (uintptr_t) *p_ptr;
    uintptr_t end = start + (uintptr_t) *p_size;
    /* ASan can only poison regions with 8-byte alignment, and only poisons a
     * region if it's fully within the requested range. We want to poison the
     * whole requested region and don't mind a few extra bytes. Therefore,
     * align start down to an 8-byte boundary, and end up to an 8-byte
     * boundary. */
    start = start & ~(uintptr_t) 7;
    end = (end + 7) & ~(uintptr_t) 7;
    *p_ptr = (const unsigned char *) start;
    *p_size = end - start;
}

void mbedtls_test_memory_poison(const unsigned char *ptr, size_t size)
{
    if (mbedtls_test_memory_poisoning_count == 0) {
        return;
    }
    if (size == 0) {
        return;
    }
    align_for_asan(&ptr, &size);
    __asan_poison_memory_region(ptr, size);
}

void mbedtls_test_memory_unpoison(const unsigned char *ptr, size_t size)
{
    if (size == 0) {
        return;
    }
    align_for_asan(&ptr, &size);
    __asan_unpoison_memory_region(ptr, size);
}
#endif /* Memory poisoning */