/src/botan/src/lib/utils/allocator.cpp
Line | Count | Source (jump to first uncovered line) |
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 | | |
18 | | namespace Botan { |
19 | | |
20 | 27.3M | BOTAN_MALLOC_FN void* allocate_memory(size_t elems, size_t elem_size) { |
21 | 27.3M | if(elems == 0 || elem_size == 0) { |
22 | 0 | return nullptr; |
23 | 0 | } |
24 | | |
25 | | // Some calloc implementations do not check for overflow (?!?) |
26 | 27.3M | if(!checked_mul(elems, elem_size).has_value()) { |
27 | 0 | throw std::bad_alloc(); |
28 | 0 | } |
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 | 27.3M | void* ptr = std::calloc(elems, elem_size); // NOLINT(*-no-malloc) |
40 | 27.3M | #endif |
41 | 27.3M | if(!ptr) { |
42 | 0 | [[unlikely]] throw std::bad_alloc(); |
43 | 0 | } |
44 | 27.3M | return ptr; |
45 | 27.3M | } |
46 | | |
47 | 27.3M | void deallocate_memory(void* p, size_t elems, size_t elem_size) { |
48 | 27.3M | if(p == nullptr) { |
49 | 0 | [[unlikely]] return; |
50 | 0 | } |
51 | | |
52 | 27.3M | 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 | 27.3M | std::free(p); // NOLINT(*-no-malloc) |
61 | 27.3M | } |
62 | | |
63 | 4 | void initialize_allocator() { |
64 | | #if defined(BOTAN_HAS_LOCKING_ALLOCATOR) |
65 | | mlock_allocator::instance(); |
66 | | #endif |
67 | 4 | } |
68 | | |
69 | | } // namespace Botan |