Check conversion return in ASN1_INTEGER_print_bio.
[oweals/openssl.git] / crypto / bn / bn_lcl.h
1 /*
2  * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #ifndef HEADER_BN_LCL_H
11 # define HEADER_BN_LCL_H
12
13 /*
14  * The EDK2 build doesn't use bn_conf.h; it sets THIRTY_TWO_BIT or
15  * SIXTY_FOUR_BIT in its own environment since it doesn't re-run our
16  * Configure script and needs to support both 32-bit and 64-bit.
17  */
18 # include <openssl/opensslconf.h>
19
20 # if !defined(OPENSSL_SYS_UEFI)
21 #  include "internal/bn_conf.h"
22 # endif
23
24 # include "internal/bn_int.h"
25
26 #ifdef  __cplusplus
27 extern "C" {
28 #endif
29
30 /*
31  * These preprocessor symbols control various aspects of the bignum headers
32  * and library code. They're not defined by any "normal" configuration, as
33  * they are intended for development and testing purposes. NB: defining all
34  * three can be useful for debugging application code as well as openssl
35  * itself. BN_DEBUG - turn on various debugging alterations to the bignum
36  * code BN_DEBUG_RAND - uses random poisoning of unused words to trip up
37  * mismanagement of bignum internals. You must also define BN_DEBUG.
38  */
39 /* #define BN_DEBUG */
40 /* #define BN_DEBUG_RAND */
41
42 # ifndef OPENSSL_SMALL_FOOTPRINT
43 #  define BN_MUL_COMBA
44 #  define BN_SQR_COMBA
45 #  define BN_RECURSION
46 # endif
47
48 /*
49  * This next option uses the C libraries (2 word)/(1 word) function. If it is
50  * not defined, I use my C version (which is slower). The reason for this
51  * flag is that when the particular C compiler library routine is used, and
52  * the library is linked with a different compiler, the library is missing.
53  * This mostly happens when the library is built with gcc and then linked
54  * using normal cc.  This would be a common occurrence because gcc normally
55  * produces code that is 2 times faster than system compilers for the big
56  * number stuff. For machines with only one compiler (or shared libraries),
57  * this should be on.  Again this in only really a problem on machines using
58  * "long long's", are 32bit, and are not using my assembler code.
59  */
60 # if defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_WINDOWS) || \
61     defined(OPENSSL_SYS_WIN32) || defined(linux)
62 #  define BN_DIV2W
63 # endif
64
65 /*
66  * 64-bit processor with LP64 ABI
67  */
68 # ifdef SIXTY_FOUR_BIT_LONG
69 #  define BN_ULLONG       unsigned long long
70 #  define BN_BITS4        32
71 #  define BN_MASK2        (0xffffffffffffffffL)
72 #  define BN_MASK2l       (0xffffffffL)
73 #  define BN_MASK2h       (0xffffffff00000000L)
74 #  define BN_MASK2h1      (0xffffffff80000000L)
75 #  define BN_DEC_CONV     (10000000000000000000UL)
76 #  define BN_DEC_NUM      19
77 #  define BN_DEC_FMT1     "%lu"
78 #  define BN_DEC_FMT2     "%019lu"
79 # endif
80
81 /*
82  * 64-bit processor other than LP64 ABI
83  */
84 # ifdef SIXTY_FOUR_BIT
85 #  undef BN_LLONG
86 #  undef BN_ULLONG
87 #  define BN_BITS4        32
88 #  define BN_MASK2        (0xffffffffffffffffLL)
89 #  define BN_MASK2l       (0xffffffffL)
90 #  define BN_MASK2h       (0xffffffff00000000LL)
91 #  define BN_MASK2h1      (0xffffffff80000000LL)
92 #  define BN_DEC_CONV     (10000000000000000000ULL)
93 #  define BN_DEC_NUM      19
94 #  define BN_DEC_FMT1     "%llu"
95 #  define BN_DEC_FMT2     "%019llu"
96 # endif
97
98 # ifdef THIRTY_TWO_BIT
99 #  ifdef BN_LLONG
100 #   if defined(_WIN32) && !defined(__GNUC__)
101 #    define BN_ULLONG     unsigned __int64
102 #   else
103 #    define BN_ULLONG     unsigned long long
104 #   endif
105 #  endif
106 #  define BN_BITS4        16
107 #  define BN_MASK2        (0xffffffffL)
108 #  define BN_MASK2l       (0xffff)
109 #  define BN_MASK2h1      (0xffff8000L)
110 #  define BN_MASK2h       (0xffff0000L)
111 #  define BN_DEC_CONV     (1000000000L)
112 #  define BN_DEC_NUM      9
113 #  define BN_DEC_FMT1     "%u"
114 #  define BN_DEC_FMT2     "%09u"
115 # endif
116
117
118 /*-
119  * Bignum consistency macros
120  * There is one "API" macro, bn_fix_top(), for stripping leading zeroes from
121  * bignum data after direct manipulations on the data. There is also an
122  * "internal" macro, bn_check_top(), for verifying that there are no leading
123  * zeroes. Unfortunately, some auditing is required due to the fact that
124  * bn_fix_top() has become an overabused duct-tape because bignum data is
125  * occasionally passed around in an inconsistent state. So the following
126  * changes have been made to sort this out;
127  * - bn_fix_top()s implementation has been moved to bn_correct_top()
128  * - if BN_DEBUG isn't defined, bn_fix_top() maps to bn_correct_top(), and
129  *   bn_check_top() is as before.
130  * - if BN_DEBUG *is* defined;
131  *   - bn_check_top() tries to pollute unused words even if the bignum 'top' is
132  *     consistent. (ed: only if BN_DEBUG_RAND is defined)
133  *   - bn_fix_top() maps to bn_check_top() rather than "fixing" anything.
134  * The idea is to have debug builds flag up inconsistent bignums when they
135  * occur. If that occurs in a bn_fix_top(), we examine the code in question; if
136  * the use of bn_fix_top() was appropriate (ie. it follows directly after code
137  * that manipulates the bignum) it is converted to bn_correct_top(), and if it
138  * was not appropriate, we convert it permanently to bn_check_top() and track
139  * down the cause of the bug. Eventually, no internal code should be using the
140  * bn_fix_top() macro. External applications and libraries should try this with
141  * their own code too, both in terms of building against the openssl headers
142  * with BN_DEBUG defined *and* linking with a version of OpenSSL built with it
143  * defined. This not only improves external code, it provides more test
144  * coverage for openssl's own code.
145  */
146
147 # ifdef BN_DEBUG
148 /*
149  * The new BN_FLG_FIXED_TOP flag marks vectors that were not treated with
150  * bn_correct_top, in other words such vectors are permitted to have zeros
151  * in most significant limbs. Such vectors are used internally to achieve
152  * execution time invariance for critical operations with private keys.
153  * It's BN_DEBUG-only flag, because user application is not supposed to
154  * observe it anyway. Moreover, optimizing compiler would actually remove
155  * all operations manipulating the bit in question in non-BN_DEBUG build.
156  */
157 #  define BN_FLG_FIXED_TOP 0x10000
158 #  ifdef BN_DEBUG_RAND
159 /* To avoid "make update" cvs wars due to BN_DEBUG, use some tricks */
160 #   ifndef RAND_bytes
161 int RAND_bytes(unsigned char *buf, int num);
162 #    define BN_DEBUG_TRIX
163 #   endif
164 #   define bn_pollute(a) \
165         do { \
166             const BIGNUM *_bnum1 = (a); \
167             if (_bnum1->top < _bnum1->dmax) { \
168                 unsigned char _tmp_char; \
169                 /* We cast away const without the compiler knowing, any \
170                  * *genuinely* constant variables that aren't mutable \
171                  * wouldn't be constructed with top!=dmax. */ \
172                 BN_ULONG *_not_const; \
173                 memcpy(&_not_const, &_bnum1->d, sizeof(_not_const)); \
174                 RAND_bytes(&_tmp_char, 1); /* Debug only - safe to ignore error return */\
175                 memset(_not_const + _bnum1->top, _tmp_char, \
176                        sizeof(*_not_const) * (_bnum1->dmax - _bnum1->top)); \
177             } \
178         } while(0)
179 #   ifdef BN_DEBUG_TRIX
180 #    undef RAND_bytes
181 #   endif
182 #  else
183 #   define bn_pollute(a)
184 #  endif
185 #  define bn_check_top(a) \
186         do { \
187                 const BIGNUM *_bnum2 = (a); \
188                 if (_bnum2 != NULL) { \
189                         int _top = _bnum2->top; \
190                         OPENSSL_assert((_top == 0 && !_bnum2->neg) || \
191                                (_top && ((_bnum2->flags & BN_FLG_FIXED_TOP) \
192                                          || _bnum2->d[_top - 1] != 0))); \
193                         bn_pollute(_bnum2); \
194                 } \
195         } while(0)
196
197 #  define bn_fix_top(a)           bn_check_top(a)
198
199 #  define bn_check_size(bn, bits) bn_wcheck_size(bn, ((bits+BN_BITS2-1))/BN_BITS2)
200 #  define bn_wcheck_size(bn, words) \
201         do { \
202                 const BIGNUM *_bnum2 = (bn); \
203                 OPENSSL_assert((words) <= (_bnum2)->dmax && \
204                         (words) >= (_bnum2)->top); \
205                 /* avoid unused variable warning with NDEBUG */ \
206                 (void)(_bnum2); \
207         } while(0)
208
209 # else                          /* !BN_DEBUG */
210
211 #  define BN_FLG_FIXED_TOP 0
212 #  define bn_pollute(a)
213 #  define bn_check_top(a)
214 #  define bn_fix_top(a)           bn_correct_top(a)
215 #  define bn_check_size(bn, bits)
216 #  define bn_wcheck_size(bn, words)
217
218 # endif
219
220 BN_ULONG bn_mul_add_words(BN_ULONG *rp, const BN_ULONG *ap, int num,
221                           BN_ULONG w);
222 BN_ULONG bn_mul_words(BN_ULONG *rp, const BN_ULONG *ap, int num, BN_ULONG w);
223 void bn_sqr_words(BN_ULONG *rp, const BN_ULONG *ap, int num);
224 BN_ULONG bn_div_words(BN_ULONG h, BN_ULONG l, BN_ULONG d);
225 BN_ULONG bn_add_words(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp,
226                       int num);
227 BN_ULONG bn_sub_words(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp,
228                       int num);
229
230 struct bignum_st {
231     BN_ULONG *d;                /* Pointer to an array of 'BN_BITS2' bit
232                                  * chunks. */
233     int top;                    /* Index of last used d +1. */
234     /* The next are internal book keeping for bn_expand. */
235     int dmax;                   /* Size of the d array. */
236     int neg;                    /* one if the number is negative */
237     int flags;
238 };
239
240 /* Used for montgomery multiplication */
241 struct bn_mont_ctx_st {
242     int ri;                     /* number of bits in R */
243     BIGNUM RR;                  /* used to convert to montgomery form,
244                                    possibly zero-padded */
245     BIGNUM N;                   /* The modulus */
246     BIGNUM Ni;                  /* R*(1/R mod N) - N*Ni = 1 (Ni is only
247                                  * stored for bignum algorithm) */
248     BN_ULONG n0[2];             /* least significant word(s) of Ni; (type
249                                  * changed with 0.9.9, was "BN_ULONG n0;"
250                                  * before) */
251     int flags;
252 };
253
254 /*
255  * Used for reciprocal division/mod functions It cannot be shared between
256  * threads
257  */
258 struct bn_recp_ctx_st {
259     BIGNUM N;                   /* the divisor */
260     BIGNUM Nr;                  /* the reciprocal */
261     int num_bits;
262     int shift;
263     int flags;
264 };
265
266 /* Used for slow "generation" functions. */
267 struct bn_gencb_st {
268     unsigned int ver;           /* To handle binary (in)compatibility */
269     void *arg;                  /* callback-specific data */
270     union {
271         /* if (ver==1) - handles old style callbacks */
272         void (*cb_1) (int, int, void *);
273         /* if (ver==2) - new callback style */
274         int (*cb_2) (int, int, BN_GENCB *);
275     } cb;
276 };
277
278 /*-
279  * BN_window_bits_for_exponent_size -- macro for sliding window mod_exp functions
280  *
281  *
282  * For window size 'w' (w >= 2) and a random 'b' bits exponent,
283  * the number of multiplications is a constant plus on average
284  *
285  *    2^(w-1) + (b-w)/(w+1);
286  *
287  * here  2^(w-1)  is for precomputing the table (we actually need
288  * entries only for windows that have the lowest bit set), and
289  * (b-w)/(w+1)  is an approximation for the expected number of
290  * w-bit windows, not counting the first one.
291  *
292  * Thus we should use
293  *
294  *    w >= 6  if        b > 671
295  *     w = 5  if  671 > b > 239
296  *     w = 4  if  239 > b >  79
297  *     w = 3  if   79 > b >  23
298  *    w <= 2  if   23 > b
299  *
300  * (with draws in between).  Very small exponents are often selected
301  * with low Hamming weight, so we use  w = 1  for b <= 23.
302  */
303 # define BN_window_bits_for_exponent_size(b) \
304                 ((b) > 671 ? 6 : \
305                  (b) > 239 ? 5 : \
306                  (b) >  79 ? 4 : \
307                  (b) >  23 ? 3 : 1)
308
309 /*
310  * BN_mod_exp_mont_conttime is based on the assumption that the L1 data cache
311  * line width of the target processor is at least the following value.
312  */
313 # define MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH      ( 64 )
314 # define MOD_EXP_CTIME_MIN_CACHE_LINE_MASK       (MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH - 1)
315
316 /*
317  * Window sizes optimized for fixed window size modular exponentiation
318  * algorithm (BN_mod_exp_mont_consttime). To achieve the security goals of
319  * BN_mode_exp_mont_consttime, the maximum size of the window must not exceed
320  * log_2(MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH). Window size thresholds are
321  * defined for cache line sizes of 32 and 64, cache line sizes where
322  * log_2(32)=5 and log_2(64)=6 respectively. A window size of 7 should only be
323  * used on processors that have a 128 byte or greater cache line size.
324  */
325 # if MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH == 64
326
327 #  define BN_window_bits_for_ctime_exponent_size(b) \
328                 ((b) > 937 ? 6 : \
329                  (b) > 306 ? 5 : \
330                  (b) >  89 ? 4 : \
331                  (b) >  22 ? 3 : 1)
332 #  define BN_MAX_WINDOW_BITS_FOR_CTIME_EXPONENT_SIZE    (6)
333
334 # elif MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH == 32
335
336 #  define BN_window_bits_for_ctime_exponent_size(b) \
337                 ((b) > 306 ? 5 : \
338                  (b) >  89 ? 4 : \
339                  (b) >  22 ? 3 : 1)
340 #  define BN_MAX_WINDOW_BITS_FOR_CTIME_EXPONENT_SIZE    (5)
341
342 # endif
343
344 /* Pentium pro 16,16,16,32,64 */
345 /* Alpha       16,16,16,16.64 */
346 # define BN_MULL_SIZE_NORMAL                     (16)/* 32 */
347 # define BN_MUL_RECURSIVE_SIZE_NORMAL            (16)/* 32 less than */
348 # define BN_SQR_RECURSIVE_SIZE_NORMAL            (16)/* 32 */
349 # define BN_MUL_LOW_RECURSIVE_SIZE_NORMAL        (32)/* 32 */
350 # define BN_MONT_CTX_SET_SIZE_WORD               (64)/* 32 */
351
352 /*
353  * 2011-02-22 SMS. In various places, a size_t variable or a type cast to
354  * size_t was used to perform integer-only operations on pointers.  This
355  * failed on VMS with 64-bit pointers (CC /POINTER_SIZE = 64) because size_t
356  * is still only 32 bits.  What's needed in these cases is an integer type
357  * with the same size as a pointer, which size_t is not certain to be. The
358  * only fix here is VMS-specific.
359  */
360 # if defined(OPENSSL_SYS_VMS)
361 #  if __INITIAL_POINTER_SIZE == 64
362 #   define PTR_SIZE_INT long long
363 #  else                         /* __INITIAL_POINTER_SIZE == 64 */
364 #   define PTR_SIZE_INT int
365 #  endif                        /* __INITIAL_POINTER_SIZE == 64 [else] */
366 # elif !defined(PTR_SIZE_INT)   /* defined(OPENSSL_SYS_VMS) */
367 #  define PTR_SIZE_INT size_t
368 # endif                         /* defined(OPENSSL_SYS_VMS) [else] */
369
370 # if !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_NO_INLINE_ASM) && !defined(PEDANTIC)
371 /*
372  * BN_UMULT_HIGH section.
373  *
374  * No, I'm not trying to overwhelm you when stating that the
375  * product of N-bit numbers is 2*N bits wide:-) No, I don't expect
376  * you to be impressed when I say that if the compiler doesn't
377  * support 2*N integer type, then you have to replace every N*N
378  * multiplication with 4 (N/2)*(N/2) accompanied by some shifts
379  * and additions which unavoidably results in severe performance
380  * penalties. Of course provided that the hardware is capable of
381  * producing 2*N result... That's when you normally start
382  * considering assembler implementation. However! It should be
383  * pointed out that some CPUs (most notably Alpha, PowerPC and
384  * upcoming IA-64 family:-) provide *separate* instruction
385  * calculating the upper half of the product placing the result
386  * into a general purpose register. Now *if* the compiler supports
387  * inline assembler, then it's not impossible to implement the
388  * "bignum" routines (and have the compiler optimize 'em)
389  * exhibiting "native" performance in C. That's what BN_UMULT_HIGH
390  * macro is about:-)
391  *
392  *                                      <appro@fy.chalmers.se>
393  */
394 #  if defined(__alpha) && (defined(SIXTY_FOUR_BIT_LONG) || defined(SIXTY_FOUR_BIT))
395 #   if defined(__DECC)
396 #    include <c_asm.h>
397 #    define BN_UMULT_HIGH(a,b)   (BN_ULONG)asm("umulh %a0,%a1,%v0",(a),(b))
398 #   elif defined(__GNUC__) && __GNUC__>=2
399 #    define BN_UMULT_HIGH(a,b)   ({      \
400         register BN_ULONG ret;          \
401         asm ("umulh     %1,%2,%0"       \
402              : "=r"(ret)                \
403              : "r"(a), "r"(b));         \
404         ret;                    })
405 #   endif                       /* compiler */
406 #  elif defined(_ARCH_PPC) && defined(__64BIT__) && defined(SIXTY_FOUR_BIT_LONG)
407 #   if defined(__GNUC__) && __GNUC__>=2
408 #    define BN_UMULT_HIGH(a,b)   ({      \
409         register BN_ULONG ret;          \
410         asm ("mulhdu    %0,%1,%2"       \
411              : "=r"(ret)                \
412              : "r"(a), "r"(b));         \
413         ret;                    })
414 #   endif                       /* compiler */
415 #  elif (defined(__x86_64) || defined(__x86_64__)) && \
416        (defined(SIXTY_FOUR_BIT_LONG) || defined(SIXTY_FOUR_BIT))
417 #   if defined(__GNUC__) && __GNUC__>=2
418 #    define BN_UMULT_HIGH(a,b)   ({      \
419         register BN_ULONG ret,discard;  \
420         asm ("mulq      %3"             \
421              : "=a"(discard),"=d"(ret)  \
422              : "a"(a), "g"(b)           \
423              : "cc");                   \
424         ret;                    })
425 #    define BN_UMULT_LOHI(low,high,a,b)  \
426         asm ("mulq      %3"             \
427                 : "=a"(low),"=d"(high)  \
428                 : "a"(a),"g"(b)         \
429                 : "cc");
430 #   endif
431 #  elif (defined(_M_AMD64) || defined(_M_X64)) && defined(SIXTY_FOUR_BIT)
432 #   if defined(_MSC_VER) && _MSC_VER>=1400
433 unsigned __int64 __umulh(unsigned __int64 a, unsigned __int64 b);
434 unsigned __int64 _umul128(unsigned __int64 a, unsigned __int64 b,
435                           unsigned __int64 *h);
436 #    pragma intrinsic(__umulh,_umul128)
437 #    define BN_UMULT_HIGH(a,b)           __umulh((a),(b))
438 #    define BN_UMULT_LOHI(low,high,a,b)  ((low)=_umul128((a),(b),&(high)))
439 #   endif
440 #  elif defined(__mips) && (defined(SIXTY_FOUR_BIT) || defined(SIXTY_FOUR_BIT_LONG))
441 #   if defined(__GNUC__) && __GNUC__>=2
442 #    if defined(__SIZEOF_INT128__) && __SIZEOF_INT128__==16
443       /* "h" constraint is not an option on R6 and was removed in 4.4 */
444 #     define BN_UMULT_HIGH(a,b)          (((__uint128_t)(a)*(b))>>64)
445 #     define BN_UMULT_LOHI(low,high,a,b) ({     \
446         __uint128_t ret=(__uint128_t)(a)*(b);   \
447         (high)=ret>>64; (low)=ret;       })
448 #    else
449 #     define BN_UMULT_HIGH(a,b) ({      \
450         register BN_ULONG ret;          \
451         asm ("dmultu    %1,%2"          \
452              : "=h"(ret)                \
453              : "r"(a), "r"(b) : "l");   \
454         ret;                    })
455 #     define BN_UMULT_LOHI(low,high,a,b)\
456         asm ("dmultu    %2,%3"          \
457              : "=l"(low),"=h"(high)     \
458              : "r"(a), "r"(b));
459 #    endif
460 #   endif
461 #  elif defined(__aarch64__) && defined(SIXTY_FOUR_BIT_LONG)
462 #   if defined(__GNUC__) && __GNUC__>=2
463 #    define BN_UMULT_HIGH(a,b)   ({      \
464         register BN_ULONG ret;          \
465         asm ("umulh     %0,%1,%2"       \
466              : "=r"(ret)                \
467              : "r"(a), "r"(b));         \
468         ret;                    })
469 #   endif
470 #  endif                        /* cpu */
471 # endif                         /* OPENSSL_NO_ASM */
472
473 /*************************************************************
474  * Using the long long type
475  */
476 # define Lw(t)    (((BN_ULONG)(t))&BN_MASK2)
477 # define Hw(t)    (((BN_ULONG)((t)>>BN_BITS2))&BN_MASK2)
478
479 # ifdef BN_DEBUG_RAND
480 #  define bn_clear_top2max(a) \
481         { \
482         int      ind = (a)->dmax - (a)->top; \
483         BN_ULONG *ftl = &(a)->d[(a)->top-1]; \
484         for (; ind != 0; ind--) \
485                 *(++ftl) = 0x0; \
486         }
487 # else
488 #  define bn_clear_top2max(a)
489 # endif
490
491 # ifdef BN_LLONG
492 #  define mul_add(r,a,w,c) { \
493         BN_ULLONG t; \
494         t=(BN_ULLONG)w * (a) + (r) + (c); \
495         (r)= Lw(t); \
496         (c)= Hw(t); \
497         }
498
499 #  define mul(r,a,w,c) { \
500         BN_ULLONG t; \
501         t=(BN_ULLONG)w * (a) + (c); \
502         (r)= Lw(t); \
503         (c)= Hw(t); \
504         }
505
506 #  define sqr(r0,r1,a) { \
507         BN_ULLONG t; \
508         t=(BN_ULLONG)(a)*(a); \
509         (r0)=Lw(t); \
510         (r1)=Hw(t); \
511         }
512
513 # elif defined(BN_UMULT_LOHI)
514 #  define mul_add(r,a,w,c) {              \
515         BN_ULONG high,low,ret,tmp=(a);  \
516         ret =  (r);                     \
517         BN_UMULT_LOHI(low,high,w,tmp);  \
518         ret += (c);                     \
519         (c) =  (ret<(c))?1:0;           \
520         (c) += high;                    \
521         ret += low;                     \
522         (c) += (ret<low)?1:0;           \
523         (r) =  ret;                     \
524         }
525
526 #  define mul(r,a,w,c)    {               \
527         BN_ULONG high,low,ret,ta=(a);   \
528         BN_UMULT_LOHI(low,high,w,ta);   \
529         ret =  low + (c);               \
530         (c) =  high;                    \
531         (c) += (ret<low)?1:0;           \
532         (r) =  ret;                     \
533         }
534
535 #  define sqr(r0,r1,a)    {               \
536         BN_ULONG tmp=(a);               \
537         BN_UMULT_LOHI(r0,r1,tmp,tmp);   \
538         }
539
540 # elif defined(BN_UMULT_HIGH)
541 #  define mul_add(r,a,w,c) {              \
542         BN_ULONG high,low,ret,tmp=(a);  \
543         ret =  (r);                     \
544         high=  BN_UMULT_HIGH(w,tmp);    \
545         ret += (c);                     \
546         low =  (w) * tmp;               \
547         (c) =  (ret<(c))?1:0;           \
548         (c) += high;                    \
549         ret += low;                     \
550         (c) += (ret<low)?1:0;           \
551         (r) =  ret;                     \
552         }
553
554 #  define mul(r,a,w,c)    {               \
555         BN_ULONG high,low,ret,ta=(a);   \
556         low =  (w) * ta;                \
557         high=  BN_UMULT_HIGH(w,ta);     \
558         ret =  low + (c);               \
559         (c) =  high;                    \
560         (c) += (ret<low)?1:0;           \
561         (r) =  ret;                     \
562         }
563
564 #  define sqr(r0,r1,a)    {               \
565         BN_ULONG tmp=(a);               \
566         (r0) = tmp * tmp;               \
567         (r1) = BN_UMULT_HIGH(tmp,tmp);  \
568         }
569
570 # else
571 /*************************************************************
572  * No long long type
573  */
574
575 #  define LBITS(a)        ((a)&BN_MASK2l)
576 #  define HBITS(a)        (((a)>>BN_BITS4)&BN_MASK2l)
577 #  define L2HBITS(a)      (((a)<<BN_BITS4)&BN_MASK2)
578
579 #  define LLBITS(a)       ((a)&BN_MASKl)
580 #  define LHBITS(a)       (((a)>>BN_BITS2)&BN_MASKl)
581 #  define LL2HBITS(a)     ((BN_ULLONG)((a)&BN_MASKl)<<BN_BITS2)
582
583 #  define mul64(l,h,bl,bh) \
584         { \
585         BN_ULONG m,m1,lt,ht; \
586  \
587         lt=l; \
588         ht=h; \
589         m =(bh)*(lt); \
590         lt=(bl)*(lt); \
591         m1=(bl)*(ht); \
592         ht =(bh)*(ht); \
593         m=(m+m1)&BN_MASK2; if (m < m1) ht+=L2HBITS((BN_ULONG)1); \
594         ht+=HBITS(m); \
595         m1=L2HBITS(m); \
596         lt=(lt+m1)&BN_MASK2; if (lt < m1) ht++; \
597         (l)=lt; \
598         (h)=ht; \
599         }
600
601 #  define sqr64(lo,ho,in) \
602         { \
603         BN_ULONG l,h,m; \
604  \
605         h=(in); \
606         l=LBITS(h); \
607         h=HBITS(h); \
608         m =(l)*(h); \
609         l*=l; \
610         h*=h; \
611         h+=(m&BN_MASK2h1)>>(BN_BITS4-1); \
612         m =(m&BN_MASK2l)<<(BN_BITS4+1); \
613         l=(l+m)&BN_MASK2; if (l < m) h++; \
614         (lo)=l; \
615         (ho)=h; \
616         }
617
618 #  define mul_add(r,a,bl,bh,c) { \
619         BN_ULONG l,h; \
620  \
621         h= (a); \
622         l=LBITS(h); \
623         h=HBITS(h); \
624         mul64(l,h,(bl),(bh)); \
625  \
626         /* non-multiply part */ \
627         l=(l+(c))&BN_MASK2; if (l < (c)) h++; \
628         (c)=(r); \
629         l=(l+(c))&BN_MASK2; if (l < (c)) h++; \
630         (c)=h&BN_MASK2; \
631         (r)=l; \
632         }
633
634 #  define mul(r,a,bl,bh,c) { \
635         BN_ULONG l,h; \
636  \
637         h= (a); \
638         l=LBITS(h); \
639         h=HBITS(h); \
640         mul64(l,h,(bl),(bh)); \
641  \
642         /* non-multiply part */ \
643         l+=(c); if ((l&BN_MASK2) < (c)) h++; \
644         (c)=h&BN_MASK2; \
645         (r)=l&BN_MASK2; \
646         }
647 # endif                         /* !BN_LLONG */
648
649 void BN_RECP_CTX_init(BN_RECP_CTX *recp);
650 void BN_MONT_CTX_init(BN_MONT_CTX *ctx);
651
652 void bn_init(BIGNUM *a);
653 void bn_mul_normal(BN_ULONG *r, BN_ULONG *a, int na, BN_ULONG *b, int nb);
654 void bn_mul_comba8(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b);
655 void bn_mul_comba4(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b);
656 void bn_sqr_normal(BN_ULONG *r, const BN_ULONG *a, int n, BN_ULONG *tmp);
657 void bn_sqr_comba8(BN_ULONG *r, const BN_ULONG *a);
658 void bn_sqr_comba4(BN_ULONG *r, const BN_ULONG *a);
659 int bn_cmp_words(const BN_ULONG *a, const BN_ULONG *b, int n);
660 int bn_cmp_part_words(const BN_ULONG *a, const BN_ULONG *b, int cl, int dl);
661 void bn_mul_recursive(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, int n2,
662                       int dna, int dnb, BN_ULONG *t);
663 void bn_mul_part_recursive(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b,
664                            int n, int tna, int tnb, BN_ULONG *t);
665 void bn_sqr_recursive(BN_ULONG *r, const BN_ULONG *a, int n2, BN_ULONG *t);
666 void bn_mul_low_normal(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, int n);
667 void bn_mul_low_recursive(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, int n2,
668                           BN_ULONG *t);
669 void bn_mul_high(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, BN_ULONG *l, int n2,
670                  BN_ULONG *t);
671 BN_ULONG bn_add_part_words(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b,
672                            int cl, int dl);
673 BN_ULONG bn_sub_part_words(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b,
674                            int cl, int dl);
675 int bn_mul_mont(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp,
676                 const BN_ULONG *np, const BN_ULONG *n0, int num);
677
678 BIGNUM *int_bn_mod_inverse(BIGNUM *in,
679                            const BIGNUM *a, const BIGNUM *n, BN_CTX *ctx,
680                            int *noinv);
681
682 int bn_probable_prime_dh(BIGNUM *rnd, int bits,
683                          const BIGNUM *add, const BIGNUM *rem, BN_CTX *ctx);
684 int bn_probable_prime_dh_retry(BIGNUM *rnd, int bits, BN_CTX *ctx);
685 int bn_probable_prime_dh_coprime(BIGNUM *rnd, int bits, BN_CTX *ctx);
686
687 static ossl_inline BIGNUM *bn_expand(BIGNUM *a, int bits)
688 {
689     if (bits > (INT_MAX - BN_BITS2 + 1))
690         return NULL;
691
692     if (((bits+BN_BITS2-1)/BN_BITS2) <= (a)->dmax)
693         return a;
694
695     return bn_expand2((a),(bits+BN_BITS2-1)/BN_BITS2);
696 }
697
698 #ifdef  __cplusplus
699 }
700 #endif
701
702 #endif