Botan 1.10.17

defalloc.cpp
Go to the documentation of this file.
1 /*
2 * Basic Allocators
3 * (C) 1999-2007 Jack Lloyd
4 *
5 * Distributed under the terms of the Botan license
6 */
7
8 #include <botan/internal/defalloc.h>
9 #include <botan/internal/mlock.h>
10 #include <botan/libstate.h>
11 #include <cstdlib>
12 #include <cstring>
13
14 namespace Botan {
15
16 namespace {
17
18 /*
19 * Perform Memory Allocation
20 */
21 void* do_malloc(size_t n, bool do_lock)
22 {
23 void* ptr = std::malloc(n);
24
25 if(!ptr)
26 return 0;
27
28 if(do_lock)
29 lock_mem(ptr, n);
30
31 std::memset(ptr, 0, n);
32 return ptr;
33 }
34
35 /*
36 * Perform Memory Deallocation
37 */
38 void do_free(void* ptr, size_t n, bool do_lock)
39 {
40 if(!ptr)
41 return;
42
43 std::memset(ptr, 0, n);
44 if(do_lock)
45 unlock_mem(ptr, n);
46
47 std::free(ptr);
48 }
49
50 }
51
52 /*
53 * Malloc_Allocator's Allocation
54 */
55 void* Malloc_Allocator::allocate(size_t n)
56 {
57 void* ptr = do_malloc(n, false);
58 if(!ptr)
59 throw Memory_Exhaustion();
60 return ptr;
61 }
62
63 /*
64 * Malloc_Allocator's Deallocation
65 */
66 void Malloc_Allocator::deallocate(void* ptr, size_t n)
67 {
68 do_free(ptr, n, false);
69 }
70
71 /*
72 * Locking_Allocator's Allocation
73 */
74 void* Locking_Allocator::alloc_block(size_t n)
75 {
76 return do_malloc(n, true);
77 }
78
79 /*
80 * Locking_Allocator's Deallocation
81 */
82 void Locking_Allocator::dealloc_block(void* ptr, size_t n)
83 {
84 do_free(ptr, n, true);
85 }
86
87 /*
88 * Get an allocator
89 */
90 Allocator* Allocator::get(bool locking)
91 {
92 std::string type = "";
93 if(!locking)
94 type = "malloc";
95
96 Allocator* alloc = global_state().get_allocator(type);
97 if(alloc)
98 return alloc;
99
100 throw Internal_Error("Couldn't find an allocator to use in get_allocator");
101 }
102
103 }
Botan::Memory_Exhaustion
Definition: exceptn.h:185
Botan::Allocator
Definition: allocate.h:19
Botan::Internal_Error
Definition: exceptn.h:45
Botan::Allocator::get
static Allocator * get(bool locking)
Definition: defalloc.cpp:90
Botan::Library_State::get_allocator
Allocator * get_allocator(const std::string &name="") const
Definition: libstate.cpp:67
Botan::Global_State_Management::global_state
Library_State & global_state()
Definition: global_state.cpp:32
Botan::Malloc_Allocator::deallocate
void deallocate(void *, size_t)
Definition: defalloc.cpp:66
Botan
Definition: algo_base.h:14
Botan::Allocator::type
virtual std::string type() const =0
Botan::unlock_mem
void unlock_mem(void *ptr, size_t bytes)
Definition: mlock.cpp:45
Botan::Malloc_Allocator::allocate
void * allocate(size_t)
Definition: defalloc.cpp:55
alloc
Allocator * alloc
Definition: bzip2.cpp:29
Botan::lock_mem
bool lock_mem(void *ptr, size_t bytes)
Definition: mlock.cpp:31