ntoskrnl.exe: Add Ex[p]InterlockedFlushSList.
[wine.git] / dlls / ntdll / time.c
bloba4762facc5b4058636ba416aa1234e2bca26c310
1 /*
2 * Nt time functions.
4 * RtlTimeToTimeFields, RtlTimeFieldsToTime and defines are taken from ReactOS and
5 * adapted to wine with special permissions of the author. This code is
6 * Copyright 2002 Rex Jolliff (rex@lvcablemodem.com)
8 * Copyright 1999 Juergen Schmied
9 * Copyright 2007 Dmitry Timoshkov
11 * This library is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public
13 * License as published by the Free Software Foundation; either
14 * version 2.1 of the License, or (at your option) any later version.
16 * This library is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with this library; if not, write to the Free Software
23 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
26 #include "config.h"
27 #include "wine/port.h"
29 #include <stdarg.h>
30 #include <stdlib.h>
31 #include <errno.h>
32 #include <string.h>
33 #include <limits.h>
34 #include <time.h>
35 #ifdef HAVE_SYS_TIME_H
36 # include <sys/time.h>
37 #endif
38 #ifdef HAVE_UNISTD_H
39 # include <unistd.h>
40 #endif
41 #ifdef __APPLE__
42 # include <mach/mach_time.h>
43 #endif
45 #include "ntstatus.h"
46 #define WIN32_NO_STATUS
47 #include "windef.h"
48 #include "winternl.h"
49 #include "wine/exception.h"
50 #include "wine/unicode.h"
51 #include "wine/debug.h"
52 #include "ntdll_misc.h"
54 WINE_DEFAULT_DEBUG_CHANNEL(ntdll);
56 #define SHORT_TZ_NAME_MAX 8
57 struct tz_name_map {
58 WCHAR key_name[128];
59 char short_name[SHORT_TZ_NAME_MAX];
62 static int init_tz_info(RTL_DYNAMIC_TIME_ZONE_INFORMATION *tzi);
64 static RTL_CRITICAL_SECTION TIME_tz_section;
65 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
67 0, 0, &TIME_tz_section,
68 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
69 0, 0, { (DWORD_PTR)(__FILE__ ": TIME_tz_section") }
71 static RTL_CRITICAL_SECTION TIME_tz_section = { &critsect_debug, -1, 0, 0, 0, 0 };
73 #define TICKSPERSEC 10000000
74 #define TICKSPERMSEC 10000
75 #define SECSPERDAY 86400
76 #define SECSPERHOUR 3600
77 #define SECSPERMIN 60
78 #define MINSPERHOUR 60
79 #define HOURSPERDAY 24
80 #define EPOCHWEEKDAY 1 /* Jan 1, 1601 was Monday */
81 #define DAYSPERWEEK 7
82 #define MONSPERYEAR 12
83 #define DAYSPERQUADRICENTENNIUM (365 * 400 + 97)
84 #define DAYSPERNORMALQUADRENNIUM (365 * 4 + 1)
86 /* 1601 to 1970 is 369 years plus 89 leap days */
87 #define SECS_1601_TO_1970 ((369 * 365 + 89) * (ULONGLONG)SECSPERDAY)
88 #define TICKS_1601_TO_1970 (SECS_1601_TO_1970 * TICKSPERSEC)
89 /* 1601 to 1980 is 379 years plus 91 leap days */
90 #define SECS_1601_TO_1980 ((379 * 365 + 91) * (ULONGLONG)SECSPERDAY)
91 #define TICKS_1601_TO_1980 (SECS_1601_TO_1980 * TICKSPERSEC)
94 static const int MonthLengths[2][MONSPERYEAR] =
96 { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
97 { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
100 static inline BOOL IsLeapYear(int Year)
102 return Year % 4 == 0 && (Year % 100 != 0 || Year % 400 == 0);
105 /* return a monotonic time counter, in Win32 ticks */
106 static ULONGLONG monotonic_counter(void)
108 struct timeval now;
110 #ifdef __APPLE__
111 static mach_timebase_info_data_t timebase;
113 if (!timebase.denom) mach_timebase_info( &timebase );
114 return mach_absolute_time() * timebase.numer / timebase.denom / 100;
115 #elif defined(HAVE_CLOCK_GETTIME)
116 struct timespec ts;
117 #ifdef CLOCK_MONOTONIC_RAW
118 if (!clock_gettime( CLOCK_MONOTONIC_RAW, &ts ))
119 return ts.tv_sec * (ULONGLONG)TICKSPERSEC + ts.tv_nsec / 100;
120 #endif
121 if (!clock_gettime( CLOCK_MONOTONIC, &ts ))
122 return ts.tv_sec * (ULONGLONG)TICKSPERSEC + ts.tv_nsec / 100;
123 #endif
125 gettimeofday( &now, 0 );
126 return now.tv_sec * (ULONGLONG)TICKSPERSEC + now.tv_usec * 10 + TICKS_1601_TO_1970 - server_start_time;
129 /******************************************************************************
130 * RtlTimeToTimeFields [NTDLL.@]
132 * Convert a time into a TIME_FIELDS structure.
134 * PARAMS
135 * liTime [I] Time to convert.
136 * TimeFields [O] Destination for the converted time.
138 * RETURNS
139 * Nothing.
141 VOID WINAPI RtlTimeToTimeFields(
142 const LARGE_INTEGER *liTime,
143 PTIME_FIELDS TimeFields)
145 int SecondsInDay;
146 long int cleaps, years, yearday, months;
147 long int Days;
148 LONGLONG Time;
150 /* Extract millisecond from time and convert time into seconds */
151 TimeFields->Milliseconds =
152 (CSHORT) (( liTime->QuadPart % TICKSPERSEC) / TICKSPERMSEC);
153 Time = liTime->QuadPart / TICKSPERSEC;
155 /* The native version of RtlTimeToTimeFields does not take leap seconds
156 * into account */
158 /* Split the time into days and seconds within the day */
159 Days = Time / SECSPERDAY;
160 SecondsInDay = Time % SECSPERDAY;
162 /* compute time of day */
163 TimeFields->Hour = (CSHORT) (SecondsInDay / SECSPERHOUR);
164 SecondsInDay = SecondsInDay % SECSPERHOUR;
165 TimeFields->Minute = (CSHORT) (SecondsInDay / SECSPERMIN);
166 TimeFields->Second = (CSHORT) (SecondsInDay % SECSPERMIN);
168 /* compute day of week */
169 TimeFields->Weekday = (CSHORT) ((EPOCHWEEKDAY + Days) % DAYSPERWEEK);
171 /* compute year, month and day of month. */
172 cleaps=( 3 * ((4 * Days + 1227) / DAYSPERQUADRICENTENNIUM) + 3 ) / 4;
173 Days += 28188 + cleaps;
174 years = (20 * Days - 2442) / (5 * DAYSPERNORMALQUADRENNIUM);
175 yearday = Days - (years * DAYSPERNORMALQUADRENNIUM)/4;
176 months = (64 * yearday) / 1959;
177 /* the result is based on a year starting on March.
178 * To convert take 12 from Januari and Februari and
179 * increase the year by one. */
180 if( months < 14 ) {
181 TimeFields->Month = months - 1;
182 TimeFields->Year = years + 1524;
183 } else {
184 TimeFields->Month = months - 13;
185 TimeFields->Year = years + 1525;
187 /* calculation of day of month is based on the wonderful
188 * sequence of INT( n * 30.6): it reproduces the
189 * 31-30-31-30-31-31 month lengths exactly for small n's */
190 TimeFields->Day = yearday - (1959 * months) / 64 ;
191 return;
194 /******************************************************************************
195 * RtlTimeFieldsToTime [NTDLL.@]
197 * Convert a TIME_FIELDS structure into a time.
199 * PARAMS
200 * ftTimeFields [I] TIME_FIELDS structure to convert.
201 * Time [O] Destination for the converted time.
203 * RETURNS
204 * Success: TRUE.
205 * Failure: FALSE.
207 BOOLEAN WINAPI RtlTimeFieldsToTime(
208 PTIME_FIELDS tfTimeFields,
209 PLARGE_INTEGER Time)
211 int month, year, cleaps, day;
213 /* FIXME: normalize the TIME_FIELDS structure here */
214 /* No, native just returns 0 (error) if the fields are not */
215 if( tfTimeFields->Milliseconds< 0 || tfTimeFields->Milliseconds > 999 ||
216 tfTimeFields->Second < 0 || tfTimeFields->Second > 59 ||
217 tfTimeFields->Minute < 0 || tfTimeFields->Minute > 59 ||
218 tfTimeFields->Hour < 0 || tfTimeFields->Hour > 23 ||
219 tfTimeFields->Month < 1 || tfTimeFields->Month > 12 ||
220 tfTimeFields->Day < 1 ||
221 tfTimeFields->Day > MonthLengths
222 [ tfTimeFields->Month ==2 || IsLeapYear(tfTimeFields->Year)]
223 [ tfTimeFields->Month - 1] ||
224 tfTimeFields->Year < 1601 )
225 return FALSE;
227 /* now calculate a day count from the date
228 * First start counting years from March. This way the leap days
229 * are added at the end of the year, not somewhere in the middle.
230 * Formula's become so much less complicate that way.
231 * To convert: add 12 to the month numbers of Jan and Feb, and
232 * take 1 from the year */
233 if(tfTimeFields->Month < 3) {
234 month = tfTimeFields->Month + 13;
235 year = tfTimeFields->Year - 1;
236 } else {
237 month = tfTimeFields->Month + 1;
238 year = tfTimeFields->Year;
240 cleaps = (3 * (year / 100) + 3) / 4; /* nr of "century leap years"*/
241 day = (36525 * year) / 100 - cleaps + /* year * dayperyr, corrected */
242 (1959 * month) / 64 + /* months * daypermonth */
243 tfTimeFields->Day - /* day of the month */
244 584817 ; /* zero that on 1601-01-01 */
245 /* done */
247 Time->QuadPart = (((((LONGLONG) day * HOURSPERDAY +
248 tfTimeFields->Hour) * MINSPERHOUR +
249 tfTimeFields->Minute) * SECSPERMIN +
250 tfTimeFields->Second ) * 1000 +
251 tfTimeFields->Milliseconds ) * TICKSPERMSEC;
253 return TRUE;
256 /***********************************************************************
257 * TIME_GetBias [internal]
259 * Helper function calculates delta local time from UTC.
261 * PARAMS
262 * utc [I] The current utc time.
263 * pdaylight [I] Local daylight.
265 * RETURNS
266 * The bias for the current timezone.
268 static LONG TIME_GetBias(void)
270 static time_t last_utc;
271 static LONG last_bias;
272 LONG ret;
273 time_t utc;
275 utc = time( NULL );
277 RtlEnterCriticalSection( &TIME_tz_section );
278 if (utc != last_utc)
280 RTL_DYNAMIC_TIME_ZONE_INFORMATION tzi;
281 int is_dst = init_tz_info( &tzi );
283 last_utc = utc;
284 last_bias = tzi.Bias;
285 last_bias += is_dst ? tzi.DaylightBias : tzi.StandardBias;
286 last_bias *= SECSPERMIN;
289 ret = last_bias;
291 RtlLeaveCriticalSection( &TIME_tz_section );
292 return ret;
295 /******************************************************************************
296 * RtlLocalTimeToSystemTime [NTDLL.@]
298 * Convert a local time into system time.
300 * PARAMS
301 * LocalTime [I] Local time to convert.
302 * SystemTime [O] Destination for the converted time.
304 * RETURNS
305 * Success: STATUS_SUCCESS.
306 * Failure: An NTSTATUS error code indicating the problem.
308 NTSTATUS WINAPI RtlLocalTimeToSystemTime( const LARGE_INTEGER *LocalTime,
309 PLARGE_INTEGER SystemTime)
311 LONG bias;
313 TRACE("(%p, %p)\n", LocalTime, SystemTime);
315 bias = TIME_GetBias();
316 SystemTime->QuadPart = LocalTime->QuadPart + bias * (LONGLONG)TICKSPERSEC;
317 return STATUS_SUCCESS;
320 /******************************************************************************
321 * RtlSystemTimeToLocalTime [NTDLL.@]
323 * Convert a system time into a local time.
325 * PARAMS
326 * SystemTime [I] System time to convert.
327 * LocalTime [O] Destination for the converted time.
329 * RETURNS
330 * Success: STATUS_SUCCESS.
331 * Failure: An NTSTATUS error code indicating the problem.
333 NTSTATUS WINAPI RtlSystemTimeToLocalTime( const LARGE_INTEGER *SystemTime,
334 PLARGE_INTEGER LocalTime )
336 LONG bias;
338 TRACE("(%p, %p)\n", SystemTime, LocalTime);
340 bias = TIME_GetBias();
341 LocalTime->QuadPart = SystemTime->QuadPart - bias * (LONGLONG)TICKSPERSEC;
342 return STATUS_SUCCESS;
345 /******************************************************************************
346 * RtlTimeToSecondsSince1970 [NTDLL.@]
348 * Convert a time into a count of seconds since 1970.
350 * PARAMS
351 * Time [I] Time to convert.
352 * Seconds [O] Destination for the converted time.
354 * RETURNS
355 * Success: TRUE.
356 * Failure: FALSE, if the resulting value will not fit in a DWORD.
358 BOOLEAN WINAPI RtlTimeToSecondsSince1970( const LARGE_INTEGER *Time, LPDWORD Seconds )
360 ULONGLONG tmp = Time->QuadPart / TICKSPERSEC - SECS_1601_TO_1970;
361 if (tmp > 0xffffffff) return FALSE;
362 *Seconds = tmp;
363 return TRUE;
366 /******************************************************************************
367 * RtlTimeToSecondsSince1980 [NTDLL.@]
369 * Convert a time into a count of seconds since 1980.
371 * PARAMS
372 * Time [I] Time to convert.
373 * Seconds [O] Destination for the converted time.
375 * RETURNS
376 * Success: TRUE.
377 * Failure: FALSE, if the resulting value will not fit in a DWORD.
379 BOOLEAN WINAPI RtlTimeToSecondsSince1980( const LARGE_INTEGER *Time, LPDWORD Seconds )
381 ULONGLONG tmp = Time->QuadPart / TICKSPERSEC - SECS_1601_TO_1980;
382 if (tmp > 0xffffffff) return FALSE;
383 *Seconds = tmp;
384 return TRUE;
387 /******************************************************************************
388 * RtlSecondsSince1970ToTime [NTDLL.@]
390 * Convert a count of seconds since 1970 to a time.
392 * PARAMS
393 * Seconds [I] Time to convert.
394 * Time [O] Destination for the converted time.
396 * RETURNS
397 * Nothing.
399 void WINAPI RtlSecondsSince1970ToTime( DWORD Seconds, LARGE_INTEGER *Time )
401 Time->QuadPart = Seconds * (ULONGLONG)TICKSPERSEC + TICKS_1601_TO_1970;
404 /******************************************************************************
405 * RtlSecondsSince1980ToTime [NTDLL.@]
407 * Convert a count of seconds since 1980 to a time.
409 * PARAMS
410 * Seconds [I] Time to convert.
411 * Time [O] Destination for the converted time.
413 * RETURNS
414 * Nothing.
416 void WINAPI RtlSecondsSince1980ToTime( DWORD Seconds, LARGE_INTEGER *Time )
418 Time->QuadPart = Seconds * (ULONGLONG)TICKSPERSEC + TICKS_1601_TO_1980;
421 /******************************************************************************
422 * RtlTimeToElapsedTimeFields [NTDLL.@]
424 * Convert a time to a count of elapsed seconds.
426 * PARAMS
427 * Time [I] Time to convert.
428 * TimeFields [O] Destination for the converted time.
430 * RETURNS
431 * Nothing.
433 void WINAPI RtlTimeToElapsedTimeFields( const LARGE_INTEGER *Time, PTIME_FIELDS TimeFields )
435 LONGLONG time;
436 INT rem;
438 time = Time->QuadPart / TICKSPERSEC;
439 TimeFields->Milliseconds = (Time->QuadPart % TICKSPERSEC) / TICKSPERMSEC;
441 /* time is now in seconds */
442 TimeFields->Year = 0;
443 TimeFields->Month = 0;
444 TimeFields->Day = time / SECSPERDAY;
446 /* rem is now the remaining seconds in the last day */
447 rem = time % SECSPERDAY;
448 TimeFields->Second = rem % 60;
449 rem /= 60;
450 TimeFields->Minute = rem % 60;
451 TimeFields->Hour = rem / 60;
454 /***********************************************************************
455 * NtQuerySystemTime [NTDLL.@]
456 * ZwQuerySystemTime [NTDLL.@]
458 * Get the current system time.
460 * PARAMS
461 * Time [O] Destination for the current system time.
463 * RETURNS
464 * Success: STATUS_SUCCESS.
465 * Failure: An NTSTATUS error code indicating the problem.
467 NTSTATUS WINAPI NtQuerySystemTime( PLARGE_INTEGER Time )
469 struct timeval now;
471 gettimeofday( &now, 0 );
472 Time->QuadPart = now.tv_sec * (ULONGLONG)TICKSPERSEC + TICKS_1601_TO_1970;
473 Time->QuadPart += now.tv_usec * 10;
474 return STATUS_SUCCESS;
477 /******************************************************************************
478 * NtQueryPerformanceCounter [NTDLL.@]
480 NTSTATUS WINAPI NtQueryPerformanceCounter( LARGE_INTEGER *counter, LARGE_INTEGER *frequency )
482 __TRY
484 counter->QuadPart = monotonic_counter();
485 if (frequency) frequency->QuadPart = TICKSPERSEC;
487 __EXCEPT_PAGE_FAULT
489 return STATUS_ACCESS_VIOLATION;
491 __ENDTRY
493 return STATUS_SUCCESS;
497 /******************************************************************************
498 * NtGetTickCount (NTDLL.@)
499 * ZwGetTickCount (NTDLL.@)
501 ULONG WINAPI NtGetTickCount(void)
503 return monotonic_counter() / TICKSPERMSEC;
506 /* calculate the mday of dst change date, so that for instance Sun 5 Oct 2007
507 * (last Sunday in October of 2007) becomes Sun Oct 28 2007
509 * Note: year, day and month must be in unix format.
511 static int weekday_to_mday(int year, int day, int mon, int day_of_week)
513 struct tm date;
514 time_t tmp;
515 int wday, mday;
517 /* find first day in the month matching week day of the date */
518 memset(&date, 0, sizeof(date));
519 date.tm_year = year;
520 date.tm_mon = mon;
521 date.tm_mday = -1;
522 date.tm_wday = -1;
525 date.tm_mday++;
526 tmp = mktime(&date);
527 } while (date.tm_wday != day_of_week || date.tm_mon != mon);
529 mday = date.tm_mday;
531 /* find number of week days in the month matching week day of the date */
532 wday = 1; /* 1 - 1st, ...., 5 - last */
533 while (wday < day)
535 struct tm *tm;
537 date.tm_mday += 7;
538 tmp = mktime(&date);
539 tm = localtime(&tmp);
540 if (tm->tm_mon != mon)
541 break;
542 mday = tm->tm_mday;
543 wday++;
546 return mday;
549 static BOOL match_tz_date(const RTL_SYSTEM_TIME *st, const RTL_SYSTEM_TIME *reg_st)
551 WORD wDay;
553 if (st->wMonth != reg_st->wMonth) return FALSE;
555 if (!st->wMonth) return TRUE; /* no transition dates */
557 wDay = reg_st->wDay;
558 if (!reg_st->wYear) /* date in a day-of-week format */
559 wDay = weekday_to_mday(st->wYear - 1900, reg_st->wDay, reg_st->wMonth - 1, reg_st->wDayOfWeek);
561 if (st->wDay != wDay ||
562 st->wHour != reg_st->wHour ||
563 st->wMinute != reg_st->wMinute ||
564 st->wSecond != reg_st->wSecond ||
565 st->wMilliseconds != reg_st->wMilliseconds) return FALSE;
567 return TRUE;
570 static BOOL match_tz_info(const RTL_DYNAMIC_TIME_ZONE_INFORMATION *tzi, const RTL_DYNAMIC_TIME_ZONE_INFORMATION *reg_tzi)
572 if (tzi->Bias == reg_tzi->Bias &&
573 match_tz_date(&tzi->StandardDate, &reg_tzi->StandardDate) &&
574 match_tz_date(&tzi->DaylightDate, &reg_tzi->DaylightDate))
575 return TRUE;
577 return FALSE;
580 static int compare_tz_key(const void *a, const void *b)
582 const struct tz_name_map *map_a, *map_b;
583 map_a = (const struct tz_name_map *)a;
584 map_b = (const struct tz_name_map *)b;
585 return strcmpW(map_a->key_name, map_b->key_name);
588 static BOOL match_tz_name(const char* tz_name,
589 const RTL_DYNAMIC_TIME_ZONE_INFORMATION *reg_tzi)
591 static const struct tz_name_map mapping[] = {
592 { {'K','o','r','e','a',' ','S','t','a','n','d','a','r','d',' ','T','i',
593 'm','e',0 },
594 "KST" },
595 { {'T','o','k','y','o',' ','S','t','a','n','d','a','r','d',' ','T','i',
596 'm','e',0 },
597 "JST" },
598 { {'Y','a','k','u','t','s','k',' ','S','t','a','n','d','a','r','d',' ',
599 'T','i','m','e',0 },
600 "+09" }, /* YAKST was used until tzdata 2016f */
602 struct tz_name_map *match, key;
604 if (reg_tzi->DaylightDate.wMonth)
605 return TRUE;
607 strcpyW(key.key_name, reg_tzi->TimeZoneKeyName);
608 match = bsearch(&key, mapping, ARRAY_SIZE(mapping), sizeof(mapping[0]), compare_tz_key);
609 if (!match)
610 return TRUE;
612 return !strcmp(match->short_name, tz_name);
615 static BOOL reg_query_value(HKEY hkey, LPCWSTR name, DWORD type, void *data, DWORD count)
617 UNICODE_STRING nameW;
618 char buf[256];
619 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buf;
621 if (count > sizeof(buf) - sizeof(KEY_VALUE_PARTIAL_INFORMATION))
622 return FALSE;
624 RtlInitUnicodeString(&nameW, name);
626 if (NtQueryValueKey(hkey, &nameW, KeyValuePartialInformation,
627 buf, sizeof(buf), &count))
628 return FALSE;
630 if (info->Type != type) return FALSE;
632 memcpy(data, info->Data, info->DataLength);
633 return TRUE;
636 static void find_reg_tz_info(RTL_DYNAMIC_TIME_ZONE_INFORMATION *tzi, const char* tz_name, int year)
638 static const WCHAR Time_ZonesW[] = { 'M','a','c','h','i','n','e','\\',
639 'S','o','f','t','w','a','r','e','\\',
640 'M','i','c','r','o','s','o','f','t','\\',
641 'W','i','n','d','o','w','s',' ','N','T','\\',
642 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
643 'T','i','m','e',' ','Z','o','n','e','s',0 };
644 static const WCHAR Dynamic_DstW[] = { 'D','y','n','a','m','i','c',' ','D','S','T',0 };
645 static const WCHAR fmtW[] = { '%','d',0 };
646 HANDLE hkey;
647 ULONG idx;
648 OBJECT_ATTRIBUTES attr, attrDynamic;
649 UNICODE_STRING nameW, nameDynamicW;
650 WCHAR buf[128], yearW[16];
652 sprintfW(yearW, fmtW, year);
654 attrDynamic.Length = sizeof(attrDynamic);
655 attrDynamic.RootDirectory = 0; /* will be replaced later */
656 attrDynamic.ObjectName = &nameDynamicW;
657 attrDynamic.Attributes = 0;
658 attrDynamic.SecurityDescriptor = NULL;
659 attrDynamic.SecurityQualityOfService = NULL;
660 RtlInitUnicodeString(&nameDynamicW, Dynamic_DstW);
662 attr.Length = sizeof(attr);
663 attr.RootDirectory = 0;
664 attr.ObjectName = &nameW;
665 attr.Attributes = 0;
666 attr.SecurityDescriptor = NULL;
667 attr.SecurityQualityOfService = NULL;
668 RtlInitUnicodeString(&nameW, Time_ZonesW);
669 if (NtOpenKey(&hkey, KEY_READ, &attr))
671 WARN("Unable to open the time zones key\n");
672 return;
675 idx = 0;
676 nameW.Buffer = buf;
677 nameW.Length = sizeof(buf);
678 nameW.MaximumLength = sizeof(buf);
680 while (!RtlpNtEnumerateSubKey(hkey, &nameW, idx++))
682 static const WCHAR stdW[] = { 'S','t','d',0 };
683 static const WCHAR dltW[] = { 'D','l','t',0 };
684 static const WCHAR mui_stdW[] = { 'M','U','I','_','S','t','d',0 };
685 static const WCHAR mui_dltW[] = { 'M','U','I','_','D','l','t',0 };
686 static const WCHAR tziW[] = { 'T','Z','I',0 };
687 RTL_DYNAMIC_TIME_ZONE_INFORMATION reg_tzi;
688 HANDLE hSubkey, hSubkeyDynamicDST;
689 BOOL is_dynamic = FALSE;
691 struct tz_reg_data
693 LONG bias;
694 LONG std_bias;
695 LONG dlt_bias;
696 RTL_SYSTEM_TIME std_date;
697 RTL_SYSTEM_TIME dlt_date;
698 } tz_data;
700 attr.Length = sizeof(attr);
701 attr.RootDirectory = hkey;
702 attr.ObjectName = &nameW;
703 attr.Attributes = 0;
704 attr.SecurityDescriptor = NULL;
705 attr.SecurityQualityOfService = NULL;
706 if (NtOpenKey(&hSubkey, KEY_READ, &attr))
708 WARN("Unable to open subkey %s\n", debugstr_wn(nameW.Buffer, nameW.Length/sizeof(WCHAR)));
709 continue;
712 #define get_value(hkey, name, type, data, len) \
713 if (!reg_query_value(hkey, name, type, data, len)) \
715 WARN("can't read data from %s\n", debugstr_w(name)); \
716 NtClose(hkey); \
717 continue; \
720 if (!reg_query_value(hSubkey, mui_stdW, REG_SZ, reg_tzi.StandardName, sizeof(reg_tzi.StandardName)))
721 get_value(hSubkey, stdW, REG_SZ, reg_tzi.StandardName, sizeof(reg_tzi.StandardName));
722 if (!reg_query_value(hSubkey, mui_dltW, REG_SZ, reg_tzi.DaylightName, sizeof(reg_tzi.DaylightName)))
723 get_value(hSubkey, dltW, REG_SZ, reg_tzi.DaylightName, sizeof(reg_tzi.DaylightName));
724 memcpy(reg_tzi.TimeZoneKeyName, nameW.Buffer, nameW.Length);
725 reg_tzi.TimeZoneKeyName[nameW.Length/sizeof(WCHAR)] = 0;
727 /* Check for Dynamic DST entry first */
728 attrDynamic.RootDirectory = hSubkey;
729 if (!NtOpenKey(&hSubkeyDynamicDST, KEY_READ, &attrDynamic))
731 is_dynamic = reg_query_value(hSubkeyDynamicDST, yearW, REG_BINARY, &tz_data, sizeof(tz_data));
732 NtClose(hSubkeyDynamicDST);
735 if (!is_dynamic)
736 get_value(hSubkey, tziW, REG_BINARY, &tz_data, sizeof(tz_data));
738 #undef get_value
740 reg_tzi.Bias = tz_data.bias;
741 reg_tzi.StandardBias = tz_data.std_bias;
742 reg_tzi.DaylightBias = tz_data.dlt_bias;
743 reg_tzi.StandardDate = tz_data.std_date;
744 reg_tzi.DaylightDate = tz_data.dlt_date;
746 TRACE("%s: bias %d\n", debugstr_wn(nameW.Buffer, nameW.Length/sizeof(WCHAR)), reg_tzi.Bias);
747 TRACE("std (d/m/y): %u/%02u/%04u day of week %u %u:%02u:%02u.%03u bias %d\n",
748 reg_tzi.StandardDate.wDay, reg_tzi.StandardDate.wMonth,
749 reg_tzi.StandardDate.wYear, reg_tzi.StandardDate.wDayOfWeek,
750 reg_tzi.StandardDate.wHour, reg_tzi.StandardDate.wMinute,
751 reg_tzi.StandardDate.wSecond, reg_tzi.StandardDate.wMilliseconds,
752 reg_tzi.StandardBias);
753 TRACE("dst (d/m/y): %u/%02u/%04u day of week %u %u:%02u:%02u.%03u bias %d\n",
754 reg_tzi.DaylightDate.wDay, reg_tzi.DaylightDate.wMonth,
755 reg_tzi.DaylightDate.wYear, reg_tzi.DaylightDate.wDayOfWeek,
756 reg_tzi.DaylightDate.wHour, reg_tzi.DaylightDate.wMinute,
757 reg_tzi.DaylightDate.wSecond, reg_tzi.DaylightDate.wMilliseconds,
758 reg_tzi.DaylightBias);
760 NtClose(hSubkey);
762 if (match_tz_info(tzi, &reg_tzi)
763 && match_tz_name(tz_name, &reg_tzi))
765 *tzi = reg_tzi;
766 NtClose(hkey);
767 return;
770 /* reset len */
771 nameW.Length = sizeof(buf);
772 nameW.MaximumLength = sizeof(buf);
775 NtClose(hkey);
777 FIXME("Can't find matching timezone information in the registry for "
778 "%s, bias %d, std (d/m/y): %u/%02u/%04u, dlt (d/m/y): %u/%02u/%04u\n",
779 tz_name, tzi->Bias,
780 tzi->StandardDate.wDay, tzi->StandardDate.wMonth, tzi->StandardDate.wYear,
781 tzi->DaylightDate.wDay, tzi->DaylightDate.wMonth, tzi->DaylightDate.wYear);
784 static time_t find_dst_change(unsigned long min, unsigned long max, int *is_dst)
786 time_t start;
787 struct tm *tm;
789 start = min;
790 tm = localtime(&start);
791 *is_dst = !tm->tm_isdst;
792 TRACE("starting date isdst %d, %s", !*is_dst, ctime(&start));
794 while (min <= max)
796 time_t pos = (min + max) / 2;
797 tm = localtime(&pos);
799 if (tm->tm_isdst != *is_dst)
800 min = pos + 1;
801 else
802 max = pos - 1;
804 return min;
807 static int init_tz_info(RTL_DYNAMIC_TIME_ZONE_INFORMATION *tzi)
809 static RTL_DYNAMIC_TIME_ZONE_INFORMATION cached_tzi;
810 static int current_year = -1, current_bias = 65535;
811 struct tm *tm;
812 char tz_name[SHORT_TZ_NAME_MAX];
813 time_t year_start, year_end, tmp, dlt = 0, std = 0;
814 int is_dst, current_is_dst, bias;
816 RtlEnterCriticalSection( &TIME_tz_section );
818 year_start = time(NULL);
819 tm = gmtime(&year_start);
820 bias = (LONG)(mktime(tm) - year_start) / 60;
822 tm = localtime(&year_start);
823 current_is_dst = tm->tm_isdst;
824 if (current_year == tm->tm_year && current_bias == bias)
826 *tzi = cached_tzi;
827 RtlLeaveCriticalSection( &TIME_tz_section );
828 return current_is_dst;
831 memset(tzi, 0, sizeof(*tzi));
832 if (!strftime(tz_name, sizeof(tz_name), "%Z", tm)) {
833 /* not enough room or another error */
834 tz_name[0] = '\0';
837 TRACE("tz data will be valid through year %d, bias %d\n", tm->tm_year + 1900, bias);
838 current_year = tm->tm_year;
839 current_bias = bias;
841 tzi->Bias = bias;
843 tm->tm_isdst = 0;
844 tm->tm_mday = 1;
845 tm->tm_mon = tm->tm_hour = tm->tm_min = tm->tm_sec = tm->tm_wday = tm->tm_yday = 0;
846 year_start = mktime(tm);
847 TRACE("year_start: %s", ctime(&year_start));
849 tm->tm_mday = tm->tm_wday = tm->tm_yday = 0;
850 tm->tm_mon = 12;
851 tm->tm_hour = 23;
852 tm->tm_min = tm->tm_sec = 59;
853 year_end = mktime(tm);
854 TRACE("year_end: %s", ctime(&year_end));
856 tmp = find_dst_change(year_start, year_end, &is_dst);
857 if (is_dst)
858 dlt = tmp;
859 else
860 std = tmp;
862 tmp = find_dst_change(tmp, year_end, &is_dst);
863 if (is_dst)
864 dlt = tmp;
865 else
866 std = tmp;
868 TRACE("std: %s", ctime(&std));
869 TRACE("dlt: %s", ctime(&dlt));
871 if (dlt == std || !dlt || !std)
872 TRACE("there is no daylight saving rules in this time zone\n");
873 else
875 tmp = dlt - tzi->Bias * 60;
876 tm = gmtime(&tmp);
877 TRACE("dlt gmtime: %s", asctime(tm));
879 tzi->DaylightBias = -60;
880 tzi->DaylightDate.wYear = tm->tm_year + 1900;
881 tzi->DaylightDate.wMonth = tm->tm_mon + 1;
882 tzi->DaylightDate.wDayOfWeek = tm->tm_wday;
883 tzi->DaylightDate.wDay = tm->tm_mday;
884 tzi->DaylightDate.wHour = tm->tm_hour;
885 tzi->DaylightDate.wMinute = tm->tm_min;
886 tzi->DaylightDate.wSecond = tm->tm_sec;
887 tzi->DaylightDate.wMilliseconds = 0;
889 TRACE("daylight (d/m/y): %u/%02u/%04u day of week %u %u:%02u:%02u.%03u bias %d\n",
890 tzi->DaylightDate.wDay, tzi->DaylightDate.wMonth,
891 tzi->DaylightDate.wYear, tzi->DaylightDate.wDayOfWeek,
892 tzi->DaylightDate.wHour, tzi->DaylightDate.wMinute,
893 tzi->DaylightDate.wSecond, tzi->DaylightDate.wMilliseconds,
894 tzi->DaylightBias);
896 tmp = std - tzi->Bias * 60 - tzi->DaylightBias * 60;
897 tm = gmtime(&tmp);
898 TRACE("std gmtime: %s", asctime(tm));
900 tzi->StandardBias = 0;
901 tzi->StandardDate.wYear = tm->tm_year + 1900;
902 tzi->StandardDate.wMonth = tm->tm_mon + 1;
903 tzi->StandardDate.wDayOfWeek = tm->tm_wday;
904 tzi->StandardDate.wDay = tm->tm_mday;
905 tzi->StandardDate.wHour = tm->tm_hour;
906 tzi->StandardDate.wMinute = tm->tm_min;
907 tzi->StandardDate.wSecond = tm->tm_sec;
908 tzi->StandardDate.wMilliseconds = 0;
910 TRACE("standard (d/m/y): %u/%02u/%04u day of week %u %u:%02u:%02u.%03u bias %d\n",
911 tzi->StandardDate.wDay, tzi->StandardDate.wMonth,
912 tzi->StandardDate.wYear, tzi->StandardDate.wDayOfWeek,
913 tzi->StandardDate.wHour, tzi->StandardDate.wMinute,
914 tzi->StandardDate.wSecond, tzi->StandardDate.wMilliseconds,
915 tzi->StandardBias);
918 find_reg_tz_info(tzi, tz_name, current_year + 1900);
919 cached_tzi = *tzi;
921 RtlLeaveCriticalSection( &TIME_tz_section );
923 return current_is_dst;
926 /***********************************************************************
927 * RtlQueryTimeZoneInformation [NTDLL.@]
929 * Get information about the current timezone.
931 * PARAMS
932 * tzinfo [O] Destination for the retrieved timezone info.
934 * RETURNS
935 * Success: STATUS_SUCCESS.
936 * Failure: An NTSTATUS error code indicating the problem.
938 NTSTATUS WINAPI RtlQueryTimeZoneInformation(RTL_TIME_ZONE_INFORMATION *ret)
940 RTL_DYNAMIC_TIME_ZONE_INFORMATION tzinfo;
942 init_tz_info( &tzinfo );
943 memcpy( ret, &tzinfo, sizeof(*ret) );
944 return STATUS_SUCCESS;
947 /***********************************************************************
948 * RtlQueryDynamicTimeZoneInformation [NTDLL.@]
950 * Get information about the current timezone.
952 * PARAMS
953 * tzinfo [O] Destination for the retrieved timezone info.
955 * RETURNS
956 * Success: STATUS_SUCCESS.
957 * Failure: An NTSTATUS error code indicating the problem.
959 NTSTATUS WINAPI RtlQueryDynamicTimeZoneInformation(RTL_DYNAMIC_TIME_ZONE_INFORMATION *tzinfo)
961 init_tz_info( tzinfo );
963 return STATUS_SUCCESS;
966 /***********************************************************************
967 * RtlSetTimeZoneInformation [NTDLL.@]
969 * Set the current time zone information.
971 * PARAMS
972 * tzinfo [I] Timezone information to set.
974 * RETURNS
975 * Success: STATUS_SUCCESS.
976 * Failure: An NTSTATUS error code indicating the problem.
979 NTSTATUS WINAPI RtlSetTimeZoneInformation( const RTL_TIME_ZONE_INFORMATION *tzinfo )
981 return STATUS_PRIVILEGE_NOT_HELD;
984 /***********************************************************************
985 * NtSetSystemTime [NTDLL.@]
986 * ZwSetSystemTime [NTDLL.@]
988 * Set the system time.
990 * PARAMS
991 * NewTime [I] The time to set.
992 * OldTime [O] Optional destination for the previous system time.
994 * RETURNS
995 * Success: STATUS_SUCCESS.
996 * Failure: An NTSTATUS error code indicating the problem.
998 NTSTATUS WINAPI NtSetSystemTime(const LARGE_INTEGER *NewTime, LARGE_INTEGER *OldTime)
1000 struct timeval tv;
1001 time_t tm_t;
1002 DWORD sec, oldsec;
1003 LARGE_INTEGER tm;
1005 /* Return the old time if necessary */
1006 if (!OldTime) OldTime = &tm;
1008 NtQuerySystemTime( OldTime );
1009 RtlTimeToSecondsSince1970( OldTime, &oldsec );
1011 RtlTimeToSecondsSince1970( NewTime, &sec );
1013 /* fake success if time didn't change */
1014 if (oldsec == sec)
1015 return STATUS_SUCCESS;
1017 /* set the new time */
1018 tv.tv_sec = sec;
1019 tv.tv_usec = 0;
1021 #ifdef HAVE_SETTIMEOFDAY
1022 tm_t = sec;
1023 if (!settimeofday(&tv, NULL)) /* 0 is OK, -1 is error */
1025 TRACE("OS time changed to %s\n", ctime(&tm_t));
1026 return STATUS_SUCCESS;
1028 ERR("Cannot set time to %s, time adjustment %ld: %s\n",
1029 ctime(&tm_t), (long)(sec-oldsec), strerror(errno));
1030 if (errno == EPERM)
1031 return STATUS_PRIVILEGE_NOT_HELD;
1032 else
1033 return STATUS_INVALID_PARAMETER;
1034 #else
1035 tm_t = sec;
1036 FIXME("setting time to %s not implemented for missing settimeofday\n",
1037 ctime(&tm_t));
1038 return STATUS_NOT_IMPLEMENTED;
1039 #endif
1042 /***********************************************************************
1043 * RtlQueryUnbiasedInterruptTime [NTDLL.@]
1045 NTSTATUS WINAPI RtlQueryUnbiasedInterruptTime(ULONGLONG *time)
1047 *time = monotonic_counter();
1048 return STATUS_SUCCESS;