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  //! \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
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
308  //! \details FixedSizeAllocatorWithCleanup provides a fixed-size, stack-
309  //! based allocation at compile time. If size is less than or equal to
310  //! S, 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  //! \note size is the count of elements, and not the number of bytes.
318  //! \sa reallocate(), SecBlockWithHint
319  pointer allocate(size_type size)
320  {
321  assert(IsAlignedOn(m_array, 8));
322 
323  if (size <= S && !m_allocated)
324  {
325  m_allocated = true;
326  return GetAlignedArray();
327  }
328  else
329  return m_fallbackAllocator.allocate(size);
330  }
331 
332  //! \brief Allocates a block of memory
333  //! \param size size of the memory block
334  //! \param hint an unused hint
335  //! \details FixedSizeAllocatorWithCleanup provides a fixed-size, stack-
336  //! based allocation at compile time. If size is less than or equal to
337  //! S, then a pointer to the static array is returned.
338  //! \details The class can grow its memory block at runtime if a suitable
339  //! allocator is available. If size grows beyond S and a suitable
340  //! allocator is available, then the statically allocated array is
341  //! obsoleted. If a suitable allocator is \a not available, as with a
342  //! NullAllocator, then the function returns NULL and a runtime error
343  //! eventually occurs.
344  //! \note size is the count of elements, and not the number of bytes.
345  //! \sa reallocate(), SecBlockWithHint
346  pointer allocate(size_type size, const void *hint)
347  {
348  if (size <= S && !m_allocated)
349  {
350  m_allocated = true;
351  return GetAlignedArray();
352  }
353  else
354  return m_fallbackAllocator.allocate(size, hint);
355  }
356 
357  //! \brief Deallocates a block of memory
358  //! \param ptr a pointer to the memory block to deallocate
359  //! \param size size of the memory block
360  //! \details The memory block is wiped or zeroized before deallocation.
361  //! If the statically allocated memory block is active, then no
362  //! additional actions are taken after the wipe.
363  //! \details If a dynamic memory block is active, then the pointer and
364  //! size are passed to the allocator for deallocation.
365  void deallocate(void *ptr, size_type size)
366  {
367  if (ptr == GetAlignedArray())
368  {
369  assert(size <= S);
370  assert(m_allocated);
371  m_allocated = false;
372  SecureWipeArray((pointer)ptr, size);
373  }
374  else
375  m_fallbackAllocator.deallocate(ptr, size);
376  }
377 
378  //! \brief Reallocates a block of memory
379  //! \param oldPtr the previous allocation
380  //! \param oldSize the size of the previous allocation
381  //! \param newSize the new, requested size
382  //! \param preserve flag that indicates if the old allocation should be preserved
383  //! \returns pointer to the new memory block
384  //! \details FixedSizeAllocatorWithCleanup provides a fixed-size, stack-
385  //! based allocation at compile time. If size is less than or equal to
386  //! S, then a pointer to the static array is returned.
387  //! \details The class can grow its memory block at runtime if a suitable
388  //! allocator is available. If size grows beyond S and a suitable
389  //! allocator is available, then the statically allocated array is
390  //! obsoleted. If a suitable allocator is \a not available, as with a
391  //! NullAllocator, then the function returns NULL and a runtime error
392  //! eventually occurs.
393  //! \note size is the count of elements, and not the number of bytes.
394  //! \sa reallocate(), SecBlockWithHint
395  pointer reallocate(pointer oldPtr, size_type oldSize, size_type newSize, bool preserve)
396  {
397  if (oldPtr == GetAlignedArray() && newSize <= S)
398  {
399  assert(oldSize <= S);
400  if (oldSize > newSize)
401  SecureWipeArray(oldPtr+newSize, oldSize-newSize);
402  return oldPtr;
403  }
404 
405  pointer newPointer = allocate(newSize, NULL);
406  if (preserve && newSize)
407  {
408  const size_t copySize = STDMIN(oldSize, newSize);
409  memcpy_s(newPointer, sizeof(T)*newSize, oldPtr, sizeof(T)*copySize);
410  }
411  deallocate(oldPtr, oldSize);
412  return newPointer;
413  }
414 
415  size_type max_size() const {return STDMAX(m_fallbackAllocator.max_size(), S);}
416 
417 private:
418 
419 #ifdef __BORLANDC__
420  T* GetAlignedArray() {return m_array;}
421  T m_array[S];
422 #else
423  T* GetAlignedArray() {return (CRYPTOPP_BOOL_ALIGN16 && T_Align16) ? (T*)(void *)(((byte *)m_array) + (0-(size_t)m_array)%16) : m_array;}
424  CRYPTOPP_ALIGN_DATA(8) T m_array[(CRYPTOPP_BOOL_ALIGN16 && T_Align16) ? S+8/sizeof(T) : S];
425 #endif
426 
427  A m_fallbackAllocator;
428  bool m_allocated;
429 };
430 
431 //! \class SecBlock
432 //! \brief Secure memory block with allocator and cleanup
433 //! \tparam T a class or type
434 //! \tparam A AllocatorWithCleanup derived class for allocation and cleanup
435 template <class T, class A = AllocatorWithCleanup<T> >
436 class SecBlock
437 {
438 public:
439  typedef typename A::value_type value_type;
440  typedef typename A::pointer iterator;
441  typedef typename A::const_pointer const_iterator;
442  typedef typename A::size_type size_type;
443 
444  //! \brief Construct a SecBlock with space for size elements.
445  //! \param size the number of elements in the allocation
446  //! \throws std::bad_alloc
447  //! \details The elements are not initialized.
448  //! \note size is the count of elements, and not the number of bytes
449  explicit SecBlock(size_type size=0)
450  : m_size(size), m_ptr(m_alloc.allocate(size, NULL)) { }
451 
452  //! \brief Copy construct a SecBlock from another SecBlock
453  //! \param t the other SecBlock
454  //! \throws std::bad_alloc
456  : m_size(t.m_size), m_ptr(m_alloc.allocate(t.m_size, NULL)) {
457  assert((!t.m_ptr && !m_size) || (t.m_ptr && m_size));
458  if (t.m_ptr) {memcpy_s(m_ptr, m_size*sizeof(T), t.m_ptr, t.m_size*sizeof(T));}
459  }
460 
461  //! \brief Construct a SecBlock from an array of elements.
462  //! \param ptr a pointer to an array of T
463  //! \param len the number of elements in the memory block
464  //! \throws std::bad_alloc
465  //! \details If <tt>ptr!=NULL</tt> and <tt>len!=0</tt>, then the block is initialized from the pointer ptr.
466  //! If <tt>ptr==NULL</tt> and <tt>len!=0</tt>, then the block is initialized to 0.
467  //! Otherwise, the block is empty and \a not initialized.
468  //! \note size is the count of elements, and not the number of bytes
469  SecBlock(const T *ptr, size_type len)
470  : m_size(len), m_ptr(m_alloc.allocate(len, NULL)) {
471  assert((!m_ptr && !m_size) || (m_ptr && m_size));
472  if (ptr && m_ptr)
473  memcpy_s(m_ptr, m_size*sizeof(T), ptr, len*sizeof(T));
474  else if (m_size)
475  memset(m_ptr, 0, m_size*sizeof(T));
476  }
477 
478  ~SecBlock()
479  {m_alloc.deallocate(m_ptr, m_size);}
480 
481 #ifdef __BORLANDC__
482  operator T *() const
483  {return (T*)m_ptr;}
484 #else
485  operator const void *() const
486  {return m_ptr;}
487  operator void *()
488  {return m_ptr;}
489 
490  operator const T *() const
491  {return m_ptr;}
492  operator T *()
493  {return m_ptr;}
494 #endif
495 
496  //! \brief Provides an iterator pointing to the first element in the memory block
497  //! \returns iterator pointing to the first element in the memory block
498  iterator begin()
499  {return m_ptr;}
500  //! \brief Provides a constant iterator pointing to the first element in the memory block
501  //! \returns constant iterator pointing to the first element in the memory block
502  const_iterator begin() const
503  {return m_ptr;}
504  //! \brief Provides an iterator pointing beyond the last element in the memory block
505  //! \returns iterator pointing beyond the last element in the memory block
506  iterator end()
507  {return m_ptr+m_size;}
508  //! \brief Provides a constant iterator pointing beyond the last element in the memory block
509  //! \returns constant iterator pointing beyond the last element in the memory block
510  const_iterator end() const
511  {return m_ptr+m_size;}
512 
513  //! \brief Provides a pointer to the first element in the memory block
514  //! \returns pointer to the first element in the memory block
515  typename A::pointer data() {return m_ptr;}
516  //! \brief Provides a pointer to the first element in the memory block
517  //! \returns constant pointer to the first element in the memory block
518  typename A::const_pointer data() const {return m_ptr;}
519 
520  //! \brief Provides the count of elements in the SecBlock
521  //! \returns number of elements in the memory block
522  //! \note the return value is the count of elements, and not the number of bytes
523  size_type size() const {return m_size;}
524  //! \brief Determines if the SecBlock is empty
525  //! \returns true if number of elements in the memory block is 0, false otherwise
526  bool empty() const {return m_size == 0;}
527 
528  //! \brief Provides a byte pointer to the first element in the memory block
529  //! \returns byte pointer to the first element in the memory block
530  byte * BytePtr() {return (byte *)m_ptr;}
531  //! \brief Return a byte pointer to the first element in the memory block
532  //! \returns constant byte pointer to the first element in the memory block
533  const byte * BytePtr() const {return (const byte *)m_ptr;}
534  //! \brief Provides the number of bytes in the SecBlock
535  //! \return the number of bytes in the memory block
536  //! \note the return value is the number of bytes, and not count of elements.
537  size_type SizeInBytes() const {return m_size*sizeof(T);}
538 
539  //! \brief Set contents and size from an array
540  //! \param ptr a pointer to an array of T
541  //! \param len the number of elements in the memory block
542  //! \details If the memory block is reduced in size, then the reclaimed memory is set to 0.
543  void Assign(const T *ptr, size_type len)
544  {
545  New(len);
546  if (m_ptr && ptr && len)
547  {memcpy_s(m_ptr, m_size*sizeof(T), ptr, len*sizeof(T));}
548  }
549 
550  //! \brief Copy contents from another SecBlock
551  //! \param t the other SecBlock
552  //! \details Assign checks for self assignment.
553  //! \details If the memory block is reduced in size, then the reclaimed memory is set to 0.
554  void Assign(const SecBlock<T, A> &t)
555  {
556  if (this != &t)
557  {
558  New(t.m_size);
559  if (m_ptr && t.m_ptr && t.m_size)
560  {memcpy_s(m_ptr, m_size*sizeof(T), t, t.m_size*sizeof(T));}
561  }
562  }
563 
564  //! \brief Assign contents from another SecBlock
565  //! \param t the other SecBlock
566  //! \details Internally, operator=() calls Assign().
567  //! \details If the memory block is reduced in size, then the reclaimed memory is set to 0.
569  {
570  // Assign guards for self-assignment
571  Assign(t);
572  return *this;
573  }
574 
575  //! \brief Append contents from another SecBlock
576  //! \param t the other SecBlock
577  //! \details Internally, this SecBlock calls Grow and then appends t.
579  {
580  assert((!t.m_ptr && !t.m_size) || (t.m_ptr && t.m_size));
581 
582  if(t.m_size)
583  {
584  const size_type oldSize = m_size;
585  if(this != &t) // s += t
586  {
587  Grow(m_size+t.m_size);
588  memcpy_s(m_ptr+oldSize, (m_size-oldSize)*sizeof(T), t.m_ptr, t.m_size*sizeof(T));
589  }
590  else // t += t
591  {
592  Grow(m_size*2);
593  memcpy_s(m_ptr+oldSize, (m_size-oldSize)*sizeof(T), m_ptr, oldSize*sizeof(T));
594  }
595  }
596  return *this;
597  }
598 
599  //! \brief Construct a SecBlock from this and another SecBlock
600  //! \param t the other SecBlock
601  //! \returns a newly constructed SecBlock that is a conacentation of this and t
602  //! \details Internally, a new SecBlock is created from this and a concatenation of t.
604  {
605  assert((!m_ptr && !m_size) || (m_ptr && m_size));
606  assert((!t.m_ptr && !t.m_size) || (t.m_ptr && t.m_size));
607  if(!t.m_size) return SecBlock(*this);
608 
609  SecBlock<T, A> result(m_size+t.m_size);
610  if(m_size) {memcpy_s(result.m_ptr, result.m_size*sizeof(T), m_ptr, m_size*sizeof(T));}
611  memcpy_s(result.m_ptr+m_size, (result.m_size-m_size)*sizeof(T), t.m_ptr, t.m_size*sizeof(T));
612  return result;
613  }
614 
615  //! \brief Bitwise compare two SecBlocks
616  //! \param t the other SecBlock
617  //! \returns true if the size and bits are equal, false otherwise
618  //! \details Uses a constant time compare if the arrays are equal size. The constant time
619  //! compare is VerifyBufsEqual() found in misc.h.
620  //! \sa operator!=()
621  bool operator==(const SecBlock<T, A> &t) const
622  {
623  return m_size == t.m_size &&
624  VerifyBufsEqual(reinterpret_cast<const byte*>(m_ptr), reinterpret_cast<const byte*>(t.m_ptr), m_size*sizeof(T));
625  }
626 
627  //! \brief Bitwise compare two SecBlocks
628  //! \param t the other SecBlock
629  //! \returns true if the size and bits are equal, false otherwise
630  //! \details Uses a constant time compare if the arrays are equal size. The constant time
631  //! compare is VerifyBufsEqual() found in misc.h.
632  //! \details Internally, operator!=() returns the inverse of operator==().
633  //! \sa operator==()
634  bool operator!=(const SecBlock<T, A> &t) const
635  {
636  return !operator==(t);
637  }
638 
639  //! \brief Change size without preserving contents
640  //! \param newSize the new size of the memory block
641  //! \details Old content is \a not preserved. If the memory block is reduced in size,
642  //! then the reclaimed memory is set to 0. If the memory block grows in size, then
643  //! the new memory is \a not initialized.
644  //! \details Internally, this SecBlock calls reallocate().
645  //! \sa New(), CleanNew(), Grow(), CleanGrow(), resize()
646  void New(size_type newSize)
647  {
648  m_ptr = m_alloc.reallocate(m_ptr, m_size, newSize, false);
649  m_size = newSize;
650  }
651 
652  //! \brief Change size without preserving contents
653  //! \param newSize the new size of the memory block
654  //! \details Old content is \a not preserved. If the memory block is reduced in size,
655  //! then the reclaimed content is set to 0. If the memory block grows in size, then
656  //! the new memory is initialized to 0.
657  //! \details Internally, this SecBlock calls New().
658  //! \sa New(), CleanNew(), Grow(), CleanGrow(), resize()
659  void CleanNew(size_type newSize)
660  {
661  New(newSize);
662  if (m_ptr) {memset_z(m_ptr, 0, m_size*sizeof(T));}
663  }
664 
665  //! \brief Change size and preserve contents
666  //! \param newSize the new size of the memory block
667  //! \details Old content is preserved. New content is not initialized.
668  //! \details Internally, this SecBlock calls reallocate() when size must increase. If the
669  //! size does not increase, then Grow() does not take action. If the size must
670  //! change, then use resize().
671  //! \sa New(), CleanNew(), Grow(), CleanGrow(), resize()
672  void Grow(size_type newSize)
673  {
674  if (newSize > m_size)
675  {
676  m_ptr = m_alloc.reallocate(m_ptr, m_size, newSize, true);
677  m_size = newSize;
678  }
679  }
680 
681  //! \brief Change size and preserve contents
682  //! \param newSize the new size of the memory block
683  //! \details Old content is preserved. New content is initialized to 0.
684  //! \details Internally, this SecBlock calls reallocate() when size must increase. If the
685  //! size does not increase, then CleanGrow() does not take action. If the size must
686  //! change, then use resize().
687  //! \sa New(), CleanNew(), Grow(), CleanGrow(), resize()
688  void CleanGrow(size_type newSize)
689  {
690  if (newSize > m_size)
691  {
692  m_ptr = m_alloc.reallocate(m_ptr, m_size, newSize, true);
693  memset_z(m_ptr+m_size, 0, (newSize-m_size)*sizeof(T));
694  m_size = newSize;
695  }
696  }
697 
698  //! \brief Change size and preserve contents
699  //! \param newSize the new size of the memory block
700  //! \details Old content is preserved. If the memory block grows in size, then
701  //! new memory is \a not initialized.
702  //! \details Internally, this SecBlock calls reallocate().
703  //! \sa New(), CleanNew(), Grow(), CleanGrow(), resize()
704  void resize(size_type newSize)
705  {
706  m_ptr = m_alloc.reallocate(m_ptr, m_size, newSize, true);
707  m_size = newSize;
708  }
709 
710  //! \brief Swap contents with another SecBlock
711  //! \param b the other SecBlock
712  //! \details Internally, std::swap() is called on m_alloc, m_size and m_ptr.
714  {
715  // Swap must occur on the allocator in case its FixedSize that spilled into the heap.
716  std::swap(m_alloc, b.m_alloc);
717  std::swap(m_size, b.m_size);
718  std::swap(m_ptr, b.m_ptr);
719  }
720 
721 // protected:
722  A m_alloc;
723  size_type m_size;
724  T *m_ptr;
725 };
726 
727 #ifdef CRYPTOPP_DOXYGEN_PROCESSING
728 //! \class SecByteBlock
729 //! \brief \ref SecBlock "SecBlock<byte>" typedef.
730 class SecByteBlock : public SecBlock<byte> {};
731 //! \class SecWordBlock
732 //! \brief \ref SecBlock "SecBlock<word>" typedef.
733 class SecWordBlock : public SecBlock<word> {};
734 //! \class AlignedSecByteBlock
735 //! \brief SecBlock using \ref AllocatorWithCleanup "AllocatorWithCleanup<byte, true>" typedef
736 class AlignedSecByteBlock : public SecBlock<byte, AllocatorWithCleanup<byte, true> > {};
737 #else
741 #endif
742 
743 // No need for move semantics on derived class *if* the class does not add any
744 // data members; see http://stackoverflow.com/q/31755703, and Rule of {0|3|5}.
745 
746 //! \class FixedSizeSecBlock
747 //! \brief Fixed size stack-based SecBlock
748 //! \tparam T class or type
749 //! \tparam S fixed-size of the stack-based memory block
750 //! \tparam A AllocatorBase derived class for allocation and cleanup
751 template <class T, unsigned int S, class A = FixedSizeAllocatorWithCleanup<T, S> >
752 class FixedSizeSecBlock : public SecBlock<T, A>
753 {
754 public:
755  //! \brief Construct a FixedSizeSecBlock
756  explicit FixedSizeSecBlock() : SecBlock<T, A>(S) {}
757 };
758 
759 //! \class FixedSizeAlignedSecBlock
760 //! \brief Fixed size stack-based SecBlock with 16-byte alignment
761 //! \tparam T class or type
762 //! \tparam S fixed-size of the stack-based memory block
763 //! \tparam A AllocatorBase derived class for allocation and cleanup
764 template <class T, unsigned int S, bool T_Align16 = true>
765 class FixedSizeAlignedSecBlock : public FixedSizeSecBlock<T, S, FixedSizeAllocatorWithCleanup<T, S, NullAllocator<T>, T_Align16> >
766 {
767 };
768 
769 //! \class SecBlockWithHint
770 //! \brief Stack-based SecBlock that grows into the heap
771 //! \tparam T class or type
772 //! \tparam S fixed-size of the stack-based memory block
773 //! \tparam A AllocatorBase derived class for allocation and cleanup
774 template <class T, unsigned int S, class A = FixedSizeAllocatorWithCleanup<T, S, AllocatorWithCleanup<T> > >
775 class SecBlockWithHint : public SecBlock<T, A>
776 {
777 public:
778  //! construct a SecBlockWithHint with a count of elements
779  explicit SecBlockWithHint(size_t size) : SecBlock<T, A>(size) {}
780 };
781 
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 (true);}
784 template<class T, bool A, class U, bool B>
785 inline bool operator!=(const CryptoPP::AllocatorWithCleanup<T, A>&, const CryptoPP::AllocatorWithCleanup<U, B>&) {return (false);}
786 
787 NAMESPACE_END
788 
789 NAMESPACE_BEGIN(std)
790 template <class T, class A>
791 inline void swap(CryptoPP::SecBlock<T, A> &a, CryptoPP::SecBlock<T, A> &b)
792 {
793  a.swap(b);
794 }
795 
796 #if defined(_STLP_DONT_SUPPORT_REBIND_MEMBER_TEMPLATE) || (defined(_STLPORT_VERSION) && !defined(_STLP_MEMBER_TEMPLATE_CLASSES))
797 // working for STLport 5.1.3 and MSVC 6 SP5
798 template <class _Tp1, class _Tp2>
799 inline CryptoPP::AllocatorWithCleanup<_Tp2>&
800 __stl_alloc_rebind(CryptoPP::AllocatorWithCleanup<_Tp1>& __a, const _Tp2*)
801 {
802  return (CryptoPP::AllocatorWithCleanup<_Tp2>&)(__a);
803 }
804 #endif
805 
806 NAMESPACE_END
807 
808 #if CRYPTOPP_MSC_VERSION
809 # pragma warning(pop)
810 #endif
811 
812 #endif
iterator end()
Provides an iterator pointing beyond the last element in the memory block.
Definition: secblock.h:506
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:713
Stack-based SecBlock that grows into the heap.
Definition: secblock.h:775
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:756
void CleanNew(size_type newSize)
Change size without preserving contents.
Definition: secblock.h:659
bool operator!=(const SecBlock< T, A > &t) const
Bitwise compare two SecBlocks.
Definition: secblock.h:634
A::const_pointer data() const
Provides a pointer to the first element in the memory block.
Definition: secblock.h:518
bool empty() const
Determines if the SecBlock is empty.
Definition: secblock.h:526
SecBlock< T, A > & operator=(const SecBlock< T, A > &t)
Assign contents from another SecBlock.
Definition: secblock.h:568
void resize(size_type newSize)
Change size and preserve contents.
Definition: secblock.h:704
SecBlock< T, A > & operator+=(const SecBlock< T, A > &t)
Append contents from another SecBlock.
Definition: secblock.h:578
void CleanGrow(size_type newSize)
Change size and preserve contents.
Definition: secblock.h:688
void Assign(const SecBlock< T, A > &t)
Copy contents from another SecBlock.
Definition: secblock.h:554
SecBlock< T, A > operator+(const SecBlock< T, A > &t)
Construct a SecBlock from this and another SecBlock.
Definition: secblock.h:603
SecBlock(size_type size=0)
Construct a SecBlock with space for size elements.
Definition: secblock.h:449
const_iterator begin() const
Provides a constant iterator pointing to the first element in the memory block.
Definition: secblock.h:502
Secure memory block with allocator and cleanup.
Definition: secblock.h:436
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:523
Library configuration file.
STL namespace.
pointer allocate(size_type size, const void *hint)
Allocates a block of memory.
Definition: secblock.h:346
void New(size_type newSize)
Change size without preserving contents.
Definition: secblock.h:646
SecBlock typedef.
Definition: secblock.h:730
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:365
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: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:510
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:515
void Assign(const T *ptr, size_type len)
Set contents and size from an array.
Definition: secblock.h:543
pointer reallocate(pointer oldPtr, size_type oldSize, size_type newSize, bool preserve)
Reallocates a block of memory.
Definition: secblock.h:395
Fixed size stack-based SecBlock with 16-byte alignment.
Definition: secblock.h:765
SecBlock using AllocatorWithCleanup typedef.
Definition: secblock.h:736
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:752
SecBlock(const SecBlock< T, A > &t)
Copy construct a SecBlock from another SecBlock.
Definition: secblock.h:455
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:498
const byte * BytePtr() const
Return a byte pointer to the first element in the memory block.
Definition: secblock.h:533
NULL allocator.
Definition: secblock.h:260
SecBlockWithHint(size_t size)
construct a SecBlockWithHint with a count of elements
Definition: secblock.h:779
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:469
pointer allocate(size_type size)
Allocates a block of memory.
Definition: secblock.h:319
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:672
Crypto++ library namespace.
bool operator==(const SecBlock< T, A > &t) const
Bitwise compare two SecBlocks.
Definition: secblock.h:621
size_type SizeInBytes() const
Provides the number of bytes in the SecBlock.
Definition: secblock.h:537
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:733
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:530