winex11: Remove unnecessary CLIPBOARDINFO structure.
[wine/multimedia.git] / dlls / ntdll / time.c
blob65bd2b61bdade3f8648f8c66eda47d89f422611b
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/unicode.h"
50 #include "wine/debug.h"
51 #include "ntdll_misc.h"
53 WINE_DEFAULT_DEBUG_CHANNEL(ntdll);
55 static int init_tz_info(RTL_TIME_ZONE_INFORMATION *tzi);
57 static RTL_CRITICAL_SECTION TIME_tz_section;
58 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
60 0, 0, &TIME_tz_section,
61 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
62 0, 0, { (DWORD_PTR)(__FILE__ ": TIME_tz_section") }
64 static RTL_CRITICAL_SECTION TIME_tz_section = { &critsect_debug, -1, 0, 0, 0, 0 };
66 #define TICKSPERSEC 10000000
67 #define TICKSPERMSEC 10000
68 #define SECSPERDAY 86400
69 #define SECSPERHOUR 3600
70 #define SECSPERMIN 60
71 #define MINSPERHOUR 60
72 #define HOURSPERDAY 24
73 #define EPOCHWEEKDAY 1 /* Jan 1, 1601 was Monday */
74 #define DAYSPERWEEK 7
75 #define MONSPERYEAR 12
76 #define DAYSPERQUADRICENTENNIUM (365 * 400 + 97)
77 #define DAYSPERNORMALQUADRENNIUM (365 * 4 + 1)
79 /* 1601 to 1970 is 369 years plus 89 leap days */
80 #define SECS_1601_TO_1970 ((369 * 365 + 89) * (ULONGLONG)SECSPERDAY)
81 #define TICKS_1601_TO_1970 (SECS_1601_TO_1970 * TICKSPERSEC)
82 /* 1601 to 1980 is 379 years plus 91 leap days */
83 #define SECS_1601_TO_1980 ((379 * 365 + 91) * (ULONGLONG)SECSPERDAY)
84 #define TICKS_1601_TO_1980 (SECS_1601_TO_1980 * TICKSPERSEC)
87 static const int MonthLengths[2][MONSPERYEAR] =
89 { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
90 { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
93 static inline BOOL IsLeapYear(int Year)
95 return Year % 4 == 0 && (Year % 100 != 0 || Year % 400 == 0);
98 /* return a monotonic time counter, in Win32 ticks */
99 static ULONGLONG monotonic_counter(void)
101 struct timeval now;
103 #ifdef HAVE_CLOCK_GETTIME
104 struct timespec ts;
105 #ifdef CLOCK_MONOTONIC_RAW
106 if (!clock_gettime( CLOCK_MONOTONIC_RAW, &ts ))
107 return ts.tv_sec * (ULONGLONG)TICKSPERSEC + ts.tv_nsec / 100;
108 #endif
109 if (!clock_gettime( CLOCK_MONOTONIC, &ts ))
110 return ts.tv_sec * (ULONGLONG)TICKSPERSEC + ts.tv_nsec / 100;
111 #elif defined(__APPLE__)
112 static mach_timebase_info_data_t timebase;
114 if (!timebase.denom) mach_timebase_info( &timebase );
115 return mach_absolute_time() * timebase.numer / timebase.denom / 100;
116 #endif
118 gettimeofday( &now, 0 );
119 return now.tv_sec * (ULONGLONG)TICKSPERSEC + now.tv_usec * 10 + TICKS_1601_TO_1970 - server_start_time;
122 /******************************************************************************
123 * RtlTimeToTimeFields [NTDLL.@]
125 * Convert a time into a TIME_FIELDS structure.
127 * PARAMS
128 * liTime [I] Time to convert.
129 * TimeFields [O] Destination for the converted time.
131 * RETURNS
132 * Nothing.
134 VOID WINAPI RtlTimeToTimeFields(
135 const LARGE_INTEGER *liTime,
136 PTIME_FIELDS TimeFields)
138 int SecondsInDay;
139 long int cleaps, years, yearday, months;
140 long int Days;
141 LONGLONG Time;
143 /* Extract millisecond from time and convert time into seconds */
144 TimeFields->Milliseconds =
145 (CSHORT) (( liTime->QuadPart % TICKSPERSEC) / TICKSPERMSEC);
146 Time = liTime->QuadPart / TICKSPERSEC;
148 /* The native version of RtlTimeToTimeFields does not take leap seconds
149 * into account */
151 /* Split the time into days and seconds within the day */
152 Days = Time / SECSPERDAY;
153 SecondsInDay = Time % SECSPERDAY;
155 /* compute time of day */
156 TimeFields->Hour = (CSHORT) (SecondsInDay / SECSPERHOUR);
157 SecondsInDay = SecondsInDay % SECSPERHOUR;
158 TimeFields->Minute = (CSHORT) (SecondsInDay / SECSPERMIN);
159 TimeFields->Second = (CSHORT) (SecondsInDay % SECSPERMIN);
161 /* compute day of week */
162 TimeFields->Weekday = (CSHORT) ((EPOCHWEEKDAY + Days) % DAYSPERWEEK);
164 /* compute year, month and day of month. */
165 cleaps=( 3 * ((4 * Days + 1227) / DAYSPERQUADRICENTENNIUM) + 3 ) / 4;
166 Days += 28188 + cleaps;
167 years = (20 * Days - 2442) / (5 * DAYSPERNORMALQUADRENNIUM);
168 yearday = Days - (years * DAYSPERNORMALQUADRENNIUM)/4;
169 months = (64 * yearday) / 1959;
170 /* the result is based on a year starting on March.
171 * To convert take 12 from Januari and Februari and
172 * increase the year by one. */
173 if( months < 14 ) {
174 TimeFields->Month = months - 1;
175 TimeFields->Year = years + 1524;
176 } else {
177 TimeFields->Month = months - 13;
178 TimeFields->Year = years + 1525;
180 /* calculation of day of month is based on the wonderful
181 * sequence of INT( n * 30.6): it reproduces the
182 * 31-30-31-30-31-31 month lengths exactly for small n's */
183 TimeFields->Day = yearday - (1959 * months) / 64 ;
184 return;
187 /******************************************************************************
188 * RtlTimeFieldsToTime [NTDLL.@]
190 * Convert a TIME_FIELDS structure into a time.
192 * PARAMS
193 * ftTimeFields [I] TIME_FIELDS structure to convert.
194 * Time [O] Destination for the converted time.
196 * RETURNS
197 * Success: TRUE.
198 * Failure: FALSE.
200 BOOLEAN WINAPI RtlTimeFieldsToTime(
201 PTIME_FIELDS tfTimeFields,
202 PLARGE_INTEGER Time)
204 int month, year, cleaps, day;
206 /* FIXME: normalize the TIME_FIELDS structure here */
207 /* No, native just returns 0 (error) if the fields are not */
208 if( tfTimeFields->Milliseconds< 0 || tfTimeFields->Milliseconds > 999 ||
209 tfTimeFields->Second < 0 || tfTimeFields->Second > 59 ||
210 tfTimeFields->Minute < 0 || tfTimeFields->Minute > 59 ||
211 tfTimeFields->Hour < 0 || tfTimeFields->Hour > 23 ||
212 tfTimeFields->Month < 1 || tfTimeFields->Month > 12 ||
213 tfTimeFields->Day < 1 ||
214 tfTimeFields->Day > MonthLengths
215 [ tfTimeFields->Month ==2 || IsLeapYear(tfTimeFields->Year)]
216 [ tfTimeFields->Month - 1] ||
217 tfTimeFields->Year < 1601 )
218 return FALSE;
220 /* now calculate a day count from the date
221 * First start counting years from March. This way the leap days
222 * are added at the end of the year, not somewhere in the middle.
223 * Formula's become so much less complicate that way.
224 * To convert: add 12 to the month numbers of Jan and Feb, and
225 * take 1 from the year */
226 if(tfTimeFields->Month < 3) {
227 month = tfTimeFields->Month + 13;
228 year = tfTimeFields->Year - 1;
229 } else {
230 month = tfTimeFields->Month + 1;
231 year = tfTimeFields->Year;
233 cleaps = (3 * (year / 100) + 3) / 4; /* nr of "century leap years"*/
234 day = (36525 * year) / 100 - cleaps + /* year * dayperyr, corrected */
235 (1959 * month) / 64 + /* months * daypermonth */
236 tfTimeFields->Day - /* day of the month */
237 584817 ; /* zero that on 1601-01-01 */
238 /* done */
240 Time->QuadPart = (((((LONGLONG) day * HOURSPERDAY +
241 tfTimeFields->Hour) * MINSPERHOUR +
242 tfTimeFields->Minute) * SECSPERMIN +
243 tfTimeFields->Second ) * 1000 +
244 tfTimeFields->Milliseconds ) * TICKSPERMSEC;
246 return TRUE;
249 /***********************************************************************
250 * TIME_GetBias [internal]
252 * Helper function calculates delta local time from UTC.
254 * PARAMS
255 * utc [I] The current utc time.
256 * pdaylight [I] Local daylight.
258 * RETURNS
259 * The bias for the current timezone.
261 static LONG TIME_GetBias(void)
263 static time_t last_utc;
264 static LONG last_bias;
265 LONG ret;
266 time_t utc;
268 utc = time( NULL );
270 RtlEnterCriticalSection( &TIME_tz_section );
271 if (utc != last_utc)
273 RTL_TIME_ZONE_INFORMATION tzi;
274 int is_dst = init_tz_info( &tzi );
276 last_utc = utc;
277 last_bias = tzi.Bias;
278 last_bias += is_dst ? tzi.DaylightBias : tzi.StandardBias;
279 last_bias *= SECSPERMIN;
282 ret = last_bias;
284 RtlLeaveCriticalSection( &TIME_tz_section );
285 return ret;
288 /******************************************************************************
289 * RtlLocalTimeToSystemTime [NTDLL.@]
291 * Convert a local time into system time.
293 * PARAMS
294 * LocalTime [I] Local time to convert.
295 * SystemTime [O] Destination for the converted time.
297 * RETURNS
298 * Success: STATUS_SUCCESS.
299 * Failure: An NTSTATUS error code indicating the problem.
301 NTSTATUS WINAPI RtlLocalTimeToSystemTime( const LARGE_INTEGER *LocalTime,
302 PLARGE_INTEGER SystemTime)
304 LONG bias;
306 TRACE("(%p, %p)\n", LocalTime, SystemTime);
308 bias = TIME_GetBias();
309 SystemTime->QuadPart = LocalTime->QuadPart + bias * (LONGLONG)TICKSPERSEC;
310 return STATUS_SUCCESS;
313 /******************************************************************************
314 * RtlSystemTimeToLocalTime [NTDLL.@]
316 * Convert a system time into a local time.
318 * PARAMS
319 * SystemTime [I] System time to convert.
320 * LocalTime [O] Destination for the converted time.
322 * RETURNS
323 * Success: STATUS_SUCCESS.
324 * Failure: An NTSTATUS error code indicating the problem.
326 NTSTATUS WINAPI RtlSystemTimeToLocalTime( const LARGE_INTEGER *SystemTime,
327 PLARGE_INTEGER LocalTime )
329 LONG bias;
331 TRACE("(%p, %p)\n", SystemTime, LocalTime);
333 bias = TIME_GetBias();
334 LocalTime->QuadPart = SystemTime->QuadPart - bias * (LONGLONG)TICKSPERSEC;
335 return STATUS_SUCCESS;
338 /******************************************************************************
339 * RtlTimeToSecondsSince1970 [NTDLL.@]
341 * Convert a time into a count of seconds since 1970.
343 * PARAMS
344 * Time [I] Time to convert.
345 * Seconds [O] Destination for the converted time.
347 * RETURNS
348 * Success: TRUE.
349 * Failure: FALSE, if the resulting value will not fit in a DWORD.
351 BOOLEAN WINAPI RtlTimeToSecondsSince1970( const LARGE_INTEGER *Time, LPDWORD Seconds )
353 ULONGLONG tmp = Time->QuadPart / TICKSPERSEC - SECS_1601_TO_1970;
354 if (tmp > 0xffffffff) return FALSE;
355 *Seconds = tmp;
356 return TRUE;
359 /******************************************************************************
360 * RtlTimeToSecondsSince1980 [NTDLL.@]
362 * Convert a time into a count of seconds since 1980.
364 * PARAMS
365 * Time [I] Time to convert.
366 * Seconds [O] Destination for the converted time.
368 * RETURNS
369 * Success: TRUE.
370 * Failure: FALSE, if the resulting value will not fit in a DWORD.
372 BOOLEAN WINAPI RtlTimeToSecondsSince1980( const LARGE_INTEGER *Time, LPDWORD Seconds )
374 ULONGLONG tmp = Time->QuadPart / TICKSPERSEC - SECS_1601_TO_1980;
375 if (tmp > 0xffffffff) return FALSE;
376 *Seconds = tmp;
377 return TRUE;
380 /******************************************************************************
381 * RtlSecondsSince1970ToTime [NTDLL.@]
383 * Convert a count of seconds since 1970 to a time.
385 * PARAMS
386 * Seconds [I] Time to convert.
387 * Time [O] Destination for the converted time.
389 * RETURNS
390 * Nothing.
392 void WINAPI RtlSecondsSince1970ToTime( DWORD Seconds, LARGE_INTEGER *Time )
394 Time->QuadPart = Seconds * (ULONGLONG)TICKSPERSEC + TICKS_1601_TO_1970;
397 /******************************************************************************
398 * RtlSecondsSince1980ToTime [NTDLL.@]
400 * Convert a count of seconds since 1980 to a time.
402 * PARAMS
403 * Seconds [I] Time to convert.
404 * Time [O] Destination for the converted time.
406 * RETURNS
407 * Nothing.
409 void WINAPI RtlSecondsSince1980ToTime( DWORD Seconds, LARGE_INTEGER *Time )
411 Time->QuadPart = Seconds * (ULONGLONG)TICKSPERSEC + TICKS_1601_TO_1980;
414 /******************************************************************************
415 * RtlTimeToElapsedTimeFields [NTDLL.@]
417 * Convert a time to a count of elapsed seconds.
419 * PARAMS
420 * Time [I] Time to convert.
421 * TimeFields [O] Destination for the converted time.
423 * RETURNS
424 * Nothing.
426 void WINAPI RtlTimeToElapsedTimeFields( const LARGE_INTEGER *Time, PTIME_FIELDS TimeFields )
428 LONGLONG time;
429 INT rem;
431 time = Time->QuadPart / TICKSPERSEC;
432 TimeFields->Milliseconds = (Time->QuadPart % TICKSPERSEC) / TICKSPERMSEC;
434 /* time is now in seconds */
435 TimeFields->Year = 0;
436 TimeFields->Month = 0;
437 TimeFields->Day = time / SECSPERDAY;
439 /* rem is now the remaining seconds in the last day */
440 rem = time % SECSPERDAY;
441 TimeFields->Second = rem % 60;
442 rem /= 60;
443 TimeFields->Minute = rem % 60;
444 TimeFields->Hour = rem / 60;
447 /***********************************************************************
448 * NtQuerySystemTime [NTDLL.@]
449 * ZwQuerySystemTime [NTDLL.@]
451 * Get the current system time.
453 * PARAMS
454 * Time [O] Destination for the current system time.
456 * RETURNS
457 * Success: STATUS_SUCCESS.
458 * Failure: An NTSTATUS error code indicating the problem.
460 NTSTATUS WINAPI NtQuerySystemTime( PLARGE_INTEGER Time )
462 struct timeval now;
464 gettimeofday( &now, 0 );
465 Time->QuadPart = now.tv_sec * (ULONGLONG)TICKSPERSEC + TICKS_1601_TO_1970;
466 Time->QuadPart += now.tv_usec * 10;
467 return STATUS_SUCCESS;
470 /******************************************************************************
471 * NtQueryPerformanceCounter [NTDLL.@]
473 NTSTATUS WINAPI NtQueryPerformanceCounter( LARGE_INTEGER *counter, LARGE_INTEGER *frequency )
475 if (!counter) return STATUS_ACCESS_VIOLATION;
477 counter->QuadPart = monotonic_counter();
478 if (frequency) frequency->QuadPart = TICKSPERSEC;
479 return STATUS_SUCCESS;
483 /******************************************************************************
484 * NtGetTickCount (NTDLL.@)
485 * ZwGetTickCount (NTDLL.@)
487 ULONG WINAPI NtGetTickCount(void)
489 return monotonic_counter() / TICKSPERMSEC;
492 /* calculate the mday of dst change date, so that for instance Sun 5 Oct 2007
493 * (last Sunday in October of 2007) becomes Sun Oct 28 2007
495 * Note: year, day and month must be in unix format.
497 static int weekday_to_mday(int year, int day, int mon, int day_of_week)
499 struct tm date;
500 time_t tmp;
501 int wday, mday;
503 /* find first day in the month matching week day of the date */
504 memset(&date, 0, sizeof(date));
505 date.tm_year = year;
506 date.tm_mon = mon;
507 date.tm_mday = -1;
508 date.tm_wday = -1;
511 date.tm_mday++;
512 tmp = mktime(&date);
513 } while (date.tm_wday != day_of_week || date.tm_mon != mon);
515 mday = date.tm_mday;
517 /* find number of week days in the month matching week day of the date */
518 wday = 1; /* 1 - 1st, ...., 5 - last */
519 while (wday < day)
521 struct tm *tm;
523 date.tm_mday += 7;
524 tmp = mktime(&date);
525 tm = localtime(&tmp);
526 if (tm->tm_mon != mon)
527 break;
528 mday = tm->tm_mday;
529 wday++;
532 return mday;
535 static BOOL match_tz_date(const RTL_SYSTEM_TIME *st, const RTL_SYSTEM_TIME *reg_st)
537 WORD wDay;
539 if (st->wMonth != reg_st->wMonth) return FALSE;
541 if (!st->wMonth) return TRUE; /* no transition dates */
543 wDay = reg_st->wDay;
544 if (!reg_st->wYear) /* date in a day-of-week format */
545 wDay = weekday_to_mday(st->wYear - 1900, reg_st->wDay, reg_st->wMonth - 1, reg_st->wDayOfWeek);
547 if (st->wDay != wDay ||
548 st->wHour != reg_st->wHour ||
549 st->wMinute != reg_st->wMinute ||
550 st->wSecond != reg_st->wSecond ||
551 st->wMilliseconds != reg_st->wMilliseconds) return FALSE;
553 return TRUE;
556 static BOOL match_tz_info(const RTL_TIME_ZONE_INFORMATION *tzi, const RTL_TIME_ZONE_INFORMATION *reg_tzi)
558 if (tzi->Bias == reg_tzi->Bias &&
559 match_tz_date(&tzi->StandardDate, &reg_tzi->StandardDate) &&
560 match_tz_date(&tzi->DaylightDate, &reg_tzi->DaylightDate))
561 return TRUE;
563 return FALSE;
566 static BOOL reg_query_value(HKEY hkey, LPCWSTR name, DWORD type, void *data, DWORD count)
568 UNICODE_STRING nameW;
569 char buf[256];
570 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buf;
572 if (count > sizeof(buf) - sizeof(KEY_VALUE_PARTIAL_INFORMATION))
573 return FALSE;
575 RtlInitUnicodeString(&nameW, name);
577 if (NtQueryValueKey(hkey, &nameW, KeyValuePartialInformation,
578 buf, sizeof(buf), &count))
579 return FALSE;
581 if (info->Type != type) return FALSE;
583 memcpy(data, info->Data, info->DataLength);
584 return TRUE;
587 static void find_reg_tz_info(RTL_TIME_ZONE_INFORMATION *tzi)
589 static const WCHAR Time_ZonesW[] = { 'M','a','c','h','i','n','e','\\',
590 'S','o','f','t','w','a','r','e','\\',
591 'M','i','c','r','o','s','o','f','t','\\',
592 'W','i','n','d','o','w','s',' ','N','T','\\',
593 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
594 'T','i','m','e',' ','Z','o','n','e','s',0 };
595 static const WCHAR Dynamic_DstW[] = { 'D','y','n','a','m','i','c',' ','D','S','T',0 };
596 static const WCHAR fmtW[] = { '%','d',0 };
597 HANDLE hkey;
598 ULONG idx;
599 OBJECT_ATTRIBUTES attr, attrDynamic;
600 UNICODE_STRING nameW, nameDynamicW;
601 WCHAR buf[128], yearW[16];
603 sprintfW(yearW, fmtW, tzi->DaylightDate.wYear);
605 attrDynamic.Length = sizeof(attrDynamic);
606 attrDynamic.RootDirectory = 0; /* will be replaced later */
607 attrDynamic.ObjectName = &nameDynamicW;
608 attrDynamic.Attributes = 0;
609 attrDynamic.SecurityDescriptor = NULL;
610 attrDynamic.SecurityQualityOfService = NULL;
611 RtlInitUnicodeString(&nameDynamicW, Dynamic_DstW);
613 attr.Length = sizeof(attr);
614 attr.RootDirectory = 0;
615 attr.ObjectName = &nameW;
616 attr.Attributes = 0;
617 attr.SecurityDescriptor = NULL;
618 attr.SecurityQualityOfService = NULL;
619 RtlInitUnicodeString(&nameW, Time_ZonesW);
620 if (NtOpenKey(&hkey, KEY_READ, &attr))
622 WARN("Unable to open the time zones key\n");
623 return;
626 idx = 0;
627 nameW.Buffer = buf;
628 nameW.Length = sizeof(buf);
629 nameW.MaximumLength = sizeof(buf);
631 while (!RtlpNtEnumerateSubKey(hkey, &nameW, idx++))
633 static const WCHAR stdW[] = { 'S','t','d',0 };
634 static const WCHAR dltW[] = { 'D','l','t',0 };
635 static const WCHAR tziW[] = { 'T','Z','I',0 };
636 RTL_TIME_ZONE_INFORMATION reg_tzi;
637 HANDLE hSubkey, hSubkeyDynamicDST;
638 BOOL is_dynamic = FALSE;
640 struct tz_reg_data
642 LONG bias;
643 LONG std_bias;
644 LONG dlt_bias;
645 RTL_SYSTEM_TIME std_date;
646 RTL_SYSTEM_TIME dlt_date;
647 } tz_data;
649 attr.Length = sizeof(attr);
650 attr.RootDirectory = hkey;
651 attr.ObjectName = &nameW;
652 attr.Attributes = 0;
653 attr.SecurityDescriptor = NULL;
654 attr.SecurityQualityOfService = NULL;
655 if (NtOpenKey(&hSubkey, KEY_READ, &attr))
657 WARN("Unable to open subkey %s\n", debugstr_wn(nameW.Buffer, nameW.Length/sizeof(WCHAR)));
658 continue;
661 #define get_value(hkey, name, type, data, len) \
662 if (!reg_query_value(hkey, name, type, data, len)) \
664 WARN("can't read data from %s\n", debugstr_w(name)); \
665 NtClose(hkey); \
666 continue; \
669 get_value(hSubkey, stdW, REG_SZ, reg_tzi.StandardName, sizeof(reg_tzi.StandardName));
670 get_value(hSubkey, dltW, REG_SZ, reg_tzi.DaylightName, sizeof(reg_tzi.DaylightName));
672 /* Check for Dynamic DST entry first */
673 attrDynamic.RootDirectory = hSubkey;
674 if (!NtOpenKey(&hSubkeyDynamicDST, KEY_READ, &attrDynamic))
676 is_dynamic = reg_query_value(hSubkeyDynamicDST, yearW, REG_BINARY, &tz_data, sizeof(tz_data));
677 NtClose(hSubkeyDynamicDST);
680 if (!is_dynamic)
681 get_value(hSubkey, tziW, REG_BINARY, &tz_data, sizeof(tz_data));
683 #undef get_value
685 reg_tzi.Bias = tz_data.bias;
686 reg_tzi.StandardBias = tz_data.std_bias;
687 reg_tzi.DaylightBias = tz_data.dlt_bias;
688 reg_tzi.StandardDate = tz_data.std_date;
689 reg_tzi.DaylightDate = tz_data.dlt_date;
691 TRACE("%s: bias %d\n", debugstr_wn(nameW.Buffer, nameW.Length/sizeof(WCHAR)), reg_tzi.Bias);
692 TRACE("std (d/m/y): %u/%02u/%04u day of week %u %u:%02u:%02u.%03u bias %d\n",
693 reg_tzi.StandardDate.wDay, reg_tzi.StandardDate.wMonth,
694 reg_tzi.StandardDate.wYear, reg_tzi.StandardDate.wDayOfWeek,
695 reg_tzi.StandardDate.wHour, reg_tzi.StandardDate.wMinute,
696 reg_tzi.StandardDate.wSecond, reg_tzi.StandardDate.wMilliseconds,
697 reg_tzi.StandardBias);
698 TRACE("dst (d/m/y): %u/%02u/%04u day of week %u %u:%02u:%02u.%03u bias %d\n",
699 reg_tzi.DaylightDate.wDay, reg_tzi.DaylightDate.wMonth,
700 reg_tzi.DaylightDate.wYear, reg_tzi.DaylightDate.wDayOfWeek,
701 reg_tzi.DaylightDate.wHour, reg_tzi.DaylightDate.wMinute,
702 reg_tzi.DaylightDate.wSecond, reg_tzi.DaylightDate.wMilliseconds,
703 reg_tzi.DaylightBias);
705 NtClose(hSubkey);
707 if (match_tz_info(tzi, &reg_tzi))
709 *tzi = reg_tzi;
710 NtClose(hkey);
711 return;
714 /* reset len */
715 nameW.Length = sizeof(buf);
716 nameW.MaximumLength = sizeof(buf);
719 NtClose(hkey);
721 FIXME("Can't find matching timezone information in the registry for "
722 "bias %d, std (d/m/y): %u/%02u/%04u, dlt (d/m/y): %u/%02u/%04u\n",
723 tzi->Bias,
724 tzi->StandardDate.wDay, tzi->StandardDate.wMonth, tzi->StandardDate.wYear,
725 tzi->DaylightDate.wDay, tzi->DaylightDate.wMonth, tzi->DaylightDate.wYear);
728 static time_t find_dst_change(unsigned long min, unsigned long max, int *is_dst)
730 time_t start;
731 struct tm *tm;
733 start = min;
734 tm = localtime(&start);
735 *is_dst = !tm->tm_isdst;
736 TRACE("starting date isdst %d, %s", !*is_dst, ctime(&start));
738 while (min <= max)
740 time_t pos = (min + max) / 2;
741 tm = localtime(&pos);
743 if (tm->tm_isdst != *is_dst)
744 min = pos + 1;
745 else
746 max = pos - 1;
748 return min;
751 static int init_tz_info(RTL_TIME_ZONE_INFORMATION *tzi)
753 static RTL_TIME_ZONE_INFORMATION cached_tzi;
754 static int current_year = -1, current_bias = 65535;
755 struct tm *tm;
756 time_t year_start, year_end, tmp, dlt = 0, std = 0;
757 int is_dst, current_is_dst, bias;
759 RtlEnterCriticalSection( &TIME_tz_section );
761 year_start = time(NULL);
762 tm = gmtime(&year_start);
763 bias = (LONG)(mktime(tm) - year_start) / 60;
765 tm = localtime(&year_start);
766 current_is_dst = tm->tm_isdst;
767 if (current_year == tm->tm_year && current_bias == bias)
769 *tzi = cached_tzi;
770 RtlLeaveCriticalSection( &TIME_tz_section );
771 return current_is_dst;
774 memset(tzi, 0, sizeof(*tzi));
776 TRACE("tz data will be valid through year %d, bias %d\n", tm->tm_year + 1900, bias);
777 current_year = tm->tm_year;
778 current_bias = bias;
780 tzi->Bias = bias;
782 tm->tm_isdst = 0;
783 tm->tm_mday = 1;
784 tm->tm_mon = tm->tm_hour = tm->tm_min = tm->tm_sec = tm->tm_wday = tm->tm_yday = 0;
785 year_start = mktime(tm);
786 TRACE("year_start: %s", ctime(&year_start));
788 tm->tm_mday = tm->tm_wday = tm->tm_yday = 0;
789 tm->tm_mon = 12;
790 tm->tm_hour = 23;
791 tm->tm_min = tm->tm_sec = 59;
792 year_end = mktime(tm);
793 TRACE("year_end: %s", ctime(&year_end));
795 tmp = find_dst_change(year_start, year_end, &is_dst);
796 if (is_dst)
797 dlt = tmp;
798 else
799 std = tmp;
801 tmp = find_dst_change(tmp, year_end, &is_dst);
802 if (is_dst)
803 dlt = tmp;
804 else
805 std = tmp;
807 TRACE("std: %s", ctime(&std));
808 TRACE("dlt: %s", ctime(&dlt));
810 if (dlt == std || !dlt || !std)
811 TRACE("there is no daylight saving rules in this time zone\n");
812 else
814 tmp = dlt - tzi->Bias * 60;
815 tm = gmtime(&tmp);
816 TRACE("dlt gmtime: %s", asctime(tm));
818 tzi->DaylightBias = -60;
819 tzi->DaylightDate.wYear = tm->tm_year + 1900;
820 tzi->DaylightDate.wMonth = tm->tm_mon + 1;
821 tzi->DaylightDate.wDayOfWeek = tm->tm_wday;
822 tzi->DaylightDate.wDay = tm->tm_mday;
823 tzi->DaylightDate.wHour = tm->tm_hour;
824 tzi->DaylightDate.wMinute = tm->tm_min;
825 tzi->DaylightDate.wSecond = tm->tm_sec;
826 tzi->DaylightDate.wMilliseconds = 0;
828 TRACE("daylight (d/m/y): %u/%02u/%04u day of week %u %u:%02u:%02u.%03u bias %d\n",
829 tzi->DaylightDate.wDay, tzi->DaylightDate.wMonth,
830 tzi->DaylightDate.wYear, tzi->DaylightDate.wDayOfWeek,
831 tzi->DaylightDate.wHour, tzi->DaylightDate.wMinute,
832 tzi->DaylightDate.wSecond, tzi->DaylightDate.wMilliseconds,
833 tzi->DaylightBias);
835 tmp = std - tzi->Bias * 60 - tzi->DaylightBias * 60;
836 tm = gmtime(&tmp);
837 TRACE("std gmtime: %s", asctime(tm));
839 tzi->StandardBias = 0;
840 tzi->StandardDate.wYear = tm->tm_year + 1900;
841 tzi->StandardDate.wMonth = tm->tm_mon + 1;
842 tzi->StandardDate.wDayOfWeek = tm->tm_wday;
843 tzi->StandardDate.wDay = tm->tm_mday;
844 tzi->StandardDate.wHour = tm->tm_hour;
845 tzi->StandardDate.wMinute = tm->tm_min;
846 tzi->StandardDate.wSecond = tm->tm_sec;
847 tzi->StandardDate.wMilliseconds = 0;
849 TRACE("standard (d/m/y): %u/%02u/%04u day of week %u %u:%02u:%02u.%03u bias %d\n",
850 tzi->StandardDate.wDay, tzi->StandardDate.wMonth,
851 tzi->StandardDate.wYear, tzi->StandardDate.wDayOfWeek,
852 tzi->StandardDate.wHour, tzi->StandardDate.wMinute,
853 tzi->StandardDate.wSecond, tzi->StandardDate.wMilliseconds,
854 tzi->StandardBias);
857 find_reg_tz_info(tzi);
858 cached_tzi = *tzi;
860 RtlLeaveCriticalSection( &TIME_tz_section );
862 return current_is_dst;
865 /***********************************************************************
866 * RtlQueryTimeZoneInformation [NTDLL.@]
868 * Get information about the current timezone.
870 * PARAMS
871 * tzinfo [O] Destination for the retrieved timezone info.
873 * RETURNS
874 * Success: STATUS_SUCCESS.
875 * Failure: An NTSTATUS error code indicating the problem.
877 NTSTATUS WINAPI RtlQueryTimeZoneInformation(RTL_TIME_ZONE_INFORMATION *tzinfo)
879 init_tz_info( tzinfo );
881 return STATUS_SUCCESS;
884 /***********************************************************************
885 * RtlSetTimeZoneInformation [NTDLL.@]
887 * Set the current time zone information.
889 * PARAMS
890 * tzinfo [I] Timezone information to set.
892 * RETURNS
893 * Success: STATUS_SUCCESS.
894 * Failure: An NTSTATUS error code indicating the problem.
897 NTSTATUS WINAPI RtlSetTimeZoneInformation( const RTL_TIME_ZONE_INFORMATION *tzinfo )
899 return STATUS_PRIVILEGE_NOT_HELD;
902 /***********************************************************************
903 * NtSetSystemTime [NTDLL.@]
904 * ZwSetSystemTime [NTDLL.@]
906 * Set the system time.
908 * PARAMS
909 * NewTime [I] The time to set.
910 * OldTime [O] Optional destination for the previous system time.
912 * RETURNS
913 * Success: STATUS_SUCCESS.
914 * Failure: An NTSTATUS error code indicating the problem.
916 NTSTATUS WINAPI NtSetSystemTime(const LARGE_INTEGER *NewTime, LARGE_INTEGER *OldTime)
918 struct timeval tv;
919 time_t tm_t;
920 DWORD sec, oldsec;
921 LARGE_INTEGER tm;
923 /* Return the old time if necessary */
924 if (!OldTime) OldTime = &tm;
926 NtQuerySystemTime( OldTime );
927 RtlTimeToSecondsSince1970( OldTime, &oldsec );
929 RtlTimeToSecondsSince1970( NewTime, &sec );
931 /* set the new time */
932 tv.tv_sec = sec;
933 tv.tv_usec = 0;
935 #ifdef HAVE_SETTIMEOFDAY
936 if (!settimeofday(&tv, NULL)) /* 0 is OK, -1 is error */
937 return STATUS_SUCCESS;
938 tm_t = sec;
939 ERR("Cannot set time to %s, time adjustment %ld: %s\n",
940 ctime(&tm_t), (long)(sec-oldsec), strerror(errno));
941 if (errno == EPERM)
942 return STATUS_PRIVILEGE_NOT_HELD;
943 else
944 return STATUS_INVALID_PARAMETER;
945 #else
946 tm_t = sec;
947 FIXME("setting time to %s not implemented for missing settimeofday\n",
948 ctime(&tm_t));
949 return STATUS_NOT_IMPLEMENTED;
950 #endif
953 /***********************************************************************
954 * RtlQueryUnbiasedInterruptTime [NTDLL.@]
956 NTSTATUS WINAPI RtlQueryUnbiasedInterruptTime(ULONGLONG *time)
958 *time = monotonic_counter();
959 return STATUS_SUCCESS;