1 /*
2  * Copyright (C) 1999-2000 Harri Porten (porten@kde.org)
3  * Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
4  * Copyright (C) 2009 Google Inc. All rights reserved.
5  * Copyright (C) 2007-2009 Torch Mobile, Inc.
6  *
7  * The Original Code is Mozilla Communicator client code, released
8  * March 31, 1998.
9  *
10  * The Initial Developer of the Original Code is
11  * Netscape Communications Corporation.
12  * Portions created by the Initial Developer are Copyright (C) 1998
13  * the Initial Developer. All Rights Reserved.
14  *
15  * This library is free software; you can redistribute it and/or
16  * modify it under the terms of the GNU Lesser General Public
17  * License as published by the Free Software Foundation; either
18  * version 2.1 of the License, or (at your option) any later version.
19  *
20  * This library is distributed in the hope that it will be useful,
21  * but WITHOUT ANY WARRANTY; without even the implied warranty of
22  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
23  * Lesser General Public License for more details.
24  *
25  * You should have received a copy of the GNU Lesser General Public
26  * License along with this library; if not, write to the Free Software
27  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
28  *
29  * Alternatively, the contents of this file may be used under the terms
30  * of either the Mozilla Public License Version 1.1, found at
31  * http://www.mozilla.org/MPL/ (the "MPL") or the GNU General Public
32  * License Version 2.0, found at http://www.fsf.org/copyleft/gpl.html
33  * (the "GPL"), in which case the provisions of the MPL or the GPL are
34  * applicable instead of those above.  If you wish to allow use of your
35  * version of this file only under the terms of one of those two
36  * licenses (the MPL or the GPL) and not to allow others to use your
37  * version of this file under the LGPL, indicate your decision by
38  * deletingthe provisions above and replace them with the notice and
39  * other provisions required by the MPL or the GPL, as the case may be.
40  * If you do not delete the provisions above, a recipient may use your
41  * version of this file under any of the LGPL, the MPL or the GPL.
42 
43  * Copyright 2006-2008 the V8 project authors. All rights reserved.
44  * Redistribution and use in source and binary forms, with or without
45  * modification, are permitted provided that the following conditions are
46  * met:
47  *
48  *     * Redistributions of source code must retain the above copyright
49  *       notice, this list of conditions and the following disclaimer.
50  *     * Redistributions in binary form must reproduce the above
51  *       copyright notice, this list of conditions and the following
52  *       disclaimer in the documentation and/or other materials provided
53  *       with the distribution.
54  *     * Neither the name of Google Inc. nor the names of its
55  *       contributors may be used to endorse or promote products derived
56  *       from this software without specific prior written permission.
57  *
58  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
59  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
60  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
61  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
62  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
63  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
64  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
65  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
66  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
67  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
68  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
69  */
70 
71 #include "config.h"
72 #include "DateMath.h"
73 
74 #include "Assertions.h"
75 #include "ASCIICType.h"
76 #include "CurrentTime.h"
77 #include "MathExtras.h"
78 #include "StringExtras.h"
79 
80 #include <algorithm>
81 #include <limits.h>
82 #include <limits>
83 #include <stdint.h>
84 #include <time.h>
85 
86 
87 #if HAVE(ERRNO_H)
88 #include <errno.h>
89 #endif
90 
91 #if OS(WINCE)
92 extern "C" size_t strftime(char * const s, const size_t maxsize, const char * const format, const struct tm * const t);
93 extern "C" struct tm * localtime(const time_t *timer);
94 #endif
95 
96 #if HAVE(SYS_TIME_H)
97 #include <sys/time.h>
98 #endif
99 
100 #if HAVE(SYS_TIMEB_H)
101 #include <sys/timeb.h>
102 #endif
103 
104 #if USE(JSC)
105 #include "CallFrame.h"
106 #endif
107 
108 #define NaN std::numeric_limits<double>::quiet_NaN()
109 
110 using namespace WTF;
111 
112 namespace WTF {
113 
114 /* Constants */
115 
116 static const double minutesPerDay = 24.0 * 60.0;
117 static const double secondsPerDay = 24.0 * 60.0 * 60.0;
118 static const double secondsPerYear = 24.0 * 60.0 * 60.0 * 365.0;
119 
120 static const double usecPerSec = 1000000.0;
121 
122 static const double maxUnixTime = 2145859200.0; // 12/31/2037
123 // ECMAScript asks not to support for a date of which total
124 // millisecond value is larger than the following value.
125 // See 15.9.1.14 of ECMA-262 5th edition.
126 static const double maxECMAScriptTime = 8.64E15;
127 
128 // Day of year for the first day of each month, where index 0 is January, and day 0 is January 1.
129 // First for non-leap years, then for leap years.
130 static const int firstDayOfMonth[2][12] = {
131     {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334},
132     {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335}
133 };
134 
isLeapYear(int year)135 static inline bool isLeapYear(int year)
136 {
137     if (year % 4 != 0)
138         return false;
139     if (year % 400 == 0)
140         return true;
141     if (year % 100 == 0)
142         return false;
143     return true;
144 }
145 
daysInYear(int year)146 static inline int daysInYear(int year)
147 {
148     return 365 + isLeapYear(year);
149 }
150 
daysFrom1970ToYear(int year)151 static inline double daysFrom1970ToYear(int year)
152 {
153     // The Gregorian Calendar rules for leap years:
154     // Every fourth year is a leap year.  2004, 2008, and 2012 are leap years.
155     // However, every hundredth year is not a leap year.  1900 and 2100 are not leap years.
156     // Every four hundred years, there's a leap year after all.  2000 and 2400 are leap years.
157 
158     static const int leapDaysBefore1971By4Rule = 1970 / 4;
159     static const int excludedLeapDaysBefore1971By100Rule = 1970 / 100;
160     static const int leapDaysBefore1971By400Rule = 1970 / 400;
161 
162     const double yearMinusOne = year - 1;
163     const double yearsToAddBy4Rule = floor(yearMinusOne / 4.0) - leapDaysBefore1971By4Rule;
164     const double yearsToExcludeBy100Rule = floor(yearMinusOne / 100.0) - excludedLeapDaysBefore1971By100Rule;
165     const double yearsToAddBy400Rule = floor(yearMinusOne / 400.0) - leapDaysBefore1971By400Rule;
166 
167     return 365.0 * (year - 1970) + yearsToAddBy4Rule - yearsToExcludeBy100Rule + yearsToAddBy400Rule;
168 }
169 
msToDays(double ms)170 static inline double msToDays(double ms)
171 {
172     return floor(ms / msPerDay);
173 }
174 
msToYear(double ms)175 int msToYear(double ms)
176 {
177     int approxYear = static_cast<int>(floor(ms / (msPerDay * 365.2425)) + 1970);
178     double msFromApproxYearTo1970 = msPerDay * daysFrom1970ToYear(approxYear);
179     if (msFromApproxYearTo1970 > ms)
180         return approxYear - 1;
181     if (msFromApproxYearTo1970 + msPerDay * daysInYear(approxYear) <= ms)
182         return approxYear + 1;
183     return approxYear;
184 }
185 
dayInYear(double ms,int year)186 int dayInYear(double ms, int year)
187 {
188     return static_cast<int>(msToDays(ms) - daysFrom1970ToYear(year));
189 }
190 
msToMilliseconds(double ms)191 static inline double msToMilliseconds(double ms)
192 {
193     double result = fmod(ms, msPerDay);
194     if (result < 0)
195         result += msPerDay;
196     return result;
197 }
198 
199 // 0: Sunday, 1: Monday, etc.
msToWeekDay(double ms)200 static inline int msToWeekDay(double ms)
201 {
202     int wd = (static_cast<int>(msToDays(ms)) + 4) % 7;
203     if (wd < 0)
204         wd += 7;
205     return wd;
206 }
207 
msToSeconds(double ms)208 static inline int msToSeconds(double ms)
209 {
210     double result = fmod(floor(ms / msPerSecond), secondsPerMinute);
211     if (result < 0)
212         result += secondsPerMinute;
213     return static_cast<int>(result);
214 }
215 
msToMinutes(double ms)216 static inline int msToMinutes(double ms)
217 {
218     double result = fmod(floor(ms / msPerMinute), minutesPerHour);
219     if (result < 0)
220         result += minutesPerHour;
221     return static_cast<int>(result);
222 }
223 
msToHours(double ms)224 static inline int msToHours(double ms)
225 {
226     double result = fmod(floor(ms/msPerHour), hoursPerDay);
227     if (result < 0)
228         result += hoursPerDay;
229     return static_cast<int>(result);
230 }
231 
monthFromDayInYear(int dayInYear,bool leapYear)232 int monthFromDayInYear(int dayInYear, bool leapYear)
233 {
234     const int d = dayInYear;
235     int step;
236 
237     if (d < (step = 31))
238         return 0;
239     step += (leapYear ? 29 : 28);
240     if (d < step)
241         return 1;
242     if (d < (step += 31))
243         return 2;
244     if (d < (step += 30))
245         return 3;
246     if (d < (step += 31))
247         return 4;
248     if (d < (step += 30))
249         return 5;
250     if (d < (step += 31))
251         return 6;
252     if (d < (step += 31))
253         return 7;
254     if (d < (step += 30))
255         return 8;
256     if (d < (step += 31))
257         return 9;
258     if (d < (step += 30))
259         return 10;
260     return 11;
261 }
262 
checkMonth(int dayInYear,int & startDayOfThisMonth,int & startDayOfNextMonth,int daysInThisMonth)263 static inline bool checkMonth(int dayInYear, int& startDayOfThisMonth, int& startDayOfNextMonth, int daysInThisMonth)
264 {
265     startDayOfThisMonth = startDayOfNextMonth;
266     startDayOfNextMonth += daysInThisMonth;
267     return (dayInYear <= startDayOfNextMonth);
268 }
269 
dayInMonthFromDayInYear(int dayInYear,bool leapYear)270 int dayInMonthFromDayInYear(int dayInYear, bool leapYear)
271 {
272     const int d = dayInYear;
273     int step;
274     int next = 30;
275 
276     if (d <= next)
277         return d + 1;
278     const int daysInFeb = (leapYear ? 29 : 28);
279     if (checkMonth(d, step, next, daysInFeb))
280         return d - step;
281     if (checkMonth(d, step, next, 31))
282         return d - step;
283     if (checkMonth(d, step, next, 30))
284         return d - step;
285     if (checkMonth(d, step, next, 31))
286         return d - step;
287     if (checkMonth(d, step, next, 30))
288         return d - step;
289     if (checkMonth(d, step, next, 31))
290         return d - step;
291     if (checkMonth(d, step, next, 31))
292         return d - step;
293     if (checkMonth(d, step, next, 30))
294         return d - step;
295     if (checkMonth(d, step, next, 31))
296         return d - step;
297     if (checkMonth(d, step, next, 30))
298         return d - step;
299     step = next;
300     return d - step;
301 }
302 
monthToDayInYear(int month,bool isLeapYear)303 static inline int monthToDayInYear(int month, bool isLeapYear)
304 {
305     return firstDayOfMonth[isLeapYear][month];
306 }
307 
timeToMS(double hour,double min,double sec,double ms)308 static inline double timeToMS(double hour, double min, double sec, double ms)
309 {
310     return (((hour * minutesPerHour + min) * secondsPerMinute + sec) * msPerSecond + ms);
311 }
312 
dateToDaysFrom1970(int year,int month,int day)313 double dateToDaysFrom1970(int year, int month, int day)
314 {
315     year += month / 12;
316 
317     month %= 12;
318     if (month < 0) {
319         month += 12;
320         --year;
321     }
322 
323     double yearday = floor(daysFrom1970ToYear(year));
324     ASSERT((year >= 1970 && yearday >= 0) || (year < 1970 && yearday < 0));
325     int monthday = monthToDayInYear(month, isLeapYear(year));
326 
327     return yearday + monthday + day - 1;
328 }
329 
330 // There is a hard limit at 2038 that we currently do not have a workaround
331 // for (rdar://problem/5052975).
maximumYearForDST()332 static inline int maximumYearForDST()
333 {
334     return 2037;
335 }
336 
minimumYearForDST()337 static inline int minimumYearForDST()
338 {
339     // Because of the 2038 issue (see maximumYearForDST) if the current year is
340     // greater than the max year minus 27 (2010), we want to use the max year
341     // minus 27 instead, to ensure there is a range of 28 years that all years
342     // can map to.
343     return std::min(msToYear(jsCurrentTime()), maximumYearForDST() - 27) ;
344 }
345 
346 /*
347  * Find an equivalent year for the one given, where equivalence is deterined by
348  * the two years having the same leapness and the first day of the year, falling
349  * on the same day of the week.
350  *
351  * This function returns a year between this current year and 2037, however this
352  * function will potentially return incorrect results if the current year is after
353  * 2010, (rdar://problem/5052975), if the year passed in is before 1900 or after
354  * 2100, (rdar://problem/5055038).
355  */
equivalentYearForDST(int year)356 int equivalentYearForDST(int year)
357 {
358     // It is ok if the cached year is not the current year as long as the rules
359     // for DST did not change between the two years; if they did the app would need
360     // to be restarted.
361     static int minYear = minimumYearForDST();
362     int maxYear = maximumYearForDST();
363 
364     int difference;
365     if (year > maxYear)
366         difference = minYear - year;
367     else if (year < minYear)
368         difference = maxYear - year;
369     else
370         return year;
371 
372     int quotient = difference / 28;
373     int product = (quotient) * 28;
374 
375     year += product;
376     ASSERT((year >= minYear && year <= maxYear) || (product - year == static_cast<int>(NaN)));
377     return year;
378 }
379 
380 #if !HAVE(TM_GMTOFF)
381 
calculateUTCOffset()382 static int32_t calculateUTCOffset()
383 {
384 #if PLATFORM(BREWMP)
385     time_t localTime = static_cast<time_t>(currentTime());
386 #else
387     time_t localTime = time(0);
388 #endif
389     tm localt;
390     getLocalTime(&localTime, &localt);
391 
392     // Get the difference between this time zone and UTC on the 1st of January of this year.
393     localt.tm_sec = 0;
394     localt.tm_min = 0;
395     localt.tm_hour = 0;
396     localt.tm_mday = 1;
397     localt.tm_mon = 0;
398     // Not setting localt.tm_year!
399     localt.tm_wday = 0;
400     localt.tm_yday = 0;
401     localt.tm_isdst = 0;
402 #if HAVE(TM_GMTOFF)
403     localt.tm_gmtoff = 0;
404 #endif
405 #if HAVE(TM_ZONE)
406     localt.tm_zone = 0;
407 #endif
408 
409 #if HAVE(TIMEGM)
410     time_t utcOffset = timegm(&localt) - mktime(&localt);
411 #else
412     // Using a canned date of 01/01/2009 on platforms with weaker date-handling foo.
413     localt.tm_year = 109;
414     time_t utcOffset = 1230768000 - mktime(&localt);
415 #endif
416 
417     return static_cast<int32_t>(utcOffset * 1000);
418 }
419 
420 /*
421  * Get the DST offset for the time passed in.
422  */
calculateDSTOffset(time_t localTime,double utcOffset)423 static double calculateDSTOffset(time_t localTime, double utcOffset)
424 {
425     //input is UTC so we have to shift back to local time to determine DST thus the + getUTCOffset()
426     double offsetTime = (localTime * msPerSecond) + utcOffset;
427 
428     // Offset from UTC but doesn't include DST obviously
429     int offsetHour =  msToHours(offsetTime);
430     int offsetMinute =  msToMinutes(offsetTime);
431 
432     tm localTM;
433     getLocalTime(&localTime, &localTM);
434 
435     double diff = ((localTM.tm_hour - offsetHour) * secondsPerHour) + ((localTM.tm_min - offsetMinute) * 60);
436 
437     if (diff < 0)
438         diff += secondsPerDay;
439 
440     return (diff * msPerSecond);
441 }
442 
443 #endif
444 
445 // Returns combined offset in millisecond (UTC + DST).
calculateLocalTimeOffset(double ms)446 LocalTimeOffset calculateLocalTimeOffset(double ms)
447 {
448     // On Mac OS X, the call to localtime (see calculateDSTOffset) will return historically accurate
449     // DST information (e.g. New Zealand did not have DST from 1946 to 1974) however the JavaScript
450     // standard explicitly dictates that historical information should not be considered when
451     // determining DST. For this reason we shift away from years that localtime can handle but would
452     // return historically accurate information.
453     int year = msToYear(ms);
454     int equivalentYear = equivalentYearForDST(year);
455     if (year != equivalentYear) {
456         bool leapYear = isLeapYear(year);
457         int dayInYearLocal = dayInYear(ms, year);
458         int dayInMonth = dayInMonthFromDayInYear(dayInYearLocal, leapYear);
459         int month = monthFromDayInYear(dayInYearLocal, leapYear);
460         double day = dateToDaysFrom1970(equivalentYear, month, dayInMonth);
461         ms = (day * msPerDay) + msToMilliseconds(ms);
462     }
463 
464     double localTimeSeconds = ms / msPerSecond;
465     if (localTimeSeconds > maxUnixTime)
466         localTimeSeconds = maxUnixTime;
467     else if (localTimeSeconds < 0) // Go ahead a day to make localtime work (does not work with 0).
468         localTimeSeconds += secondsPerDay;
469     // FIXME: time_t has a potential problem in 2038.
470     time_t localTime = static_cast<time_t>(localTimeSeconds);
471 
472 #if HAVE(TM_GMTOFF)
473     tm localTM;
474     getLocalTime(&localTime, &localTM);
475     return LocalTimeOffset(localTM.tm_isdst, localTM.tm_gmtoff * msPerSecond);
476 #else
477     double utcOffset = calculateUTCOffset();
478     double dstOffset = calculateDSTOffset(localTime, utcOffset);
479     return LocalTimeOffset(dstOffset, utcOffset + dstOffset);
480 #endif
481 }
482 
initializeDates()483 void initializeDates()
484 {
485 #ifndef NDEBUG
486     static bool alreadyInitialized;
487     ASSERT(!alreadyInitialized);
488     alreadyInitialized = true;
489 #endif
490 
491     equivalentYearForDST(2000); // Need to call once to initialize a static used in this function.
492 }
493 
ymdhmsToSeconds(long year,int mon,int day,int hour,int minute,int second)494 static inline double ymdhmsToSeconds(long year, int mon, int day, int hour, int minute, int second)
495 {
496     double days = (day - 32075)
497         + floor(1461 * (year + 4800.0 + (mon - 14) / 12) / 4)
498         + 367 * (mon - 2 - (mon - 14) / 12 * 12) / 12
499         - floor(3 * ((year + 4900.0 + (mon - 14) / 12) / 100) / 4)
500         - 2440588;
501     return ((days * hoursPerDay + hour) * minutesPerHour + minute) * secondsPerMinute + second;
502 }
503 
504 // We follow the recommendation of RFC 2822 to consider all
505 // obsolete time zones not listed here equivalent to "-0000".
506 static const struct KnownZone {
507 #if !OS(WINDOWS)
508     const
509 #endif
510         char tzName[4];
511     int tzOffset;
512 } known_zones[] = {
513     { "UT", 0 },
514     { "GMT", 0 },
515     { "EST", -300 },
516     { "EDT", -240 },
517     { "CST", -360 },
518     { "CDT", -300 },
519     { "MST", -420 },
520     { "MDT", -360 },
521     { "PST", -480 },
522     { "PDT", -420 }
523 };
524 
skipSpacesAndComments(const char * & s)525 inline static void skipSpacesAndComments(const char*& s)
526 {
527     int nesting = 0;
528     char ch;
529     while ((ch = *s)) {
530         if (!isASCIISpace(ch)) {
531             if (ch == '(')
532                 nesting++;
533             else if (ch == ')' && nesting > 0)
534                 nesting--;
535             else if (nesting == 0)
536                 break;
537         }
538         s++;
539     }
540 }
541 
542 // returns 0-11 (Jan-Dec); -1 on failure
findMonth(const char * monthStr)543 static int findMonth(const char* monthStr)
544 {
545     ASSERT(monthStr);
546     char needle[4];
547     for (int i = 0; i < 3; ++i) {
548         if (!*monthStr)
549             return -1;
550         needle[i] = static_cast<char>(toASCIILower(*monthStr++));
551     }
552     needle[3] = '\0';
553     const char *haystack = "janfebmaraprmayjunjulaugsepoctnovdec";
554     const char *str = strstr(haystack, needle);
555     if (str) {
556         int position = static_cast<int>(str - haystack);
557         if (position % 3 == 0)
558             return position / 3;
559     }
560     return -1;
561 }
562 
parseLong(const char * string,char ** stopPosition,int base,long * result)563 static bool parseLong(const char* string, char** stopPosition, int base, long* result)
564 {
565     *result = strtol(string, stopPosition, base);
566     // Avoid the use of errno as it is not available on Windows CE
567     if (string == *stopPosition || *result == LONG_MIN || *result == LONG_MAX)
568         return false;
569     return true;
570 }
571 
572 // Odd case where 'exec' is allowed to be 0, to accomodate a caller in WebCore.
parseDateFromNullTerminatedCharacters(const char * dateString,bool & haveTZ,int & offset)573 static double parseDateFromNullTerminatedCharacters(const char* dateString, bool& haveTZ, int& offset)
574 {
575     haveTZ = false;
576     offset = 0;
577 
578     // This parses a date in the form:
579     //     Tuesday, 09-Nov-99 23:12:40 GMT
580     // or
581     //     Sat, 01-Jan-2000 08:00:00 GMT
582     // or
583     //     Sat, 01 Jan 2000 08:00:00 GMT
584     // or
585     //     01 Jan 99 22:00 +0100    (exceptions in rfc822/rfc2822)
586     // ### non RFC formats, added for Javascript:
587     //     [Wednesday] January 09 1999 23:12:40 GMT
588     //     [Wednesday] January 09 23:12:40 GMT 1999
589     //
590     // We ignore the weekday.
591 
592     // Skip leading space
593     skipSpacesAndComments(dateString);
594 
595     long month = -1;
596     const char *wordStart = dateString;
597     // Check contents of first words if not number
598     while (*dateString && !isASCIIDigit(*dateString)) {
599         if (isASCIISpace(*dateString) || *dateString == '(') {
600             if (dateString - wordStart >= 3)
601                 month = findMonth(wordStart);
602             skipSpacesAndComments(dateString);
603             wordStart = dateString;
604         } else
605            dateString++;
606     }
607 
608     // Missing delimiter between month and day (like "January29")?
609     if (month == -1 && wordStart != dateString)
610         month = findMonth(wordStart);
611 
612     skipSpacesAndComments(dateString);
613 
614     if (!*dateString)
615         return NaN;
616 
617     // ' 09-Nov-99 23:12:40 GMT'
618     char* newPosStr;
619     long day;
620     if (!parseLong(dateString, &newPosStr, 10, &day))
621         return NaN;
622     dateString = newPosStr;
623 
624     if (!*dateString)
625         return NaN;
626 
627     if (day < 0)
628         return NaN;
629 
630     long year = 0;
631     if (day > 31) {
632         // ### where is the boundary and what happens below?
633         if (*dateString != '/')
634             return NaN;
635         // looks like a YYYY/MM/DD date
636         if (!*++dateString)
637             return NaN;
638         year = day;
639         if (!parseLong(dateString, &newPosStr, 10, &month))
640             return NaN;
641         month -= 1;
642         dateString = newPosStr;
643         if (*dateString++ != '/' || !*dateString)
644             return NaN;
645         if (!parseLong(dateString, &newPosStr, 10, &day))
646             return NaN;
647         dateString = newPosStr;
648     } else if (*dateString == '/' && month == -1) {
649         dateString++;
650         // This looks like a MM/DD/YYYY date, not an RFC date.
651         month = day - 1; // 0-based
652         if (!parseLong(dateString, &newPosStr, 10, &day))
653             return NaN;
654         if (day < 1 || day > 31)
655             return NaN;
656         dateString = newPosStr;
657         if (*dateString == '/')
658             dateString++;
659         if (!*dateString)
660             return NaN;
661      } else {
662         if (*dateString == '-')
663             dateString++;
664 
665         skipSpacesAndComments(dateString);
666 
667         if (*dateString == ',')
668             dateString++;
669 
670         if (month == -1) { // not found yet
671             month = findMonth(dateString);
672             if (month == -1)
673                 return NaN;
674 
675             while (*dateString && *dateString != '-' && *dateString != ',' && !isASCIISpace(*dateString))
676                 dateString++;
677 
678             if (!*dateString)
679                 return NaN;
680 
681             // '-99 23:12:40 GMT'
682             if (*dateString != '-' && *dateString != '/' && *dateString != ',' && !isASCIISpace(*dateString))
683                 return NaN;
684             dateString++;
685         }
686     }
687 
688     if (month < 0 || month > 11)
689         return NaN;
690 
691     // '99 23:12:40 GMT'
692     if (year <= 0 && *dateString) {
693         if (!parseLong(dateString, &newPosStr, 10, &year))
694             return NaN;
695     }
696 
697     // Don't fail if the time is missing.
698     long hour = 0;
699     long minute = 0;
700     long second = 0;
701     if (!*newPosStr)
702         dateString = newPosStr;
703     else {
704         // ' 23:12:40 GMT'
705         if (!(isASCIISpace(*newPosStr) || *newPosStr == ',')) {
706             if (*newPosStr != ':')
707                 return NaN;
708             // There was no year; the number was the hour.
709             year = -1;
710         } else {
711             // in the normal case (we parsed the year), advance to the next number
712             dateString = ++newPosStr;
713             skipSpacesAndComments(dateString);
714         }
715 
716         parseLong(dateString, &newPosStr, 10, &hour);
717         // Do not check for errno here since we want to continue
718         // even if errno was set becasue we are still looking
719         // for the timezone!
720 
721         // Read a number? If not, this might be a timezone name.
722         if (newPosStr != dateString) {
723             dateString = newPosStr;
724 
725             if (hour < 0 || hour > 23)
726                 return NaN;
727 
728             if (!*dateString)
729                 return NaN;
730 
731             // ':12:40 GMT'
732             if (*dateString++ != ':')
733                 return NaN;
734 
735             if (!parseLong(dateString, &newPosStr, 10, &minute))
736                 return NaN;
737             dateString = newPosStr;
738 
739             if (minute < 0 || minute > 59)
740                 return NaN;
741 
742             // ':40 GMT'
743             if (*dateString && *dateString != ':' && !isASCIISpace(*dateString))
744                 return NaN;
745 
746             // seconds are optional in rfc822 + rfc2822
747             if (*dateString ==':') {
748                 dateString++;
749 
750                 if (!parseLong(dateString, &newPosStr, 10, &second))
751                     return NaN;
752                 dateString = newPosStr;
753 
754                 if (second < 0 || second > 59)
755                     return NaN;
756             }
757 
758             skipSpacesAndComments(dateString);
759 
760             if (strncasecmp(dateString, "AM", 2) == 0) {
761                 if (hour > 12)
762                     return NaN;
763                 if (hour == 12)
764                     hour = 0;
765                 dateString += 2;
766                 skipSpacesAndComments(dateString);
767             } else if (strncasecmp(dateString, "PM", 2) == 0) {
768                 if (hour > 12)
769                     return NaN;
770                 if (hour != 12)
771                     hour += 12;
772                 dateString += 2;
773                 skipSpacesAndComments(dateString);
774             }
775         }
776     }
777 
778     // Don't fail if the time zone is missing.
779     // Some websites omit the time zone (4275206).
780     if (*dateString) {
781         if (strncasecmp(dateString, "GMT", 3) == 0 || strncasecmp(dateString, "UTC", 3) == 0) {
782             dateString += 3;
783             haveTZ = true;
784         }
785 
786         if (*dateString == '+' || *dateString == '-') {
787             long o;
788             if (!parseLong(dateString, &newPosStr, 10, &o))
789                 return NaN;
790             dateString = newPosStr;
791 
792             if (o < -9959 || o > 9959)
793                 return NaN;
794 
795             int sgn = (o < 0) ? -1 : 1;
796             o = labs(o);
797             if (*dateString != ':') {
798                 offset = ((o / 100) * 60 + (o % 100)) * sgn;
799             } else { // GMT+05:00
800                 long o2;
801                 if (!parseLong(dateString, &newPosStr, 10, &o2))
802                     return NaN;
803                 dateString = newPosStr;
804                 offset = (o * 60 + o2) * sgn;
805             }
806             haveTZ = true;
807         } else {
808             for (int i = 0; i < int(sizeof(known_zones) / sizeof(KnownZone)); i++) {
809                 if (0 == strncasecmp(dateString, known_zones[i].tzName, strlen(known_zones[i].tzName))) {
810                     offset = known_zones[i].tzOffset;
811                     dateString += strlen(known_zones[i].tzName);
812                     haveTZ = true;
813                     break;
814                 }
815             }
816         }
817     }
818 
819     skipSpacesAndComments(dateString);
820 
821     if (*dateString && year == -1) {
822         if (!parseLong(dateString, &newPosStr, 10, &year))
823             return NaN;
824         dateString = newPosStr;
825     }
826 
827     skipSpacesAndComments(dateString);
828 
829     // Trailing garbage
830     if (*dateString)
831         return NaN;
832 
833     // Y2K: Handle 2 digit years.
834     if (year >= 0 && year < 100) {
835         if (year < 50)
836             year += 2000;
837         else
838             year += 1900;
839     }
840 
841     return ymdhmsToSeconds(year, month + 1, day, hour, minute, second) * msPerSecond;
842 }
843 
parseDateFromNullTerminatedCharacters(const char * dateString)844 double parseDateFromNullTerminatedCharacters(const char* dateString)
845 {
846     bool haveTZ;
847     int offset;
848     double ms = parseDateFromNullTerminatedCharacters(dateString, haveTZ, offset);
849     if (isnan(ms))
850         return NaN;
851 
852     // fall back to local timezone
853     if (!haveTZ)
854         offset = calculateLocalTimeOffset(ms).offset / msPerMinute;
855 
856     return ms - (offset * msPerMinute);
857 }
858 
timeClip(double t)859 double timeClip(double t)
860 {
861     if (!isfinite(t))
862         return NaN;
863     if (fabs(t) > maxECMAScriptTime)
864         return NaN;
865     return trunc(t);
866 }
867 } // namespace WTF
868 
869 #if USE(JSC)
870 namespace JSC {
871 
872 // Get the combined UTC + DST offset for the time passed in.
873 //
874 // NOTE: The implementation relies on the fact that no time zones have
875 // more than one daylight savings offset change per month.
876 // If this function is called with NaN it returns NaN.
localTimeOffset(ExecState * exec,double ms)877 static LocalTimeOffset localTimeOffset(ExecState* exec, double ms)
878 {
879     LocalTimeOffsetCache& cache = exec->globalData().localTimeOffsetCache;
880     double start = cache.start;
881     double end = cache.end;
882 
883     if (start <= ms) {
884         // If the time fits in the cached interval, return the cached offset.
885         if (ms <= end) return cache.offset;
886 
887         // Compute a possible new interval end.
888         double newEnd = end + cache.increment;
889 
890         if (ms <= newEnd) {
891             LocalTimeOffset endOffset = calculateLocalTimeOffset(newEnd);
892             if (cache.offset == endOffset) {
893                 // If the offset at the end of the new interval still matches
894                 // the offset in the cache, we grow the cached time interval
895                 // and return the offset.
896                 cache.end = newEnd;
897                 cache.increment = msPerMonth;
898                 return endOffset;
899             }
900             LocalTimeOffset offset = calculateLocalTimeOffset(ms);
901             if (offset == endOffset) {
902                 // The offset at the given time is equal to the offset at the
903                 // new end of the interval, so that means that we've just skipped
904                 // the point in time where the DST offset change occurred. Updated
905                 // the interval to reflect this and reset the increment.
906                 cache.start = ms;
907                 cache.end = newEnd;
908                 cache.increment = msPerMonth;
909             } else {
910                 // The interval contains a DST offset change and the given time is
911                 // before it. Adjust the increment to avoid a linear search for
912                 // the offset change point and change the end of the interval.
913                 cache.increment /= 3;
914                 cache.end = ms;
915             }
916             // Update the offset in the cache and return it.
917             cache.offset = offset;
918             return offset;
919         }
920     }
921 
922     // Compute the DST offset for the time and shrink the cache interval
923     // to only contain the time. This allows fast repeated DST offset
924     // computations for the same time.
925     LocalTimeOffset offset = calculateLocalTimeOffset(ms);
926     cache.offset = offset;
927     cache.start = ms;
928     cache.end = ms;
929     cache.increment = msPerMonth;
930     return offset;
931 }
932 
gregorianDateTimeToMS(ExecState * exec,const GregorianDateTime & t,double milliSeconds,bool inputIsUTC)933 double gregorianDateTimeToMS(ExecState* exec, const GregorianDateTime& t, double milliSeconds, bool inputIsUTC)
934 {
935     double day = dateToDaysFrom1970(t.year + 1900, t.month, t.monthDay);
936     double ms = timeToMS(t.hour, t.minute, t.second, milliSeconds);
937     double result = (day * WTF::msPerDay) + ms;
938 
939     if (!inputIsUTC)
940         result -= localTimeOffset(exec, result).offset;
941 
942     return result;
943 }
944 
945 // input is UTC
msToGregorianDateTime(ExecState * exec,double ms,bool outputIsUTC,GregorianDateTime & tm)946 void msToGregorianDateTime(ExecState* exec, double ms, bool outputIsUTC, GregorianDateTime& tm)
947 {
948     LocalTimeOffset localTime(false, 0);
949     if (!outputIsUTC) {
950         localTime = localTimeOffset(exec, ms);
951         ms += localTime.offset;
952     }
953 
954     const int year = msToYear(ms);
955     tm.second   =  msToSeconds(ms);
956     tm.minute   =  msToMinutes(ms);
957     tm.hour     =  msToHours(ms);
958     tm.weekDay  =  msToWeekDay(ms);
959     tm.yearDay  =  dayInYear(ms, year);
960     tm.monthDay =  dayInMonthFromDayInYear(tm.yearDay, isLeapYear(year));
961     tm.month    =  monthFromDayInYear(tm.yearDay, isLeapYear(year));
962     tm.year     =  year - 1900;
963     tm.isDST    =  localTime.isDST;
964     tm.utcOffset = localTime.offset / WTF::msPerSecond;
965     tm.timeZone = NULL;
966 }
967 
parseDateFromNullTerminatedCharacters(ExecState * exec,const char * dateString)968 double parseDateFromNullTerminatedCharacters(ExecState* exec, const char* dateString)
969 {
970     ASSERT(exec);
971     bool haveTZ;
972     int offset;
973     double ms = WTF::parseDateFromNullTerminatedCharacters(dateString, haveTZ, offset);
974     if (isnan(ms))
975         return NaN;
976 
977     // fall back to local timezone
978     if (!haveTZ)
979         offset = calculateLocalTimeOffset(ms).offset / msPerMinute;
980 
981     return ms - (offset * WTF::msPerMinute);
982 }
983 
984 } // namespace JSC
985 #endif // USE(JSC)
986