Botan  2.13.0
Crypto and TLS for C++11
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/locking_allocator.h>
14 #endif
15 
16 namespace Botan {
17 
18 BOTAN_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 #if defined(BOTAN_HAS_LOCKING_ALLOCATOR)
24  if(void* p = mlock_allocator::instance().allocate(elems, elem_size))
25  return p;
26 #endif
27 
28  void* ptr = std::calloc(elems, elem_size);
29  if(!ptr)
30  throw std::bad_alloc();
31  return ptr;
32  }
33 
34 void deallocate_memory(void* p, size_t elems, size_t elem_size)
35  {
36  if(p == nullptr)
37  return;
38 
39  secure_scrub_memory(p, elems * elem_size);
40 
41 #if defined(BOTAN_HAS_LOCKING_ALLOCATOR)
42  if(mlock_allocator::instance().deallocate(p, elems, elem_size))
43  return;
44 #endif
45 
46  std::free(p);
47  }
48 
50  {
51 #if defined(BOTAN_HAS_LOCKING_ALLOCATOR)
53 #endif
54  }
55 
56 uint8_t ct_compare_u8(const uint8_t x[],
57  const uint8_t y[],
58  size_t len)
59  {
60  volatile uint8_t difference = 0;
61 
62  for(size_t i = 0; i != len; ++i)
63  difference |= (x[i] ^ y[i]);
64 
65  return CT::Mask<uint8_t>::is_zero(difference).value();
66  }
67 
68 }
static mlock_allocator & instance()
BOTAN_MALLOC_FN void * allocate_memory(size_t elems, size_t elem_size)
Definition: mem_ops.cpp:18
#define BOTAN_MALLOC_FN
Definition: compiler.h:94
uint8_t ct_compare_u8(const uint8_t x[], const uint8_t y[], size_t len)
Definition: mem_ops.cpp:56
void deallocate_memory(void *p, size_t elems, size_t elem_size)
Definition: mem_ops.cpp:34
Definition: alg_id.cpp:13
void secure_scrub_memory(void *ptr, size_t n)
Definition: os_utils.cpp:66
static Mask< T > is_zero(T x)
Definition: ct_utils.h:141
void initialize_allocator()
Definition: mem_ops.cpp:49