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 #ifndef jslibmath_h
8 #define jslibmath_h
9 
10 #include "mozilla/FloatingPoint.h"
11 
12 #include <math.h>
13 
14 #include "jsnum.h"
15 
16 #include "vm/JSContext.h"
17 
18 /*
19  * Use system provided math routines.
20  */
21 
22 /* The right copysign function is not always named the same thing. */
23 #ifdef __GNUC__
24 #define js_copysign __builtin_copysign
25 #elif defined _WIN32
26 #define js_copysign _copysign
27 #else
28 #define js_copysign copysign
29 #endif
30 
31 /* Consistency wrapper for platform deviations in fmod() */
js_fmod(double d,double d2)32 static inline double js_fmod(double d, double d2) {
33 #ifdef XP_WIN
34   /*
35    * Workaround MS fmod bug where 42 % (1/0) => NaN, not 42.
36    * Workaround MS fmod bug where -0 % -N => 0, not -0.
37    */
38   if ((mozilla::IsFinite(d) && mozilla::IsInfinite(d2)) ||
39       (d == 0 && mozilla::IsFinite(d2))) {
40     return d;
41   }
42 #endif
43   return fmod(d, d2);
44 }
45 
46 namespace js {
47 
NumberDiv(double a,double b)48 inline double NumberDiv(double a, double b) {
49   AutoUnsafeCallWithABI unsafe;
50   if (b == 0) {
51     if (a == 0 || mozilla::IsNaN(a)
52 #ifdef XP_WIN
53         || mozilla::IsNaN(b) /* XXX MSVC miscompiles such that (NaN == 0) */
54 #endif
55     )
56       return JS::GenericNaN();
57 
58     if (mozilla::IsNegative(a) != mozilla::IsNegative(b))
59       return mozilla::NegativeInfinity<double>();
60     return mozilla::PositiveInfinity<double>();
61   }
62 
63   return a / b;
64 }
65 
NumberMod(double a,double b)66 inline double NumberMod(double a, double b) {
67   AutoUnsafeCallWithABI unsafe;
68   if (b == 0) return JS::GenericNaN();
69   double r = fmod(a, b);
70 #if defined(XP_WIN)
71   // Some versions of Windows (Win 10 v1803, v1809) miscompute the sign of zero
72   // results from fmod. The sign should match the sign of the LHS. This bug
73   // only affects 64-bit builds. See bug 1527007.
74   if (mozilla::IsPositiveZero(r) && mozilla::IsNegative(a)) {
75     return -0.0;
76   }
77 #endif
78   return r;
79 }
80 
81 }  // namespace js
82 
83 #endif /* jslibmath_h */
84