user32: Support forcing the DPI awareness through the image file execution options.
[wine.git] / dlls / ntdll / time.c
blobe2cd770af063d1a57b7fd2c8e16f63a459883897
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, sizeof(mapping)/sizeof(mapping[0]),
609 sizeof(mapping[0]), compare_tz_key);
610 if (!match)
611 return TRUE;
613 return !strcmp(match->short_name, tz_name);
616 static BOOL reg_query_value(HKEY hkey, LPCWSTR name, DWORD type, void *data, DWORD count)
618 UNICODE_STRING nameW;
619 char buf[256];
620 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buf;
622 if (count > sizeof(buf) - sizeof(KEY_VALUE_PARTIAL_INFORMATION))
623 return FALSE;
625 RtlInitUnicodeString(&nameW, name);
627 if (NtQueryValueKey(hkey, &nameW, KeyValuePartialInformation,
628 buf, sizeof(buf), &count))
629 return FALSE;
631 if (info->Type != type) return FALSE;
633 memcpy(data, info->Data, info->DataLength);
634 return TRUE;
637 static void find_reg_tz_info(RTL_DYNAMIC_TIME_ZONE_INFORMATION *tzi, const char* tz_name, int year)
639 static const WCHAR Time_ZonesW[] = { 'M','a','c','h','i','n','e','\\',
640 'S','o','f','t','w','a','r','e','\\',
641 'M','i','c','r','o','s','o','f','t','\\',
642 'W','i','n','d','o','w','s',' ','N','T','\\',
643 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
644 'T','i','m','e',' ','Z','o','n','e','s',0 };
645 static const WCHAR Dynamic_DstW[] = { 'D','y','n','a','m','i','c',' ','D','S','T',0 };
646 static const WCHAR fmtW[] = { '%','d',0 };
647 HANDLE hkey;
648 ULONG idx;
649 OBJECT_ATTRIBUTES attr, attrDynamic;
650 UNICODE_STRING nameW, nameDynamicW;
651 WCHAR buf[128], yearW[16];
653 sprintfW(yearW, fmtW, year);
655 attrDynamic.Length = sizeof(attrDynamic);
656 attrDynamic.RootDirectory = 0; /* will be replaced later */
657 attrDynamic.ObjectName = &nameDynamicW;
658 attrDynamic.Attributes = 0;
659 attrDynamic.SecurityDescriptor = NULL;
660 attrDynamic.SecurityQualityOfService = NULL;
661 RtlInitUnicodeString(&nameDynamicW, Dynamic_DstW);
663 attr.Length = sizeof(attr);
664 attr.RootDirectory = 0;
665 attr.ObjectName = &nameW;
666 attr.Attributes = 0;
667 attr.SecurityDescriptor = NULL;
668 attr.SecurityQualityOfService = NULL;
669 RtlInitUnicodeString(&nameW, Time_ZonesW);
670 if (NtOpenKey(&hkey, KEY_READ, &attr))
672 WARN("Unable to open the time zones key\n");
673 return;
676 idx = 0;
677 nameW.Buffer = buf;
678 nameW.Length = sizeof(buf);
679 nameW.MaximumLength = sizeof(buf);
681 while (!RtlpNtEnumerateSubKey(hkey, &nameW, idx++))
683 static const WCHAR stdW[] = { 'S','t','d',0 };
684 static const WCHAR dltW[] = { 'D','l','t',0 };
685 static const WCHAR tziW[] = { 'T','Z','I',0 };
686 RTL_DYNAMIC_TIME_ZONE_INFORMATION reg_tzi;
687 HANDLE hSubkey, hSubkeyDynamicDST;
688 BOOL is_dynamic = FALSE;
690 struct tz_reg_data
692 LONG bias;
693 LONG std_bias;
694 LONG dlt_bias;
695 RTL_SYSTEM_TIME std_date;
696 RTL_SYSTEM_TIME dlt_date;
697 } tz_data;
699 attr.Length = sizeof(attr);
700 attr.RootDirectory = hkey;
701 attr.ObjectName = &nameW;
702 attr.Attributes = 0;
703 attr.SecurityDescriptor = NULL;
704 attr.SecurityQualityOfService = NULL;
705 if (NtOpenKey(&hSubkey, KEY_READ, &attr))
707 WARN("Unable to open subkey %s\n", debugstr_wn(nameW.Buffer, nameW.Length/sizeof(WCHAR)));
708 continue;
711 #define get_value(hkey, name, type, data, len) \
712 if (!reg_query_value(hkey, name, type, data, len)) \
714 WARN("can't read data from %s\n", debugstr_w(name)); \
715 NtClose(hkey); \
716 continue; \
719 get_value(hSubkey, stdW, REG_SZ, reg_tzi.StandardName, sizeof(reg_tzi.StandardName));
720 get_value(hSubkey, dltW, REG_SZ, reg_tzi.DaylightName, sizeof(reg_tzi.DaylightName));
721 memcpy(reg_tzi.TimeZoneKeyName, nameW.Buffer, nameW.Length);
722 reg_tzi.TimeZoneKeyName[nameW.Length/sizeof(WCHAR)] = 0;
724 /* Check for Dynamic DST entry first */
725 attrDynamic.RootDirectory = hSubkey;
726 if (!NtOpenKey(&hSubkeyDynamicDST, KEY_READ, &attrDynamic))
728 is_dynamic = reg_query_value(hSubkeyDynamicDST, yearW, REG_BINARY, &tz_data, sizeof(tz_data));
729 NtClose(hSubkeyDynamicDST);
732 if (!is_dynamic)
733 get_value(hSubkey, tziW, REG_BINARY, &tz_data, sizeof(tz_data));
735 #undef get_value
737 reg_tzi.Bias = tz_data.bias;
738 reg_tzi.StandardBias = tz_data.std_bias;
739 reg_tzi.DaylightBias = tz_data.dlt_bias;
740 reg_tzi.StandardDate = tz_data.std_date;
741 reg_tzi.DaylightDate = tz_data.dlt_date;
743 TRACE("%s: bias %d\n", debugstr_wn(nameW.Buffer, nameW.Length/sizeof(WCHAR)), reg_tzi.Bias);
744 TRACE("std (d/m/y): %u/%02u/%04u day of week %u %u:%02u:%02u.%03u bias %d\n",
745 reg_tzi.StandardDate.wDay, reg_tzi.StandardDate.wMonth,
746 reg_tzi.StandardDate.wYear, reg_tzi.StandardDate.wDayOfWeek,
747 reg_tzi.StandardDate.wHour, reg_tzi.StandardDate.wMinute,
748 reg_tzi.StandardDate.wSecond, reg_tzi.StandardDate.wMilliseconds,
749 reg_tzi.StandardBias);
750 TRACE("dst (d/m/y): %u/%02u/%04u day of week %u %u:%02u:%02u.%03u bias %d\n",
751 reg_tzi.DaylightDate.wDay, reg_tzi.DaylightDate.wMonth,
752 reg_tzi.DaylightDate.wYear, reg_tzi.DaylightDate.wDayOfWeek,
753 reg_tzi.DaylightDate.wHour, reg_tzi.DaylightDate.wMinute,
754 reg_tzi.DaylightDate.wSecond, reg_tzi.DaylightDate.wMilliseconds,
755 reg_tzi.DaylightBias);
757 NtClose(hSubkey);
759 if (match_tz_info(tzi, &reg_tzi)
760 && match_tz_name(tz_name, &reg_tzi))
762 *tzi = reg_tzi;
763 NtClose(hkey);
764 return;
767 /* reset len */
768 nameW.Length = sizeof(buf);
769 nameW.MaximumLength = sizeof(buf);
772 NtClose(hkey);
774 FIXME("Can't find matching timezone information in the registry for "
775 "%s, bias %d, std (d/m/y): %u/%02u/%04u, dlt (d/m/y): %u/%02u/%04u\n",
776 tz_name, tzi->Bias,
777 tzi->StandardDate.wDay, tzi->StandardDate.wMonth, tzi->StandardDate.wYear,
778 tzi->DaylightDate.wDay, tzi->DaylightDate.wMonth, tzi->DaylightDate.wYear);
781 static time_t find_dst_change(unsigned long min, unsigned long max, int *is_dst)
783 time_t start;
784 struct tm *tm;
786 start = min;
787 tm = localtime(&start);
788 *is_dst = !tm->tm_isdst;
789 TRACE("starting date isdst %d, %s", !*is_dst, ctime(&start));
791 while (min <= max)
793 time_t pos = (min + max) / 2;
794 tm = localtime(&pos);
796 if (tm->tm_isdst != *is_dst)
797 min = pos + 1;
798 else
799 max = pos - 1;
801 return min;
804 static int init_tz_info(RTL_DYNAMIC_TIME_ZONE_INFORMATION *tzi)
806 static RTL_DYNAMIC_TIME_ZONE_INFORMATION cached_tzi;
807 static int current_year = -1, current_bias = 65535;
808 struct tm *tm;
809 char tz_name[SHORT_TZ_NAME_MAX];
810 time_t year_start, year_end, tmp, dlt = 0, std = 0;
811 int is_dst, current_is_dst, bias;
813 RtlEnterCriticalSection( &TIME_tz_section );
815 year_start = time(NULL);
816 tm = gmtime(&year_start);
817 bias = (LONG)(mktime(tm) - year_start) / 60;
819 tm = localtime(&year_start);
820 current_is_dst = tm->tm_isdst;
821 if (current_year == tm->tm_year && current_bias == bias)
823 *tzi = cached_tzi;
824 RtlLeaveCriticalSection( &TIME_tz_section );
825 return current_is_dst;
828 memset(tzi, 0, sizeof(*tzi));
829 if (!strftime(tz_name, sizeof(tz_name), "%Z", tm)) {
830 /* not enough room or another error */
831 tz_name[0] = '\0';
834 TRACE("tz data will be valid through year %d, bias %d\n", tm->tm_year + 1900, bias);
835 current_year = tm->tm_year;
836 current_bias = bias;
838 tzi->Bias = bias;
840 tm->tm_isdst = 0;
841 tm->tm_mday = 1;
842 tm->tm_mon = tm->tm_hour = tm->tm_min = tm->tm_sec = tm->tm_wday = tm->tm_yday = 0;
843 year_start = mktime(tm);
844 TRACE("year_start: %s", ctime(&year_start));
846 tm->tm_mday = tm->tm_wday = tm->tm_yday = 0;
847 tm->tm_mon = 12;
848 tm->tm_hour = 23;
849 tm->tm_min = tm->tm_sec = 59;
850 year_end = mktime(tm);
851 TRACE("year_end: %s", ctime(&year_end));
853 tmp = find_dst_change(year_start, year_end, &is_dst);
854 if (is_dst)
855 dlt = tmp;
856 else
857 std = tmp;
859 tmp = find_dst_change(tmp, year_end, &is_dst);
860 if (is_dst)
861 dlt = tmp;
862 else
863 std = tmp;
865 TRACE("std: %s", ctime(&std));
866 TRACE("dlt: %s", ctime(&dlt));
868 if (dlt == std || !dlt || !std)
869 TRACE("there is no daylight saving rules in this time zone\n");
870 else
872 tmp = dlt - tzi->Bias * 60;
873 tm = gmtime(&tmp);
874 TRACE("dlt gmtime: %s", asctime(tm));
876 tzi->DaylightBias = -60;
877 tzi->DaylightDate.wYear = tm->tm_year + 1900;
878 tzi->DaylightDate.wMonth = tm->tm_mon + 1;
879 tzi->DaylightDate.wDayOfWeek = tm->tm_wday;
880 tzi->DaylightDate.wDay = tm->tm_mday;
881 tzi->DaylightDate.wHour = tm->tm_hour;
882 tzi->DaylightDate.wMinute = tm->tm_min;
883 tzi->DaylightDate.wSecond = tm->tm_sec;
884 tzi->DaylightDate.wMilliseconds = 0;
886 TRACE("daylight (d/m/y): %u/%02u/%04u day of week %u %u:%02u:%02u.%03u bias %d\n",
887 tzi->DaylightDate.wDay, tzi->DaylightDate.wMonth,
888 tzi->DaylightDate.wYear, tzi->DaylightDate.wDayOfWeek,
889 tzi->DaylightDate.wHour, tzi->DaylightDate.wMinute,
890 tzi->DaylightDate.wSecond, tzi->DaylightDate.wMilliseconds,
891 tzi->DaylightBias);
893 tmp = std - tzi->Bias * 60 - tzi->DaylightBias * 60;
894 tm = gmtime(&tmp);
895 TRACE("std gmtime: %s", asctime(tm));
897 tzi->StandardBias = 0;
898 tzi->StandardDate.wYear = tm->tm_year + 1900;
899 tzi->StandardDate.wMonth = tm->tm_mon + 1;
900 tzi->StandardDate.wDayOfWeek = tm->tm_wday;
901 tzi->StandardDate.wDay = tm->tm_mday;
902 tzi->StandardDate.wHour = tm->tm_hour;
903 tzi->StandardDate.wMinute = tm->tm_min;
904 tzi->StandardDate.wSecond = tm->tm_sec;
905 tzi->StandardDate.wMilliseconds = 0;
907 TRACE("standard (d/m/y): %u/%02u/%04u day of week %u %u:%02u:%02u.%03u bias %d\n",
908 tzi->StandardDate.wDay, tzi->StandardDate.wMonth,
909 tzi->StandardDate.wYear, tzi->StandardDate.wDayOfWeek,
910 tzi->StandardDate.wHour, tzi->StandardDate.wMinute,
911 tzi->StandardDate.wSecond, tzi->StandardDate.wMilliseconds,
912 tzi->StandardBias);
915 find_reg_tz_info(tzi, tz_name, current_year + 1900);
916 cached_tzi = *tzi;
918 RtlLeaveCriticalSection( &TIME_tz_section );
920 return current_is_dst;
923 /***********************************************************************
924 * RtlQueryTimeZoneInformation [NTDLL.@]
926 * Get information about the current timezone.
928 * PARAMS
929 * tzinfo [O] Destination for the retrieved timezone info.
931 * RETURNS
932 * Success: STATUS_SUCCESS.
933 * Failure: An NTSTATUS error code indicating the problem.
935 NTSTATUS WINAPI RtlQueryTimeZoneInformation(RTL_TIME_ZONE_INFORMATION *ret)
937 RTL_DYNAMIC_TIME_ZONE_INFORMATION tzinfo;
939 init_tz_info( &tzinfo );
940 memcpy( ret, &tzinfo, sizeof(*ret) );
941 return STATUS_SUCCESS;
944 /***********************************************************************
945 * RtlQueryDynamicTimeZoneInformation [NTDLL.@]
947 * Get information about the current timezone.
949 * PARAMS
950 * tzinfo [O] Destination for the retrieved timezone info.
952 * RETURNS
953 * Success: STATUS_SUCCESS.
954 * Failure: An NTSTATUS error code indicating the problem.
956 NTSTATUS WINAPI RtlQueryDynamicTimeZoneInformation(RTL_DYNAMIC_TIME_ZONE_INFORMATION *tzinfo)
958 init_tz_info( tzinfo );
960 return STATUS_SUCCESS;
963 /***********************************************************************
964 * RtlSetTimeZoneInformation [NTDLL.@]
966 * Set the current time zone information.
968 * PARAMS
969 * tzinfo [I] Timezone information to set.
971 * RETURNS
972 * Success: STATUS_SUCCESS.
973 * Failure: An NTSTATUS error code indicating the problem.
976 NTSTATUS WINAPI RtlSetTimeZoneInformation( const RTL_TIME_ZONE_INFORMATION *tzinfo )
978 return STATUS_PRIVILEGE_NOT_HELD;
981 /***********************************************************************
982 * NtSetSystemTime [NTDLL.@]
983 * ZwSetSystemTime [NTDLL.@]
985 * Set the system time.
987 * PARAMS
988 * NewTime [I] The time to set.
989 * OldTime [O] Optional destination for the previous system time.
991 * RETURNS
992 * Success: STATUS_SUCCESS.
993 * Failure: An NTSTATUS error code indicating the problem.
995 NTSTATUS WINAPI NtSetSystemTime(const LARGE_INTEGER *NewTime, LARGE_INTEGER *OldTime)
997 struct timeval tv;
998 time_t tm_t;
999 DWORD sec, oldsec;
1000 LARGE_INTEGER tm;
1002 /* Return the old time if necessary */
1003 if (!OldTime) OldTime = &tm;
1005 NtQuerySystemTime( OldTime );
1006 RtlTimeToSecondsSince1970( OldTime, &oldsec );
1008 RtlTimeToSecondsSince1970( NewTime, &sec );
1010 /* fake success if time didn't change */
1011 if (oldsec == sec)
1012 return STATUS_SUCCESS;
1014 /* set the new time */
1015 tv.tv_sec = sec;
1016 tv.tv_usec = 0;
1018 #ifdef HAVE_SETTIMEOFDAY
1019 tm_t = sec;
1020 if (!settimeofday(&tv, NULL)) /* 0 is OK, -1 is error */
1022 TRACE("OS time changed to %s\n", ctime(&tm_t));
1023 return STATUS_SUCCESS;
1025 ERR("Cannot set time to %s, time adjustment %ld: %s\n",
1026 ctime(&tm_t), (long)(sec-oldsec), strerror(errno));
1027 if (errno == EPERM)
1028 return STATUS_PRIVILEGE_NOT_HELD;
1029 else
1030 return STATUS_INVALID_PARAMETER;
1031 #else
1032 tm_t = sec;
1033 FIXME("setting time to %s not implemented for missing settimeofday\n",
1034 ctime(&tm_t));
1035 return STATUS_NOT_IMPLEMENTED;
1036 #endif
1039 /***********************************************************************
1040 * RtlQueryUnbiasedInterruptTime [NTDLL.@]
1042 NTSTATUS WINAPI RtlQueryUnbiasedInterruptTime(ULONGLONG *time)
1044 *time = monotonic_counter();
1045 return STATUS_SUCCESS;