ntdll: Assert when trying to replace an exiting file descriptor in fd_cache.
[wine/multimedia.git] / dlls / ntdll / time.c
blob0f14a3ee3afa7b13a5025a3d5915b9eae53c7567
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 #define NONAMELESSUNION
46 #define NONAMELESSSTRUCT
47 #include "ntstatus.h"
48 #define WIN32_NO_STATUS
49 #include "windef.h"
50 #include "winternl.h"
51 #include "wine/unicode.h"
52 #include "wine/debug.h"
53 #include "ntdll_misc.h"
55 WINE_DEFAULT_DEBUG_CHANNEL(ntdll);
57 static int init_tz_info(RTL_TIME_ZONE_INFORMATION *tzi);
59 static RTL_CRITICAL_SECTION TIME_tz_section;
60 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
62 0, 0, &TIME_tz_section,
63 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
64 0, 0, { (DWORD_PTR)(__FILE__ ": TIME_tz_section") }
66 static RTL_CRITICAL_SECTION TIME_tz_section = { &critsect_debug, -1, 0, 0, 0, 0 };
68 #define TICKSPERSEC 10000000
69 #define TICKSPERMSEC 10000
70 #define SECSPERDAY 86400
71 #define SECSPERHOUR 3600
72 #define SECSPERMIN 60
73 #define MINSPERHOUR 60
74 #define HOURSPERDAY 24
75 #define EPOCHWEEKDAY 1 /* Jan 1, 1601 was Monday */
76 #define DAYSPERWEEK 7
77 #define MONSPERYEAR 12
78 #define DAYSPERQUADRICENTENNIUM (365 * 400 + 97)
79 #define DAYSPERNORMALQUADRENNIUM (365 * 4 + 1)
81 /* 1601 to 1970 is 369 years plus 89 leap days */
82 #define SECS_1601_TO_1970 ((369 * 365 + 89) * (ULONGLONG)SECSPERDAY)
83 #define TICKS_1601_TO_1970 (SECS_1601_TO_1970 * TICKSPERSEC)
84 /* 1601 to 1980 is 379 years plus 91 leap days */
85 #define SECS_1601_TO_1980 ((379 * 365 + 91) * (ULONGLONG)SECSPERDAY)
86 #define TICKS_1601_TO_1980 (SECS_1601_TO_1980 * TICKSPERSEC)
89 static const int MonthLengths[2][MONSPERYEAR] =
91 { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
92 { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
95 static inline BOOL IsLeapYear(int Year)
97 return Year % 4 == 0 && (Year % 100 != 0 || Year % 400 == 0);
100 /* return a monotonic time counter, in Win32 ticks */
101 static ULONGLONG monotonic_counter(void)
103 struct timeval now;
105 #ifdef HAVE_CLOCK_GETTIME
106 struct timespec ts;
107 #ifdef CLOCK_MONOTONIC_RAW
108 if (!clock_gettime( CLOCK_MONOTONIC_RAW, &ts ))
109 return ts.tv_sec * (ULONGLONG)TICKSPERSEC + ts.tv_nsec / 100;
110 #endif
111 if (!clock_gettime( CLOCK_MONOTONIC, &ts ))
112 return ts.tv_sec * (ULONGLONG)TICKSPERSEC + ts.tv_nsec / 100;
113 #elif defined(__APPLE__)
114 static mach_timebase_info_data_t timebase;
116 if (!timebase.denom) mach_timebase_info( &timebase );
117 return mach_absolute_time() * timebase.numer / timebase.denom / 100;
118 #endif
120 gettimeofday( &now, 0 );
121 return now.tv_sec * (ULONGLONG)TICKSPERSEC + now.tv_usec * 10 + TICKS_1601_TO_1970 - server_start_time;
124 /******************************************************************************
125 * RtlTimeToTimeFields [NTDLL.@]
127 * Convert a time into a TIME_FIELDS structure.
129 * PARAMS
130 * liTime [I] Time to convert.
131 * TimeFields [O] Destination for the converted time.
133 * RETURNS
134 * Nothing.
136 VOID WINAPI RtlTimeToTimeFields(
137 const LARGE_INTEGER *liTime,
138 PTIME_FIELDS TimeFields)
140 int SecondsInDay;
141 long int cleaps, years, yearday, months;
142 long int Days;
143 LONGLONG Time;
145 /* Extract millisecond from time and convert time into seconds */
146 TimeFields->Milliseconds =
147 (CSHORT) (( liTime->QuadPart % TICKSPERSEC) / TICKSPERMSEC);
148 Time = liTime->QuadPart / TICKSPERSEC;
150 /* The native version of RtlTimeToTimeFields does not take leap seconds
151 * into account */
153 /* Split the time into days and seconds within the day */
154 Days = Time / SECSPERDAY;
155 SecondsInDay = Time % SECSPERDAY;
157 /* compute time of day */
158 TimeFields->Hour = (CSHORT) (SecondsInDay / SECSPERHOUR);
159 SecondsInDay = SecondsInDay % SECSPERHOUR;
160 TimeFields->Minute = (CSHORT) (SecondsInDay / SECSPERMIN);
161 TimeFields->Second = (CSHORT) (SecondsInDay % SECSPERMIN);
163 /* compute day of week */
164 TimeFields->Weekday = (CSHORT) ((EPOCHWEEKDAY + Days) % DAYSPERWEEK);
166 /* compute year, month and day of month. */
167 cleaps=( 3 * ((4 * Days + 1227) / DAYSPERQUADRICENTENNIUM) + 3 ) / 4;
168 Days += 28188 + cleaps;
169 years = (20 * Days - 2442) / (5 * DAYSPERNORMALQUADRENNIUM);
170 yearday = Days - (years * DAYSPERNORMALQUADRENNIUM)/4;
171 months = (64 * yearday) / 1959;
172 /* the result is based on a year starting on March.
173 * To convert take 12 from Januari and Februari and
174 * increase the year by one. */
175 if( months < 14 ) {
176 TimeFields->Month = months - 1;
177 TimeFields->Year = years + 1524;
178 } else {
179 TimeFields->Month = months - 13;
180 TimeFields->Year = years + 1525;
182 /* calculation of day of month is based on the wonderful
183 * sequence of INT( n * 30.6): it reproduces the
184 * 31-30-31-30-31-31 month lengths exactly for small n's */
185 TimeFields->Day = yearday - (1959 * months) / 64 ;
186 return;
189 /******************************************************************************
190 * RtlTimeFieldsToTime [NTDLL.@]
192 * Convert a TIME_FIELDS structure into a time.
194 * PARAMS
195 * ftTimeFields [I] TIME_FIELDS structure to convert.
196 * Time [O] Destination for the converted time.
198 * RETURNS
199 * Success: TRUE.
200 * Failure: FALSE.
202 BOOLEAN WINAPI RtlTimeFieldsToTime(
203 PTIME_FIELDS tfTimeFields,
204 PLARGE_INTEGER Time)
206 int month, year, cleaps, day;
208 /* FIXME: normalize the TIME_FIELDS structure here */
209 /* No, native just returns 0 (error) if the fields are not */
210 if( tfTimeFields->Milliseconds< 0 || tfTimeFields->Milliseconds > 999 ||
211 tfTimeFields->Second < 0 || tfTimeFields->Second > 59 ||
212 tfTimeFields->Minute < 0 || tfTimeFields->Minute > 59 ||
213 tfTimeFields->Hour < 0 || tfTimeFields->Hour > 23 ||
214 tfTimeFields->Month < 1 || tfTimeFields->Month > 12 ||
215 tfTimeFields->Day < 1 ||
216 tfTimeFields->Day > MonthLengths
217 [ tfTimeFields->Month ==2 || IsLeapYear(tfTimeFields->Year)]
218 [ tfTimeFields->Month - 1] ||
219 tfTimeFields->Year < 1601 )
220 return FALSE;
222 /* now calculate a day count from the date
223 * First start counting years from March. This way the leap days
224 * are added at the end of the year, not somewhere in the middle.
225 * Formula's become so much less complicate that way.
226 * To convert: add 12 to the month numbers of Jan and Feb, and
227 * take 1 from the year */
228 if(tfTimeFields->Month < 3) {
229 month = tfTimeFields->Month + 13;
230 year = tfTimeFields->Year - 1;
231 } else {
232 month = tfTimeFields->Month + 1;
233 year = tfTimeFields->Year;
235 cleaps = (3 * (year / 100) + 3) / 4; /* nr of "century leap years"*/
236 day = (36525 * year) / 100 - cleaps + /* year * dayperyr, corrected */
237 (1959 * month) / 64 + /* months * daypermonth */
238 tfTimeFields->Day - /* day of the month */
239 584817 ; /* zero that on 1601-01-01 */
240 /* done */
242 Time->QuadPart = (((((LONGLONG) day * HOURSPERDAY +
243 tfTimeFields->Hour) * MINSPERHOUR +
244 tfTimeFields->Minute) * SECSPERMIN +
245 tfTimeFields->Second ) * 1000 +
246 tfTimeFields->Milliseconds ) * TICKSPERMSEC;
248 return TRUE;
251 /***********************************************************************
252 * TIME_GetBias [internal]
254 * Helper function calculates delta local time from UTC.
256 * PARAMS
257 * utc [I] The current utc time.
258 * pdaylight [I] Local daylight.
260 * RETURNS
261 * The bias for the current timezone.
263 static LONG TIME_GetBias(void)
265 static time_t last_utc;
266 static LONG last_bias;
267 LONG ret;
268 time_t utc;
270 utc = time( NULL );
272 RtlEnterCriticalSection( &TIME_tz_section );
273 if (utc != last_utc)
275 RTL_TIME_ZONE_INFORMATION tzi;
276 int is_dst = init_tz_info( &tzi );
278 last_utc = utc;
279 last_bias = tzi.Bias;
280 last_bias += is_dst ? tzi.DaylightBias : tzi.StandardBias;
281 last_bias *= SECSPERMIN;
284 ret = last_bias;
286 RtlLeaveCriticalSection( &TIME_tz_section );
287 return ret;
290 /******************************************************************************
291 * RtlLocalTimeToSystemTime [NTDLL.@]
293 * Convert a local time into system time.
295 * PARAMS
296 * LocalTime [I] Local time to convert.
297 * SystemTime [O] Destination for the converted time.
299 * RETURNS
300 * Success: STATUS_SUCCESS.
301 * Failure: An NTSTATUS error code indicating the problem.
303 NTSTATUS WINAPI RtlLocalTimeToSystemTime( const LARGE_INTEGER *LocalTime,
304 PLARGE_INTEGER SystemTime)
306 LONG bias;
308 TRACE("(%p, %p)\n", LocalTime, SystemTime);
310 bias = TIME_GetBias();
311 SystemTime->QuadPart = LocalTime->QuadPart + bias * (LONGLONG)TICKSPERSEC;
312 return STATUS_SUCCESS;
315 /******************************************************************************
316 * RtlSystemTimeToLocalTime [NTDLL.@]
318 * Convert a system time into a local time.
320 * PARAMS
321 * SystemTime [I] System time to convert.
322 * LocalTime [O] Destination for the converted time.
324 * RETURNS
325 * Success: STATUS_SUCCESS.
326 * Failure: An NTSTATUS error code indicating the problem.
328 NTSTATUS WINAPI RtlSystemTimeToLocalTime( const LARGE_INTEGER *SystemTime,
329 PLARGE_INTEGER LocalTime )
331 LONG bias;
333 TRACE("(%p, %p)\n", SystemTime, LocalTime);
335 bias = TIME_GetBias();
336 LocalTime->QuadPart = SystemTime->QuadPart - bias * (LONGLONG)TICKSPERSEC;
337 return STATUS_SUCCESS;
340 /******************************************************************************
341 * RtlTimeToSecondsSince1970 [NTDLL.@]
343 * Convert a time into a count of seconds since 1970.
345 * PARAMS
346 * Time [I] Time to convert.
347 * Seconds [O] Destination for the converted time.
349 * RETURNS
350 * Success: TRUE.
351 * Failure: FALSE, if the resulting value will not fit in a DWORD.
353 BOOLEAN WINAPI RtlTimeToSecondsSince1970( const LARGE_INTEGER *Time, LPDWORD Seconds )
355 ULONGLONG tmp = Time->QuadPart / TICKSPERSEC - SECS_1601_TO_1970;
356 if (tmp > 0xffffffff) return FALSE;
357 *Seconds = tmp;
358 return TRUE;
361 /******************************************************************************
362 * RtlTimeToSecondsSince1980 [NTDLL.@]
364 * Convert a time into a count of seconds since 1980.
366 * PARAMS
367 * Time [I] Time to convert.
368 * Seconds [O] Destination for the converted time.
370 * RETURNS
371 * Success: TRUE.
372 * Failure: FALSE, if the resulting value will not fit in a DWORD.
374 BOOLEAN WINAPI RtlTimeToSecondsSince1980( const LARGE_INTEGER *Time, LPDWORD Seconds )
376 ULONGLONG tmp = Time->QuadPart / TICKSPERSEC - SECS_1601_TO_1980;
377 if (tmp > 0xffffffff) return FALSE;
378 *Seconds = tmp;
379 return TRUE;
382 /******************************************************************************
383 * RtlSecondsSince1970ToTime [NTDLL.@]
385 * Convert a count of seconds since 1970 to a time.
387 * PARAMS
388 * Seconds [I] Time to convert.
389 * Time [O] Destination for the converted time.
391 * RETURNS
392 * Nothing.
394 void WINAPI RtlSecondsSince1970ToTime( DWORD Seconds, LARGE_INTEGER *Time )
396 Time->QuadPart = Seconds * (ULONGLONG)TICKSPERSEC + TICKS_1601_TO_1970;
399 /******************************************************************************
400 * RtlSecondsSince1980ToTime [NTDLL.@]
402 * Convert a count of seconds since 1980 to a time.
404 * PARAMS
405 * Seconds [I] Time to convert.
406 * Time [O] Destination for the converted time.
408 * RETURNS
409 * Nothing.
411 void WINAPI RtlSecondsSince1980ToTime( DWORD Seconds, LARGE_INTEGER *Time )
413 Time->QuadPart = Seconds * (ULONGLONG)TICKSPERSEC + TICKS_1601_TO_1980;
416 /******************************************************************************
417 * RtlTimeToElapsedTimeFields [NTDLL.@]
419 * Convert a time to a count of elapsed seconds.
421 * PARAMS
422 * Time [I] Time to convert.
423 * TimeFields [O] Destination for the converted time.
425 * RETURNS
426 * Nothing.
428 void WINAPI RtlTimeToElapsedTimeFields( const LARGE_INTEGER *Time, PTIME_FIELDS TimeFields )
430 LONGLONG time;
431 INT rem;
433 time = Time->QuadPart / TICKSPERSEC;
434 TimeFields->Milliseconds = (Time->QuadPart % TICKSPERSEC) / TICKSPERMSEC;
436 /* time is now in seconds */
437 TimeFields->Year = 0;
438 TimeFields->Month = 0;
439 TimeFields->Day = time / SECSPERDAY;
441 /* rem is now the remaining seconds in the last day */
442 rem = time % SECSPERDAY;
443 TimeFields->Second = rem % 60;
444 rem /= 60;
445 TimeFields->Minute = rem % 60;
446 TimeFields->Hour = rem / 60;
449 /***********************************************************************
450 * NtQuerySystemTime [NTDLL.@]
451 * ZwQuerySystemTime [NTDLL.@]
453 * Get the current system time.
455 * PARAMS
456 * Time [O] Destination for the current system time.
458 * RETURNS
459 * Success: STATUS_SUCCESS.
460 * Failure: An NTSTATUS error code indicating the problem.
462 NTSTATUS WINAPI NtQuerySystemTime( PLARGE_INTEGER Time )
464 struct timeval now;
466 gettimeofday( &now, 0 );
467 Time->QuadPart = now.tv_sec * (ULONGLONG)TICKSPERSEC + TICKS_1601_TO_1970;
468 Time->QuadPart += now.tv_usec * 10;
469 return STATUS_SUCCESS;
472 /******************************************************************************
473 * NtQueryPerformanceCounter [NTDLL.@]
475 NTSTATUS WINAPI NtQueryPerformanceCounter( LARGE_INTEGER *counter, LARGE_INTEGER *frequency )
477 if (!counter) return STATUS_ACCESS_VIOLATION;
479 counter->QuadPart = monotonic_counter();
480 if (frequency) frequency->QuadPart = TICKSPERSEC;
481 return STATUS_SUCCESS;
485 /******************************************************************************
486 * NtGetTickCount (NTDLL.@)
487 * ZwGetTickCount (NTDLL.@)
489 ULONG WINAPI NtGetTickCount(void)
491 return monotonic_counter() / TICKSPERMSEC;
494 /* calculate the mday of dst change date, so that for instance Sun 5 Oct 2007
495 * (last Sunday in October of 2007) becomes Sun Oct 28 2007
497 * Note: year, day and month must be in unix format.
499 static int weekday_to_mday(int year, int day, int mon, int day_of_week)
501 struct tm date;
502 time_t tmp;
503 int wday, mday;
505 /* find first day in the month matching week day of the date */
506 memset(&date, 0, sizeof(date));
507 date.tm_year = year;
508 date.tm_mon = mon;
509 date.tm_mday = -1;
510 date.tm_wday = -1;
513 date.tm_mday++;
514 tmp = mktime(&date);
515 } while (date.tm_wday != day_of_week || date.tm_mon != mon);
517 mday = date.tm_mday;
519 /* find number of week days in the month matching week day of the date */
520 wday = 1; /* 1 - 1st, ...., 5 - last */
521 while (wday < day)
523 struct tm *tm;
525 date.tm_mday += 7;
526 tmp = mktime(&date);
527 tm = localtime(&tmp);
528 if (tm->tm_mon != mon)
529 break;
530 mday = tm->tm_mday;
531 wday++;
534 return mday;
537 static BOOL match_tz_date(const RTL_SYSTEM_TIME *st, const RTL_SYSTEM_TIME *reg_st)
539 WORD wDay;
541 if (st->wMonth != reg_st->wMonth) return FALSE;
543 if (!st->wMonth) return TRUE; /* no transition dates */
545 wDay = reg_st->wDay;
546 if (!reg_st->wYear) /* date in a day-of-week format */
547 wDay = weekday_to_mday(st->wYear - 1900, reg_st->wDay, reg_st->wMonth - 1, reg_st->wDayOfWeek);
549 if (st->wDay != wDay ||
550 st->wHour != reg_st->wHour ||
551 st->wMinute != reg_st->wMinute ||
552 st->wSecond != reg_st->wSecond ||
553 st->wMilliseconds != reg_st->wMilliseconds) return FALSE;
555 return TRUE;
558 static BOOL match_tz_info(const RTL_TIME_ZONE_INFORMATION *tzi, const RTL_TIME_ZONE_INFORMATION *reg_tzi)
560 if (tzi->Bias == reg_tzi->Bias &&
561 match_tz_date(&tzi->StandardDate, &reg_tzi->StandardDate) &&
562 match_tz_date(&tzi->DaylightDate, &reg_tzi->DaylightDate))
563 return TRUE;
565 return FALSE;
568 static BOOL reg_query_value(HKEY hkey, LPCWSTR name, DWORD type, void *data, DWORD count)
570 UNICODE_STRING nameW;
571 char buf[256];
572 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buf;
574 if (count > sizeof(buf) - sizeof(KEY_VALUE_PARTIAL_INFORMATION))
575 return FALSE;
577 RtlInitUnicodeString(&nameW, name);
579 if (NtQueryValueKey(hkey, &nameW, KeyValuePartialInformation,
580 buf, sizeof(buf), &count))
581 return FALSE;
583 if (info->Type != type) return FALSE;
585 memcpy(data, info->Data, info->DataLength);
586 return TRUE;
589 static void find_reg_tz_info(RTL_TIME_ZONE_INFORMATION *tzi)
591 static const WCHAR Time_ZonesW[] = { 'M','a','c','h','i','n','e','\\',
592 'S','o','f','t','w','a','r','e','\\',
593 'M','i','c','r','o','s','o','f','t','\\',
594 'W','i','n','d','o','w','s',' ','N','T','\\',
595 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
596 'T','i','m','e',' ','Z','o','n','e','s',0 };
597 HANDLE hkey;
598 ULONG idx;
599 OBJECT_ATTRIBUTES attr;
600 UNICODE_STRING nameW;
601 WCHAR buf[128];
603 attr.Length = sizeof(attr);
604 attr.RootDirectory = 0;
605 attr.ObjectName = &nameW;
606 attr.Attributes = 0;
607 attr.SecurityDescriptor = NULL;
608 attr.SecurityQualityOfService = NULL;
609 RtlInitUnicodeString(&nameW, Time_ZonesW);
610 if (NtOpenKey(&hkey, KEY_READ, &attr))
612 WARN("Unable to open the time zones key\n");
613 return;
616 idx = 0;
617 nameW.Buffer = buf;
618 nameW.Length = sizeof(buf);
619 nameW.MaximumLength = sizeof(buf);
621 while (!RtlpNtEnumerateSubKey(hkey, &nameW, idx++))
623 static const WCHAR stdW[] = { 'S','t','d',0 };
624 static const WCHAR dltW[] = { 'D','l','t',0 };
625 static const WCHAR tziW[] = { 'T','Z','I',0 };
626 RTL_TIME_ZONE_INFORMATION reg_tzi;
627 HANDLE hSubkey;
628 struct tz_reg_data
630 LONG bias;
631 LONG std_bias;
632 LONG dlt_bias;
633 RTL_SYSTEM_TIME std_date;
634 RTL_SYSTEM_TIME dlt_date;
635 } tz_data;
637 attr.Length = sizeof(attr);
638 attr.RootDirectory = hkey;
639 attr.ObjectName = &nameW;
640 attr.Attributes = 0;
641 attr.SecurityDescriptor = NULL;
642 attr.SecurityQualityOfService = NULL;
643 if (NtOpenKey(&hSubkey, KEY_READ, &attr))
645 WARN("Unable to open subkey %s\n", debugstr_wn(nameW.Buffer, nameW.Length/sizeof(WCHAR)));
646 continue;
649 #define get_value(hkey, name, type, data, len) \
650 if (!reg_query_value(hkey, name, type, data, len)) \
652 WARN("can't read data from %s\n", debugstr_w(name)); \
653 NtClose(hkey); \
654 continue; \
657 get_value(hSubkey, stdW, REG_SZ, reg_tzi.StandardName, sizeof(reg_tzi.StandardName));
658 get_value(hSubkey, dltW, REG_SZ, reg_tzi.DaylightName, sizeof(reg_tzi.DaylightName));
659 get_value(hSubkey, tziW, REG_BINARY, &tz_data, sizeof(tz_data));
661 #undef get_value
663 reg_tzi.Bias = tz_data.bias;
664 reg_tzi.StandardBias = tz_data.std_bias;
665 reg_tzi.DaylightBias = tz_data.dlt_bias;
666 reg_tzi.StandardDate = tz_data.std_date;
667 reg_tzi.DaylightDate = tz_data.dlt_date;
669 TRACE("%s: bias %d\n", debugstr_wn(nameW.Buffer, nameW.Length/sizeof(WCHAR)), reg_tzi.Bias);
670 TRACE("std (d/m/y): %u/%02u/%04u day of week %u %u:%02u:%02u.%03u bias %d\n",
671 reg_tzi.StandardDate.wDay, reg_tzi.StandardDate.wMonth,
672 reg_tzi.StandardDate.wYear, reg_tzi.StandardDate.wDayOfWeek,
673 reg_tzi.StandardDate.wHour, reg_tzi.StandardDate.wMinute,
674 reg_tzi.StandardDate.wSecond, reg_tzi.StandardDate.wMilliseconds,
675 reg_tzi.StandardBias);
676 TRACE("dst (d/m/y): %u/%02u/%04u day of week %u %u:%02u:%02u.%03u bias %d\n",
677 reg_tzi.DaylightDate.wDay, reg_tzi.DaylightDate.wMonth,
678 reg_tzi.DaylightDate.wYear, reg_tzi.DaylightDate.wDayOfWeek,
679 reg_tzi.DaylightDate.wHour, reg_tzi.DaylightDate.wMinute,
680 reg_tzi.DaylightDate.wSecond, reg_tzi.DaylightDate.wMilliseconds,
681 reg_tzi.DaylightBias);
683 NtClose(hSubkey);
685 if (match_tz_info(tzi, &reg_tzi))
687 *tzi = reg_tzi;
688 NtClose(hkey);
689 return;
692 /* reset len */
693 nameW.Length = sizeof(buf);
694 nameW.MaximumLength = sizeof(buf);
697 NtClose(hkey);
699 FIXME("Can't find matching timezone information in the registry for "
700 "bias %d, std (d/m/y): %u/%02u/%04u, dlt (d/m/y): %u/%02u/%04u\n",
701 tzi->Bias,
702 tzi->StandardDate.wDay, tzi->StandardDate.wMonth, tzi->StandardDate.wYear,
703 tzi->DaylightDate.wDay, tzi->DaylightDate.wMonth, tzi->DaylightDate.wYear);
706 static time_t find_dst_change(unsigned long min, unsigned long max, int *is_dst)
708 time_t start;
709 struct tm *tm;
711 start = min;
712 tm = localtime(&start);
713 *is_dst = !tm->tm_isdst;
714 TRACE("starting date isdst %d, %s", !*is_dst, ctime(&start));
716 while (min <= max)
718 time_t pos = (min + max) / 2;
719 tm = localtime(&pos);
721 if (tm->tm_isdst != *is_dst)
722 min = pos + 1;
723 else
724 max = pos - 1;
726 return min;
729 static int init_tz_info(RTL_TIME_ZONE_INFORMATION *tzi)
731 static RTL_TIME_ZONE_INFORMATION cached_tzi;
732 static int current_year = -1, current_bias = 65535;
733 struct tm *tm;
734 time_t year_start, year_end, tmp, dlt = 0, std = 0;
735 int is_dst, current_is_dst, bias;
737 RtlEnterCriticalSection( &TIME_tz_section );
739 year_start = time(NULL);
740 tm = gmtime(&year_start);
741 bias = (LONG)(mktime(tm) - year_start) / 60;
743 tm = localtime(&year_start);
744 current_is_dst = tm->tm_isdst;
745 if (current_year == tm->tm_year && current_bias == bias)
747 *tzi = cached_tzi;
748 RtlLeaveCriticalSection( &TIME_tz_section );
749 return current_is_dst;
752 memset(tzi, 0, sizeof(*tzi));
754 TRACE("tz data will be valid through year %d, bias %d\n", tm->tm_year + 1900, bias);
755 current_year = tm->tm_year;
756 current_bias = bias;
758 tzi->Bias = bias;
760 tm->tm_isdst = 0;
761 tm->tm_mday = 1;
762 tm->tm_mon = tm->tm_hour = tm->tm_min = tm->tm_sec = tm->tm_wday = tm->tm_yday = 0;
763 year_start = mktime(tm);
764 TRACE("year_start: %s", ctime(&year_start));
766 tm->tm_mday = tm->tm_wday = tm->tm_yday = 0;
767 tm->tm_mon = 12;
768 tm->tm_hour = 23;
769 tm->tm_min = tm->tm_sec = 59;
770 year_end = mktime(tm);
771 TRACE("year_end: %s", ctime(&year_end));
773 tmp = find_dst_change(year_start, year_end, &is_dst);
774 if (is_dst)
775 dlt = tmp;
776 else
777 std = tmp;
779 tmp = find_dst_change(tmp, year_end, &is_dst);
780 if (is_dst)
781 dlt = tmp;
782 else
783 std = tmp;
785 TRACE("std: %s", ctime(&std));
786 TRACE("dlt: %s", ctime(&dlt));
788 if (dlt == std || !dlt || !std)
789 TRACE("there is no daylight saving rules in this time zone\n");
790 else
792 tmp = dlt - tzi->Bias * 60;
793 tm = gmtime(&tmp);
794 TRACE("dlt gmtime: %s", asctime(tm));
796 tzi->DaylightBias = -60;
797 tzi->DaylightDate.wYear = tm->tm_year + 1900;
798 tzi->DaylightDate.wMonth = tm->tm_mon + 1;
799 tzi->DaylightDate.wDayOfWeek = tm->tm_wday;
800 tzi->DaylightDate.wDay = tm->tm_mday;
801 tzi->DaylightDate.wHour = tm->tm_hour;
802 tzi->DaylightDate.wMinute = tm->tm_min;
803 tzi->DaylightDate.wSecond = tm->tm_sec;
804 tzi->DaylightDate.wMilliseconds = 0;
806 TRACE("daylight (d/m/y): %u/%02u/%04u day of week %u %u:%02u:%02u.%03u bias %d\n",
807 tzi->DaylightDate.wDay, tzi->DaylightDate.wMonth,
808 tzi->DaylightDate.wYear, tzi->DaylightDate.wDayOfWeek,
809 tzi->DaylightDate.wHour, tzi->DaylightDate.wMinute,
810 tzi->DaylightDate.wSecond, tzi->DaylightDate.wMilliseconds,
811 tzi->DaylightBias);
813 tmp = std - tzi->Bias * 60 - tzi->DaylightBias * 60;
814 tm = gmtime(&tmp);
815 TRACE("std gmtime: %s", asctime(tm));
817 tzi->StandardBias = 0;
818 tzi->StandardDate.wYear = tm->tm_year + 1900;
819 tzi->StandardDate.wMonth = tm->tm_mon + 1;
820 tzi->StandardDate.wDayOfWeek = tm->tm_wday;
821 tzi->StandardDate.wDay = tm->tm_mday;
822 tzi->StandardDate.wHour = tm->tm_hour;
823 tzi->StandardDate.wMinute = tm->tm_min;
824 tzi->StandardDate.wSecond = tm->tm_sec;
825 tzi->StandardDate.wMilliseconds = 0;
827 TRACE("standard (d/m/y): %u/%02u/%04u day of week %u %u:%02u:%02u.%03u bias %d\n",
828 tzi->StandardDate.wDay, tzi->StandardDate.wMonth,
829 tzi->StandardDate.wYear, tzi->StandardDate.wDayOfWeek,
830 tzi->StandardDate.wHour, tzi->StandardDate.wMinute,
831 tzi->StandardDate.wSecond, tzi->StandardDate.wMilliseconds,
832 tzi->StandardBias);
835 find_reg_tz_info(tzi);
836 cached_tzi = *tzi;
838 RtlLeaveCriticalSection( &TIME_tz_section );
840 return current_is_dst;
843 /***********************************************************************
844 * RtlQueryTimeZoneInformation [NTDLL.@]
846 * Get information about the current timezone.
848 * PARAMS
849 * tzinfo [O] Destination for the retrieved timezone info.
851 * RETURNS
852 * Success: STATUS_SUCCESS.
853 * Failure: An NTSTATUS error code indicating the problem.
855 NTSTATUS WINAPI RtlQueryTimeZoneInformation(RTL_TIME_ZONE_INFORMATION *tzinfo)
857 init_tz_info( tzinfo );
859 return STATUS_SUCCESS;
862 /***********************************************************************
863 * RtlSetTimeZoneInformation [NTDLL.@]
865 * Set the current time zone information.
867 * PARAMS
868 * tzinfo [I] Timezone information to set.
870 * RETURNS
871 * Success: STATUS_SUCCESS.
872 * Failure: An NTSTATUS error code indicating the problem.
875 NTSTATUS WINAPI RtlSetTimeZoneInformation( const RTL_TIME_ZONE_INFORMATION *tzinfo )
877 return STATUS_PRIVILEGE_NOT_HELD;
880 /***********************************************************************
881 * NtSetSystemTime [NTDLL.@]
882 * ZwSetSystemTime [NTDLL.@]
884 * Set the system time.
886 * PARAMS
887 * NewTime [I] The time to set.
888 * OldTime [O] Optional destination for the previous system time.
890 * RETURNS
891 * Success: STATUS_SUCCESS.
892 * Failure: An NTSTATUS error code indicating the problem.
894 NTSTATUS WINAPI NtSetSystemTime(const LARGE_INTEGER *NewTime, LARGE_INTEGER *OldTime)
896 struct timeval tv;
897 time_t tm_t;
898 DWORD sec, oldsec;
899 LARGE_INTEGER tm;
901 /* Return the old time if necessary */
902 if (!OldTime) OldTime = &tm;
904 NtQuerySystemTime( OldTime );
905 RtlTimeToSecondsSince1970( OldTime, &oldsec );
907 RtlTimeToSecondsSince1970( NewTime, &sec );
909 /* set the new time */
910 tv.tv_sec = sec;
911 tv.tv_usec = 0;
913 #ifdef HAVE_SETTIMEOFDAY
914 if (!settimeofday(&tv, NULL)) /* 0 is OK, -1 is error */
915 return STATUS_SUCCESS;
916 tm_t = sec;
917 ERR("Cannot set time to %s, time adjustment %ld: %s\n",
918 ctime(&tm_t), (long)(sec-oldsec), strerror(errno));
919 if (errno == EPERM)
920 return STATUS_PRIVILEGE_NOT_HELD;
921 else
922 return STATUS_INVALID_PARAMETER;
923 #else
924 tm_t = sec;
925 FIXME("setting time to %s not implemented for missing settimeofday\n",
926 ctime(&tm_t));
927 return STATUS_NOT_IMPLEMENTED;
928 #endif
931 /***********************************************************************
932 * RtlQueryUnbiasedInterruptTime [NTDLL.@]
934 NTSTATUS WINAPI RtlQueryUnbiasedInterruptTime(ULONGLONG *time)
936 *time = monotonic_counter();
937 return STATUS_SUCCESS;