1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef V8_DATE_H_
6 #define V8_DATE_H_
7 
8 #include "src/allocation.h"
9 #include "src/base/platform/platform.h"
10 #include "src/globals.h"
11 
12 
13 namespace v8 {
14 namespace internal {
15 
16 class DateCache {
17  public:
18   static const int kMsPerMin = 60 * 1000;
19   static const int kSecPerDay = 24 * 60 * 60;
20   static const int64_t kMsPerDay = kSecPerDay * 1000;
21 
22   // The largest time that can be passed to OS date-time library functions.
23   static const int kMaxEpochTimeInSec = kMaxInt;
24   static const int64_t kMaxEpochTimeInMs =
25       static_cast<int64_t>(kMaxInt) * 1000;
26 
27   // The largest time that can be stored in JSDate.
28   static const int64_t kMaxTimeInMs =
29       static_cast<int64_t>(864000000) * 10000000;
30 
31   // Conservative upper bound on time that can be stored in JSDate
32   // before UTC conversion.
33   static const int64_t kMaxTimeBeforeUTCInMs =
34       kMaxTimeInMs + 10 * kMsPerDay;
35 
36   // Sentinel that denotes an invalid local offset.
37   static const int kInvalidLocalOffsetInMs = kMaxInt;
38   // Sentinel that denotes an invalid cache stamp.
39   // It is an invariant of DateCache that cache stamp is non-negative.
40   static const int kInvalidStamp = -1;
41 
DateCache()42   DateCache() : stamp_(0), tz_cache_(base::OS::CreateTimezoneCache()) {
43     ResetDateCache();
44   }
45 
~DateCache()46   virtual ~DateCache() {
47     base::OS::DisposeTimezoneCache(tz_cache_);
48     tz_cache_ = NULL;
49   }
50 
51 
52   // Clears cached timezone information and increments the cache stamp.
53   void ResetDateCache();
54 
55 
56   // Computes floor(time_ms / kMsPerDay).
DaysFromTime(int64_t time_ms)57   static int DaysFromTime(int64_t time_ms) {
58     if (time_ms < 0) time_ms -= (kMsPerDay - 1);
59     return static_cast<int>(time_ms / kMsPerDay);
60   }
61 
62 
63   // Computes modulo(time_ms, kMsPerDay) given that
64   // days = floor(time_ms / kMsPerDay).
TimeInDay(int64_t time_ms,int days)65   static int TimeInDay(int64_t time_ms, int days) {
66     return static_cast<int>(time_ms - days * kMsPerDay);
67   }
68 
69 
70   // Given the number of days since the epoch, computes the weekday.
71   // ECMA 262 - 15.9.1.6.
Weekday(int days)72   int Weekday(int days) {
73     int result = (days + 4) % 7;
74     return result >= 0 ? result : result + 7;
75   }
76 
77 
IsLeap(int year)78   bool IsLeap(int year) {
79     return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
80   }
81 
82 
83   // ECMA 262 - 15.9.1.7.
LocalOffsetInMs()84   int LocalOffsetInMs() {
85     if (local_offset_ms_ == kInvalidLocalOffsetInMs)  {
86       local_offset_ms_ = GetLocalOffsetFromOS();
87     }
88     return local_offset_ms_;
89   }
90 
91 
LocalTimezone(int64_t time_ms)92   const char* LocalTimezone(int64_t time_ms) {
93     if (time_ms < 0 || time_ms > kMaxEpochTimeInMs) {
94       time_ms = EquivalentTime(time_ms);
95     }
96     return base::OS::LocalTimezone(static_cast<double>(time_ms), tz_cache_);
97   }
98 
99   // ECMA 262 - 15.9.5.26
TimezoneOffset(int64_t time_ms)100   int TimezoneOffset(int64_t time_ms) {
101     int64_t local_ms = ToLocal(time_ms);
102     return static_cast<int>((time_ms - local_ms) / kMsPerMin);
103   }
104 
105   // ECMA 262 - 15.9.1.9
106   // LocalTime(t) = t + LocalTZA + DaylightSavingTA(t)
ToLocal(int64_t time_ms)107   int64_t ToLocal(int64_t time_ms) {
108     return time_ms + LocalOffsetInMs() + DaylightSavingsOffsetInMs(time_ms);
109   }
110 
111   // ECMA 262 - 15.9.1.9
112   // UTC(t) = t - LocalTZA - DaylightSavingTA(t - LocalTZA)
ToUTC(int64_t time_ms)113   int64_t ToUTC(int64_t time_ms) {
114     // We need to compute UTC time that corresponds to the given local time.
115     // Literally following spec here leads to incorrect time computation at
116     // the points were we transition to and from DST.
117     //
118     // The following shows that using DST for (t - LocalTZA - hour) produces
119     // correct conversion.
120     //
121     // Consider transition to DST at local time L1.
122     // Let L0 = L1 - hour, L2 = L1 + hour,
123     //     U1 = UTC time that corresponds to L1,
124     //     U0 = U1 - hour.
125     // Transitioning to DST moves local clock one hour forward L1 => L2, so
126     // U0 = UTC time that corresponds to L0 = L0 - LocalTZA,
127     // U1 = UTC time that corresponds to L1 = L1 - LocalTZA,
128     // U1 = UTC time that corresponds to L2 = L2 - LocalTZA - hour.
129     // Note that DST(U0 - hour) = 0, DST(U0) = 0, DST(U1) = 1.
130     // U0 = L0 - LocalTZA - DST(L0 - LocalTZA - hour),
131     // U1 = L1 - LocalTZA - DST(L1 - LocalTZA - hour),
132     // U1 = L2 - LocalTZA - DST(L2 - LocalTZA - hour).
133     //
134     // Consider transition from DST at local time L1.
135     // Let L0 = L1 - hour,
136     //     U1 = UTC time that corresponds to L1,
137     //     U0 = U1 - hour, U2 = U1 + hour.
138     // Transitioning from DST moves local clock one hour back L1 => L0, so
139     // U0 = UTC time that corresponds to L0 (before transition)
140     //    = L0 - LocalTZA - hour.
141     // U1 = UTC time that corresponds to L0 (after transition)
142     //    = L0 - LocalTZA = L1 - LocalTZA - hour
143     // U2 = UTC time that corresponds to L1 = L1 - LocalTZA.
144     // Note that DST(U0) = 1, DST(U1) = 0, DST(U2) = 0.
145     // U0 = L0 - LocalTZA - DST(L0 - LocalTZA - hour) = L0 - LocalTZA - DST(U0).
146     // U2 = L1 - LocalTZA - DST(L1 - LocalTZA - hour) = L1 - LocalTZA - DST(U1).
147     // It is impossible to get U1 from local time.
148 
149     const int kMsPerHour = 3600 * 1000;
150     time_ms -= LocalOffsetInMs();
151     return time_ms - DaylightSavingsOffsetInMs(time_ms - kMsPerHour);
152   }
153 
154 
155   // Computes a time equivalent to the given time according
156   // to ECMA 262 - 15.9.1.9.
157   // The issue here is that some library calls don't work right for dates
158   // that cannot be represented using a non-negative signed 32 bit integer
159   // (measured in whole seconds based on the 1970 epoch).
160   // We solve this by mapping the time to a year with same leap-year-ness
161   // and same starting day for the year. The ECMAscript specification says
162   // we must do this, but for compatibility with other browsers, we use
163   // the actual year if it is in the range 1970..2037
EquivalentTime(int64_t time_ms)164   int64_t EquivalentTime(int64_t time_ms) {
165     int days = DaysFromTime(time_ms);
166     int time_within_day_ms = static_cast<int>(time_ms - days * kMsPerDay);
167     int year, month, day;
168     YearMonthDayFromDays(days, &year, &month, &day);
169     int new_days = DaysFromYearMonth(EquivalentYear(year), month) + day - 1;
170     return static_cast<int64_t>(new_days) * kMsPerDay + time_within_day_ms;
171   }
172 
173   // Returns an equivalent year in the range [2008-2035] matching
174   // - leap year,
175   // - week day of first day.
176   // ECMA 262 - 15.9.1.9.
EquivalentYear(int year)177   int EquivalentYear(int year) {
178     int week_day = Weekday(DaysFromYearMonth(year, 0));
179     int recent_year = (IsLeap(year) ? 1956 : 1967) + (week_day * 12) % 28;
180     // Find the year in the range 2008..2037 that is equivalent mod 28.
181     // Add 3*28 to give a positive argument to the modulus operator.
182     return 2008 + (recent_year + 3 * 28 - 2008) % 28;
183   }
184 
185   // Given the number of days since the epoch, computes
186   // the corresponding year, month, and day.
187   void YearMonthDayFromDays(int days, int* year, int* month, int* day);
188 
189   // Computes the number of days since the epoch for
190   // the first day of the given month in the given year.
191   int DaysFromYearMonth(int year, int month);
192 
193   // Cache stamp is used for invalidating caches in JSDate.
194   // We increment the stamp each time when the timezone information changes.
195   // JSDate objects perform stamp check and invalidate their caches if
196   // their saved stamp is not equal to the current stamp.
stamp()197   Smi* stamp() { return stamp_; }
stamp_address()198   void* stamp_address() { return &stamp_; }
199 
200   // These functions are virtual so that we can override them when testing.
GetDaylightSavingsOffsetFromOS(int64_t time_sec)201   virtual int GetDaylightSavingsOffsetFromOS(int64_t time_sec) {
202     double time_ms = static_cast<double>(time_sec * 1000);
203     return static_cast<int>(
204         base::OS::DaylightSavingsOffset(time_ms, tz_cache_));
205   }
206 
GetLocalOffsetFromOS()207   virtual int GetLocalOffsetFromOS() {
208     double offset = base::OS::LocalTimeOffset(tz_cache_);
209     DCHECK(offset < kInvalidLocalOffsetInMs);
210     return static_cast<int>(offset);
211   }
212 
213  private:
214   // The implementation relies on the fact that no time zones have
215   // more than one daylight savings offset change per 19 days.
216   // In Egypt in 2010 they decided to suspend DST during Ramadan. This
217   // led to a short interval where DST is in effect from September 10 to
218   // September 30.
219   static const int kDefaultDSTDeltaInSec = 19 * kSecPerDay;
220 
221   // Size of the Daylight Savings Time cache.
222   static const int kDSTSize = 32;
223 
224   // Daylight Savings Time segment stores a segment of time where
225   // daylight savings offset does not change.
226   struct DST {
227     int start_sec;
228     int end_sec;
229     int offset_ms;
230     int last_used;
231   };
232 
233   // Computes the daylight savings offset for the given time.
234   // ECMA 262 - 15.9.1.8
235   int DaylightSavingsOffsetInMs(int64_t time_ms);
236 
237   // Sets the before_ and the after_ segments from the DST cache such that
238   // the before_ segment starts earlier than the given time and
239   // the after_ segment start later than the given time.
240   // Both segments might be invalid.
241   // The last_used counters of the before_ and after_ are updated.
242   void ProbeDST(int time_sec);
243 
244   // Finds the least recently used segment from the DST cache that is not
245   // equal to the given 'skip' segment.
246   DST* LeastRecentlyUsedDST(DST* skip);
247 
248   // Extends the after_ segment with the given point or resets it
249   // if it starts later than the given time + kDefaultDSTDeltaInSec.
250   inline void ExtendTheAfterSegment(int time_sec, int offset_ms);
251 
252   // Makes the given segment invalid.
253   inline void ClearSegment(DST* segment);
254 
InvalidSegment(DST * segment)255   bool InvalidSegment(DST* segment) {
256     return segment->start_sec > segment->end_sec;
257   }
258 
259   Smi* stamp_;
260 
261   // Daylight Saving Time cache.
262   DST dst_[kDSTSize];
263   int dst_usage_counter_;
264   DST* before_;
265   DST* after_;
266 
267   int local_offset_ms_;
268 
269   // Year/Month/Day cache.
270   bool ymd_valid_;
271   int ymd_days_;
272   int ymd_year_;
273   int ymd_month_;
274   int ymd_day_;
275 
276   base::TimezoneCache* tz_cache_;
277 };
278 
279 } }   // namespace v8::internal
280 
281 #endif
282