forked from weidai11/cryptopp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmisc.h
3013 lines (2753 loc) · 116 KB
/
misc.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// misc.h - originally written and placed in the public domain by Wei Dai
/// \file misc.h
/// \brief Utility functions for the Crypto++ library.
#ifndef CRYPTOPP_MISC_H
#define CRYPTOPP_MISC_H
#include "config.h"
#include "cryptlib.h"
#include "secblockfwd.h"
#include "smartptr.h"
#include "stdcpp.h"
#include "trap.h"
#if !defined(CRYPTOPP_DOXYGEN_PROCESSING)
#if (CRYPTOPP_MSC_VERSION)
# pragma warning(push)
# pragma warning(disable: 4146 4514)
# if (CRYPTOPP_MSC_VERSION >= 1400)
# pragma warning(disable: 6326)
# endif
#endif
// Issue 340 and Issue 793
#if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wconversion"
# pragma GCC diagnostic ignored "-Wsign-conversion"
# pragma GCC diagnostic ignored "-Wunused-function"
#endif
#ifdef _MSC_VER
#if _MSC_VER >= 1400
// VC2005 workaround: disable declarations that conflict with winnt.h
#define _interlockedbittestandset CRYPTOPP_DISABLED_INTRINSIC_1
#define _interlockedbittestandreset CRYPTOPP_DISABLED_INTRINSIC_2
#define _interlockedbittestandset64 CRYPTOPP_DISABLED_INTRINSIC_3
#define _interlockedbittestandreset64 CRYPTOPP_DISABLED_INTRINSIC_4
#include <intrin.h>
#undef _interlockedbittestandset
#undef _interlockedbittestandreset
#undef _interlockedbittestandset64
#undef _interlockedbittestandreset64
#define CRYPTOPP_FAST_ROTATE(x) 1
#elif _MSC_VER >= 1300
#define CRYPTOPP_FAST_ROTATE(x) ((x) == 32 | (x) == 64)
#else
#define CRYPTOPP_FAST_ROTATE(x) ((x) == 32)
#endif
#elif (defined(__MWERKS__) && TARGET_CPU_PPC) || \
(defined(__GNUC__) && (defined(_ARCH_PWR2) || defined(_ARCH_PWR) || defined(_ARCH_PPC) || defined(_ARCH_PPC64) || defined(_ARCH_COM)))
#define CRYPTOPP_FAST_ROTATE(x) ((x) == 32)
#elif defined(__GNUC__) && (CRYPTOPP_BOOL_X64 || CRYPTOPP_BOOL_X32 || CRYPTOPP_BOOL_X86) // depend on GCC's peephole optimization to generate rotate instructions
#define CRYPTOPP_FAST_ROTATE(x) 1
#else
#define CRYPTOPP_FAST_ROTATE(x) 0
#endif
#ifdef __BORLANDC__
#include <mem.h>
#include <stdlib.h>
#endif
#if (defined(__GNUC__) || defined(__clang__)) && defined(__linux__)
#define CRYPTOPP_BYTESWAP_AVAILABLE 1
#include <byteswap.h>
#endif
// Limit to ARM A-32. Aarch64 is failing self tests.
#if defined(__arm__) && (defined(__GNUC__) || defined(__clang__)) && (__ARM_ARCH >= 6)
#define CRYPTOPP_ARM_BYTEREV_AVAILABLE 1
#endif
// Limit to ARM A-32. Aarch64 is failing self tests.
#if defined(__arm__) && (defined(__GNUC__) || defined(__clang__)) && (__ARM_ARCH >= 7)
#define CRYPTOPP_ARM_BITREV_AVAILABLE 1
#endif
#if defined(__BMI__)
# include <x86intrin.h>
# include <immintrin.h>
#endif // GCC and BMI
// More LLVM bullshit. Apple Clang 6.0 does not define them.
// Later version of Clang defines them and results in warnings.
#if defined(__clang__)
# ifndef _blsr_u32
# define _blsr_u32 __blsr_u32
# endif
# ifndef _blsr_u64
# define _blsr_u64 __blsr_u64
# endif
# ifndef _tzcnt_u32
# define _tzcnt_u32 __tzcnt_u32
# endif
# ifndef _tzcnt_u64
# define _tzcnt_u64 __tzcnt_u64
# endif
#endif
#endif // CRYPTOPP_DOXYGEN_PROCESSING
#if CRYPTOPP_DOXYGEN_PROCESSING
/// \brief The maximum value of a machine word
/// \details <tt>SIZE_MAX</tt> provides the maximum value of a machine word. The value
/// is <tt>0xffffffff</tt> on 32-bit targets, and <tt>0xffffffffffffffff</tt> on 64-bit
/// targets.
/// \details If <tt>SIZE_MAX</tt> is not defined, then <tt>__SIZE_MAX__</tt> is used if
/// defined. If not defined, then <tt>SIZE_T_MAX</tt> is used if defined. If not defined,
/// then the library uses <tt>std::numeric_limits<size_t>::max()</tt>.
/// \details The library prefers <tt>__SIZE_MAX__</tt> or <tt>__SIZE_T_MAX__</tt> because
/// they are effectively <tt>constexpr</tt> that is optimized well by all compilers.
/// <tt>std::numeric_limits<size_t>::max()</tt> is not always a <tt>constexpr</tt>, and
/// it is not always optimized well.
# define SIZE_MAX ...
#else
// Its amazing portability problems still plague this simple concept in 2015.
// http://stackoverflow.com/questions/30472731/which-c-standard-header-defines-size-max
// Avoid NOMINMAX macro on Windows. http://support.microsoft.com/en-us/kb/143208
#ifndef SIZE_MAX
# if defined(__SIZE_MAX__)
# define SIZE_MAX __SIZE_MAX__
# elif defined(SIZE_T_MAX)
# define SIZE_MAX SIZE_T_MAX
# elif defined(__SIZE_TYPE__)
# define SIZE_MAX (~(__SIZE_TYPE__)0)
# else
# define SIZE_MAX ((std::numeric_limits<size_t>::max)())
# endif
#endif
#endif // CRYPTOPP_DOXYGEN_PROCESSING
NAMESPACE_BEGIN(CryptoPP)
// Forward declaration for IntToString specialization
class Integer;
// ************** compile-time assertion ***************
#if CRYPTOPP_DOXYGEN_PROCESSING
/// \brief Compile time assertion
/// \param expr the expression to evaluate
/// \details Asserts the expression <tt>expr</tt> during compile. If C++14 and
/// N3928 are available, then C++14 <tt>static_assert</tt> is used. Otherwise,
/// a <tt>CompileAssert</tt> structure is used. When the structure is used
/// a negative-sized array triggers the assert at compile time.
# define CRYPTOPP_COMPILE_ASSERT(expr) { ... }
#elif defined(CRYPTOPP_CXX17_STATIC_ASSERT)
# define CRYPTOPP_COMPILE_ASSERT(expr) static_assert(expr)
#else // CRYPTOPP_DOXYGEN_PROCESSING
template <bool b>
struct CompileAssert
{
static char dummy[2*b-1];
};
#define CRYPTOPP_COMPILE_ASSERT(assertion) CRYPTOPP_COMPILE_ASSERT_INSTANCE(assertion, __LINE__)
#define CRYPTOPP_ASSERT_JOIN(X, Y) CRYPTOPP_DO_ASSERT_JOIN(X, Y)
#define CRYPTOPP_DO_ASSERT_JOIN(X, Y) X##Y
#if defined(CRYPTOPP_EXPORTS) || defined(CRYPTOPP_IMPORTS)
# define CRYPTOPP_COMPILE_ASSERT_INSTANCE(assertion, instance)
#else
# if defined(__GNUC__) || defined(__clang__)
# define CRYPTOPP_COMPILE_ASSERT_INSTANCE(assertion, instance) \
static CompileAssert<(assertion)> \
CRYPTOPP_ASSERT_JOIN(cryptopp_CRYPTOPP_ASSERT_, instance) __attribute__ ((unused))
# else
# define CRYPTOPP_COMPILE_ASSERT_INSTANCE(assertion, instance) \
static CompileAssert<(assertion)> \
CRYPTOPP_ASSERT_JOIN(cryptopp_CRYPTOPP_ASSERT_, instance)
# endif // GCC or Clang
#endif
#endif // CRYPTOPP_DOXYGEN_PROCESSING
// ************** count elements in an array ***************
#if CRYPTOPP_DOXYGEN_PROCESSING
/// \brief Counts elements in an array
/// \param arr an array of elements
/// \details COUNTOF counts elements in an array. On Windows COUNTOF(x) is defined
/// to <tt>_countof(x)</tt> to ensure correct results for pointers.
/// \note COUNTOF does not produce correct results with pointers, and an array must be used.
/// <tt>sizeof(x)/sizeof(x[0])</tt> suffers the same problem. The risk is eliminated by using
/// <tt>_countof(x)</tt> on Windows. Windows will provide the immunity for other platforms.
# define COUNTOF(arr)
#else
// VS2005 added _countof
#ifndef COUNTOF
# if defined(_MSC_VER) && (_MSC_VER >= 1400)
# define COUNTOF(x) _countof(x)
# else
# define COUNTOF(x) (sizeof(x)/sizeof(x[0]))
# endif
#endif // COUNTOF
#endif // CRYPTOPP_DOXYGEN_PROCESSING
// ************** misc classes ***************
/// \brief An Empty class
/// \details The Empty class can be used as a template parameter <tt>BASE</tt> when no base class exists.
class CRYPTOPP_DLL Empty
{
};
#if !defined(CRYPTOPP_DOXYGEN_PROCESSING)
template <class BASE1, class BASE2>
class CRYPTOPP_NO_VTABLE TwoBases : public BASE1, public BASE2
{
};
template <class BASE1, class BASE2, class BASE3>
class CRYPTOPP_NO_VTABLE ThreeBases : public BASE1, public BASE2, public BASE3
{
};
#endif // CRYPTOPP_DOXYGEN_PROCESSING
/// \tparam T class or type
/// \brief Uses encapsulation to hide an object in derived classes
/// \details The object T is declared as protected.
template <class T>
class ObjectHolder
{
protected:
T m_object;
};
/// \brief Ensures an object is not copyable
/// \details NotCopyable ensures an object is not copyable by making the
/// copy constructor and assignment operator private. Deleters are used
/// under C++11.
/// \sa Clonable class
class NotCopyable
{
public:
NotCopyable() {}
#if CRYPTOPP_CXX11_DELETED_FUNCTIONS
NotCopyable(const NotCopyable &) = delete;
void operator=(const NotCopyable &) = delete;
#else
private:
NotCopyable(const NotCopyable &);
void operator=(const NotCopyable &);
#endif
};
/// \brief An object factory function
/// \tparam T class or type
/// \details NewObject overloads operator()().
template <class T>
struct NewObject
{
T* operator()() const {return new T;}
};
#if CRYPTOPP_DOXYGEN_PROCESSING
/// \brief A memory barrier
/// \details MEMORY_BARRIER attempts to ensure reads and writes are completed
/// in the absence of a language synchronization point. It is used by the
/// Singleton class if the compiler supports it. The barrier is provided at the
/// customary places in a double-checked initialization.
/// \details Internally, MEMORY_BARRIER uses <tt>std::atomic_thread_fence</tt> if
/// C++11 atomics are available. Otherwise, <tt>intrinsic(_ReadWriteBarrier)</tt>,
/// <tt>_ReadWriteBarrier()</tt> or <tt>__asm__("" ::: "memory")</tt> is used.
#define MEMORY_BARRIER ...
#else
#if defined(CRYPTOPP_CXX11_ATOMIC)
# define MEMORY_BARRIER() std::atomic_thread_fence(std::memory_order_acq_rel)
#elif (_MSC_VER >= 1400)
# pragma intrinsic(_ReadWriteBarrier)
# define MEMORY_BARRIER() _ReadWriteBarrier()
#elif defined(__INTEL_COMPILER)
# define MEMORY_BARRIER() __memory_barrier()
#elif defined(__GNUC__) || defined(__clang__)
# define MEMORY_BARRIER() __asm__ __volatile__ ("" ::: "memory")
#else
# define MEMORY_BARRIER()
#endif
#endif // CRYPTOPP_DOXYGEN_PROCESSING
/// \brief Restricts the instantiation of a class to one static object without locks
/// \tparam T the class or type
/// \tparam F the object factory for T
/// \tparam instance an instance counter for the class object
/// \details This class safely initializes a static object in a multi-threaded environment. For C++03
/// and below it will do so without using locks for portability. If two threads call Ref() at the same
/// time, they may get back different references, and one object may end up being memory leaked. This
/// is by design and it avoids a subtle initialization problem in a multi-threaded environment with thread
/// local storage on early Windows platforms, like Windows XP and Windows 2003.
/// \details For C++11 and above, a standard double-checked locking pattern with thread fences
/// are used. The locks and fences are standard and do not hinder portability.
/// \details Microsoft's C++11 implementation provides the necessary primitive support on Windows Vista and
/// above when using Visual Studio 2015 (<tt>cl.exe</tt> version 19.00). If C++11 is desired, you should
/// set <tt>WINVER</tt> or <tt>_WIN32_WINNT</tt> to 0x600 (or above), and compile with Visual Studio 2015.
/// \sa <A HREF="http://preshing.com/20130930/double-checked-locking-is-fixed-in-cpp11/">Double-Checked Locking
/// is Fixed In C++11</A>, <A HREF="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2660.htm">Dynamic
/// Initialization and Destruction with Concurrency</A> and
/// <A HREF="http://msdn.microsoft.com/en-us/library/6yh4a9k1.aspx">Thread Local Storage (TLS)</A> on MSDN.
/// \since Crypto++ 5.2
template <class T, class F = NewObject<T>, int instance=0>
class Singleton
{
public:
Singleton(F objectFactory = F()) : m_objectFactory(objectFactory) {}
// prevent this function from being inlined
CRYPTOPP_NOINLINE const T & Ref(CRYPTOPP_NOINLINE_DOTDOTDOT) const;
private:
F m_objectFactory;
};
/// \brief Return a reference to the inner Singleton object
/// \tparam T the class or type
/// \tparam F the object factory for T
/// \tparam instance an instance counter for the class object
/// \details Ref() is used to create the object using the object factory. The
/// object is only created once with the limitations discussed in the class documentation.
/// \sa <A HREF="http://preshing.com/20130930/double-checked-locking-is-fixed-in-cpp11/">Double-Checked Locking is Fixed In C++11</A>
/// \since Crypto++ 5.2
template <class T, class F, int instance>
const T & Singleton<T, F, instance>::Ref(CRYPTOPP_NOINLINE_DOTDOTDOT) const
{
#if defined(CRYPTOPP_CXX11_ATOMIC) && defined(CRYPTOPP_CXX11_SYNCHRONIZATION) && defined(CRYPTOPP_CXX11_STATIC_INIT)
static std::mutex s_mutex;
static std::atomic<T*> s_pObject;
T *p = s_pObject.load(std::memory_order_relaxed);
std::atomic_thread_fence(std::memory_order_acquire);
if (p)
return *p;
std::lock_guard<std::mutex> lock(s_mutex);
p = s_pObject.load(std::memory_order_relaxed);
std::atomic_thread_fence(std::memory_order_acquire);
if (p)
return *p;
T *newObject = m_objectFactory();
s_pObject.store(newObject, std::memory_order_relaxed);
std::atomic_thread_fence(std::memory_order_release);
return *newObject;
#else
static volatile simple_ptr<T> s_pObject;
T *p = s_pObject.m_p;
MEMORY_BARRIER();
if (p)
return *p;
T *newObject = m_objectFactory();
p = s_pObject.m_p;
MEMORY_BARRIER();
if (p)
{
delete newObject;
return *p;
}
s_pObject.m_p = newObject;
MEMORY_BARRIER();
return *newObject;
#endif
}
// ************** misc functions ***************
/// \brief Create a pointer with an offset
/// \tparam PTR a pointer type
/// \tparam OFF a size type
/// \param pointer a pointer
/// \param offset a offset into the pointer
/// \details PtrAdd can be used to squash Clang and GCC
/// UBsan findings for pointer addition and subtraction.
template <typename PTR, typename OFF>
inline PTR PtrAdd(PTR pointer, OFF offset)
{
return pointer+static_cast<ptrdiff_t>(offset);
}
/// \brief Create a pointer with an offset
/// \tparam PTR a pointer type
/// \tparam OFF a size type
/// \param pointer a pointer
/// \param offset a offset into the pointer
/// \details PtrSub can be used to squash Clang and GCC
/// UBsan findings for pointer addition and subtraction.
template <typename PTR, typename OFF>
inline PTR PtrSub(PTR pointer, OFF offset)
{
return pointer-static_cast<ptrdiff_t>(offset);
}
/// \brief Determine pointer difference
/// \tparam PTR a pointer type
/// \param pointer1 the first pointer
/// \param pointer2 the second pointer
/// \details PtrDiff can be used to squash Clang and GCC
/// UBsan findings for pointer addition and subtraction.
/// pointer1 and pointer2 must point to the same object or
/// array (or one past the end), and yields the number of
/// elements (not bytes) difference.
template <typename PTR>
inline ptrdiff_t PtrDiff(const PTR pointer1, const PTR pointer2)
{
return pointer1 - pointer2;
}
/// \brief Determine pointer difference
/// \tparam PTR a pointer type
/// \param pointer1 the first pointer
/// \param pointer2 the second pointer
/// \details PtrByteDiff can be used to squash Clang and GCC
/// UBsan findings for pointer addition and subtraction.
/// pointer1 and pointer2 must point to the same object or
/// array (or one past the end), and yields the number of
/// bytes (not elements) difference.
template <typename PTR>
inline size_t PtrByteDiff(const PTR pointer1, const PTR pointer2)
{
return (size_t)(reinterpret_cast<uintptr_t>(pointer1) - reinterpret_cast<uintptr_t>(pointer2));
}
/// \brief Pointer to the first element of a string
/// \param str std::string
/// \details BytePtr returns NULL pointer for an empty string.
/// \return Pointer to the first element of a string
/// \since Crypto++ 8.0
inline byte* BytePtr(std::string& str)
{
// Caller wants a writable pointer
CRYPTOPP_ASSERT(str.empty() == false);
if (str.empty())
return NULLPTR;
return reinterpret_cast<byte*>(&str[0]);
}
/// \brief Pointer to the first element of a string
/// \param str SecByteBlock
/// \details BytePtr returns NULL pointer for an empty string.
/// \return Pointer to the first element of a string
/// \since Crypto++ 8.3
byte* BytePtr(SecByteBlock& str);
/// \brief Const pointer to the first element of a string
/// \param str std::string
/// \details ConstBytePtr returns non-NULL pointer for an empty string.
/// \return Pointer to the first element of a string
/// \since Crypto++ 8.0
inline const byte* ConstBytePtr(const std::string& str)
{
if (str.empty())
return NULLPTR;
return reinterpret_cast<const byte*>(&str[0]);
}
/// \brief Const pointer to the first element of a string
/// \param str SecByteBlock
/// \details ConstBytePtr returns non-NULL pointer for an empty string.
/// \return Pointer to the first element of a string
/// \since Crypto++ 8.3
const byte* ConstBytePtr(const SecByteBlock& str);
/// \brief Size of a string
/// \param str std::string
/// \return size of a string
/// \since Crypto++ 8.3
inline size_t BytePtrSize(const std::string& str)
{
return str.size();
}
/// \brief Size of a string
/// \param str SecByteBlock
/// \return size of a string
/// \since Crypto++ 8.3
size_t BytePtrSize(const SecByteBlock& str);
/// \brief Integer value
/// \details EnumToInt avoids C++20 enum-enum conversion
/// warnings under GCC and Clang. C++11 and above use a
/// constexpr function. C++03 and below use a macro due
/// to [lack of] constexpr-ness in early versions of C++.
/// \since Crypto++ 8.6
#if (CRYPTOPP_CXX11_CONSTEXPR)
template <typename T>
constexpr int EnumToInt(T v) {
return static_cast<int>(v);
}
#else
# define EnumToInt(v) static_cast<int>(v)
#endif
#if (!__STDC_WANT_SECURE_LIB__ && !defined(_MEMORY_S_DEFINED)) || defined(CRYPTOPP_WANT_SECURE_LIB)
/// \brief Bounds checking replacement for memcpy()
/// \param dest pointer to the destination memory block
/// \param sizeInBytes size of the destination memory block, in bytes
/// \param src pointer to the source memory block
/// \param count the number of bytes to copy
/// \throw InvalidArgument
/// \details ISO/IEC TR-24772 provides bounds checking interfaces for potentially
/// unsafe functions like memcpy(), strcpy() and memmove(). However,
/// not all standard libraries provides them, like Glibc. The library's
/// memcpy_s() is a near-drop in replacement. Its only a near-replacement
/// because the library's version throws an InvalidArgument on a bounds violation.
/// \details memcpy_s() and memmove_s() are guarded by __STDC_WANT_SECURE_LIB__.
/// If __STDC_WANT_SECURE_LIB__ is not defined or defined to 0, then the library
/// makes memcpy_s() and memmove_s() available. The library will also optionally
/// make the symbols available if <tt>CRYPTOPP_WANT_SECURE_LIB</tt> is defined.
/// <tt>CRYPTOPP_WANT_SECURE_LIB</tt> is in config.h, but it is disabled by default.
/// \details memcpy_s() will assert the pointers src and dest are not NULL
/// in debug builds. Passing NULL for either pointer is undefined behavior.
inline void memcpy_s(void *dest, size_t sizeInBytes, const void *src, size_t count)
{
// Safer functions on Windows for C&A, http://github.com/weidai11/cryptopp/issues/55
// Pointers must be valid; otherwise undefined behavior
CRYPTOPP_ASSERT(dest != NULLPTR); CRYPTOPP_ASSERT(src != NULLPTR);
// Restricted pointers. We want to check ranges, but it is not clear how to do it.
CRYPTOPP_ASSERT(src != dest);
// Destination buffer must be large enough to satisfy request
CRYPTOPP_ASSERT(sizeInBytes >= count);
if (count > sizeInBytes)
throw InvalidArgument("memcpy_s: buffer overflow");
#if CRYPTOPP_MSC_VERSION
# pragma warning(push)
# pragma warning(disable: 4996)
# if (CRYPTOPP_MSC_VERSION >= 1400)
# pragma warning(disable: 6386)
# endif
#endif
if (src != NULLPTR && dest != NULLPTR)
std::memcpy(dest, src, count);
#if CRYPTOPP_MSC_VERSION
# pragma warning(pop)
#endif
}
/// \brief Bounds checking replacement for memmove()
/// \param dest pointer to the destination memory block
/// \param sizeInBytes size of the destination memory block, in bytes
/// \param src pointer to the source memory block
/// \param count the number of bytes to copy
/// \throw InvalidArgument
/// \details ISO/IEC TR-24772 provides bounds checking interfaces for potentially
/// unsafe functions like memcpy(), strcpy() and memmove(). However,
/// not all standard libraries provides them, like Glibc. The library's
/// memmove_s() is a near-drop in replacement. Its only a near-replacement
/// because the library's version throws an InvalidArgument on a bounds violation.
/// \details memcpy_s() and memmove_s() are guarded by __STDC_WANT_SECURE_LIB__.
/// If __STDC_WANT_SECURE_LIB__ is not defined or defined to 0, then the library
/// makes memcpy_s() and memmove_s() available. The library will also optionally
/// make the symbols available if <tt>CRYPTOPP_WANT_SECURE_LIB</tt> is defined.
/// <tt>CRYPTOPP_WANT_SECURE_LIB</tt> is in config.h, but it is disabled by default.
/// \details memmove_s() will assert the pointers src and dest are not NULL
/// in debug builds. Passing NULL for either pointer is undefined behavior.
inline void memmove_s(void *dest, size_t sizeInBytes, const void *src, size_t count)
{
// Safer functions on Windows for C&A, http://github.com/weidai11/cryptopp/issues/55
// Pointers must be valid; otherwise undefined behavior
CRYPTOPP_ASSERT(dest != NULLPTR); CRYPTOPP_ASSERT(src != NULLPTR);
// Destination buffer must be large enough to satisfy request
CRYPTOPP_ASSERT(sizeInBytes >= count);
if (count > sizeInBytes)
throw InvalidArgument("memmove_s: buffer overflow");
#if CRYPTOPP_MSC_VERSION
# pragma warning(push)
# pragma warning(disable: 4996)
# if (CRYPTOPP_MSC_VERSION >= 1400)
# pragma warning(disable: 6386)
# endif
#endif
if (src != NULLPTR && dest != NULLPTR)
std::memmove(dest, src, count);
#if CRYPTOPP_MSC_VERSION
# pragma warning(pop)
#endif
}
#if __BORLANDC__ >= 0x620
// C++Builder 2010 workaround: can't use std::memcpy_s
// because it doesn't allow 0 lengths
# define memcpy_s CryptoPP::memcpy_s
# define memmove_s CryptoPP::memmove_s
#endif
#endif // __STDC_WANT_SECURE_LIB__
/// \brief Swaps two variables which are arrays
/// \tparam T class or type
/// \param a the first value
/// \param b the second value
/// \details C++03 does not provide support for <tt>std::swap(__m128i a, __m128i b)</tt>
/// because <tt>__m128i</tt> is an <tt>unsigned long long[2]</tt>. Most compilers
/// support it out of the box, but Sun Studio C++ compilers 12.2 and 12.3 do not.
/// \sa <A HREF="http://stackoverflow.com/q/38417413">How to swap two __m128i variables
/// in C++03 given its an opaque type and an array?</A> on Stack Overflow.
template <class T>
inline void vec_swap(T& a, T& b)
{
// __m128i is an unsigned long long[2], and support for swapping it was
// not added until C++11. SunCC 12.1 - 12.3 fail to consume the swap; while
// SunCC 12.4 consumes it without -std=c++11.
#if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x5120)
T t;
t=a, a=b, b=t;
#else
std::swap(a, b);
#endif
}
/// \brief Memory block initializer
/// \param ptr pointer to the memory block being written
/// \param val the integer value to write for each byte
/// \param num the size of the source memory block, in bytes
/// \details Internally the function calls memset with the value <tt>val</tt>.
/// memset_z can be used to initialize a freshly allocated memory block.
/// To zeroize a memory block on destruction use <tt>SecureWipeBuffer</tt>.
/// \return the pointer to the memory block
/// \sa SecureWipeBuffer
inline void * memset_z(void *ptr, int val, size_t num)
{
// avoid extraneous warning on GCC 4.3.2 Ubuntu 8.10
#if CRYPTOPP_GCC_VERSION >= 30001 || CRYPTOPP_LLVM_CLANG_VERSION >= 20800 || \
CRYPTOPP_APPLE_CLANG_VERSION >= 30000
if (__builtin_constant_p(num) && num==0)
return ptr;
#endif
return std::memset(ptr, val, num);
}
/// \brief Replacement function for std::min
/// \tparam T class or type
/// \param a the first value
/// \param b the second value
/// \return the minimum value based on a comparison of <tt>b \< a</tt> using <tt>operator\<</tt>
/// \details STDMIN was provided because the library could not easily use std::min or std::max in Windows or Cygwin 1.1.0
template <class T> inline const T& STDMIN(const T& a, const T& b)
{
return b < a ? b : a;
}
/// \brief Replacement function for std::max
/// \tparam T class or type
/// \param a the first value
/// \param b the second value
/// \return the minimum value based on a comparison of <tt>a \< b</tt> using <tt>operator\<</tt>
/// \details STDMAX was provided because the library could not easily use std::min or std::max in Windows or Cygwin 1.1.0
template <class T> inline const T& STDMAX(const T& a, const T& b)
{
return a < b ? b : a;
}
#if CRYPTOPP_MSC_VERSION
# pragma warning(push)
# pragma warning(disable: 4389)
#endif
#if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wsign-compare"
# pragma GCC diagnostic ignored "-Wstrict-overflow"
# if (CRYPTOPP_LLVM_CLANG_VERSION >= 20800) || (CRYPTOPP_APPLE_CLANG_VERSION >= 30000)
# pragma GCC diagnostic ignored "-Wtautological-compare"
# elif (CRYPTOPP_GCC_VERSION >= 40300)
# pragma GCC diagnostic ignored "-Wtype-limits"
# endif
#endif
/// \brief Safe comparison of values that could be negative and incorrectly promoted
/// \tparam T1 class or type
/// \tparam T2 class or type
/// \param a the first value
/// \param b the second value
/// \return the minimum value based on a comparison a and b using <tt>operator<</tt>.
/// \details The comparison <tt>b \< a</tt> is performed and the value returned is a's type T1.
template <class T1, class T2> inline const T1 UnsignedMin(const T1& a, const T2& b)
{
CRYPTOPP_COMPILE_ASSERT((sizeof(T1)<=sizeof(T2) && T2(-1)>0) || (sizeof(T1)>sizeof(T2) && T1(-1)>0));
if (sizeof(T1)<=sizeof(T2))
return b < (T2)a ? (T1)b : a;
else
return (T1)b < a ? (T1)b : a;
}
/// \brief Tests whether a conversion from -> to is safe to perform
/// \tparam T1 class or type
/// \tparam T2 class or type
/// \param from the first value
/// \param to the second value
/// \return true if its safe to convert from into to, false otherwise.
template <class T1, class T2>
inline bool SafeConvert(T1 from, T2 &to)
{
to = static_cast<T2>(from);
if (from != to || (from > 0) != (to > 0))
return false;
return true;
}
/// \brief Converts a value to a string
/// \tparam T class or type
/// \param value the value to convert
/// \param base the base to use during the conversion
/// \return the string representation of value in base.
template <class T>
std::string IntToString(T value, unsigned int base = 10)
{
// Hack... set the high bit for uppercase.
const unsigned int HIGH_BIT = (1U << 31);
const char CH = !!(base & HIGH_BIT) ? 'A' : 'a';
base &= ~HIGH_BIT;
CRYPTOPP_ASSERT(base >= 2);
if (value == 0)
return "0";
bool negate = false;
if (value < 0)
{
negate = true;
value = 0-value; // VC .NET does not like -a
}
std::string result;
while (value > 0)
{
T digit = value % base;
result = char((digit < 10 ? '0' : (CH - 10)) + digit) + result;
value /= base;
}
if (negate)
result = "-" + result;
return result;
}
/// \brief Converts an unsigned value to a string
/// \param value the value to convert
/// \param base the base to use during the conversion
/// \return the string representation of value in base.
/// \details this template function specialization was added to suppress
/// Coverity findings on IntToString() with unsigned types.
template <> CRYPTOPP_DLL
std::string IntToString<word64>(word64 value, unsigned int base);
/// \brief Converts an Integer to a string
/// \param value the Integer to convert
/// \param base the base to use during the conversion
/// \return the string representation of value in base.
/// \details This is a template specialization of IntToString(). Use it
/// like IntToString():
/// <pre>
/// // Print integer in base 10
/// Integer n...
/// std::string s = IntToString(n, 10);
/// </pre>
/// \details The string is presented with lowercase letters by default. A
/// hack is available to switch to uppercase letters without modifying
/// the function signature.
/// <pre>
/// // Print integer in base 16, uppercase letters
/// Integer n...
/// const unsigned int UPPER = (1 << 31);
/// std::string s = IntToString(n, (UPPER | 16));</pre>
template <> CRYPTOPP_DLL
std::string IntToString<Integer>(Integer value, unsigned int base);
#if CRYPTOPP_MSC_VERSION
# pragma warning(pop)
#endif
#if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
# pragma GCC diagnostic pop
#endif
#define RETURN_IF_NONZERO(x) size_t returnedValue = x; if (returnedValue) return returnedValue
// this version of the macro is fastest on Pentium 3 and Pentium 4 with MSVC 6 SP5 w/ Processor Pack
#define GETBYTE(x, y) (unsigned int)byte((x)>>(8*(y)))
// these may be faster on other CPUs/compilers
// #define GETBYTE(x, y) (unsigned int)(((x)>>(8*(y)))&255)
// #define GETBYTE(x, y) (((byte *)&(x))[y])
#define CRYPTOPP_GET_BYTE_AS_BYTE(x, y) byte((x)>>(8*(y)))
/// \brief Returns the parity of a value
/// \tparam T class or type
/// \param value the value to provide the parity
/// \return 1 if the number 1-bits in the value is odd, 0 otherwise
template <class T>
unsigned int Parity(T value)
{
for (unsigned int i=8*sizeof(value)/2; i>0; i/=2)
value ^= value >> i;
return (unsigned int)value&1;
}
/// \brief Returns the number of 8-bit bytes or octets required for a value
/// \tparam T class or type
/// \param value the value to test
/// \return the minimum number of 8-bit bytes or octets required to represent a value
template <class T>
unsigned int BytePrecision(const T &value)
{
if (!value)
return 0;
unsigned int l=0, h=8*sizeof(value);
while (h-l > 8)
{
unsigned int t = (l+h)/2;
if (value >> t)
l = t;
else
h = t;
}
return h/8;
}
/// \brief Returns the number of bits required for a value
/// \tparam T class or type
/// \param value the value to test
/// \return the maximum number of bits required to represent a value.
template <class T>
unsigned int BitPrecision(const T &value)
{
if (!value)
return 0;
unsigned int l=0, h=8*sizeof(value);
while (h-l > 1)
{
unsigned int t = (l+h)/2;
if (value >> t)
l = t;
else
h = t;
}
return h;
}
/// Determines the number of trailing 0-bits in a value
/// \param v the 32-bit value to test
/// \return the number of trailing 0-bits in v, starting at the least significant bit position
/// \details TrailingZeros returns the number of trailing 0-bits in v, starting at the least
/// significant bit position. The return value is undefined if there are no 1-bits set in the value v.
/// \note The function does not return 0 if no 1-bits are set because 0 collides with a 1-bit at the 0-th position.
inline unsigned int TrailingZeros(word32 v)
{
// GCC 4.7 and VS2012 provides tzcnt on AVX2/BMI enabled processors
// We don't enable for Microsoft because it requires a runtime check.
// http://msdn.microsoft.com/en-us/library/hh977023%28v=vs.110%29.aspx
CRYPTOPP_ASSERT(v != 0);
#if defined(__BMI__)
return (unsigned int)_tzcnt_u32(v);
#elif defined(__GNUC__) && (CRYPTOPP_GCC_VERSION >= 30400)
return (unsigned int)__builtin_ctz(v);
#elif defined(_MSC_VER) && (_MSC_VER >= 1400)
unsigned long result;
_BitScanForward(&result, v);
return static_cast<unsigned int>(result);
#else
// from http://graphics.stanford.edu/~seander/bithacks.html#ZerosOnRightMultLookup
static const int MultiplyDeBruijnBitPosition[32] =
{
0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
};
return MultiplyDeBruijnBitPosition[((word32)((v & -v) * 0x077CB531U)) >> 27];
#endif
}
/// Determines the number of trailing 0-bits in a value
/// \param v the 64-bit value to test
/// \return the number of trailing 0-bits in v, starting at the least significant bit position
/// \details TrailingZeros returns the number of trailing 0-bits in v, starting at the least
/// significant bit position. The return value is undefined if there are no 1-bits set in the value v.
/// \note The function does not return 0 if no 1-bits are set because 0 collides with a 1-bit at the 0-th position.
inline unsigned int TrailingZeros(word64 v)
{
// GCC 4.7 and VS2012 provides tzcnt on AVX2/BMI enabled processors
// We don't enable for Microsoft because it requires a runtime check.
// http://msdn.microsoft.com/en-us/library/hh977023%28v=vs.110%29.aspx
CRYPTOPP_ASSERT(v != 0);
#if defined(__BMI__) && defined(__x86_64__)
return (unsigned int)_tzcnt_u64(v);
#elif defined(__GNUC__) && (CRYPTOPP_GCC_VERSION >= 30400)
return (unsigned int)__builtin_ctzll(v);
#elif defined(_MSC_VER) && (_MSC_VER >= 1400) && (defined(_M_X64) || defined(_M_IA64))
unsigned long result;
_BitScanForward64(&result, v);
return static_cast<unsigned int>(result);
#else
return word32(v) ? TrailingZeros(word32(v)) : 32 + TrailingZeros(word32(v>>32));
#endif
}
/// \brief Truncates the value to the specified number of bits.
/// \tparam T class or type
/// \param value the value to truncate or mask
/// \param bits the number of bits to truncate or mask
/// \return the value truncated to the specified number of bits, starting at the least
/// significant bit position
/// \details This function masks the low-order bits of value and returns the result. The
/// mask is created with <tt>(1 << bits) - 1</tt>.
template <class T>
inline T Crop(T value, size_t bits)
{
if (bits < 8*sizeof(value))
return T(value & ((T(1) << bits) - 1));
else
return value;
}
/// \brief Returns the number of 8-bit bytes or octets required for the specified number of bits
/// \param bitCount the number of bits
/// \return the minimum number of 8-bit bytes or octets required by bitCount
/// \details BitsToBytes is effectively a ceiling function based on 8-bit bytes.
inline size_t BitsToBytes(size_t bitCount)
{
return ((bitCount+7)/(8));
}
/// \brief Returns the number of words required for the specified number of bytes
/// \param byteCount the number of bytes
/// \return the minimum number of words required by byteCount
/// \details BytesToWords is effectively a ceiling function based on <tt>WORD_SIZE</tt>.
/// <tt>WORD_SIZE</tt> is defined in config.h
inline size_t BytesToWords(size_t byteCount)
{
return ((byteCount+WORD_SIZE-1)/WORD_SIZE);
}
/// \brief Returns the number of words required for the specified number of bits
/// \param bitCount the number of bits
/// \return the minimum number of words required by bitCount
/// \details BitsToWords is effectively a ceiling function based on <tt>WORD_BITS</tt>.
/// <tt>WORD_BITS</tt> is defined in config.h
inline size_t BitsToWords(size_t bitCount)
{
return ((bitCount+WORD_BITS-1)/(WORD_BITS));
}
/// \brief Returns the number of double words required for the specified number of bits
/// \param bitCount the number of bits
/// \return the minimum number of double words required by bitCount
/// \details BitsToDwords is effectively a ceiling function based on <tt>2*WORD_BITS</tt>.
/// <tt>WORD_BITS</tt> is defined in config.h
inline size_t BitsToDwords(size_t bitCount)
{
return ((bitCount+2*WORD_BITS-1)/(2*WORD_BITS));
}
/// Performs an XOR of a buffer with a mask
/// \param buf the buffer to XOR with the mask
/// \param mask the mask to XOR with the buffer
/// \param count the size of the buffers, in bytes
/// \details The function effectively visits each element in the buffers and performs
/// <tt>buf[i] ^= mask[i]</tt>. buf and mask must be of equal size.
CRYPTOPP_DLL void CRYPTOPP_API xorbuf(byte *buf, const byte *mask, size_t count);
/// Performs an XOR of an input buffer with a mask and stores the result in an output buffer
/// \param output the destination buffer
/// \param input the source buffer to XOR with the mask
/// \param mask the mask buffer to XOR with the input buffer
/// \param count the size of the buffers, in bytes
/// \details The function effectively visits each element in the buffers and performs
/// <tt>output[i] = input[i] ^ mask[i]</tt>. output, input and mask must be of equal size.
CRYPTOPP_DLL void CRYPTOPP_API xorbuf(byte *output, const byte *input, const byte *mask, size_t count);
/// \brief Performs a near constant-time comparison of two equally sized buffers
/// \param buf1 the first buffer
/// \param buf2 the second buffer
/// \param count the size of the buffers, in bytes
/// \details VerifyBufsEqual performs an XOR of the elements in two equally sized
/// buffers and returns a result based on the XOR operation. A count of 0 returns
/// true because two empty buffers are considered equal.
/// \details The function is near constant-time because CPU micro-code timings could
/// affect the "constant-ness". Calling code is responsible for mitigating timing
/// attacks if the buffers are not equally sized.
/// \sa ModPowerOf2