Botan  2.7.0
Crypto and TLS for C++11
locking_allocator.cpp
Go to the documentation of this file.
1 /*
2 * Mlock Allocator
3 * (C) 2012,2014,2015 Jack Lloyd
4 *
5 * Botan is released under the Simplified BSD License (see license.txt)
6 */
7 
8 #include <botan/locking_allocator.h>
9 #include <botan/internal/os_utils.h>
10 #include <botan/internal/mem_pool.h>
11 
12 namespace Botan {
13 
14 void* mlock_allocator::allocate(size_t num_elems, size_t elem_size)
15  {
16  if(!m_pool)
17  return nullptr;
18 
19  const size_t n = num_elems * elem_size;
20  if(n / elem_size != num_elems)
21  return nullptr; // overflow!
22 
23  return m_pool->allocate(n);
24  }
25 
26 bool mlock_allocator::deallocate(void* p, size_t num_elems, size_t elem_size) BOTAN_NOEXCEPT
27  {
28  if(!m_pool)
29  return false;
30 
31  size_t n = num_elems * elem_size;
32 
33  /*
34  We return nullptr in allocate if there was an overflow, so if an
35  overflow occurs here we know the pointer was not allocated by this pool.
36  */
37  if(n / elem_size != num_elems)
38  return false;
39 
40  return m_pool->deallocate(p, n);
41  }
42 
43 mlock_allocator::mlock_allocator()
44  {
45  const size_t mem_to_lock = OS::get_memory_locking_limit();
46 
47  if(mem_to_lock)
48  {
49  m_locked_pages = static_cast<uint8_t*>(OS::allocate_locked_pages(mem_to_lock));
50 
51  if(m_locked_pages)
52  {
53  m_locked_pages_size = mem_to_lock;
54  m_pool.reset(new Memory_Pool(m_locked_pages,
55  m_locked_pages_size,
57  BOTAN_MLOCK_ALLOCATOR_MIN_ALLOCATION,
58  BOTAN_MLOCK_ALLOCATOR_MAX_ALLOCATION,
59  4));
60  }
61  }
62  }
63 
64 mlock_allocator::~mlock_allocator()
65  {
66  if(m_pool)
67  {
68  m_pool.reset();
69  // OS::free_locked_pages scrubs the memory before free
70  OS::free_locked_pages(m_locked_pages, m_locked_pages_size);
71  }
72  }
73 
75  {
76  static mlock_allocator mlock;
77  return mlock;
78  }
79 
80 }
static mlock_allocator & instance()
void * allocate_locked_pages(size_t length)
Definition: os_utils.cpp:300
#define BOTAN_NOEXCEPT
Definition: compiler.h:154
void * allocate(size_t num_elems, size_t elem_size)
size_t get_memory_locking_limit()
Definition: os_utils.cpp:218
bool deallocate(void *p, size_t num_elems, size_t elem_size) BOTAN_NOEXCEPT
Definition: alg_id.cpp:13
size_t system_page_size()
Definition: os_utils.cpp:200
void free_locked_pages(void *ptr, size_t length)
Definition: os_utils.cpp:359