Botan 2.19.1
Crypto and TLS for C&
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
12namespace Botan {
13
14void* 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
26bool 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
43mlock_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
59mlock_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
70 {
71 static mlock_allocator mlock;
72 return mlock;
73 }
74
75}
static mlock_allocator & instance()
bool deallocate(void *p, size_t num_elems, size_t elem_size) noexcept
void * allocate(size_t num_elems, size_t elem_size)
size_t get_memory_locking_limit()
Definition: os_utils.cpp:327
std::vector< void * > allocate_locked_pages(size_t count)
Definition: os_utils.cpp:459
size_t system_page_size()
Definition: os_utils.cpp:307
void free_locked_pages(const std::vector< void * > &pages)
Definition: os_utils.cpp:577
Definition: alg_id.cpp:13