2 * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
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
10 #include <openssl/bn.h>
11 #include "internal/cryptlib.h"
14 /* The old slow way */
16 int BN_div(BIGNUM *dv, BIGNUM *rem, const BIGNUM *m, const BIGNUM *d,
26 BNerr(BN_F_BN_DIV, BN_R_DIV_BY_ZERO);
30 if (BN_ucmp(m, d) < 0) {
32 if (BN_copy(rem, m) == NULL)
45 rem = BN_CTX_get(ctx);
46 if (D == NULL || dv == NULL || rem == NULL)
51 if (BN_copy(D, d) == NULL)
53 if (BN_copy(rem, m) == NULL)
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 :-)
61 if (bn_wexpand(dv, 1) == NULL)
65 if (!BN_lshift(D, D, nm - nd))
67 for (i = nm - nd; i >= 0; i--) {
68 if (!BN_lshift1(dv, dv))
70 if (BN_ucmp(rem, D) >= 0) {
72 if (!BN_usub(rem, rem, D))
75 /* CAN IMPROVE (and have now :=) */
76 if (!BN_rshift1(D, D))
79 rem->neg = BN_is_zero(rem) ? 0 : m->neg;
80 dv->neg = m->neg ^ d->neg;
89 # if defined(BN_DIV3W)
90 BN_ULONG bn_div_3_words(const BN_ULONG *m, BN_ULONG d1, BN_ULONG d0);
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.
97 # if BN_BITS2 == 64 && defined(__SIZEOF_INT128__) && __SIZEOF_INT128__==16
99 # define BN_ULLONG __uint128_t
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...
114 static BN_ULONG bn_div_3_words(const BN_ULONG *m, BN_ULONG d1, BN_ULONG d0)
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;
121 for (i = 0; i < BN_BITS2; i++) {
130 mask = 0 - (Q >> (BN_BITS2 - 1)); /* does it overflow? */
135 return (Q | mask) & BN_MASK2;
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__)
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:-)
153 # define bn_div_words(n0,n1,d0) \
156 : "=a"(q), "=d"(rem) \
157 : "a"(n1), "d"(n0), "r"(d0) \
161 # define REMAINDER_IS_ALREADY_CALCULATED
162 # elif defined(__x86_64) && defined(SIXTY_FOUR_BIT_LONG)
164 * Same story here, but it's 128-bit by 64-bit division. Wow!
167 # define bn_div_words(n0,n1,d0) \
170 : "=a"(q), "=d"(rem) \
171 : "a"(n1), "d"(n0), "r"(d0) \
175 # define REMAINDER_IS_ALREADY_CALCULATED
176 # endif /* __<cpu> */
177 # endif /* __GNUC__ */
178 # endif /* OPENSSL_NO_ASM */
181 * BN_div computes dv := num / divisor, rounding towards
182 * zero, and sets up rm such that dv*divisor + rm = num holds.
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.
188 int BN_div(BIGNUM *dv, BIGNUM *rm, const BIGNUM *num, const BIGNUM *divisor,
191 int norm_shift, i, j, loop;
192 BIGNUM *tmp, wnum, *snum, *sdiv, *res;
193 BN_ULONG *resp, *wnump;
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
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);
210 bn_check_top(divisor);
212 if ((BN_get_flags(num, BN_FLG_CONSTTIME) != 0)
213 || (BN_get_flags(divisor, BN_FLG_CONSTTIME) != 0)) {
219 /*- bn_check_top(num); *//*
220 * 'num' has been checked already
222 /*- bn_check_top(divisor); *//*
223 * 'divisor' has been checked already
226 if (BN_is_zero(divisor)) {
227 BNerr(BN_F_BN_DIV, BN_R_DIV_BY_ZERO);
231 if (!no_branch && BN_ucmp(num, divisor) < 0) {
233 if (BN_copy(rm, num) == NULL)
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);
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)))
254 norm_shift += BN_BITS2;
255 if (!(BN_lshift(snum, num, norm_shift)))
261 * Since we don't know whether snum is larger than sdiv, we pad snum
262 * with enough zeroes without changing its value.
264 if (snum->top <= sdiv->top + 1) {
265 if (bn_wexpand(snum, sdiv->top + 2) == NULL)
267 for (i = snum->top; i < sdiv->top + 2; i++)
269 snum->top = sdiv->top + 2;
271 if (bn_wexpand(snum, snum->top + 1) == NULL)
273 snum->d[snum->top] = 0;
280 loop = num_n - div_n;
282 * Lets setup a 'window' into snum This is the part that corresponds to
283 * the current 'area' being divided
286 wnum.d = &(snum->d[loop]);
288 wnum.flags = BN_FLG_STATIC_DATA;
290 * only needed when BN_ucmp messes up the values between top and max
292 wnum.dmax = snum->dmax - loop; /* so we don't step out of bounds */
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];
299 /* pointer to the 'top' of snum */
300 wnump = &(snum->d[num_n - 1]);
303 if (!bn_wexpand(res, (loop + 1)))
305 res->neg = (num->neg ^ divisor->neg);
306 res->top = loop - no_branch;
307 resp = &(res->d[loop - 1]);
310 if (!bn_wexpand(tmp, (div_n + 1)))
314 if (BN_ucmp(&wnum, sdiv) >= 0) {
316 * If BN_DEBUG_RAND is defined BN_ucmp changes (via bn_pollute)
317 * the const bignum arguments => clean the values between top and
320 bn_clear_top2max(&wnum);
321 bn_sub_words(wnum.d, wnum.d, sdiv->d, div_n);
327 /* Increase the resp pointer so that we never create an invalid pointer. */
331 * if res->top == 0 then clear the neg value otherwise decrease the resp
339 for (i = 0; i < loop - 1; i++, wnump--) {
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
345 # if defined(BN_DIV3W)
346 q = bn_div_3_words(wnump, d1, d0);
348 BN_ULONG n0, n1, rem = 0;
359 # if defined(BN_LLONG) && defined(BN_DIV2W) && !defined(bn_div_words)
360 q = (BN_ULONG)(((((BN_ULLONG) n0) << BN_BITS2) | n1) / d0);
362 q = bn_div_words(n0, n1, d0);
365 # ifndef REMAINDER_IS_ALREADY_CALCULATED
367 * rem doesn't have to be BN_ULLONG. The least we
368 * know it's less that d0, isn't it?
370 rem = (n1 - q * d0) & BN_MASK2;
372 t2 = (BN_ULLONG) d1 *q;
375 if (t2 <= ((((BN_ULLONG) rem) << BN_BITS2) | wnump[-2]))
380 break; /* don't let rem overflow */
383 # else /* !BN_LLONG */
386 q = bn_div_words(n0, n1, d0);
387 # ifndef REMAINDER_IS_ALREADY_CALCULATED
388 rem = (n1 - q * d0) & BN_MASK2;
391 # if defined(BN_UMULT_LOHI)
392 BN_UMULT_LOHI(t2l, t2h, d1, q);
393 # elif defined(BN_UMULT_HIGH)
395 t2h = BN_UMULT_HIGH(d1, q);
403 mul64(t2l, t2h, ql, qh); /* t2=(BN_ULLONG)d1*q; */
408 if ((t2h < rem) || ((t2h == rem) && (t2l <= wnump[-2])))
413 break; /* don't let rem overflow */
418 # endif /* !BN_LLONG */
420 # endif /* !BN_DIV3W */
422 l0 = bn_mul_words(tmp->d, sdiv->d, div_n, q);
426 * ingore top values of the bignums just sub the two BN_ULONG arrays
429 l0 = bn_sub_words(wnum.d, wnum.d, tmp->d, div_n + 1);
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)
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);
440 * we can't have an overflow here (assuming that q != 0, but
441 * if q == 0 then tmp is zero anyway)
445 /* store part of the result */
449 bn_correct_top(snum);
452 * Keep a copy of the neg flag in num because if rm==num BN_rshift()
456 BN_rshift(rm, snum, norm_shift);