Coverage Report

Created: 2023-02-13 06:21

/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
#include <botan/internal/ct_utils.h>
9
#include <botan/internal/safeint.h>
10
#include <cstdlib>
11
#include <new>
12
13
#if defined(BOTAN_HAS_LOCKING_ALLOCATOR)
14
  #include <botan/internal/locking_allocator.h>
15
#endif
16
17
namespace Botan {
18
19
BOTAN_MALLOC_FN void* allocate_memory(size_t elems, size_t elem_size)
20
146M
   {
21
146M
   if(elems == 0 || elem_size == 0)
22
0
      return nullptr;
23
24
   // Some calloc implementations do not check for overflow (?!?)
25
26
146M
   if(!BOTAN_CHECKED_MUL(elems, elem_size).has_value())
27
0
      throw std::bad_alloc();
28
29
#if defined(BOTAN_HAS_LOCKING_ALLOCATOR)
30
   if(void* p = mlock_allocator::instance().allocate(elems, elem_size))
31
      return p;
32
#endif
33
34
#if defined(BOTAN_TARGET_OS_HAS_ALLOC_CONCEAL)
35
   void *ptr = ::calloc_conceal(elems, elem_size);
36
#else
37
146M
   void* ptr = std::calloc(elems, elem_size);
38
146M
#endif
39
146M
   if(!ptr) [[unlikely]]
40
0
      throw std::bad_alloc();
41
146M
   return ptr;
42
146M
   }
43
44
void deallocate_memory(void* p, size_t elems, size_t elem_size)
45
146M
   {
46
146M
   if(p == nullptr) [[unlikely]]
47
0
      return;
48
49
146M
   secure_scrub_memory(p, elems * elem_size);
50
51
#if defined(BOTAN_HAS_LOCKING_ALLOCATOR)
52
   if(mlock_allocator::instance().deallocate(p, elems, elem_size))
53
      return;
54
#endif
55
146M
   std::free(p);
56
146M
   }
57
58
void initialize_allocator()
59
8
   {
60
#if defined(BOTAN_HAS_LOCKING_ALLOCATOR)
61
   mlock_allocator::instance();
62
#endif
63
8
   }
64
65
uint8_t ct_compare_u8(const uint8_t x[],
66
                      const uint8_t y[],
67
                      size_t len)
68
7.63k
   {
69
7.63k
   volatile uint8_t difference = 0;
70
71
242k
   for(size_t i = 0; i != len; ++i)
72
234k
      difference = difference | (x[i] ^ y[i]);
73
74
7.63k
   return CT::Mask<uint8_t>::is_zero(difference).value();
75
7.63k
   }
76
77
}