Crypto++  5.6.3
Free C++ class library of cryptographic schemes
secblock.h
Go to the documentation of this file.
1 // secblock.h - written and placed in the public domain by Wei Dai
2 
3 //! \file secblock.h
4 //! \brief Classes and functions for secure memory allocations.
5 
6 #ifndef CRYPTOPP_SECBLOCK_H
7 #define CRYPTOPP_SECBLOCK_H
8 
9 #include "config.h"
10 #include "stdcpp.h"
11 #include "misc.h"
12 
13 #if CRYPTOPP_MSC_VERSION
14 # pragma warning(push)
15 # pragma warning(disable: 4700)
16 # if (CRYPTOPP_MSC_VERSION >= 1400)
17 # pragma warning(disable: 6386)
18 # endif
19 #endif
20 
21 NAMESPACE_BEGIN(CryptoPP)
22 
23 // ************** secure memory allocation ***************
24 
25 //! \class AllocatorBase
26 //! \brief Base class for all allocators used by SecBlock
27 //! \tparam T the class or type
28 template<class T>
30 {
31 public:
32  typedef T value_type;
33  typedef size_t size_type;
34 #ifdef CRYPTOPP_MSVCRT6
35  typedef ptrdiff_t difference_type;
36 #else
37  typedef std::ptrdiff_t difference_type;
38 #endif
39  typedef T * pointer;
40  typedef const T * const_pointer;
41  typedef T & reference;
42  typedef const T & const_reference;
43 
44  pointer address(reference r) const {return (&r);}
45  const_pointer address(const_reference r) const {return (&r); }
46  void construct(pointer p, const T& val) {new (p) T(val);}
47  void destroy(pointer p) {CRYPTOPP_UNUSED(p); p->~T();}
48 
49  //! \brief Returns the maximum number of elements the allocator can provide
50  //! \returns the maximum number of elements the allocator can provide
51  //! \details Internally, preprocessor macros are used rather than std::numeric_limits
52  //! because the latter is \a not a \a constexpr. Some compilers, like Clang, do not
53  //! optimize it well under all circumstances. Compilers like GCC, ICC and MSVC appear
54  //! to optimize it well in either form.
55  size_type max_size() const {return (SIZE_MAX/sizeof(T));}
56 
57 #if defined(CRYPTOPP_CXX11_VARIADIC_TEMPLATES) || defined(CRYPTOPP_DOXYGEN_PROCESSING)
58 
59  //! \brief Constructs a new U using variadic arguments
60  //! \tparam U the type to be forwarded
61  //! \tparam Args the arguments to be forwarded
62  //! \param ptr pointer to type U
63  //! \param args variadic arguments
64  //! \details This is a C++11 feature. It is available when CRYPTOPP_CXX11_VARIADIC_TEMPLATES
65  //! is defined. The define is controlled by compiler versions detected in config.h.
66  template<typename U, typename... Args>
67  void construct(U* ptr, Args&&... args) {::new ((void*)ptr) U(std::forward<Args>(args)...);}
68 
69  //! \brief Destroys an U constructed with variadic arguments
70  //! \tparam U the type to be forwarded
71  //! \details This is a C++11 feature. It is available when CRYPTOPP_CXX11_VARIADIC_TEMPLATES
72  //! is defined. The define is controlled by compiler versions detected in config.h.
73  template<typename U>
74  void destroy(U* ptr) {if(ptr) ptr->~U();}
75 
76 #endif
77 
78 protected:
79 
80  //! \brief Verifies the allocator can satisfy a request based on size
81  //! \param size the number of elements
82  //! \throws InvalidArgument
83  //! \details CheckSize verifies the number of elements requested is valid.
84  //! \details If size is greater than max_size(), then InvalidArgument is thrown.
85  //! The library throws InvalidArgument if the size is too large to satisfy.
86  //! \details Internally, preprocessor macros are used rather than std::numeric_limits
87  //! because the latter is \a not a \a constexpr. Some compilers, like Clang, do not
88  //! optimize it well under all circumstances. Compilers like GCC, ICC and MSVC appear
89  //! to optimize it well in either form.
90  //! \note size is the count of elements, and not the number of bytes
91  static void CheckSize(size_t size)
92  {
93  // C++ throws std::bad_alloc (C++03) or std::bad_array_new_length (C++11) here.
94  if (size > (SIZE_MAX/sizeof(T)))
95  throw InvalidArgument("AllocatorBase: requested size would cause integer overflow");
96  }
97 };
98 
99 #define CRYPTOPP_INHERIT_ALLOCATOR_TYPES \
100 typedef typename AllocatorBase<T>::value_type value_type;\
101 typedef typename AllocatorBase<T>::size_type size_type;\
102 typedef typename AllocatorBase<T>::difference_type difference_type;\
103 typedef typename AllocatorBase<T>::pointer pointer;\
104 typedef typename AllocatorBase<T>::const_pointer const_pointer;\
105 typedef typename AllocatorBase<T>::reference reference;\
106 typedef typename AllocatorBase<T>::const_reference const_reference;
107 
108 //! \brief Reallocation function
109 //! \tparam T the class or type
110 //! \tparam A the class or type's allocator
111 //! \param alloc the allocator
112 //! \param oldPtr the previous allocation
113 //! \param oldSize the size of the previous allocation
114 //! \param newSize the new, requested size
115 //! \param preserve flag that indicates if the old allocation should be preserved
116 //! \note oldSize and newSize are the count of elements, and not the
117 //! number of bytes.
118 template <class T, class A>
119 typename A::pointer StandardReallocate(A& alloc, T *oldPtr, typename A::size_type oldSize, typename A::size_type newSize, bool preserve)
120 {
121  assert((oldPtr && oldSize) || !(oldPtr || oldSize));
122  if (oldSize == newSize)
123  return oldPtr;
124 
125  if (preserve)
126  {
127  typename A::pointer newPointer = alloc.allocate(newSize, NULL);
128  const size_t copySize = STDMIN(oldSize, newSize) * sizeof(T);
129 
130  if (oldPtr && newPointer) {memcpy_s(newPointer, copySize, oldPtr, copySize);}
131  alloc.deallocate(oldPtr, oldSize);
132  return newPointer;
133  }
134  else
135  {
136  alloc.deallocate(oldPtr, oldSize);
137  return alloc.allocate(newSize, NULL);
138  }
139 }
140 
141 //! \class AllocatorWithCleanup
142 //! \brief Allocates a block of memory with cleanup
143 //! \tparam T class or type
144 //! \tparam T_Align16 boolean that determines whether allocations should be aligned on 16-byte boundaries
145 //! \details If T_Align16 is true, then AllocatorWithCleanup calls AlignedAllocate()
146 //! for memory allocations. If T_Align16 is false, then AllocatorWithCleanup() calls
147 //! UnalignedAllocate() for memory allocations.
148 //! \details Template parameter T_Align16 is effectively controlled by cryptlib.h and mirrors
149 //! CRYPTOPP_BOOL_ALIGN16. CRYPTOPP_BOOL_ALIGN16 is often used as the template parameter.
150 template <class T, bool T_Align16 = false>
151 class AllocatorWithCleanup : public AllocatorBase<T>
152 {
153 public:
154  CRYPTOPP_INHERIT_ALLOCATOR_TYPES
155 
156  //! \brief Allocates a block of memory
157  //! \param ptr the size of the allocation
158  //! \param size the size of the allocation
159  //! \returns a memory block
160  //! \throws InvalidArgument
161  //! \details allocate() first checks the size of the request. If it is non-0
162  //! and less than max_size(), then an attempt is made to fulfill the request using either
163  //! AlignedAllocate() or UnalignedAllocate().
164  //! \details AlignedAllocate() is used if T_Align16 is true.
165  //! UnalignedAllocate() used if T_Align16 is false.
166  //! \details This is the C++ *Placement New* operator. ptr is not used, and the function
167  //! asserts in Debug builds if ptr is non-NULL.
168  //! \sa CallNewHandler() for the methods used to recover from a failed
169  //! allocation attempt.
170  //! \note size is the count of elements, and not the number of bytes
171  pointer allocate(size_type size, const void *ptr = NULL)
172  {
173  CRYPTOPP_UNUSED(ptr); assert(ptr == NULL);
174  this->CheckSize(size);
175  if (size == 0)
176  return NULL;
177 
178 #if CRYPTOPP_BOOL_ALIGN16
179  // TODO: should this need the test 'size*sizeof(T) >= 16'?
180  if (T_Align16 && size*sizeof(T) >= 16)
181  return (pointer)AlignedAllocate(size*sizeof(T));
182 #endif
183 
184  return (pointer)UnalignedAllocate(size*sizeof(T));
185  }
186 
187  //! \brief Deallocates a block of memory
188  //! \param ptr the size of the allocation
189  //! \param size the size of the allocation
190  //! \details Internally, SecureWipeArray() is called before deallocating the memory.
191  //! Once the memory block is wiped or zeroized, AlignedDeallocate() or
192  //! UnalignedDeallocate() is called.
193  //! \details AlignedDeallocate() is used if T_Align16 is true.
194  //! UnalignedDeallocate() used if T_Align16 is false.
195  void deallocate(void *ptr, size_type size)
196  {
197  assert((ptr && size) || !(ptr || size));
198  SecureWipeArray((pointer)ptr, size);
199 
200 #if CRYPTOPP_BOOL_ALIGN16
201  if (T_Align16 && size*sizeof(T) >= 16)
202  return AlignedDeallocate(ptr);
203 #endif
204 
205  UnalignedDeallocate(ptr);
206  }
207 
208  //! \brief Reallocates a block of memory
209  //! \param oldPtr the previous allocation
210  //! \param oldSize the size of the previous allocation
211  //! \param newSize the new, requested size
212  //! \param preserve flag that indicates if the old allocation should be preserved
213  //! \returns pointer to the new memory block
214  //! \details Internally, reallocate() calls StandardReallocate().
215  //! \details If preserve is true, then index 0 is used to begin copying the
216  //! old memory block to the new one. If the block grows, then the old array
217  //! is copied in its entirety. If the block shrinks, then only newSize
218  //! elements are copied from the old block to the new one.
219  //! \note oldSize and newSize are the count of elements, and not the
220  //! number of bytes.
221  pointer reallocate(T *oldPtr, size_type oldSize, size_type newSize, bool preserve)
222  {
223  assert((oldPtr && oldSize) || !(oldPtr || oldSize));
224  return StandardReallocate(*this, oldPtr, oldSize, newSize, preserve);
225  }
226 
227  // VS.NET STL enforces the policy of "All STL-compliant allocators have to provide a
228  // template class member called rebind".
229  template <class U> struct rebind { typedef AllocatorWithCleanup<U, T_Align16> other; };
230 #if _MSC_VER >= 1500
232  template <class U, bool A> AllocatorWithCleanup(const AllocatorWithCleanup<U, A> &) {}
233 #endif
234 };
235 
236 CRYPTOPP_DLL_TEMPLATE_CLASS AllocatorWithCleanup<byte>;
237 CRYPTOPP_DLL_TEMPLATE_CLASS AllocatorWithCleanup<word16>;
238 CRYPTOPP_DLL_TEMPLATE_CLASS AllocatorWithCleanup<word32>;
239 CRYPTOPP_DLL_TEMPLATE_CLASS AllocatorWithCleanup<word64>;
240 #if CRYPTOPP_BOOL_X86
241 CRYPTOPP_DLL_TEMPLATE_CLASS AllocatorWithCleanup<word, true>; // for Integer
242 #endif
243 
244 //! \class NullAllocator
245 //! \brief NULL allocator
246 //! \tparam T class or type
247 //! \details A NullAllocator is useful for fixed-size, stack based allocations
248 //! (i.e., static arrays used by FixedSizeAllocatorWithCleanup).
249 //! \details A NullAllocator always returns 0 for max_size(), and always returns
250 //! NULL for allocation requests. Though the allocator does not allocate at
251 //! runtime, it does perform a secure wipe or zeroization during cleanup.
252 template <class T>
253 class NullAllocator : public AllocatorBase<T>
254 {
255 public:
256  //LCOV_EXCL_START
257  CRYPTOPP_INHERIT_ALLOCATOR_TYPES
258 
259  // TODO: should this return NULL or throw bad_alloc? Non-Windows C++ standard
260  // libraries always throw. And late mode Windows throws. Early model Windows
261  // (circa VC++ 6.0) returned NULL.
262  pointer allocate(size_type n, const void* unused = NULL)
263  {
264  CRYPTOPP_UNUSED(n); CRYPTOPP_UNUSED(unused);
265  assert(false); return NULL;
266  }
267 
268  void deallocate(void *p, size_type n)
269  {
270  CRYPTOPP_UNUSED(p); CRYPTOPP_UNUSED(n);
271  assert(false);
272  }
273 
274  size_type max_size() const {return 0;}
275  //LCOV_EXCL_STOP
276 };
277 
278 //! \class FixedSizeAllocatorWithCleanup
279 //! \brief Static secure memory block with cleanup
280 //! \tparam T class or type
281 //! \tparam S fixed-size of the stack-based memory block
282 //! \tparam A AllocatorBase derived class for allocation and cleanup
283 //! \details FixedSizeAllocatorWithCleanup provides a fixed-size, stack-
284 //! based allocation at compile time. The class can grow its memory
285 //! block at runtime if a suitable allocator is available. If size
286 //! grows beyond S and a suitable allocator is available, then the
287 //! statically allocated array is obsoleted.
288 //! \note This allocator can't be used with standard collections because
289 //! they require that all objects of the same allocator type are equivalent.
290 template <class T, size_t S, class A = NullAllocator<T>, bool T_Align16 = false>
291 class FixedSizeAllocatorWithCleanup : public AllocatorBase<T>
292 {
293 public:
294  CRYPTOPP_INHERIT_ALLOCATOR_TYPES
295 
296  //! \brief Constructs a FixedSizeAllocatorWithCleanup
297  FixedSizeAllocatorWithCleanup() : m_allocated(false) {}
298 
299  //! \brief Allocates a block of memory
300  //! \param size size of the memory block
301  //! \details FixedSizeAllocatorWithCleanup provides a fixed-size, stack-
302  //! based allocation at compile time. If size is less than or equal to
303  //! S, then a pointer to the static array is returned.
304  //! \details The class can grow its memory block at runtime if a suitable
305  //! allocator is available. If size grows beyond S and a suitable
306  //! allocator is available, then the statically allocated array is
307  //! obsoleted. If a suitable allocator is \a not available, as with a
308  //! NullAllocator, then the function returns NULL and a runtime error
309  //! eventually occurs.
310  //! \note size is the count of elements, and not the number of bytes.
311  //! \sa reallocate(), SecBlockWithHint
312  pointer allocate(size_type size)
313  {
314  assert(IsAlignedOn(m_array, 8));
315 
316  if (size <= S && !m_allocated)
317  {
318  m_allocated = true;
319  return GetAlignedArray();
320  }
321  else
322  return m_fallbackAllocator.allocate(size);
323  }
324 
325  //! \brief Allocates a block of memory
326  //! \param size size of the memory block
327  //! \param hint an unused hint
328  //! \details FixedSizeAllocatorWithCleanup provides a fixed-size, stack-
329  //! based allocation at compile time. If size is less than or equal to
330  //! S, then a pointer to the static array is returned.
331  //! \details The class can grow its memory block at runtime if a suitable
332  //! allocator is available. If size grows beyond S and a suitable
333  //! allocator is available, then the statically allocated array is
334  //! obsoleted. If a suitable allocator is \a not available, as with a
335  //! NullAllocator, then the function returns NULL and a runtime error
336  //! eventually occurs.
337  //! \note size is the count of elements, and not the number of bytes.
338  //! \sa reallocate(), SecBlockWithHint
339  pointer allocate(size_type size, const void *hint)
340  {
341  if (size <= S && !m_allocated)
342  {
343  m_allocated = true;
344  return GetAlignedArray();
345  }
346  else
347  return m_fallbackAllocator.allocate(size, hint);
348  }
349 
350  //! \brief Deallocates a block of memory
351  //! \param ptr a pointer to the memory block to deallocate
352  //! \param size size of the memory block
353  //! \details The memory block is wiped or zeroized before deallocation.
354  //! If the statically allocated memory block is active, then no
355  //! additional actions are taken after the wipe.
356  //! \details If a dynamic memory block is active, then the pointer and
357  //! size are passed to the allocator for deallocation.
358  void deallocate(void *ptr, size_type size)
359  {
360  if (ptr == GetAlignedArray())
361  {
362  assert(size <= S);
363  assert(m_allocated);
364  m_allocated = false;
365  SecureWipeArray((pointer)ptr, size);
366  }
367  else
368  m_fallbackAllocator.deallocate(ptr, size);
369  }
370 
371  //! \brief Reallocates a block of memory
372  //! \param oldPtr the previous allocation
373  //! \param oldSize the size of the previous allocation
374  //! \param newSize the new, requested size
375  //! \param preserve flag that indicates if the old allocation should be preserved
376  //! \returns pointer to the new memory block
377  //! \details FixedSizeAllocatorWithCleanup provides a fixed-size, stack-
378  //! based allocation at compile time. If size is less than or equal to
379  //! S, then a pointer to the static array is returned.
380  //! \details The class can grow its memory block at runtime if a suitable
381  //! allocator is available. If size grows beyond S and a suitable
382  //! allocator is available, then the statically allocated array is
383  //! obsoleted. If a suitable allocator is \a not available, as with a
384  //! NullAllocator, then the function returns NULL and a runtime error
385  //! eventually occurs.
386  //! \note size is the count of elements, and not the number of bytes.
387  //! \sa reallocate(), SecBlockWithHint
388  pointer reallocate(pointer oldPtr, size_type oldSize, size_type newSize, bool preserve)
389  {
390  if (oldPtr == GetAlignedArray() && newSize <= S)
391  {
392  assert(oldSize <= S);
393  if (oldSize > newSize)
394  SecureWipeArray(oldPtr+newSize, oldSize-newSize);
395  return oldPtr;
396  }
397 
398  pointer newPointer = allocate(newSize, NULL);
399  if (preserve && newSize)
400  {
401  const size_t copySize = STDMIN(oldSize, newSize);
402  memcpy_s(newPointer, sizeof(T)*newSize, oldPtr, sizeof(T)*copySize);
403  }
404  deallocate(oldPtr, oldSize);
405  return newPointer;
406  }
407 
408  size_type max_size() const {return STDMAX(m_fallbackAllocator.max_size(), S);}
409 
410 private:
411 
412 #ifdef __BORLANDC__
413  T* GetAlignedArray() {return m_array;}
414  T m_array[S];
415 #else
416  T* GetAlignedArray() {return (CRYPTOPP_BOOL_ALIGN16 && T_Align16) ? (T*)(void *)(((byte *)m_array) + (0-(size_t)m_array)%16) : m_array;}
417  CRYPTOPP_ALIGN_DATA(8) T m_array[(CRYPTOPP_BOOL_ALIGN16 && T_Align16) ? S+8/sizeof(T) : S];
418 #endif
419 
420  A m_fallbackAllocator;
421  bool m_allocated;
422 };
423 
424 //! \class SecBlock
425 //! \brief Secure memory block with allocator and cleanup
426 //! \tparam T a class or type
427 //! \tparam A AllocatorWithCleanup derived class for allocation and cleanup
428 template <class T, class A = AllocatorWithCleanup<T> >
429 class SecBlock
430 {
431 public:
432  typedef typename A::value_type value_type;
433  typedef typename A::pointer iterator;
434  typedef typename A::const_pointer const_iterator;
435  typedef typename A::size_type size_type;
436 
437  //! \brief Construct a SecBlock with space for size elements.
438  //! \param size the number of elements in the allocation
439  //! \throws std::bad_alloc
440  //! \details The elements are not initialized.
441  //! \note size is the count of elements, and not the number of bytes
442  explicit SecBlock(size_type size=0)
443  : m_size(size), m_ptr(m_alloc.allocate(size, NULL)) { }
444 
445  //! \brief Copy construct a SecBlock from another SecBlock
446  //! \param t the other SecBlock
447  //! \throws std::bad_alloc
449  : m_size(t.m_size), m_ptr(m_alloc.allocate(t.m_size, NULL)) {
450  assert((!t.m_ptr && !m_size) || (t.m_ptr && m_size));
451  if (t.m_ptr) {memcpy_s(m_ptr, m_size*sizeof(T), t.m_ptr, t.m_size*sizeof(T));}
452  }
453 
454  //! \brief Construct a SecBlock from an array of elements.
455  //! \param ptr a pointer to an array of T
456  //! \param len the number of elements in the memory block
457  //! \throws std::bad_alloc
458  //! \details If <tt>ptr!=NULL</tt> and <tt>len!=0</tt>, then the block is initialized from the pointer ptr.
459  //! If <tt>ptr==NULL</tt> and <tt>len!=0</tt>, then the block is initialized to 0.
460  //! Otherwise, the block is empty and \a not initialized.
461  //! \note size is the count of elements, and not the number of bytes
462  SecBlock(const T *ptr, size_type len)
463  : m_size(len), m_ptr(m_alloc.allocate(len, NULL)) {
464  assert((!m_ptr && !m_size) || (m_ptr && m_size));
465  if (ptr && m_ptr)
466  memcpy_s(m_ptr, m_size*sizeof(T), ptr, len*sizeof(T));
467  else if (m_size)
468  memset(m_ptr, 0, m_size*sizeof(T));
469  }
470 
471  ~SecBlock()
472  {m_alloc.deallocate(m_ptr, m_size);}
473 
474 #ifdef __BORLANDC__
475  operator T *() const
476  {return (T*)m_ptr;}
477 #else
478  operator const void *() const
479  {return m_ptr;}
480  operator void *()
481  {return m_ptr;}
482 
483  operator const T *() const
484  {return m_ptr;}
485  operator T *()
486  {return m_ptr;}
487 #endif
488 
489  //! \brief Provides an iterator pointing to the first element in the memory block
490  //! \returns iterator pointing to the first element in the memory block
491  iterator begin()
492  {return m_ptr;}
493  //! \brief Provides a constant iterator pointing to the first element in the memory block
494  //! \returns constant iterator pointing to the first element in the memory block
495  const_iterator begin() const
496  {return m_ptr;}
497  //! \brief Provides an iterator pointing beyond the last element in the memory block
498  //! \returns iterator pointing beyond the last element in the memory block
499  iterator end()
500  {return m_ptr+m_size;}
501  //! \brief Provides a constant iterator pointing beyond the last element in the memory block
502  //! \returns constant iterator pointing beyond the last element in the memory block
503  const_iterator end() const
504  {return m_ptr+m_size;}
505 
506  //! \brief Provides a pointer to the first element in the memory block
507  //! \returns pointer to the first element in the memory block
508  typename A::pointer data() {return m_ptr;}
509  //! \brief Provides a pointer to the first element in the memory block
510  //! \returns constant pointer to the first element in the memory block
511  typename A::const_pointer data() const {return m_ptr;}
512 
513  //! \brief Provides the count of elements in the SecBlock
514  //! \returns number of elements in the memory block
515  //! \note the return value is the count of elements, and not the number of bytes
516  size_type size() const {return m_size;}
517  //! \brief Determines if the SecBlock is empty
518  //! \returns true if number of elements in the memory block is 0, false otherwise
519  bool empty() const {return m_size == 0;}
520 
521  //! \brief Provides a byte pointer to the first element in the memory block
522  //! \returns byte pointer to the first element in the memory block
523  byte * BytePtr() {return (byte *)m_ptr;}
524  //! \brief Return a byte pointer to the first element in the memory block
525  //! \returns constant byte pointer to the first element in the memory block
526  const byte * BytePtr() const {return (const byte *)m_ptr;}
527  //! \brief Provides the number of bytes in the SecBlock
528  //! \return the number of bytes in the memory block
529  //! \note the return value is the number of bytes, and not count of elements.
530  size_type SizeInBytes() const {return m_size*sizeof(T);}
531 
532  //! \brief Set contents and size from an array
533  //! \param ptr a pointer to an array of T
534  //! \param len the number of elements in the memory block
535  //! \details If the memory block is reduced in size, then the reclaimed memory is set to 0.
536  void Assign(const T *ptr, size_type len)
537  {
538  New(len);
539  if (m_ptr && ptr && len)
540  {memcpy_s(m_ptr, m_size*sizeof(T), ptr, len*sizeof(T));}
541  }
542 
543  //! \brief Copy contents from another SecBlock
544  //! \param t the other SecBlock
545  //! \details Assign checks for self assignment.
546  //! \details If the memory block is reduced in size, then the reclaimed memory is set to 0.
547  void Assign(const SecBlock<T, A> &t)
548  {
549  if (this != &t)
550  {
551  New(t.m_size);
552  if (m_ptr && t.m_ptr && t.m_size)
553  {memcpy_s(m_ptr, m_size*sizeof(T), t, t.m_size*sizeof(T));}
554  }
555  }
556 
557  //! \brief Assign contents from another SecBlock
558  //! \param t the other SecBlock
559  //! \details Internally, operator=() calls Assign().
560  //! \details If the memory block is reduced in size, then the reclaimed memory is set to 0.
562  {
563  // Assign guards for self-assignment
564  Assign(t);
565  return *this;
566  }
567 
568  //! \brief Append contents from another SecBlock
569  //! \param t the other SecBlock
570  //! \details Internally, this SecBlock calls Grow and then appends t.
572  {
573  assert((!t.m_ptr && !t.m_size) || (t.m_ptr && t.m_size));
574 
575  if(t.m_size)
576  {
577  const size_type oldSize = m_size;
578  if(this != &t) // s += t
579  {
580  Grow(m_size+t.m_size);
581  memcpy_s(m_ptr+oldSize, (m_size-oldSize)*sizeof(T), t.m_ptr, t.m_size*sizeof(T));
582  }
583  else // t += t
584  {
585  Grow(m_size*2);
586  memcpy_s(m_ptr+oldSize, (m_size-oldSize)*sizeof(T), m_ptr, oldSize*sizeof(T));
587  }
588  }
589  return *this;
590  }
591 
592  //! \brief Construct a SecBlock from this and another SecBlock
593  //! \param t the other SecBlock
594  //! \returns a newly constructed SecBlock that is a conacentation of this and t
595  //! \details Internally, a new SecBlock is created from this and a concatenation of t.
597  {
598  assert((!m_ptr && !m_size) || (m_ptr && m_size));
599  assert((!t.m_ptr && !t.m_size) || (t.m_ptr && t.m_size));
600  if(!t.m_size) return SecBlock(*this);
601 
602  SecBlock<T, A> result(m_size+t.m_size);
603  if(m_size) {memcpy_s(result.m_ptr, result.m_size*sizeof(T), m_ptr, m_size*sizeof(T));}
604  memcpy_s(result.m_ptr+m_size, (result.m_size-m_size)*sizeof(T), t.m_ptr, t.m_size*sizeof(T));
605  return result;
606  }
607 
608  //! \brief Bitwise compare two SecBlocks
609  //! \param t the other SecBlock
610  //! \returns true if the size and bits are equal, false otherwise
611  //! \details Uses a constant time compare if the arrays are equal size. The constant time
612  //! compare is VerifyBufsEqual() found in misc.h.
613  //! \sa operator!=()
614  bool operator==(const SecBlock<T, A> &t) const
615  {
616  return m_size == t.m_size &&
617  VerifyBufsEqual(reinterpret_cast<const byte*>(m_ptr), reinterpret_cast<const byte*>(t.m_ptr), m_size*sizeof(T));
618  }
619 
620  //! \brief Bitwise compare two SecBlocks
621  //! \param t the other SecBlock
622  //! \returns true if the size and bits are equal, false otherwise
623  //! \details Uses a constant time compare if the arrays are equal size. The constant time
624  //! compare is VerifyBufsEqual() found in misc.h.
625  //! \details Internally, operator!=() returns the inverse of operator==().
626  //! \sa operator==()
627  bool operator!=(const SecBlock<T, A> &t) const
628  {
629  return !operator==(t);
630  }
631 
632  //! \brief Change size without preserving contents
633  //! \param newSize the new size of the memory block
634  //! \details Old content is \a not preserved. If the memory block is reduced in size,
635  //! then the reclaimed memory is set to 0. If the memory block grows in size, then
636  //! the new memory is \a not initialized.
637  //! \details Internally, this SecBlock calls reallocate().
638  //! \sa New(), CleanNew(), Grow(), CleanGrow(), resize()
639  void New(size_type newSize)
640  {
641  m_ptr = m_alloc.reallocate(m_ptr, m_size, newSize, false);
642  m_size = newSize;
643  }
644 
645  //! \brief Change size without preserving contents
646  //! \param newSize the new size of the memory block
647  //! \details Old content is \a not preserved. If the memory block is reduced in size,
648  //! then the reclaimed content is set to 0. If the memory block grows in size, then
649  //! the new memory is initialized to 0.
650  //! \details Internally, this SecBlock calls New().
651  //! \sa New(), CleanNew(), Grow(), CleanGrow(), resize()
652  void CleanNew(size_type newSize)
653  {
654  New(newSize);
655  if (m_ptr) {memset_z(m_ptr, 0, m_size*sizeof(T));}
656  }
657 
658  //! \brief Change size and preserve contents
659  //! \param newSize the new size of the memory block
660  //! \details Old content is preserved. New content is not initialized.
661  //! \details Internally, this SecBlock calls reallocate() when size must increase. If the
662  //! size does not increase, then Grow() does not take action. If the size must
663  //! change, then use resize().
664  //! \sa New(), CleanNew(), Grow(), CleanGrow(), resize()
665  void Grow(size_type newSize)
666  {
667  if (newSize > m_size)
668  {
669  m_ptr = m_alloc.reallocate(m_ptr, m_size, newSize, true);
670  m_size = newSize;
671  }
672  }
673 
674  //! \brief Change size and preserve contents
675  //! \param newSize the new size of the memory block
676  //! \details Old content is preserved. New content is initialized to 0.
677  //! \details Internally, this SecBlock calls reallocate() when size must increase. If the
678  //! size does not increase, then CleanGrow() does not take action. If the size must
679  //! change, then use resize().
680  //! \sa New(), CleanNew(), Grow(), CleanGrow(), resize()
681  void CleanGrow(size_type newSize)
682  {
683  if (newSize > m_size)
684  {
685  m_ptr = m_alloc.reallocate(m_ptr, m_size, newSize, true);
686  memset_z(m_ptr+m_size, 0, (newSize-m_size)*sizeof(T));
687  m_size = newSize;
688  }
689  }
690 
691  //! \brief Change size and preserve contents
692  //! \param newSize the new size of the memory block
693  //! \details Old content is preserved. If the memory block grows in size, then
694  //! new memory is \a not initialized.
695  //! \details Internally, this SecBlock calls reallocate().
696  //! \sa New(), CleanNew(), Grow(), CleanGrow(), resize()
697  void resize(size_type newSize)
698  {
699  m_ptr = m_alloc.reallocate(m_ptr, m_size, newSize, true);
700  m_size = newSize;
701  }
702 
703  //! \brief Swap contents with another SecBlock
704  //! \param b the other SecBlock
705  //! \details Internally, std::swap() is called on m_alloc, m_size and m_ptr.
707  {
708  // Swap must occur on the allocator in case its FixedSize that spilled into the heap.
709  std::swap(m_alloc, b.m_alloc);
710  std::swap(m_size, b.m_size);
711  std::swap(m_ptr, b.m_ptr);
712  }
713 
714 // protected:
715  A m_alloc;
716  size_type m_size;
717  T *m_ptr;
718 };
719 
720 #ifdef CRYPTOPP_DOXYGEN_PROCESSING
721 //! \class SecByteBlock
722 //! \brief \ref SecBlock "SecBlock<byte>" typedef.
723 class SecByteBlock : public SecBlock<byte> {};
724 //! \class SecWordBlock
725 //! \brief \ref SecBlock "SecBlock<word>" typedef.
726 class SecWordBlock : public SecBlock<word> {};
727 //! \class AlignedSecByteBlock
728 //! \brief SecBlock using \ref AllocatorWithCleanup "AllocatorWithCleanup<byte, true>" typedef
729 class AlignedSecByteBlock : public SecBlock<byte, AllocatorWithCleanup<byte, true> > {};
730 #else
734 #endif
735 
736 // No need for move semantics on derived class *if* the class does not add any
737 // data members; see http://stackoverflow.com/q/31755703, and Rule of {0|3|5}.
738 
739 //! \class FixedSizeSecBlock
740 //! \brief Fixed size stack-based SecBlock
741 //! \tparam T class or type
742 //! \tparam S fixed-size of the stack-based memory block
743 //! \tparam A AllocatorBase derived class for allocation and cleanup
744 template <class T, unsigned int S, class A = FixedSizeAllocatorWithCleanup<T, S> >
745 class FixedSizeSecBlock : public SecBlock<T, A>
746 {
747 public:
748  //! \brief Construct a FixedSizeSecBlock
749  explicit FixedSizeSecBlock() : SecBlock<T, A>(S) {}
750 };
751 
752 //! \class FixedSizeAlignedSecBlock
753 //! \brief Fixed size stack-based SecBlock with 16-byte alignment
754 //! \tparam T class or type
755 //! \tparam S fixed-size of the stack-based memory block
756 //! \tparam A AllocatorBase derived class for allocation and cleanup
757 template <class T, unsigned int S, bool T_Align16 = true>
758 class FixedSizeAlignedSecBlock : public FixedSizeSecBlock<T, S, FixedSizeAllocatorWithCleanup<T, S, NullAllocator<T>, T_Align16> >
759 {
760 };
761 
762 //! \class SecBlockWithHint
763 //! \brief Stack-based SecBlock that grows into the heap
764 //! \tparam T class or type
765 //! \tparam S fixed-size of the stack-based memory block
766 //! \tparam A AllocatorBase derived class for allocation and cleanup
767 template <class T, unsigned int S, class A = FixedSizeAllocatorWithCleanup<T, S, AllocatorWithCleanup<T> > >
768 class SecBlockWithHint : public SecBlock<T, A>
769 {
770 public:
771  //! construct a SecBlockWithHint with a count of elements
772  explicit SecBlockWithHint(size_t size) : SecBlock<T, A>(size) {}
773 };
774 
775 template<class T, bool A, class U, bool B>
776 inline bool operator==(const CryptoPP::AllocatorWithCleanup<T, A>&, const CryptoPP::AllocatorWithCleanup<U, B>&) {return (true);}
777 template<class T, bool A, class U, bool B>
778 inline bool operator!=(const CryptoPP::AllocatorWithCleanup<T, A>&, const CryptoPP::AllocatorWithCleanup<U, B>&) {return (false);}
779 
780 NAMESPACE_END
781 
782 NAMESPACE_BEGIN(std)
783 template <class T, class A>
784 inline void swap(CryptoPP::SecBlock<T, A> &a, CryptoPP::SecBlock<T, A> &b)
785 {
786  a.swap(b);
787 }
788 
789 #if defined(_STLP_DONT_SUPPORT_REBIND_MEMBER_TEMPLATE) || (defined(_STLPORT_VERSION) && !defined(_STLP_MEMBER_TEMPLATE_CLASSES))
790 // working for STLport 5.1.3 and MSVC 6 SP5
791 template <class _Tp1, class _Tp2>
792 inline CryptoPP::AllocatorWithCleanup<_Tp2>&
793 __stl_alloc_rebind(CryptoPP::AllocatorWithCleanup<_Tp1>& __a, const _Tp2*)
794 {
795  return (CryptoPP::AllocatorWithCleanup<_Tp2>&)(__a);
796 }
797 #endif
798 
799 NAMESPACE_END
800 
801 #if CRYPTOPP_MSC_VERSION
802 # pragma warning(pop)
803 #endif
804 
805 #endif
iterator end()
Provides an iterator pointing beyond the last element in the memory block.
Definition: secblock.h:499
An invalid argument was detected.
Definition: cryptlib.h:182
Base class for all allocators used by SecBlock.
Definition: secblock.h:29
void swap(SecBlock< T, A > &b)
Swap contents with another SecBlock.
Definition: secblock.h:706
Stack-based SecBlock that grows into the heap.
Definition: secblock.h:768
void destroy(U *ptr)
Destroys an U constructed with variadic arguments.
Definition: secblock.h:74
Utility functions for the Crypto++ library.
void construct(U *ptr, Args &&...args)
Constructs a new U using variadic arguments.
Definition: secblock.h:67
void AlignedDeallocate(void *ptr)
Frees a buffer allocated with AlignedAllocate.
FixedSizeSecBlock()
Construct a FixedSizeSecBlock.
Definition: secblock.h:749
void CleanNew(size_type newSize)
Change size without preserving contents.
Definition: secblock.h:652
bool operator!=(const SecBlock< T, A > &t) const
Bitwise compare two SecBlocks.
Definition: secblock.h:627
A::const_pointer data() const
Provides a pointer to the first element in the memory block.
Definition: secblock.h:511
bool empty() const
Determines if the SecBlock is empty.
Definition: secblock.h:519
SecBlock< T, A > & operator=(const SecBlock< T, A > &t)
Assign contents from another SecBlock.
Definition: secblock.h:561
void resize(size_type newSize)
Change size and preserve contents.
Definition: secblock.h:697
SecBlock< T, A > & operator+=(const SecBlock< T, A > &t)
Append contents from another SecBlock.
Definition: secblock.h:571
void CleanGrow(size_type newSize)
Change size and preserve contents.
Definition: secblock.h:681
void Assign(const SecBlock< T, A > &t)
Copy contents from another SecBlock.
Definition: secblock.h:547
SecBlock< T, A > operator+(const SecBlock< T, A > &t)
Construct a SecBlock from this and another SecBlock.
Definition: secblock.h:596
SecBlock(size_type size=0)
Construct a SecBlock with space for size elements.
Definition: secblock.h:442
const_iterator begin() const
Provides a constant iterator pointing to the first element in the memory block.
Definition: secblock.h:495
Secure memory block with allocator and cleanup.
Definition: secblock.h:429
void memcpy_s(void *dest, size_t sizeInBytes, const void *src, size_t count)
Bounds checking replacement for memcpy()
Definition: misc.h:301
size_type size() const
Provides the count of elements in the SecBlock.
Definition: secblock.h:516
Library configuration file.
STL namespace.
pointer allocate(size_type size, const void *hint)
Allocates a block of memory.
Definition: secblock.h:339
void New(size_type newSize)
Change size without preserving contents.
Definition: secblock.h:639
SecBlock typedef.
Definition: secblock.h:723
pointer reallocate(T *oldPtr, size_type oldSize, size_type newSize, bool preserve)
Reallocates a block of memory.
Definition: secblock.h:221
size_type max_size() const
Returns the maximum number of elements the allocator can provide.
Definition: secblock.h:55
Static secure memory block with cleanup.
Definition: secblock.h:291
Allocates a block of memory with cleanup.
Definition: secblock.h:151
void deallocate(void *ptr, size_type size)
Deallocates a block of memory.
Definition: secblock.h:358
void SecureWipeArray(T *buf, size_t n)
Sets each element of an array to 0.
Definition: misc.h:1050
bool IsAlignedOn(const void *ptr, unsigned int alignment)
Determines whether ptr is aligned to a minimum value.
Definition: misc.h:811
const_iterator end() const
Provides a constant iterator pointing beyond the last element in the memory block.
Definition: secblock.h:503
void * UnalignedAllocate(size_t size)
Allocates a buffer.
Definition: misc.cpp:253
A::pointer data()
Provides a pointer to the first element in the memory block.
Definition: secblock.h:508
void Assign(const T *ptr, size_type len)
Set contents and size from an array.
Definition: secblock.h:536
pointer reallocate(pointer oldPtr, size_type oldSize, size_type newSize, bool preserve)
Reallocates a block of memory.
Definition: secblock.h:388
Fixed size stack-based SecBlock with 16-byte alignment.
Definition: secblock.h:758
SecBlock using AllocatorWithCleanup typedef.
Definition: secblock.h:729
pointer allocate(size_type size, const void *ptr=NULL)
Allocates a block of memory.
Definition: secblock.h:171
Fixed size stack-based SecBlock.
Definition: secblock.h:745
SecBlock(const SecBlock< T, A > &t)
Copy construct a SecBlock from another SecBlock.
Definition: secblock.h:448
void * memset_z(void *ptr, int value, size_t num)
Memory block initializer and eraser that attempts to survive optimizations.
Definition: misc.h:381
const T & STDMIN(const T &a, const T &b)
Replacement function for std::min.
Definition: misc.h:397
void deallocate(void *ptr, size_type size)
Deallocates a block of memory.
Definition: secblock.h:195
iterator begin()
Provides an iterator pointing to the first element in the memory block.
Definition: secblock.h:491
const byte * BytePtr() const
Return a byte pointer to the first element in the memory block.
Definition: secblock.h:526
NULL allocator.
Definition: secblock.h:253
SecBlockWithHint(size_t size)
construct a SecBlockWithHint with a count of elements
Definition: secblock.h:772
A::pointer StandardReallocate(A &alloc, T *oldPtr, typename A::size_type oldSize, typename A::size_type newSize, bool preserve)
Reallocation function.
Definition: secblock.h:119
bool VerifyBufsEqual(const byte *buf1, const byte *buf2, size_t count)
Performs a near constant-time comparison of two equally sized buffers.
Definition: misc.cpp:96
SecBlock(const T *ptr, size_type len)
Construct a SecBlock from an array of elements.
Definition: secblock.h:462
pointer allocate(size_type size)
Allocates a block of memory.
Definition: secblock.h:312
const T & STDMAX(const T &a, const T &b)
Replacement function for std::max.
Definition: misc.h:407
void Grow(size_type newSize)
Change size and preserve contents.
Definition: secblock.h:665
Crypto++ library namespace.
bool operator==(const SecBlock< T, A > &t) const
Bitwise compare two SecBlocks.
Definition: secblock.h:614
size_type SizeInBytes() const
Provides the number of bytes in the SecBlock.
Definition: secblock.h:530
FixedSizeAllocatorWithCleanup()
Constructs a FixedSizeAllocatorWithCleanup.
Definition: secblock.h:297
void UnalignedDeallocate(void *ptr)
Frees a buffer allocated with UnalignedAllocate.
Definition: misc.cpp:261
SecBlock typedef.
Definition: secblock.h:726
void * AlignedAllocate(size_t size)
Allocates a buffer on 16-byte boundary.
#define SIZE_MAX
The maximum value of a machine word.
Definition: misc.h:74
byte * BytePtr()
Provides a byte pointer to the first element in the memory block.
Definition: secblock.h:523