bn/bn_div.c: make conditional addition unconditional
[openssl.git] / crypto / bn / bn_div.c
1 /*
2  * Copyright 1995-2018 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 #include <openssl/bn.h>
11 #include "internal/cryptlib.h"
12 #include "bn_lcl.h"
13
14 /* The old slow way */
15 #if 0
16 int BN_div(BIGNUM *dv, BIGNUM *rem, const BIGNUM *m, const BIGNUM *d,
17            BN_CTX *ctx)
18 {
19     int i, nm, nd;
20     int ret = 0;
21     BIGNUM *D;
22
23     bn_check_top(m);
24     bn_check_top(d);
25     if (BN_is_zero(d)) {
26         BNerr(BN_F_BN_DIV, BN_R_DIV_BY_ZERO);
27         return 0;
28     }
29
30     if (BN_ucmp(m, d) < 0) {
31         if (rem != NULL) {
32             if (BN_copy(rem, m) == NULL)
33                 return 0;
34         }
35         if (dv != NULL)
36             BN_zero(dv);
37         return 1;
38     }
39
40     BN_CTX_start(ctx);
41     D = BN_CTX_get(ctx);
42     if (dv == NULL)
43         dv = BN_CTX_get(ctx);
44     if (rem == NULL)
45         rem = BN_CTX_get(ctx);
46     if (D == NULL || dv == NULL || rem == NULL)
47         goto end;
48
49     nd = BN_num_bits(d);
50     nm = BN_num_bits(m);
51     if (BN_copy(D, d) == NULL)
52         goto end;
53     if (BN_copy(rem, m) == NULL)
54         goto end;
55
56     /*
57      * The next 2 are needed so we can do a dv->d[0]|=1 later since
58      * BN_lshift1 will only work once there is a value :-)
59      */
60     BN_zero(dv);
61     if (bn_wexpand(dv, 1) == NULL)
62         goto end;
63     dv->top = 1;
64
65     if (!BN_lshift(D, D, nm - nd))
66         goto end;
67     for (i = nm - nd; i >= 0; i--) {
68         if (!BN_lshift1(dv, dv))
69             goto end;
70         if (BN_ucmp(rem, D) >= 0) {
71             dv->d[0] |= 1;
72             if (!BN_usub(rem, rem, D))
73                 goto end;
74         }
75 /* CAN IMPROVE (and have now :=) */
76         if (!BN_rshift1(D, D))
77             goto end;
78     }
79     rem->neg = BN_is_zero(rem) ? 0 : m->neg;
80     dv->neg = m->neg ^ d->neg;
81     ret = 1;
82  end:
83     BN_CTX_end(ctx);
84     return ret;
85 }
86
87 #else
88
89 # if defined(BN_DIV3W)
90 BN_ULONG bn_div_3_words(const BN_ULONG *m, BN_ULONG d1, BN_ULONG d0);
91 # elif 0
92 /*
93  * This is #if-ed away, because it's a reference for assembly implementations,
94  * where it can and should be made constant-time. But if you want to test it,
95  * just replace 0 with 1.
96  */
97 #  if BN_BITS2 == 64 && defined(__SIZEOF_INT128__) && __SIZEOF_INT128__==16
98 #   undef BN_ULLONG
99 #   define BN_ULLONG __uint128_t
100 #   define BN_LLONG
101 #  endif
102
103 #  ifdef BN_LLONG
104 #   define BN_DIV3W
105 /*
106  * Interface is somewhat quirky, |m| is pointer to most significant limb,
107  * and less significant limb is referred at |m[-1]|. This means that caller
108  * is responsible for ensuring that |m[-1]| is valid. Second condition that
109  * has to be met is that |d0|'s most significant bit has to be set. Or in
110  * other words divisor has to be "bit-aligned to the left." bn_div_fixed_top
111  * does all this. The subroutine considers four limbs, two of which are
112  * "overlapping," hence the name...
113  */
114 static BN_ULONG bn_div_3_words(const BN_ULONG *m, BN_ULONG d1, BN_ULONG d0)
115 {
116     BN_ULLONG R = ((BN_ULLONG)m[0] << BN_BITS2) | m[-1];
117     BN_ULLONG D = ((BN_ULLONG)d0 << BN_BITS2) | d1;
118     BN_ULONG Q = 0, mask;
119     int i;
120
121     for (i = 0; i < BN_BITS2; i++) {
122         Q <<= 1;
123         if (R >= D) {
124             Q |= 1;
125             R -= D;
126         }
127         D >>= 1;
128     }
129
130     mask = 0 - (Q >> (BN_BITS2 - 1));   /* does it overflow? */
131
132     Q <<= 1;
133     Q |= (R >= D);
134
135     return (Q | mask) & BN_MASK2;
136 }
137 #  endif
138 # endif
139
140 # if !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_NO_INLINE_ASM) \
141     && !defined(PEDANTIC) && !defined(BN_DIV3W)
142 #  if defined(__GNUC__) && __GNUC__>=2
143 #   if defined(__i386) || defined (__i386__)
144    /*-
145     * There were two reasons for implementing this template:
146     * - GNU C generates a call to a function (__udivdi3 to be exact)
147     *   in reply to ((((BN_ULLONG)n0)<<BN_BITS2)|n1)/d0 (I fail to
148     *   understand why...);
149     * - divl doesn't only calculate quotient, but also leaves
150     *   remainder in %edx which we can definitely use here:-)
151     */
152 #    undef bn_div_words
153 #    define bn_div_words(n0,n1,d0)                \
154         ({  asm volatile (                      \
155                 "divl   %4"                     \
156                 : "=a"(q), "=d"(rem)            \
157                 : "a"(n1), "d"(n0), "r"(d0)     \
158                 : "cc");                        \
159             q;                                  \
160         })
161 #    define REMAINDER_IS_ALREADY_CALCULATED
162 #   elif defined(__x86_64) && defined(SIXTY_FOUR_BIT_LONG)
163    /*
164     * Same story here, but it's 128-bit by 64-bit division. Wow!
165     */
166 #    undef bn_div_words
167 #    define bn_div_words(n0,n1,d0)                \
168         ({  asm volatile (                      \
169                 "divq   %4"                     \
170                 : "=a"(q), "=d"(rem)            \
171                 : "a"(n1), "d"(n0), "r"(d0)     \
172                 : "cc");                        \
173             q;                                  \
174         })
175 #    define REMAINDER_IS_ALREADY_CALCULATED
176 #   endif                       /* __<cpu> */
177 #  endif                        /* __GNUC__ */
178 # endif                         /* OPENSSL_NO_ASM */
179
180 /*-
181  * BN_div computes  dv := num / divisor, rounding towards
182  * zero, and sets up rm  such that  dv*divisor + rm = num  holds.
183  * Thus:
184  *     dv->neg == num->neg ^ divisor->neg  (unless the result is zero)
185  *     rm->neg == num->neg                 (unless the remainder is zero)
186  * If 'dv' or 'rm' is NULL, the respective value is not returned.
187  */
188 int BN_div(BIGNUM *dv, BIGNUM *rm, const BIGNUM *num, const BIGNUM *divisor,
189            BN_CTX *ctx)
190 {
191     int norm_shift, i, j, loop;
192     BIGNUM *tmp, wnum, *snum, *sdiv, *res;
193     BN_ULONG *resp, *wnump;
194     BN_ULONG d0, d1;
195     int num_n, div_n;
196     int no_branch = 0;
197
198     /*
199      * Invalid zero-padding would have particularly bad consequences so don't
200      * just rely on bn_check_top() here (bn_check_top() works only for
201      * BN_DEBUG builds)
202      */
203     if ((num->top > 0 && num->d[num->top - 1] == 0) ||
204         (divisor->top > 0 && divisor->d[divisor->top - 1] == 0)) {
205         BNerr(BN_F_BN_DIV, BN_R_NOT_INITIALIZED);
206         return 0;
207     }
208
209     bn_check_top(num);
210     bn_check_top(divisor);
211
212     if ((BN_get_flags(num, BN_FLG_CONSTTIME) != 0)
213         || (BN_get_flags(divisor, BN_FLG_CONSTTIME) != 0)) {
214         no_branch = 1;
215     }
216
217     bn_check_top(dv);
218     bn_check_top(rm);
219     /*- bn_check_top(num); *//*
220      * 'num' has been checked already
221      */
222     /*- bn_check_top(divisor); *//*
223      * 'divisor' has been checked already
224      */
225
226     if (BN_is_zero(divisor)) {
227         BNerr(BN_F_BN_DIV, BN_R_DIV_BY_ZERO);
228         return 0;
229     }
230
231     if (!no_branch && BN_ucmp(num, divisor) < 0) {
232         if (rm != NULL) {
233             if (BN_copy(rm, num) == NULL)
234                 return 0;
235         }
236         if (dv != NULL)
237             BN_zero(dv);
238         return 1;
239     }
240
241     BN_CTX_start(ctx);
242     res = (dv == NULL) ? BN_CTX_get(ctx) : dv;
243     tmp = BN_CTX_get(ctx);
244     snum = BN_CTX_get(ctx);
245     sdiv = BN_CTX_get(ctx);
246     if (sdiv == NULL)
247         goto err;
248
249     /* First we normalise the numbers */
250     norm_shift = BN_BITS2 - ((BN_num_bits(divisor)) % BN_BITS2);
251     if (!(BN_lshift(sdiv, divisor, norm_shift)))
252         goto err;
253     sdiv->neg = 0;
254     norm_shift += BN_BITS2;
255     if (!(BN_lshift(snum, num, norm_shift)))
256         goto err;
257     snum->neg = 0;
258
259     if (no_branch) {
260         /*
261          * Since we don't know whether snum is larger than sdiv, we pad snum
262          * with enough zeroes without changing its value.
263          */
264         if (snum->top <= sdiv->top + 1) {
265             if (bn_wexpand(snum, sdiv->top + 2) == NULL)
266                 goto err;
267             for (i = snum->top; i < sdiv->top + 2; i++)
268                 snum->d[i] = 0;
269             snum->top = sdiv->top + 2;
270         } else {
271             if (bn_wexpand(snum, snum->top + 1) == NULL)
272                 goto err;
273             snum->d[snum->top] = 0;
274             snum->top++;
275         }
276     }
277
278     div_n = sdiv->top;
279     num_n = snum->top;
280     loop = num_n - div_n;
281     /*
282      * Lets setup a 'window' into snum This is the part that corresponds to
283      * the current 'area' being divided
284      */
285     wnum.neg = 0;
286     wnum.d = &(snum->d[loop]);
287     wnum.top = div_n;
288     wnum.flags = BN_FLG_STATIC_DATA;
289     /*
290      * only needed when BN_ucmp messes up the values between top and max
291      */
292     wnum.dmax = snum->dmax - loop; /* so we don't step out of bounds */
293
294     /* Get the top 2 words of sdiv */
295     /* div_n=sdiv->top; */
296     d0 = sdiv->d[div_n - 1];
297     d1 = (div_n == 1) ? 0 : sdiv->d[div_n - 2];
298
299     /* pointer to the 'top' of snum */
300     wnump = &(snum->d[num_n - 1]);
301
302     /* Setup to 'res' */
303     if (!bn_wexpand(res, (loop + 1)))
304         goto err;
305     res->neg = (num->neg ^ divisor->neg);
306     res->top = loop - no_branch;
307     resp = &(res->d[loop - 1]);
308
309     /* space for temp */
310     if (!bn_wexpand(tmp, (div_n + 1)))
311         goto err;
312
313     if (!no_branch) {
314         if (BN_ucmp(&wnum, sdiv) >= 0) {
315             /*
316              * If BN_DEBUG_RAND is defined BN_ucmp changes (via bn_pollute)
317              * the const bignum arguments => clean the values between top and
318              * max again
319              */
320             bn_clear_top2max(&wnum);
321             bn_sub_words(wnum.d, wnum.d, sdiv->d, div_n);
322             *resp = 1;
323         } else
324             res->top--;
325     }
326
327     /* Increase the resp pointer so that we never create an invalid pointer. */
328     resp++;
329
330     /*
331      * if res->top == 0 then clear the neg value otherwise decrease the resp
332      * pointer
333      */
334     if (res->top == 0)
335         res->neg = 0;
336     else
337         resp--;
338
339     for (i = 0; i < loop - 1; i++, wnump--) {
340         BN_ULONG q, l0;
341         /*
342          * the first part of the loop uses the top two words of snum and sdiv
343          * to calculate a BN_ULONG q such that | wnum - sdiv * q | < sdiv
344          */
345 # if defined(BN_DIV3W)
346         q = bn_div_3_words(wnump, d1, d0);
347 # else
348         BN_ULONG n0, n1, rem = 0;
349
350         n0 = wnump[0];
351         n1 = wnump[-1];
352         if (n0 == d0)
353             q = BN_MASK2;
354         else {                  /* n0 < d0 */
355
356 #  ifdef BN_LLONG
357             BN_ULLONG t2;
358
359 #   if defined(BN_LLONG) && defined(BN_DIV2W) && !defined(bn_div_words)
360             q = (BN_ULONG)(((((BN_ULLONG) n0) << BN_BITS2) | n1) / d0);
361 #   else
362             q = bn_div_words(n0, n1, d0);
363 #   endif
364
365 #   ifndef REMAINDER_IS_ALREADY_CALCULATED
366             /*
367              * rem doesn't have to be BN_ULLONG. The least we
368              * know it's less that d0, isn't it?
369              */
370             rem = (n1 - q * d0) & BN_MASK2;
371 #   endif
372             t2 = (BN_ULLONG) d1 *q;
373
374             for (;;) {
375                 if (t2 <= ((((BN_ULLONG) rem) << BN_BITS2) | wnump[-2]))
376                     break;
377                 q--;
378                 rem += d0;
379                 if (rem < d0)
380                     break;      /* don't let rem overflow */
381                 t2 -= d1;
382             }
383 #  else                         /* !BN_LLONG */
384             BN_ULONG t2l, t2h;
385
386             q = bn_div_words(n0, n1, d0);
387 #   ifndef REMAINDER_IS_ALREADY_CALCULATED
388             rem = (n1 - q * d0) & BN_MASK2;
389 #   endif
390
391 #   if defined(BN_UMULT_LOHI)
392             BN_UMULT_LOHI(t2l, t2h, d1, q);
393 #   elif defined(BN_UMULT_HIGH)
394             t2l = d1 * q;
395             t2h = BN_UMULT_HIGH(d1, q);
396 #   else
397             {
398                 BN_ULONG ql, qh;
399                 t2l = LBITS(d1);
400                 t2h = HBITS(d1);
401                 ql = LBITS(q);
402                 qh = HBITS(q);
403                 mul64(t2l, t2h, ql, qh); /* t2=(BN_ULLONG)d1*q; */
404             }
405 #   endif
406
407             for (;;) {
408                 if ((t2h < rem) || ((t2h == rem) && (t2l <= wnump[-2])))
409                     break;
410                 q--;
411                 rem += d0;
412                 if (rem < d0)
413                     break;      /* don't let rem overflow */
414                 if (t2l < d1)
415                     t2h--;
416                 t2l -= d1;
417             }
418 #  endif                        /* !BN_LLONG */
419         }
420 # endif                         /* !BN_DIV3W */
421
422         l0 = bn_mul_words(tmp->d, sdiv->d, div_n, q);
423         tmp->d[div_n] = l0;
424         wnum.d--;
425         /*
426          * ingore top values of the bignums just sub the two BN_ULONG arrays
427          * with bn_sub_words
428          */
429         l0 = bn_sub_words(wnum.d, wnum.d, tmp->d, div_n + 1);
430         q -= l0;
431         /*
432          * Note: As we have considered only the leading two BN_ULONGs in
433          * the calculation of q, sdiv * q might be greater than wnum (but
434          * then (q-1) * sdiv is less or equal than wnum)
435          */
436         for (l0 = 0 - l0, j = 0; j < div_n; j++)
437             tmp->d[j] = sdiv->d[j] & l0;
438         l0 = bn_add_words(wnum.d, wnum.d, tmp->d, div_n);
439         /*
440          * we can't have an overflow here (assuming that q != 0, but
441          * if q == 0 then tmp is zero anyway)
442          */
443         (*wnump) += l0;
444
445         /* store part of the result */
446         resp--;
447         *resp = q;
448     }
449     bn_correct_top(snum);
450     if (rm != NULL) {
451         /*
452          * Keep a copy of the neg flag in num because if rm==num BN_rshift()
453          * will overwrite it.
454          */
455         int neg = num->neg;
456         BN_rshift(rm, snum, norm_shift);
457         if (!BN_is_zero(rm))
458             rm->neg = neg;
459         bn_check_top(rm);
460     }
461     if (no_branch)
462         bn_correct_top(res);
463     BN_CTX_end(ctx);
464     return 1;
465  err:
466     bn_check_top(rm);
467     BN_CTX_end(ctx);
468     return 0;
469 }
470 #endif