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 size of the allocation, in 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, in elements
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 pointer for the allocation
189  //! \param size the size of the allocation, in elements
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  //! \brief Template class memeber Rebind
228  //! \tparam T allocated class or type
229  //! \tparam T_Align16 boolean that determines whether allocations should be aligned on 16-byte boundaries
230  //! \tparam U bound class or type
231  //! \details Rebind allows a container class to allocate a different type of object
232  //! to store elements. For example, a std::list will allocate std::list_node to
233  //! store elements in the list.
234  //! \details VS.NET STL enforces the policy of "All STL-compliant allocators
235  //! have to provide a template class member called rebind".
236  template <class U> struct rebind { typedef AllocatorWithCleanup<U, T_Align16> other; };
237 #if _MSC_VER >= 1500
239  template <class U, bool A> AllocatorWithCleanup(const AllocatorWithCleanup<U, A> &) {}
240 #endif
241 };
242 
243 CRYPTOPP_DLL_TEMPLATE_CLASS AllocatorWithCleanup<byte>;
244 CRYPTOPP_DLL_TEMPLATE_CLASS AllocatorWithCleanup<word16>;
245 CRYPTOPP_DLL_TEMPLATE_CLASS AllocatorWithCleanup<word32>;
246 CRYPTOPP_DLL_TEMPLATE_CLASS AllocatorWithCleanup<word64>;
247 #if CRYPTOPP_BOOL_X86
248 CRYPTOPP_DLL_TEMPLATE_CLASS AllocatorWithCleanup<word, true>; // for Integer
249 #endif
250 
251 //! \class NullAllocator
252 //! \brief NULL allocator
253 //! \tparam T class or type
254 //! \details A NullAllocator is useful for fixed-size, stack based allocations
255 //! (i.e., static arrays used by FixedSizeAllocatorWithCleanup).
256 //! \details A NullAllocator always returns 0 for max_size(), and always returns
257 //! NULL for allocation requests. Though the allocator does not allocate at
258 //! runtime, it does perform a secure wipe or zeroization during cleanup.
259 template <class T>
260 class NullAllocator : public AllocatorBase<T>
261 {
262 public:
263  //LCOV_EXCL_START
264  CRYPTOPP_INHERIT_ALLOCATOR_TYPES
265 
266  // TODO: should this return NULL or throw bad_alloc? Non-Windows C++ standard
267  // libraries always throw. And late mode Windows throws. Early model Windows
268  // (circa VC++ 6.0) returned NULL.
269  pointer allocate(size_type n, const void* unused = NULL)
270  {
271  CRYPTOPP_UNUSED(n); CRYPTOPP_UNUSED(unused);
272  assert(false); return NULL;
273  }
274 
275  void deallocate(void *p, size_type n)
276  {
277  CRYPTOPP_UNUSED(p); CRYPTOPP_UNUSED(n);
278  assert(false);
279  }
280 
281  size_type max_size() const {return 0;}
282  //LCOV_EXCL_STOP
283 };
284 
285 //! \class FixedSizeAllocatorWithCleanup
286 //! \brief Static secure memory block with cleanup
287 //! \tparam T class or type
288 //! \tparam S fixed-size of the stack-based memory block, in elements
289 //! \tparam A AllocatorBase derived class for allocation and cleanup
290 //! \details FixedSizeAllocatorWithCleanup provides a fixed-size, stack-
291 //! based allocation at compile time. The class can grow its memory
292 //! block at runtime if a suitable allocator is available. If size
293 //! grows beyond S and a suitable allocator is available, then the
294 //! statically allocated array is obsoleted.
295 //! \note This allocator can't be used with standard collections because
296 //! they require that all objects of the same allocator type are equivalent.
297 template <class T, size_t S, class A = NullAllocator<T>, bool T_Align16 = false>
298 class FixedSizeAllocatorWithCleanup : public AllocatorBase<T>
299 {
300 public:
301  CRYPTOPP_INHERIT_ALLOCATOR_TYPES
302 
303  //! \brief Constructs a FixedSizeAllocatorWithCleanup
304  FixedSizeAllocatorWithCleanup() : m_allocated(false) {}
305 
306  //! \brief Allocates a block of memory
307  //! \param size size of the memory block, in elements
308  //! \details FixedSizeAllocatorWithCleanup provides a fixed-size, stack-based
309  //! allocation at compile time. If size is less than or equal to
310  //! <tt>S</tt>, then a pointer to the static array is returned.
311  //! \details The class can grow its memory block at runtime if a suitable
312  //! allocator is available. If size grows beyond S and a suitable
313  //! allocator is available, then the statically allocated array is
314  //! obsoleted. If a suitable allocator is \a not available, as with a
315  //! NullAllocator, then the function returns NULL and a runtime error
316  //! eventually occurs.
317  //! \sa reallocate(), SecBlockWithHint
318  pointer allocate(size_type size)
319  {
320  assert(IsAlignedOn(m_array, 8));
321 
322  if (size <= S && !m_allocated)
323  {
324  m_allocated = true;
325  return GetAlignedArray();
326  }
327  else
328  return m_fallbackAllocator.allocate(size);
329  }
330 
331  //! \brief Allocates a block of memory
332  //! \param size size of the memory block, in elements
333  //! \param hint an unused hint
334  //! \details FixedSizeAllocatorWithCleanup provides a fixed-size, stack-
335  //! based allocation at compile time. If size is less than or equal to
336  //! S, then a pointer to the static array is returned.
337  //! \details The class can grow its memory block at runtime if a suitable
338  //! allocator is available. If size grows beyond S and a suitable
339  //! allocator is available, then the statically allocated array is
340  //! obsoleted. If a suitable allocator is \a not available, as with a
341  //! NullAllocator, then the function returns NULL and a runtime error
342  //! eventually occurs.
343  //! \sa reallocate(), SecBlockWithHint
344  pointer allocate(size_type size, const void *hint)
345  {
346  if (size <= S && !m_allocated)
347  {
348  m_allocated = true;
349  return GetAlignedArray();
350  }
351  else
352  return m_fallbackAllocator.allocate(size, hint);
353  }
354 
355  //! \brief Deallocates a block of memory
356  //! \param ptr a pointer to the memory block to deallocate
357  //! \param size size of the memory block, in elements
358  //! \details The memory block is wiped or zeroized before deallocation.
359  //! If the statically allocated memory block is active, then no
360  //! additional actions are taken after the wipe.
361  //! \details If a dynamic memory block is active, then the pointer and
362  //! size are passed to the allocator for deallocation.
363  void deallocate(void *ptr, size_type size)
364  {
365  if (ptr == GetAlignedArray())
366  {
367  assert(size <= S);
368  assert(m_allocated);
369  m_allocated = false;
370  SecureWipeArray((pointer)ptr, size);
371  }
372  else
373  m_fallbackAllocator.deallocate(ptr, size);
374  }
375 
376  //! \brief Reallocates a block of memory
377  //! \param oldPtr the previous allocation
378  //! \param oldSize the size of the previous allocation
379  //! \param newSize the new, requested size
380  //! \param preserve flag that indicates if the old allocation should be preserved
381  //! \returns pointer to the new memory block
382  //! \details FixedSizeAllocatorWithCleanup provides a fixed-size, stack-
383  //! based allocation at compile time. If size is less than or equal to
384  //! S, then a pointer to the static array is returned.
385  //! \details The class can grow its memory block at runtime if a suitable
386  //! allocator is available. If size grows beyond S and a suitable
387  //! allocator is available, then the statically allocated array is
388  //! obsoleted. If a suitable allocator is \a not available, as with a
389  //! NullAllocator, then the function returns NULL and a runtime error
390  //! eventually occurs.
391  //! \note size is the count of elements, and not the number of bytes.
392  //! \sa reallocate(), SecBlockWithHint
393  pointer reallocate(pointer oldPtr, size_type oldSize, size_type newSize, bool preserve)
394  {
395  if (oldPtr == GetAlignedArray() && newSize <= S)
396  {
397  assert(oldSize <= S);
398  if (oldSize > newSize)
399  SecureWipeArray(oldPtr+newSize, oldSize-newSize);
400  return oldPtr;
401  }
402 
403  pointer newPointer = allocate(newSize, NULL);
404  if (preserve && newSize)
405  {
406  const size_t copySize = STDMIN(oldSize, newSize);
407  memcpy_s(newPointer, sizeof(T)*newSize, oldPtr, sizeof(T)*copySize);
408  }
409  deallocate(oldPtr, oldSize);
410  return newPointer;
411  }
412 
413  size_type max_size() const {return STDMAX(m_fallbackAllocator.max_size(), S);}
414 
415 private:
416 
417 #ifdef __BORLANDC__
418  T* GetAlignedArray() {return m_array;}
419  T m_array[S];
420 #else
421  T* GetAlignedArray() {return (CRYPTOPP_BOOL_ALIGN16 && T_Align16) ? (T*)(void *)(((byte *)m_array) + (0-(size_t)m_array)%16) : m_array;}
422  CRYPTOPP_ALIGN_DATA(8) T m_array[(CRYPTOPP_BOOL_ALIGN16 && T_Align16) ? S+8/sizeof(T) : S];
423 #endif
424 
425  A m_fallbackAllocator;
426  bool m_allocated;
427 };
428 
429 //! \class SecBlock
430 //! \brief Secure memory block with allocator and cleanup
431 //! \tparam T a class or type
432 //! \tparam A AllocatorWithCleanup derived class for allocation and cleanup
433 template <class T, class A = AllocatorWithCleanup<T> >
434 class SecBlock
435 {
436 public:
437  typedef typename A::value_type value_type;
438  typedef typename A::pointer iterator;
439  typedef typename A::const_pointer const_iterator;
440  typedef typename A::size_type size_type;
441 
442  //! \brief Construct a SecBlock with space for size elements.
443  //! \param size the size of the allocation, in elements
444  //! \throws std::bad_alloc
445  //! \details The elements are not initialized.
446  //! \note size is the count of elements, and not the number of bytes
447  explicit SecBlock(size_type size=0)
448  : m_size(size), m_ptr(m_alloc.allocate(size, NULL)) { }
449 
450  //! \brief Copy construct a SecBlock from another SecBlock
451  //! \param t the other SecBlock
452  //! \throws std::bad_alloc
454  : m_size(t.m_size), m_ptr(m_alloc.allocate(t.m_size, NULL)) {
455  assert((!t.m_ptr && !m_size) || (t.m_ptr && m_size));
456  if (t.m_ptr) {memcpy_s(m_ptr, m_size*sizeof(T), t.m_ptr, t.m_size*sizeof(T));}
457  }
458 
459  //! \brief Construct a SecBlock from an array of elements.
460  //! \param ptr a pointer to an array of T
461  //! \param len the number of elements in the memory block
462  //! \throws std::bad_alloc
463  //! \details If <tt>ptr!=NULL</tt> and <tt>len!=0</tt>, then the block is initialized from the pointer ptr.
464  //! If <tt>ptr==NULL</tt> and <tt>len!=0</tt>, then the block is initialized to 0.
465  //! Otherwise, the block is empty and \a not initialized.
466  //! \note size is the count of elements, and not the number of bytes
467  SecBlock(const T *ptr, size_type len)
468  : m_size(len), m_ptr(m_alloc.allocate(len, NULL)) {
469  assert((!m_ptr && !m_size) || (m_ptr && m_size));
470  if (ptr && m_ptr)
471  memcpy_s(m_ptr, m_size*sizeof(T), ptr, len*sizeof(T));
472  else if (m_size)
473  memset(m_ptr, 0, m_size*sizeof(T));
474  }
475 
476  ~SecBlock()
477  {m_alloc.deallocate(m_ptr, m_size);}
478 
479 #ifdef __BORLANDC__
480  operator T *() const
481  {return (T*)m_ptr;}
482 #else
483  operator const void *() const
484  {return m_ptr;}
485  operator void *()
486  {return m_ptr;}
487 
488  operator const T *() const
489  {return m_ptr;}
490  operator T *()
491  {return m_ptr;}
492 #endif
493 
494  //! \brief Provides an iterator pointing to the first element in the memory block
495  //! \returns iterator pointing to the first element in the memory block
496  iterator begin()
497  {return m_ptr;}
498  //! \brief Provides a constant iterator pointing to the first element in the memory block
499  //! \returns constant iterator pointing to the first element in the memory block
500  const_iterator begin() const
501  {return m_ptr;}
502  //! \brief Provides an iterator pointing beyond the last element in the memory block
503  //! \returns iterator pointing beyond the last element in the memory block
504  iterator end()
505  {return m_ptr+m_size;}
506  //! \brief Provides a constant iterator pointing beyond the last element in the memory block
507  //! \returns constant iterator pointing beyond the last element in the memory block
508  const_iterator end() const
509  {return m_ptr+m_size;}
510 
511  //! \brief Provides a pointer to the first element in the memory block
512  //! \returns pointer to the first element in the memory block
513  typename A::pointer data() {return m_ptr;}
514  //! \brief Provides a pointer to the first element in the memory block
515  //! \returns constant pointer to the first element in the memory block
516  typename A::const_pointer data() const {return m_ptr;}
517 
518  //! \brief Provides the count of elements in the SecBlock
519  //! \returns number of elements in the memory block
520  //! \note the return value is the count of elements, and not the number of bytes
521  size_type size() const {return m_size;}
522  //! \brief Determines if the SecBlock is empty
523  //! \returns true if number of elements in the memory block is 0, false otherwise
524  bool empty() const {return m_size == 0;}
525 
526  //! \brief Provides a byte pointer to the first element in the memory block
527  //! \returns byte pointer to the first element in the memory block
528  byte * BytePtr() {return (byte *)m_ptr;}
529  //! \brief Return a byte pointer to the first element in the memory block
530  //! \returns constant byte pointer to the first element in the memory block
531  const byte * BytePtr() const {return (const byte *)m_ptr;}
532  //! \brief Provides the number of bytes in the SecBlock
533  //! \return the number of bytes in the memory block
534  //! \note the return value is the number of bytes, and not count of elements.
535  size_type SizeInBytes() const {return m_size*sizeof(T);}
536 
537  //! \brief Set contents and size from an array
538  //! \param ptr a pointer to an array of T
539  //! \param len the number of elements in the memory block
540  //! \details If the memory block is reduced in size, then the reclaimed memory is set to 0.
541  void Assign(const T *ptr, size_type len)
542  {
543  New(len);
544  if (m_ptr && ptr && len)
545  {memcpy_s(m_ptr, m_size*sizeof(T), ptr, len*sizeof(T));}
546  }
547 
548  //! \brief Copy contents from another SecBlock
549  //! \param t the other SecBlock
550  //! \details Assign checks for self assignment.
551  //! \details If the memory block is reduced in size, then the reclaimed memory is set to 0.
552  void Assign(const SecBlock<T, A> &t)
553  {
554  if (this != &t)
555  {
556  New(t.m_size);
557  if (m_ptr && t.m_ptr && t.m_size)
558  {memcpy_s(m_ptr, m_size*sizeof(T), t, t.m_size*sizeof(T));}
559  }
560  }
561 
562  //! \brief Assign contents from another SecBlock
563  //! \param t the other SecBlock
564  //! \details Internally, operator=() calls Assign().
565  //! \details If the memory block is reduced in size, then the reclaimed memory is set to 0.
567  {
568  // Assign guards for self-assignment
569  Assign(t);
570  return *this;
571  }
572 
573  //! \brief Append contents from another SecBlock
574  //! \param t the other SecBlock
575  //! \details Internally, this SecBlock calls Grow and then appends t.
577  {
578  assert((!t.m_ptr && !t.m_size) || (t.m_ptr && t.m_size));
579 
580  if(t.m_size)
581  {
582  const size_type oldSize = m_size;
583  if(this != &t) // s += t
584  {
585  Grow(m_size+t.m_size);
586  memcpy_s(m_ptr+oldSize, (m_size-oldSize)*sizeof(T), t.m_ptr, t.m_size*sizeof(T));
587  }
588  else // t += t
589  {
590  Grow(m_size*2);
591  memcpy_s(m_ptr+oldSize, (m_size-oldSize)*sizeof(T), m_ptr, oldSize*sizeof(T));
592  }
593  }
594  return *this;
595  }
596 
597  //! \brief Construct a SecBlock from this and another SecBlock
598  //! \param t the other SecBlock
599  //! \returns a newly constructed SecBlock that is a conacentation of this and t
600  //! \details Internally, a new SecBlock is created from this and a concatenation of t.
602  {
603  assert((!m_ptr && !m_size) || (m_ptr && m_size));
604  assert((!t.m_ptr && !t.m_size) || (t.m_ptr && t.m_size));
605  if(!t.m_size) return SecBlock(*this);
606 
607  SecBlock<T, A> result(m_size+t.m_size);
608  if(m_size) {memcpy_s(result.m_ptr, result.m_size*sizeof(T), m_ptr, m_size*sizeof(T));}
609  memcpy_s(result.m_ptr+m_size, (result.m_size-m_size)*sizeof(T), t.m_ptr, t.m_size*sizeof(T));
610  return result;
611  }
612 
613  //! \brief Bitwise compare two SecBlocks
614  //! \param t the other SecBlock
615  //! \returns true if the size and bits are equal, false otherwise
616  //! \details Uses a constant time compare if the arrays are equal size. The constant time
617  //! compare is VerifyBufsEqual() found in misc.h.
618  //! \sa operator!=()
619  bool operator==(const SecBlock<T, A> &t) const
620  {
621  return m_size == t.m_size &&
622  VerifyBufsEqual(reinterpret_cast<const byte*>(m_ptr), reinterpret_cast<const byte*>(t.m_ptr), m_size*sizeof(T));
623  }
624 
625  //! \brief Bitwise compare two SecBlocks
626  //! \param t the other SecBlock
627  //! \returns true if the size and bits are equal, false otherwise
628  //! \details Uses a constant time compare if the arrays are equal size. The constant time
629  //! compare is VerifyBufsEqual() found in misc.h.
630  //! \details Internally, operator!=() returns the inverse of operator==().
631  //! \sa operator==()
632  bool operator!=(const SecBlock<T, A> &t) const
633  {
634  return !operator==(t);
635  }
636 
637  //! \brief Change size without preserving contents
638  //! \param newSize the new size of the memory block
639  //! \details Old content is \a not preserved. If the memory block is reduced in size,
640  //! then the reclaimed memory is set to 0. If the memory block grows in size, then
641  //! the new memory is \a not initialized.
642  //! \details Internally, this SecBlock calls reallocate().
643  //! \sa New(), CleanNew(), Grow(), CleanGrow(), resize()
644  void New(size_type newSize)
645  {
646  m_ptr = m_alloc.reallocate(m_ptr, m_size, newSize, false);
647  m_size = newSize;
648  }
649 
650  //! \brief Change size without preserving contents
651  //! \param newSize the new size of the memory block
652  //! \details Old content is \a not preserved. If the memory block is reduced in size,
653  //! then the reclaimed content is set to 0. If the memory block grows in size, then
654  //! the new memory is initialized to 0.
655  //! \details Internally, this SecBlock calls New().
656  //! \sa New(), CleanNew(), Grow(), CleanGrow(), resize()
657  void CleanNew(size_type newSize)
658  {
659  New(newSize);
660  if (m_ptr) {memset_z(m_ptr, 0, m_size*sizeof(T));}
661  }
662 
663  //! \brief Change size and preserve contents
664  //! \param newSize the new size of the memory block
665  //! \details Old content is preserved. New content is not initialized.
666  //! \details Internally, this SecBlock calls reallocate() when size must increase. If the
667  //! size does not increase, then Grow() does not take action. If the size must
668  //! change, then use resize().
669  //! \sa New(), CleanNew(), Grow(), CleanGrow(), resize()
670  void Grow(size_type newSize)
671  {
672  if (newSize > m_size)
673  {
674  m_ptr = m_alloc.reallocate(m_ptr, m_size, newSize, true);
675  m_size = newSize;
676  }
677  }
678 
679  //! \brief Change size and preserve contents
680  //! \param newSize the new size of the memory block
681  //! \details Old content is preserved. New content is initialized to 0.
682  //! \details Internally, this SecBlock calls reallocate() when size must increase. If the
683  //! size does not increase, then CleanGrow() does not take action. If the size must
684  //! change, then use resize().
685  //! \sa New(), CleanNew(), Grow(), CleanGrow(), resize()
686  void CleanGrow(size_type newSize)
687  {
688  if (newSize > m_size)
689  {
690  m_ptr = m_alloc.reallocate(m_ptr, m_size, newSize, true);
691  memset_z(m_ptr+m_size, 0, (newSize-m_size)*sizeof(T));
692  m_size = newSize;
693  }
694  }
695 
696  //! \brief Change size and preserve contents
697  //! \param newSize the new size of the memory block
698  //! \details Old content is preserved. If the memory block grows in size, then
699  //! new memory is \a not initialized.
700  //! \details Internally, this SecBlock calls reallocate().
701  //! \sa New(), CleanNew(), Grow(), CleanGrow(), resize()
702  void resize(size_type newSize)
703  {
704  m_ptr = m_alloc.reallocate(m_ptr, m_size, newSize, true);
705  m_size = newSize;
706  }
707 
708  //! \brief Swap contents with another SecBlock
709  //! \param b the other SecBlock
710  //! \details Internally, std::swap() is called on m_alloc, m_size and m_ptr.
712  {
713  // Swap must occur on the allocator in case its FixedSize that spilled into the heap.
714  std::swap(m_alloc, b.m_alloc);
715  std::swap(m_size, b.m_size);
716  std::swap(m_ptr, b.m_ptr);
717  }
718 
719 // protected:
720  A m_alloc;
721  size_type m_size;
722  T *m_ptr;
723 };
724 
725 #ifdef CRYPTOPP_DOXYGEN_PROCESSING
726 //! \class SecByteBlock
727 //! \brief \ref SecBlock "SecBlock<byte>" typedef.
728 class SecByteBlock : public SecBlock<byte> {};
729 //! \class SecWordBlock
730 //! \brief \ref SecBlock "SecBlock<word>" typedef.
731 class SecWordBlock : public SecBlock<word> {};
732 //! \class AlignedSecByteBlock
733 //! \brief SecBlock using \ref AllocatorWithCleanup "AllocatorWithCleanup<byte, true>" typedef
734 class AlignedSecByteBlock : public SecBlock<byte, AllocatorWithCleanup<byte, true> > {};
735 #else
739 #endif
740 
741 // No need for move semantics on derived class *if* the class does not add any
742 // data members; see http://stackoverflow.com/q/31755703, and Rule of {0|3|5}.
743 
744 //! \class FixedSizeSecBlock
745 //! \brief Fixed size stack-based SecBlock
746 //! \tparam T class or type
747 //! \tparam S fixed-size of the stack-based memory block, in elements
748 //! \tparam A AllocatorBase derived class for allocation and cleanup
749 template <class T, unsigned int S, class A = FixedSizeAllocatorWithCleanup<T, S> >
750 class FixedSizeSecBlock : public SecBlock<T, A>
751 {
752 public:
753  //! \brief Construct a FixedSizeSecBlock
754  explicit FixedSizeSecBlock() : SecBlock<T, A>(S) {}
755 };
756 
757 //! \class FixedSizeAlignedSecBlock
758 //! \brief Fixed size stack-based SecBlock with 16-byte alignment
759 //! \tparam T class or type
760 //! \tparam S fixed-size of the stack-based memory block, in elements
761 //! \tparam A AllocatorBase derived class for allocation and cleanup
762 template <class T, unsigned int S, bool T_Align16 = true>
763 class FixedSizeAlignedSecBlock : public FixedSizeSecBlock<T, S, FixedSizeAllocatorWithCleanup<T, S, NullAllocator<T>, T_Align16> >
764 {
765 };
766 
767 //! \class SecBlockWithHint
768 //! \brief Stack-based SecBlock that grows into the heap
769 //! \tparam T class or type
770 //! \tparam S fixed-size of the stack-based memory block, in elements
771 //! \tparam A AllocatorBase derived class for allocation and cleanup
772 template <class T, unsigned int S, class A = FixedSizeAllocatorWithCleanup<T, S, AllocatorWithCleanup<T> > >
773 class SecBlockWithHint : public SecBlock<T, A>
774 {
775 public:
776  //! construct a SecBlockWithHint with a count of elements
777  explicit SecBlockWithHint(size_t size) : SecBlock<T, A>(size) {}
778 };
779 
780 template<class T, bool A, class U, bool B>
781 inline bool operator==(const CryptoPP::AllocatorWithCleanup<T, A>&, const CryptoPP::AllocatorWithCleanup<U, B>&) {return (true);}
782 template<class T, bool A, class U, bool B>
783 inline bool operator!=(const CryptoPP::AllocatorWithCleanup<T, A>&, const CryptoPP::AllocatorWithCleanup<U, B>&) {return (false);}
784 
785 NAMESPACE_END
786 
787 NAMESPACE_BEGIN(std)
788 template <class T, class A>
789 inline void swap(CryptoPP::SecBlock<T, A> &a, CryptoPP::SecBlock<T, A> &b)
790 {
791  a.swap(b);
792 }
793 
794 #if defined(_STLP_DONT_SUPPORT_REBIND_MEMBER_TEMPLATE) || (defined(_STLPORT_VERSION) && !defined(_STLP_MEMBER_TEMPLATE_CLASSES))
795 // working for STLport 5.1.3 and MSVC 6 SP5
796 template <class _Tp1, class _Tp2>
797 inline CryptoPP::AllocatorWithCleanup<_Tp2>&
798 __stl_alloc_rebind(CryptoPP::AllocatorWithCleanup<_Tp1>& __a, const _Tp2*)
799 {
800  return (CryptoPP::AllocatorWithCleanup<_Tp2>&)(__a);
801 }
802 #endif
803 
804 NAMESPACE_END
805 
806 #if CRYPTOPP_MSC_VERSION
807 # pragma warning(pop)
808 #endif
809 
810 #endif
iterator end()
Provides an iterator pointing beyond the last element in the memory block.
Definition: secblock.h:504
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:711
Stack-based SecBlock that grows into the heap.
Definition: secblock.h:773
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:754
void CleanNew(size_type newSize)
Change size without preserving contents.
Definition: secblock.h:657
bool operator!=(const SecBlock< T, A > &t) const
Bitwise compare two SecBlocks.
Definition: secblock.h:632
A::const_pointer data() const
Provides a pointer to the first element in the memory block.
Definition: secblock.h:516
bool empty() const
Determines if the SecBlock is empty.
Definition: secblock.h:524
SecBlock< T, A > & operator=(const SecBlock< T, A > &t)
Assign contents from another SecBlock.
Definition: secblock.h:566
void resize(size_type newSize)
Change size and preserve contents.
Definition: secblock.h:702
SecBlock< T, A > & operator+=(const SecBlock< T, A > &t)
Append contents from another SecBlock.
Definition: secblock.h:576
void CleanGrow(size_type newSize)
Change size and preserve contents.
Definition: secblock.h:686
void Assign(const SecBlock< T, A > &t)
Copy contents from another SecBlock.
Definition: secblock.h:552
SecBlock< T, A > operator+(const SecBlock< T, A > &t)
Construct a SecBlock from this and another SecBlock.
Definition: secblock.h:601
SecBlock(size_type size=0)
Construct a SecBlock with space for size elements.
Definition: secblock.h:447
const_iterator begin() const
Provides a constant iterator pointing to the first element in the memory block.
Definition: secblock.h:500
Secure memory block with allocator and cleanup.
Definition: secblock.h:434
void memcpy_s(void *dest, size_t sizeInBytes, const void *src, size_t count)
Bounds checking replacement for memcpy()
Definition: misc.h:356
size_type size() const
Provides the count of elements in the SecBlock.
Definition: secblock.h:521
Library configuration file.
STL namespace.
pointer allocate(size_type size, const void *hint)
Allocates a block of memory.
Definition: secblock.h:344
void New(size_type newSize)
Change size without preserving contents.
Definition: secblock.h:644
SecBlock typedef.
Definition: secblock.h:728
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
bool operator==(const OID &lhs, const OID &rhs)
Compare two OIDs for equality.
Static secure memory block with cleanup.
Definition: secblock.h:298
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:363
bool operator!=(const OID &lhs, const OID &rhs)
Compare two OIDs for inequality.
void SecureWipeArray(T *buf, size_t n)
Sets each element of an array to 0.
Definition: misc.h:1176
bool IsAlignedOn(const void *ptr, unsigned int alignment)
Determines whether ptr is aligned to a minimum value.
Definition: misc.h:907
const_iterator end() const
Provides a constant iterator pointing beyond the last element in the memory block.
Definition: secblock.h:508
void * UnalignedAllocate(size_t size)
Allocates a buffer.
Definition: misc.cpp:253
Template class memeber Rebind.
Definition: secblock.h:236
A::pointer data()
Provides a pointer to the first element in the memory block.
Definition: secblock.h:513
void Assign(const T *ptr, size_type len)
Set contents and size from an array.
Definition: secblock.h:541
pointer reallocate(pointer oldPtr, size_type oldSize, size_type newSize, bool preserve)
Reallocates a block of memory.
Definition: secblock.h:393
Fixed size stack-based SecBlock with 16-byte alignment.
Definition: secblock.h:763
SecBlock using AllocatorWithCleanup typedef.
Definition: secblock.h:734
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:750
SecBlock(const SecBlock< T, A > &t)
Copy construct a SecBlock from another SecBlock.
Definition: secblock.h:453
void * memset_z(void *ptr, int value, size_t num)
Memory block initializer and eraser that attempts to survive optimizations.
Definition: misc.h:451
const T & STDMIN(const T &a, const T &b)
Replacement function for std::min.
Definition: misc.h:467
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:496
const byte * BytePtr() const
Return a byte pointer to the first element in the memory block.
Definition: secblock.h:531
NULL allocator.
Definition: secblock.h:260
SecBlockWithHint(size_t size)
construct a SecBlockWithHint with a count of elements
Definition: secblock.h:777
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:467
pointer allocate(size_type size)
Allocates a block of memory.
Definition: secblock.h:318
const T & STDMAX(const T &a, const T &b)
Replacement function for std::max.
Definition: misc.h:477
void Grow(size_type newSize)
Change size and preserve contents.
Definition: secblock.h:670
Crypto++ library namespace.
bool operator==(const SecBlock< T, A > &t) const
Bitwise compare two SecBlocks.
Definition: secblock.h:619
size_type SizeInBytes() const
Provides the number of bytes in the SecBlock.
Definition: secblock.h:535
FixedSizeAllocatorWithCleanup()
Constructs a FixedSizeAllocatorWithCleanup.
Definition: secblock.h:304
void UnalignedDeallocate(void *ptr)
Frees a buffer allocated with UnalignedAllocate.
Definition: misc.cpp:261
SecBlock typedef.
Definition: secblock.h:731
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:95
byte * BytePtr()
Provides a byte pointer to the first element in the memory block.
Definition: secblock.h:528