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
14namespace Botan {
15
16namespace {
17
18/*
19* Perform Memory Allocation
20*/
21void* 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*/
38void 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*/
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*/
66void Malloc_Allocator::deallocate(void* ptr, size_t n)
67 {
68 do_free(ptr, n, false);
69 }
70
71/*
72* Locking_Allocator's Allocation
73*/
74void* Locking_Allocator::alloc_block(size_t n)
75 {
76 return do_malloc(n, true);
77 }
78
79/*
80* Locking_Allocator's Deallocation
81*/
82void Locking_Allocator::dealloc_block(void* ptr, size_t n)
83 {
84 do_free(ptr, n, true);
85 }
86
87/*
88* Get an allocator
89*/
91 {
92 std::string type = "";
93 if(!locking)
94 type = "malloc";
95
97 if(alloc)
98 return alloc;
99
100 throw Internal_Error("Couldn't find an allocator to use in get_allocator");
101 }
102
103}
virtual std::string type() const =0
static Allocator * get(bool locking)
Definition defalloc.cpp:90
Allocator * get_allocator(const std::string &name="") const
Definition libstate.cpp:67
void deallocate(void *, size_t)
Definition defalloc.cpp:66
void * allocate(size_t)
Definition defalloc.cpp:55
bool lock_mem(void *ptr, size_t bytes)
Definition mlock.cpp:31
void unlock_mem(void *ptr, size_t bytes)
Definition mlock.cpp:45
Library_State & global_state()
Internal_Error(const std::string &err)
Definition exceptn.h:47