| 1 |
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- |
| 2 |
* vim: set ts=8 sts=2 et sw=2 tw=80: |
| 3 |
* This Source Code Form is subject to the terms of the Mozilla Public |
| 4 |
* License, v. 2.0. If a copy of the MPL was not distributed with this |
| 5 |
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
| 6 |
|
| 7 |
#ifndef vm_DateTime_h |
| 8 |
#define vm_DateTime_h |
| 9 |
|
| 10 |
#include "mozilla/Atomics.h" |
| 11 |
#include "mozilla/UniquePtr.h" |
| 12 |
|
| 13 |
#include <stdint.h> |
| 14 |
|
| 15 |
#include "js/Utility.h" |
| 16 |
#include "threading/ExclusiveData.h" |
| 17 |
|
| 18 |
#if JS_HAS_INTL_API |
| 19 |
# include "mozilla/intl/ICU4CGlue.h" |
| 20 |
# include "mozilla/intl/TimeZone.h" |
| 21 |
#endif |
| 22 |
|
| 23 |
namespace JS { |
| 24 |
class Realm; |
| 25 |
} |
| 26 |
|
| 27 |
namespace js { |
| 28 |
|
| 29 |
/** |
| 30 |
* 21.4.1.2 Time-related Constants |
| 31 |
* |
| 32 |
* ES2025 draft rev 76814cbd5d7842c2a99d28e6e8c7833f1de5bee0 |
| 33 |
*/ |
| 34 |
constexpr int32_t HoursPerDay = 24; |
| 35 |
constexpr int32_t MinutesPerHour = 60; |
| 36 |
constexpr int32_t SecondsPerMinute = 60; |
| 37 |
constexpr int32_t msPerSecond = 1000; |
| 38 |
constexpr int32_t msPerMinute = msPerSecond * SecondsPerMinute; |
| 39 |
constexpr int32_t msPerHour = msPerMinute * MinutesPerHour; |
| 40 |
constexpr int32_t msPerDay = msPerHour * HoursPerDay; |
| 41 |
|
| 42 |
/* |
| 43 |
* Additional quantities not mentioned in the spec. |
| 44 |
*/ |
| 45 |
constexpr int32_t SecondsPerHour = 60 * 60; |
| 46 |
constexpr int32_t SecondsPerDay = SecondsPerHour * 24; |
| 47 |
|
| 48 |
constexpr double StartOfTime = -8.64e15; |
| 49 |
constexpr double EndOfTime = 8.64e15; |
| 50 |
|
| 51 |
extern bool InitDateTimeState(); |
| 52 |
|
| 53 |
extern void FinishDateTimeState(); |
| 54 |
|
| 55 |
enum class ResetTimeZoneMode : bool { |
| 56 |
DontResetIfOffsetUnchanged, |
| 57 |
ResetEvenIfOffsetUnchanged, |
| 58 |
}; |
| 59 |
|
| 60 |
/** |
| 61 |
* Engine-internal variant of JS::ResetTimeZone with an additional flag to |
| 62 |
* control whether to forcibly reset all time zone data (this is the default |
| 63 |
* behavior when calling JS::ResetTimeZone) or to try to reuse the previous |
| 64 |
* time zone data. |
| 65 |
*/ |
| 66 |
extern void ResetTimeZoneInternal(ResetTimeZoneMode mode); |
| 67 |
|
| 68 |
/** |
| 69 |
* Stores date/time information, particularly concerning the current local |
| 70 |
* time zone, and implements a small cache for daylight saving time offset |
| 71 |
* computation. |
| 72 |
* |
| 73 |
* The basic idea is premised upon this fact: the DST offset never changes more |
| 74 |
* than once in any thirty-day period. If we know the offset at t_0 is o_0, |
| 75 |
* the offset at [t_1, t_2] is also o_0, where t_1 + 3_0 days == t_2, |
| 76 |
* t_1 <= t_0, and t0 <= t2. (In other words, t_0 is always somewhere within a |
| 77 |
* thirty-day range where the DST offset is constant: DST changes never occur |
| 78 |
* more than once in any thirty-day period.) Therefore, if we intelligently |
| 79 |
* retain knowledge of the offset for a range of dates (which may vary over |
| 80 |
* time), and if requests are usually for dates within that range, we can often |
| 81 |
* provide a response without repeated offset calculation. |
| 82 |
* |
| 83 |
* Our caching strategy is as follows: on the first request at date t_0 compute |
| 84 |
* the requested offset o_0. Save { start: t_0, end: t_0, offset: o_0 } as the |
| 85 |
* cache's state. Subsequent requests within that range are straightforwardly |
| 86 |
* handled. If a request for t_i is far outside the range (more than thirty |
| 87 |
* days), compute o_i = dstOffset(t_i) and save { start: t_i, end: t_i, |
| 88 |
* offset: t_i }. Otherwise attempt to *overextend* the range to either |
| 89 |
* [start - 30d, end] or [start, end + 30d] as appropriate to encompass |
| 90 |
* t_i. If the offset o_i30 is the same as the cached offset, extend the |
| 91 |
* range. Otherwise the over-guess crossed a DST change -- compute |
| 92 |
* o_i = dstOffset(t_i) and either extend the original range (if o_i == offset) |
| 93 |
* or start a new one beneath/above the current one with o_i30 as the offset. |
| 94 |
* |
| 95 |
* This cache strategy results in 0 to 2 DST offset computations. The naive |
| 96 |
* always-compute strategy is 1 computation, and since cache maintenance is a |
| 97 |
* handful of integer arithmetic instructions the speed difference between |
| 98 |
* always-1 and 1-with-cache is negligible. Caching loses if two computations |
| 99 |
* happen: when the date is within 30 days of the cached range and when that |
| 100 |
* 30-day range crosses a DST change. This is relatively uncommon. Further, |
| 101 |
* instances of such are often dominated by in-range hits, so caching is an |
| 102 |
* overall slight win. |
| 103 |
* |
| 104 |
* Why 30 days? For correctness the duration must be smaller than any possible |
| 105 |
* duration between DST changes. Past that, note that 1) a large duration |
| 106 |
* increases the likelihood of crossing a DST change while reducing the number |
| 107 |
* of cache misses, and 2) a small duration decreases the size of the cached |
| 108 |
* range while producing more misses. Using a month as the interval change is |
| 109 |
* a balance between these two that tries to optimize for the calendar month at |
| 110 |
* a time that a site might display. (One could imagine an adaptive duration |
| 111 |
* that accommodates near-DST-change dates better; we don't believe the |
| 112 |
* potential win from better caching offsets the loss from extra complexity.) |
| 113 |
*/ |
| 114 |
class DateTimeInfo { |
| 115 |
public: |
| 116 |
// For realms that force the UTC time zone (for fingerprinting protection) a |
| 117 |
// separate DateTimeInfo instance is used that is always in the UTC time zone. |
| 118 |
enum class ForceUTC { No, Yes }; |
| 119 |
|
| 120 |
private: |
| 121 |
static ExclusiveData<DateTimeInfo>* instance; |
| 122 |
static ExclusiveData<DateTimeInfo>* instanceUTC; |
| 123 |
|
| 124 |
static constexpr int32_t InvalidOffset = INT32_MIN; |
| 125 |
|
| 126 |
// Additional cache to avoid the mutex overhead. Uses "relaxed" semantics |
| 127 |
// because it's acceptable if time zone offset changes aren't propagated right |
| 128 |
// away to all other threads. |
| 129 |
static inline mozilla::Atomic<int32_t, mozilla::Relaxed> |
| 130 |
utcToLocalOffsetSeconds{InvalidOffset}; |
| 131 |
|
| 132 |
friend class ExclusiveData<DateTimeInfo>; |
| 133 |
|
| 134 |
friend bool InitDateTimeState(); |
| 135 |
friend void FinishDateTimeState(); |
| 136 |
|
| 137 |
explicit DateTimeInfo(bool forceUTC); |
| 138 |
~DateTimeInfo(); |
| 139 |
|
| 140 |
static auto acquireLockWithValidTimeZone(ForceUTC forceUTC) { |
| 141 |
auto guard = |
| 142 |
forceUTC == ForceUTC::Yes ? instanceUTC->lock() : instance->lock(); |
| 143 |
if (guard->timeZoneStatus_ != TimeZoneStatus::Valid) { |
| 144 |
guard->updateTimeZone(); |
| 145 |
} |
| 146 |
return guard; |
| 147 |
} |
| 148 |
|
| 149 |
public: |
| 150 |
static ForceUTC forceUTC(JS::Realm* realm); |
| 151 |
|
| 152 |
// The spec implicitly assumes DST and time zone adjustment information |
| 153 |
// never change in the course of a function -- sometimes even across |
| 154 |
// reentrancy. So make critical sections as narrow as possible. |
| 155 |
|
| 156 |
/** |
| 157 |
* Get the DST offset in milliseconds at a UTC time. This is usually |
| 158 |
* either 0 or |msPerSecond * SecondsPerHour|, but at least one exotic time |
| 159 |
* zone (Lord Howe Island, Australia) has a fractional-hour offset, just to |
| 160 |
* keep things interesting. |
| 161 |
*/ |
| 162 |
static int32_t getDSTOffsetMilliseconds(ForceUTC forceUTC, |
| 163 |
int64_t utcMilliseconds) { |
| 164 |
auto guard = acquireLockWithValidTimeZone(forceUTC); |
| 165 |
return guard->internalGetDSTOffsetMilliseconds(utcMilliseconds); |
| 166 |
} |
| 167 |
|
| 168 |
/** |
| 169 |
* The offset in seconds from the current UTC time to the current local |
| 170 |
* standard time (i.e. not including any offset due to DST) as computed by the |
| 171 |
* operating system. |
| 172 |
*/ |
| 173 |
static int32_t utcToLocalStandardOffsetSeconds(ForceUTC forceUTC) { |
| 174 |
// UTC offset is always zero. |
| 175 |
if (forceUTC == ForceUTC::Yes) { |
| 176 |
return 0; |
| 177 |
} |
| 178 |
|
| 179 |
// First try the cached offset to avoid any mutex overhead. |
| 180 |
int32_t offset = utcToLocalOffsetSeconds; |
| 181 |
if (offset != InvalidOffset) { |
| 182 |
return offset; |
| 183 |
} |
| 184 |
|
| 185 |
// If that fails, use the mutex-synchronized code path. |
| 186 |
auto guard = acquireLockWithValidTimeZone(forceUTC); |
| 187 |
offset = guard->utcToLocalStandardOffsetSeconds_; |
| 188 |
utcToLocalOffsetSeconds = offset; |
| 189 |
return offset; |
| 190 |
} |
| 191 |
|
| 192 |
enum class TimeZoneOffset { UTC, Local }; |
| 193 |
|
| 194 |
#if JS_HAS_INTL_API |
| 195 |
/** |
| 196 |
* Return the time zone offset, including DST, in milliseconds at the |
| 197 |
* given time. The input time can be either at UTC or at local time. |
| 198 |
*/ |
| 199 |
static int32_t getOffsetMilliseconds(ForceUTC forceUTC, int64_t milliseconds, |
| 200 |
TimeZoneOffset offset) { |
| 201 |
auto guard = acquireLockWithValidTimeZone(forceUTC); |
| 202 |
return guard->internalGetOffsetMilliseconds(milliseconds, offset); |
| 203 |
} |
| 204 |
|
| 205 |
/** |
| 206 |
* Copy the display name for the current time zone at the given time, |
| 207 |
* localized for the specified locale, into the supplied buffer. If the |
| 208 |
* buffer is too small, an empty string is stored. The stored display name |
| 209 |
* is null-terminated in any case. |
| 210 |
*/ |
| 211 |
static bool timeZoneDisplayName(ForceUTC forceUTC, char16_t* buf, |
| 212 |
size_t buflen, int64_t utcMilliseconds, |
| 213 |
const char* locale) { |
| 214 |
auto guard = acquireLockWithValidTimeZone(forceUTC); |
| 215 |
return guard->internalTimeZoneDisplayName(buf, buflen, utcMilliseconds, |
| 216 |
locale); |
| 217 |
} |
| 218 |
|
| 219 |
/** |
| 220 |
* Copy the identifier for the current time zone to the provided resizable |
| 221 |
* buffer. |
| 222 |
*/ |
| 223 |
template <typename B> |
| 224 |
static mozilla::intl::ICUResult timeZoneId(ForceUTC forceUTC, B& buffer) { |
| 225 |
auto guard = acquireLockWithValidTimeZone(forceUTC); |
| 226 |
return guard->timeZone()->GetId(buffer); |
| 227 |
} |
| 228 |
|
| 229 |
/** |
| 230 |
* A number indicating the raw offset from GMT in milliseconds. |
| 231 |
*/ |
| 232 |
static mozilla::Result<int32_t, mozilla::intl::ICUError> getRawOffsetMs( |
| 233 |
ForceUTC forceUTC) { |
| 234 |
auto guard = acquireLockWithValidTimeZone(forceUTC); |
| 235 |
return guard->timeZone()->GetRawOffsetMs(); |
| 236 |
} |
| 237 |
#else |
| 238 |
/** |
| 239 |
* Return the local time zone adjustment (ES2019 20.3.1.7) as computed by |
| 240 |
* the operating system. |
| 241 |
*/ |
| 242 |
static int32_t localTZA(ForceUTC forceUTC) { |
| 243 |
return utcToLocalStandardOffsetSeconds(forceUTC) * msPerSecond; |
| 244 |
} |
| 245 |
#endif /* JS_HAS_INTL_API */ |
| 246 |
|
| 247 |
// JIT access. |
| 248 |
static const void* addressOfUTCToLocalOffsetSeconds() { |
| 249 |
static_assert(sizeof(decltype(utcToLocalOffsetSeconds)) == sizeof(int32_t)); |
| 250 |
return &DateTimeInfo::utcToLocalOffsetSeconds; |
| 251 |
} |
| 252 |
|
| 253 |
private: |
| 254 |
// The method below should only be called via js::ResetTimeZoneInternal(). |
| 255 |
friend void js::ResetTimeZoneInternal(ResetTimeZoneMode); |
| 256 |
|
| 257 |
static void resetTimeZone(ResetTimeZoneMode mode) { |
| 258 |
{ |
| 259 |
auto guard = instance->lock(); |
| 260 |
guard->internalResetTimeZone(mode); |
| 261 |
|
| 262 |
// Mark the cached value as invalid. |
| 263 |
utcToLocalOffsetSeconds = InvalidOffset; |
| 264 |
} |
| 265 |
{ |
| 266 |
// Only needed to initialize the default state and any later call will |
| 267 |
// perform an unnecessary reset. |
| 268 |
auto guard = instanceUTC->lock(); |
| 269 |
guard->internalResetTimeZone(mode); |
| 270 |
} |
| 271 |
} |
| 272 |
|
| 273 |
struct RangeCache { |
| 274 |
// Start and end offsets in seconds describing the current and the |
| 275 |
// last cached range. |
| 276 |
int64_t startSeconds, endSeconds; |
| 277 |
int64_t oldStartSeconds, oldEndSeconds; |
| 278 |
|
| 279 |
// The current and the last cached offset in milliseconds. |
| 280 |
int32_t offsetMilliseconds; |
| 281 |
int32_t oldOffsetMilliseconds; |
| 282 |
|
| 283 |
void reset(); |
| 284 |
|
| 285 |
void sanityCheck(); |
| 286 |
}; |
| 287 |
|
| 288 |
bool forceUTC_; |
| 289 |
|
| 290 |
enum class TimeZoneStatus : uint8_t { Valid, NeedsUpdate, UpdateIfChanged }; |
| 291 |
|
| 292 |
TimeZoneStatus timeZoneStatus_; |
| 293 |
|
| 294 |
/** |
| 295 |
* The offset in seconds from the current UTC time to the current local |
| 296 |
* standard time (i.e. not including any offset due to DST) as computed by the |
| 297 |
* operating system. |
| 298 |
* |
| 299 |
* Cached because retrieving this dynamically is Slow, and a certain venerable |
| 300 |
* benchmark which shall not be named depends on it being fast. |
| 301 |
* |
| 302 |
* SpiderMonkey occasionally and arbitrarily updates this value from the |
| 303 |
* system time zone to attempt to keep this reasonably up-to-date. If |
| 304 |
* temporary inaccuracy can't be tolerated, JSAPI clients may call |
| 305 |
* JS::ResetTimeZone to forcibly sync this with the system time zone. |
| 306 |
* |
| 307 |
* In most cases this value is consistent with the raw time zone offset as |
| 308 |
* returned by the ICU default time zone (`icu::TimeZone::getRawOffset()`), |
| 309 |
* but it is possible to create cases where the operating system default time |
| 310 |
* zone differs from the ICU default time zone. For example ICU doesn't |
| 311 |
* support the full range of TZ environment variable settings, which can |
| 312 |
* result in <ctime> returning a different time zone than what's returned by |
| 313 |
* ICU. One example is "TZ=WGT3WGST,M3.5.0/-2,M10.5.0/-1", where <ctime> |
| 314 |
* returns -3 hours as the local offset, but ICU flat out rejects the TZ value |
| 315 |
* and instead infers the default time zone via "/etc/localtime" (on Unix). |
| 316 |
* This offset can also differ from ICU when the operating system and ICU use |
| 317 |
* different tzdata versions and the time zone rules of the current system |
| 318 |
* time zone have changed. Or, on Windows, when the Windows default time zone |
| 319 |
* can't be mapped to a IANA time zone, see for example |
| 320 |
* <https://unicode-org.atlassian.net/browse/ICU-13845>. |
| 321 |
* |
| 322 |
* When ICU is exclusively used for time zone computations, that means when |
| 323 |
* |JS_HAS_INTL_API| is true, this field is only used to detect system default |
| 324 |
* time zone changes. It must not be used to convert between local and UTC |
| 325 |
* time, because, as outlined above, this could lead to different results when |
| 326 |
* compared to ICU. |
| 327 |
*/ |
| 328 |
int32_t utcToLocalStandardOffsetSeconds_; |
| 329 |
|
| 330 |
RangeCache dstRange_; // UTC-based ranges |
| 331 |
|
| 332 |
#if JS_HAS_INTL_API |
| 333 |
// Use the full date-time range when we can use mozilla::intl::TimeZone. |
| 334 |
static constexpr int64_t MinTimeT = |
| 335 |
static_cast<int64_t>(StartOfTime / msPerSecond); |
| 336 |
static constexpr int64_t MaxTimeT = |
| 337 |
static_cast<int64_t>(EndOfTime / msPerSecond); |
| 338 |
|
| 339 |
RangeCache utcRange_; // localtime-based ranges |
| 340 |
RangeCache localRange_; // UTC-based ranges |
| 341 |
|
| 342 |
/** |
| 343 |
* The current time zone. Lazily constructed to avoid potential I/O access |
| 344 |
* when initializing this class. |
| 345 |
*/ |
| 346 |
mozilla::UniquePtr<mozilla::intl::TimeZone> timeZone_; |
| 347 |
|
| 348 |
/** |
| 349 |
* Cached names of the standard and daylight savings display names of the |
| 350 |
* current time zone for the default locale. |
| 351 |
*/ |
| 352 |
JS::UniqueChars locale_; |
| 353 |
JS::UniqueTwoByteChars standardName_; |
| 354 |
JS::UniqueTwoByteChars daylightSavingsName_; |
| 355 |
#else |
| 356 |
// Restrict the data-time range to the minimum required time_t range as |
| 357 |
// specified in POSIX. Most operating systems support 64-bit time_t |
| 358 |
// values, but we currently still have some configurations which use |
| 359 |
// 32-bit time_t, e.g. the ARM simulator on 32-bit Linux (bug 1406993). |
| 360 |
// Bug 1406992 explores to use 64-bit time_t when supported by the |
| 361 |
// underlying operating system. |
| 362 |
static constexpr int64_t MinTimeT = 0; /* time_t 01/01/1970 */ |
| 363 |
static constexpr int64_t MaxTimeT = 2145830400; /* time_t 12/31/2037 */ |
| 364 |
#endif /* JS_HAS_INTL_API */ |
| 365 |
|
| 366 |
static constexpr int64_t RangeExpansionAmount = 30 * SecondsPerDay; |
| 367 |
|
| 368 |
void internalResetTimeZone(ResetTimeZoneMode mode); |
| 369 |
|
| 370 |
void updateTimeZone(); |
| 371 |
|
| 372 |
void internalResyncICUDefaultTimeZone(); |
| 373 |
|
| 374 |
int64_t toClampedSeconds(int64_t milliseconds); |
| 375 |
|
| 376 |
using ComputeFn = int32_t (DateTimeInfo::*)(int64_t); |
| 377 |
|
| 378 |
/** |
| 379 |
* Get or compute an offset value for the requested seconds value. |
| 380 |
*/ |
| 381 |
int32_t getOrComputeValue(RangeCache& range, int64_t seconds, |
| 382 |
ComputeFn compute); |
| 383 |
|
| 384 |
/** |
| 385 |
* Compute the DST offset at the given UTC time in seconds from the epoch. |
| 386 |
* (getDSTOffsetMilliseconds attempts to return a cached value from the |
| 387 |
* dstRange_ member, but in case of a cache miss it calls this method.) |
| 388 |
*/ |
| 389 |
int32_t computeDSTOffsetMilliseconds(int64_t utcSeconds); |
| 390 |
|
| 391 |
int32_t internalGetDSTOffsetMilliseconds(int64_t utcMilliseconds); |
| 392 |
|
| 393 |
#if JS_HAS_INTL_API |
| 394 |
/** |
| 395 |
* Compute the UTC offset in milliseconds for the given local time. Called |
| 396 |
* by internalGetOffsetMilliseconds on a cache miss. |
| 397 |
*/ |
| 398 |
int32_t computeUTCOffsetMilliseconds(int64_t localSeconds); |
| 399 |
|
| 400 |
/** |
| 401 |
* Compute the local time offset in milliseconds for the given UTC time. |
| 402 |
* Called by internalGetOffsetMilliseconds on a cache miss. |
| 403 |
*/ |
| 404 |
int32_t computeLocalOffsetMilliseconds(int64_t utcSeconds); |
| 405 |
|
| 406 |
int32_t internalGetOffsetMilliseconds(int64_t milliseconds, |
| 407 |
TimeZoneOffset offset); |
| 408 |
|
| 409 |
bool internalTimeZoneDisplayName(char16_t* buf, size_t buflen, |
| 410 |
int64_t utcMilliseconds, const char* locale); |
| 411 |
|
| 412 |
mozilla::intl::TimeZone* timeZone(); |
| 413 |
#endif /* JS_HAS_INTL_API */ |
| 414 |
}; |
| 415 |
|
| 416 |
} /* namespace js */ |
| 417 |
|
| 418 |
#endif /* vm_DateTime_h */ |