Botan  1.10.9
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 */
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 
97  if(alloc)
98  return alloc;
99 
100  throw Internal_Error("Couldn't find an allocator to use in get_allocator");
101  }
102 
103 }
BigInt n
Definition: numthry.cpp:26
static Allocator * get(bool locking)
Definition: defalloc.cpp:90
Library_State & global_state()
Allocator * get_allocator(const std::string &name="") const
Definition: libstate.cpp:67
void deallocate(void *, size_t)
Definition: defalloc.cpp:66
virtual std::string type() const =0
void unlock_mem(void *ptr, size_t bytes)
Definition: mlock.cpp:45
void * allocate(size_t)
Definition: defalloc.cpp:55
Allocator * alloc
Definition: bzip2.cpp:29
bool lock_mem(void *ptr, size_t bytes)
Definition: mlock.cpp:31