Botan 3.9.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 <botan/internal/target_info.h>
12#include <cstdlib>
13#include <new>
14
15#if defined(BOTAN_HAS_LOCKING_ALLOCATOR)
16 #include <botan/internal/locking_allocator.h>
17#endif
18
19namespace Botan {
20
21BOTAN_MALLOC_FN void* allocate_memory(size_t elems, size_t elem_size) {
22 if(elems == 0 || elem_size == 0) {
23 return nullptr;
24 }
25
26 // Some calloc implementations do not check for overflow (?!?)
27 if(!checked_mul(elems, elem_size).has_value()) {
28 throw std::bad_alloc();
29 }
30
31#if defined(BOTAN_HAS_LOCKING_ALLOCATOR)
32 if(void* p = mlock_allocator::instance().allocate(elems, elem_size)) {
33 return p;
34 }
35#endif
36
37#if defined(BOTAN_TARGET_OS_HAS_ALLOC_CONCEAL)
38 void* ptr = ::calloc_conceal(elems, elem_size);
39#else
40 void* ptr = std::calloc(elems, elem_size); // NOLINT(*-no-malloc,*-owning-memory)
41#endif
42 if(ptr == nullptr) {
43 [[unlikely]] throw std::bad_alloc();
44 }
45 return ptr;
46}
47
48void deallocate_memory(void* p, size_t elems, size_t elem_size) {
49 if(p == nullptr) {
50 [[unlikely]] return;
51 }
52
53 secure_scrub_memory(p, elems * elem_size);
54
55#if defined(BOTAN_HAS_LOCKING_ALLOCATOR)
56 if(mlock_allocator::instance().deallocate(p, elems, elem_size)) {
57 return;
58 }
59#endif
60
61 std::free(p); // NOLINT(*-no-malloc,*-owning-memory)
62}
63
65#if defined(BOTAN_HAS_LOCKING_ALLOCATOR)
67#endif
68}
69
70} // namespace Botan
#define BOTAN_MALLOC_FN
Definition allocator.h:23
static mlock_allocator & instance() noexcept
void deallocate_memory(void *p, size_t elems, size_t elem_size)
Definition allocator.cpp:48
void secure_scrub_memory(void *ptr, size_t n)
Definition mem_utils.cpp:24
constexpr std::optional< T > checked_mul(T a, T b)
Definition int_utils.h:46
void initialize_allocator()
Definition allocator.cpp:64
BOTAN_MALLOC_FN void * allocate_memory(size_t elems, size_t elem_size)
Definition allocator.cpp:21