Botan 3.5.0
Crypto and TLS for C&
allocator.cpp
Go to the documentation of this file.
1/*
2* (C) 2017,2023 Jack Lloyd
3*
4* Botan is released under the Simplified BSD License (see license.txt)
5*/
6
7#include <botan/allocator.h>
8
9#include <botan/mem_ops.h>
10#include <botan/internal/int_utils.h>
11#include <cstdlib>
12#include <new>
13
14#if defined(BOTAN_HAS_LOCKING_ALLOCATOR)
15 #include <botan/internal/locking_allocator.h>
16#endif
17
18namespace Botan {
19
20BOTAN_MALLOC_FN void* allocate_memory(size_t elems, size_t elem_size) {
21 if(elems == 0 || elem_size == 0) {
22 return nullptr;
23 }
24
25 // Some calloc implementations do not check for overflow (?!?)
26 if(!checked_mul(elems, elem_size).has_value()) {
27 throw std::bad_alloc();
28 }
29
30#if defined(BOTAN_HAS_LOCKING_ALLOCATOR)
31 if(void* p = mlock_allocator::instance().allocate(elems, elem_size)) {
32 return p;
33 }
34#endif
35
36#if defined(BOTAN_TARGET_OS_HAS_ALLOC_CONCEAL)
37 void* ptr = ::calloc_conceal(elems, elem_size);
38#else
39 void* ptr = std::calloc(elems, elem_size); // NOLINT(*-no-malloc)
40#endif
41 if(!ptr) {
42 [[unlikely]] throw std::bad_alloc();
43 }
44 return ptr;
45}
46
47void deallocate_memory(void* p, size_t elems, size_t elem_size) {
48 if(p == nullptr) {
49 [[unlikely]] return;
50 }
51
52 secure_scrub_memory(p, elems * elem_size);
53
54#if defined(BOTAN_HAS_LOCKING_ALLOCATOR)
55 if(mlock_allocator::instance().deallocate(p, elems, elem_size)) {
56 return;
57 }
58#endif
59
60 std::free(p); // NOLINT(*-no-malloc)
61}
62
64#if defined(BOTAN_HAS_LOCKING_ALLOCATOR)
66#endif
67}
68
69} // namespace Botan
static mlock_allocator & instance()
#define BOTAN_MALLOC_FN
Definition compiler.h:108
BOTAN_MALLOC_FN void * allocate_memory(size_t elems, size_t elem_size)
Definition allocator.cpp:20
void deallocate_memory(void *p, size_t elems, size_t elem_size)
Definition allocator.cpp:47
void secure_scrub_memory(void *ptr, size_t n)
Definition os_utils.cpp:89
constexpr std::optional< T > checked_mul(T a, T b)
Definition int_utils.h:38
void initialize_allocator()
Definition allocator.cpp:63