PageRenderTime 37ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/js/lib/Socket.IO-node/support/expresso/deps/jscoverage/js/prmjtime.cpp

http://github.com/onedayitwillmake/RealtimeMultiplayerNodeJs
C++ | 846 lines | 496 code | 118 blank | 232 comment | 58 complexity | 24cba67ab368621d97c7032e5a7025ce MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1, MPL-2.0-no-copyleft-exception, BSD-3-Clause
  1. /* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  2. *
  3. * ***** BEGIN LICENSE BLOCK *****
  4. * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  5. *
  6. * The contents of this file are subject to the Mozilla Public License Version
  7. * 1.1 (the "License"); you may not use this file except in compliance with
  8. * the License. You may obtain a copy of the License at
  9. * http://www.mozilla.org/MPL/
  10. *
  11. * Software distributed under the License is distributed on an "AS IS" basis,
  12. * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  13. * for the specific language governing rights and limitations under the
  14. * License.
  15. *
  16. * The Original Code is Mozilla Communicator client code, released
  17. * March 31, 1998.
  18. *
  19. * The Initial Developer of the Original Code is
  20. * Netscape Communications Corporation.
  21. * Portions created by the Initial Developer are Copyright (C) 1998
  22. * the Initial Developer. All Rights Reserved.
  23. *
  24. * Contributor(s):
  25. *
  26. * Alternatively, the contents of this file may be used under the terms of
  27. * either of the GNU General Public License Version 2 or later (the "GPL"),
  28. * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  29. * in which case the provisions of the GPL or the LGPL are applicable instead
  30. * of those above. If you wish to allow use of your version of this file only
  31. * under the terms of either the GPL or the LGPL, and not to allow others to
  32. * use your version of this file under the terms of the MPL, indicate your
  33. * decision by deleting the provisions above and replace them with the notice
  34. * and other provisions required by the GPL or the LGPL. If you do not delete
  35. * the provisions above, a recipient may use your version of this file under
  36. * the terms of any one of the MPL, the GPL or the LGPL.
  37. *
  38. * ***** END LICENSE BLOCK ***** */
  39. /*
  40. * PR time code.
  41. */
  42. #include "jsstddef.h"
  43. #ifdef SOLARIS
  44. #define _REENTRANT 1
  45. #endif
  46. #include <string.h>
  47. #include <time.h>
  48. #include "jstypes.h"
  49. #include "jsutil.h"
  50. #include "jsprf.h"
  51. #include "jslock.h"
  52. #include "prmjtime.h"
  53. #define PRMJ_DO_MILLISECONDS 1
  54. #ifdef XP_OS2
  55. #include <sys/timeb.h>
  56. #endif
  57. #ifdef XP_WIN
  58. #include <windef.h>
  59. #include <winbase.h>
  60. #include <math.h> /* for fabs */
  61. #include <mmsystem.h> /* for timeBegin/EndPeriod */
  62. /* VC++ 8.0 or later, and not WINCE */
  63. #if _MSC_VER >= 1400 && !defined(WINCE)
  64. #define NS_HAVE_INVALID_PARAMETER_HANDLER 1
  65. #endif
  66. #ifdef NS_HAVE_INVALID_PARAMETER_HANDLER
  67. #include <stdlib.h> /* for _set_invalid_parameter_handler */
  68. #include <crtdbg.h> /* for _CrtSetReportMode */
  69. #endif
  70. #ifdef JS_THREADSAFE
  71. #include <prinit.h>
  72. #endif
  73. #endif
  74. #if defined(XP_UNIX) || defined(XP_BEOS)
  75. #ifdef _SVID_GETTOD /* Defined only on Solaris, see Solaris <sys/types.h> */
  76. extern int gettimeofday(struct timeval *tv);
  77. #endif
  78. #include <sys/time.h>
  79. #endif /* XP_UNIX */
  80. #define PRMJ_YEAR_DAYS 365L
  81. #define PRMJ_FOUR_YEARS_DAYS (4 * PRMJ_YEAR_DAYS + 1)
  82. #define PRMJ_CENTURY_DAYS (25 * PRMJ_FOUR_YEARS_DAYS - 1)
  83. #define PRMJ_FOUR_CENTURIES_DAYS (4 * PRMJ_CENTURY_DAYS + 1)
  84. #define PRMJ_HOUR_SECONDS 3600L
  85. #define PRMJ_DAY_SECONDS (24L * PRMJ_HOUR_SECONDS)
  86. #define PRMJ_YEAR_SECONDS (PRMJ_DAY_SECONDS * PRMJ_YEAR_DAYS)
  87. #define PRMJ_MAX_UNIX_TIMET 2145859200L /*time_t value equiv. to 12/31/2037 */
  88. /* function prototypes */
  89. static void PRMJ_basetime(JSInt64 tsecs, PRMJTime *prtm);
  90. /*
  91. * get the difference in seconds between this time zone and UTC (GMT)
  92. */
  93. JSInt32
  94. PRMJ_LocalGMTDifference()
  95. {
  96. struct tm ltime;
  97. /* get the difference between this time zone and GMT */
  98. memset((char *)&ltime,0,sizeof(ltime));
  99. ltime.tm_mday = 2;
  100. ltime.tm_year = 70;
  101. return (JSInt32)mktime(&ltime) - (24L * 3600L);
  102. }
  103. /* Constants for GMT offset from 1970 */
  104. #define G1970GMTMICROHI 0x00dcdcad /* micro secs to 1970 hi */
  105. #define G1970GMTMICROLOW 0x8b3fa000 /* micro secs to 1970 low */
  106. #define G2037GMTMICROHI 0x00e45fab /* micro secs to 2037 high */
  107. #define G2037GMTMICROLOW 0x7a238000 /* micro secs to 2037 low */
  108. /* Convert from base time to extended time */
  109. static JSInt64
  110. PRMJ_ToExtendedTime(JSInt32 base_time)
  111. {
  112. JSInt64 exttime;
  113. JSInt64 g1970GMTMicroSeconds;
  114. JSInt64 low;
  115. JSInt32 diff;
  116. JSInt64 tmp;
  117. JSInt64 tmp1;
  118. diff = PRMJ_LocalGMTDifference();
  119. JSLL_UI2L(tmp, PRMJ_USEC_PER_SEC);
  120. JSLL_I2L(tmp1,diff);
  121. JSLL_MUL(tmp,tmp,tmp1);
  122. JSLL_UI2L(g1970GMTMicroSeconds,G1970GMTMICROHI);
  123. JSLL_UI2L(low,G1970GMTMICROLOW);
  124. #ifndef JS_HAVE_LONG_LONG
  125. JSLL_SHL(g1970GMTMicroSeconds,g1970GMTMicroSeconds,16);
  126. JSLL_SHL(g1970GMTMicroSeconds,g1970GMTMicroSeconds,16);
  127. #else
  128. JSLL_SHL(g1970GMTMicroSeconds,g1970GMTMicroSeconds,32);
  129. #endif
  130. JSLL_ADD(g1970GMTMicroSeconds,g1970GMTMicroSeconds,low);
  131. JSLL_I2L(exttime,base_time);
  132. JSLL_ADD(exttime,exttime,g1970GMTMicroSeconds);
  133. JSLL_SUB(exttime,exttime,tmp);
  134. return exttime;
  135. }
  136. #ifdef XP_WIN
  137. typedef struct CalibrationData
  138. {
  139. long double freq; /* The performance counter frequency */
  140. long double offset; /* The low res 'epoch' */
  141. long double timer_offset; /* The high res 'epoch' */
  142. /* The last high res time that we returned since recalibrating */
  143. JSInt64 last;
  144. JSBool calibrated;
  145. #ifdef JS_THREADSAFE
  146. CRITICAL_SECTION data_lock;
  147. CRITICAL_SECTION calibration_lock;
  148. #endif
  149. } CalibrationData;
  150. static const JSInt64 win2un = JSLL_INIT(0x19DB1DE, 0xD53E8000);
  151. static CalibrationData calibration = { 0 };
  152. #define FILETIME2INT64(ft) (((JSInt64)ft.dwHighDateTime) << 32LL | (JSInt64)ft.dwLowDateTime)
  153. static void
  154. NowCalibrate()
  155. {
  156. FILETIME ft, ftStart;
  157. LARGE_INTEGER liFreq, now;
  158. if (calibration.freq == 0.0) {
  159. if(!QueryPerformanceFrequency(&liFreq)) {
  160. /* High-performance timer is unavailable */
  161. calibration.freq = -1.0;
  162. } else {
  163. calibration.freq = (long double) liFreq.QuadPart;
  164. }
  165. }
  166. if (calibration.freq > 0.0) {
  167. JSInt64 calibrationDelta = 0;
  168. /* By wrapping a timeBegin/EndPeriod pair of calls around this loop,
  169. the loop seems to take much less time (1 ms vs 15ms) on Vista. */
  170. timeBeginPeriod(1);
  171. GetSystemTimeAsFileTime(&ftStart);
  172. do {
  173. GetSystemTimeAsFileTime(&ft);
  174. } while (memcmp(&ftStart,&ft, sizeof(ft)) == 0);
  175. timeEndPeriod(1);
  176. /*
  177. calibrationDelta = (FILETIME2INT64(ft) - FILETIME2INT64(ftStart))/10;
  178. fprintf(stderr, "Calibration delta was %I64d us\n", calibrationDelta);
  179. */
  180. QueryPerformanceCounter(&now);
  181. calibration.offset = (long double) FILETIME2INT64(ft);
  182. calibration.timer_offset = (long double) now.QuadPart;
  183. /* The windows epoch is around 1600. The unix epoch is around
  184. 1970. win2un is the difference (in windows time units which
  185. are 10 times more highres than the JS time unit) */
  186. calibration.offset -= win2un;
  187. calibration.offset *= 0.1;
  188. calibration.last = 0;
  189. calibration.calibrated = JS_TRUE;
  190. }
  191. }
  192. #define CALIBRATIONLOCK_SPINCOUNT 0
  193. #define DATALOCK_SPINCOUNT 4096
  194. #define LASTLOCK_SPINCOUNT 4096
  195. #ifdef JS_THREADSAFE
  196. static PRStatus
  197. NowInit(void)
  198. {
  199. memset(&calibration, 0, sizeof(calibration));
  200. NowCalibrate();
  201. InitializeCriticalSectionAndSpinCount(&calibration.calibration_lock, CALIBRATIONLOCK_SPINCOUNT);
  202. InitializeCriticalSectionAndSpinCount(&calibration.data_lock, DATALOCK_SPINCOUNT);
  203. return PR_SUCCESS;
  204. }
  205. void
  206. PRMJ_NowShutdown()
  207. {
  208. DeleteCriticalSection(&calibration.calibration_lock);
  209. DeleteCriticalSection(&calibration.data_lock);
  210. }
  211. #define MUTEX_LOCK(m) EnterCriticalSection(m)
  212. #define MUTEX_TRYLOCK(m) TryEnterCriticalSection(m)
  213. #define MUTEX_UNLOCK(m) LeaveCriticalSection(m)
  214. #define MUTEX_SETSPINCOUNT(m, c) SetCriticalSectionSpinCount((m),(c))
  215. static PRCallOnceType calibrationOnce = { 0 };
  216. #else
  217. #define MUTEX_LOCK(m)
  218. #define MUTEX_TRYLOCK(m) 1
  219. #define MUTEX_UNLOCK(m)
  220. #define MUTEX_SETSPINCOUNT(m, c)
  221. #endif
  222. #endif /* XP_WIN */
  223. /*
  224. Win32 python-esque pseudo code
  225. Please see bug 363258 for why the win32 timing code is so complex.
  226. calibration mutex : Win32CriticalSection(spincount=0)
  227. data mutex : Win32CriticalSection(spincount=4096)
  228. def NowInit():
  229. init mutexes
  230. PRMJ_NowCalibration()
  231. def NowCalibration():
  232. expensive up-to-15ms call
  233. def PRMJ_Now():
  234. returnedTime = 0
  235. needCalibration = False
  236. cachedOffset = 0.0
  237. calibrated = False
  238. PR_CallOnce(PRMJ_NowInit)
  239. do
  240. if not global.calibrated or needCalibration:
  241. acquire calibration mutex
  242. acquire data mutex
  243. // Only recalibrate if someone didn't already
  244. if cachedOffset == calibration.offset:
  245. // Have all waiting threads immediately wait
  246. set data mutex spin count = 0
  247. PRMJ_NowCalibrate()
  248. calibrated = 1
  249. set data mutex spin count = default
  250. release data mutex
  251. release calibration mutex
  252. calculate lowres time
  253. if highres timer available:
  254. acquire data mutex
  255. calculate highres time
  256. cachedOffset = calibration.offset
  257. highres time = calibration.last = max(highres time, calibration.last)
  258. release data mutex
  259. get kernel tick interval
  260. if abs(highres - lowres) < kernel tick:
  261. returnedTime = highres time
  262. needCalibration = False
  263. else:
  264. if calibrated:
  265. returnedTime = lowres
  266. needCalibration = False
  267. else:
  268. needCalibration = True
  269. else:
  270. returnedTime = lowres
  271. while needCalibration
  272. */
  273. JSInt64
  274. PRMJ_Now(void)
  275. {
  276. #ifdef XP_OS2
  277. JSInt64 s, us, ms2us, s2us;
  278. struct timeb b;
  279. #endif
  280. #ifdef XP_WIN
  281. static int nCalls = 0;
  282. long double lowresTime, highresTimerValue;
  283. FILETIME ft;
  284. LARGE_INTEGER now;
  285. JSBool calibrated = JS_FALSE;
  286. JSBool needsCalibration = JS_FALSE;
  287. JSInt64 returnedTime;
  288. long double cachedOffset = 0.0;
  289. #endif
  290. #if defined(XP_UNIX) || defined(XP_BEOS)
  291. struct timeval tv;
  292. JSInt64 s, us, s2us;
  293. #endif /* XP_UNIX */
  294. #ifdef XP_OS2
  295. ftime(&b);
  296. JSLL_UI2L(ms2us, PRMJ_USEC_PER_MSEC);
  297. JSLL_UI2L(s2us, PRMJ_USEC_PER_SEC);
  298. JSLL_UI2L(s, b.time);
  299. JSLL_UI2L(us, b.millitm);
  300. JSLL_MUL(us, us, ms2us);
  301. JSLL_MUL(s, s, s2us);
  302. JSLL_ADD(s, s, us);
  303. return s;
  304. #endif
  305. #ifdef XP_WIN
  306. /* To avoid regressing startup time (where high resolution is likely
  307. not needed), give the old behavior for the first few calls.
  308. This does not appear to be needed on Vista as the timeBegin/timeEndPeriod
  309. calls seem to immediately take effect. */
  310. int thiscall = JS_ATOMIC_INCREMENT(&nCalls);
  311. /* 10 seems to be the number of calls to load with a blank homepage */
  312. if (thiscall <= 10) {
  313. GetSystemTimeAsFileTime(&ft);
  314. return (FILETIME2INT64(ft)-win2un)/10L;
  315. }
  316. /* For non threadsafe platforms, NowInit is not necessary */
  317. #ifdef JS_THREADSAFE
  318. PR_CallOnce(&calibrationOnce, NowInit);
  319. #endif
  320. do {
  321. if (!calibration.calibrated || needsCalibration) {
  322. MUTEX_LOCK(&calibration.calibration_lock);
  323. MUTEX_LOCK(&calibration.data_lock);
  324. /* Recalibrate only if no one else did before us */
  325. if(calibration.offset == cachedOffset) {
  326. /* Since calibration can take a while, make any other
  327. threads immediately wait */
  328. MUTEX_SETSPINCOUNT(&calibration.data_lock, 0);
  329. NowCalibrate();
  330. calibrated = JS_TRUE;
  331. /* Restore spin count */
  332. MUTEX_SETSPINCOUNT(&calibration.data_lock, DATALOCK_SPINCOUNT);
  333. }
  334. MUTEX_UNLOCK(&calibration.data_lock);
  335. MUTEX_UNLOCK(&calibration.calibration_lock);
  336. }
  337. /* Calculate a low resolution time */
  338. GetSystemTimeAsFileTime(&ft);
  339. lowresTime = 0.1*(long double)(FILETIME2INT64(ft) - win2un);
  340. if (calibration.freq > 0.0) {
  341. long double highresTime, diff;
  342. DWORD timeAdjustment, timeIncrement;
  343. BOOL timeAdjustmentDisabled;
  344. /* Default to 15.625 ms if the syscall fails */
  345. long double skewThreshold = 15625.25;
  346. /* Grab high resolution time */
  347. QueryPerformanceCounter(&now);
  348. highresTimerValue = (long double)now.QuadPart;
  349. MUTEX_LOCK(&calibration.data_lock);
  350. highresTime = calibration.offset + PRMJ_USEC_PER_SEC*
  351. (highresTimerValue-calibration.timer_offset)/calibration.freq;
  352. cachedOffset = calibration.offset;
  353. /* On some dual processor/core systems, we might get an earlier time
  354. so we cache the last time that we returned */
  355. calibration.last = max(calibration.last,(JSInt64)highresTime);
  356. returnedTime = calibration.last;
  357. MUTEX_UNLOCK(&calibration.data_lock);
  358. /* Rather than assume the NT kernel ticks every 15.6ms, ask it */
  359. if (GetSystemTimeAdjustment(&timeAdjustment,
  360. &timeIncrement,
  361. &timeAdjustmentDisabled)) {
  362. if (timeAdjustmentDisabled) {
  363. /* timeAdjustment is in units of 100ns */
  364. skewThreshold = timeAdjustment/10.0;
  365. } else {
  366. /* timeIncrement is in units of 100ns */
  367. skewThreshold = timeIncrement/10.0;
  368. }
  369. }
  370. /* Check for clock skew */
  371. diff = lowresTime - highresTime;
  372. /* For some reason that I have not determined, the skew can be
  373. up to twice a kernel tick. This does not seem to happen by
  374. itself, but I have only seen it triggered by another program
  375. doing some kind of file I/O. The symptoms are a negative diff
  376. followed by an equally large positive diff. */
  377. if (fabs(diff) > 2*skewThreshold) {
  378. /*fprintf(stderr,"Clock skew detected (diff = %f)!\n", diff);*/
  379. if (calibrated) {
  380. /* If we already calibrated once this instance, and the
  381. clock is still skewed, then either the processor(s) are
  382. wildly changing clockspeed or the system is so busy that
  383. we get switched out for long periods of time. In either
  384. case, it would be infeasible to make use of high
  385. resolution results for anything, so let's resort to old
  386. behavior for this call. It's possible that in the
  387. future, the user will want the high resolution timer, so
  388. we don't disable it entirely. */
  389. returnedTime = (JSInt64)lowresTime;
  390. needsCalibration = JS_FALSE;
  391. } else {
  392. /* It is possible that when we recalibrate, we will return a
  393. value less than what we have returned before; this is
  394. unavoidable. We cannot tell the different between a
  395. faulty QueryPerformanceCounter implementation and user
  396. changes to the operating system time. Since we must
  397. respect user changes to the operating system time, we
  398. cannot maintain the invariant that Date.now() never
  399. decreases; the old implementation has this behavior as
  400. well. */
  401. needsCalibration = JS_TRUE;
  402. }
  403. } else {
  404. /* No detectable clock skew */
  405. returnedTime = (JSInt64)highresTime;
  406. needsCalibration = JS_FALSE;
  407. }
  408. } else {
  409. /* No high resolution timer is available, so fall back */
  410. returnedTime = (JSInt64)lowresTime;
  411. }
  412. } while (needsCalibration);
  413. return returnedTime;
  414. #endif
  415. #if defined(XP_UNIX) || defined(XP_BEOS)
  416. #ifdef _SVID_GETTOD /* Defined only on Solaris, see Solaris <sys/types.h> */
  417. gettimeofday(&tv);
  418. #else
  419. gettimeofday(&tv, 0);
  420. #endif /* _SVID_GETTOD */
  421. JSLL_UI2L(s2us, PRMJ_USEC_PER_SEC);
  422. JSLL_UI2L(s, tv.tv_sec);
  423. JSLL_UI2L(us, tv.tv_usec);
  424. JSLL_MUL(s, s, s2us);
  425. JSLL_ADD(s, s, us);
  426. return s;
  427. #endif /* XP_UNIX */
  428. }
  429. /* Get the DST timezone offset for the time passed in */
  430. JSInt64
  431. PRMJ_DSTOffset(JSInt64 local_time)
  432. {
  433. JSInt64 us2s;
  434. time_t local;
  435. JSInt32 diff;
  436. JSInt64 maxtimet;
  437. struct tm tm;
  438. PRMJTime prtm;
  439. #ifndef HAVE_LOCALTIME_R
  440. struct tm *ptm;
  441. #endif
  442. JSLL_UI2L(us2s, PRMJ_USEC_PER_SEC);
  443. JSLL_DIV(local_time, local_time, us2s);
  444. /* get the maximum of time_t value */
  445. JSLL_UI2L(maxtimet,PRMJ_MAX_UNIX_TIMET);
  446. if(JSLL_CMP(local_time,>,maxtimet)){
  447. JSLL_UI2L(local_time,PRMJ_MAX_UNIX_TIMET);
  448. } else if(!JSLL_GE_ZERO(local_time)){
  449. /*go ahead a day to make localtime work (does not work with 0) */
  450. JSLL_UI2L(local_time,PRMJ_DAY_SECONDS);
  451. }
  452. JSLL_L2UI(local,local_time);
  453. PRMJ_basetime(local_time,&prtm);
  454. #ifndef HAVE_LOCALTIME_R
  455. ptm = localtime(&local);
  456. if(!ptm){
  457. return 0;
  458. }
  459. tm = *ptm;
  460. #else
  461. localtime_r(&local,&tm); /* get dst information */
  462. #endif
  463. diff = ((tm.tm_hour - prtm.tm_hour) * PRMJ_HOUR_SECONDS) +
  464. ((tm.tm_min - prtm.tm_min) * 60);
  465. if(diff < 0){
  466. diff += PRMJ_DAY_SECONDS;
  467. }
  468. JSLL_UI2L(local_time,diff);
  469. JSLL_MUL(local_time,local_time,us2s);
  470. return(local_time);
  471. }
  472. #ifdef NS_HAVE_INVALID_PARAMETER_HANDLER
  473. static void
  474. PRMJ_InvalidParameterHandler(const wchar_t *expression,
  475. const wchar_t *function,
  476. const wchar_t *file,
  477. unsigned int line,
  478. uintptr_t pReserved)
  479. {
  480. /* empty */
  481. }
  482. #endif
  483. /* Format a time value into a buffer. Same semantics as strftime() */
  484. size_t
  485. PRMJ_FormatTime(char *buf, int buflen, const char *fmt, PRMJTime *prtm)
  486. {
  487. size_t result = 0;
  488. #if defined(XP_UNIX) || defined(XP_WIN) || defined(XP_OS2) || defined(XP_BEOS)
  489. struct tm a;
  490. int fake_tm_year = 0;
  491. #ifdef NS_HAVE_INVALID_PARAMETER_HANDLER
  492. _invalid_parameter_handler oldHandler;
  493. int oldReportMode;
  494. #endif
  495. /* Zero out the tm struct. Linux, SunOS 4 struct tm has extra members int
  496. * tm_gmtoff, char *tm_zone; when tm_zone is garbage, strftime gets
  497. * confused and dumps core. NSPR20 prtime.c attempts to fill these in by
  498. * calling mktime on the partially filled struct, but this doesn't seem to
  499. * work as well; the result string has "can't get timezone" for ECMA-valid
  500. * years. Might still make sense to use this, but find the range of years
  501. * for which valid tz information exists, and map (per ECMA hint) from the
  502. * given year into that range.
  503. * N.B. This hasn't been tested with anything that actually _uses_
  504. * tm_gmtoff; zero might be the wrong thing to set it to if you really need
  505. * to format a time. This fix is for jsdate.c, which only uses
  506. * JS_FormatTime to get a string representing the time zone. */
  507. memset(&a, 0, sizeof(struct tm));
  508. a.tm_sec = prtm->tm_sec;
  509. a.tm_min = prtm->tm_min;
  510. a.tm_hour = prtm->tm_hour;
  511. a.tm_mday = prtm->tm_mday;
  512. a.tm_mon = prtm->tm_mon;
  513. a.tm_wday = prtm->tm_wday;
  514. /*
  515. * Years before 1900 and after 9999 cause strftime() to abort on Windows.
  516. * To avoid that we replace it with FAKE_YEAR_BASE + year % 100 and then
  517. * replace matching substrings in the strftime() result with the real year.
  518. * Note that FAKE_YEAR_BASE should be a multiple of 100 to make 2-digit
  519. * year formats (%y) work correctly (since we won't find the fake year
  520. * in that case).
  521. * e.g. new Date(1873, 0).toLocaleFormat('%Y %y') => "1873 73"
  522. * See bug 327869.
  523. */
  524. #define FAKE_YEAR_BASE 9900
  525. if (prtm->tm_year < 1900 || prtm->tm_year > 9999) {
  526. fake_tm_year = FAKE_YEAR_BASE + prtm->tm_year % 100;
  527. a.tm_year = fake_tm_year - 1900;
  528. }
  529. else {
  530. a.tm_year = prtm->tm_year - 1900;
  531. }
  532. a.tm_yday = prtm->tm_yday;
  533. a.tm_isdst = prtm->tm_isdst;
  534. /*
  535. * Even with the above, SunOS 4 seems to detonate if tm_zone and tm_gmtoff
  536. * are null. This doesn't quite work, though - the timezone is off by
  537. * tzoff + dst. (And mktime seems to return -1 for the exact dst
  538. * changeover time.)
  539. */
  540. #ifdef NS_HAVE_INVALID_PARAMETER_HANDLER
  541. oldHandler = _set_invalid_parameter_handler(PRMJ_InvalidParameterHandler);
  542. oldReportMode = _CrtSetReportMode(_CRT_ASSERT, 0);
  543. #endif
  544. result = strftime(buf, buflen, fmt, &a);
  545. #ifdef NS_HAVE_INVALID_PARAMETER_HANDLER
  546. _set_invalid_parameter_handler(oldHandler);
  547. _CrtSetReportMode(_CRT_ASSERT, oldReportMode);
  548. #endif
  549. if (fake_tm_year && result) {
  550. char real_year[16];
  551. char fake_year[16];
  552. size_t real_year_len;
  553. size_t fake_year_len;
  554. char* p;
  555. sprintf(real_year, "%d", prtm->tm_year);
  556. real_year_len = strlen(real_year);
  557. sprintf(fake_year, "%d", fake_tm_year);
  558. fake_year_len = strlen(fake_year);
  559. /* Replace the fake year in the result with the real year. */
  560. for (p = buf; (p = strstr(p, fake_year)); p += real_year_len) {
  561. size_t new_result = result + real_year_len - fake_year_len;
  562. if ((int)new_result >= buflen) {
  563. return 0;
  564. }
  565. memmove(p + real_year_len, p + fake_year_len, strlen(p + fake_year_len));
  566. memcpy(p, real_year, real_year_len);
  567. result = new_result;
  568. *(buf + result) = '\0';
  569. }
  570. }
  571. #endif
  572. return result;
  573. }
  574. /* table for number of days in a month */
  575. static int mtab[] = {
  576. /* jan, feb,mar,apr,may,jun */
  577. 31,28,31,30,31,30,
  578. /* july,aug,sep,oct,nov,dec */
  579. 31,31,30,31,30,31
  580. };
  581. /*
  582. * basic time calculation functionality for localtime and gmtime
  583. * setups up prtm argument with correct values based upon input number
  584. * of seconds.
  585. */
  586. static void
  587. PRMJ_basetime(JSInt64 tsecs, PRMJTime *prtm)
  588. {
  589. /* convert tsecs back to year,month,day,hour,secs */
  590. JSInt32 year = 0;
  591. JSInt32 month = 0;
  592. JSInt32 yday = 0;
  593. JSInt32 mday = 0;
  594. JSInt32 wday = 6; /* start on a Sunday */
  595. JSInt32 days = 0;
  596. JSInt32 seconds = 0;
  597. JSInt32 minutes = 0;
  598. JSInt32 hours = 0;
  599. JSInt32 isleap = 0;
  600. /* Temporaries used for various computations */
  601. JSInt64 result;
  602. JSInt64 result1;
  603. JSInt64 result2;
  604. JSInt64 base;
  605. /* Some variables for intermediate result storage to make computing isleap
  606. easier/faster */
  607. JSInt32 fourCenturyBlocks;
  608. JSInt32 centuriesLeft;
  609. JSInt32 fourYearBlocksLeft;
  610. JSInt32 yearsLeft;
  611. /* Since leap years work by 400/100/4 year intervals, precompute the length
  612. of those in seconds if they start at the beginning of year 1. */
  613. JSInt64 fourYears;
  614. JSInt64 century;
  615. JSInt64 fourCenturies;
  616. JSLL_UI2L(result, PRMJ_DAY_SECONDS);
  617. JSLL_I2L(fourYears, PRMJ_FOUR_YEARS_DAYS);
  618. JSLL_MUL(fourYears, fourYears, result);
  619. JSLL_I2L(century, PRMJ_CENTURY_DAYS);
  620. JSLL_MUL(century, century, result);
  621. JSLL_I2L(fourCenturies, PRMJ_FOUR_CENTURIES_DAYS);
  622. JSLL_MUL(fourCenturies, fourCenturies, result);
  623. /* get the base time via UTC */
  624. base = PRMJ_ToExtendedTime(0);
  625. JSLL_UI2L(result, PRMJ_USEC_PER_SEC);
  626. JSLL_DIV(base,base,result);
  627. JSLL_ADD(tsecs,tsecs,base);
  628. /* Compute our |year|, |isleap|, and part of |days|. When this part is
  629. done, |year| should hold the year our date falls in (number of whole
  630. years elapsed before our date), isleap should hold 1 if the year the
  631. date falls in is a leap year and 0 otherwise. */
  632. /* First do year 0; it's special and nonleap. */
  633. JSLL_UI2L(result, PRMJ_YEAR_SECONDS);
  634. if (!JSLL_CMP(tsecs,<,result)) {
  635. days = PRMJ_YEAR_DAYS;
  636. year = 1;
  637. JSLL_SUB(tsecs, tsecs, result);
  638. }
  639. /* Now use those constants we computed above */
  640. JSLL_UDIVMOD(&result1, &result2, tsecs, fourCenturies);
  641. JSLL_L2I(fourCenturyBlocks, result1);
  642. year += fourCenturyBlocks * 400;
  643. days += fourCenturyBlocks * PRMJ_FOUR_CENTURIES_DAYS;
  644. tsecs = result2;
  645. JSLL_UDIVMOD(&result1, &result2, tsecs, century);
  646. JSLL_L2I(centuriesLeft, result1);
  647. year += centuriesLeft * 100;
  648. days += centuriesLeft * PRMJ_CENTURY_DAYS;
  649. tsecs = result2;
  650. JSLL_UDIVMOD(&result1, &result2, tsecs, fourYears);
  651. JSLL_L2I(fourYearBlocksLeft, result1);
  652. year += fourYearBlocksLeft * 4;
  653. days += fourYearBlocksLeft * PRMJ_FOUR_YEARS_DAYS;
  654. tsecs = result2;
  655. /* Recall that |result| holds PRMJ_YEAR_SECONDS */
  656. JSLL_UDIVMOD(&result1, &result2, tsecs, result);
  657. JSLL_L2I(yearsLeft, result1);
  658. year += yearsLeft;
  659. days += yearsLeft * PRMJ_YEAR_DAYS;
  660. tsecs = result2;
  661. /* now compute isleap. Note that we don't have to use %, since we've
  662. already computed those remainders. Also note that they're all offset by
  663. 1 because of the 1 for year 0. */
  664. isleap =
  665. (yearsLeft == 3) && (fourYearBlocksLeft != 24 || centuriesLeft == 3);
  666. JS_ASSERT(isleap ==
  667. ((year % 4 == 0) && (year % 100 != 0 || year % 400 == 0)));
  668. JSLL_UI2L(result1,PRMJ_DAY_SECONDS);
  669. JSLL_DIV(result,tsecs,result1);
  670. JSLL_L2I(mday,result);
  671. /* let's find the month */
  672. while(((month == 1 && isleap) ?
  673. (mday >= mtab[month] + 1) :
  674. (mday >= mtab[month]))){
  675. yday += mtab[month];
  676. days += mtab[month];
  677. mday -= mtab[month];
  678. /* it's a Feb, check if this is a leap year */
  679. if(month == 1 && isleap != 0){
  680. yday++;
  681. days++;
  682. mday--;
  683. }
  684. month++;
  685. }
  686. /* now adjust tsecs */
  687. JSLL_MUL(result,result,result1);
  688. JSLL_SUB(tsecs,tsecs,result);
  689. mday++; /* day of month always start with 1 */
  690. days += mday;
  691. wday = (days + wday) % 7;
  692. yday += mday;
  693. /* get the hours */
  694. JSLL_UI2L(result1,PRMJ_HOUR_SECONDS);
  695. JSLL_DIV(result,tsecs,result1);
  696. JSLL_L2I(hours,result);
  697. JSLL_MUL(result,result,result1);
  698. JSLL_SUB(tsecs,tsecs,result);
  699. /* get minutes */
  700. JSLL_UI2L(result1,60);
  701. JSLL_DIV(result,tsecs,result1);
  702. JSLL_L2I(minutes,result);
  703. JSLL_MUL(result,result,result1);
  704. JSLL_SUB(tsecs,tsecs,result);
  705. JSLL_L2I(seconds,tsecs);
  706. prtm->tm_usec = 0L;
  707. prtm->tm_sec = (JSInt8)seconds;
  708. prtm->tm_min = (JSInt8)minutes;
  709. prtm->tm_hour = (JSInt8)hours;
  710. prtm->tm_mday = (JSInt8)mday;
  711. prtm->tm_mon = (JSInt8)month;
  712. prtm->tm_wday = (JSInt8)wday;
  713. prtm->tm_year = (JSInt16)year;
  714. prtm->tm_yday = (JSInt16)yday;
  715. }