Botan  2.11.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) 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  const size_t page_size = OS::system_page_size();
47 
48  if(mem_to_lock > 0 && mem_to_lock % page_size == 0)
49  {
50  m_locked_pages = OS::allocate_locked_pages(mem_to_lock / page_size);
51 
52  if(m_locked_pages.size() > 0)
53  {
54  m_pool.reset(new Memory_Pool(m_locked_pages, page_size));
55  }
56  }
57  }
58 
59 mlock_allocator::~mlock_allocator()
60  {
61  if(m_pool)
62  {
63  m_pool.reset();
64  // OS::free_locked_pages scrubs the memory before free
65  OS::free_locked_pages(m_locked_pages);
66  }
67  }
68 
69 mlock_allocator& mlock_allocator::instance()
70  {
71  static mlock_allocator mlock;
72  return mlock;
73  }
74 
75 }
BigInt size_t n
Definition: bigint.h:1096
size_t elem_size
Definition: mem_ops.h:25
BigInt const BigInt & p
Definition: numthry.h:150
size_t get_memory_locking_limit()
Definition: os_utils.cpp:322
std::vector< void * > allocate_locked_pages(size_t count)
Definition: os_utils.cpp:405
void free_locked_pages(const std::vector< void * > &pages)
Definition: os_utils.cpp:500
Definition: alg_id.cpp:13
size_t system_page_size()
Definition: os_utils.cpp:303