Botan  2.6.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 <cstdlib>
9 
10 #if defined(BOTAN_HAS_LOCKING_ALLOCATOR)
11  #include <botan/locking_allocator.h>
12 #endif
13 
14 namespace Botan {
15 
16 BOTAN_MALLOC_FN void* allocate_memory(size_t elems, size_t elem_size)
17  {
18 #if defined(BOTAN_HAS_LOCKING_ALLOCATOR)
19  if(void* p = mlock_allocator::instance().allocate(elems, elem_size))
20  return p;
21 #endif
22 
23  void* ptr = std::calloc(elems, elem_size);
24  if(!ptr)
25  throw std::bad_alloc();
26  return ptr;
27  }
28 
29 void deallocate_memory(void* p, size_t elems, size_t elem_size)
30  {
31  if(p == nullptr)
32  return;
33 
34  secure_scrub_memory(p, elems * elem_size);
35 
36 #if defined(BOTAN_HAS_LOCKING_ALLOCATOR)
37  if(mlock_allocator::instance().deallocate(p, elems, elem_size))
38  return;
39 #endif
40 
41  std::free(p);
42  }
43 
45  {
46 #if defined(BOTAN_HAS_LOCKING_ALLOCATOR)
48 #endif
49  }
50 
51 bool constant_time_compare(const uint8_t x[],
52  const uint8_t y[],
53  size_t len)
54  {
55  volatile uint8_t difference = 0;
56 
57  for(size_t i = 0; i != len; ++i)
58  difference |= (x[i] ^ y[i]);
59 
60  return difference == 0;
61  }
62 
63 }
static mlock_allocator & instance()
BOTAN_MALLOC_FN void * allocate_memory(size_t elems, size_t elem_size)
Definition: mem_ops.cpp:16
bool constant_time_compare(const uint8_t x[], const uint8_t y[], size_t len)
Definition: mem_ops.cpp:51
#define BOTAN_MALLOC_FN
Definition: compiler.h:95
void deallocate_memory(void *p, size_t elems, size_t elem_size)
Definition: mem_ops.cpp:29
Definition: alg_id.cpp:13
void secure_scrub_memory(void *ptr, size_t n)
Definition: os_utils.cpp:37
void initialize_allocator()
Definition: mem_ops.cpp:44