Move the GetDeviceCaps into the wined3d library and call from d3d9.
[wine] / dlls / ntdll / time.c
1 /*
2  * Nt time functions.
3  *
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)
7  *
8  * Copyright 1999 Juergen Schmied
9  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2.1 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with this library; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23  */
24
25 #include "config.h"
26 #include "wine/port.h"
27
28 #include <stdarg.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <limits.h>
32 #include <time.h>
33 #ifdef HAVE_SYS_TIME_H
34 # include <sys/time.h>
35 #endif
36 #ifdef HAVE_UNISTD_H
37 # include <unistd.h>
38 #endif
39
40 #define NONAMELESSUNION
41 #define NONAMELESSSTRUCT
42 #include "windef.h"
43 #include "winbase.h"
44 #include "winreg.h"
45 #include "winternl.h"
46 #include "wine/unicode.h"
47 #include "wine/debug.h"
48 #include "ntdll_misc.h"
49
50 WINE_DEFAULT_DEBUG_CHANNEL(ntdll);
51
52 static CRITICAL_SECTION TIME_GetBias_section;
53 static CRITICAL_SECTION_DEBUG critsect_debug =
54 {
55     0, 0, &TIME_GetBias_section,
56     { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
57       0, 0, { 0, (DWORD)(__FILE__ ": TIME_GetBias_section") }
58 };
59 static CRITICAL_SECTION TIME_GetBias_section = { &critsect_debug, -1, 0, 0, 0, 0 };
60
61
62 #define SETTIME_MAX_ADJUST 120
63
64 /* This structure is used to store strings that represent all of the time zones
65  * in the world. (This is used to help GetTimeZoneInformation)
66  */
67 struct tagTZ_INFO
68 {
69     const char *psTZFromUnix;
70     WCHAR psTZWindows[32];
71     int bias;
72     int dst;
73 };
74
75 static const struct tagTZ_INFO TZ_INFO[] =
76 {
77    {"MHT",
78     {'D','a','t','e','l','i','n','e',' ','S','t','a','n','d','a','r','d',' ',
79      'T','i','m','e','\0'}, -720, 0},
80    {"SST",
81     {'S','a','m','o','a',' ','S','t','a','n','d','a','r','d',' ','T','i','m',
82      'e','\0'}, 660, 0},
83    {"HST",
84     {'H','a','w','a','i','i','a','n',' ','S','t','a','n','d','a','r','d',' ',
85      'T','i','m','e','\0'}, 600, 0},
86    {"AKDT",
87     {'A','l','a','s','k','a','n',' ','S','t','a','n','d','a','r','d',' ','T',
88      'i','m','e','\0'}, 480, 1},
89    {"PDT",
90     {'P','a','c','i','f','i','c',' ','S','t','a','n','d','a','r','d',' ','T',
91      'i','m','e','\0'}, 420, 1},
92    {"MST",
93     {'U','S',' ','M','o','u','n','t','a','i','n',' ','S','t','a','n','d','a',
94      'r','d',' ','T','i','m','e','\0'}, 420, 0},
95    {"MDT",
96     {'M','o','u','n','t','a','i','n',' ','S','t','a','n','d','a','r','d',' ',
97      'T','i','m','e','\0'}, 360, 1},
98    {"CST",
99     {'C','e','n','t','r','a','l',' ','A','m','e','r','i','c','a',' ','S','t',
100      'a','n','d','a','r','d',' ','T','i','m','e','\0'}, 360, 0},
101    {"CDT",
102     {'C','e','n','t','r','a','l',' ','S','t','a','n','d','a','r','d',' ','T',
103      'i','m','e','\0'}, 300, 1},
104    {"COT",
105     {'S','A',' ','P','a','c','i','f','i','c',' ','S','t','a','n','d','a','r',
106      'd',' ','T','i','m','e','\0'}, 300, 0},
107    {"EDT",
108     {'E','a','s','t','e','r','n',' ','S','t','a','n','d','a','r','d',' ','T',
109      'i','m','e','\0'}, 240, 1},
110    {"EST",
111     {'U','S',' ','E','a','s','t','e','r','n',' ','S','t','a','n','d','a','r',
112      'd',' ','T','i','m','e','\0'}, 300, 0},
113    {"ADT",
114     {'A','t','l','a','n','t','i','c',' ','S','t','a','n','d','a','r','d',' ',
115      'T','i','m','e','\0'}, 180, 1},
116    {"VET",
117     {'S','A',' ','W','e','s','t','e','r','n',' ','S','t','a','n','d','a','r',
118      'd',' ','T','i','m','e','\0'}, 240, 0},
119    {"CLT",
120     {'P','a','c','i','f','i','c',' ','S','A',' ','S','t','a','n','d','a','r',
121      'd',' ','T','i','m','e','\0'}, 240, 0},
122    {"NDT",
123     {'N','e','w','f','o','u','n','d','l','a','n','d',' ','S','t','a','n','d',
124      'a','r','d',' ','T','i','m','e','\0'}, 150, 1},
125    {"BRT",
126     {'E','.',' ','S','o','u','t','h',' ','A','m','e','r','i','c','a',' ','S',
127      't','a','n','d','a','r','d',' ','T','i','m','e','\0'}, 180, 0},
128    {"ART",
129     {'S','A',' ','E','a','s','t','e','r','n',' ','S','t','a','n','d','a','r',
130      'd',' ','T','i','m','e','\0'}, 180, 0},
131    {"WGST",
132     {'G','r','e','e','n','l','a','n','d',' ','S','t','a','n','d','a','r','d',
133      ' ','T','i','m','e','\0'}, 120, 1},
134    {"GST",
135     {'M','i','d','-','A','t','l','a','n','t','i','c',' ','S','t','a','n','d',
136      'a','r','d',' ','T','i','m','e','\0'}, 120, 0},
137    {"AZOST",
138     {'A','z','o','r','e','s',' ','S','t','a','n','d','a','r','d',' ','T','i',
139      'm','e','\0'}, 0, 1},
140    {"CVT",
141     {'C','a','p','e',' ','V','e','r','d','e',' ','S','t','a','n','d','a','r',
142      'd',' ','T','i','m','e','\0'}, 60, 0},
143    {"WET",
144     {'G','r','e','e','n','w','i','c','h',' ','S','t','a','n','d','a','r','d',
145      ' ','T','i','m','e','\0'}, 0, 0},
146    {"BST",
147     {'G','M','T',' ','S','t','a','n','d','a','r','d',' ','T','i','m','e','\0'},
148     -60, 1},
149    {"GMT",
150     {'G','M','T',' ','S','t','a','n','d','a','r','d',' ','T','i','m','e','\0'},
151     0, 0},
152    {"UTC",
153     {'G','M','T',' ','S','t','a','n','d','a','r','d',' ','T','i','m','e','\0'},
154     0, 0},
155    {"CEST",
156     {'C','e','n','t','r','a','l',' ','E','u','r','o','p','e',' ','S','t','a',
157      'n','d','a','r','d',' ','T','i','m','e','\0'}, -120, 1},
158    {"MET",
159     {'C','e','n','t','r','a','l',' ','E','u','r','o','p','e',' ','S','t','a',
160      'n','d','a','r','d',' ','T','i','m','e','\0'}, -60, 0},
161    {"MEST",
162     {'C','e','n','t','r','a','l',' ','E','u','r','o','p','e',' ','D','a','y',
163      'l','i','g','h','t',' ','T','i','m','e','\0'}, -120, 1},
164    {"WAT",
165     {'W','.',' ','C','e','n','t','r','a','l',' ','A','f','r','i','c','a',' ',
166      'S','t','a','n','d','a','r','d',' ','T','i','m','e','\0'}, -60, 0},
167    {"EEST",
168     {'E','.',' ','E','u','r','o','p','e',' ','S','t','a','n','d','a','r','d',
169      ' ','T','i','m','e','\0'}, -180, 1},
170    {"EET",
171     {'E','g','y','p','t',' ','S','t','a','n','d','a','r','d',' ','T','i','m',
172      'e','\0'}, -120, 0},
173    {"CAT",
174     {'S','o','u','t','h',' ','A','f','r','i','c','a',' ','S','t','a','n','d',
175      'a','r','d',' ','T','i','m','e','\0'}, -120, 0},
176    {"IST",
177     {'I','s','r','a','e','l',' ','S','t','a','n','d','a','r','d',' ','T','i',
178      'm','e','\0'}, -120, 0},
179    {"ADT",
180     {'A','r','a','b','i','c',' ','S','t','a','n','d','a','r','d',' ','T','i',
181      'm','e','\0'}, -240, 1},
182    {"AST",
183     {'A','r','a','b',' ','S','t','a','n','d','a','r','d',' ','T','i','m','e',
184      '\0'}, -180, 0},
185    {"MSD",
186     {'R','u','s','s','i','a','n',' ','S','t','a','n','d','a','r','d',' ','T',
187      'i','m','e','\0'}, -240, 1},
188    {"EAT",
189     {'E','.',' ','A','f','r','i','c','a',' ','S','t','a','n','d','a','r','d',
190      ' ','T','i','m','e','\0'}, -180, 0},
191    {"IRST",
192     {'I','r','a','n',' ','S','t','a','n','d','a','r','d',' ','T','i','m','e',
193      '\0'}, -270, 1},
194    {"GST",
195     {'A','r','a','b','i','a','n',' ','S','t','a','n','d','a','r','d',' ','T',
196      'i','m','e','\0'}, -240, 0},
197    {"AZST",
198     {'C','a','u','c','a','s','u','s',' ','S','t','a','n','d','a','r','d',' ',
199      'T','i','m','e','\0'}, -300, 1},
200    {"AFT",
201     {'A','f','g','h','a','n','i','s','t','a','n',' ','S','t','a','n','d','a',
202      'r','d',' ','T','i','m','e','\0'}, -270, 0},
203    {"YEKST",
204     {'E','k','a','t','e','r','i','n','b','u','r','g',' ','S','t','a','n','d',
205      'a','r','d',' ','T','i','m','e','\0'}, -360, 1},
206    {"PKT",
207     {'W','e','s','t',' ','A','s','i','a',' ','S','t','a','n','d','a','r','d',
208      ' ','T','i','m','e','\0'}, -300, 0},
209    {"IST",
210     {'I','n','d','i','a',' ','S','t','a','n','d','a','r','d',' ','T','i','m',
211      'e','\0'}, -330, 0},
212    {"NPT",
213     {'N','e','p','a','l',' ','S','t','a','n','d','a','r','d',' ','T','i','m',
214      'e','\0'}, -345, 0},
215    {"ALMST",
216     {'N','.',' ','C','e','n','t','r','a','l',' ','A','s','i','a',' ','S','t',
217      'a','n','d','a','r','d',' ','T','i','m','e','\0'}, -420, 1},
218    {"BDT",
219     {'C','e','n','t','r','a','l',' ','A','s','i','a',' ','S','t','a','n','d',
220      'a','r','d',' ','T','i','m','e','\0'}, -360, 0},
221    {"LKT",
222     {'S','r','i',' ','L','a','n','k','a',' ','S','t','a','n','d','a','r','d',
223      ' ','T','i','m','e','\0'}, -360, 0},
224    {"MMT",
225     {'M','y','a','n','m','a','r',' ','S','t','a','n','d','a','r','d',' ','T',
226      'i','m','e','\0'}, -390, 0},
227    {"ICT",
228     {'S','E',' ','A','s','i','a',' ','S','t','a','n','d','a','r','d',' ','T',
229      'i','m','e','\0'}, -420, 0},
230    {"KRAST",
231     {'N','o','r','t','h',' ','A','s','i','a',' ','S','t','a','n','d','a','r',
232      'd',' ','T','i','m','e','\0'}, -480, 1},
233    {"CST",
234     {'C','h','i','n','a',' ','S','t','a','n','d','a','r','d',' ','T','i','m',
235      'e','\0'}, -480, 0},
236    {"IRKST",
237     {'N','o','r','t','h',' ','A','s','i','a',' ','E','a','s','t',' ','S','t',
238      'a','n','d','a','r','d',' ','T','i','m','e','\0'}, -540, 1},
239    {"SGT",
240     {'M','a','l','a','y',' ','P','e','n','i','n','s','u','l','a',' ','S','t',
241      'a','n','d','a','r','d',' ','T','i','m','e','\0'}, -480, 0},
242    {"WST",
243     {'W','.',' ','A','u','s','t','r','a','l','i','a',' ','S','t','a','n','d',
244      'a','r','d',' ','T','i','m','e','\0'}, -480, 0},
245    {"JST",
246     {'T','o','k','y','o',' ','S','t','a','n','d','a','r','d',' ','T','i','m',
247      'e','\0'}, -540, 0},
248    {"KST",
249     {'K','o','r','e','a',' ','S','t','a','n','d','a','r','d',' ','T','i','m',
250      'e','\0'}, -540, 0},
251    {"YAKST",
252     {'Y','a','k','u','t','s','k',' ','S','t','a','n','d','a','r','d',' ','T',
253      'i','m','e','\0'}, -600, 1},
254    {"CST",
255     {'C','e','n','.',' ','A','u','s','t','r','a','l','i','a',' ','S','t','a',
256      'n','d','a','r','d',' ','T','i','m','e','\0'}, -570, 0},
257    {"EST",
258     {'E','.',' ','A','u','s','t','r','a','l','i','a',' ','S','t','a','n','d',
259      'a','r','d',' ','T','i','m','e','\0'}, -600, 0},
260    {"GST",
261     {'W','e','s','t',' ','P','a','c','i','f','i','c',' ','S','t','a','n','d',
262      'a','r','d',' ','T','i','m','e','\0'}, -600, 0},
263    {"VLAST",
264     {'V','l','a','d','i','v','o','s','t','o','k',' ','S','t','a','n','d','a',
265      'r','d',' ','T','i','m','e','\0'}, -660, 1},
266    {"MAGST",
267     {'C','e','n','t','r','a','l',' ','P','a','c','i','f','i','c',' ','S','t',
268      'a','n','d','a','r','d',' ','T','i','m','e','\0'}, -720, 1},
269    {"NZST",
270     {'N','e','w',' ','Z','e','a','l','a','n','d',' ','S','t','a','n','d','a',
271      'r','d',' ','T','i','m','e','\0'}, -720, 0},
272    {"FJT",
273     {'F','i','j','i',' ','S','t','a','n','d','a','r','d',' ','T','i','m','e',
274      '\0'}, -720, 0},
275    {"TOT",
276     {'T','o','n','g','a',' ','S','t','a','n','d','a','r','d',' ','T','i','m',
277      'e','\0'}, -780, 0}
278 };
279
280 #define TICKSPERSEC        10000000
281 #define TICKSPERMSEC       10000
282 #define SECSPERDAY         86400
283 #define SECSPERHOUR        3600
284 #define SECSPERMIN         60
285 #define MINSPERHOUR        60
286 #define HOURSPERDAY        24
287 #define EPOCHWEEKDAY       1  /* Jan 1, 1601 was Monday */
288 #define DAYSPERWEEK        7
289 #define EPOCHYEAR          1601
290 #define DAYSPERNORMALYEAR  365
291 #define DAYSPERLEAPYEAR    366
292 #define MONSPERYEAR        12
293 #define DAYSPERQUADRICENTENNIUM (365 * 400 + 97)
294 #define DAYSPERNORMALCENTURY (365 * 100 + 24)
295 #define DAYSPERNORMALQUADRENNIUM (365 * 4 + 1)
296
297 /* 1601 to 1970 is 369 years plus 89 leap days */
298 #define SECS_1601_TO_1970  ((369 * 365 + 89) * (ULONGLONG)SECSPERDAY)
299 #define TICKS_1601_TO_1970 (SECS_1601_TO_1970 * TICKSPERSEC)
300 /* 1601 to 1980 is 379 years plus 91 leap days */
301 #define SECS_1601_TO_1980  ((379 * 365 + 91) * (ULONGLONG)SECSPERDAY)
302 #define TICKS_1601_TO_1980 (SECS_1601_TO_1980 * TICKSPERSEC)
303 /* max ticks that can be represented as Unix time */
304 #define TICKS_1601_TO_UNIX_MAX ((SECS_1601_TO_1970 + INT_MAX) * TICKSPERSEC)
305
306
307 static const int MonthLengths[2][MONSPERYEAR] =
308 {
309         { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
310         { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
311 };
312
313 static const int YearDays[2][MONSPERYEAR+1] =
314 {
315         { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 },
316         { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }
317 };
318
319 static inline int IsLeapYear(int Year)
320 {
321         return Year % 4 == 0 && (Year % 100 != 0 || Year % 400 == 0) ? 1 : 0;
322 }
323
324 static inline void NormalizeTimeFields(CSHORT *FieldToNormalize, CSHORT *CarryField,int Modulus)
325 {
326         *FieldToNormalize = (CSHORT) (*FieldToNormalize - Modulus);
327         *CarryField = (CSHORT) (*CarryField + 1);
328 }
329
330 /***********************************************************************
331  *              NTDLL_get_server_timeout
332  *
333  * Convert a NTDLL timeout into a timeval struct to send to the server.
334  */
335 void NTDLL_get_server_timeout( abs_time_t *when, const LARGE_INTEGER *timeout )
336 {
337     UINT remainder;
338
339     if (!timeout)  /* infinite timeout */
340     {
341         when->sec = when->usec = 0;
342     }
343     else if (timeout->QuadPart <= 0)  /* relative timeout */
344     {
345         struct timeval tv;
346
347         if (-timeout->QuadPart > (LONGLONG)INT_MAX * TICKSPERSEC)
348             when->sec = when->usec = INT_MAX;
349         else
350         {
351             ULONG sec = RtlEnlargedUnsignedDivide( -timeout->QuadPart, TICKSPERSEC, &remainder );
352             gettimeofday( &tv, 0 );
353             when->sec = tv.tv_sec + sec;
354             if ((when->usec = tv.tv_usec + (remainder / 10)) >= 1000000)
355             {
356                 when->usec -= 1000000;
357                 when->sec++;
358             }
359             if (when->sec < tv.tv_sec)  /* overflow */
360                 when->sec = when->usec = INT_MAX;
361         }
362     }
363     else  /* absolute time */
364     {
365         if (timeout->QuadPart < TICKS_1601_TO_1970)
366             when->sec = when->usec = 0;
367         else if (timeout->QuadPart > TICKS_1601_TO_UNIX_MAX)
368             when->sec = when->usec = INT_MAX;
369         else
370         {
371             when->sec = RtlEnlargedUnsignedDivide( timeout->QuadPart - TICKS_1601_TO_1970,
372                                                    TICKSPERSEC, &remainder );
373             when->usec = remainder / 10;
374         }
375     }
376 }
377
378
379 /******************************************************************************
380  *       RtlTimeToTimeFields [NTDLL.@]
381  *
382  * Convert a time into a TIME_FIELDS structure.
383  *
384  * PARAMS
385  *   liTime     [I] Time to convert.
386  *   TimeFields [O] Destination for the converted time.
387  *
388  * RETURNS
389  *   Nothing.
390  */
391 VOID WINAPI RtlTimeToTimeFields(
392         const LARGE_INTEGER *liTime,
393         PTIME_FIELDS TimeFields)
394 {
395         int SecondsInDay, DeltaYear;
396         int LeapYear, CurMonth;
397         long int Days;
398         LONGLONG Time = liTime->QuadPart;
399
400         /* Extract millisecond from time and convert time into seconds */
401         TimeFields->Milliseconds = (CSHORT) ((Time % TICKSPERSEC) / TICKSPERMSEC);
402         Time = Time / TICKSPERSEC;
403
404         /* The native version of RtlTimeToTimeFields does not take leap seconds
405          * into account */
406
407         /* Split the time into days and seconds within the day */
408         Days = Time / SECSPERDAY;
409         SecondsInDay = Time % SECSPERDAY;
410
411         /* compute time of day */
412         TimeFields->Hour = (CSHORT) (SecondsInDay / SECSPERHOUR);
413         SecondsInDay = SecondsInDay % SECSPERHOUR;
414         TimeFields->Minute = (CSHORT) (SecondsInDay / SECSPERMIN);
415         TimeFields->Second = (CSHORT) (SecondsInDay % SECSPERMIN);
416
417         /* compute day of week */
418         TimeFields->Weekday = (CSHORT) ((EPOCHWEEKDAY + Days) % DAYSPERWEEK);
419
420         /* compute year */
421         /* FIXME: handle calendar modifications */
422         TimeFields->Year = EPOCHYEAR;
423         DeltaYear = Days / DAYSPERQUADRICENTENNIUM;
424         TimeFields->Year += DeltaYear * 400;
425         Days -= DeltaYear * DAYSPERQUADRICENTENNIUM;
426         DeltaYear = Days / DAYSPERNORMALCENTURY;
427         TimeFields->Year += DeltaYear * 100;
428         Days -= DeltaYear * DAYSPERNORMALCENTURY;
429         DeltaYear = Days / DAYSPERNORMALQUADRENNIUM;
430         TimeFields->Year += DeltaYear * 4;
431         Days -= DeltaYear * DAYSPERNORMALQUADRENNIUM;
432         DeltaYear = Days / DAYSPERNORMALYEAR;
433         TimeFields->Year += DeltaYear;
434         Days -= DeltaYear * DAYSPERNORMALYEAR;
435
436         LeapYear = IsLeapYear(TimeFields->Year);
437
438         /* Compute month of year */
439         CurMonth = 1;
440         while (Days >= YearDays[LeapYear][CurMonth]) CurMonth++;
441         TimeFields->Day = Days - YearDays[LeapYear][CurMonth-1] + 1;
442         TimeFields->Month = CurMonth;
443 }
444
445 /******************************************************************************
446  *       RtlTimeFieldsToTime [NTDLL.@]
447  *
448  * Convert a TIME_FIELDS structure into a time.
449  *
450  * PARAMS
451  *   ftTimeFields [I] TIME_FIELDS structure to convert.
452  *   Time         [O] Destination for the converted time.
453  *
454  * RETURNS
455  *   Success: TRUE.
456  *   Failure: FALSE.
457  */
458 BOOLEAN WINAPI RtlTimeFieldsToTime(
459         PTIME_FIELDS tfTimeFields,
460         PLARGE_INTEGER Time)
461 {
462         int CurYear, DeltaYear;
463         LONGLONG rcTime;
464         TIME_FIELDS TimeFields = *tfTimeFields;
465
466         rcTime = 0;
467
468         /* FIXME: normalize the TIME_FIELDS structure here */
469         while (TimeFields.Second >= SECSPERMIN)
470         { NormalizeTimeFields(&TimeFields.Second, &TimeFields.Minute, SECSPERMIN);
471         }
472         while (TimeFields.Minute >= MINSPERHOUR)
473         { NormalizeTimeFields(&TimeFields.Minute, &TimeFields.Hour, MINSPERHOUR);
474         }
475         while (TimeFields.Hour >= HOURSPERDAY)
476         { NormalizeTimeFields(&TimeFields.Hour, &TimeFields.Day, HOURSPERDAY);
477         }
478         while (TimeFields.Day > MonthLengths[IsLeapYear(TimeFields.Year)][TimeFields.Month - 1])
479         { NormalizeTimeFields(&TimeFields.Day, &TimeFields.Month,
480                               MonthLengths[IsLeapYear(TimeFields.Year)][TimeFields.Month - 1]);
481         }
482         while (TimeFields.Month > MONSPERYEAR)
483         { NormalizeTimeFields(&TimeFields.Month, &TimeFields.Year, MONSPERYEAR);
484         }
485
486         /* FIXME: handle calendar corrections here */
487         CurYear = TimeFields.Year - EPOCHYEAR;
488         DeltaYear = CurYear / 400;
489         CurYear -= DeltaYear * 400;
490         rcTime += DeltaYear * DAYSPERQUADRICENTENNIUM;
491         DeltaYear = CurYear / 100;
492         CurYear -= DeltaYear * 100;
493         rcTime += DeltaYear * DAYSPERNORMALCENTURY;
494         DeltaYear = CurYear / 4;
495         CurYear -= DeltaYear * 4;
496         rcTime += DeltaYear * DAYSPERNORMALQUADRENNIUM;
497         rcTime += CurYear * DAYSPERNORMALYEAR;
498         rcTime += YearDays[IsLeapYear(TimeFields.Year)][TimeFields.Month - 1];
499         rcTime += TimeFields.Day - 1;
500         rcTime *= SECSPERDAY;
501         rcTime += TimeFields.Hour * SECSPERHOUR + TimeFields.Minute * SECSPERMIN + TimeFields.Second;
502         rcTime *= TICKSPERSEC;
503         rcTime += TimeFields.Milliseconds * TICKSPERMSEC;
504         Time->QuadPart = rcTime;
505
506         return TRUE;
507 }
508
509 /***********************************************************************
510  *       TIME_GetBias [internal]
511  *
512  * Helper function calculates delta local time from UTC. 
513  *
514  * PARAMS
515  *   utc [I] The current utc time.
516  *   pdaylight [I] Local daylight.
517  *
518  * RETURNS
519  *   The bias for the current timezone.
520  */
521 static int TIME_GetBias(time_t utc, int *pdaylight)
522 {
523     struct tm *ptm;
524     static time_t last_utc;
525     static int last_bias;
526     static int last_daylight;
527     int ret;
528
529     RtlEnterCriticalSection( &TIME_GetBias_section );
530     if(utc == last_utc)
531     {
532         *pdaylight = last_daylight;
533         ret = last_bias;        
534     } else
535     {
536         ptm = localtime(&utc);
537         *pdaylight = last_daylight =
538             ptm->tm_isdst; /* daylight for local timezone */
539         ptm = gmtime(&utc);
540         ptm->tm_isdst = *pdaylight; /* use local daylight, not that of Greenwich */
541         last_utc = utc;
542         ret = last_bias = (int)(utc-mktime(ptm));
543     }
544     RtlLeaveCriticalSection( &TIME_GetBias_section );
545     return ret;
546 }
547
548 /******************************************************************************
549  *        RtlLocalTimeToSystemTime [NTDLL.@]
550  *
551  * Convert a local time into system time.
552  *
553  * PARAMS
554  *   LocalTime  [I] Local time to convert.
555  *   SystemTime [O] Destination for the converted time.
556  *
557  * RETURNS
558  *   Success: STATUS_SUCCESS.
559  *   Failure: An NTSTATUS error code indicating the problem.
560  */
561 NTSTATUS WINAPI RtlLocalTimeToSystemTime( const LARGE_INTEGER *LocalTime,
562                                           PLARGE_INTEGER SystemTime)
563 {
564     time_t gmt;
565     int bias, daylight;
566
567     TRACE("(%p, %p)\n", LocalTime, SystemTime);
568
569     gmt = time(NULL);
570     bias = TIME_GetBias(gmt, &daylight);
571
572     SystemTime->QuadPart = LocalTime->QuadPart - bias * (LONGLONG)10000000;
573     return STATUS_SUCCESS;
574 }
575
576 /******************************************************************************
577  *       RtlSystemTimeToLocalTime [NTDLL.@]
578  *
579  * Convert a system time into a local time.
580  *
581  * PARAMS
582  *   SystemTime [I] System time to convert.
583  *   LocalTime  [O] Destination for the converted time.
584  *
585  * RETURNS
586  *   Success: STATUS_SUCCESS.
587  *   Failure: An NTSTATUS error code indicating the problem.
588  */
589 NTSTATUS WINAPI RtlSystemTimeToLocalTime( const LARGE_INTEGER *SystemTime,
590                                           PLARGE_INTEGER LocalTime )
591 {
592     time_t gmt;
593     int bias, daylight;
594
595     TRACE("(%p, %p)\n", SystemTime, LocalTime);
596
597     gmt = time(NULL);
598     bias = TIME_GetBias(gmt, &daylight);
599
600     LocalTime->QuadPart = SystemTime->QuadPart + bias * (LONGLONG)10000000;
601     return STATUS_SUCCESS;
602 }
603
604 /******************************************************************************
605  *       RtlTimeToSecondsSince1970 [NTDLL.@]
606  *
607  * Convert a time into a count of seconds since 1970.
608  *
609  * PARAMS
610  *   Time    [I] Time to convert.
611  *   Seconds [O] Destination for the converted time.
612  *
613  * RETURNS
614  *   Success: TRUE.
615  *   Failure: FALSE, if the resulting value will not fit in a DWORD.
616  */
617 BOOLEAN WINAPI RtlTimeToSecondsSince1970( const LARGE_INTEGER *Time, LPDWORD Seconds )
618 {
619     ULONGLONG tmp = ((ULONGLONG)Time->u.HighPart << 32) | Time->u.LowPart;
620     tmp = RtlLargeIntegerDivide( tmp, 10000000, NULL );
621     tmp -= SECS_1601_TO_1970;
622     if (tmp > 0xffffffff) return FALSE;
623     *Seconds = (DWORD)tmp;
624     return TRUE;
625 }
626
627 /******************************************************************************
628  *       RtlTimeToSecondsSince1980 [NTDLL.@]
629  *
630  * Convert a time into a count of seconds since 1980.
631  *
632  * PARAMS
633  *   Time    [I] Time to convert.
634  *   Seconds [O] Destination for the converted time.
635  *
636  * RETURNS
637  *   Success: TRUE.
638  *   Failure: FALSE, if the resulting value will not fit in a DWORD.
639  */
640 BOOLEAN WINAPI RtlTimeToSecondsSince1980( const LARGE_INTEGER *Time, LPDWORD Seconds )
641 {
642     ULONGLONG tmp = ((ULONGLONG)Time->u.HighPart << 32) | Time->u.LowPart;
643     tmp = RtlLargeIntegerDivide( tmp, 10000000, NULL );
644     tmp -= SECS_1601_TO_1980;
645     if (tmp > 0xffffffff) return FALSE;
646     *Seconds = (DWORD)tmp;
647     return TRUE;
648 }
649
650 /******************************************************************************
651  *       RtlSecondsSince1970ToTime [NTDLL.@]
652  *
653  * Convert a count of seconds since 1970 to a time.
654  *
655  * PARAMS
656  *   Seconds [I] Time to convert.
657  *   Time    [O] Destination for the converted time.
658  *
659  * RETURNS
660  *   Nothing.
661  */
662 void WINAPI RtlSecondsSince1970ToTime( DWORD Seconds, LARGE_INTEGER *Time )
663 {
664     ULONGLONG secs = Seconds * (ULONGLONG)TICKSPERSEC + TICKS_1601_TO_1970;
665     Time->u.LowPart  = (DWORD)secs;
666     Time->u.HighPart = (DWORD)(secs >> 32);
667 }
668
669 /******************************************************************************
670  *       RtlSecondsSince1980ToTime [NTDLL.@]
671  *
672  * Convert a count of seconds since 1980 to a time.
673  *
674  * PARAMS
675  *   Seconds [I] Time to convert.
676  *   Time    [O] Destination for the converted time.
677  *
678  * RETURNS
679  *   Nothing.
680  */
681 void WINAPI RtlSecondsSince1980ToTime( DWORD Seconds, LARGE_INTEGER *Time )
682 {
683     ULONGLONG secs = Seconds * (ULONGLONG)TICKSPERSEC + TICKS_1601_TO_1980;
684     Time->u.LowPart  = (DWORD)secs;
685     Time->u.HighPart = (DWORD)(secs >> 32);
686 }
687
688 /******************************************************************************
689  *       RtlTimeToElapsedTimeFields [NTDLL.@]
690  *
691  * Convert a time to a count of elapsed seconds.
692  *
693  * PARAMS
694  *   Time       [I] Time to convert.
695  *   TimeFields [O] Destination for the converted time.
696  *
697  * RETURNS
698  *   Nothing.
699  */
700 void WINAPI RtlTimeToElapsedTimeFields( const LARGE_INTEGER *Time, PTIME_FIELDS TimeFields )
701 {
702     LONGLONG time;
703     UINT rem;
704
705     time = RtlExtendedLargeIntegerDivide( Time->QuadPart, TICKSPERSEC, &rem );
706     TimeFields->Milliseconds = rem / TICKSPERMSEC;
707
708     /* time is now in seconds */
709     TimeFields->Year  = 0;
710     TimeFields->Month = 0;
711     TimeFields->Day   = RtlExtendedLargeIntegerDivide( time, SECSPERDAY, &rem );
712
713     /* rem is now the remaining seconds in the last day */
714     TimeFields->Second = rem % 60;
715     rem /= 60;
716     TimeFields->Minute = rem % 60;
717     TimeFields->Hour = rem / 60;
718 }
719
720 /***********************************************************************
721  *       NtQuerySystemTime [NTDLL.@]
722  *       ZwQuerySystemTime [NTDLL.@]
723  *
724  * Get the current system time.
725  *
726  * PARAMS
727  *   Time [O] Destination for the current system time.
728  *
729  * RETURNS
730  *   Success: STATUS_SUCCESS.
731  *   Failure: An NTSTATUS error code indicating the problem.
732  */
733 NTSTATUS WINAPI NtQuerySystemTime( PLARGE_INTEGER Time )
734 {
735     struct timeval now;
736
737     gettimeofday( &now, 0 );
738     Time->QuadPart = now.tv_sec * (ULONGLONG)TICKSPERSEC + TICKS_1601_TO_1970;
739     Time->QuadPart += now.tv_usec * 10;
740     return STATUS_SUCCESS;
741 }
742
743 /***********************************************************************
744  *        TIME_GetTZAsStr [internal]
745  *
746  * Helper function that returns the given timezone as a string.
747  *
748  * PARAMS
749  *   utc [I] The current utc time.
750  *   bias [I] The bias of the current timezone.
751  *   dst [I] ??
752  *
753  * RETURNS
754  *   Timezone name.
755  *
756  * NOTES:
757  *   This could be done with a hash table instead of merely iterating through a
758  *   table, however with the small amount of entries (60 or so) I didn't think
759  *   it was worth it.
760  */
761 static const WCHAR* TIME_GetTZAsStr (time_t utc, int bias, int dst)
762 {
763    char psTZName[7];
764    struct tm *ptm = localtime(&utc);
765    unsigned int i;
766
767    if (!strftime (psTZName, 7, "%Z", ptm))
768       return (NULL);
769
770    for (i=0; i<(sizeof(TZ_INFO) / sizeof(struct tagTZ_INFO)); i++)
771    {
772       if ( strcmp(TZ_INFO[i].psTZFromUnix, psTZName) == 0 &&
773            TZ_INFO[i].bias == bias &&
774            TZ_INFO[i].dst == dst
775          )
776             return TZ_INFO[i].psTZWindows;
777    }
778    FIXME("Can't match system time zone name \"%s\" to an entry in TZ_INFO\n",psTZName);
779    FIXME(" Please add appropriate entry to TZ_INFO and submit as patch to wine-patches\n");
780    return NULL;
781 }
782
783 /***********************************************************************
784  *      RtlQueryTimeZoneInformation [NTDLL.@]
785  *
786  * Get information about the current timezone.
787  *
788  * PARAMS
789  *   tzinfo [O] Destination for the retrieved timezone info.
790  *
791  * RETURNS
792  *   Success: STATUS_SUCCESS.
793  *   Failure: An NTSTATUS error code indicating the problem.
794  */
795 NTSTATUS WINAPI RtlQueryTimeZoneInformation(LPTIME_ZONE_INFORMATION tzinfo)
796 {
797     time_t gmt;
798     int bias, daylight;
799     const WCHAR *psTZ;
800
801     memset(tzinfo, 0, sizeof(TIME_ZONE_INFORMATION));
802
803     gmt = time(NULL);
804     bias = TIME_GetBias(gmt, &daylight);
805
806     tzinfo->Bias = -bias / 60;
807     tzinfo->StandardBias = 0;
808     tzinfo->DaylightBias = -60;
809     psTZ = TIME_GetTZAsStr (gmt, (-bias/60), daylight);
810     if (psTZ) strcpyW( tzinfo->StandardName, psTZ );
811     return STATUS_SUCCESS;
812 }
813
814 /***********************************************************************
815  *       RtlSetTimeZoneInformation [NTDLL.@]
816  *
817  * Set the current time zone information.
818  *
819  * PARAMS
820  *   tzinfo [I] Timezone information to set.
821  *
822  * RETURNS
823  *   Success: STATUS_SUCCESS.
824  *   Failure: An NTSTATUS error code indicating the problem.
825  *
826  * BUGS
827  *   Uses the obsolete unix timezone structure and tz_dsttime member.
828  */
829 NTSTATUS WINAPI RtlSetTimeZoneInformation( const TIME_ZONE_INFORMATION *tzinfo )
830 {
831 #ifdef HAVE_SETTIMEOFDAY
832     struct timezone tz;
833
834     tz.tz_minuteswest = tzinfo->Bias;
835 #ifdef DST_NONE
836     tz.tz_dsttime = DST_NONE;
837 #else
838     tz.tz_dsttime = 0;
839 #endif
840     if(!settimeofday(NULL, &tz))
841         return STATUS_SUCCESS;
842 #endif
843     return STATUS_PRIVILEGE_NOT_HELD;
844 }
845
846 /***********************************************************************
847  *        NtSetSystemTime [NTDLL.@]
848  *        ZwSetSystemTime [NTDLL.@]
849  *
850  * Set the system time.
851  *
852  * PARAMS
853  *   NewTime [I] The time to set.
854  *   OldTime [O] Optional destination for the previous system time.
855  *
856  * RETURNS
857  *   Success: STATUS_SUCCESS.
858  *   Failure: An NTSTATUS error code indicating the problem.
859  */
860 NTSTATUS WINAPI NtSetSystemTime(const LARGE_INTEGER *NewTime, LARGE_INTEGER *OldTime)
861 {
862     TIME_FIELDS tf;
863     struct timeval tv;
864     struct timezone tz;
865     struct tm t;
866     time_t sec, oldsec;
867     int dst, bias;
868     int err;
869
870     /* Return the old time if necessary */
871     if(OldTime)
872         NtQuerySystemTime(OldTime);
873
874     RtlTimeToTimeFields(NewTime, &tf);
875
876     /* call gettimeofday to get the current timezone */
877     gettimeofday(&tv, &tz);
878     oldsec = tv.tv_sec;
879     /* get delta local time from utc */
880     bias = TIME_GetBias(oldsec, &dst);
881
882     /* get the number of seconds */
883     t.tm_sec = tf.Second;
884     t.tm_min = tf.Minute;
885     t.tm_hour = tf.Hour;
886     t.tm_mday = tf.Day;
887     t.tm_mon = tf.Month - 1;
888     t.tm_year = tf.Year - 1900;
889     t.tm_isdst = dst;
890     sec = mktime (&t);
891     /* correct for timezone and daylight */
892     sec += bias;
893
894     /* set the new time */
895     tv.tv_sec = sec;
896     tv.tv_usec = tf.Milliseconds * 1000;
897
898     /* error and sanity check*/
899     if(sec == (time_t)-1 || abs((int)(sec-oldsec)) > SETTIME_MAX_ADJUST) {
900         err = 2;
901     } else {
902 #ifdef HAVE_SETTIMEOFDAY
903         err = settimeofday(&tv, NULL); /* 0 is OK, -1 is error */
904         if(err == 0)
905             return STATUS_SUCCESS;
906 #else
907         err = 1;
908 #endif
909     }
910
911     ERR("Cannot set time to %d/%d/%d %d:%d:%d Time adjustment %ld %s\n",
912             tf.Year, tf.Month, tf.Day, tf.Hour, tf.Minute, tf.Second,
913             (long)(sec-oldsec),
914             err == -1 ? "No Permission"
915                       : sec == (time_t)-1 ? "" : "is too large." );
916
917     if(err == 2)
918         return STATUS_INVALID_PARAMETER;
919     else if(err == -1)
920         return STATUS_PRIVILEGE_NOT_HELD;
921     else
922         return STATUS_NOT_IMPLEMENTED;
923 }