Botan 3.5.0
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/internal/locking_allocator.h>
9
10#include <botan/internal/int_utils.h>
11#include <botan/internal/mem_pool.h>
12#include <botan/internal/os_utils.h>
13
14namespace Botan {
15
16void* mlock_allocator::allocate(size_t num_elems, size_t elem_size) {
17 if(!m_pool) {
18 return nullptr;
19 }
20
21 if(auto n = checked_mul(num_elems, elem_size)) {
22 return m_pool->allocate(n.value());
23 } else {
24 // overflow!
25 return nullptr;
26 }
27}
28
29bool mlock_allocator::deallocate(void* p, size_t num_elems, size_t elem_size) noexcept {
30 if(!m_pool) {
31 return false;
32 }
33
34 if(auto n = checked_mul(num_elems, elem_size)) {
35 return m_pool->deallocate(p, n.value());
36 } else {
37 /*
38 We return nullptr in allocate if there was an overflow, so if an
39 overflow occurs here we know the pointer was not allocated by this pool.
40 */
41 return false;
42 }
43}
44
46 const size_t mem_to_lock = OS::get_memory_locking_limit();
47 const size_t page_size = OS::system_page_size();
48
49 if(mem_to_lock > 0 && mem_to_lock % page_size == 0) {
50 m_locked_pages = OS::allocate_locked_pages(mem_to_lock / page_size);
51
52 if(!m_locked_pages.empty()) {
53 m_pool = std::make_unique<Memory_Pool>(m_locked_pages, page_size);
54 }
55 }
56}
57
59 if(m_pool) {
60 m_pool.reset();
61 // OS::free_locked_pages scrubs the memory before free
62 OS::free_locked_pages(m_locked_pages);
63 }
64}
65
66namespace {
67
68// NOLINTNEXTLINE(*-avoid-non-const-global-variables)
69BOTAN_EARLY_INIT(101) mlock_allocator g_mlock_allocator;
70
71} // namespace
72
74 return g_mlock_allocator;
75}
76
77} // namespace Botan
bool deallocate(void *p, size_t num_elems, size_t elem_size) noexcept
void * allocate(size_t num_elems, size_t elem_size)
#define BOTAN_EARLY_INIT(prio)
Definition compiler.h:117
size_t get_memory_locking_limit()
Definition os_utils.cpp:370
std::vector< void * > allocate_locked_pages(size_t count)
Definition os_utils.cpp:504
size_t system_page_size()
Definition os_utils.cpp:350
void free_locked_pages(const std::vector< void * > &pages)
Definition os_utils.cpp:623
constexpr std::optional< T > checked_mul(T a, T b)
Definition int_utils.h:38