Debian Codegraph @

js/src/vm/BigIntType.cpp

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 /*
8 * Portions of this code taken from WebKit, whose copyright is as follows:
9 *
10 * Copyright (C) 2017 Caio Lima <[email protected]>
11 * Copyright (C) 2017-2018 Apple Inc. All rights reserved.
12 *
13 * Redistribution and use in source and binary forms, with or without
14 * modification, are permitted provided that the following conditions
15 * are met:
16 * 1. Redistributions of source code must retain the above copyright
17 * notice, this list of conditions and the following disclaimer.
18 * 2. Redistributions in binary form must reproduce the above copyright
19 * notice, this list of conditions and the following disclaimer in the
20 * documentation and/or other materials provided with the distribution.
21 *
22 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
23 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
25 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
26 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
27 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
28 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
29 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
30 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
32 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 *
34 * Portions of this code taken from V8, whose copyright notice is as follows:
35 *
36 * Copyright 2017 the V8 project authors. All rights reserved.
37 * Redistribution and use in source and binary forms, with or without
38 * modification, are permitted provided that the following conditions are
39 * met:
40 * * Redistributions of source code must retain the above copyright
41 * notice, this list of conditions and the following disclaimer.
42 * * Redistributions in binary form must reproduce the above
43 * copyright notice, this list of conditions and the following
44 * disclaimer in the documentation and/or other materials provided
45 * with the distribution.
46 * * Neither the name of Google Inc. nor the names of its
47 * contributors may be used to endorse or promote products derived
48 * from this software without specific prior written permission.
49 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
50 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
51 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
52 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
53 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
54 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
55 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
56 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
57 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
58 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
59 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
60 *
61 * Portions of this code taken from Dart, whose copyright notice is as follows:
62 *
63 * Copyright (c) 2014 the Dart project authors. Please see the AUTHORS file
64 * [1] for details. All rights reserved. Use of this source code is governed by
65 * a BSD-style license that can be found in the LICENSE file [2].
66 *
67 * [1] https://github.com/dart-lang/sdk/blob/master/AUTHORS
68 * [2] https://github.com/dart-lang/sdk/blob/master/LICENSE
69 *
70 * Portions of this code taken from Go, whose copyright notice is as follows:
71 *
72 * Copyright 2009 The Go Authors. All rights reserved.
73 * Use of this source code is governed by a BSD-style
74 * license that can be found in the LICENSE file [3].
75 *
76 * [3] https://golang.org/LICENSE
77 */
78
79 #include "vm/BigIntType.h"
80
81 #include "mozilla/Casting.h"
82 #include "mozilla/CheckedInt.h"
83 #include "mozilla/FloatingPoint.h"
84 #include "mozilla/HashFunctions.h"
85 #include "mozilla/MathAlgorithms.h"
86 #include "mozilla/Maybe.h"
87 #include "mozilla/MemoryChecking.h"
88 #include "mozilla/Range.h"
89 #include "mozilla/RangedPtr.h"
90 #include "mozilla/Span.h" // mozilla::Span
91 #include "mozilla/TextUtils.h"
92 #include "mozilla/Try.h"
93 #include "mozilla/WrappingOperations.h"
94
95 #include <charconv>
96 #include <functional>
97 #include <limits>
98 #include <memory>
99 #include <type_traits> // std::is_same_v
100
101 #include "jsnum.h"
102
103 #include "gc/GCEnum.h"
104 #include "js/BigInt.h"
105 #include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_*
106 #include "js/Printer.h" // js::GenericPrinter
107 #include "js/StableStringChars.h"
108 #include "js/Utility.h"
109 #include "util/CheckedArithmetic.h"
110 #include "util/DifferentialTesting.h"
111 #include "vm/JSONPrinter.h" // js::JSONPrinter
112 #include "vm/StaticStrings.h"
113
114 #include "gc/GCContext-inl.h"
115 #include "gc/Nursery-inl.h"
116 #include "vm/JSContext-inl.h"
117 #include "vm/StringType-inl.h"
118
119 using namespace js;
120
121 using JS::AutoStableStringChars;
122 using mozilla::Abs;
123 using mozilla::AssertedCast;
124 using mozilla::Maybe;
125 using mozilla::NegativeInfinity;
126 using mozilla::Nothing;
127 using mozilla::PositiveInfinity;
128 using mozilla::Range;
129 using mozilla::RangedPtr;
130 using mozilla::Some;
131 using mozilla::WrapToSigned;
132
133 static inline unsigned DigitLeadingZeroes(BigInt::Digit x) {
134 return sizeof(x) == 4 ? mozilla::CountLeadingZeroes32(x)
135 : mozilla::CountLeadingZeroes64(x);
136 }
137
138 #ifdef DEBUG
139 static bool HasLeadingZeroes(const BigInt* bi) {
140 return bi->digitLength() > 0 && bi->digit(bi->digitLength() - 1) == 0;
141 }
142 #endif
143
144 BigInt* BigInt::createUninitialized(JSContext* cx, size_t digitLength,
145 bool isNegative, gc::Heap heap) {
146 if (digitLength > MaxDigitLength) {
147 ReportOversizedAllocation(cx, JSMSG_BIGINT_TOO_LARGE);
148 return nullptr;
149 }
150
151 BigInt* x = cx->newCell<BigInt>(heap);
152 if (!x) {
153 return nullptr;
154 }
155
156 x->setLengthAndFlags(digitLength, isNegative ? SignBit : 0);
157
158 MOZ_ASSERT(x->digitLength() == digitLength);
159 MOZ_ASSERT(x->isNegative() == isNegative);
160
161 if (digitLength > InlineDigitsLength) {
162 x->heapDigits_ = js::AllocNurseryOrMallocBuffer<Digit>(cx, x, digitLength);
163 if (!x->heapDigits_) {
164 // |x| is partially initialized, expose it as a BigInt using inline digits
165 // to the GC.
166 x->setLengthAndFlags(0, 0);
167 return nullptr;
168 }
169
170 AddCellMemory(x, digitLength * sizeof(Digit), js::MemoryUse::BigIntDigits);
171 }
172
173 return x;
174 }
175
176 void BigInt::initializeDigitsToZero() {
177 auto digs = digits();
178 std::uninitialized_fill_n(digs.begin(), digs.Length(), 0);
179 }
180
181 void BigInt::finalize(JS::GCContext* gcx) {
182 MOZ_ASSERT(isTenured());
183 if (hasHeapDigits()) {
184 size_t size = digitLength() * sizeof(Digit);
185 gcx->free_(this, heapDigits_, size, js::MemoryUse::BigIntDigits);
186 }
187 }
188
189 js::HashNumber BigInt::hash() const {
190 js::HashNumber h =
191 mozilla::HashBytes(digits().data(), digitLength() * sizeof(Digit));
192 return mozilla::AddToHash(h, isNegative());
193 }
194
195 size_t BigInt::sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const {
196 return hasInlineDigits() ? 0 : mallocSizeOf(heapDigits_);
197 }
198
199 size_t BigInt::sizeOfExcludingThisInNursery(
200 mozilla::MallocSizeOf mallocSizeOf) const {
201 MOZ_ASSERT(!isTenured());
202
203 if (hasInlineDigits()) {
204 return 0;
205 }
206
207 const Nursery& nursery = runtimeFromMainThread()->gc.nursery();
208 if (nursery.isInside(heapDigits_)) {
209 // Buffer allocations are aligned to the size of JS::Value.
210 return RoundUp(digitLength() * sizeof(Digit), sizeof(Value));
211 }
212
213 return mallocSizeOf(heapDigits_);
214 }
215
216 BigInt* BigInt::zero(JSContext* cx, gc::Heap heap) {
217 return createUninitialized(cx, 0, false, heap);
218 }
219
220 BigInt* BigInt::createFromDigit(JSContext* cx, Digit d, bool isNegative,
221 gc::Heap heap) {
222 MOZ_ASSERT(d != 0);
223 BigInt* res = createUninitialized(cx, 1, isNegative, heap);
224 if (!res) {
225 return nullptr;
226 }
227 res->setDigit(0, d);
228 return res;
229 }
230
231 BigInt* BigInt::one(JSContext* cx) { return createFromDigit(cx, 1, false); }
232
233 BigInt* BigInt::negativeOne(JSContext* cx) {
234 return createFromDigit(cx, 1, true);
235 }
236
237 BigInt* BigInt::createFromNonZeroRawUint64(JSContext* cx, uint64_t n,
238 bool isNegative) {
239 MOZ_ASSERT(n != 0);
240
241 size_t resultLength = 1;
242 if (DigitBits == 32 && (n >> 32) != 0) {
243 resultLength = 2;
244 }
245
246 BigInt* result = createUninitialized(cx, resultLength, isNegative);
247 if (!result) {
248 return nullptr;
249 }
250 result->setDigit(0, n);
251 if (DigitBits == 32 && resultLength > 1) {
252 result->setDigit(1, n >> 32);
253 }
254
255 MOZ_ASSERT(!HasLeadingZeroes(result));
256 return result;
257 }
258
259 BigInt* BigInt::neg(JSContext* cx, HandleBigInt x) {
260 if (x->isZero()) {
261 return x;
262 }
263
264 BigInt* result = copy(cx, x);
265 if (!result) {
266 return nullptr;
267 }
268 result->toggleHeaderFlagBit(SignBit);
269 return result;
270 }
271
272 #if !defined(JS_64BIT)
273 # define HAVE_TWO_DIGIT 1
274 using TwoDigit = uint64_t;
275 #elif defined(__SIZEOF_INT128__)
276 # define HAVE_TWO_DIGIT 1
277 using TwoDigit = __uint128_t;
278 #endif
279
280 inline BigInt::Digit BigInt::digitMul(Digit a, Digit b, Digit* high) {
281 #if defined(HAVE_TWO_DIGIT)
282 TwoDigit result = static_cast<TwoDigit>(a) * static_cast<TwoDigit>(b);
283 *high = result >> DigitBits;
284
285 return static_cast<Digit>(result);
286 #else
287 // Multiply in half-pointer-sized chunks.
288 // For inputs [AH AL]*[BH BL], the result is:
289 //
290 // [AL*BL] // rLow
291 // + [AL*BH] // rMid1
292 // + [AH*BL] // rMid2
293 // + [AH*BH] // rHigh
294 // = [R4 R3 R2 R1] // high = [R4 R3], low = [R2 R1]
295 //
296 // Where of course we must be careful with carries between the columns.
297 Digit aLow = a & HalfDigitMask;
298 Digit aHigh = a >> HalfDigitBits;
299 Digit bLow = b & HalfDigitMask;
300 Digit bHigh = b >> HalfDigitBits;
301
302 Digit rLow = aLow * bLow;
303 Digit rMid1 = aLow * bHigh;
304 Digit rMid2 = aHigh * bLow;
305 Digit rHigh = aHigh * bHigh;
306
307 Digit carry = 0;
308 Digit low = digitAdd(rLow, rMid1 << HalfDigitBits, &carry);
309 low = digitAdd(low, rMid2 << HalfDigitBits, &carry);
310
311 *high = (rMid1 >> HalfDigitBits) + (rMid2 >> HalfDigitBits) + rHigh + carry;
312
313 return low;
314 #endif
315 }
316
317 BigInt::Digit BigInt::digitDiv(Digit high, Digit low, Digit divisor,
318 Digit* remainder) {
319 MOZ_ASSERT(high < divisor, "division must not overflow");
320 #if defined(__x86_64__)
321 Digit quotient;
322 Digit rem;
323 __asm__("divq %[divisor]"
324 // Outputs: `quotient` will be in rax, `rem` in rdx.
325 : "=a"(quotient), "=d"(rem)
326 // Inputs: put `high` into rdx, `low` into rax, and `divisor` into
327 // any register or stack slot.
328 : "d"(high), "a"(low), [divisor] "rm"(divisor));
329 *remainder = rem;
330 return quotient;
331 #elif defined(__i386__)
332 Digit quotient;
333 Digit rem;
334 __asm__("divl %[divisor]"
335 // Outputs: `quotient` will be in eax, `rem` in edx.
336 : "=a"(quotient), "=d"(rem)
337 // Inputs: put `high` into edx, `low` into eax, and `divisor` into
338 // any register or stack slot.
339 : "d"(high), "a"(low), [divisor] "rm"(divisor));
340 *remainder = rem;
341 return quotient;
342 #else
343 static constexpr Digit HalfDigitBase = 1ull << HalfDigitBits;
344 // Adapted from Warren, Hacker's Delight, p. 152.
345 unsigned s = DigitLeadingZeroes(divisor);
346 // If `s` is DigitBits here, it causes an undefined behavior.
347 // But `s` is never DigitBits since `divisor` is never zero here.
348 MOZ_ASSERT(s != DigitBits);
349 divisor <<= s;
350
351 Digit vn1 = divisor >> HalfDigitBits;
352 Digit vn0 = divisor & HalfDigitMask;
353
354 // `sZeroMask` which is 0 if s == 0 and all 1-bits otherwise.
355 //
356 // `s` can be 0. If `s` is 0, performing "low >> (DigitBits - s)" must not
357 // be done since it causes an undefined behavior since `>> DigitBits` is
358 // undefined in C++. Quoted from C++ spec, "The type of the result is that of
359 // the promoted left operand.
360 //
361 // The behavior is undefined if the right operand is negative, or greater
362 // than or equal to the length in bits of the promoted left operand". We
363 // mask the right operand of the shift by `shiftMask` (`DigitBits - 1`),
364 // which makes `DigitBits - 0` zero.
365 //
366 // This shifting produces a value which covers 0 < `s` <= (DigitBits - 1)
367 // cases. `s` == DigitBits never happen as we asserted. Since `sZeroMask`
368 // clears the value in the case of `s` == 0, `s` == 0 case is also covered.
369 static_assert(sizeof(intptr_t) == sizeof(Digit),
370 "unexpected size of BigInt::Digit");
371 Digit sZeroMask =
372 static_cast<Digit>((-static_cast<intptr_t>(s)) >> (DigitBits - 1));
373 static constexpr unsigned shiftMask = DigitBits - 1;
374 Digit un32 =
375 (high << s) | ((low >> ((DigitBits - s) & shiftMask)) & sZeroMask);
376
377 Digit un10 = low << s;
378 Digit un1 = un10 >> HalfDigitBits;
379 Digit un0 = un10 & HalfDigitMask;
380 Digit q1 = un32 / vn1;
381 Digit rhat = un32 - q1 * vn1;
382
383 while (q1 >= HalfDigitBase || q1 * vn0 > rhat * HalfDigitBase + un1) {
384 q1--;
385 rhat += vn1;
386 if (rhat >= HalfDigitBase) {
387 break;
388 }
389 }
390
391 Digit un21 = un32 * HalfDigitBase + un1 - q1 * divisor;
392 Digit q0 = un21 / vn1;
393 rhat = un21 - q0 * vn1;
394
395 while (q0 >= HalfDigitBase || q0 * vn0 > rhat * HalfDigitBase + un0) {
396 q0--;
397 rhat += vn1;
398 if (rhat >= HalfDigitBase) {
399 break;
400 }
401 }
402
403 *remainder = (un21 * HalfDigitBase + un0 - q0 * divisor) >> s;
404 return q1 * HalfDigitBase + q0;
405 #endif
406 }
407
408 // Multiplies `source` with `factor` and adds `summand` to the result.
409 // `result` and `source` may be the same BigInt for inplace modification.
410 void BigInt::internalMultiplyAdd(const BigInt* source, Digit factor,
411 Digit summand, unsigned n, BigInt* result) {
412 MOZ_ASSERT(source->digitLength() >= n);
413 MOZ_ASSERT(result->digitLength() >= n);
414
415 Digit carry = summand;
416 Digit high = 0;
417 for (unsigned i = 0; i < n; i++) {
418 Digit current = source->digit(i);
419 Digit newCarry = 0;
420
421 // Compute this round's multiplication.
422 Digit newHigh = 0;
423 current = digitMul(current, factor, &newHigh);
424
425 // Add last round's carryovers.
426 current = digitAdd(current, high, &newCarry);
427 current = digitAdd(current, carry, &newCarry);
428
429 // Store result and prepare for next round.
430 result->setDigit(i, current);
431 carry = newCarry;
432 high = newHigh;
433 }
434
435 if (result->digitLength() > n) {
436 result->setDigit(n++, carry + high);
437
438 // Current callers don't pass in such large results, but let's be robust.
439 while (n < result->digitLength()) {
440 result->setDigit(n++, 0);
441 }
442 } else {
443 MOZ_ASSERT(!(carry + high));
444 }
445 }
446
447 // Multiplies `this` with `factor` and adds `summand` to the result.
448 void BigInt::inplaceMultiplyAdd(Digit factor, Digit summand) {
449 internalMultiplyAdd(this, factor, summand, digitLength(), this);
450 }
451
452 // Multiplies `multiplicand` with `multiplier` and adds the result to
453 // `accumulator`, starting at `accumulatorIndex` for the least-significant
454 // digit. Callers must ensure that `accumulator`'s digitLength and
455 // corresponding digit storage is long enough to hold the result.
456 void BigInt::multiplyAccumulate(const BigInt* multiplicand, Digit multiplier,
457 BigInt* accumulator,
458 unsigned accumulatorIndex) {
459 MOZ_ASSERT(accumulator->digitLength() >
460 multiplicand->digitLength() + accumulatorIndex);
461 if (!multiplier) {
462 return;
463 }
464
465 Digit carry = 0;
466 Digit high = 0;
467 for (unsigned i = 0; i < multiplicand->digitLength();
468 i++, accumulatorIndex++) {
469 Digit acc = accumulator->digit(accumulatorIndex);
470 Digit newCarry = 0;
471
472 // Add last round's carryovers.
473 acc = digitAdd(acc, high, &newCarry);
474 acc = digitAdd(acc, carry, &newCarry);
475
476 // Compute this round's multiplication.
477 Digit multiplicandDigit = multiplicand->digit(i);
478 Digit low = digitMul(multiplier, multiplicandDigit, &high);
479 acc = digitAdd(acc, low, &newCarry);
480
481 // Store result and prepare for next round.
482 accumulator->setDigit(accumulatorIndex, acc);
483 carry = newCarry;
484 }
485
486 while (carry || high) {
487 MOZ_ASSERT(accumulatorIndex < accumulator->digitLength());
488 Digit acc = accumulator->digit(accumulatorIndex);
489 Digit newCarry = 0;
490 acc = digitAdd(acc, high, &newCarry);
491 high = 0;
492 acc = digitAdd(acc, carry, &newCarry);
493 accumulator->setDigit(accumulatorIndex, acc);
494 carry = newCarry;
495 accumulatorIndex++;
496 }
497 }
498
499 inline int8_t BigInt::absoluteCompare(const BigInt* x, const BigInt* y) {
500 MOZ_ASSERT(!HasLeadingZeroes(x));
501 MOZ_ASSERT(!HasLeadingZeroes(y));
502
503 // Sanity checks to catch negative zeroes escaping to the wild.
504 MOZ_ASSERT(!x->isNegative() || !x->isZero());
505 MOZ_ASSERT(!y->isNegative() || !y->isZero());
506
507 int diff = x->digitLength() - y->digitLength();
508 if (diff) {
509 return diff < 0 ? -1 : 1;
510 }
511
512 int i = x->digitLength() - 1;
513 while (i >= 0 && x->digit(i) == y->digit(i)) {
514 i--;
515 }
516
517 if (i < 0) {
518 return 0;
519 }
520
521 return x->digit(i) > y->digit(i) ? 1 : -1;
522 }
523
524 BigInt* BigInt::absoluteAdd(JSContext* cx, HandleBigInt x, HandleBigInt y,
525 bool resultNegative) {
526 bool swap = x->digitLength() < y->digitLength();
527 // Ensure `left` has at least as many digits as `right`.
528 HandleBigInt& left = swap ? y : x;
529 HandleBigInt& right = swap ? x : y;
530
531 if (left->isZero()) {
532 MOZ_ASSERT(right->isZero());
533 return left;
534 }
535
536 if (right->isZero()) {
537 return resultNegative == left->isNegative() ? left : neg(cx, left);
538 }
539
540 // Fast path for the likely-common case of up to a uint64_t of magnitude.
541 if (left->absFitsInUint64()) {
542 MOZ_ASSERT(right->absFitsInUint64());
543
544 uint64_t lhs = left->uint64FromAbsNonZero();
545 uint64_t rhs = right->uint64FromAbsNonZero();
546
547 uint64_t res = lhs + rhs;
548 bool overflow = res < lhs;
549 MOZ_ASSERT(res != 0 || overflow);
550
551 size_t resultLength = 1;
552 if (DigitBits == 32) {
553 if (overflow) {
554 resultLength = 3;
555 } else if (res >> 32) {
556 resultLength = 2;
557 }
558 } else {
559 if (overflow) {
560 resultLength = 2;
561 }
562 }
563 BigInt* result = createUninitialized(cx, resultLength, resultNegative);
564 if (!result) {
565 return nullptr;
566 }
567 result->setDigit(0, res);
568 if (DigitBits == 32 && resultLength > 1) {
569 result->setDigit(1, res >> 32);
570 }
571 if (overflow) {
572 constexpr size_t overflowIndex = DigitBits == 32 ? 2 : 1;
573 result->setDigit(overflowIndex, 1);
574 }
575
576 MOZ_ASSERT(!HasLeadingZeroes(result));
577 return result;
578 }
579
580 BigInt* result =
581 createUninitialized(cx, left->digitLength() + 1, resultNegative);
582 if (!result) {
583 return nullptr;
584 }
585 Digit carry = 0;
586 unsigned i = 0;
587 for (; i < right->digitLength(); i++) {
588 Digit newCarry = 0;
589 Digit sum = digitAdd(left->digit(i), right->digit(i), &newCarry);
590 sum = digitAdd(sum, carry, &newCarry);
591 result->setDigit(i, sum);
592 carry = newCarry;
593 }
594
595 for (; i < left->digitLength(); i++) {
596 Digit newCarry = 0;
597 Digit sum = digitAdd(left->digit(i), carry, &newCarry);
598 result->setDigit(i, sum);
599 carry = newCarry;
600 }
601
602 result->setDigit(i, carry);
603
604 return destructivelyTrimHighZeroDigits(cx, result);
605 }
606
607 BigInt* BigInt::absoluteSub(JSContext* cx, HandleBigInt x, HandleBigInt y,
608 bool resultNegative) {
609 MOZ_ASSERT(x->digitLength() >= y->digitLength());
610 MOZ_ASSERT(absoluteCompare(x, y) > 0);
611 MOZ_ASSERT(!x->isZero());
612
613 if (y->isZero()) {
614 return resultNegative == x->isNegative() ? x : neg(cx, x);
615 }
616
617 // Fast path for the likely-common case of up to a uint64_t of magnitude.
618 if (x->absFitsInUint64()) {
619 MOZ_ASSERT(y->absFitsInUint64());
620
621 uint64_t lhs = x->uint64FromAbsNonZero();
622 uint64_t rhs = y->uint64FromAbsNonZero();
623 MOZ_ASSERT(lhs > rhs);
624
625 uint64_t res = lhs - rhs;
626 MOZ_ASSERT(res != 0);
627
628 return createFromNonZeroRawUint64(cx, res, resultNegative);
629 }
630
631 BigInt* result = createUninitialized(cx, x->digitLength(), resultNegative);
632 if (!result) {
633 return nullptr;
634 }
635 Digit borrow = 0;
636 unsigned i = 0;
637 for (; i < y->digitLength(); i++) {
638 Digit newBorrow = 0;
639 Digit difference = digitSub(x->digit(i), y->digit(i), &newBorrow);
640 difference = digitSub(difference, borrow, &newBorrow);
641 result->setDigit(i, difference);
642 borrow = newBorrow;
643 }
644
645 for (; i < x->digitLength(); i++) {
646 Digit newBorrow = 0;
647 Digit difference = digitSub(x->digit(i), borrow, &newBorrow);
648 result->setDigit(i, difference);
649 borrow = newBorrow;
650 }
651
652 MOZ_ASSERT(!borrow);
653 return destructivelyTrimHighZeroDigits(cx, result);
654 }
655
656 // Divides `x` by `divisor`, returning the result in `quotient` and `remainder`.
657 // Mathematically, the contract is:
658 //
659 // quotient = (x - remainder) / divisor, with 0 <= remainder < divisor.
660 //
661 // If `quotient` is an empty handle, an appropriately sized BigInt will be
662 // allocated for it; otherwise the caller must ensure that it is big enough.
663 // `quotient` can be the same as `x` for an in-place division. `quotient` can
664 // also be `Nothing()` if the caller is only interested in the remainder.
665 //
666 // This function returns false if `quotient` is an empty handle, but allocating
667 // the quotient failed. Otherwise it returns true, indicating success.
668 bool BigInt::absoluteDivWithDigitDivisor(
669 JSContext* cx, HandleBigInt x, Digit divisor,
670 const Maybe<MutableHandleBigInt>& quotient, Digit* remainder,
671 bool quotientNegative) {
672 MOZ_ASSERT(divisor);
673
674 MOZ_ASSERT(!x->isZero());
675 *remainder = 0;
676 if (divisor == 1) {
677 if (quotient) {
678 BigInt* q;
679 if (x->isNegative() == quotientNegative) {
680 q = x;
681 } else {
682 q = neg(cx, x);
683 if (!q) {
684 return false;
685 }
686 }
687 quotient.value().set(q);
688 }
689 return true;
690 }
691
692 unsigned length = x->digitLength();
693 if (quotient) {
694 if (!quotient.value()) {
695 BigInt* q = createUninitialized(cx, length, quotientNegative);
696 if (!q) {
697 return false;
698 }
699 quotient.value().set(q);
700 }
701
702 for (int i = length - 1; i >= 0; i--) {
703 Digit q = digitDiv(*remainder, x->digit(i), divisor, remainder);
704 quotient.value()->setDigit(i, q);
705 }
706 } else {
707 for (int i = length - 1; i >= 0; i--) {
708 digitDiv(*remainder, x->digit(i), divisor, remainder);
709 }
710 }
711
712 return true;
713 }
714
715 // Adds `summand` onto `this`, starting with `summand`'s 0th digit
716 // at `this`'s `startIndex`'th digit. Returns the "carry" (0 or 1).
717 BigInt::Digit BigInt::absoluteInplaceAdd(const BigInt* summand,
718 unsigned startIndex) {
719 Digit carry = 0;
720 unsigned n = summand->digitLength();
721 MOZ_ASSERT(digitLength() > startIndex,
722 "must start adding at an in-range digit");
723 MOZ_ASSERT(digitLength() - startIndex >= n,
724 "digits being added to must not extend above the digits in "
725 "this (except for the returned carry digit)");
726 for (unsigned i = 0; i < n; i++) {
727 Digit newCarry = 0;
728 Digit sum = digitAdd(digit(startIndex + i), summand->digit(i), &newCarry);
729 sum = digitAdd(sum, carry, &newCarry);
730 setDigit(startIndex + i, sum);
731 carry = newCarry;
732 }
733
734 return carry;
735 }
736
737 // Subtracts `subtrahend` from this, starting with `subtrahend`'s 0th digit
738 // at `this`'s `startIndex`-th digit. Returns the "borrow" (0 or 1).
739 BigInt::Digit BigInt::absoluteInplaceSub(const BigInt* subtrahend,
740 unsigned startIndex) {
741 Digit borrow = 0;
742 unsigned n = subtrahend->digitLength();
743 MOZ_ASSERT(digitLength() > startIndex,
744 "must start subtracting from an in-range digit");
745 MOZ_ASSERT(digitLength() - startIndex >= n,
746 "digits being subtracted from must not extend above the "
747 "digits in this (except for the returned borrow digit)");
748 for (unsigned i = 0; i < n; i++) {
749 Digit newBorrow = 0;
750 Digit difference =
751 digitSub(digit(startIndex + i), subtrahend->digit(i), &newBorrow);
752 difference = digitSub(difference, borrow, &newBorrow);
753 setDigit(startIndex + i, difference);
754 borrow = newBorrow;
755 }
756
757 return borrow;
758 }
759
760 // Returns whether (factor1 * factor2) > (high << kDigitBits) + low.
761 inline bool BigInt::productGreaterThan(Digit factor1, Digit factor2, Digit high,
762 Digit low) {
763 Digit resultHigh;
764 Digit resultLow = digitMul(factor1, factor2, &resultHigh);
765 return resultHigh > high || (resultHigh == high && resultLow > low);
766 }
767
768 void BigInt::inplaceRightShiftLowZeroBits(unsigned shift) {
769 MOZ_ASSERT(shift < DigitBits);
770 MOZ_ASSERT(!(digit(0) & ((static_cast<Digit>(1) << shift) - 1)),
771 "should only be shifting away zeroes");
772
773 if (!shift) {
774 return;
775 }
776
777 Digit carry = digit(0) >> shift;
778 unsigned last = digitLength() - 1;
779 for (unsigned i = 0; i < last; i++) {
780 Digit d = digit(i + 1);
781 setDigit(i, (d << (DigitBits - shift)) | carry);
782 carry = d >> shift;
783 }
784 setDigit(last, carry);
785 }
786
787 // Always copies the input, even when `shift` == 0.
788 BigInt* BigInt::absoluteLeftShiftAlwaysCopy(JSContext* cx, HandleBigInt x,
789 unsigned shift,
790 LeftShiftMode mode) {
791 MOZ_ASSERT(shift < DigitBits);
792 MOZ_ASSERT(!x->isZero());
793
794 unsigned n = x->digitLength();
795 unsigned resultLength = mode == LeftShiftMode::AlwaysAddOneDigit ? n + 1 : n;
796 BigInt* result = createUninitialized(cx, resultLength, x->isNegative());
797 if (!result) {
798 return nullptr;
799 }
800
801 if (!shift) {
802 for (unsigned i = 0; i < n; i++) {
803 result->setDigit(i, x->digit(i));
804 }
805 if (mode == LeftShiftMode::AlwaysAddOneDigit) {
806 result->setDigit(n, 0);
807 }
808
809 return result;
810 }
811
812 Digit carry = 0;
813 for (unsigned i = 0; i < n; i++) {
814 Digit d = x->digit(i);
815 result->setDigit(i, (d << shift) | carry);
816 carry = d >> (DigitBits - shift);
817 }
818
819 if (mode == LeftShiftMode::AlwaysAddOneDigit) {
820 result->setDigit(n, carry);
821 } else {
822 MOZ_ASSERT(mode == LeftShiftMode::SameSizeResult);
823 MOZ_ASSERT(!carry);
824 }
825
826 return result;
827 }
828
829 // Divides `dividend` by `divisor`, returning the result in `quotient` and
830 // `remainder`. Mathematically, the contract is:
831 //
832 // quotient = (dividend - remainder) / divisor, with 0 <= remainder < divisor.
833 //
834 // Both `quotient` and `remainder` are optional, for callers that are only
835 // interested in one of them. See Knuth, Volume 2, section 4.3.1, Algorithm D.
836 // Also see the overview of the algorithm by Jan Marthedal Rasmussen over at
837 // https://janmr.com/blog/2014/04/basic-multiple-precision-long-division/.
838 bool BigInt::absoluteDivWithBigIntDivisor(
839 JSContext* cx, HandleBigInt dividend, HandleBigInt divisor,
840 const Maybe<MutableHandleBigInt>& quotient,
841 const Maybe<MutableHandleBigInt>& remainder, bool isNegative) {
842 MOZ_ASSERT(divisor->digitLength() >= 2);
843 MOZ_ASSERT(dividend->digitLength() >= divisor->digitLength());
844
845 // Any early error return is detectable by checking the quotient and/or
846 // remainder output values.
847 MOZ_ASSERT(!quotient || !quotient.value());
848 MOZ_ASSERT(!remainder || !remainder.value());
849
850 // The unusual variable names inside this function are consistent with
851 // Knuth's book, as well as with Go's implementation of this algorithm.
852 // Maintaining this consistency is probably more useful than trying to
853 // come up with more descriptive names for them.
854 const unsigned n = divisor->digitLength();
855 const unsigned m = dividend->digitLength() - n;
856
857 // The quotient to be computed.
858 RootedBigInt q(cx);
859 if (quotient) {
860 q = createUninitialized(cx, m + 1, isNegative);
861 if (!q) {
862 return false;
863 }
864 }
865
866 // In each iteration, `qhatv` holds `divisor` * `current quotient digit`.
867 // "v" is the book's name for `divisor`, `qhat` the current quotient digit.
868 RootedBigInt qhatv(cx, createUninitialized(cx, n + 1, isNegative));
869 if (!qhatv) {
870 return false;
871 }
872
873 // D1.
874 // Left-shift inputs so that the divisor's MSB is set. This is necessary to
875 // prevent the digit-wise divisions (see digitDiv call below) from
876 // overflowing (they take a two digits wide input, and return a one digit
877 // result).
878 Digit lastDigit = divisor->digit(n - 1);
879 unsigned shift = DigitLeadingZeroes(lastDigit);
880
881 RootedBigInt shiftedDivisor(cx);
882 if (shift > 0) {
883 shiftedDivisor = absoluteLeftShiftAlwaysCopy(cx, divisor, shift,
884 LeftShiftMode::SameSizeResult);
885 if (!shiftedDivisor) {
886 return false;
887 }
888 } else {
889 shiftedDivisor = divisor;
890 }
891
892 // Holds the (continuously updated) remaining part of the dividend, which
893 // eventually becomes the remainder.
894 RootedBigInt u(cx,
895 absoluteLeftShiftAlwaysCopy(cx, dividend, shift,
896 LeftShiftMode::AlwaysAddOneDigit));
897 if (!u) {
898 return false;
899 }
900
901 // D2.
902 // Iterate over the dividend's digit (like the "grade school" algorithm).
903 // `vn1` is the divisor's most significant digit.
904 Digit vn1 = shiftedDivisor->digit(n - 1);
905 for (int j = m; j >= 0; j--) {
906 // D3.
907 // Estimate the current iteration's quotient digit (see Knuth for details).
908 // `qhat` is the current quotient digit.
909 Digit qhat = std::numeric_limits<Digit>::max();
910
911 // `ujn` is the dividend's most significant remaining digit.
912 Digit ujn = u->digit(j + n);
913 if (ujn != vn1) {
914 // `rhat` is the current iteration's remainder.
915 Digit rhat = 0;
916 // Estimate the current quotient digit by dividing the most significant
917 // digits of dividend and divisor. The result will not be too small,
918 // but could be a bit too large.
919 qhat = digitDiv(ujn, u->digit(j + n - 1), vn1, &rhat);
920
921 // Decrement the quotient estimate as needed by looking at the next
922 // digit, i.e. by testing whether
923 // qhat * v_{n-2} > (rhat << DigitBits) + u_{j+n-2}.
924 Digit vn2 = shiftedDivisor->digit(n - 2);
925 Digit ujn2 = u->digit(j + n - 2);
926 while (productGreaterThan(qhat, vn2, rhat, ujn2)) {
927 qhat--;
928 Digit prevRhat = rhat;
929 rhat += vn1;
930 // v[n-1] >= 0, so this tests for overflow.
931 if (rhat < prevRhat) {
932 break;
933 }
934 }
935 }
936
937 // D4.
938 // Multiply the divisor with the current quotient digit, and subtract
939 // it from the dividend. If there was "borrow", then the quotient digit
940 // was one too high, so we must correct it and undo one subtraction of
941 // the (shifted) divisor.
942 internalMultiplyAdd(shiftedDivisor, qhat, 0, n, qhatv);
943 Digit c = u->absoluteInplaceSub(qhatv, j);
944 if (c) {
945 c = u->absoluteInplaceAdd(shiftedDivisor, j);
946 u->setDigit(j + n, u->digit(j + n) + c);
947 qhat--;
948 }
949
950 if (quotient) {
951 q->setDigit(j, qhat);
952 }
953 }
954
955 if (quotient) {
956 BigInt* bi = destructivelyTrimHighZeroDigits(cx, q);
957 if (!bi) {
958 return false;
959 }
960 quotient.value().set(q);
961 }
962
963 if (remainder) {
964 u->inplaceRightShiftLowZeroBits(shift);
965 remainder.value().set(u);
966 }
967
968 return true;
969 }
970
971 // Helper for Absolute{And,AndNot,Or,Xor}.
972 // Performs the given binary `op` on digit pairs of `x` and `y`; when the
973 // end of the shorter of the two is reached, `kind` configures how
974 // remaining digits are handled.
975 // Example:
976 // y: [ y2 ][ y1 ][ y0 ]
977 // x: [ x3 ][ x2 ][ x1 ][ x0 ]
978 // | | | |
979 // (Fill) (op) (op) (op)
980 // | | | |
981 // v v v v
982 // result: [ 0 ][ x3 ][ r2 ][ r1 ][ r0 ]
983 template <BigInt::BitwiseOpKind kind, typename BitwiseOp>
984 inline BigInt* BigInt::absoluteBitwiseOp(JSContext* cx, HandleBigInt x,
985 HandleBigInt y, BitwiseOp&& op) {
986 unsigned xLength = x->digitLength();
987 unsigned yLength = y->digitLength();
988 unsigned numPairs = std::min(xLength, yLength);
989 unsigned resultLength;
990 if (kind == BitwiseOpKind::SymmetricTrim) {
991 resultLength = numPairs;
992 } else if (kind == BitwiseOpKind::SymmetricFill) {
993 resultLength = std::max(xLength, yLength);
994 } else {
995 MOZ_ASSERT(kind == BitwiseOpKind::AsymmetricFill);
996 resultLength = xLength;
997 }
998 bool resultNegative = false;
999
1000 BigInt* result = createUninitialized(cx, resultLength, resultNegative);
1001 if (!result) {
1002 return nullptr;
1003 }
1004
1005 unsigned i = 0;
1006 for (; i < numPairs; i++) {
1007 result->setDigit(i, op(x->digit(i), y->digit(i)));
1008 }
1009
1010 if (kind != BitwiseOpKind::SymmetricTrim) {
1011 BigInt* source = kind == BitwiseOpKind::AsymmetricFill ? x
1012 : xLength == i ? y
1013 : x;
1014 for (; i < resultLength; i++) {
1015 result->setDigit(i, source->digit(i));
1016 }
1017 }
1018
1019 MOZ_ASSERT(i == resultLength);
1020
1021 return destructivelyTrimHighZeroDigits(cx, result);
1022 }
1023
1024 BigInt* BigInt::absoluteAnd(JSContext* cx, HandleBigInt x, HandleBigInt y) {
1025 return absoluteBitwiseOp<BitwiseOpKind::SymmetricTrim>(cx, x, y,
1026 std::bit_and<Digit>());
1027 }
1028
1029 BigInt* BigInt::absoluteOr(JSContext* cx, HandleBigInt x, HandleBigInt y) {
1030 return absoluteBitwiseOp<BitwiseOpKind::SymmetricFill>(cx, x, y,
1031 std::bit_or<Digit>());
1032 }
1033
1034 BigInt* BigInt::absoluteAndNot(JSContext* cx, HandleBigInt x, HandleBigInt y) {
1035 auto digitOperation = [](Digit a, Digit b) { return a & ~b; };
1036 return absoluteBitwiseOp<BitwiseOpKind::AsymmetricFill>(cx, x, y,
1037 digitOperation);
1038 }
1039
1040 BigInt* BigInt::absoluteXor(JSContext* cx, HandleBigInt x, HandleBigInt y) {
1041 return absoluteBitwiseOp<BitwiseOpKind::SymmetricFill>(cx, x, y,
1042 std::bit_xor<Digit>());
1043 }
1044
1045 BigInt* BigInt::absoluteAddOne(JSContext* cx, HandleBigInt x,
1046 bool resultNegative) {
1047 unsigned inputLength = x->digitLength();
1048 // The addition will overflow into a new digit if all existing digits are
1049 // at maximum.
1050 bool willOverflow = true;
1051 for (unsigned i = 0; i < inputLength; i++) {
1052 if (std::numeric_limits<Digit>::max() != x->digit(i)) {
1053 willOverflow = false;
1054 break;
1055 }
1056 }
1057
1058 unsigned resultLength = inputLength + willOverflow;
1059 BigInt* result = createUninitialized(cx, resultLength, resultNegative);
1060 if (!result) {
1061 return nullptr;
1062 }
1063
1064 Digit carry = 1;
1065 for (unsigned i = 0; i < inputLength; i++) {
1066 Digit newCarry = 0;
1067 result->setDigit(i, digitAdd(x->digit(i), carry, &newCarry));
1068 carry = newCarry;
1069 }
1070 if (resultLength > inputLength) {
1071 MOZ_ASSERT(carry == 1);
1072 result->setDigit(inputLength, 1);
1073 } else {
1074 MOZ_ASSERT(!carry);
1075 }
1076
1077 return destructivelyTrimHighZeroDigits(cx, result);
1078 }
1079
1080 BigInt* BigInt::absoluteSubOne(JSContext* cx, HandleBigInt x,
1081 bool resultNegative) {
1082 MOZ_ASSERT(!x->isZero());
1083
1084 unsigned length = x->digitLength();
1085
1086 if (length == 1) {
1087 Digit d = x->digit(0);
1088 if (d == 1) {
1089 // Ignore resultNegative.
1090 return zero(cx);
1091 }
1092 return createFromDigit(cx, d - 1, resultNegative);
1093 }
1094
1095 BigInt* result = createUninitialized(cx, length, resultNegative);
1096 if (!result) {
1097 return nullptr;
1098 }
1099
1100 Digit borrow = 1;
1101 for (unsigned i = 0; i < length; i++) {
1102 Digit newBorrow = 0;
1103 result->setDigit(i, digitSub(x->digit(i), borrow, &newBorrow));
1104 borrow = newBorrow;
1105 }
1106 MOZ_ASSERT(!borrow);
1107
1108 return destructivelyTrimHighZeroDigits(cx, result);
1109 }
1110
1111 BigInt* BigInt::inc(JSContext* cx, HandleBigInt x) {
1112 if (x->isZero()) {
1113 return one(cx);
1114 }
1115
1116 bool isNegative = x->isNegative();
1117 if (isNegative) {
1118 return absoluteSubOne(cx, x, isNegative);
1119 }
1120
1121 return absoluteAddOne(cx, x, isNegative);
1122 }
1123
1124 BigInt* BigInt::dec(JSContext* cx, HandleBigInt x) {
1125 if (x->isZero()) {
1126 return negativeOne(cx);
1127 }
1128
1129 bool isNegative = x->isNegative();
1130 if (isNegative) {
1131 return absoluteAddOne(cx, x, isNegative);
1132 }
1133
1134 return absoluteSubOne(cx, x, isNegative);
1135 }
1136
1137 // Lookup table for the maximum number of bits required per character of a
1138 // base-N string representation of a number. To increase accuracy, the array
1139 // value is the actual value multiplied by 32. To generate this table:
1140 // for (var i = 0; i <= 36; i++) { print(Math.ceil(Math.log2(i) * 32) + ","); }
1141 static constexpr uint8_t maxBitsPerCharTable[] = {
1142 0, 0, 32, 51, 64, 75, 83, 90, 96, // 0..8
1143 102, 107, 111, 115, 119, 122, 126, 128, // 9..16
1144 131, 134, 136, 139, 141, 143, 145, 147, // 17..24
1145 149, 151, 153, 154, 156, 158, 159, 160, // 25..32
1146 162, 163, 165, 166, // 33..36
1147 };
1148
1149 static constexpr unsigned bitsPerCharTableShift = 5;
1150 static constexpr size_t bitsPerCharTableMultiplier = 1u
1151 << bitsPerCharTableShift;
1152 static constexpr char radixDigits[] = "0123456789abcdefghijklmnopqrstuvwxyz";
1153
1154 static inline uint64_t CeilDiv(uint64_t numerator, uint64_t denominator) {
1155 MOZ_ASSERT(numerator != 0);
1156 return 1 + (numerator - 1) / denominator;
1157 };
1158
1159 // Compute (an overapproximation of) the length of the string representation of
1160 // a BigInt. In base B an X-digit number has maximum value:
1161 //
1162 // B**X - 1
1163 //
1164 // We're trying to find N for an N-digit number in base |radix| full
1165 // representing a |bitLength|-digit number in base 2, so we have:
1166 //
1167 // radix**N - 1 ≥ 2**bitLength - 1
1168 // radix**N ≥ 2**bitLength
1169 // N ≥ log2(2**bitLength) / log2(radix)
1170 // N ≥ bitLength / log2(radix)
1171 //
1172 // so the smallest N is:
1173 //
1174 // N = ⌈bitLength / log2(radix)⌉
1175 //
1176 // We want to avoid floating-point computations and precompute the logarithm, so
1177 // we multiply both sides of the division by |bitsPerCharTableMultiplier|:
1178 //
1179 // N = ⌈(bPCTM * bitLength) / (bPCTM * log2(radix))⌉
1180 //
1181 // and then because |maxBitsPerChar| representing the denominator may have been
1182 // rounded *up* -- which could produce an overall under-computation -- we reduce
1183 // by one to undo any rounding and conservatively compute:
1184 //
1185 // N ≥ ⌈(bPCTM * bitLength) / (maxBitsPerChar - 1)⌉
1186 //
1187 size_t BigInt::calculateMaximumCharactersRequired(HandleBigInt x,
1188 unsigned radix) {
1189 MOZ_ASSERT(!x->isZero());
1190 MOZ_ASSERT(radix >= 2 && radix <= 36);
1191
1192 size_t length = x->digitLength();
1193 Digit lastDigit = x->digit(length - 1);
1194 size_t bitLength = length * DigitBits - DigitLeadingZeroes(lastDigit);
1195
1196 uint8_t maxBitsPerChar = maxBitsPerCharTable[radix];
1197 uint64_t maximumCharactersRequired =
1198 CeilDiv(static_cast<uint64_t>(bitsPerCharTableMultiplier) * bitLength,
1199 maxBitsPerChar - 1);
1200 maximumCharactersRequired += x->isNegative();
1201
1202 return AssertedCast<size_t>(maximumCharactersRequired);
1203 }
1204
1205 template <AllowGC allowGC>
1206 JSLinearString* BigInt::toStringBasePowerOfTwo(JSContext* cx, HandleBigInt x,
1207 unsigned radix) {
1208 MOZ_ASSERT(mozilla::IsPowerOfTwo(radix));
1209 MOZ_ASSERT(radix >= 2 && radix <= 32);
1210 MOZ_ASSERT(!x->isZero());
1211 MOZ_ASSERT(x->digitLength() > 1);
1212
1213 const unsigned length = x->digitLength();
1214 const bool sign = x->isNegative();
1215 const unsigned bitsPerChar = mozilla::CountTrailingZeroes32(radix);
1216 const unsigned charMask = radix - 1;
1217 // Compute the length of the resulting string: divide the bit length of the
1218 // BigInt by the number of bits representable per character (rounding up).
1219 const Digit msd = x->digit(length - 1);
1220
1221 const size_t bitLength = length * DigitBits - DigitLeadingZeroes(msd);
1222 const size_t charsRequired = CeilDiv(bitLength, bitsPerChar) + sign;
1223
1224 static_assert(MaxBitLength + 1 <= JSString::MAX_LENGTH,
1225 "Base 2 representation (including leading sign) of the largest "
1226 "possible BigInt fits into a string");
1227
1228 MOZ_RELEASE_ASSERT(charsRequired <= JSString::MAX_LENGTH);
1229
1230 StringChars<JS::Latin1Char> stringChars(cx);
1231 if (!stringChars.maybeAlloc(cx, charsRequired)) {
1232 if constexpr (!allowGC) {
1233 cx->recoverFromOutOfMemory();
1234 }
1235 return nullptr;
1236 }
1237
1238 {
1239 JS::AutoCheckCannotGC nogc;
1240 auto* resultChars = stringChars.data(nogc);
1241
1242 Digit digit = 0;
1243 // Keeps track of how many unprocessed bits there are in |digit|.
1244 unsigned availableBits = 0;
1245 size_t pos = charsRequired;
1246 for (unsigned i = 0; i < length - 1; i++) {
1247 Digit newDigit = x->digit(i);
1248 // Take any leftover bits from the last iteration into account.
1249 unsigned current = (digit | (newDigit << availableBits)) & charMask;
1250 MOZ_ASSERT(pos);
1251 resultChars[--pos] = radixDigits[current];
1252 unsigned consumedBits = bitsPerChar - availableBits;
1253 digit = newDigit >> consumedBits;
1254 availableBits = DigitBits - consumedBits;
1255 while (availableBits >= bitsPerChar) {
1256 MOZ_ASSERT(pos);
1257 resultChars[--pos] = radixDigits[digit & charMask];
1258 digit >>= bitsPerChar;
1259 availableBits -= bitsPerChar;
1260 }
1261 }
1262
1263 // Write out the character containing the lowest-order bit of |msd|.
1264 //
1265 // This character may include leftover bits from the Digit below |msd|. For
1266 // example, if |x === 2n**64n| and |radix == 32|: the preceding loop writes
1267 // twelve zeroes for low-order bits 0-59 in |x->digit(0)| (and |x->digit(1)|
1268 // on 32-bit); then the highest 4 bits of of |x->digit(0)| (or |x->digit(1)|
1269 // on 32-bit) and bit 0 of |x->digit(1)| (|x->digit(2)| on 32-bit) will
1270 // comprise the |current == 0b1'0000| computed below for the high-order 'g'
1271 // character.
1272 unsigned current = (digit | (msd << availableBits)) & charMask;
1273 MOZ_ASSERT(pos);
1274 resultChars[--pos] = radixDigits[current];
1275
1276 // Write out remaining characters represented by |msd|. (There may be none,
1277 // as in the example above.)
1278 digit = msd >> (bitsPerChar - availableBits);
1279 while (digit != 0) {
1280 MOZ_ASSERT(pos);
1281 resultChars[--pos] = radixDigits[digit & charMask];
1282 digit >>= bitsPerChar;
1283 }
1284
1285 if (sign) {
1286 MOZ_ASSERT(pos);
1287 resultChars[--pos] = '-';
1288 }
1289 MOZ_ASSERT(pos == 0);
1290 }
1291
1292 return stringChars.toStringDontDeflateNonStatic<allowGC>(cx, charsRequired);
1293 }
1294
1295 template <AllowGC allowGC>
1296 JSLinearString* BigInt::toStringSingleDigit(JSContext* cx, Digit digit,
1297 bool isNegative, unsigned radix) {
1298 MOZ_ASSERT(digit != 0, "zero case should have been handled in toString");
1299
1300 if (digit <= Digit(INT32_MAX)) {
1301 int32_t val = AssertedCast<int32_t>(digit);
1302 return Int32ToStringWithBase<allowGC>(cx, isNegative ? -val : val, radix,
1303 /* lowerCase = */ true);
1304 }
1305
1306 // Plus one to include the sign.
1307 constexpr size_t maxLength = std::numeric_limits<Digit>::digits + 1;
1308 static_assert(maxLength == 33 || maxLength == 65,
1309 "unexpected single digit string length");
1310
1311 char resultChars[maxLength];
1312
1313 char* chars = resultChars;
1314 if (isNegative) {
1315 *chars++ = '-';
1316 }
1317
1318 auto result = std::to_chars(chars, std::end(resultChars), digit, radix);
1319 MOZ_ASSERT(result.ec == std::errc());
1320
1321 size_t length = result.ptr - resultChars;
1322 MOZ_ASSERT(length <= maxLength);
1323
1324 return NewStringCopyN<allowGC>(cx, resultChars, length);
1325 }
1326
1327 static constexpr BigInt::Digit MaxPowerInDigit(uint8_t radix) {
1328 BigInt::Digit result = 1;
1329 while (result < BigInt::Digit(-1) / radix) {
1330 result *= radix;
1331 }
1332 return result;
1333 }
1334
1335 static constexpr uint8_t MaxExponentInDigit(uint8_t radix) {
1336 uint8_t exp = 0;
1337 BigInt::Digit result = 1;
1338 while (result < BigInt::Digit(-1) / radix) {
1339 result *= radix;
1340 exp += 1;
1341 }
1342 return exp;
1343 }
1344
1345 struct RadixInfo {
1346 BigInt::Digit maxPowerInDigit;
1347 uint8_t maxExponentInDigit;
1348
1349 constexpr RadixInfo(BigInt::Digit maxPower, uint8_t maxExponent)
1350 : maxPowerInDigit(maxPower), maxExponentInDigit(maxExponent) {}
1351
1352 explicit constexpr RadixInfo(uint8_t radix)
1353 : RadixInfo(MaxPowerInDigit(radix), MaxExponentInDigit(radix)) {}
1354 };
1355
1356 static constexpr const RadixInfo toStringInfo[37] = {
1357 {0, 0}, {0, 0}, RadixInfo(2), RadixInfo(3), RadixInfo(4),
1358 RadixInfo(5), RadixInfo(6), RadixInfo(7), RadixInfo(8), RadixInfo(9),
1359 RadixInfo(10), RadixInfo(11), RadixInfo(12), RadixInfo(13), RadixInfo(14),
1360 RadixInfo(15), RadixInfo(16), RadixInfo(17), RadixInfo(18), RadixInfo(19),
1361 RadixInfo(20), RadixInfo(21), RadixInfo(22), RadixInfo(23), RadixInfo(24),
1362 RadixInfo(25), RadixInfo(26), RadixInfo(27), RadixInfo(28), RadixInfo(29),
1363 RadixInfo(30), RadixInfo(31), RadixInfo(32), RadixInfo(33), RadixInfo(34),
1364 RadixInfo(35), RadixInfo(36),
1365 };
1366
1367 JSLinearString* BigInt::toStringGeneric(JSContext* cx, HandleBigInt x,
1368 unsigned radix) {
1369 MOZ_ASSERT(radix >= 2 && radix <= 36);
1370 MOZ_ASSERT(!x->isZero());
1371 MOZ_ASSERT(x->digitLength() > 1);
1372 MOZ_ASSERT(!mozilla::IsPowerOfTwo(radix));
1373
1374 size_t maximumCharactersRequired =
1375 calculateMaximumCharactersRequired(x, radix);
1376 if (maximumCharactersRequired > JSString::MAX_LENGTH) {
1377 ReportAllocationOverflow(cx);
1378 return nullptr;
1379 }
1380
1381 auto resultString = cx->make_pod_array<char>(maximumCharactersRequired);
1382 if (!resultString) {
1383 return nullptr;
1384 }
1385
1386 size_t writePos = maximumCharactersRequired;
1387
1388 unsigned chunkChars = toStringInfo[radix].maxExponentInDigit;
1389 Digit chunkDivisor = toStringInfo[radix].maxPowerInDigit;
1390
1391 unsigned length = x->digitLength();
1392 unsigned nonZeroDigit = length - 1;
1393 MOZ_ASSERT(x->digit(nonZeroDigit) != 0);
1394
1395 // `rest` holds the part of the BigInt that we haven't looked at yet.
1396 // Not to be confused with "remainder"!
1397 RootedBigInt rest(cx);
1398
1399 // In the first round, divide the input, allocating a new BigInt for
1400 // the result == rest; from then on divide the rest in-place.
1401 //
1402 // FIXME: absoluteDivWithDigitDivisor doesn't
1403 // destructivelyTrimHighZeroDigits for in-place divisions, leading to
1404 // worse constant factors. See
1405 // https://bugzilla.mozilla.org/show_bug.cgi?id=1510213.
1406 RootedBigInt dividend(cx, x);
1407 do {
1408 Digit chunk;
1409 if (!absoluteDivWithDigitDivisor(cx, dividend, chunkDivisor, Some(&rest),
1410 &chunk, dividend->isNegative())) {
1411 return nullptr;
1412 }
1413
1414 dividend = rest;
1415 for (unsigned i = 0; i < chunkChars; i++) {
1416 MOZ_ASSERT(writePos > 0);
1417 resultString[--writePos] = radixDigits[chunk % radix];
1418 chunk /= radix;
1419 }
1420 MOZ_ASSERT(!chunk);
1421
1422 if (!rest->digit(nonZeroDigit)) {
1423 nonZeroDigit--;
1424 }
1425
1426 MOZ_ASSERT(rest->digit(nonZeroDigit) != 0,
1427 "division by a single digit can't remove more than one "
1428 "digit from a number");
1429 } while (nonZeroDigit > 0);
1430
1431 Digit lastDigit = rest->digit(0);
1432 do {
1433 MOZ_ASSERT(writePos > 0);
1434 resultString[--writePos] = radixDigits[lastDigit % radix];
1435 lastDigit /= radix;
1436 } while (lastDigit > 0);
1437 MOZ_ASSERT(writePos < maximumCharactersRequired);
1438 MOZ_ASSERT(maximumCharactersRequired - writePos <=
1439 static_cast<size_t>(maximumCharactersRequired));
1440
1441 // Remove leading zeroes.
1442 while (writePos + 1 < maximumCharactersRequired &&
1443 resultString[writePos] == '0') {
1444 writePos++;
1445 }
1446
1447 if (x->isNegative()) {
1448 MOZ_ASSERT(writePos > 0);
1449 resultString[--writePos] = '-';
1450 }
1451
1452 MOZ_ASSERT(writePos < maximumCharactersRequired);
1453 // Would be better to somehow adopt resultString directly.
1454 return NewStringCopyN<CanGC>(cx, resultString.get() + writePos,
1455 maximumCharactersRequired - writePos);
1456 }
1457
1458 static void FreeDigits(JSContext* cx, BigInt* bi, BigInt::Digit* digits,
1459 size_t nbytes) {
1460 if (bi->isTenured()) {
1461 MOZ_ASSERT(!cx->nursery().isInside(digits));
1462 js_free(digits);
1463 } else {
1464 cx->nursery().freeBuffer(digits, nbytes);
1465 }
1466 }
1467
1468 BigInt* BigInt::destructivelyTrimHighZeroDigits(JSContext* cx, BigInt* x) {
1469 if (x->isZero()) {
1470 MOZ_ASSERT(!x->isNegative());
1471 return x;
1472 }
1473 MOZ_ASSERT(x->digitLength());
1474
1475 int nonZeroIndex = x->digitLength() - 1;
1476 while (nonZeroIndex >= 0 && x->digit(nonZeroIndex) == 0) {
1477 nonZeroIndex--;
1478 }
1479
1480 if (nonZeroIndex < 0) {
1481 return zero(cx);
1482 }
1483
1484 if (nonZeroIndex == static_cast<int>(x->digitLength() - 1)) {
1485 return x;
1486 }
1487
1488 unsigned newLength = nonZeroIndex + 1;
1489
1490 if (newLength > InlineDigitsLength) {
1491 MOZ_ASSERT(x->hasHeapDigits());
1492
1493 size_t oldLength = x->digitLength();
1494 Digit* newdigits = js::ReallocNurseryOrMallocBuffer<Digit>(
1495 cx, x, x->heapDigits_, oldLength, newLength, js::MallocArena);
1496 if (!newdigits) {
1497 return nullptr;
1498 }
1499 x->heapDigits_ = newdigits;
1500
1501 RemoveCellMemory(x, oldLength * sizeof(Digit), js::MemoryUse::BigIntDigits);
1502 AddCellMemory(x, newLength * sizeof(Digit), js::MemoryUse::BigIntDigits);
1503 } else {
1504 if (x->hasHeapDigits()) {
1505 Digit digits[InlineDigitsLength];
1506 std::copy_n(x->heapDigits_, InlineDigitsLength, digits);
1507
1508 size_t nbytes = x->digitLength() * sizeof(Digit);
1509 FreeDigits(cx, x, x->heapDigits_, nbytes);
1510 RemoveCellMemory(x, nbytes, js::MemoryUse::BigIntDigits);
1511
1512 std::copy_n(digits, InlineDigitsLength, x->inlineDigits_);
1513 }
1514 }
1515
1516 x->setLengthAndFlags(newLength, x->isNegative() ? SignBit : 0);
1517
1518 return x;
1519 }
1520
1521 // The maximum value `radix**charCount - 1` must be represented as a max number
1522 // `2**(N * DigitBits) - 1` for `N` digits, so
1523 //
1524 // 2**(N * DigitBits) - 1 ≥ radix**charcount - 1
1525 // 2**(N * DigitBits) ≥ radix**charcount
1526 // N * DigitBits ≥ log2(radix**charcount)
1527 // N * DigitBits ≥ charcount * log2(radix)
1528 // N ≥ ⌈charcount * log2(radix) / DigitBits⌉ (conservatively)
1529 //
1530 // or in the code's terms (all numbers promoted to exact mathematical values),
1531 //
1532 // N ≥ ⌈charcount * bitsPerChar / (DigitBits * bitsPerCharTableMultiplier)⌉
1533 //
1534 // Note that `N` is computed even more conservatively here because `bitsPerChar`
1535 // is rounded up.
1536 bool BigInt::calculateMaximumDigitsRequired(JSContext* cx, uint8_t radix,
1537 size_t charcount, size_t* result) {
1538 MOZ_ASSERT(2 <= radix && radix <= 36);
1539
1540 uint8_t bitsPerChar = maxBitsPerCharTable[radix];
1541
1542 MOZ_ASSERT(charcount > 0);
1543 MOZ_ASSERT(charcount <= std::numeric_limits<uint64_t>::max() / bitsPerChar);
1544 static_assert(
1545 MaxDigitLength < std::numeric_limits<size_t>::max(),
1546 "can't safely cast calculateMaximumDigitsRequired result to size_t");
1547
1548 uint64_t n = CeilDiv(static_cast<uint64_t>(charcount) * bitsPerChar,
1549 DigitBits * bitsPerCharTableMultiplier);
1550 if (n > MaxDigitLength) {
1551 ReportOversizedAllocation(cx, JSMSG_BIGINT_TOO_LARGE);
1552 return false;
1553 }
1554
1555 *result = n;
1556 return true;
1557 }
1558
1559 static BigInt::Digit PowerOf(BigInt::Digit base, size_t n) {
1560 MOZ_ASSERT(n > 0);
1561 mozilla::CheckedInt<BigInt::Digit> result = base;
1562 for (size_t i = 1; i < n; i++) {
1563 result *= base;
1564 }
1565 MOZ_ASSERT(result.isValid(), "unexpected overflow");
1566 return result.value();
1567 }
1568
1569 template <typename CharT>
1570 static bool ParseLiteralDigit(Range<const CharT> chars, unsigned radix,
1571 BigInt::Digit* result) {
1572 MOZ_ASSERT(chars.length() > 0);
1573 RangedPtr<const CharT> start = chars.begin();
1574 RangedPtr<const CharT> end = chars.end();
1575
1576 mozilla::CheckedInt<BigInt::Digit> d = 0;
1577 for (; start < end; start++) {
1578 uint32_t digit;
1579 CharT c = *start;
1580 if (c >= '0' && c <= '9') {
1581 digit = c - '0';
1582 } else if (c >= 'a' && c <= 'z') {
1583 digit = c - 'a' + 10;
1584 } else if (c >= 'A' && c <= 'Z') {
1585 digit = c - 'A' + 10;
1586 } else {
1587 return false;
1588 }
1589 if (MOZ_UNLIKELY(digit >= radix)) {
1590 return false;
1591 }
1592
1593 d = d * radix + digit;
1594 }
1595 MOZ_ASSERT(d.isValid(), "unexpected overflow");
1596
1597 *result = d.value();
1598 return true;
1599 }
1600
1601 template <typename CharT>
1602 BigInt* BigInt::parseLiteralDigits(JSContext* cx, Range<const CharT> chars,
1603 unsigned radix, bool isNegative,
1604 bool* haveParseError, gc::Heap heap) {
1605 static_assert(
1606 std::is_same_v<CharT, JS::Latin1Char> || std::is_same_v<CharT, char16_t>,
1607 "only the bare minimum character types are supported, to avoid "
1608 "excessively instantiating this template");
1609
1610 MOZ_ASSERT(chars.length());
1611
1612 RangedPtr<const CharT> start = chars.begin();
1613 RangedPtr<const CharT> end = chars.end();
1614
1615 // Skipping leading zeroes.
1616 while (start[0] == '0') {
1617 start++;
1618 if (start == end) {
1619 return zero(cx, heap);
1620 }
1621 }
1622
1623 size_t length;
1624 if (!calculateMaximumDigitsRequired(cx, radix, end - start, &length)) {
1625 return nullptr;
1626 }
1627 MOZ_ASSERT(length > 0);
1628
1629 // Fast path for the single digit case.
1630 if (length == 1) {
1631 BigInt::Digit digit = 0;
1632 if (!ParseLiteralDigit(chars, radix, &digit)) {
1633 *haveParseError = true;
1634 return nullptr;
1635 }
1636 MOZ_ASSERT(digit > 0);
1637 return BigInt::createFromDigit(cx, digit, isNegative, heap);
1638 }
1639
1640 BigInt* result = createUninitialized(cx, length, isNegative, heap);
1641 if (!result) {
1642 return nullptr;
1643 }
1644
1645 result->initializeDigitsToZero();
1646
1647 // Numbers in radix 2, 4, and 16 can be directly stored into the result when
1648 // parsing from right to left.
1649 uint8_t log2 = mozilla::FloorLog2(radix);
1650 if (mozilla::IsPowerOfTwo(log2)) {
1651 size_t chunkChars = BigInt::DigitBits >> mozilla::FloorLog2(log2);
1652
1653 size_t i = 0;
1654 RangedPtr<const CharT> to = end;
1655 while (to > start) {
1656 RangedPtr<const CharT> from = to - std::min(to - start, chunkChars);
1657
1658 Digit chunk = 0;
1659 if (!ParseLiteralDigit(Range{from, to}, radix, &chunk)) {
1660 *haveParseError = true;
1661 return nullptr;
1662 }
1663
1664 result->setDigit(i++, chunk);
1665 to = from;
1666 }
1667 MOZ_ASSERT(i == length, "unexpected over allocation");
1668 MOZ_ASSERT(result->digit(length - 1) > 0, "unexpected leading zero");
1669
1670 return result;
1671 }
1672
1673 size_t chunkChars = toStringInfo[radix].maxExponentInDigit;
1674 Digit chunkMultiplier = toStringInfo[radix].maxPowerInDigit;
1675
1676 while (start < end) {
1677 RangedPtr<const CharT> limit = start + std::min(end - start, chunkChars);
1678
1679 Digit chunk = 0;
1680 if (!ParseLiteralDigit(Range{start, limit}, radix, &chunk)) {
1681 *haveParseError = true;
1682 return nullptr;
1683 }
1684
1685 BigInt::Digit multiplier = chunkMultiplier;
1686 if ((limit - start) < chunkChars) {
1687 multiplier = PowerOf(radix, limit - start);
1688 MOZ_ASSERT(multiplier < chunkMultiplier);
1689 }
1690 result->inplaceMultiplyAdd(multiplier, chunk);
1691 start = limit;
1692 }
1693
1694 return destructivelyTrimHighZeroDigits(cx, result);
1695 }
1696
1697 // BigInt proposal section 7.2
1698 template <typename CharT>
1699 BigInt* BigInt::parseLiteral(JSContext* cx, Range<const CharT> chars,
1700 bool* haveParseError, js::gc::Heap heap) {
1701 RangedPtr<const CharT> start = chars.begin();
1702 const RangedPtr<const CharT> end = chars.end();
1703 bool isNegative = false;
1704
1705 MOZ_ASSERT(chars.length());
1706
1707 if (end - start > 2 && start[0] == '0') {
1708 if (start[1] == 'b' || start[1] == 'B') {
1709 // StringNumericLiteral ::: BinaryIntegerLiteral
1710 return parseLiteralDigits(cx, Range<const CharT>(start + 2, end), 2,
1711 isNegative, haveParseError, heap);
1712 }
1713 if (start[1] == 'x' || start[1] == 'X') {
1714 // StringNumericLiteral ::: HexIntegerLiteral
1715 return parseLiteralDigits(cx, Range<const CharT>(start + 2, end), 16,
1716 isNegative, haveParseError, heap);
1717 }
1718 if (start[1] == 'o' || start[1] == 'O') {
1719 // StringNumericLiteral ::: OctalIntegerLiteral
1720 return parseLiteralDigits(cx, Range<const CharT>(start + 2, end), 8,
1721 isNegative, haveParseError, heap);
1722 }
1723 }
1724
1725 return parseLiteralDigits(cx, Range<const CharT>(start, end), 10, isNegative,
1726 haveParseError, heap);
1727 }
1728
1729 BigInt* BigInt::createFromDouble(JSContext* cx, double d) {
1730 MOZ_ASSERT(IsInteger(d), "Only integer-valued doubles can convert to BigInt");
1731
1732 if (d == 0) {
1733 return zero(cx);
1734 }
1735
1736 int exponent = mozilla::ExponentComponent(d);
1737 MOZ_ASSERT(exponent >= 0);
1738 int length = exponent / DigitBits + 1;
1739 BigInt* result = createUninitialized(cx, length, d < 0);
1740 if (!result) {
1741 return nullptr;
1742 }
1743
1744 // We construct a BigInt from the double `d` by shifting its mantissa
1745 // according to its exponent and mapping the bit pattern onto digits.
1746 //
1747 // <----------- bitlength = exponent + 1 ----------->
1748 // <----- 52 ------> <------ trailing zeroes ------>
1749 // mantissa: 1yyyyyyyyyyyyyyyyy 0000000000000000000000000000000
1750 // digits: 0001xxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx
1751 // <--> <------>
1752 // msdTopBits DigitBits
1753 //
1754 using Double = mozilla::FloatingPoint<double>;
1755 uint64_t mantissa =
1756 mozilla::BitwiseCast<uint64_t>(d) & Double::kSignificandBits;
1757 // Add implicit high bit.
1758 mantissa |= 1ull << Double::kSignificandWidth;
1759
1760 const int mantissaTopBit = Double::kSignificandWidth; // 0-indexed.
1761
1762 // 0-indexed position of `d`'s most significant bit within the `msd`.
1763 int msdTopBit = exponent % DigitBits;
1764
1765 // Next digit under construction.
1766 Digit digit;
1767
1768 // First, build the MSD by shifting the mantissa appropriately.
1769 if (msdTopBit < mantissaTopBit) {
1770 int remainingMantissaBits = mantissaTopBit - msdTopBit;
1771 digit = mantissa >> remainingMantissaBits;
1772 mantissa = mantissa << (64 - remainingMantissaBits);
1773 } else {
1774 MOZ_ASSERT(msdTopBit >= mantissaTopBit);
1775 digit = mantissa << (msdTopBit - mantissaTopBit);
1776 mantissa = 0;
1777 }
1778 MOZ_ASSERT(digit != 0, "most significant digit should not be zero");
1779 result->setDigit(--length, digit);
1780
1781 // Fill in digits containing mantissa contributions.
1782 while (mantissa) {
1783 MOZ_ASSERT(length > 0,
1784 "double bits were all non-fractional, so there must be "
1785 "digits present to hold them");
1786
1787 if (DigitBits == 64) {
1788 result->setDigit(--length, mantissa);
1789 break;
1790 }
1791
1792 MOZ_ASSERT(DigitBits == 32);
1793 Digit current = mantissa >> 32;
1794 mantissa = mantissa << 32;
1795 result->setDigit(--length, current);
1796 }
1797
1798 // Fill in low-order zeroes.
1799 for (int i = length - 1; i >= 0; i--) {
1800 result->setDigit(i, 0);
1801 }
1802
1803 return result;
1804 }
1805
1806 BigInt* BigInt::createFromUint64(JSContext* cx, uint64_t n, gc::Heap heap) {
1807 if (n == 0) {
1808 return zero(cx, heap);
1809 }
1810
1811 const bool isNegative = false;
1812
1813 if (DigitBits == 32) {
1814 Digit low = n;
1815 Digit high = n >> 32;
1816 size_t length = high ? 2 : 1;
1817
1818 BigInt* res = createUninitialized(cx, length, isNegative, heap);
1819 if (!res) {
1820 return nullptr;
1821 }
1822 res->setDigit(0, low);
1823 if (high) {
1824 res->setDigit(1, high);
1825 }
1826 return res;
1827 }
1828
1829 return createFromDigit(cx, n, isNegative, heap);
1830 }
1831
1832 BigInt* BigInt::createFromInt64(JSContext* cx, int64_t n, gc::Heap heap) {
1833 BigInt* res = createFromUint64(cx, Abs(n), heap);
1834 if (!res) {
1835 return nullptr;
1836 }
1837
1838 if (n < 0) {
1839 res->setHeaderFlagBit(SignBit);
1840 }
1841 MOZ_ASSERT(res->isNegative() == (n < 0));
1842
1843 return res;
1844 }
1845
1846 BigInt* BigInt::createFromIntPtr(JSContext* cx, intptr_t n) {
1847 static_assert(sizeof(intptr_t) == sizeof(BigInt::Digit));
1848
1849 if (n == 0) {
1850 return BigInt::zero(cx);
1851 }
1852 return BigInt::createFromDigit(cx, BigInt::Digit(Abs(n)), n < 0);
1853 }
1854
1855 // BigInt proposal section 5.1.2
1856 BigInt* js::NumberToBigInt(JSContext* cx, double d) {
1857 // Step 1 is an assertion checked by the caller.
1858 // Step 2.
1859 if (!IsInteger(d)) {
1860 ToCStringBuf cbuf;
1861 const char* str = NumberToCString(&cbuf, d);
1862 MOZ_ASSERT(str);
1863
1864 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1865 JSMSG_NONINTEGER_NUMBER_TO_BIGINT, str);
1866 return nullptr;
1867 }
1868
1869 // Step 3.
1870 return BigInt::createFromDouble(cx, d);
1871 }
1872
1873 BigInt* BigInt::copy(JSContext* cx, HandleBigInt x, gc::Heap heap) {
1874 if (x->isZero()) {
1875 return zero(cx, heap);
1876 }
1877
1878 BigInt* result =
1879 createUninitialized(cx, x->digitLength(), x->isNegative(), heap);
1880 if (!result) {
1881 return nullptr;
1882 }
1883 for (size_t i = 0; i < x->digitLength(); i++) {
1884 result->setDigit(i, x->digit(i));
1885 }
1886 return result;
1887 }
1888
1889 // BigInt proposal section 1.1.7
1890 BigInt* BigInt::add(JSContext* cx, HandleBigInt x, HandleBigInt y) {
1891 bool xNegative = x->isNegative();
1892
1893 // x + y == x + y
1894 // -x + -y == -(x + y)
1895 if (xNegative == y->isNegative()) {
1896 return absoluteAdd(cx, x, y, xNegative);
1897 }
1898
1899 // x + -y == x - y == -(y - x)
1900 // -x + y == y - x == -(x - y)
1901 int8_t compare = absoluteCompare(x, y);
1902 if (compare == 0) {
1903 return zero(cx);
1904 }
1905
1906 if (compare > 0) {
1907 return absoluteSub(cx, x, y, xNegative);
1908 }
1909
1910 return absoluteSub(cx, y, x, !xNegative);
1911 }
1912
1913 // BigInt proposal section 1.1.8
1914 BigInt* BigInt::sub(JSContext* cx, HandleBigInt x, HandleBigInt y) {
1915 bool xNegative = x->isNegative();
1916 if (xNegative != y->isNegative()) {
1917 // x - (-y) == x + y
1918 // (-x) - y == -(x + y)
1919 return absoluteAdd(cx, x, y, xNegative);
1920 }
1921
1922 // x - y == -(y - x)
1923 // (-x) - (-y) == y - x == -(x - y)
1924 int8_t compare = absoluteCompare(x, y);
1925 if (compare == 0) {
1926 return zero(cx);
1927 }
1928
1929 if (compare > 0) {
1930 return absoluteSub(cx, x, y, xNegative);
1931 }
1932
1933 return absoluteSub(cx, y, x, !xNegative);
1934 }
1935
1936 // BigInt proposal section 1.1.4
1937 BigInt* BigInt::mul(JSContext* cx, HandleBigInt x, HandleBigInt y) {
1938 if (x->isZero()) {
1939 return x;
1940 }
1941 if (y->isZero()) {
1942 return y;
1943 }
1944
1945 bool resultNegative = x->isNegative() != y->isNegative();
1946
1947 // Fast path for the likely-common case of up to a uint64_t of magnitude.
1948 if (x->absFitsInUint64() && y->absFitsInUint64()) {
1949 uint64_t lhs = x->uint64FromAbsNonZero();
1950 uint64_t rhs = y->uint64FromAbsNonZero();
1951
1952 uint64_t res;
1953 if (js::SafeMul(lhs, rhs, &res)) {
1954 MOZ_ASSERT(res != 0);
1955 return createFromNonZeroRawUint64(cx, res, resultNegative);
1956 }
1957 }
1958
1959 unsigned resultLength = x->digitLength() + y->digitLength();
1960 BigInt* result = createUninitialized(cx, resultLength, resultNegative);
1961 if (!result) {
1962 return nullptr;
1963 }
1964 result->initializeDigitsToZero();
1965
1966 // Reorder operands to minimize calls to multiplyAccumulate.
1967 BigInt* left = x;
1968 BigInt* right = y;
1969 if (left->digitLength() < right->digitLength()) {
1970 std::swap(left, right);
1971 }
1972
1973 for (size_t i = 0; i < right->digitLength(); i++) {
1974 multiplyAccumulate(left, right->digit(i), result, i);
1975 }
1976
1977 return destructivelyTrimHighZeroDigits(cx, result);
1978 }
1979
1980 // BigInt proposal section 1.1.5
1981 BigInt* BigInt::div(JSContext* cx, HandleBigInt x, HandleBigInt y) {
1982 // 1. If y is 0n, throw a RangeError exception.
1983 if (y->isZero()) {
1984 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1985 JSMSG_BIGINT_DIVISION_BY_ZERO);
1986 return nullptr;
1987 }
1988
1989 // 2. Let quotient be the mathematical value of x divided by y.
1990 // 3. Return a BigInt representing quotient rounded towards 0 to the next
1991 // integral value.
1992 if (x->isZero()) {
1993 return x;
1994 }
1995
1996 if (absoluteCompare(x, y) < 0) {
1997 return zero(cx);
1998 }
1999
2000 RootedBigInt quotient(cx);
2001 bool resultNegative = x->isNegative() != y->isNegative();
2002 if (y->digitLength() == 1) {
2003 Digit divisor = y->digit(0);
2004 if (divisor == 1) {
2005 return resultNegative == x->isNegative() ? x : neg(cx, x);
2006 }
2007
2008 Digit remainder;
2009 if (!absoluteDivWithDigitDivisor(cx, x, divisor, Some(&quotient),
2010 &remainder, resultNegative)) {
2011 return nullptr;
2012 }
2013 } else {
2014 if (!absoluteDivWithBigIntDivisor(cx, x, y, Some(&quotient), Nothing(),
2015 resultNegative)) {
2016 return nullptr;
2017 }
2018 }
2019
2020 return destructivelyTrimHighZeroDigits(cx, quotient);
2021 }
2022
2023 // BigInt proposal section 1.1.6
2024 BigInt* BigInt::mod(JSContext* cx, HandleBigInt x, HandleBigInt y) {
2025 // 1. If y is 0n, throw a RangeError exception.
2026 if (y->isZero()) {
2027 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
2028 JSMSG_BIGINT_DIVISION_BY_ZERO);
2029 return nullptr;
2030 }
2031
2032 // 2. If x is 0n, return x.
2033 if (x->isZero()) {
2034 return x;
2035 }
2036 // 3. Let r be the BigInt defined by the mathematical relation r = x - (y ×
2037 // q) where q is a BigInt that is negative only if x/y is negative and
2038 // positive only if x/y is positive, and whose magnitude is as large as
2039 // possible without exceeding the magnitude of the true mathematical
2040 // quotient of x and y.
2041 if (absoluteCompare(x, y) < 0) {
2042 return x;
2043 }
2044
2045 if (y->digitLength() == 1) {
2046 Digit divisor = y->digit(0);
2047 if (divisor == 1) {
2048 return zero(cx);
2049 }
2050
2051 Digit remainderDigit;
2052 bool unusedQuotientNegative = false;
2053 if (!absoluteDivWithDigitDivisor(cx, x, divisor, Nothing(), &remainderDigit,
2054 unusedQuotientNegative)) {
2055 MOZ_CRASH("BigInt div by digit failed unexpectedly");
2056 }
2057
2058 if (!remainderDigit) {
2059 return zero(cx);
2060 }
2061
2062 return createFromDigit(cx, remainderDigit, x->isNegative());
2063 } else {
2064 RootedBigInt remainder(cx);
2065 if (!absoluteDivWithBigIntDivisor(cx, x, y, Nothing(), Some(&remainder),
2066 x->isNegative())) {
2067 return nullptr;
2068 }
2069 MOZ_ASSERT(remainder);
2070 return destructivelyTrimHighZeroDigits(cx, remainder);
2071 }
2072 }
2073
2074 bool BigInt::divmod(JSContext* cx, Handle<BigInt*> x, Handle<BigInt*> y,
2075 MutableHandle<BigInt*> quotient,
2076 MutableHandle<BigInt*> remainder) {
2077 // 1. If y is 0n, throw a RangeError exception.
2078 if (y->isZero()) {
2079 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
2080 JSMSG_BIGINT_DIVISION_BY_ZERO);
2081 return false;
2082 }
2083
2084 // 2. If x is 0n, quotient and remainder are zero, too.
2085 if (x->isZero()) {
2086 quotient.set(x);
2087 remainder.set(x);
2088 return true;
2089 }
2090
2091 // 3. Let r be the BigInt defined by the mathematical relation r = x - (y ×
2092 // q) where q is a BigInt that is negative only if x/y is negative and
2093 // positive only if x/y is positive, and whose magnitude is as large as
2094 // possible without exceeding the magnitude of the true mathematical
2095 // quotient of x and y.
2096 if (absoluteCompare(x, y) < 0) {
2097 auto* zero = BigInt::zero(cx);
2098 if (!zero) {
2099 return false;
2100 }
2101
2102 quotient.set(zero);
2103 remainder.set(x);
2104 return true;
2105 }
2106
2107 bool resultNegative = x->isNegative() != y->isNegative();
2108
2109 if (y->digitLength() == 1) {
2110 Digit divisor = y->digit(0);
2111 if (divisor == 1) {
2112 quotient.set(resultNegative == x->isNegative() ? x : neg(cx, x));
2113 if (!quotient) {
2114 return false;
2115 }
2116
2117 remainder.set(BigInt::zero(cx));
2118 if (!remainder) {
2119 return false;
2120 }
2121 } else {
2122 Rooted<BigInt*> quot(cx);
2123 Digit remainderDigit;
2124 if (!absoluteDivWithDigitDivisor(cx, x, divisor, Some(&quot),
2125 &remainderDigit, resultNegative)) {
2126 return false;
2127 }
2128
2129 quotient.set(destructivelyTrimHighZeroDigits(cx, quot));
2130 if (!quotient) {
2131 return false;
2132 }
2133
2134 if (!remainderDigit) {
2135 remainder.set(zero(cx));
2136 } else {
2137 remainder.set(createFromDigit(cx, remainderDigit, x->isNegative()));
2138 }
2139 if (!remainder) {
2140 return false;
2141 }
2142 }
2143 } else {
2144 RootedBigInt quot(cx);
2145 RootedBigInt rem(cx);
2146 if (!absoluteDivWithBigIntDivisor(cx, x, y, Some(&quot), Some(&rem),
2147 resultNegative)) {
2148 return false;
2149 }
2150
2151 quotient.set(destructivelyTrimHighZeroDigits(cx, quot));
2152 if (!quotient) {
2153 return false;
2154 }
2155
2156 remainder.set(destructivelyTrimHighZeroDigits(cx, rem));
2157 if (!remainder) {
2158 return false;
2159 }
2160 }
2161
2162 MOZ_ASSERT(quotient && remainder,
2163 "quotient and remainder are computed on return");
2164 MOZ_ASSERT(!quotient->isZero(), "zero quotient is handled earlier");
2165 MOZ_ASSERT(quotient->isNegative() == resultNegative,
2166 "quotient has the correct sign");
2167 MOZ_ASSERT(
2168 remainder->isZero() || (x->isNegative() == remainder->isNegative()),
2169 "remainder has the correct sign");
2170
2171 return true;
2172 }
2173
2174 // BigInt proposal section 1.1.3
2175 BigInt* BigInt::pow(JSContext* cx, HandleBigInt x, HandleBigInt y) {
2176 // 1. If exponent is < 0, throw a RangeError exception.
2177 if (y->isNegative()) {
2178 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
2179 JSMSG_BIGINT_NEGATIVE_EXPONENT);
2180 return nullptr;
2181 }
2182
2183 // 2. If base is 0n and exponent is 0n, return 1n.
2184 if (y->isZero()) {
2185 return one(cx);
2186 }
2187
2188 if (x->isZero()) {
2189 return x;
2190 }
2191
2192 // 3. Return a BigInt representing the mathematical value of base raised
2193 // to the power exponent.
2194 if (x->digitLength() == 1 && x->digit(0) == 1) {
2195 // (-1) ** even_number == 1.
2196 if (x->isNegative() && (y->digit(0) & 1) == 0) {
2197 return neg(cx, x);
2198 }
2199 // (-1) ** odd_number == -1; 1 ** anything == 1.
2200 return x;
2201 }
2202
2203 // For all bases >= 2, very large exponents would lead to unrepresentable
2204 // results.
2205 static_assert(MaxBitLength < std::numeric_limits<Digit>::max(),
2206 "unexpectedly large MaxBitLength");
2207 if (y->digitLength() > 1) {
2208 ReportOversizedAllocation(cx, JSMSG_BIGINT_TOO_LARGE);
2209 return nullptr;
2210 }
2211 Digit exponent = y->digit(0);
2212 if (exponent == 1) {
2213 return x;
2214 }
2215 if (exponent >= MaxBitLength) {
2216 ReportOversizedAllocation(cx, JSMSG_BIGINT_TOO_LARGE);
2217 return nullptr;
2218 }
2219
2220 static_assert(
2221 MaxBitLength <= static_cast<unsigned>(std::numeric_limits<int>::max()),
2222 "unexpectedly large MaxBitLength");
2223 int n = static_cast<int>(exponent);
2224 bool isOddPower = n & 1;
2225
2226 if (x->digitLength() == 1 && mozilla::IsPowerOfTwo(x->digit(0))) {
2227 // Fast path for (2^m)^n.
2228
2229 // Result is negative for odd powers.
2230 bool resultNegative = x->isNegative() && isOddPower;
2231
2232 unsigned m = mozilla::FloorLog2(x->digit(0));
2233 MOZ_ASSERT(m < DigitBits);
2234
2235 static_assert(MaxBitLength * DigitBits > MaxBitLength,
2236 "n * m can't overflow");
2237 n *= int(m);
2238
2239 int length = 1 + (n / DigitBits);
2240 BigInt* result = createUninitialized(cx, length, resultNegative);
2241 if (!result) {
2242 return nullptr;
2243 }
2244 result->initializeDigitsToZero();
2245 result->setDigit(length - 1, static_cast<Digit>(1) << (n % DigitBits));
2246 return result;
2247 }
2248
2249 RootedBigInt runningSquare(cx, x);
2250 RootedBigInt result(cx, isOddPower ? x : nullptr);
2251 n /= 2;
2252
2253 // Fast path for the likely-common case of up to a uint64_t of magnitude.
2254 if (x->absFitsInUint64()) {
2255 bool resultNegative = x->isNegative() && isOddPower;
2256
2257 uint64_t runningSquareInt = x->uint64FromAbsNonZero();
2258 uint64_t resultInt = isOddPower ? runningSquareInt : 1;
2259 while (true) {
2260 uint64_t runningSquareStart = runningSquareInt;
2261 uint64_t r;
2262 if (!js::SafeMul(runningSquareInt, runningSquareInt, &r)) {
2263 break;
2264 }
2265 runningSquareInt = r;
2266
2267 if (n & 1) {
2268 if (!js::SafeMul(resultInt, runningSquareInt, &r)) {
2269 // Recover |runningSquare| before we restart the loop.
2270 runningSquareInt = runningSquareStart;
2271 break;
2272 }
2273 resultInt = r;
2274 }
2275
2276 n /= 2;
2277 if (n == 0) {
2278 return createFromNonZeroRawUint64(cx, resultInt, resultNegative);
2279 }
2280 }
2281
2282 runningSquare = createFromNonZeroRawUint64(cx, runningSquareInt, false);
2283 if (!runningSquare) {
2284 return nullptr;
2285 }
2286
2287 result = createFromNonZeroRawUint64(cx, resultInt, resultNegative);
2288 if (!result) {
2289 return nullptr;
2290 }
2291 }
2292
2293 // This implicitly sets the result's sign correctly.
2294 while (true) {
2295 runningSquare = mul(cx, runningSquare, runningSquare);
2296 if (!runningSquare) {
2297 return nullptr;
2298 }
2299
2300 if (n & 1) {
2301 if (!result) {
2302 result = runningSquare;
2303 } else {
2304 result = mul(cx, result, runningSquare);
2305 if (!result) {
2306 return nullptr;
2307 }
2308 }
2309 }
2310
2311 n /= 2;
2312 if (n == 0) {
2313 return result;
2314 }
2315 }
2316 }
2317
2318 bool BigInt::powIntPtr(intptr_t x, intptr_t y, intptr_t* result) {
2319 if (y < 0) {
2320 return false;
2321 }
2322 uintptr_t n = uintptr_t(y);
2323
2324 // x^y where x == 1 returns 1 for any y.
2325 if (x == 1) {
2326 *result = 1;
2327 return true;
2328 }
2329
2330 // x^y where x == -1 returns 1 for even y, and -1 for odd y.
2331 if (x == -1) {
2332 *result = (y & 1) ? -1 : 1;
2333 return true;
2334 }
2335
2336 using CheckedIntPtr = mozilla::CheckedInt<intptr_t>;
2337
2338 CheckedIntPtr runningSquare = x;
2339 CheckedIntPtr res = 1;
2340 while (true) {
2341 if ((n & 1) != 0) {
2342 res *= runningSquare;
2343 if (!res.isValid()) {
2344 return false;
2345 }
2346 }
2347
2348 n >>= 1;
2349 if (n == 0) {
2350 *result = res.value();
2351 return true;
2352 }
2353
2354 runningSquare *= runningSquare;
2355 if (!runningSquare.isValid()) {
2356 return false;
2357 }
2358 }
2359 }
2360
2361 BigInt* BigInt::lshByAbsolute(JSContext* cx, HandleBigInt x, HandleBigInt y) {
2362 if (x->isZero() || y->isZero()) {
2363 return x;
2364 }
2365
2366 if (y->digitLength() > 1 || y->digit(0) > MaxBitLength) {
2367 ReportOversizedAllocation(cx, JSMSG_BIGINT_TOO_LARGE);
2368 if (js::SupportDifferentialTesting()) {
2369 fprintf(stderr, "ReportOutOfMemory called\n");
2370 }
2371 return nullptr;
2372 }
2373 Digit shift = y->digit(0);
2374 int digitShift = static_cast<int>(shift / DigitBits);
2375 int bitsShift = static_cast<int>(shift % DigitBits);
2376 int length = x->digitLength();
2377 bool grow = bitsShift && (x->digit(length - 1) >> (DigitBits - bitsShift));
2378 int resultLength = length + digitShift + grow;
2379 BigInt* result = createUninitialized(cx, resultLength, x->isNegative());
2380 if (!result) {
2381 return nullptr;
2382 }
2383
2384 int i = 0;
2385 for (; i < digitShift; i++) {
2386 result->setDigit(i, 0);
2387 }
2388
2389 if (bitsShift == 0) {
2390 for (int j = 0; i < resultLength; i++, j++) {
2391 result->setDigit(i, x->digit(j));
2392 }
2393 } else {
2394 Digit carry = 0;
2395 for (int j = 0; j < length; i++, j++) {
2396 Digit d = x->digit(j);
2397 result->setDigit(i, (d << bitsShift) | carry);
2398 carry = d >> (DigitBits - bitsShift);
2399 }
2400 if (grow) {
2401 result->setDigit(i, carry);
2402 } else {
2403 MOZ_ASSERT(!carry);
2404 }
2405 }
2406 return result;
2407 }
2408
2409 BigInt* BigInt::rshByMaximum(JSContext* cx, bool isNegative) {
2410 return isNegative ? negativeOne(cx) : zero(cx);
2411 }
2412
2413 BigInt* BigInt::rshByAbsolute(JSContext* cx, HandleBigInt x, HandleBigInt y) {
2414 if (x->isZero() || y->isZero()) {
2415 return x;
2416 }
2417
2418 if (y->digitLength() > 1 || y->digit(0) >= MaxBitLength) {
2419 return rshByMaximum(cx, x->isNegative());
2420 }
2421 Digit shift = y->digit(0);
2422 int length = x->digitLength();
2423 int digitShift = static_cast<int>(shift / DigitBits);
2424 int bitsShift = static_cast<int>(shift % DigitBits);
2425 int resultLength = length - digitShift;
2426 if (resultLength <= 0) {
2427 return rshByMaximum(cx, x->isNegative());
2428 }
2429 // For negative numbers, round down if any bit was shifted out (so that e.g.
2430 // -5n >> 1n == -3n and not -2n). Check now whether this will happen and
2431 // whether it can cause overflow into a new digit. If we allocate the result
2432 // large enough up front, it avoids having to do a second allocation later.
2433 bool mustRoundDown = false;
2434 if (x->isNegative()) {
2435 const Digit mask = (static_cast<Digit>(1) << bitsShift) - 1;
2436 if ((x->digit(digitShift) & mask)) {
2437 mustRoundDown = true;
2438 } else {
2439 for (int i = 0; i < digitShift; i++) {
2440 if (x->digit(i)) {
2441 mustRoundDown = true;
2442 break;
2443 }
2444 }
2445 }
2446 }
2447 // If bits_shift is non-zero, it frees up bits, preventing overflow.
2448 if (mustRoundDown && bitsShift == 0) {
2449 // Overflow cannot happen if the most significant digit has unset bits.
2450 Digit msd = x->digit(length - 1);
2451 bool roundingCanOverflow = msd == std::numeric_limits<Digit>::max();
2452 if (roundingCanOverflow) {
2453 resultLength++;
2454 }
2455 }
2456
2457 MOZ_ASSERT(resultLength <= length);
2458 RootedBigInt result(cx,
2459 createUninitialized(cx, resultLength, x->isNegative()));
2460 if (!result) {
2461 return nullptr;
2462 }
2463 if (!bitsShift) {
2464 // If roundingCanOverflow, manually initialize the overflow digit.
2465 result->setDigit(resultLength - 1, 0);
2466 for (int i = digitShift; i < length; i++) {
2467 result->setDigit(i - digitShift, x->digit(i));
2468 }
2469 } else {
2470 Digit carry = x->digit(digitShift) >> bitsShift;
2471 int last = length - digitShift - 1;
2472 for (int i = 0; i < last; i++) {
2473 Digit d = x->digit(i + digitShift + 1);
2474 result->setDigit(i, (d << (DigitBits - bitsShift)) | carry);
2475 carry = d >> bitsShift;
2476 }
2477 result->setDigit(last, carry);
2478 }
2479
2480 if (mustRoundDown) {
2481 MOZ_ASSERT(x->isNegative());
2482 // Since the result is negative, rounding down means adding one to
2483 // its absolute value. This cannot overflow. TODO: modify the result in
2484 // place.
2485 return absoluteAddOne(cx, result, x->isNegative());
2486 }
2487 return destructivelyTrimHighZeroDigits(cx, result);
2488 }
2489
2490 // BigInt proposal section 1.1.9. BigInt::leftShift ( x, y )
2491 BigInt* BigInt::lsh(JSContext* cx, HandleBigInt x, HandleBigInt y) {
2492 if (y->isNegative()) {
2493 return rshByAbsolute(cx, x, y);
2494 }
2495 return lshByAbsolute(cx, x, y);
2496 }
2497
2498 // BigInt proposal section 1.1.10. BigInt::signedRightShift ( x, y )
2499 BigInt* BigInt::rsh(JSContext* cx, HandleBigInt x, HandleBigInt y) {
2500 if (y->isNegative()) {
2501 return lshByAbsolute(cx, x, y);
2502 }
2503 return rshByAbsolute(cx, x, y);
2504 }
2505
2506 // BigInt proposal section 1.1.17. BigInt::bitwiseAND ( x, y )
2507 BigInt* BigInt::bitAnd(JSContext* cx, HandleBigInt x, HandleBigInt y) {
2508 if (x->isZero()) {
2509 return x;
2510 }
2511
2512 if (y->isZero()) {
2513 return y;
2514 }
2515
2516 if (!x->isNegative() && !y->isNegative()) {
2517 return absoluteAnd(cx, x, y);
2518 }
2519
2520 if (x->isNegative() && y->isNegative()) {
2521 // (-x) & (-y) == ~(x-1) & ~(y-1) == ~((x-1) | (y-1))
2522 // == -(((x-1) | (y-1)) + 1)
2523 RootedBigInt x1(cx, absoluteSubOne(cx, x));
2524 if (!x1) {
2525 return nullptr;
2526 }
2527 RootedBigInt y1(cx, absoluteSubOne(cx, y));
2528 if (!y1) {
2529 return nullptr;
2530 }
2531 RootedBigInt result(cx, absoluteOr(cx, x1, y1));
2532 if (!result) {
2533 return nullptr;
2534 }
2535 bool resultNegative = true;
2536 return absoluteAddOne(cx, result, resultNegative);
2537 }
2538
2539 MOZ_ASSERT(x->isNegative() != y->isNegative());
2540 HandleBigInt& pos = x->isNegative() ? y : x;
2541 HandleBigInt& neg = x->isNegative() ? x : y;
2542
2543 RootedBigInt neg1(cx, absoluteSubOne(cx, neg));
2544 if (!neg1) {
2545 return nullptr;
2546 }
2547
2548 // x & (-y) == x & ~(y-1) == x & ~(y-1)
2549 return absoluteAndNot(cx, pos, neg1);
2550 }
2551
2552 // BigInt proposal section 1.1.18. BigInt::bitwiseXOR ( x, y )
2553 BigInt* BigInt::bitXor(JSContext* cx, HandleBigInt x, HandleBigInt y) {
2554 if (x->isZero()) {
2555 return y;
2556 }
2557
2558 if (y->isZero()) {
2559 return x;
2560 }
2561
2562 if (!x->isNegative() && !y->isNegative()) {
2563 return absoluteXor(cx, x, y);
2564 }
2565
2566 if (x->isNegative() && y->isNegative()) {
2567 // (-x) ^ (-y) == ~(x-1) ^ ~(y-1) == (x-1) ^ (y-1)
2568 RootedBigInt x1(cx, absoluteSubOne(cx, x));
2569 if (!x1) {
2570 return nullptr;
2571 }
2572 RootedBigInt y1(cx, absoluteSubOne(cx, y));
2573 if (!y1) {
2574 return nullptr;
2575 }
2576 return absoluteXor(cx, x1, y1);
2577 }
2578 MOZ_ASSERT(x->isNegative() != y->isNegative());
2579
2580 HandleBigInt& pos = x->isNegative() ? y : x;
2581 HandleBigInt& neg = x->isNegative() ? x : y;
2582
2583 // x ^ (-y) == x ^ ~(y-1) == ~(x ^ (y-1)) == -((x ^ (y-1)) + 1)
2584 RootedBigInt result(cx, absoluteSubOne(cx, neg));
2585 if (!result) {
2586 return nullptr;
2587 }
2588 result = absoluteXor(cx, result, pos);
2589 if (!result) {
2590 return nullptr;
2591 }
2592 bool resultNegative = true;
2593 return absoluteAddOne(cx, result, resultNegative);
2594 }
2595
2596 // BigInt proposal section 1.1.19. BigInt::bitwiseOR ( x, y )
2597 BigInt* BigInt::bitOr(JSContext* cx, HandleBigInt x, HandleBigInt y) {
2598 if (x->isZero()) {
2599 return y;
2600 }
2601
2602 if (y->isZero()) {
2603 return x;
2604 }
2605
2606 bool resultNegative = x->isNegative() || y->isNegative();
2607
2608 if (!resultNegative) {
2609 return absoluteOr(cx, x, y);
2610 }
2611
2612 if (x->isNegative() && y->isNegative()) {
2613 // (-x) | (-y) == ~(x-1) | ~(y-1) == ~((x-1) & (y-1))
2614 // == -(((x-1) & (y-1)) + 1)
2615 RootedBigInt result(cx, absoluteSubOne(cx, x));
2616 if (!result) {
2617 return nullptr;
2618 }
2619 RootedBigInt y1(cx, absoluteSubOne(cx, y));
2620 if (!y1) {
2621 return nullptr;
2622 }
2623 result = absoluteAnd(cx, result, y1);
2624 if (!result) {
2625 return nullptr;
2626 }
2627 return absoluteAddOne(cx, result, resultNegative);
2628 }
2629
2630 MOZ_ASSERT(x->isNegative() != y->isNegative());
2631 HandleBigInt& pos = x->isNegative() ? y : x;
2632 HandleBigInt& neg = x->isNegative() ? x : y;
2633
2634 // x | (-y) == x | ~(y-1) == ~((y-1) &~ x) == -(((y-1) &~ x) + 1)
2635 RootedBigInt result(cx, absoluteSubOne(cx, neg));
2636 if (!result) {
2637 return nullptr;
2638 }
2639 result = absoluteAndNot(cx, result, pos);
2640 if (!result) {
2641 return nullptr;
2642 }
2643 return absoluteAddOne(cx, result, resultNegative);
2644 }
2645
2646 // BigInt proposal section 1.1.2. BigInt::bitwiseNOT ( x )
2647 BigInt* BigInt::bitNot(JSContext* cx, HandleBigInt x) {
2648 if (x->isNegative()) {
2649 // ~(-x) == ~(~(x-1)) == x-1
2650 return absoluteSubOne(cx, x);
2651 } else {
2652 // ~x == -x-1 == -(x+1)
2653 bool resultNegative = true;
2654 return absoluteAddOne(cx, x, resultNegative);
2655 }
2656 }
2657
2658 int64_t BigInt::toInt64(const BigInt* x) { return WrapToSigned(toUint64(x)); }
2659
2660 uint64_t BigInt::toUint64(const BigInt* x) {
2661 if (x->isZero()) {
2662 return 0;
2663 }
2664
2665 uint64_t digit = x->uint64FromAbsNonZero();
2666
2667 // Return the two's complement if x is negative.
2668 if (x->isNegative()) {
2669 return ~(digit - 1);
2670 }
2671
2672 return digit;
2673 }
2674
2675 bool BigInt::isInt32(const BigInt* x, int32_t* result) {
2676 MOZ_MAKE_MEM_UNDEFINED(result, sizeof(*result));
2677
2678 int64_t r;
2679 if (!BigInt::isInt64(x, &r)) {
2680 return false;
2681 }
2682
2683 if (std::numeric_limits<int32_t>::min() <= r &&
2684 r <= std::numeric_limits<int32_t>::max()) {
2685 *result = AssertedCast<int32_t>(r);
2686 return true;
2687 }
2688 return false;
2689 }
2690
2691 bool BigInt::isInt64(const BigInt* x, int64_t* result) {
2692 MOZ_MAKE_MEM_UNDEFINED(result, sizeof(*result));
2693
2694 if (!x->absFitsInUint64()) {
2695 return false;
2696 }
2697
2698 if (x->isZero()) {
2699 *result = 0;
2700 return true;
2701 }
2702
2703 uint64_t magnitude = x->uint64FromAbsNonZero();
2704
2705 if (x->isNegative()) {
2706 constexpr uint64_t Int64MinMagnitude = uint64_t(1) << 63;
2707 if (magnitude <= Int64MinMagnitude) {
2708 *result = magnitude == Int64MinMagnitude
2709 ? std::numeric_limits<int64_t>::min()
2710 : -AssertedCast<int64_t>(magnitude);
2711 return true;
2712 }
2713 } else {
2714 if (magnitude <=
2715 static_cast<uint64_t>(std::numeric_limits<int64_t>::max())) {
2716 *result = AssertedCast<int64_t>(magnitude);
2717 return true;
2718 }
2719 }
2720
2721 return false;
2722 }
2723
2724 bool BigInt::isUint64(const BigInt* x, uint64_t* result) {
2725 MOZ_MAKE_MEM_UNDEFINED(result, sizeof(*result));
2726
2727 if (!x->absFitsInUint64() || x->isNegative()) {
2728 return false;
2729 }
2730
2731 if (x->isZero()) {
2732 *result = 0;
2733 return true;
2734 }
2735
2736 *result = x->uint64FromAbsNonZero();
2737 return true;
2738 }
2739
2740 bool BigInt::isIntPtr(const BigInt* x, intptr_t* result) {
2741 MOZ_MAKE_MEM_UNDEFINED(result, sizeof(*result));
2742
2743 static_assert(sizeof(intptr_t) == sizeof(BigInt::Digit));
2744
2745 if (x->digitLength() > 1) {
2746 return false;
2747 }
2748
2749 if (x->isZero()) {
2750 *result = 0;
2751 return true;
2752 }
2753
2754 uintptr_t magnitude = x->digit(0);
2755
2756 if (x->isNegative()) {
2757 constexpr uintptr_t IntPtrMinMagnitude = uintptr_t(1) << (DigitBits - 1);
2758 if (magnitude <= IntPtrMinMagnitude) {
2759 *result = magnitude == IntPtrMinMagnitude
2760 ? std::numeric_limits<intptr_t>::min()
2761 : -AssertedCast<intptr_t>(magnitude);
2762 return true;
2763 }
2764 } else {
2765 if (magnitude <=
2766 static_cast<uintptr_t>(std::numeric_limits<intptr_t>::max())) {
2767 *result = AssertedCast<intptr_t>(magnitude);
2768 return true;
2769 }
2770 }
2771
2772 return false;
2773 }
2774
2775 bool BigInt::isNumber(const BigInt* x, double* result) {
2776 MOZ_MAKE_MEM_UNDEFINED(result, sizeof(*result));
2777
2778 if (!x->absFitsInUint64()) {
2779 return false;
2780 }
2781
2782 if (x->isZero()) {
2783 *result = 0;
2784 return true;
2785 }
2786
2787 uint64_t magnitude = x->uint64FromAbsNonZero();
2788 if (magnitude < uint64_t(DOUBLE_INTEGRAL_PRECISION_LIMIT)) {
2789 *result = x->isNegative() ? -double(magnitude) : double(magnitude);
2790 return true;
2791 }
2792
2793 return false;
2794 }
2795
2796 // Compute `2**bits - (x & (2**bits - 1))`. Used when treating BigInt values as
2797 // arbitrary-precision two's complement signed integers.
2798 BigInt* BigInt::truncateAndSubFromPowerOfTwo(JSContext* cx, HandleBigInt x,
2799 uint64_t bits,
2800 bool resultNegative) {
2801 MOZ_ASSERT(bits != 0);
2802 MOZ_ASSERT(!x->isZero());
2803
2804 if (bits > MaxBitLength) {
2805 ReportOversizedAllocation(cx, JSMSG_BIGINT_TOO_LARGE);
2806 return nullptr;
2807 }
2808
2809 size_t resultLength = CeilDiv(bits, DigitBits);
2810 BigInt* result = createUninitialized(cx, resultLength, resultNegative);
2811 if (!result) {
2812 return nullptr;
2813 }
2814
2815 // Process all digits except the MSD.
2816 size_t xLength = x->digitLength();
2817 Digit borrow = 0;
2818 // Take digits from `x` until its length is exhausted.
2819 for (size_t i = 0; i < std::min(resultLength - 1, xLength); i++) {
2820 Digit newBorrow = 0;
2821 Digit difference = digitSub(0, x->digit(i), &newBorrow);
2822 difference = digitSub(difference, borrow, &newBorrow);
2823 result->setDigit(i, difference);
2824 borrow = newBorrow;
2825 }
2826 // Then simulate leading zeroes in `x` as needed.
2827 for (size_t i = xLength; i < resultLength - 1; i++) {
2828 Digit newBorrow = 0;
2829 Digit difference = digitSub(0, borrow, &newBorrow);
2830 result->setDigit(i, difference);
2831 borrow = newBorrow;
2832 }
2833
2834 // The MSD might contain extra bits that we don't want.
2835 Digit xMSD = resultLength <= xLength ? x->digit(resultLength - 1) : 0;
2836 Digit resultMSD;
2837 if (bits % DigitBits == 0) {
2838 Digit newBorrow = 0;
2839 resultMSD = digitSub(0, xMSD, &newBorrow);
2840 resultMSD = digitSub(resultMSD, borrow, &newBorrow);
2841 } else {
2842 size_t drop = DigitBits - (bits % DigitBits);
2843 xMSD = (xMSD << drop) >> drop;
2844 Digit minuendMSD = Digit(1) << (DigitBits - drop);
2845 Digit newBorrow = 0;
2846 resultMSD = digitSub(minuendMSD, xMSD, &newBorrow);
2847 resultMSD = digitSub(resultMSD, borrow, &newBorrow);
2848 MOZ_ASSERT(newBorrow == 0, "result < 2^bits");
2849 // If all subtracted bits were zero, we have to get rid of the
2850 // materialized minuendMSD again.
2851 resultMSD &= (minuendMSD - 1);
2852 }
2853 result->setDigit(resultLength - 1, resultMSD);
2854
2855 return destructivelyTrimHighZeroDigits(cx, result);
2856 }
2857
2858 BigInt* BigInt::asUintN(JSContext* cx, HandleBigInt x, uint64_t bits) {
2859 if (x->isZero()) {
2860 return x;
2861 }
2862
2863 if (bits == 0) {
2864 return zero(cx);
2865 }
2866
2867 // When truncating a negative number, simulate two's complement.
2868 if (x->isNegative()) {
2869 bool resultNegative = false;
2870 return truncateAndSubFromPowerOfTwo(cx, x, bits, resultNegative);
2871 }
2872
2873 if (bits <= 64) {
2874 uint64_t u64 = toUint64(x);
2875 uint64_t mask = uint64_t(-1) >> (64 - bits);
2876 uint64_t n = u64 & mask;
2877 if (u64 == n && x->absFitsInUint64()) {
2878 return x;
2879 }
2880 return createFromUint64(cx, n);
2881 }
2882
2883 if (bits >= MaxBitLength) {
2884 return x;
2885 }
2886
2887 Digit msd = x->digit(x->digitLength() - 1);
2888 size_t msdBits = DigitBits - DigitLeadingZeroes(msd);
2889 size_t bitLength = msdBits + (x->digitLength() - 1) * DigitBits;
2890
2891 if (bits >= bitLength) {
2892 return x;
2893 }
2894
2895 size_t length = CeilDiv(bits, DigitBits);
2896 MOZ_ASSERT(length >= 2, "single-digit cases should be handled above");
2897 MOZ_ASSERT(length <= x->digitLength());
2898
2899 // Eagerly trim high zero digits.
2900 const size_t highDigitBits = ((bits - 1) % DigitBits) + 1;
2901 const Digit highDigitMask = Digit(-1) >> (DigitBits - highDigitBits);
2902 Digit mask = highDigitMask;
2903 while (length > 0) {
2904 if (x->digit(length - 1) & mask) {
2905 break;
2906 }
2907
2908 mask = Digit(-1);
2909 length--;
2910 }
2911
2912 const bool isNegative = false;
2913 BigInt* res = createUninitialized(cx, length, isNegative);
2914 if (res == nullptr) {
2915 return nullptr;
2916 }
2917
2918 while (length-- > 0) {
2919 res->setDigit(length, x->digit(length) & mask);
2920 mask = Digit(-1);
2921 }
2922 MOZ_ASSERT_IF(length == 0, res->isZero());
2923
2924 return res;
2925 }
2926
2927 BigInt* BigInt::asIntN(JSContext* cx, HandleBigInt x, uint64_t bits) {
2928 if (x->isZero()) {
2929 return x;
2930 }
2931
2932 if (bits == 0) {
2933 return zero(cx);
2934 }
2935
2936 if (bits == 64) {
2937 int64_t n = toInt64(x);
2938 if (((n < 0) == x->isNegative()) && x->absFitsInUint64()) {
2939 return x;
2940 }
2941 return createFromInt64(cx, n);
2942 }
2943
2944 if (bits > MaxBitLength) {
2945 return x;
2946 }
2947
2948 Digit msd = x->digit(x->digitLength() - 1);
2949 size_t msdBits = DigitBits - DigitLeadingZeroes(msd);
2950 size_t bitLength = msdBits + (x->digitLength() - 1) * DigitBits;
2951
2952 if (bits > bitLength) {
2953 return x;
2954 }
2955
2956 Digit signBit = Digit(1) << ((bits - 1) % DigitBits);
2957 if (bits == bitLength && msd < signBit) {
2958 return x;
2959 }
2960
2961 // All the cases above were the trivial cases: truncating zero, or to zero
2962 // bits, or to more bits than are in `x` (so we return `x` directly), or we
2963 // already have the 64-bit fast path. If we get here, follow the textbook
2964 // algorithm from the specification.
2965
2966 // BigInt.asIntN step 3: Let `mod` be `x` modulo `2**bits`.
2967 RootedBigInt mod(cx, asUintN(cx, x, bits));
2968 if (!mod) {
2969 return nullptr;
2970 }
2971
2972 // Step 4: If `mod >= 2**(bits - 1)`, return `mod - 2**bits`; otherwise,
2973 // return `mod`.
2974 if (mod->digitLength() == CeilDiv(bits, DigitBits)) {
2975 MOZ_ASSERT(!mod->isZero(),
2976 "nonzero bits implies nonzero digit length which implies "
2977 "nonzero overall");
2978
2979 if ((mod->digit(mod->digitLength() - 1) & signBit) != 0) {
2980 bool resultNegative = true;
2981 return truncateAndSubFromPowerOfTwo(cx, mod, bits, resultNegative);
2982 }
2983 }
2984
2985 return mod;
2986 }
2987
2988 static bool ValidBigIntOperands(JSContext* cx, HandleValue lhs,
2989 HandleValue rhs) {
2990 MOZ_ASSERT(lhs.isBigInt() || rhs.isBigInt());
2991
2992 if (!lhs.isBigInt() || !rhs.isBigInt()) {
2993 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
2994 JSMSG_BIGINT_TO_NUMBER);
2995 return false;
2996 }
2997
2998 return true;
2999 }
3000
3001 bool BigInt::addValue(JSContext* cx, HandleValue lhs, HandleValue rhs,
3002 MutableHandleValue res) {
3003 if (!ValidBigIntOperands(cx, lhs, rhs)) {
3004 return false;
3005 }
3006
3007 RootedBigInt lhsBigInt(cx, lhs.toBigInt());
3008 RootedBigInt rhsBigInt(cx, rhs.toBigInt());
3009 BigInt* resBigInt = BigInt::add(cx, lhsBigInt, rhsBigInt);
3010 if (!resBigInt) {
3011 return false;
3012 }
3013 res.setBigInt(resBigInt);
3014 return true;
3015 }
3016
3017 bool BigInt::subValue(JSContext* cx, HandleValue lhs, HandleValue rhs,
3018 MutableHandleValue res) {
3019 if (!ValidBigIntOperands(cx, lhs, rhs)) {
3020 return false;
3021 }
3022
3023 RootedBigInt lhsBigInt(cx, lhs.toBigInt());
3024 RootedBigInt rhsBigInt(cx, rhs.toBigInt());
3025 BigInt* resBigInt = BigInt::sub(cx, lhsBigInt, rhsBigInt);
3026 if (!resBigInt) {
3027 return false;
3028 }
3029 res.setBigInt(resBigInt);
3030 return true;
3031 }
3032
3033 bool BigInt::mulValue(JSContext* cx, HandleValue lhs, HandleValue rhs,
3034 MutableHandleValue res) {
3035 if (!ValidBigIntOperands(cx, lhs, rhs)) {
3036 return false;
3037 }
3038
3039 RootedBigInt lhsBigInt(cx, lhs.toBigInt());
3040 RootedBigInt rhsBigInt(cx, rhs.toBigInt());
3041 BigInt* resBigInt = BigInt::mul(cx, lhsBigInt, rhsBigInt);
3042 if (!resBigInt) {
3043 return false;
3044 }
3045 res.setBigInt(resBigInt);
3046 return true;
3047 }
3048
3049 bool BigInt::divValue(JSContext* cx, HandleValue lhs, HandleValue rhs,
3050 MutableHandleValue res) {
3051 if (!ValidBigIntOperands(cx, lhs, rhs)) {
3052 return false;
3053 }
3054
3055 RootedBigInt lhsBigInt(cx, lhs.toBigInt());
3056 RootedBigInt rhsBigInt(cx, rhs.toBigInt());
3057 BigInt* resBigInt = BigInt::div(cx, lhsBigInt, rhsBigInt);
3058 if (!resBigInt) {
3059 return false;
3060 }
3061 res.setBigInt(resBigInt);
3062 return true;
3063 }
3064
3065 bool BigInt::modValue(JSContext* cx, HandleValue lhs, HandleValue rhs,
3066 MutableHandleValue res) {
3067 if (!ValidBigIntOperands(cx, lhs, rhs)) {
3068 return false;
3069 }
3070
3071 RootedBigInt lhsBigInt(cx, lhs.toBigInt());
3072 RootedBigInt rhsBigInt(cx, rhs.toBigInt());
3073 BigInt* resBigInt = BigInt::mod(cx, lhsBigInt, rhsBigInt);
3074 if (!resBigInt) {
3075 return false;
3076 }
3077 res.setBigInt(resBigInt);
3078 return true;
3079 }
3080
3081 bool BigInt::powValue(JSContext* cx, HandleValue lhs, HandleValue rhs,
3082 MutableHandleValue res) {
3083 if (!ValidBigIntOperands(cx, lhs, rhs)) {
3084 return false;
3085 }
3086
3087 RootedBigInt lhsBigInt(cx, lhs.toBigInt());
3088 RootedBigInt rhsBigInt(cx, rhs.toBigInt());
3089 BigInt* resBigInt = BigInt::pow(cx, lhsBigInt, rhsBigInt);
3090 if (!resBigInt) {
3091 return false;
3092 }
3093 res.setBigInt(resBigInt);
3094 return true;
3095 }
3096
3097 bool BigInt::negValue(JSContext* cx, HandleValue operand,
3098 MutableHandleValue res) {
3099 MOZ_ASSERT(operand.isBigInt());
3100
3101 RootedBigInt operandBigInt(cx, operand.toBigInt());
3102 BigInt* resBigInt = BigInt::neg(cx, operandBigInt);
3103 if (!resBigInt) {
3104 return false;
3105 }
3106 res.setBigInt(resBigInt);
3107 return true;
3108 }
3109
3110 bool BigInt::incValue(JSContext* cx, HandleValue operand,
3111 MutableHandleValue res) {
3112 MOZ_ASSERT(operand.isBigInt());
3113
3114 RootedBigInt operandBigInt(cx, operand.toBigInt());
3115 BigInt* resBigInt = BigInt::inc(cx, operandBigInt);
3116 if (!resBigInt) {
3117 return false;
3118 }
3119 res.setBigInt(resBigInt);
3120 return true;
3121 }
3122
3123 bool BigInt::decValue(JSContext* cx, HandleValue operand,
3124 MutableHandleValue res) {
3125 MOZ_ASSERT(operand.isBigInt());
3126
3127 RootedBigInt operandBigInt(cx, operand.toBigInt());
3128 BigInt* resBigInt = BigInt::dec(cx, operandBigInt);
3129 if (!resBigInt) {
3130 return false;
3131 }
3132 res.setBigInt(resBigInt);
3133 return true;
3134 }
3135
3136 bool BigInt::lshValue(JSContext* cx, HandleValue lhs, HandleValue rhs,
3137 MutableHandleValue res) {
3138 if (!ValidBigIntOperands(cx, lhs, rhs)) {
3139 return false;
3140 }
3141
3142 RootedBigInt lhsBigInt(cx, lhs.toBigInt());
3143 RootedBigInt rhsBigInt(cx, rhs.toBigInt());
3144 BigInt* resBigInt = BigInt::lsh(cx, lhsBigInt, rhsBigInt);
3145 if (!resBigInt) {
3146 return false;
3147 }
3148 res.setBigInt(resBigInt);
3149 return true;
3150 }
3151
3152 bool BigInt::rshValue(JSContext* cx, HandleValue lhs, HandleValue rhs,
3153 MutableHandleValue res) {
3154 if (!ValidBigIntOperands(cx, lhs, rhs)) {
3155 return false;
3156 }
3157
3158 RootedBigInt lhsBigInt(cx, lhs.toBigInt());
3159 RootedBigInt rhsBigInt(cx, rhs.toBigInt());
3160 BigInt* resBigInt = BigInt::rsh(cx, lhsBigInt, rhsBigInt);
3161 if (!resBigInt) {
3162 return false;
3163 }
3164 res.setBigInt(resBigInt);
3165 return true;
3166 }
3167
3168 bool BigInt::bitAndValue(JSContext* cx, HandleValue lhs, HandleValue rhs,
3169 MutableHandleValue res) {
3170 if (!ValidBigIntOperands(cx, lhs, rhs)) {
3171 return false;
3172 }
3173
3174 RootedBigInt lhsBigInt(cx, lhs.toBigInt());
3175 RootedBigInt rhsBigInt(cx, rhs.toBigInt());
3176 BigInt* resBigInt = BigInt::bitAnd(cx, lhsBigInt, rhsBigInt);
3177 if (!resBigInt) {
3178 return false;
3179 }
3180 res.setBigInt(resBigInt);
3181 return true;
3182 }
3183
3184 bool BigInt::bitXorValue(JSContext* cx, HandleValue lhs, HandleValue rhs,
3185 MutableHandleValue res) {
3186 if (!ValidBigIntOperands(cx, lhs, rhs)) {
3187 return false;
3188 }
3189
3190 RootedBigInt lhsBigInt(cx, lhs.toBigInt());
3191 RootedBigInt rhsBigInt(cx, rhs.toBigInt());
3192 BigInt* resBigInt = BigInt::bitXor(cx, lhsBigInt, rhsBigInt);
3193 if (!resBigInt) {
3194 return false;
3195 }
3196 res.setBigInt(resBigInt);
3197 return true;
3198 }
3199
3200 bool BigInt::bitOrValue(JSContext* cx, HandleValue lhs, HandleValue rhs,
3201 MutableHandleValue res) {
3202 if (!ValidBigIntOperands(cx, lhs, rhs)) {
3203 return false;
3204 }
3205
3206 RootedBigInt lhsBigInt(cx, lhs.toBigInt());
3207 RootedBigInt rhsBigInt(cx, rhs.toBigInt());
3208 BigInt* resBigInt = BigInt::bitOr(cx, lhsBigInt, rhsBigInt);
3209 if (!resBigInt) {
3210 return false;
3211 }
3212 res.setBigInt(resBigInt);
3213 return true;
3214 }
3215
3216 bool BigInt::bitNotValue(JSContext* cx, HandleValue operand,
3217 MutableHandleValue res) {
3218 MOZ_ASSERT(operand.isBigInt());
3219
3220 RootedBigInt operandBigInt(cx, operand.toBigInt());
3221 BigInt* resBigInt = BigInt::bitNot(cx, operandBigInt);
3222 if (!resBigInt) {
3223 return false;
3224 }
3225 res.setBigInt(resBigInt);
3226 return true;
3227 }
3228
3229 // BigInt proposal section 7.3
3230 BigInt* js::ToBigInt(JSContext* cx, HandleValue val) {
3231 RootedValue v(cx, val);
3232
3233 // Step 1.
3234 if (!ToPrimitive(cx, JSTYPE_NUMBER, &v)) {
3235 return nullptr;
3236 }
3237
3238 // Step 2.
3239 if (v.isBigInt()) {
3240 return v.toBigInt();
3241 }
3242
3243 if (v.isBoolean()) {
3244 return v.toBoolean() ? BigInt::one(cx) : BigInt::zero(cx);
3245 }
3246
3247 if (v.isString()) {
3248 RootedString str(cx, v.toString());
3249 BigInt* bi;
3250 JS_TRY_VAR_OR_RETURN_NULL(cx, bi, StringToBigInt(cx, str));
3251 if (!bi) {
3252 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3253 JSMSG_BIGINT_INVALID_SYNTAX);
3254 return nullptr;
3255 }
3256 return bi;
3257 }
3258
3259 ReportValueError(cx, JSMSG_CANT_CONVERT_TO, JSDVG_IGNORE_STACK, v, nullptr,
3260 "BigInt");
3261 return nullptr;
3262 }
3263
3264 JS::Result<int64_t> js::ToBigInt64(JSContext* cx, HandleValue v) {
3265 BigInt* bi = js::ToBigInt(cx, v);
3266 if (!bi) {
3267 return cx->alreadyReportedError();
3268 }
3269 return BigInt::toInt64(bi);
3270 }
3271
3272 JS::Result<uint64_t> js::ToBigUint64(JSContext* cx, HandleValue v) {
3273 BigInt* bi = js::ToBigInt(cx, v);
3274 if (!bi) {
3275 return cx->alreadyReportedError();
3276 }
3277 return BigInt::toUint64(bi);
3278 }
3279
3280 double BigInt::numberValue(const BigInt* x) {
3281 if (x->isZero()) {
3282 return 0.0;
3283 }
3284
3285 using Double = mozilla::FloatingPoint<double>;
3286 constexpr uint8_t ExponentShift = Double::kExponentShift;
3287 constexpr uint8_t SignificandWidth = Double::kSignificandWidth;
3288 constexpr unsigned ExponentBias = Double::kExponentBias;
3289 constexpr uint8_t SignShift = Double::kExponentWidth + SignificandWidth;
3290
3291 MOZ_ASSERT(x->digitLength() > 0);
3292
3293 // Fast path for the likely-common case of up to a uint64_t of magnitude not
3294 // exceeding integral precision in IEEE-754. (Note that we *depend* on this
3295 // optimization being performed further down.)
3296 if (x->absFitsInUint64()) {
3297 uint64_t magnitude = x->uint64FromAbsNonZero();
3298 const uint64_t MaxIntegralPrecisionDouble = uint64_t(1)
3299 << (SignificandWidth + 1);
3300 if (magnitude <= MaxIntegralPrecisionDouble) {
3301 return x->isNegative() ? -double(magnitude) : +double(magnitude);
3302 }
3303 }
3304
3305 size_t length = x->digitLength();
3306 Digit msd = x->digit(length - 1);
3307 uint8_t msdLeadingZeroes = DigitLeadingZeroes(msd);
3308
3309 // `2**ExponentBias` is the largest power of two in a finite IEEE-754
3310 // double. If this bigint has a greater power of two, it'll round to
3311 // infinity.
3312 uint64_t exponent = length * DigitBits - msdLeadingZeroes - 1;
3313 if (exponent > ExponentBias) {
3314 return x->isNegative() ? mozilla::NegativeInfinity<double>()
3315 : mozilla::PositiveInfinity<double>();
3316 }
3317
3318 // Otherwise munge the most significant bits of the number into proper
3319 // position in an IEEE-754 double and go to town.
3320
3321 // Omit the most significant bit: the IEEE-754 format includes this bit
3322 // implicitly for all double-precision integers.
3323 const uint8_t msdIgnoredBits = msdLeadingZeroes + 1;
3324 const uint8_t msdIncludedBits = DigitBits - msdIgnoredBits;
3325
3326 // We compute the final mantissa of the result, shifted upward to the top of
3327 // the `uint64_t` space -- plus an extra bit to detect potential rounding.
3328 constexpr uint8_t BitsNeededForShiftedMantissa = SignificandWidth + 1;
3329
3330 // Shift `msd`'s contributed bits upward to remove high-order zeroes and the
3331 // highest set bit (which is implicit in IEEE-754 integral values so must be
3332 // removed) and to add low-order zeroes. (Lower-order garbage bits are
3333 // discarded when `shiftedMantissa` is converted to a real mantissa.)
3334 uint64_t shiftedMantissa =
3335 msdIncludedBits == 0 ? 0 : uint64_t(msd) << (64 - msdIncludedBits);
3336
3337 // If the extra bit is set, correctly rounding the result may require
3338 // examining all lower-order bits. Also compute 1) the index of the Digit
3339 // storing the extra bit, and 2) whether bits beneath the extra bit in that
3340 // Digit are nonzero so we can round if needed.
3341 size_t digitContainingExtraBit;
3342 Digit bitsBeneathExtraBitInDigitContainingExtraBit;
3343
3344 // Add shifted bits to `shiftedMantissa` until we have a complete mantissa and
3345 // an extra bit.
3346 if (msdIncludedBits >= BitsNeededForShiftedMantissa) {
3347 // DigitBits=64 (necessarily for msdIncludedBits ≥ SignificandWidth+1;
3348 // | C++ compiler range analysis ought eliminate this
3349 // | check on 32-bit)
3350 // _________|__________
3351 // / |
3352 // msdIncludedBits
3353 // ________|________
3354 // / |
3355 // [001···················|
3356 // \_/\_____________/\__|
3357 // | | |
3358 // msdIgnoredBits | bits below the extra bit (may be no bits)
3359 // BitsNeededForShiftedMantissa=SignificandWidth+1
3360 digitContainingExtraBit = length - 1;
3361
3362 const uint8_t countOfBitsInDigitBelowExtraBit =
3363 DigitBits - BitsNeededForShiftedMantissa - msdIgnoredBits;
3364 bitsBeneathExtraBitInDigitContainingExtraBit =
3365 msd & ((Digit(1) << countOfBitsInDigitBelowExtraBit) - 1);
3366 } else {
3367 MOZ_ASSERT(length >= 2,
3368 "single-Digit numbers with this few bits should have been "
3369 "handled by the fast-path above");
3370
3371 Digit second = x->digit(length - 2);
3372 if (DigitBits == 64) {
3373 shiftedMantissa |= second >> msdIncludedBits;
3374
3375 digitContainingExtraBit = length - 2;
3376
3377 // msdIncludedBits + DigitBits
3378 // ________|_________
3379 // / |
3380 // DigitBits=64
3381 // msdIncludedBits |
3382 // __|___ _____|___
3383 // / \ / |
3384 // [001········|···········|
3385 // \_/\_____________/\___|
3386 // | | |
3387 // msdIgnoredBits | bits below the extra bit (always more than one)
3388 // |
3389 // BitsNeededForShiftedMantissa=SignificandWidth+1
3390 const uint8_t countOfBitsInSecondDigitBelowExtraBit =
3391 (msdIncludedBits + DigitBits) - BitsNeededForShiftedMantissa;
3392
3393 bitsBeneathExtraBitInDigitContainingExtraBit =
3394 second << (DigitBits - countOfBitsInSecondDigitBelowExtraBit);
3395 } else {
3396 shiftedMantissa |= uint64_t(second) << msdIgnoredBits;
3397
3398 if (msdIncludedBits + DigitBits >= BitsNeededForShiftedMantissa) {
3399 digitContainingExtraBit = length - 2;
3400
3401 // msdIncludedBits + DigitBits
3402 // ______|________
3403 // / |
3404 // DigitBits=32
3405 // msdIncludedBits |
3406 // _|_ _____|___
3407 // / \ / |
3408 // [001·····|···········|
3409 // \___________/\__|
3410 // | |
3411 // | bits below the extra bit (may be no bits)
3412 // BitsNeededForShiftedMantissa=SignificandWidth+1
3413 const uint8_t countOfBitsInSecondDigitBelowExtraBit =
3414 (msdIncludedBits + DigitBits) - BitsNeededForShiftedMantissa;
3415
3416 bitsBeneathExtraBitInDigitContainingExtraBit =
3417 second & ((Digit(1) << countOfBitsInSecondDigitBelowExtraBit) - 1);
3418 } else {
3419 MOZ_ASSERT(length >= 3,
3420 "we must have at least three digits here, because "
3421 "`msdIncludedBits + 32 < BitsNeededForShiftedMantissa` "
3422 "guarantees `x < 2**53` -- and therefore the "
3423 "MaxIntegralPrecisionDouble optimization above will have "
3424 "handled two-digit cases");
3425
3426 Digit third = x->digit(length - 3);
3427 shiftedMantissa |= uint64_t(third) >> msdIncludedBits;
3428
3429 digitContainingExtraBit = length - 3;
3430
3431 // msdIncludedBits + DigitBits + DigitBits
3432 // ____________|______________
3433 // / |
3434 // DigitBits=32
3435 // msdIncludedBits | DigitBits=32
3436 // _|_ _____|___ ____|____
3437 // / \ / \ / |
3438 // [001·····|···········|···········|
3439 // \____________________/\_____|
3440 // | |
3441 // | bits below the extra bit
3442 // BitsNeededForShiftedMantissa=SignificandWidth+1
3443 static_assert(2 * DigitBits > BitsNeededForShiftedMantissa,
3444 "two 32-bit digits should more than fill a mantissa");
3445 const uint8_t countOfBitsInThirdDigitBelowExtraBit =
3446 msdIncludedBits + 2 * DigitBits - BitsNeededForShiftedMantissa;
3447
3448 // Shift out the mantissa bits and the extra bit.
3449 bitsBeneathExtraBitInDigitContainingExtraBit =
3450 third << (DigitBits - countOfBitsInThirdDigitBelowExtraBit);
3451 }
3452 }
3453 }
3454
3455 constexpr uint64_t LeastSignificantBit = uint64_t(1)
3456 << (64 - SignificandWidth);
3457 constexpr uint64_t ExtraBit = LeastSignificantBit >> 1;
3458
3459 // The extra bit must be set for rounding to change the mantissa.
3460 if ((shiftedMantissa & ExtraBit) != 0) {
3461 bool shouldRoundUp;
3462 if (shiftedMantissa & LeastSignificantBit) {
3463 // If the lowest mantissa bit is set, it doesn't matter what lower bits
3464 // are: nearest-even rounds up regardless.
3465 shouldRoundUp = true;
3466 } else {
3467 // If the lowest mantissa bit is unset, *all* lower bits are relevant.
3468 // All-zero bits below the extra bit situates `x` halfway between two
3469 // values, and the nearest *even* value lies downward. But if any bit
3470 // below the extra bit is set, `x` is closer to the rounded-up value.
3471 shouldRoundUp = bitsBeneathExtraBitInDigitContainingExtraBit != 0;
3472 if (!shouldRoundUp) {
3473 while (digitContainingExtraBit-- > 0) {
3474 if (x->digit(digitContainingExtraBit) != 0) {
3475 shouldRoundUp = true;
3476 break;
3477 }
3478 }
3479 }
3480 }
3481
3482 if (shouldRoundUp) {
3483 // Add one to the significand bits. If they overflow, the exponent must
3484 // also be increased. If *that* overflows, return the correct infinity.
3485 uint64_t before = shiftedMantissa;
3486 shiftedMantissa += ExtraBit;
3487 if (shiftedMantissa < before) {
3488 exponent++;
3489 if (exponent > ExponentBias) {
3490 return x->isNegative() ? NegativeInfinity<double>()
3491 : PositiveInfinity<double>();
3492 }
3493 }
3494 }
3495 }
3496
3497 uint64_t significandBits = shiftedMantissa >> (64 - SignificandWidth);
3498 uint64_t signBit = uint64_t(x->isNegative() ? 1 : 0) << SignShift;
3499 uint64_t exponentBits = (exponent + ExponentBias) << ExponentShift;
3500 return mozilla::BitwiseCast<double>(signBit | exponentBits | significandBits);
3501 }
3502
3503 int8_t BigInt::compare(const BigInt* x, const BigInt* y) {
3504 // Sanity checks to catch negative zeroes escaping to the wild.
3505 MOZ_ASSERT(!x->isNegative() || !x->isZero());
3506 MOZ_ASSERT(!y->isNegative() || !y->isZero());
3507
3508 bool xSign = x->isNegative();
3509
3510 if (xSign != y->isNegative()) {
3511 return xSign ? -1 : 1;
3512 }
3513
3514 if (xSign) {
3515 std::swap(x, y);
3516 }
3517
3518 return absoluteCompare(x, y);
3519 }
3520
3521 bool BigInt::equal(const BigInt* lhs, const BigInt* rhs) {
3522 if (lhs == rhs) {
3523 return true;
3524 }
3525 if (lhs->digitLength() != rhs->digitLength()) {
3526 return false;
3527 }
3528 if (lhs->isNegative() != rhs->isNegative()) {
3529 return false;
3530 }
3531 for (size_t i = 0; i < lhs->digitLength(); i++) {
3532 if (lhs->digit(i) != rhs->digit(i)) {
3533 return false;
3534 }
3535 }
3536 return true;
3537 }
3538
3539 int8_t BigInt::compare(const BigInt* x, double y) {
3540 MOZ_ASSERT(!std::isnan(y));
3541
3542 constexpr int LessThan = -1, Equal = 0, GreaterThan = 1;
3543
3544 // ±Infinity exceeds a finite bigint value.
3545 if (!std::isfinite(y)) {
3546 return y > 0 ? LessThan : GreaterThan;
3547 }
3548
3549 // Handle `x === 0n` and `y == 0` special cases.
3550 if (x->isZero()) {
3551 if (y == 0) {
3552 // -0 and +0 are treated identically.
3553 return Equal;
3554 }
3555
3556 return y > 0 ? LessThan : GreaterThan;
3557 }
3558
3559 const bool xNegative = x->isNegative();
3560 if (y == 0) {
3561 return xNegative ? LessThan : GreaterThan;
3562 }
3563
3564 // Nonzero `x` and `y` with different signs are trivially compared.
3565 const bool yNegative = y < 0;
3566 if (xNegative != yNegative) {
3567 return xNegative ? LessThan : GreaterThan;
3568 }
3569
3570 // `x` and `y` are same-signed. Determine which has greater magnitude,
3571 // then combine that with the signedness just computed to reach a result.
3572 const int exponent = mozilla::ExponentComponent(y);
3573 if (exponent < 0) {
3574 // `y` is a nonzero fraction of magnitude less than 1.
3575 return xNegative ? LessThan : GreaterThan;
3576 }
3577
3578 size_t xLength = x->digitLength();
3579 MOZ_ASSERT(xLength > 0);
3580
3581 Digit xMSD = x->digit(xLength - 1);
3582 const int shift = DigitLeadingZeroes(xMSD);
3583 int xBitLength = xLength * DigitBits - shift;
3584
3585 // Differing bit-length makes for a simple comparison.
3586 int yBitLength = exponent + 1;
3587 if (xBitLength < yBitLength) {
3588 return xNegative ? GreaterThan : LessThan;
3589 }
3590 if (xBitLength > yBitLength) {
3591 return xNegative ? LessThan : GreaterThan;
3592 }
3593
3594 // Compare the high 64 bits of both numbers. (Lower-order bits not present
3595 // in either number are zeroed.) Either that distinguishes `x` and `y`, or
3596 // `x` and `y` differ only if a subsequent nonzero bit in `x` means `x` has
3597 // larger magnitude.
3598
3599 using Double = mozilla::FloatingPoint<double>;
3600 constexpr uint8_t SignificandWidth = Double::kSignificandWidth;
3601 constexpr uint64_t SignificandBits = Double::kSignificandBits;
3602
3603 const uint64_t doubleBits = mozilla::BitwiseCast<uint64_t>(y);
3604 const uint64_t significandBits = doubleBits & SignificandBits;
3605
3606 // Readd the implicit-one bit when constructing `y`'s high 64 bits.
3607 const uint64_t yHigh64Bits =
3608 ((uint64_t(1) << SignificandWidth) | significandBits)
3609 << (64 - SignificandWidth - 1);
3610
3611 // Cons up `x`'s high 64 bits, backfilling zeroes for binary fractions of 1
3612 // if `x` doesn't have 64 bits.
3613 uint8_t xBitsFilled = DigitBits - shift;
3614 uint64_t xHigh64Bits = uint64_t(xMSD) << (64 - xBitsFilled);
3615
3616 // At this point we no longer need to look at the most significant digit.
3617 xLength--;
3618
3619 // The high 64 bits from `x` will probably not align to a digit boundary.
3620 // `xHasNonZeroLeftoverBits` will be set to true if any remaining
3621 // least-significant bit from the digit holding xHigh64Bits's
3622 // least-significant bit is nonzero.
3623 bool xHasNonZeroLeftoverBits = false;
3624
3625 if (xBitsFilled < std::min(xBitLength, 64)) {
3626 MOZ_ASSERT(xLength >= 1,
3627 "If there are more bits to fill, there should be "
3628 "more digits to fill them from");
3629
3630 Digit second = x->digit(--xLength);
3631 if (DigitBits == 32) {
3632 xBitsFilled += 32;
3633 xHigh64Bits |= uint64_t(second) << (64 - xBitsFilled);
3634 if (xBitsFilled < 64 && xLength >= 1) {
3635 Digit third = x->digit(--xLength);
3636 const uint8_t neededBits = 64 - xBitsFilled;
3637 xHigh64Bits |= uint64_t(third) >> (DigitBits - neededBits);
3638 xHasNonZeroLeftoverBits = (third << neededBits) != 0;
3639 }
3640 } else {
3641 const uint8_t neededBits = 64 - xBitsFilled;
3642 xHigh64Bits |= uint64_t(second) >> (DigitBits - neededBits);
3643 xHasNonZeroLeftoverBits = (second << neededBits) != 0;
3644 }
3645 }
3646
3647 // If high bits are unequal, the larger one has greater magnitude.
3648 if (yHigh64Bits > xHigh64Bits) {
3649 return xNegative ? GreaterThan : LessThan;
3650 }
3651 if (xHigh64Bits > yHigh64Bits) {
3652 return xNegative ? LessThan : GreaterThan;
3653 }
3654
3655 // Otherwise the top 64 bits of both are equal. If the values differ, a
3656 // lower-order bit in `x` is nonzero and `x` has greater magnitude than
3657 // `y`; otherwise `x == y`.
3658 if (xHasNonZeroLeftoverBits) {
3659 return xNegative ? LessThan : GreaterThan;
3660 }
3661 while (xLength != 0) {
3662 if (x->digit(--xLength) != 0) {
3663 return xNegative ? LessThan : GreaterThan;
3664 }
3665 }
3666
3667 return Equal;
3668 }
3669
3670 bool BigInt::equal(const BigInt* lhs, double rhs) {
3671 if (std::isnan(rhs)) {
3672 return false;
3673 }
3674 return compare(lhs, rhs) == 0;
3675 }
3676
3677 JS::Result<bool> BigInt::equal(JSContext* cx, Handle<BigInt*> lhs,
3678 HandleString rhs) {
3679 BigInt* rhsBigInt;
3680 MOZ_TRY_VAR(rhsBigInt, StringToBigInt(cx, rhs));
3681 if (!rhsBigInt) {
3682 return false;
3683 }
3684 return equal(lhs, rhsBigInt);
3685 }
3686
3687 // BigInt proposal section 1.1.12. BigInt::lessThan ( x, y )
3688 bool BigInt::lessThan(const BigInt* x, const BigInt* y) {
3689 return compare(x, y) < 0;
3690 }
3691
3692 Maybe<bool> BigInt::lessThan(const BigInt* lhs, double rhs) {
3693 if (std::isnan(rhs)) {
3694 return Maybe<bool>(Nothing());
3695 }
3696 return Some(compare(lhs, rhs) < 0);
3697 }
3698
3699 Maybe<bool> BigInt::lessThan(double lhs, const BigInt* rhs) {
3700 if (std::isnan(lhs)) {
3701 return Maybe<bool>(Nothing());
3702 }
3703 return Some(-compare(rhs, lhs) < 0);
3704 }
3705
3706 bool BigInt::lessThan(JSContext* cx, HandleBigInt lhs, HandleString rhs,
3707 Maybe<bool>& res) {
3708 BigInt* rhsBigInt;
3709 JS_TRY_VAR_OR_RETURN_FALSE(cx, rhsBigInt, StringToBigInt(cx, rhs));
3710 if (!rhsBigInt) {
3711 res = Nothing();
3712 return true;
3713 }
3714 res = Some(lessThan(lhs, rhsBigInt));
3715 return true;
3716 }
3717
3718 bool BigInt::lessThan(JSContext* cx, HandleString lhs, HandleBigInt rhs,
3719 Maybe<bool>& res) {
3720 BigInt* lhsBigInt;
3721 JS_TRY_VAR_OR_RETURN_FALSE(cx, lhsBigInt, StringToBigInt(cx, lhs));
3722 if (!lhsBigInt) {
3723 res = Nothing();
3724 return true;
3725 }
3726 res = Some(lessThan(lhsBigInt, rhs));
3727 return true;
3728 }
3729
3730 bool BigInt::lessThan(JSContext* cx, HandleValue lhs, HandleValue rhs,
3731 Maybe<bool>& res) {
3732 if (lhs.isBigInt()) {
3733 if (rhs.isString()) {
3734 RootedBigInt lhsBigInt(cx, lhs.toBigInt());
3735 RootedString rhsString(cx, rhs.toString());
3736 return lessThan(cx, lhsBigInt, rhsString, res);
3737 }
3738
3739 if (rhs.isNumber()) {
3740 res = lessThan(lhs.toBigInt(), rhs.toNumber());
3741 return true;
3742 }
3743
3744 MOZ_ASSERT(rhs.isBigInt());
3745 res = Some(lessThan(lhs.toBigInt(), rhs.toBigInt()));
3746 return true;
3747 }
3748
3749 MOZ_ASSERT(rhs.isBigInt());
3750 if (lhs.isString()) {
3751 RootedString lhsString(cx, lhs.toString());
3752 RootedBigInt rhsBigInt(cx, rhs.toBigInt());
3753 return lessThan(cx, lhsString, rhsBigInt, res);
3754 }
3755
3756 MOZ_ASSERT(lhs.isNumber());
3757 res = lessThan(lhs.toNumber(), rhs.toBigInt());
3758 return true;
3759 }
3760
3761 template <js::AllowGC allowGC>
3762 JSLinearString* BigInt::toString(JSContext* cx, HandleBigInt x, uint8_t radix) {
3763 MOZ_ASSERT(2 <= radix && radix <= 36);
3764
3765 if (x->isZero()) {
3766 return cx->staticStrings().getInt(0);
3767 }
3768
3769 if (x->digitLength() == 1) {
3770 return toStringSingleDigit<allowGC>(cx, x->digit(0), x->isNegative(),
3771 radix);
3772 }
3773
3774 if (mozilla::IsPowerOfTwo(radix)) {
3775 return toStringBasePowerOfTwo<allowGC>(cx, x, radix);
3776 }
3777
3778 // Punt on doing generic toString without GC.
3779 if (!allowGC) {
3780 return nullptr;
3781 }
3782
3783 return toStringGeneric(cx, x, radix);
3784 }
3785
3786 template JSLinearString* BigInt::toString<js::CanGC>(JSContext* cx,
3787 HandleBigInt x,
3788 uint8_t radix);
3789 template JSLinearString* BigInt::toString<js::NoGC>(JSContext* cx,
3790 HandleBigInt x,
3791 uint8_t radix);
3792
3793 template <typename CharT>
3794 static inline BigInt* ParseStringBigIntLiteral(JSContext* cx,
3795 Range<const CharT> range,
3796 bool* haveParseError) {
3797 auto start = range.begin();
3798 auto end = range.end();
3799
3800 while (start < end && unicode::IsSpace(start[0])) {
3801 start++;
3802 }
3803
3804 while (start < end && unicode::IsSpace(end[-1])) {
3805 end--;
3806 }
3807
3808 if (start == end) {
3809 return BigInt::zero(cx);
3810 }
3811
3812 // StringNumericLiteral ::: StrDecimalLiteral, but without Infinity, decimal
3813 // points, or exponents. Note that the raw '+' or '-' cases fall through
3814 // because the string is too short, and eventually signal a parse error.
3815 if (end - start > 1) {
3816 if (start[0] == '+') {
3817 bool isNegative = false;
3818 start++;
3819 return BigInt::parseLiteralDigits(cx, Range<const CharT>(start, end), 10,
3820 isNegative, haveParseError);
3821 }
3822 if (start[0] == '-') {
3823 bool isNegative = true;
3824 start++;
3825 return BigInt::parseLiteralDigits(cx, Range<const CharT>(start, end), 10,
3826 isNegative, haveParseError);
3827 }
3828 }
3829
3830 return BigInt::parseLiteral(cx, Range<const CharT>(start, end),
3831 haveParseError);
3832 }
3833
3834 // Called from BigInt constructor.
3835 JS::Result<BigInt*> js::StringToBigInt(JSContext* cx, HandleString str) {
3836 JSLinearString* linear = str->ensureLinear(cx);
3837 if (!linear) {
3838 return cx->alreadyReportedOOM();
3839 }
3840
3841 AutoStableStringChars chars(cx);
3842 if (!chars.init(cx, str)) {
3843 return cx->alreadyReportedOOM();
3844 }
3845
3846 BigInt* res;
3847 bool parseError = false;
3848 if (chars.isLatin1()) {
3849 res = ParseStringBigIntLiteral(cx, chars.latin1Range(), &parseError);
3850 } else {
3851 res = ParseStringBigIntLiteral(cx, chars.twoByteRange(), &parseError);
3852 }
3853
3854 // A nullptr result can indicate either a parse error or generic error.
3855 if (!res && !parseError) {
3856 return cx->alreadyReportedError();
3857 }
3858
3859 return res;
3860 }
3861
3862 // Called from parser with already trimmed and validated token.
3863 BigInt* js::ParseBigIntLiteral(JSContext* cx,
3864 const Range<const char16_t>& chars) {
3865 // This function is only called from the frontend when parsing BigInts. Parsed
3866 // BigInts are stored in the script's data vector and therefore need to be
3867 // allocated in the tenured heap.
3868 constexpr gc::Heap heap = gc::Heap::Tenured;
3869
3870 bool parseError = false;
3871 BigInt* res = BigInt::parseLiteral(cx, chars, &parseError, heap);
3872 if (!res) {
3873 return nullptr;
3874 }
3875 MOZ_ASSERT(res->isTenured());
3876 MOZ_RELEASE_ASSERT(!parseError);
3877 return res;
3878 }
3879
3880 mozilla::Maybe<int64_t> js::ParseBigInt64Literal(
3881 mozilla::Range<const char16_t> chars) {
3882 size_t length = chars.length();
3883 MOZ_ASSERT(length > 0);
3884
3885 int32_t radix = 10;
3886 if (length > 2 && chars[0] == '0') {
3887 if (chars[1] == 'b' || chars[1] == 'B') {
3888 // StringNumericLiteral ::: BinaryIntegerLiteral
3889 radix = 2;
3890 } else if (chars[1] == 'x' || chars[1] == 'X') {
3891 // StringNumericLiteral ::: HexIntegerLiteral
3892 radix = 16;
3893 } else if (chars[1] == 'o' || chars[1] == 'O') {
3894 // StringNumericLiteral ::: OctalIntegerLiteral
3895 radix = 8;
3896 }
3897 }
3898
3899 auto start = chars.begin();
3900 const auto end = chars.end();
3901
3902 // Skip over prefix.
3903 if (radix != 10) {
3904 start += 2;
3905 }
3906
3907 // Skipping leading zeroes.
3908 while (*start == '0') {
3909 start++;
3910 if (start == end) {
3911 return mozilla::Some(0);
3912 }
3913 }
3914
3915 mozilla::CheckedInt<int64_t> r = 0;
3916 while (start < end) {
3917 char16_t c = *start++;
3918 MOZ_ASSERT(mozilla::IsAsciiAlphanumeric(c));
3919
3920 int32_t digit = mozilla::AsciiAlphanumericToNumber(c);
3921 MOZ_ASSERT(digit < radix);
3922
3923 r *= radix;
3924 r += digit;
3925 if (!r.isValid()) {
3926 return mozilla::Nothing();
3927 }
3928 }
3929
3930 return mozilla::Some(r.value());
3931 }
3932
3933 template <js::AllowGC allowGC>
3934 JSAtom* js::BigIntToAtom(JSContext* cx, HandleBigInt bi) {
3935 JSString* str = BigInt::toString<allowGC>(cx, bi, 10);
3936 if (!str) {
3937 return nullptr;
3938 }
3939 JSAtom* atom = AtomizeString(cx, str);
3940 if (!atom) {
3941 if constexpr (!allowGC) {
3942 // NOTE: AtomizeString can call ReportAllocationOverflow other than
3943 // ReportOutOfMemory, but ReportAllocationOverflow cannot happen
3944 // because the length is guarded by BigInt::toString.
3945 cx->recoverFromOutOfMemory();
3946 }
3947 return nullptr;
3948 }
3949 return atom;
3950 }
3951
3952 template JSAtom* js::BigIntToAtom<js::CanGC>(JSContext* cx, HandleBigInt bi);
3953 template JSAtom* js::BigIntToAtom<js::NoGC>(JSContext* cx, HandleBigInt bi);
3954
3955 #if defined(DEBUG) || defined(JS_JITSPEW)
3956 void BigInt::dump() const {
3957 js::Fprinter out(stderr);
3958 dump(out);
3959 }
3960
3961 void BigInt::dump(js::GenericPrinter& out) const {
3962 js::JSONPrinter json(out);
3963 dump(json);
3964 out.put("\n");
3965 }
3966
3967 void BigInt::dump(js::JSONPrinter& json) const {
3968 json.beginObject();
3969 dumpFields(json);
3970 json.endObject();
3971 }
3972
3973 void BigInt::dumpFields(js::JSONPrinter& json) const {
3974 json.formatProperty("address", "(JS::BigInt*)0x%p", this);
3975
3976 json.property("digitLength", digitLength());
3977
3978 js::GenericPrinter& out = json.beginStringProperty("value");
3979 dumpLiteral(out);
3980 json.endStringProperty();
3981 }
3982
3983 void BigInt::dumpStringContent(js::GenericPrinter& out) const {
3984 dumpLiteral(out);
3985
3986 out.printf(" @ (JS::BigInt*)0x%p", this);
3987 }
3988
3989 void BigInt::dumpLiteral(js::GenericPrinter& out) const {
3990 if (isNegative()) {
3991 out.putChar('-');
3992 }
3993
3994 if (digitLength() == 0) {
3995 out.put("0");
3996 } else if (digitLength() == 1) {
3997 uint64_t d = digit(0);
3998 out.printf("%" PRIu64, d);
3999 } else {
4000 out.put("0x");
4001 for (size_t i = 0; i < digitLength(); i++) {
4002 uint64_t d = digit(digitLength() - i - 1);
4003 if (sizeof(Digit) == 4) {
4004 out.printf("%.8" PRIX32, uint32_t(d));
4005 } else {
4006 out.printf("%.16" PRIX64, d);
4007 }
4008 }
4009 }
4010
4011 out.putChar('n');
4012 }
4013 #endif
4014
4015 JS::ubi::Node::Size JS::ubi::Concrete<BigInt>::size(
4016 mozilla::MallocSizeOf mallocSizeOf) const {
4017 BigInt& bi = get();
4018 size_t size = sizeof(JS::BigInt);
4019 if (IsInsideNursery(&bi)) {
4020 size += Nursery::nurseryCellHeaderSize();
4021 size += bi.sizeOfExcludingThisInNursery(mallocSizeOf);
4022 } else {
4023 size += bi.sizeOfExcludingThis(mallocSizeOf);
4024 }
4025 return size;
4026 }
4027
4028 // Public API
4029
4030 BigInt* JS::NumberToBigInt(JSContext* cx, double num) {
4031 return js::NumberToBigInt(cx, num);
4032 }
4033
4034 template <typename CharT>
4035 static inline BigInt* StringToBigIntHelper(JSContext* cx,
4036 const Range<const CharT>& chars) {
4037 bool parseError = false;
4038 BigInt* bi = ParseStringBigIntLiteral(cx, chars, &parseError);
4039 if (!bi) {
4040 if (parseError) {
4041 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
4042 JSMSG_BIGINT_INVALID_SYNTAX);
4043 }
4044 return nullptr;
4045 }
4046 MOZ_RELEASE_ASSERT(!parseError);
4047 return bi;
4048 }
4049
4050 BigInt* JS::StringToBigInt(JSContext* cx,
4051 const Range<const Latin1Char>& chars) {
4052 return StringToBigIntHelper(cx, chars);
4053 }
4054
4055 BigInt* JS::StringToBigInt(JSContext* cx, const Range<const char16_t>& chars) {
4056 return StringToBigIntHelper(cx, chars);
4057 }
4058
4059 BigInt* JS::SimpleStringToBigInt(JSContext* cx, mozilla::Span<const char> chars,
4060 uint8_t radix) {
4061 if (chars.empty()) {
4062 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
4063 JSMSG_BIGINT_INVALID_SYNTAX);
4064 return nullptr;
4065 }
4066 if (radix < 2 || radix > 36) {
4067 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_BAD_RADIX);
4068 return nullptr;
4069 }
4070
4071 mozilla::Span<const Latin1Char> latin1{
4072 reinterpret_cast<const Latin1Char*>(chars.data()), chars.size()};
4073
4074 bool isNegative = false;
4075 if (chars.size() > 1 && (chars[0] == '-' || chars[0] == '+')) {
4076 isNegative = chars[0] == '-';
4077 latin1 = latin1.From(1);
4078 }
4079
4080 bool haveParseError = false;
4081 BigInt* bi = BigInt::parseLiteralDigits(cx, mozilla::Range{latin1}, radix,
4082 isNegative, &haveParseError);
4083 if (!bi) {
4084 if (haveParseError) {
4085 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
4086 JSMSG_BIGINT_INVALID_SYNTAX);
4087 }
4088 return nullptr;
4089 }
4090 MOZ_RELEASE_ASSERT(!haveParseError);
4091 return bi;
4092 }
4093
4094 BigInt* JS::ToBigInt(JSContext* cx, HandleValue val) {
4095 return js::ToBigInt(cx, val);
4096 }
4097
4098 int64_t JS::ToBigInt64(const JS::BigInt* bi) { return BigInt::toInt64(bi); }
4099
4100 uint64_t JS::ToBigUint64(const JS::BigInt* bi) { return BigInt::toUint64(bi); }
4101
4102 double JS::BigIntToNumber(const JS::BigInt* bi) {
4103 return BigInt::numberValue(bi);
4104 }
4105
4106 bool JS::BigIntIsNegative(const BigInt* bi) {
4107 return !bi->isZero() && bi->isNegative();
4108 }
4109
4110 bool JS::BigIntFitsNumber(const BigInt* bi, double* out) {
4111 return bi->isNumber(bi, out);
4112 }
4113
4114 JSString* JS::BigIntToString(JSContext* cx, Handle<BigInt*> bi, uint8_t radix) {
4115 if (radix < 2 || radix > 36) {
4116 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_BAD_RADIX);
4117 return nullptr;
4118 }
4119 return BigInt::toString<CanGC>(cx, bi, radix);
4120 }
4121
4122 // Semi-public template details
4123
4124 BigInt* JS::detail::BigIntFromInt64(JSContext* cx, int64_t num) {
4125 return BigInt::createFromInt64(cx, num);
4126 }
4127
4128 BigInt* JS::detail::BigIntFromUint64(JSContext* cx, uint64_t num) {
4129 return BigInt::createFromUint64(cx, num);
4130 }
4131
4132 BigInt* JS::detail::BigIntFromBool(JSContext* cx, bool b) {
4133 return b ? BigInt::one(cx) : BigInt::zero(cx);
4134 }
4135
4136 bool JS::detail::BigIntIsInt64(const BigInt* bi, int64_t* result) {
4137 return BigInt::isInt64(bi, result);
4138 }
4139
4140 bool JS::detail::BigIntIsUint64(const BigInt* bi, uint64_t* result) {
4141 return BigInt::isUint64(bi, result);
4142 }