Coverage Report

Created: 2025-12-31 06:08

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/botan/src/lib/utils/allocator.cpp
Line
Count
Source
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
19
namespace Botan {
20
21
1.13M
BOTAN_MALLOC_FN void* allocate_memory(size_t elems, size_t elem_size) {
22
1.13M
   if(elems == 0 || elem_size == 0) {
23
0
      return nullptr;
24
0
   }
25
26
   // Some calloc implementations do not check for overflow (?!?)
27
1.13M
   if(!checked_mul(elems, elem_size).has_value()) {
28
0
      throw std::bad_alloc();
29
0
   }
30
31
#if defined(BOTAN_HAS_LOCKING_ALLOCATOR)
32
   // NOLINTNEXTLINE(*-const-correctness) bug in clang-tidy
33
   if(void* p = mlock_allocator::instance().allocate(elems, elem_size)) {
34
      return p;
35
   }
36
#endif
37
38
#if defined(BOTAN_TARGET_OS_HAS_ALLOC_CONCEAL)
39
   void* ptr = ::calloc_conceal(elems, elem_size);
40
#else
41
   // NOLINTNEXTLINE(*-const-correctness) bug in clang-tidy
42
1.13M
   void* ptr = std::calloc(elems, elem_size);  // NOLINT(*-no-malloc,*-owning-memory)
43
1.13M
#endif
44
1.13M
   if(ptr == nullptr) {
45
0
      [[unlikely]] throw std::bad_alloc();
46
0
   }
47
1.13M
   return ptr;
48
1.13M
}
49
50
1.13M
void deallocate_memory(void* p, size_t elems, size_t elem_size) {
51
1.13M
   if(p == nullptr) {
52
0
      [[unlikely]] return;
53
0
   }
54
55
1.13M
   secure_scrub_memory(p, elems * elem_size);
56
57
#if defined(BOTAN_HAS_LOCKING_ALLOCATOR)
58
   if(mlock_allocator::instance().deallocate(p, elems, elem_size)) {
59
      return;
60
   }
61
#endif
62
63
1.13M
   std::free(p);  // NOLINT(*-no-malloc,*-owning-memory)
64
1.13M
}
65
66
2
void initialize_allocator() {
67
#if defined(BOTAN_HAS_LOCKING_ALLOCATOR)
68
   mlock_allocator::instance();
69
#endif
70
2
}
71
72
}  // namespace Botan