1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2  * vim: set ts=8 sts=4 et sw=4 tw=99:
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  * JS math package.
9  */
10 
11 #include "jsmath.h"
12 
13 #include "mozilla/FloatingPoint.h"
14 #include "mozilla/MathAlgorithms.h"
15 #include "mozilla/MemoryReporting.h"
16 
17 #include <algorithm>  // for std::max
18 #include <fcntl.h>
19 
20 #ifdef XP_UNIX
21 # include <unistd.h>
22 #endif
23 
24 #ifdef XP_WIN
25 # include "jswin.h"
26 #endif
27 
28 #include "jsapi.h"
29 #include "jsatom.h"
30 #include "jscntxt.h"
31 #include "jscompartment.h"
32 #include "jslibmath.h"
33 #include "jstypes.h"
34 
35 #include "jit/InlinableNatives.h"
36 #include "js/Class.h"
37 #include "vm/Time.h"
38 
39 #include "jsobjinlines.h"
40 
41 #if defined(XP_WIN)
42 // #define needed to link in RtlGenRandom(), a.k.a. SystemFunction036.  See the
43 // "Community Additions" comment on MSDN here:
44 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa387694.aspx
45 # define SystemFunction036 NTAPI SystemFunction036
46 # include <NTSecAPI.h>
47 # undef SystemFunction036
48 #endif
49 
50 #if defined(ANDROID) || defined(XP_DARWIN) || defined(__DragonFly__) || \
51     defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
52 # include <stdlib.h>
53 # define HAVE_ARC4RANDOM
54 #endif
55 
56 using namespace js;
57 
58 using mozilla::Abs;
59 using mozilla::NumberEqualsInt32;
60 using mozilla::NumberIsInt32;
61 using mozilla::ExponentComponent;
62 using mozilla::FloatingPoint;
63 using mozilla::IsFinite;
64 using mozilla::IsInfinite;
65 using mozilla::IsNaN;
66 using mozilla::IsNegative;
67 using mozilla::IsNegativeZero;
68 using mozilla::PositiveInfinity;
69 using mozilla::NegativeInfinity;
70 using JS::ToNumber;
71 using JS::GenericNaN;
72 
73 static const JSConstDoubleSpec math_constants[] = {
74     {"E"      ,  M_E       },
75     {"LOG2E"  ,  M_LOG2E   },
76     {"LOG10E" ,  M_LOG10E  },
77     {"LN2"    ,  M_LN2     },
78     {"LN10"   ,  M_LN10    },
79     {"PI"     ,  M_PI      },
80     {"SQRT2"  ,  M_SQRT2   },
81     {"SQRT1_2",  M_SQRT1_2 },
82     {0,0}
83 };
84 
MathCache()85 MathCache::MathCache() {
86     memset(table, 0, sizeof(table));
87 
88     /* See comments in lookup(). */
89     MOZ_ASSERT(IsNegativeZero(-0.0));
90     MOZ_ASSERT(!IsNegativeZero(+0.0));
91     MOZ_ASSERT(hash(-0.0, MathCache::Sin) != hash(+0.0, MathCache::Sin));
92 }
93 
94 size_t
sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf)95 MathCache::sizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf)
96 {
97     return mallocSizeOf(this);
98 }
99 
100 const Class js::MathClass = {
101     js_Math_str,
102     JSCLASS_HAS_CACHED_PROTO(JSProto_Math)
103 };
104 
105 bool
math_abs_handle(JSContext * cx,js::HandleValue v,js::MutableHandleValue r)106 js::math_abs_handle(JSContext* cx, js::HandleValue v, js::MutableHandleValue r)
107 {
108     double x;
109     if (!ToNumber(cx, v, &x))
110         return false;
111 
112     double z = Abs(x);
113     r.setNumber(z);
114 
115     return true;
116 }
117 
118 bool
math_abs(JSContext * cx,unsigned argc,Value * vp)119 js::math_abs(JSContext* cx, unsigned argc, Value* vp)
120 {
121     CallArgs args = CallArgsFromVp(argc, vp);
122 
123     if (args.length() == 0) {
124         args.rval().setNaN();
125         return true;
126     }
127 
128     return math_abs_handle(cx, args[0], args.rval());
129 }
130 
131 #if defined(SOLARIS) && defined(__GNUC__)
132 #define ACOS_IF_OUT_OF_RANGE(x) if (x < -1 || 1 < x) return GenericNaN();
133 #else
134 #define ACOS_IF_OUT_OF_RANGE(x)
135 #endif
136 
137 double
math_acos_impl(MathCache * cache,double x)138 js::math_acos_impl(MathCache* cache, double x)
139 {
140     ACOS_IF_OUT_OF_RANGE(x);
141     return cache->lookup(acos, x, MathCache::Acos);
142 }
143 
144 double
math_acos_uncached(double x)145 js::math_acos_uncached(double x)
146 {
147     ACOS_IF_OUT_OF_RANGE(x);
148     return acos(x);
149 }
150 
151 #undef ACOS_IF_OUT_OF_RANGE
152 
153 bool
math_acos(JSContext * cx,unsigned argc,Value * vp)154 js::math_acos(JSContext* cx, unsigned argc, Value* vp)
155 {
156     CallArgs args = CallArgsFromVp(argc, vp);
157 
158     if (args.length() == 0) {
159         args.rval().setNaN();
160         return true;
161     }
162 
163     double x;
164     if (!ToNumber(cx, args[0], &x))
165         return false;
166 
167     MathCache* mathCache = cx->runtime()->getMathCache(cx);
168     if (!mathCache)
169         return false;
170 
171     double z = math_acos_impl(mathCache, x);
172     args.rval().setDouble(z);
173     return true;
174 }
175 
176 #if defined(SOLARIS) && defined(__GNUC__)
177 #define ASIN_IF_OUT_OF_RANGE(x) if (x < -1 || 1 < x) return GenericNaN();
178 #else
179 #define ASIN_IF_OUT_OF_RANGE(x)
180 #endif
181 
182 double
math_asin_impl(MathCache * cache,double x)183 js::math_asin_impl(MathCache* cache, double x)
184 {
185     ASIN_IF_OUT_OF_RANGE(x);
186     return cache->lookup(asin, x, MathCache::Asin);
187 }
188 
189 double
math_asin_uncached(double x)190 js::math_asin_uncached(double x)
191 {
192     ASIN_IF_OUT_OF_RANGE(x);
193     return asin(x);
194 }
195 
196 #undef ASIN_IF_OUT_OF_RANGE
197 
198 bool
math_asin(JSContext * cx,unsigned argc,Value * vp)199 js::math_asin(JSContext* cx, unsigned argc, Value* vp)
200 {
201     CallArgs args = CallArgsFromVp(argc, vp);
202 
203     if (args.length() == 0) {
204         args.rval().setNaN();
205         return true;
206     }
207 
208     double x;
209     if (!ToNumber(cx, args[0], &x))
210         return false;
211 
212     MathCache* mathCache = cx->runtime()->getMathCache(cx);
213     if (!mathCache)
214         return false;
215 
216     double z = math_asin_impl(mathCache, x);
217     args.rval().setDouble(z);
218     return true;
219 }
220 
221 double
math_atan_impl(MathCache * cache,double x)222 js::math_atan_impl(MathCache* cache, double x)
223 {
224     return cache->lookup(atan, x, MathCache::Atan);
225 }
226 
227 double
math_atan_uncached(double x)228 js::math_atan_uncached(double x)
229 {
230     return atan(x);
231 }
232 
233 bool
math_atan(JSContext * cx,unsigned argc,Value * vp)234 js::math_atan(JSContext* cx, unsigned argc, Value* vp)
235 {
236     CallArgs args = CallArgsFromVp(argc, vp);
237 
238     if (args.length() == 0) {
239         args.rval().setNaN();
240         return true;
241     }
242 
243     double x;
244     if (!ToNumber(cx, args[0], &x))
245         return false;
246 
247     MathCache* mathCache = cx->runtime()->getMathCache(cx);
248     if (!mathCache)
249         return false;
250 
251     double z = math_atan_impl(mathCache, x);
252     args.rval().setDouble(z);
253     return true;
254 }
255 
256 double
ecmaAtan2(double y,double x)257 js::ecmaAtan2(double y, double x)
258 {
259 #if defined(_MSC_VER)
260     /*
261      * MSVC's atan2 does not yield the result demanded by ECMA when both x
262      * and y are infinite.
263      * - The result is a multiple of pi/4.
264      * - The sign of y determines the sign of the result.
265      * - The sign of x determines the multiplicator, 1 or 3.
266      */
267     if (IsInfinite(y) && IsInfinite(x)) {
268         double z = js_copysign(M_PI / 4, y);
269         if (x < 0)
270             z *= 3;
271         return z;
272     }
273 #endif
274 
275 #if defined(SOLARIS) && defined(__GNUC__)
276     if (y == 0) {
277         if (IsNegativeZero(x))
278             return js_copysign(M_PI, y);
279         if (x == 0)
280             return y;
281     }
282 #endif
283     return atan2(y, x);
284 }
285 
286 bool
math_atan2_handle(JSContext * cx,HandleValue y,HandleValue x,MutableHandleValue res)287 js::math_atan2_handle(JSContext* cx, HandleValue y, HandleValue x, MutableHandleValue res)
288 {
289     double dy;
290     if (!ToNumber(cx, y, &dy))
291         return false;
292 
293     double dx;
294     if (!ToNumber(cx, x, &dx))
295         return false;
296 
297     double z = ecmaAtan2(dy, dx);
298     res.setDouble(z);
299     return true;
300 }
301 
302 bool
math_atan2(JSContext * cx,unsigned argc,Value * vp)303 js::math_atan2(JSContext* cx, unsigned argc, Value* vp)
304 {
305     CallArgs args = CallArgsFromVp(argc, vp);
306 
307     return math_atan2_handle(cx, args.get(0), args.get(1), args.rval());
308 }
309 
310 double
math_ceil_impl(double x)311 js::math_ceil_impl(double x)
312 {
313 #ifdef __APPLE__
314     if (x < 0 && x > -1.0)
315         return js_copysign(0, -1);
316 #endif
317     return ceil(x);
318 }
319 
320 bool
math_ceil_handle(JSContext * cx,HandleValue v,MutableHandleValue res)321 js::math_ceil_handle(JSContext* cx, HandleValue v, MutableHandleValue res)
322 {
323     double d;
324     if(!ToNumber(cx, v, &d))
325         return false;
326 
327     double result = math_ceil_impl(d);
328     res.setNumber(result);
329     return true;
330 }
331 
332 bool
math_ceil(JSContext * cx,unsigned argc,Value * vp)333 js::math_ceil(JSContext* cx, unsigned argc, Value* vp)
334 {
335     CallArgs args = CallArgsFromVp(argc, vp);
336 
337     if (args.length() == 0) {
338         args.rval().setNaN();
339         return true;
340     }
341 
342     return math_ceil_handle(cx, args[0], args.rval());
343 }
344 
345 bool
math_clz32(JSContext * cx,unsigned argc,Value * vp)346 js::math_clz32(JSContext* cx, unsigned argc, Value* vp)
347 {
348     CallArgs args = CallArgsFromVp(argc, vp);
349 
350     if (args.length() == 0) {
351         args.rval().setInt32(32);
352         return true;
353     }
354 
355     uint32_t n;
356     if (!ToUint32(cx, args[0], &n))
357         return false;
358 
359     if (n == 0) {
360         args.rval().setInt32(32);
361         return true;
362     }
363 
364     args.rval().setInt32(mozilla::CountLeadingZeroes32(n));
365     return true;
366 }
367 
368 double
math_cos_impl(MathCache * cache,double x)369 js::math_cos_impl(MathCache* cache, double x)
370 {
371     return cache->lookup(cos, x, MathCache::Cos);
372 }
373 
374 double
math_cos_uncached(double x)375 js::math_cos_uncached(double x)
376 {
377     return cos(x);
378 }
379 
380 bool
math_cos(JSContext * cx,unsigned argc,Value * vp)381 js::math_cos(JSContext* cx, unsigned argc, Value* vp)
382 {
383     CallArgs args = CallArgsFromVp(argc, vp);
384 
385     if (args.length() == 0) {
386         args.rval().setNaN();
387         return true;
388     }
389 
390     double x;
391     if (!ToNumber(cx, args[0], &x))
392         return false;
393 
394     MathCache* mathCache = cx->runtime()->getMathCache(cx);
395     if (!mathCache)
396         return false;
397 
398     double z = math_cos_impl(mathCache, x);
399     args.rval().setDouble(z);
400     return true;
401 }
402 
403 #ifdef _WIN32
404 #define EXP_IF_OUT_OF_RANGE(x)                  \
405     if (!IsNaN(x)) {                            \
406         if (x == PositiveInfinity<double>())    \
407             return PositiveInfinity<double>();  \
408         if (x == NegativeInfinity<double>())    \
409             return 0.0;                         \
410     }
411 #else
412 #define EXP_IF_OUT_OF_RANGE(x)
413 #endif
414 
415 double
math_exp_impl(MathCache * cache,double x)416 js::math_exp_impl(MathCache* cache, double x)
417 {
418     EXP_IF_OUT_OF_RANGE(x);
419     return cache->lookup(exp, x, MathCache::Exp);
420 }
421 
422 double
math_exp_uncached(double x)423 js::math_exp_uncached(double x)
424 {
425     EXP_IF_OUT_OF_RANGE(x);
426     return exp(x);
427 }
428 
429 #undef EXP_IF_OUT_OF_RANGE
430 
431 bool
math_exp(JSContext * cx,unsigned argc,Value * vp)432 js::math_exp(JSContext* cx, unsigned argc, Value* vp)
433 {
434     CallArgs args = CallArgsFromVp(argc, vp);
435 
436     if (args.length() == 0) {
437         args.rval().setNaN();
438         return true;
439     }
440 
441     double x;
442     if (!ToNumber(cx, args[0], &x))
443         return false;
444 
445     MathCache* mathCache = cx->runtime()->getMathCache(cx);
446     if (!mathCache)
447         return false;
448 
449     double z = math_exp_impl(mathCache, x);
450     args.rval().setNumber(z);
451     return true;
452 }
453 
454 double
math_floor_impl(double x)455 js::math_floor_impl(double x)
456 {
457     return floor(x);
458 }
459 
460 bool
math_floor_handle(JSContext * cx,HandleValue v,MutableHandleValue r)461 js::math_floor_handle(JSContext* cx, HandleValue v, MutableHandleValue r)
462 {
463     double d;
464     if (!ToNumber(cx, v, &d))
465         return false;
466 
467     double z = math_floor_impl(d);
468     r.setNumber(z);
469 
470     return true;
471 }
472 
473 bool
math_floor(JSContext * cx,unsigned argc,Value * vp)474 js::math_floor(JSContext* cx, unsigned argc, Value* vp)
475 {
476     CallArgs args = CallArgsFromVp(argc, vp);
477 
478     if (args.length() == 0) {
479         args.rval().setNaN();
480         return true;
481     }
482 
483     return math_floor_handle(cx, args[0], args.rval());
484 }
485 
486 bool
math_imul_handle(JSContext * cx,HandleValue lhs,HandleValue rhs,MutableHandleValue res)487 js::math_imul_handle(JSContext* cx, HandleValue lhs, HandleValue rhs, MutableHandleValue res)
488 {
489     uint32_t a = 0, b = 0;
490     if (!lhs.isUndefined() && !ToUint32(cx, lhs, &a))
491         return false;
492     if (!rhs.isUndefined() && !ToUint32(cx, rhs, &b))
493         return false;
494 
495     uint32_t product = a * b;
496     res.setInt32(product > INT32_MAX
497                  ? int32_t(INT32_MIN + (product - INT32_MAX - 1))
498                  : int32_t(product));
499     return true;
500 }
501 
502 bool
math_imul(JSContext * cx,unsigned argc,Value * vp)503 js::math_imul(JSContext* cx, unsigned argc, Value* vp)
504 {
505     CallArgs args = CallArgsFromVp(argc, vp);
506 
507     return math_imul_handle(cx, args.get(0), args.get(1), args.rval());
508 }
509 
510 // Implements Math.fround (20.2.2.16) up to step 3
511 bool
RoundFloat32(JSContext * cx,HandleValue v,float * out)512 js::RoundFloat32(JSContext* cx, HandleValue v, float* out)
513 {
514     double d;
515     bool success = ToNumber(cx, v, &d);
516     *out = static_cast<float>(d);
517     return success;
518 }
519 
520 bool
RoundFloat32(JSContext * cx,HandleValue arg,MutableHandleValue res)521 js::RoundFloat32(JSContext* cx, HandleValue arg, MutableHandleValue res)
522 {
523     float f;
524     if (!RoundFloat32(cx, arg, &f))
525         return false;
526 
527     res.setDouble(static_cast<double>(f));
528     return true;
529 }
530 
531 bool
math_fround(JSContext * cx,unsigned argc,Value * vp)532 js::math_fround(JSContext* cx, unsigned argc, Value* vp)
533 {
534     CallArgs args = CallArgsFromVp(argc, vp);
535 
536     if (args.length() == 0) {
537         args.rval().setNaN();
538         return true;
539     }
540 
541     return RoundFloat32(cx, args[0], args.rval());
542 }
543 
544 #if defined(SOLARIS) && defined(__GNUC__)
545 #define LOG_IF_OUT_OF_RANGE(x) if (x < 0) return GenericNaN();
546 #else
547 #define LOG_IF_OUT_OF_RANGE(x)
548 #endif
549 
550 double
math_log_impl(MathCache * cache,double x)551 js::math_log_impl(MathCache* cache, double x)
552 {
553     LOG_IF_OUT_OF_RANGE(x);
554     return cache->lookup(math_log_uncached, x, MathCache::Log);
555 }
556 
557 double
math_log_uncached(double x)558 js::math_log_uncached(double x)
559 {
560     LOG_IF_OUT_OF_RANGE(x);
561     return log(x);
562 }
563 
564 #undef LOG_IF_OUT_OF_RANGE
565 
566 bool
math_log_handle(JSContext * cx,HandleValue val,MutableHandleValue res)567 js::math_log_handle(JSContext* cx, HandleValue val, MutableHandleValue res)
568 {
569     double in;
570     if (!ToNumber(cx, val, &in))
571         return false;
572 
573     MathCache* mathCache = cx->runtime()->getMathCache(cx);
574     if (!mathCache)
575         return false;
576 
577     double out = math_log_impl(mathCache, in);
578     res.setNumber(out);
579     return true;
580 }
581 
582 bool
math_log(JSContext * cx,unsigned argc,Value * vp)583 js::math_log(JSContext* cx, unsigned argc, Value* vp)
584 {
585     CallArgs args = CallArgsFromVp(argc, vp);
586 
587     if (args.length() == 0) {
588         args.rval().setNaN();
589         return true;
590     }
591 
592     return math_log_handle(cx, args[0], args.rval());
593 }
594 
595 double
math_max_impl(double x,double y)596 js::math_max_impl(double x, double y)
597 {
598     // Math.max(num, NaN) => NaN, Math.max(-0, +0) => +0
599     if (x > y || IsNaN(x) || (x == y && IsNegative(y)))
600         return x;
601     return y;
602 }
603 
604 bool
math_max(JSContext * cx,unsigned argc,Value * vp)605 js::math_max(JSContext* cx, unsigned argc, Value* vp)
606 {
607     CallArgs args = CallArgsFromVp(argc, vp);
608 
609     double maxval = NegativeInfinity<double>();
610     for (unsigned i = 0; i < args.length(); i++) {
611         double x;
612         if (!ToNumber(cx, args[i], &x))
613             return false;
614         maxval = math_max_impl(x, maxval);
615     }
616     args.rval().setNumber(maxval);
617     return true;
618 }
619 
620 double
math_min_impl(double x,double y)621 js::math_min_impl(double x, double y)
622 {
623     // Math.min(num, NaN) => NaN, Math.min(-0, +0) => -0
624     if (x < y || IsNaN(x) || (x == y && IsNegativeZero(x)))
625         return x;
626     return y;
627 }
628 
629 bool
math_min(JSContext * cx,unsigned argc,Value * vp)630 js::math_min(JSContext* cx, unsigned argc, Value* vp)
631 {
632     CallArgs args = CallArgsFromVp(argc, vp);
633 
634     double minval = PositiveInfinity<double>();
635     for (unsigned i = 0; i < args.length(); i++) {
636         double x;
637         if (!ToNumber(cx, args[i], &x))
638             return false;
639         minval = math_min_impl(x, minval);
640     }
641     args.rval().setNumber(minval);
642     return true;
643 }
644 
645 bool
minmax_impl(JSContext * cx,bool max,HandleValue a,HandleValue b,MutableHandleValue res)646 js::minmax_impl(JSContext* cx, bool max, HandleValue a, HandleValue b, MutableHandleValue res)
647 {
648     double x, y;
649 
650     if (!ToNumber(cx, a, &x))
651         return false;
652     if (!ToNumber(cx, b, &y))
653         return false;
654 
655     if (max)
656         res.setNumber(math_max_impl(x, y));
657     else
658         res.setNumber(math_min_impl(x, y));
659 
660     return true;
661 }
662 
663 double
powi(double x,int y)664 js::powi(double x, int y)
665 {
666     unsigned n = (y < 0) ? -y : y;
667     double m = x;
668     double p = 1;
669     while (true) {
670         if ((n & 1) != 0) p *= m;
671         n >>= 1;
672         if (n == 0) {
673             if (y < 0) {
674                 // Unfortunately, we have to be careful when p has reached
675                 // infinity in the computation, because sometimes the higher
676                 // internal precision in the pow() implementation would have
677                 // given us a finite p. This happens very rarely.
678 
679                 double result = 1.0 / p;
680                 return (result == 0 && IsInfinite(p))
681                        ? pow(x, static_cast<double>(y))  // Avoid pow(double, int).
682                        : result;
683             }
684 
685             return p;
686         }
687         m *= m;
688     }
689 }
690 
691 double
ecmaPow(double x,double y)692 js::ecmaPow(double x, double y)
693 {
694     /*
695      * Use powi if the exponent is an integer-valued double. We don't have to
696      * check for NaN since a comparison with NaN is always false.
697      */
698     int32_t yi;
699     if (NumberEqualsInt32(y, &yi))
700         return powi(x, yi);
701 
702     /*
703      * Because C99 and ECMA specify different behavior for pow(),
704      * we need to wrap the libm call to make it ECMA compliant.
705      */
706     if (!IsFinite(y) && (x == 1.0 || x == -1.0))
707         return GenericNaN();
708 
709     /* pow(x, +-0) is always 1, even for x = NaN (MSVC gets this wrong). */
710     if (y == 0)
711         return 1;
712 
713     /*
714      * Special case for square roots. Note that pow(x, 0.5) != sqrt(x)
715      * when x = -0.0, so we have to guard for this.
716      */
717     if (IsFinite(x) && x != 0.0) {
718         if (y == 0.5)
719             return sqrt(x);
720         if (y == -0.5)
721             return 1.0 / sqrt(x);
722     }
723     return pow(x, y);
724 }
725 
726 bool
math_pow_handle(JSContext * cx,HandleValue base,HandleValue power,MutableHandleValue result)727 js::math_pow_handle(JSContext* cx, HandleValue base, HandleValue power, MutableHandleValue result)
728 {
729     double x;
730     if (!ToNumber(cx, base, &x))
731         return false;
732 
733     double y;
734     if (!ToNumber(cx, power, &y))
735         return false;
736 
737     double z = ecmaPow(x, y);
738     result.setNumber(z);
739     return true;
740 }
741 
742 bool
math_pow(JSContext * cx,unsigned argc,Value * vp)743 js::math_pow(JSContext* cx, unsigned argc, Value* vp)
744 {
745     CallArgs args = CallArgsFromVp(argc, vp);
746 
747     return math_pow_handle(cx, args.get(0), args.get(1), args.rval());
748 }
749 
750 uint64_t
GenerateRandomSeed()751 js::GenerateRandomSeed()
752 {
753     uint64_t seed = 0;
754 
755 #if defined(XP_WIN)
756     MOZ_ALWAYS_TRUE(RtlGenRandom(&seed, sizeof(seed)));
757 #elif defined(HAVE_ARC4RANDOM)
758     seed = (static_cast<uint64_t>(arc4random()) << 32) | arc4random();
759 #elif defined(XP_UNIX)
760     int fd = open("/dev/urandom", O_RDONLY);
761     if (fd >= 0) {
762         read(fd, static_cast<void*>(&seed), sizeof(seed));
763         close(fd);
764     }
765 #else
766 # error "Platform needs to implement GenerateRandomSeed()"
767 #endif
768 
769     // Also mix in PRMJ_Now() in case we couldn't read random bits from the OS.
770     return seed ^ PRMJ_Now();
771 }
772 
773 void
GenerateXorShift128PlusSeed(mozilla::Array<uint64_t,2> & seed)774 js::GenerateXorShift128PlusSeed(mozilla::Array<uint64_t, 2>& seed)
775 {
776     // XorShift128PlusRNG must be initialized with a non-zero seed.
777     do {
778         seed[0] = GenerateRandomSeed();
779         seed[1] = GenerateRandomSeed();
780     } while (seed[0] == 0 && seed[1] == 0);
781 }
782 
783 void
ensureRandomNumberGenerator()784 JSCompartment::ensureRandomNumberGenerator()
785 {
786     if (randomNumberGenerator.isNothing()) {
787         mozilla::Array<uint64_t, 2> seed;
788         GenerateXorShift128PlusSeed(seed);
789         randomNumberGenerator.emplace(seed[0], seed[1]);
790     }
791 }
792 
793 bool
math_random(JSContext * cx,unsigned argc,Value * vp)794 js::math_random(JSContext* cx, unsigned argc, Value* vp)
795 {
796     CallArgs args = CallArgsFromVp(argc, vp);
797 
798     JSCompartment* comp = cx->compartment();
799     comp->ensureRandomNumberGenerator();
800 
801     double z = comp->randomNumberGenerator.ref().nextDouble();
802     args.rval().setDouble(z);
803     return true;
804 }
805 
806 bool
math_round_handle(JSContext * cx,HandleValue arg,MutableHandleValue res)807 js::math_round_handle(JSContext* cx, HandleValue arg, MutableHandleValue res)
808 {
809     double d;
810     if (!ToNumber(cx, arg, &d))
811         return false;
812 
813     d = math_round_impl(d);
814     res.setNumber(d);
815     return true;
816 }
817 
818 template<typename T>
819 T
GetBiggestNumberLessThan(T x)820 js::GetBiggestNumberLessThan(T x)
821 {
822     MOZ_ASSERT(!IsNegative(x));
823     MOZ_ASSERT(IsFinite(x));
824     typedef typename mozilla::FloatingPoint<T>::Bits Bits;
825     Bits bits = mozilla::BitwiseCast<Bits>(x);
826     MOZ_ASSERT(bits > 0, "will underflow");
827     return mozilla::BitwiseCast<T>(bits - 1);
828 }
829 
830 template double js::GetBiggestNumberLessThan<>(double x);
831 template float js::GetBiggestNumberLessThan<>(float x);
832 
833 double
math_round_impl(double x)834 js::math_round_impl(double x)
835 {
836     int32_t ignored;
837     if (NumberIsInt32(x, &ignored))
838         return x;
839 
840     /* Some numbers are so big that adding 0.5 would give the wrong number. */
841     if (ExponentComponent(x) >= int_fast16_t(FloatingPoint<double>::kExponentShift))
842         return x;
843 
844     double add = (x >= 0) ? GetBiggestNumberLessThan(0.5) : 0.5;
845     return js_copysign(floor(x + add), x);
846 }
847 
848 float
math_roundf_impl(float x)849 js::math_roundf_impl(float x)
850 {
851     int32_t ignored;
852     if (NumberIsInt32(x, &ignored))
853         return x;
854 
855     /* Some numbers are so big that adding 0.5 would give the wrong number. */
856     if (ExponentComponent(x) >= int_fast16_t(FloatingPoint<float>::kExponentShift))
857         return x;
858 
859     float add = (x >= 0) ? GetBiggestNumberLessThan(0.5f) : 0.5f;
860     return js_copysign(floorf(x + add), x);
861 }
862 
863 bool /* ES5 15.8.2.15. */
math_round(JSContext * cx,unsigned argc,Value * vp)864 js::math_round(JSContext* cx, unsigned argc, Value* vp)
865 {
866     CallArgs args = CallArgsFromVp(argc, vp);
867 
868     if (args.length() == 0) {
869         args.rval().setNaN();
870         return true;
871     }
872 
873     return math_round_handle(cx, args[0], args.rval());
874 }
875 
876 double
math_sin_impl(MathCache * cache,double x)877 js::math_sin_impl(MathCache* cache, double x)
878 {
879     return cache->lookup(math_sin_uncached, x, MathCache::Sin);
880 }
881 
882 double
math_sin_uncached(double x)883 js::math_sin_uncached(double x)
884 {
885 #ifdef _WIN64
886     // Workaround MSVC bug where sin(-0) is +0 instead of -0 on x64 on
887     // CPUs without FMA3 (pre-Haswell). See bug 1076670.
888     if (IsNegativeZero(x))
889         return -0.0;
890 #endif
891     return sin(x);
892 }
893 
894 bool
math_sin_handle(JSContext * cx,HandleValue val,MutableHandleValue res)895 js::math_sin_handle(JSContext* cx, HandleValue val, MutableHandleValue res)
896 {
897     double in;
898     if (!ToNumber(cx, val, &in))
899         return false;
900 
901     MathCache* mathCache = cx->runtime()->getMathCache(cx);
902     if (!mathCache)
903         return false;
904 
905     double out = math_sin_impl(mathCache, in);
906     res.setDouble(out);
907     return true;
908 }
909 
910 bool
math_sin(JSContext * cx,unsigned argc,Value * vp)911 js::math_sin(JSContext* cx, unsigned argc, Value* vp)
912 {
913     CallArgs args = CallArgsFromVp(argc, vp);
914 
915     if (args.length() == 0) {
916         args.rval().setNaN();
917         return true;
918     }
919 
920     return math_sin_handle(cx, args[0], args.rval());
921 }
922 
923 void
math_sincos_uncached(double x,double * sin,double * cos)924 js::math_sincos_uncached(double x, double *sin, double *cos)
925 {
926 #if defined(__GLIBC__)
927     sincos(x, sin, cos);
928 #elif defined(HAVE_SINCOS)
929     __sincos(x, sin, cos);
930 #else
931     *sin = js::math_sin_uncached(x);
932     *cos = js::math_cos_uncached(x);
933 #endif
934 }
935 
936 void
math_sincos_impl(MathCache * mathCache,double x,double * sin,double * cos)937 js::math_sincos_impl(MathCache* mathCache, double x, double *sin, double *cos)
938 {
939     unsigned indexSin;
940     unsigned indexCos;
941     bool hasSin = mathCache->isCached(x, MathCache::Sin, sin, &indexSin);
942     bool hasCos = mathCache->isCached(x, MathCache::Cos, cos, &indexCos);
943     if (!(hasSin || hasCos)) {
944         js::math_sincos_uncached(x, sin, cos);
945         mathCache->store(MathCache::Sin, x, *sin, indexSin);
946         mathCache->store(MathCache::Cos, x, *cos, indexCos);
947         return;
948     }
949 
950     if (!hasSin)
951         *sin = js::math_sin_impl(mathCache, x);
952 
953     if (!hasCos)
954         *cos = js::math_cos_impl(mathCache, x);
955 }
956 
957 bool
math_sqrt_handle(JSContext * cx,HandleValue number,MutableHandleValue result)958 js::math_sqrt_handle(JSContext* cx, HandleValue number, MutableHandleValue result)
959 {
960     double x;
961     if (!ToNumber(cx, number, &x))
962         return false;
963 
964     MathCache* mathCache = cx->runtime()->getMathCache(cx);
965     if (!mathCache)
966         return false;
967 
968     double z = mathCache->lookup(sqrt, x, MathCache::Sqrt);
969     result.setDouble(z);
970     return true;
971 }
972 
973 bool
math_sqrt(JSContext * cx,unsigned argc,Value * vp)974 js::math_sqrt(JSContext* cx, unsigned argc, Value* vp)
975 {
976     CallArgs args = CallArgsFromVp(argc, vp);
977 
978     if (args.length() == 0) {
979         args.rval().setNaN();
980         return true;
981     }
982 
983     return math_sqrt_handle(cx, args[0], args.rval());
984 }
985 
986 double
math_tan_impl(MathCache * cache,double x)987 js::math_tan_impl(MathCache* cache, double x)
988 {
989     return cache->lookup(tan, x, MathCache::Tan);
990 }
991 
992 double
math_tan_uncached(double x)993 js::math_tan_uncached(double x)
994 {
995     return tan(x);
996 }
997 
998 bool
math_tan(JSContext * cx,unsigned argc,Value * vp)999 js::math_tan(JSContext* cx, unsigned argc, Value* vp)
1000 {
1001     CallArgs args = CallArgsFromVp(argc, vp);
1002 
1003     if (args.length() == 0) {
1004         args.rval().setNaN();
1005         return true;
1006     }
1007 
1008     double x;
1009     if (!ToNumber(cx, args[0], &x))
1010         return false;
1011 
1012     MathCache* mathCache = cx->runtime()->getMathCache(cx);
1013     if (!mathCache)
1014         return false;
1015 
1016     double z = math_tan_impl(mathCache, x);
1017     args.rval().setDouble(z);
1018     return true;
1019 }
1020 
1021 typedef double (*UnaryMathFunctionType)(MathCache* cache, double);
1022 
1023 template <UnaryMathFunctionType F>
math_function(JSContext * cx,unsigned argc,Value * vp)1024 static bool math_function(JSContext* cx, unsigned argc, Value* vp)
1025 {
1026     CallArgs args = CallArgsFromVp(argc, vp);
1027     if (args.length() == 0) {
1028         args.rval().setNumber(GenericNaN());
1029         return true;
1030     }
1031 
1032     double x;
1033     if (!ToNumber(cx, args[0], &x))
1034         return false;
1035 
1036     MathCache* mathCache = cx->runtime()->getMathCache(cx);
1037     if (!mathCache)
1038         return false;
1039     double z = F(mathCache, x);
1040     args.rval().setNumber(z);
1041 
1042     return true;
1043 }
1044 
1045 double
math_log10_impl(MathCache * cache,double x)1046 js::math_log10_impl(MathCache* cache, double x)
1047 {
1048     return cache->lookup(log10, x, MathCache::Log10);
1049 }
1050 
1051 double
math_log10_uncached(double x)1052 js::math_log10_uncached(double x)
1053 {
1054     return log10(x);
1055 }
1056 
1057 bool
math_log10(JSContext * cx,unsigned argc,Value * vp)1058 js::math_log10(JSContext* cx, unsigned argc, Value* vp)
1059 {
1060     return math_function<math_log10_impl>(cx, argc, vp);
1061 }
1062 
1063 #if !HAVE_LOG2
log2(double x)1064 double log2(double x)
1065 {
1066     return log(x) / M_LN2;
1067 }
1068 #endif
1069 
1070 double
math_log2_impl(MathCache * cache,double x)1071 js::math_log2_impl(MathCache* cache, double x)
1072 {
1073     return cache->lookup(log2, x, MathCache::Log2);
1074 }
1075 
1076 double
math_log2_uncached(double x)1077 js::math_log2_uncached(double x)
1078 {
1079     return log2(x);
1080 }
1081 
1082 bool
math_log2(JSContext * cx,unsigned argc,Value * vp)1083 js::math_log2(JSContext* cx, unsigned argc, Value* vp)
1084 {
1085     return math_function<math_log2_impl>(cx, argc, vp);
1086 }
1087 
1088 #if !HAVE_LOG1P
log1p(double x)1089 double log1p(double x)
1090 {
1091     if (fabs(x) < 1e-4) {
1092         /*
1093          * Use Taylor approx. log(1 + x) = x - x^2 / 2 + x^3 / 3 - x^4 / 4 with error x^5 / 5
1094          * Since |x| < 10^-4, |x|^5 < 10^-20, relative error less than 10^-16
1095          */
1096         double z = -(x * x * x * x) / 4 + (x * x * x) / 3 - (x * x) / 2 + x;
1097         return z;
1098     } else {
1099         /* For other large enough values of x use direct computation */
1100         return log(1.0 + x);
1101     }
1102 }
1103 #endif
1104 
1105 #ifdef __APPLE__
1106 // Ensure that log1p(-0) is -0.
1107 #define LOG1P_IF_OUT_OF_RANGE(x) if (x == 0) return x;
1108 #else
1109 #define LOG1P_IF_OUT_OF_RANGE(x)
1110 #endif
1111 
1112 double
math_log1p_impl(MathCache * cache,double x)1113 js::math_log1p_impl(MathCache* cache, double x)
1114 {
1115     LOG1P_IF_OUT_OF_RANGE(x);
1116     return cache->lookup(log1p, x, MathCache::Log1p);
1117 }
1118 
1119 double
math_log1p_uncached(double x)1120 js::math_log1p_uncached(double x)
1121 {
1122     LOG1P_IF_OUT_OF_RANGE(x);
1123     return log1p(x);
1124 }
1125 
1126 #undef LOG1P_IF_OUT_OF_RANGE
1127 
1128 bool
math_log1p(JSContext * cx,unsigned argc,Value * vp)1129 js::math_log1p(JSContext* cx, unsigned argc, Value* vp)
1130 {
1131     return math_function<math_log1p_impl>(cx, argc, vp);
1132 }
1133 
1134 #if !HAVE_EXPM1
expm1(double x)1135 double expm1(double x)
1136 {
1137     /* Special handling for -0 */
1138     if (x == 0.0)
1139         return x;
1140 
1141     if (fabs(x) < 1e-5) {
1142         /*
1143          * Use Taylor approx. exp(x) - 1 = x + x^2 / 2 + x^3 / 6 with error x^4 / 24
1144          * Since |x| < 10^-5, |x|^4 < 10^-20, relative error less than 10^-15
1145          */
1146         double z = (x * x * x) / 6 + (x * x) / 2 + x;
1147         return z;
1148     } else {
1149         /* For other large enough values of x use direct computation */
1150         return exp(x) - 1.0;
1151     }
1152 }
1153 #endif
1154 
1155 double
math_expm1_impl(MathCache * cache,double x)1156 js::math_expm1_impl(MathCache* cache, double x)
1157 {
1158     return cache->lookup(expm1, x, MathCache::Expm1);
1159 }
1160 
1161 double
math_expm1_uncached(double x)1162 js::math_expm1_uncached(double x)
1163 {
1164     return expm1(x);
1165 }
1166 
1167 bool
math_expm1(JSContext * cx,unsigned argc,Value * vp)1168 js::math_expm1(JSContext* cx, unsigned argc, Value* vp)
1169 {
1170     return math_function<math_expm1_impl>(cx, argc, vp);
1171 }
1172 
1173 #if !HAVE_SQRT1PM1
1174 /* This algorithm computes sqrt(1+x)-1 for small x */
sqrt1pm1(double x)1175 double sqrt1pm1(double x)
1176 {
1177     if (fabs(x) > 0.75)
1178         return sqrt(1 + x) - 1;
1179 
1180     return expm1(log1p(x) / 2);
1181 }
1182 #endif
1183 
1184 double
math_cosh_impl(MathCache * cache,double x)1185 js::math_cosh_impl(MathCache* cache, double x)
1186 {
1187     return cache->lookup(cosh, x, MathCache::Cosh);
1188 }
1189 
1190 double
math_cosh_uncached(double x)1191 js::math_cosh_uncached(double x)
1192 {
1193     return cosh(x);
1194 }
1195 
1196 bool
math_cosh(JSContext * cx,unsigned argc,Value * vp)1197 js::math_cosh(JSContext* cx, unsigned argc, Value* vp)
1198 {
1199     return math_function<math_cosh_impl>(cx, argc, vp);
1200 }
1201 
1202 double
math_sinh_impl(MathCache * cache,double x)1203 js::math_sinh_impl(MathCache* cache, double x)
1204 {
1205     return cache->lookup(sinh, x, MathCache::Sinh);
1206 }
1207 
1208 double
math_sinh_uncached(double x)1209 js::math_sinh_uncached(double x)
1210 {
1211     return sinh(x);
1212 }
1213 
1214 bool
math_sinh(JSContext * cx,unsigned argc,Value * vp)1215 js::math_sinh(JSContext* cx, unsigned argc, Value* vp)
1216 {
1217     return math_function<math_sinh_impl>(cx, argc, vp);
1218 }
1219 
1220 double
math_tanh_impl(MathCache * cache,double x)1221 js::math_tanh_impl(MathCache* cache, double x)
1222 {
1223     return cache->lookup(tanh, x, MathCache::Tanh);
1224 }
1225 
1226 double
math_tanh_uncached(double x)1227 js::math_tanh_uncached(double x)
1228 {
1229     return tanh(x);
1230 }
1231 
1232 bool
math_tanh(JSContext * cx,unsigned argc,Value * vp)1233 js::math_tanh(JSContext* cx, unsigned argc, Value* vp)
1234 {
1235     return math_function<math_tanh_impl>(cx, argc, vp);
1236 }
1237 
1238 #if !HAVE_ACOSH
acosh(double x)1239 double acosh(double x)
1240 {
1241     const double SQUARE_ROOT_EPSILON = sqrt(std::numeric_limits<double>::epsilon());
1242 
1243     if ((x - 1) >= SQUARE_ROOT_EPSILON) {
1244         if (x > 1 / SQUARE_ROOT_EPSILON) {
1245             /*
1246              * http://functions.wolfram.com/ElementaryFunctions/ArcCosh/06/01/06/01/0001/
1247              * approximation by laurent series in 1/x at 0+ order from -1 to 0
1248              */
1249             return log(x) + M_LN2;
1250         } else if (x < 1.5) {
1251             // This is just a rearrangement of the standard form below
1252             // devised to minimize loss of precision when x ~ 1:
1253             double y = x - 1;
1254             return log1p(y + sqrt(y * y + 2 * y));
1255         } else {
1256             // http://functions.wolfram.com/ElementaryFunctions/ArcCosh/02/
1257             return log(x + sqrt(x * x - 1));
1258         }
1259     } else {
1260         // see http://functions.wolfram.com/ElementaryFunctions/ArcCosh/06/01/04/01/0001/
1261         double y = x - 1;
1262         // approximation by taylor series in y at 0 up to order 2.
1263         // If x is less than 1, sqrt(2 * y) is NaN and the result is NaN.
1264         return sqrt(2 * y) * (1 - y / 12 + 3 * y * y / 160);
1265     }
1266 }
1267 #endif
1268 
1269 double
math_acosh_impl(MathCache * cache,double x)1270 js::math_acosh_impl(MathCache* cache, double x)
1271 {
1272     return cache->lookup(acosh, x, MathCache::Acosh);
1273 }
1274 
1275 double
math_acosh_uncached(double x)1276 js::math_acosh_uncached(double x)
1277 {
1278     return acosh(x);
1279 }
1280 
1281 bool
math_acosh(JSContext * cx,unsigned argc,Value * vp)1282 js::math_acosh(JSContext* cx, unsigned argc, Value* vp)
1283 {
1284     return math_function<math_acosh_impl>(cx, argc, vp);
1285 }
1286 
1287 #if !HAVE_ASINH
1288 // Bug 899712 - gcc incorrectly rewrites -asinh(-x) to asinh(x) when overriding
1289 // asinh.
my_asinh(double x)1290 static double my_asinh(double x)
1291 {
1292     const double SQUARE_ROOT_EPSILON = sqrt(std::numeric_limits<double>::epsilon());
1293     const double FOURTH_ROOT_EPSILON = sqrt(SQUARE_ROOT_EPSILON);
1294 
1295     if (x >= FOURTH_ROOT_EPSILON) {
1296         if (x > 1 / SQUARE_ROOT_EPSILON)
1297             // http://functions.wolfram.com/ElementaryFunctions/ArcSinh/06/01/06/01/0001/
1298             // approximation by laurent series in 1/x at 0+ order from -1 to 1
1299             return M_LN2 + log(x) + 1 / (4 * x * x);
1300         else if (x < 0.5)
1301             return log1p(x + sqrt1pm1(x * x));
1302         else
1303             return log(x + sqrt(x * x + 1));
1304     } else if (x <= -FOURTH_ROOT_EPSILON) {
1305         return -my_asinh(-x);
1306     } else {
1307         // http://functions.wolfram.com/ElementaryFunctions/ArcSinh/06/01/03/01/0001/
1308         // approximation by taylor series in x at 0 up to order 2
1309         double result = x;
1310 
1311         if (fabs(x) >= SQUARE_ROOT_EPSILON) {
1312             double x3 = x * x * x;
1313             // approximation by taylor series in x at 0 up to order 4
1314             result -= x3 / 6;
1315         }
1316 
1317         return result;
1318     }
1319 }
1320 #endif
1321 
1322 double
math_asinh_impl(MathCache * cache,double x)1323 js::math_asinh_impl(MathCache* cache, double x)
1324 {
1325 #ifdef HAVE_ASINH
1326     return cache->lookup(asinh, x, MathCache::Asinh);
1327 #else
1328     return cache->lookup(my_asinh, x, MathCache::Asinh);
1329 #endif
1330 }
1331 
1332 double
math_asinh_uncached(double x)1333 js::math_asinh_uncached(double x)
1334 {
1335 #ifdef HAVE_ASINH
1336     return asinh(x);
1337 #else
1338     return my_asinh(x);
1339 #endif
1340 }
1341 
1342 bool
math_asinh(JSContext * cx,unsigned argc,Value * vp)1343 js::math_asinh(JSContext* cx, unsigned argc, Value* vp)
1344 {
1345     return math_function<math_asinh_impl>(cx, argc, vp);
1346 }
1347 
1348 #if !HAVE_ATANH
atanh(double x)1349 double atanh(double x)
1350 {
1351     const double EPSILON = std::numeric_limits<double>::epsilon();
1352     const double SQUARE_ROOT_EPSILON = sqrt(EPSILON);
1353     const double FOURTH_ROOT_EPSILON = sqrt(SQUARE_ROOT_EPSILON);
1354 
1355     if (fabs(x) >= FOURTH_ROOT_EPSILON) {
1356         // http://functions.wolfram.com/ElementaryFunctions/ArcTanh/02/
1357         if (fabs(x) < 0.5)
1358             return (log1p(x) - log1p(-x)) / 2;
1359 
1360         return log((1 + x) / (1 - x)) / 2;
1361     } else {
1362         // http://functions.wolfram.com/ElementaryFunctions/ArcTanh/06/01/03/01/
1363         // approximation by taylor series in x at 0 up to order 2
1364         double result = x;
1365 
1366         if (fabs(x) >= SQUARE_ROOT_EPSILON) {
1367             double x3 = x * x * x;
1368             result += x3 / 3;
1369         }
1370 
1371         return result;
1372     }
1373 }
1374 #endif
1375 
1376 double
math_atanh_impl(MathCache * cache,double x)1377 js::math_atanh_impl(MathCache* cache, double x)
1378 {
1379     return cache->lookup(atanh, x, MathCache::Atanh);
1380 }
1381 
1382 double
math_atanh_uncached(double x)1383 js::math_atanh_uncached(double x)
1384 {
1385     return atanh(x);
1386 }
1387 
1388 bool
math_atanh(JSContext * cx,unsigned argc,Value * vp)1389 js::math_atanh(JSContext* cx, unsigned argc, Value* vp)
1390 {
1391     return math_function<math_atanh_impl>(cx, argc, vp);
1392 }
1393 
1394 /* Consistency wrapper for platform deviations in hypot() */
1395 double
ecmaHypot(double x,double y)1396 js::ecmaHypot(double x, double y)
1397 {
1398 #ifdef XP_WIN
1399     /*
1400      * Workaround MS hypot bug, where hypot(Infinity, NaN or Math.MIN_VALUE)
1401      * is NaN, not Infinity.
1402      */
1403     if (mozilla::IsInfinite(x) || mozilla::IsInfinite(y)) {
1404         return mozilla::PositiveInfinity<double>();
1405     }
1406 #endif
1407     return hypot(x, y);
1408 }
1409 
1410 static inline
1411 void
hypot_step(double & scale,double & sumsq,double x)1412 hypot_step(double& scale, double& sumsq, double x)
1413 {
1414     double xabs = mozilla::Abs(x);
1415     if (scale < xabs) {
1416         sumsq = 1 + sumsq * (scale / xabs) * (scale / xabs);
1417         scale = xabs;
1418     } else if (scale != 0) {
1419         sumsq += (xabs / scale) * (xabs / scale);
1420     }
1421 }
1422 
1423 double
hypot4(double x,double y,double z,double w)1424 js::hypot4(double x, double y, double z, double w)
1425 {
1426     /* Check for infinity or NaNs so that we can return immediatelly.
1427      * Does not need to be WIN_XP specific as ecmaHypot
1428      */
1429     if (mozilla::IsInfinite(x) || mozilla::IsInfinite(y) ||
1430             mozilla::IsInfinite(z) || mozilla::IsInfinite(w))
1431         return mozilla::PositiveInfinity<double>();
1432 
1433     if (mozilla::IsNaN(x) || mozilla::IsNaN(y) || mozilla::IsNaN(z) ||
1434             mozilla::IsNaN(w))
1435         return GenericNaN();
1436 
1437     double scale = 0;
1438     double sumsq = 1;
1439 
1440     hypot_step(scale, sumsq, x);
1441     hypot_step(scale, sumsq, y);
1442     hypot_step(scale, sumsq, z);
1443     hypot_step(scale, sumsq, w);
1444 
1445     return scale * sqrt(sumsq);
1446 }
1447 
1448 double
hypot3(double x,double y,double z)1449 js::hypot3(double x, double y, double z)
1450 {
1451     return hypot4(x, y, z, 0.0);
1452 }
1453 
1454 bool
math_hypot(JSContext * cx,unsigned argc,Value * vp)1455 js::math_hypot(JSContext* cx, unsigned argc, Value* vp)
1456 {
1457     CallArgs args = CallArgsFromVp(argc, vp);
1458     return math_hypot_handle(cx, args, args.rval());
1459 }
1460 
1461 bool
math_hypot_handle(JSContext * cx,HandleValueArray args,MutableHandleValue res)1462 js::math_hypot_handle(JSContext* cx, HandleValueArray args, MutableHandleValue res)
1463 {
1464     // IonMonkey calls the system hypot function directly if two arguments are
1465     // given. Do that here as well to get the same results.
1466     if (args.length() == 2) {
1467         double x, y;
1468         if (!ToNumber(cx, args[0], &x))
1469             return false;
1470         if (!ToNumber(cx, args[1], &y))
1471             return false;
1472 
1473         double result = ecmaHypot(x, y);
1474         res.setNumber(result);
1475         return true;
1476     }
1477 
1478     bool isInfinite = false;
1479     bool isNaN = false;
1480 
1481     double scale = 0;
1482     double sumsq = 1;
1483 
1484     for (unsigned i = 0; i < args.length(); i++) {
1485         double x;
1486         if (!ToNumber(cx, args[i], &x))
1487             return false;
1488 
1489         isInfinite |= mozilla::IsInfinite(x);
1490         isNaN |= mozilla::IsNaN(x);
1491         if (isInfinite || isNaN)
1492             continue;
1493 
1494         hypot_step(scale, sumsq, x);
1495     }
1496 
1497     double result = isInfinite ? PositiveInfinity<double>() :
1498                     isNaN ? GenericNaN() :
1499                     scale * sqrt(sumsq);
1500     res.setNumber(result);
1501     return true;
1502 }
1503 
1504 double
math_trunc_impl(MathCache * cache,double x)1505 js::math_trunc_impl(MathCache* cache, double x)
1506 {
1507     return cache->lookup(trunc, x, MathCache::Trunc);
1508 }
1509 
1510 double
math_trunc_uncached(double x)1511 js::math_trunc_uncached(double x)
1512 {
1513     return trunc(x);
1514 }
1515 
1516 bool
math_trunc(JSContext * cx,unsigned argc,Value * vp)1517 js::math_trunc(JSContext* cx, unsigned argc, Value* vp)
1518 {
1519     return math_function<math_trunc_impl>(cx, argc, vp);
1520 }
1521 
sign(double x)1522 static double sign(double x)
1523 {
1524     if (mozilla::IsNaN(x))
1525         return GenericNaN();
1526 
1527     return x == 0 ? x : x < 0 ? -1 : 1;
1528 }
1529 
1530 double
math_sign_impl(MathCache * cache,double x)1531 js::math_sign_impl(MathCache* cache, double x)
1532 {
1533     return cache->lookup(sign, x, MathCache::Sign);
1534 }
1535 
1536 double
math_sign_uncached(double x)1537 js::math_sign_uncached(double x)
1538 {
1539     return sign(x);
1540 }
1541 
1542 bool
math_sign(JSContext * cx,unsigned argc,Value * vp)1543 js::math_sign(JSContext* cx, unsigned argc, Value* vp)
1544 {
1545     return math_function<math_sign_impl>(cx, argc, vp);
1546 }
1547 
1548 #if !HAVE_CBRT
cbrt(double x)1549 double cbrt(double x)
1550 {
1551     if (x > 0) {
1552         return pow(x, 1.0 / 3.0);
1553     } else if (x == 0) {
1554         return x;
1555     } else {
1556         return -pow(-x, 1.0 / 3.0);
1557     }
1558 }
1559 #endif
1560 
1561 double
math_cbrt_impl(MathCache * cache,double x)1562 js::math_cbrt_impl(MathCache* cache, double x)
1563 {
1564     return cache->lookup(cbrt, x, MathCache::Cbrt);
1565 }
1566 
1567 double
math_cbrt_uncached(double x)1568 js::math_cbrt_uncached(double x)
1569 {
1570     return cbrt(x);
1571 }
1572 
1573 bool
math_cbrt(JSContext * cx,unsigned argc,Value * vp)1574 js::math_cbrt(JSContext* cx, unsigned argc, Value* vp)
1575 {
1576     return math_function<math_cbrt_impl>(cx, argc, vp);
1577 }
1578 
1579 #if JS_HAS_TOSOURCE
1580 static bool
math_toSource(JSContext * cx,unsigned argc,Value * vp)1581 math_toSource(JSContext* cx, unsigned argc, Value* vp)
1582 {
1583     CallArgs args = CallArgsFromVp(argc, vp);
1584     args.rval().setString(cx->names().Math);
1585     return true;
1586 }
1587 #endif
1588 
1589 static const JSFunctionSpec math_static_methods[] = {
1590 #if JS_HAS_TOSOURCE
1591     JS_FN(js_toSource_str,  math_toSource,        0, 0),
1592 #endif
1593     JS_INLINABLE_FN("abs",    math_abs,             1, 0, MathAbs),
1594     JS_INLINABLE_FN("acos",   math_acos,            1, 0, MathACos),
1595     JS_INLINABLE_FN("asin",   math_asin,            1, 0, MathASin),
1596     JS_INLINABLE_FN("atan",   math_atan,            1, 0, MathATan),
1597     JS_INLINABLE_FN("atan2",  math_atan2,           2, 0, MathATan2),
1598     JS_INLINABLE_FN("ceil",   math_ceil,            1, 0, MathCeil),
1599     JS_INLINABLE_FN("clz32",  math_clz32,           1, 0, MathClz32),
1600     JS_INLINABLE_FN("cos",    math_cos,             1, 0, MathCos),
1601     JS_INLINABLE_FN("exp",    math_exp,             1, 0, MathExp),
1602     JS_INLINABLE_FN("floor",  math_floor,           1, 0, MathFloor),
1603     JS_INLINABLE_FN("imul",   math_imul,            2, 0, MathImul),
1604     JS_INLINABLE_FN("fround", math_fround,          1, 0, MathFRound),
1605     JS_INLINABLE_FN("log",    math_log,             1, 0, MathLog),
1606     JS_INLINABLE_FN("max",    math_max,             2, 0, MathMax),
1607     JS_INLINABLE_FN("min",    math_min,             2, 0, MathMin),
1608     JS_INLINABLE_FN("pow",    math_pow,             2, 0, MathPow),
1609     JS_INLINABLE_FN("random", math_random,          0, 0, MathRandom),
1610     JS_INLINABLE_FN("round",  math_round,           1, 0, MathRound),
1611     JS_INLINABLE_FN("sin",    math_sin,             1, 0, MathSin),
1612     JS_INLINABLE_FN("sqrt",   math_sqrt,            1, 0, MathSqrt),
1613     JS_INLINABLE_FN("tan",    math_tan,             1, 0, MathTan),
1614     JS_INLINABLE_FN("log10",  math_log10,           1, 0, MathLog10),
1615     JS_INLINABLE_FN("log2",   math_log2,            1, 0, MathLog2),
1616     JS_INLINABLE_FN("log1p",  math_log1p,           1, 0, MathLog1P),
1617     JS_INLINABLE_FN("expm1",  math_expm1,           1, 0, MathExpM1),
1618     JS_INLINABLE_FN("cosh",   math_cosh,            1, 0, MathCosH),
1619     JS_INLINABLE_FN("sinh",   math_sinh,            1, 0, MathSinH),
1620     JS_INLINABLE_FN("tanh",   math_tanh,            1, 0, MathTanH),
1621     JS_INLINABLE_FN("acosh",  math_acosh,           1, 0, MathACosH),
1622     JS_INLINABLE_FN("asinh",  math_asinh,           1, 0, MathASinH),
1623     JS_INLINABLE_FN("atanh",  math_atanh,           1, 0, MathATanH),
1624     JS_INLINABLE_FN("hypot",  math_hypot,           2, 0, MathHypot),
1625     JS_INLINABLE_FN("trunc",  math_trunc,           1, 0, MathTrunc),
1626     JS_INLINABLE_FN("sign",   math_sign,            1, 0, MathSign),
1627     JS_INLINABLE_FN("cbrt",   math_cbrt,            1, 0, MathCbrt),
1628     JS_FS_END
1629 };
1630 
1631 JSObject*
InitMathClass(JSContext * cx,HandleObject obj)1632 js::InitMathClass(JSContext* cx, HandleObject obj)
1633 {
1634     RootedObject proto(cx, obj->as<GlobalObject>().getOrCreateObjectPrototype(cx));
1635     if (!proto)
1636         return nullptr;
1637     RootedObject Math(cx, NewObjectWithGivenProto(cx, &MathClass, proto, SingletonObject));
1638     if (!Math)
1639         return nullptr;
1640 
1641     if (!JS_DefineProperty(cx, obj, js_Math_str, Math, JSPROP_RESOLVING,
1642                            JS_STUBGETTER, JS_STUBSETTER))
1643     {
1644         return nullptr;
1645     }
1646     if (!JS_DefineFunctions(cx, Math, math_static_methods))
1647         return nullptr;
1648     if (!JS_DefineConstDoubles(cx, Math, math_constants))
1649         return nullptr;
1650 
1651     obj->as<GlobalObject>().setConstructor(JSProto_Math, ObjectValue(*Math));
1652 
1653     return Math;
1654 }
1655