Botan 3.0.0-alpha0
Crypto and TLS for C&
mem_ops.cpp
Go to the documentation of this file.
1/*
2* (C) 2017 Jack Lloyd
3*
4* Botan is released under the Simplified BSD License (see license.txt)
5*/
6
7#include <botan/mem_ops.h>
8#include <botan/internal/ct_utils.h>
9#include <cstdlib>
10#include <new>
11
12#if defined(BOTAN_HAS_LOCKING_ALLOCATOR)
13 #include <botan/internal/locking_allocator.h>
14#endif
15
16namespace Botan {
17
18BOTAN_MALLOC_FN void* allocate_memory(size_t elems, size_t elem_size)
19 {
20 if(elems == 0 || elem_size == 0)
21 return nullptr;
22
23 // Some calloc implementations do not check for overflow (?!?)
24 const size_t total_size = elems * elem_size;
25
26 if(total_size < elems || total_size < elem_size)
27 throw std::bad_alloc();
28
29#if defined(BOTAN_HAS_LOCKING_ALLOCATOR)
30 if(void* p = mlock_allocator::instance().allocate(elems, elem_size))
31 return p;
32#endif
33
34#if defined(BOTAN_TARGET_OS_HAS_ALLOC_CONCEAL)
35 void *ptr = ::calloc_conceal(elems, elem_size);
36#else
37 void* ptr = std::calloc(elems, elem_size);
38#endif
39 if(!ptr)
40 throw std::bad_alloc();
41 return ptr;
42 }
43
44void deallocate_memory(void* p, size_t elems, size_t elem_size)
45 {
46 if(p == nullptr)
47 return;
48
49 secure_scrub_memory(p, elems * elem_size);
50
51#if defined(BOTAN_HAS_LOCKING_ALLOCATOR)
52 if(mlock_allocator::instance().deallocate(p, elems, elem_size))
53 return;
54#endif
55 std::free(p);
56 }
57
59 {
60#if defined(BOTAN_HAS_LOCKING_ALLOCATOR)
62#endif
63 }
64
65uint8_t ct_compare_u8(const uint8_t x[],
66 const uint8_t y[],
67 size_t len)
68 {
69 volatile uint8_t difference = 0;
70
71 for(size_t i = 0; i != len; ++i)
72 difference = difference | (x[i] ^ y[i]);
73
74 return CT::Mask<uint8_t>::is_zero(difference).value();
75 }
76
77}
static Mask< T > is_zero(T x)
Definition: ct_utils.h:139
static mlock_allocator & instance()
#define BOTAN_MALLOC_FN
Definition: compiler.h:73
Definition: alg_id.cpp:13
BOTAN_MALLOC_FN void * allocate_memory(size_t elems, size_t elem_size)
Definition: mem_ops.cpp:18
void deallocate_memory(void *p, size_t elems, size_t elem_size)
Definition: mem_ops.cpp:44
void secure_scrub_memory(void *ptr, size_t n)
Definition: os_utils.cpp:81
uint8_t ct_compare_u8(const uint8_t x[], const uint8_t y[], size_t len)
Definition: mem_ops.cpp:65
void initialize_allocator()
Definition: mem_ops.cpp:58