Coverage Report

Created: 2023-09-25 06:34

/src/botan/src/lib/utils/mem_ops.cpp
Line
Count
Source (jump to first uncovered line)
1
/*
2
* (C) 2017 Jack Lloyd
3
*
4
* Botan is released under the Simplified BSD License (see license.txt)
5
*/
6
7
#include <botan/mem_ops.h>
8
9
#include <botan/internal/ct_utils.h>
10
#include <botan/internal/safeint.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
14.2M
BOTAN_MALLOC_FN void* allocate_memory(size_t elems, size_t elem_size) {
21
14.2M
   if(elems == 0 || elem_size == 0) {
22
0
      return nullptr;
23
0
   }
24
25
   // Some calloc implementations do not check for overflow (?!?)
26
27
14.2M
   if(!BOTAN_CHECKED_MUL(elems, elem_size).has_value()) {
28
0
      throw std::bad_alloc();
29
0
   }
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
14.2M
   void* ptr = std::calloc(elems, elem_size);  // NOLINT(*-no-malloc)
41
14.2M
#endif
42
14.2M
   if(!ptr) {
43
0
      [[unlikely]] throw std::bad_alloc();
44
0
   }
45
14.2M
   return ptr;
46
14.2M
}
47
48
14.2M
void deallocate_memory(void* p, size_t elems, size_t elem_size) {
49
14.2M
   if(p == nullptr) {
50
0
      [[unlikely]] return;
51
0
   }
52
53
14.2M
   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
14.2M
   std::free(p);  // NOLINT(*-no-malloc)
62
14.2M
}
63
64
1
void initialize_allocator() {
65
#if defined(BOTAN_HAS_LOCKING_ALLOCATOR)
66
   mlock_allocator::instance();
67
#endif
68
1
}
69
70
1.71k
uint8_t ct_compare_u8(const uint8_t x[], const uint8_t y[], size_t len) {
71
1.71k
   volatile uint8_t difference = 0;
72
73
27.6k
   for(size_t i = 0; i != len; ++i) {
74
25.9k
      difference = difference | (x[i] ^ y[i]);
75
25.9k
   }
76
77
1.71k
   return CT::Mask<uint8_t>::is_zero(difference).value();
78
1.71k
}
79
80
}  // namespace Botan