time.c 42.2 KB
Newer Older
1
/*
2
 * Win32 kernel time functions
3 4
 *
 * Copyright 1995 Martin von Loewis and Cameron Heide
5 6 7 8 9 10 11 12 13 14 15 16 17
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19 20
 */

21 22
#include "config.h"

23
#include <string.h>
24 25 26
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
27
#include <stdarg.h>
28
#include <stdlib.h>
29
#include <time.h>
30 31 32
#ifdef HAVE_SYS_TIME_H
# include <sys/time.h>
#endif
33 34 35
#ifdef HAVE_SYS_TIMES_H
# include <sys/times.h>
#endif
36 37 38
#ifdef HAVE_SYS_LIMITS_H
#include <sys/limits.h>
#elif defined(HAVE_MACHINE_LIMITS_H)
39 40
#include <machine/limits.h>
#endif
41

42 43
#include "ntstatus.h"
#define WIN32_NO_STATUS
44
#define NONAMELESSUNION
45 46
#include "windef.h"
#include "winbase.h"
47
#include "winternl.h"
48
#include "kernel_private.h"
49
#include "wine/unicode.h"
50
#include "wine/debug.h"
51

52
WINE_DEFAULT_DEBUG_CHANNEL(time);
53

54
#define CALINFO_MAX_YEAR 2029
55

56 57 58 59 60
#define LL2FILETIME( ll, pft )\
    (pft)->dwLowDateTime = (UINT)(ll); \
    (pft)->dwHighDateTime = (UINT)((ll) >> 32);
#define FILETIME2LL( pft, ll) \
    ll = (((LONGLONG)((pft)->dwHighDateTime))<<32) + (pft)-> dwLowDateTime ;
61

62 63 64 65 66 67 68

static const int MonthLengths[2][12] =
{
	{ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
	{ 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
};

69
static inline BOOL IsLeapYear(int Year)
70
{
71
    return Year % 4 == 0 && (Year % 100 != 0 || Year % 400 == 0);
72 73
}

74
/***********************************************************************
75
 *  TIME_DayLightCompareDate
76
 *
77 78 79 80
 * Compares two dates without looking at the year.
 *
 * PARAMS
 *   date        [in] The local time to compare.
81
 *   compareDate [in] The daylight savings begin or end date.
82 83 84 85 86 87
 *
 * RETURNS
 *
 *  -1 if date < compareDate
 *   0 if date == compareDate
 *   1 if date > compareDate
88
 *  -2 if an error occurs
89
 */
90 91
static int TIME_DayLightCompareDate( const SYSTEMTIME *date,
    const SYSTEMTIME *compareDate )
92
{
93
    int limit_day, dayinsecs;
94 95 96 97 98 99 100

    if (date->wMonth < compareDate->wMonth)
        return -1; /* We are in a month before the date limit. */

    if (date->wMonth > compareDate->wMonth)
        return 1; /* We are in a month after the date limit. */

101 102 103 104
    /* if year is 0 then date is in day-of-week format, otherwise
     * it's absolute date.
     */
    if (compareDate->wYear == 0)
105
    {
106 107 108 109 110 111 112 113 114 115 116 117
        WORD First;
        /* compareDate->wDay is interpreted as number of the week in the month
         * 5 means: the last week in the month */
        int weekofmonth = compareDate->wDay;
          /* calculate the day of the first DayOfWeek in the month */
        First = ( 6 + compareDate->wDayOfWeek - date->wDayOfWeek + date->wDay 
               ) % 7 + 1;
        limit_day = First + 7 * (weekofmonth - 1);
        /* check needed for the 5th weekday of the month */
        if(limit_day > MonthLengths[date->wMonth==2 && IsLeapYear(date->wYear)]
                [date->wMonth - 1])
            limit_day -= 7;
118 119 120 121 122 123
    }
    else
    {
       limit_day = compareDate->wDay;
    }

124 125 126 127 128 129 130 131 132
    /* convert to seconds */
    limit_day = ((limit_day * 24  + compareDate->wHour) * 60 +
            compareDate->wMinute ) * 60;
    dayinsecs = ((date->wDay * 24  + date->wHour) * 60 +
            date->wMinute ) * 60 + date->wSecond;
    /* and compare */
    return dayinsecs < limit_day ? -1 :
           dayinsecs > limit_day ? 1 :
           0;   /* date is equal to the date limit. */
133 134 135
}

/***********************************************************************
136
 *  TIME_CompTimeZoneID
137
 *
138 139 140 141 142 143
 *  Computes the local time bias for a given time and time zone.
 *
 *  PARAMS
 *      pTZinfo     [in] The time zone data.
 *      lpFileTime  [in] The system or local time.
 *      islocal     [in] it is local time.
144
 *
145
 *  RETURNS
146 147 148
 *      TIME_ZONE_ID_INVALID    An error occurred
 *      TIME_ZONE_ID_UNKNOWN    There are no transition time known
 *      TIME_ZONE_ID_STANDARD   Current time is standard time
149
 *      TIME_ZONE_ID_DAYLIGHT   Current time is daylight savings time
150
 */
151
static DWORD TIME_CompTimeZoneID ( const TIME_ZONE_INFORMATION *pTZinfo,
152
    FILETIME *lpFileTime, BOOL islocal )
153
{
154
    int ret, year;
155
    BOOL beforeStandardDate, afterDaylightDate;
156
    DWORD retval = TIME_ZONE_ID_INVALID;
157
    LONGLONG llTime = 0; /* initialized to prevent gcc complaining */
158 159
    SYSTEMTIME SysTime;
    FILETIME ftTemp;
160

161
    if (pTZinfo->DaylightDate.wMonth != 0)
162
    {
163 164 165
        /* if year is 0 then date is in day-of-week format, otherwise
         * it's absolute date.
         */
166 167
        if (pTZinfo->StandardDate.wMonth == 0 ||
            (pTZinfo->StandardDate.wYear == 0 &&
168
            (pTZinfo->StandardDate.wDay<1 ||
169 170
            pTZinfo->StandardDate.wDay>5 ||
            pTZinfo->DaylightDate.wDay<1 ||
171
            pTZinfo->DaylightDate.wDay>5)))
172 173
        {
            SetLastError(ERROR_INVALID_PARAMETER);
174
            return TIME_ZONE_ID_INVALID;
175 176
        }

177
        if (!islocal) {
178
            FILETIME2LL( lpFileTime, llTime );
179
            llTime -= pTZinfo->Bias * (LONGLONG)600000000;
180 181
            LL2FILETIME( llTime, &ftTemp)
            lpFileTime = &ftTemp;
182
        }
183 184

        FileTimeToSystemTime(lpFileTime, &SysTime);
185 186 187 188 189 190 191 192 193 194 195 196 197
        year = SysTime.wYear;

        if (!islocal) {
            llTime -= pTZinfo->DaylightBias * (LONGLONG)600000000;
            LL2FILETIME( llTime, &ftTemp)
            FileTimeToSystemTime(lpFileTime, &SysTime);
        }

        /* check for daylight savings */
        if(year == SysTime.wYear) {
            ret = TIME_DayLightCompareDate( &SysTime, &pTZinfo->StandardDate);
            if (ret == -2)
                return TIME_ZONE_ID_INVALID;
198

199 200 201
            beforeStandardDate = ret < 0;
        } else
            beforeStandardDate = SysTime.wYear < year;
202

203
        if (!islocal) {
204 205 206 207
            llTime -= ( pTZinfo->StandardBias - pTZinfo->DaylightBias )
                * (LONGLONG)600000000;
            LL2FILETIME( llTime, &ftTemp)
            FileTimeToSystemTime(lpFileTime, &SysTime);
208 209
        }

210 211 212 213
        if(year == SysTime.wYear) {
            ret = TIME_DayLightCompareDate( &SysTime, &pTZinfo->DaylightDate);
            if (ret == -2)
                return TIME_ZONE_ID_INVALID;
214

215 216 217
            afterDaylightDate = ret >= 0;
        } else
            afterDaylightDate = SysTime.wYear > year;
218

219 220 221
        retval = TIME_ZONE_ID_STANDARD;
        if( pTZinfo->DaylightDate.wMonth <  pTZinfo->StandardDate.wMonth ) {
            /* Northern hemisphere */
222
            if( beforeStandardDate && afterDaylightDate )
223
                retval = TIME_ZONE_ID_DAYLIGHT;
224 225
        } else    /* Down south */
            if( beforeStandardDate || afterDaylightDate )
226 227 228 229 230 231 232 233 234 235 236
            retval = TIME_ZONE_ID_DAYLIGHT;
    } else 
        /* No transition date */
        retval = TIME_ZONE_ID_UNKNOWN;
        
    return retval;
}

/***********************************************************************
 *  TIME_TimeZoneID
 *
237
 *  Calculates whether daylight savings is on now.
238
 *
239 240 241 242
 *  PARAMS
 *      pTzi [in] Timezone info.
 *
 *  RETURNS
243 244 245
 *      TIME_ZONE_ID_INVALID    An error occurred
 *      TIME_ZONE_ID_UNKNOWN    There are no transition time known
 *      TIME_ZONE_ID_STANDARD   Current time is standard time
246
 *      TIME_ZONE_ID_DAYLIGHT   Current time is daylight savings time
247
 */
248
static DWORD TIME_ZoneID( const TIME_ZONE_INFORMATION *pTzi )
249 250 251 252 253
{
    FILETIME ftTime;
    GetSystemTimeAsFileTime( &ftTime);
    return TIME_CompTimeZoneID( pTzi, &ftTime, FALSE);
}
254

255 256 257
/***********************************************************************
 *  TIME_GetTimezoneBias
 *
258
 *  Calculates the local time bias for a given time zone.
259
 *
260 261 262 263 264
 * PARAMS
 *  pTZinfo    [in]  The time zone data.
 *  lpFileTime [in]  The system or local time.
 *  islocal    [in]  It is local time.
 *  pBias      [out] The calculated bias in minutes.
265
 *
266 267
 * RETURNS
 *  TRUE when the time zone bias was calculated.
268
 */
269 270
static BOOL TIME_GetTimezoneBias( const TIME_ZONE_INFORMATION *pTZinfo,
    FILETIME *lpFileTime, BOOL islocal, LONG *pBias )
271 272 273
{
    LONG bias = pTZinfo->Bias;
    DWORD tzid = TIME_CompTimeZoneID( pTZinfo, lpFileTime, islocal);
274

275 276 277 278 279 280
    if( tzid == TIME_ZONE_ID_INVALID)
        return FALSE;
    if (tzid == TIME_ZONE_ID_DAYLIGHT)
        bias += pTZinfo->DaylightBias;
    else if (tzid == TIME_ZONE_ID_STANDARD)
        bias += pTZinfo->StandardBias;
281
    *pBias = bias;
282 283 284
    return TRUE;
}

285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
/***********************************************************************
 *  TIME_GetSpecificTimeZoneKey
 *
 *  Opens the registry key for the time zone with the given name.
 *
 * PARAMS
 *  key_name   [in]  The time zone name.
 *  result     [out] The open registry key handle.
 *
 * RETURNS
 *  TRUE if successful.
 */
static BOOL TIME_GetSpecificTimeZoneKey( const WCHAR *key_name, HANDLE *result )
{
    static const WCHAR Time_ZonesW[] = { '\\','R','E','G','I','S','T','R','Y','\\',
        'M','a','c','h','i','n','e','\\',
        'S','o','f','t','w','a','r','e','\\',
        'M','i','c','r','o','s','o','f','t','\\',
        'W','i','n','d','o','w','s',' ','N','T','\\',
        'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
        'T','i','m','e',' ','Z','o','n','e','s',0 };
    HANDLE time_zones_key;
    OBJECT_ATTRIBUTES attr;
    UNICODE_STRING nameW;
    NTSTATUS status;

    attr.Length = sizeof(attr);
    attr.RootDirectory = 0;
    attr.ObjectName = &nameW;
    attr.Attributes = 0;
    attr.SecurityDescriptor = NULL;
    attr.SecurityQualityOfService = NULL;
    RtlInitUnicodeString( &nameW, Time_ZonesW );
    status = NtOpenKey( &time_zones_key, KEY_READ, &attr );
    if (status)
    {
        WARN("Unable to open the time zones key\n");
        SetLastError( RtlNtStatusToDosError(status) );
        return FALSE;
    }

    attr.RootDirectory = time_zones_key;
    RtlInitUnicodeString( &nameW, key_name );
    status = NtOpenKey( result, KEY_READ, &attr );

    NtClose( time_zones_key );

    if (status)
    {
        SetLastError( RtlNtStatusToDosError(status) );
        return FALSE;
    }

    return TRUE;
}

static BOOL reg_query_value(HKEY hkey, LPCWSTR name, DWORD type, void *data, DWORD count)
{
    UNICODE_STRING nameW;
    char buf[256];
    KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buf;
    NTSTATUS status;

    if (count > sizeof(buf) - sizeof(KEY_VALUE_PARTIAL_INFORMATION))
        return FALSE;

    RtlInitUnicodeString(&nameW, name);

    if ((status = NtQueryValueKey(hkey, &nameW, KeyValuePartialInformation,
                                  buf, sizeof(buf), &count)))
    {
        SetLastError( RtlNtStatusToDosError(status) );
        return FALSE;
    }

    if (info->Type != type)
    {
        SetLastError( ERROR_DATATYPE_MISMATCH );
        return FALSE;
    }

    memcpy(data, info->Data, info->DataLength);
    return TRUE;
}

/***********************************************************************
 *  TIME_GetSpecificTimeZoneInfo
 *
 *  Returns time zone information for the given time zone and year.
 *
 * PARAMS
 *  key_name   [in]  The time zone name.
 *  year       [in]  The year, if Dynamic DST is used.
 *  dynamic    [in]  Whether to use Dynamic DST.
 *  result     [out] The time zone information.
 *
 * RETURNS
 *  TRUE if successful.
 */
static BOOL TIME_GetSpecificTimeZoneInfo( const WCHAR *key_name, WORD year,
    BOOL dynamic, DYNAMIC_TIME_ZONE_INFORMATION *tzinfo )
{
    static const WCHAR Dynamic_DstW[] = { 'D','y','n','a','m','i','c',' ','D','S','T',0 };
    static const WCHAR fmtW[] = { '%','d',0 };
    static const WCHAR stdW[] = { 'S','t','d',0 };
    static const WCHAR dltW[] = { 'D','l','t',0 };
    static const WCHAR tziW[] = { 'T','Z','I',0 };
    HANDLE time_zone_key, dynamic_dst_key;
    OBJECT_ATTRIBUTES attr;
    UNICODE_STRING nameW;
    WCHAR yearW[16];
    BOOL got_reg_data = FALSE;
    struct tz_reg_data
    {
        LONG bias;
        LONG std_bias;
        LONG dlt_bias;
        SYSTEMTIME std_date;
        SYSTEMTIME dlt_date;
    } tz_data;

    if (!TIME_GetSpecificTimeZoneKey( key_name, &time_zone_key ))
        return FALSE;

    if (!reg_query_value( time_zone_key, stdW, REG_SZ, tzinfo->StandardName, sizeof(tzinfo->StandardName)) ||
        !reg_query_value( time_zone_key, dltW, REG_SZ, tzinfo->DaylightName, sizeof(tzinfo->DaylightName)))
    {
        NtClose( time_zone_key );
        return FALSE;
    }

    lstrcpyW(tzinfo->TimeZoneKeyName, key_name);

    if (dynamic)
    {
        attr.Length = sizeof(attr);
        attr.RootDirectory = time_zone_key;
        attr.ObjectName = &nameW;
        attr.Attributes = 0;
        attr.SecurityDescriptor = NULL;
        attr.SecurityQualityOfService = NULL;
        RtlInitUnicodeString( &nameW, Dynamic_DstW );
        if (!NtOpenKey( &dynamic_dst_key, KEY_READ, &attr ))
        {
            sprintfW( yearW, fmtW, year );
            got_reg_data = reg_query_value( dynamic_dst_key, yearW, REG_BINARY, &tz_data, sizeof(tz_data) );

            NtClose( dynamic_dst_key );
        }
    }

    if (!got_reg_data)
    {
        if (!reg_query_value( time_zone_key, tziW, REG_BINARY, &tz_data, sizeof(tz_data) ))
        {
            NtClose( time_zone_key );
            return FALSE;
        }
    }

    tzinfo->Bias = tz_data.bias;
    tzinfo->StandardBias = tz_data.std_bias;
    tzinfo->DaylightBias = tz_data.dlt_bias;
    tzinfo->StandardDate = tz_data.std_date;
    tzinfo->DaylightDate = tz_data.dlt_date;

    tzinfo->DynamicDaylightTimeDisabled = !dynamic;

    NtClose( time_zone_key );

    return TRUE;
}

458 459 460 461 462 463 464

/***********************************************************************
 *              SetLocalTime            (KERNEL32.@)
 *
 *  Set the local time using current time zone and daylight
 *  savings settings.
 *
465 466 467
 * PARAMS
 *  systime [in] The desired local time.
 *
468
 * RETURNS
469
 *  Success: TRUE. The time was set.
470 471 472
 *  Failure: FALSE, if the time was invalid or caller does not have
 *           permission to change the time.
 */
473
BOOL WINAPI SetLocalTime( const SYSTEMTIME *systime )
474 475 476 477 478
{
    FILETIME ft;
    LARGE_INTEGER st, st2;
    NTSTATUS status;

479 480
    if( !SystemTimeToFileTime( systime, &ft ))
        return FALSE;
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
    st.u.LowPart = ft.dwLowDateTime;
    st.u.HighPart = ft.dwHighDateTime;
    RtlLocalTimeToSystemTime( &st, &st2 );

    if ((status = NtSetSystemTime(&st2, NULL)))
        SetLastError( RtlNtStatusToDosError(status) );
    return !status;
}


/***********************************************************************
 *           GetSystemTimeAdjustment     (KERNEL32.@)
 *
 *  Get the period between clock interrupts and the amount the clock
 *  is adjusted each interrupt so as to keep it in sync with an external source.
 *
497 498 499 500 501
 * PARAMS
 *  lpTimeAdjustment [out] The clock adjustment per interrupt in 100's of nanoseconds.
 *  lpTimeIncrement  [out] The time between clock interrupts in 100's of nanoseconds.
 *  lpTimeAdjustmentDisabled [out] The clock synchronisation has been disabled.
 *
502 503 504 505 506 507
 * RETURNS
 *  TRUE.
 *
 * BUGS
 *  Only the special case of disabled time adjustments is supported.
 */
508 509
BOOL WINAPI GetSystemTimeAdjustment( PDWORD lpTimeAdjustment, PDWORD lpTimeIncrement,
    PBOOL  lpTimeAdjustmentDisabled )
510 511
{
    *lpTimeAdjustment = 0;
512
    *lpTimeIncrement = 10000000 / sysconf(_SC_CLK_TCK);
513 514 515 516
    *lpTimeAdjustmentDisabled = TRUE;
    return TRUE;
}

517

518 519 520 521 522
/***********************************************************************
 *              SetSystemTime            (KERNEL32.@)
 *
 *  Set the system time in utc.
 *
523 524 525
 * PARAMS
 *  systime [in] The desired system time.
 *
526
 * RETURNS
527
 *  Success: TRUE. The time was set.
528 529 530
 *  Failure: FALSE, if the time was invalid or caller does not have
 *           permission to change the time.
 */
531
BOOL WINAPI SetSystemTime( const SYSTEMTIME *systime )
532 533 534 535 536
{
    FILETIME ft;
    LARGE_INTEGER t;
    NTSTATUS status;

537 538
    if( !SystemTimeToFileTime( systime, &ft ))
        return FALSE;
539 540 541 542 543 544 545 546 547 548 549 550
    t.u.LowPart = ft.dwLowDateTime;
    t.u.HighPart = ft.dwHighDateTime;
    if ((status = NtSetSystemTime(&t, NULL)))
        SetLastError( RtlNtStatusToDosError(status) );
    return !status;
}

/***********************************************************************
 *              SetSystemTimeAdjustment  (KERNEL32.@)
 *
 *  Enables or disables the timing adjustments to the system's clock.
 *
551 552 553 554
 * PARAMS
 *  dwTimeAdjustment        [in] Number of units to add per clock interrupt.
 *  bTimeAdjustmentDisabled [in] Adjustment mode.
 *
555 556 557 558
 * RETURNS
 *  Success: TRUE.
 *  Failure: FALSE.
 */
559
BOOL WINAPI SetSystemTimeAdjustment( DWORD dwTimeAdjustment, BOOL bTimeAdjustmentDisabled )
560 561
{
    /* Fake function for now... */
562
    FIXME("(%08x,%d): stub !\n", dwTimeAdjustment, bTimeAdjustmentDisabled);
563 564 565
    return TRUE;
}

566 567 568 569 570
/***********************************************************************
 *              GetTimeZoneInformation  (KERNEL32.@)
 *
 *  Get information about the current local time zone.
 *
571 572 573
 * PARAMS
 *  tzinfo [out] Destination for time zone information.
 *
574
 * RETURNS
575 576 577
 *  TIME_ZONE_ID_INVALID    An error occurred
 *  TIME_ZONE_ID_UNKNOWN    There are no transition time known
 *  TIME_ZONE_ID_STANDARD   Current time is standard time
Austin English's avatar
Austin English committed
578
 *  TIME_ZONE_ID_DAYLIGHT   Current time is daylight savings time
579
 */
580
DWORD WINAPI GetTimeZoneInformation( LPTIME_ZONE_INFORMATION tzinfo )
581 582
{
    NTSTATUS status;
583 584 585 586

    status = RtlQueryTimeZoneInformation( (RTL_TIME_ZONE_INFORMATION*)tzinfo );
    if ( status != STATUS_SUCCESS )
    {
587 588 589 590 591 592
        SetLastError( RtlNtStatusToDosError(status) );
        return TIME_ZONE_ID_INVALID;
    }
    return TIME_ZoneID( tzinfo );
}

593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616
/***********************************************************************
 *              GetTimeZoneInformationForYear  (KERNEL32.@)
 */
BOOL WINAPI GetTimeZoneInformationForYear( USHORT wYear,
    PDYNAMIC_TIME_ZONE_INFORMATION pdtzi, LPTIME_ZONE_INFORMATION ptzi )
{
    DYNAMIC_TIME_ZONE_INFORMATION local_dtzi, result;

    if (!pdtzi)
    {
        if (GetDynamicTimeZoneInformation(&local_dtzi) == TIME_ZONE_ID_INVALID)
            return FALSE;
        pdtzi = &local_dtzi;
    }

    if (!TIME_GetSpecificTimeZoneInfo(pdtzi->TimeZoneKeyName, wYear,
            !pdtzi->DynamicDaylightTimeDisabled, &result))
        return FALSE;

    memcpy(ptzi, &result, sizeof(*ptzi));

    return TRUE;
}

617 618 619 620 621
/***********************************************************************
 *              SetTimeZoneInformation  (KERNEL32.@)
 *
 *  Change the settings of the current local time zone.
 *
622 623 624
 * PARAMS
 *  tzinfo [in] The new time zone.
 *
625
 * RETURNS
626
 *  Success: TRUE. The time zone was updated with the settings from tzinfo.
627 628
 *  Failure: FALSE.
 */
629
BOOL WINAPI SetTimeZoneInformation( const TIME_ZONE_INFORMATION *tzinfo )
630 631
{
    NTSTATUS status;
632
    status = RtlSetTimeZoneInformation( (const RTL_TIME_ZONE_INFORMATION *)tzinfo );
633
    if ( status != STATUS_SUCCESS )
634 635 636
        SetLastError( RtlNtStatusToDosError(status) );
    return !status;
}
637

638
/***********************************************************************
639
 *              SystemTimeToTzSpecificLocalTime  (KERNEL32.@)
Andrew Johnston's avatar
Andrew Johnston committed
640
 *
Jon Griffiths's avatar
Jon Griffiths committed
641
 *  Convert a utc system time to a local time in a given time zone.
Andrew Johnston's avatar
Andrew Johnston committed
642
 *
643 644 645 646 647
 * PARAMS
 *  lpTimeZoneInformation [in]  The desired time zone.
 *  lpUniversalTime       [in]  The utc time to base local time on.
 *  lpLocalTime           [out] The local time in the time zone.
 *
Andrew Johnston's avatar
Andrew Johnston committed
648
 * RETURNS
Jon Griffiths's avatar
Jon Griffiths committed
649 650
 *  Success: TRUE. lpLocalTime contains the converted time
 *  Failure: FALSE.
651
 */
652

653
BOOL WINAPI SystemTimeToTzSpecificLocalTime(
654 655
    const TIME_ZONE_INFORMATION *lpTimeZoneInformation,
    const SYSTEMTIME *lpUniversalTime, LPSYSTEMTIME lpLocalTime )
656
{
657 658
    FILETIME ft;
    LONG lBias;
659
    LONGLONG llTime;
660 661 662 663
    TIME_ZONE_INFORMATION tzinfo;

    if (lpTimeZoneInformation != NULL)
    {
664
        tzinfo = *lpTimeZoneInformation;
665 666 667 668 669 670 671 672 673
    }
    else
    {
        if (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_INVALID)
            return FALSE;
    }

    if (!SystemTimeToFileTime(lpUniversalTime, &ft))
        return FALSE;
674
    FILETIME2LL( &ft, llTime)
675
    if (!TIME_GetTimezoneBias(&tzinfo, &ft, FALSE, &lBias))
676
        return FALSE;
677 678 679
    /* convert minutes to 100-nanoseconds-ticks */
    llTime -= (LONGLONG)lBias * 600000000;
    LL2FILETIME( llTime, &ft)
680 681 682 683 684 685 686 687

    return FileTimeToSystemTime(&ft, lpLocalTime);
}


/***********************************************************************
 *              TzSpecificLocalTimeToSystemTime  (KERNEL32.@)
 *
Jon Griffiths's avatar
Jon Griffiths committed
688
 *  Converts a local time to a time in utc.
689
 *
690 691 692 693 694
 * PARAMS
 *  lpTimeZoneInformation [in]  The desired time zone.
 *  lpLocalTime           [in]  The local time.
 *  lpUniversalTime       [out] The calculated utc time.
 *
695
 * RETURNS
696
 *  Success: TRUE. lpUniversalTime contains the converted time.
Jon Griffiths's avatar
Jon Griffiths committed
697
 *  Failure: FALSE.
698 699
 */
BOOL WINAPI TzSpecificLocalTimeToSystemTime(
700 701
    const TIME_ZONE_INFORMATION *lpTimeZoneInformation,
    const SYSTEMTIME *lpLocalTime, LPSYSTEMTIME lpUniversalTime)
702 703 704
{
    FILETIME ft;
    LONG lBias;
705
    LONGLONG t;
706 707 708 709
    TIME_ZONE_INFORMATION tzinfo;

    if (lpTimeZoneInformation != NULL)
    {
710
        tzinfo = *lpTimeZoneInformation;
711 712 713 714 715 716 717 718 719
    }
    else
    {
        if (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_INVALID)
            return FALSE;
    }

    if (!SystemTimeToFileTime(lpLocalTime, &ft))
        return FALSE;
720
    FILETIME2LL( &ft, t)
721
    if (!TIME_GetTimezoneBias(&tzinfo, &ft, TRUE, &lBias))
722
        return FALSE;
723 724 725
    /* convert minutes to 100-nanoseconds-ticks */
    t += (LONGLONG)lBias * 600000000;
    LL2FILETIME( t, &ft)
726
    return FileTimeToSystemTime(&ft, lpUniversalTime);
727 728
}

729 730

/***********************************************************************
731
 *              GetSystemTimeAsFileTime  (KERNEL32.@)
Andrew Johnston's avatar
Andrew Johnston committed
732
 *
Jon Griffiths's avatar
Jon Griffiths committed
733 734 735 736
 *  Get the current time in utc format.
 *
 *  RETURNS
 *   Nothing.
737
 */
Andrew Johnston's avatar
Andrew Johnston committed
738
VOID WINAPI GetSystemTimeAsFileTime(
Jon Griffiths's avatar
Jon Griffiths committed
739
    LPFILETIME time) /* [out] Destination for the current utc time */
740
{
741 742
    LARGE_INTEGER t;
    NtQuerySystemTime( &t );
743 744
    time->dwLowDateTime = t.u.LowPart;
    time->dwHighDateTime = t.u.HighPart;
745 746 747
}


748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
/***********************************************************************
 *              GetSystemTimePreciseAsFileTime  (KERNEL32.@)
 *
 *  Get the current time in utc format, with <1 us precision.
 *
 *  RETURNS
 *   Nothing.
 */
VOID WINAPI GetSystemTimePreciseAsFileTime(
    LPFILETIME time) /* [out] Destination for the current utc time */
{
    GetSystemTimeAsFileTime(time);
}


763
/*********************************************************************
Andrew Johnston's avatar
Andrew Johnston committed
764 765 766 767
 *      TIME_ClockTimeToFileTime    (olorin@fandra.org, 20-Sep-1998)
 *
 *  Used by GetProcessTimes to convert clock_t into FILETIME.
 *
768 769
 *      Differences to UnixTimeToFileTime:
 *          1) Divided by CLK_TCK
770
 *          2) Time is relative. There is no 'starting date', so there is
Jon Griffiths's avatar
Jon Griffiths committed
771
 *             no need for offset correction, like in UnixTimeToFileTime
772 773 774
 */
static void TIME_ClockTimeToFileTime(clock_t unix_time, LPFILETIME filetime)
{
775
    long clocksPerSec = sysconf(_SC_CLK_TCK);
776
    ULONGLONG secs = (ULONGLONG)unix_time * 10000000 / clocksPerSec;
777 778
    filetime->dwLowDateTime  = (DWORD)secs;
    filetime->dwHighDateTime = (DWORD)(secs >> 32);
779 780 781
}

/*********************************************************************
782
 *	GetProcessTimes				(KERNEL32.@)
783
 *
Jon Griffiths's avatar
Jon Griffiths committed
784
 *  Get the user and kernel execution times of a process,
Andrew Johnston's avatar
Andrew Johnston committed
785 786
 *  along with the creation and exit times if known.
 *
787 788 789 790 791 792 793
 * PARAMS
 *  hprocess       [in]  The process to be queried.
 *  lpCreationTime [out] The creation time of the process.
 *  lpExitTime     [out] The exit time of the process if exited.
 *  lpKernelTime   [out] The time spent in kernel routines in 100's of nanoseconds.
 *  lpUserTime     [out] The time spent in user routines in 100's of nanoseconds.
 *
Andrew Johnston's avatar
Andrew Johnston committed
794
 * RETURNS
Jon Griffiths's avatar
Jon Griffiths committed
795
 *  TRUE.
Andrew Johnston's avatar
Andrew Johnston committed
796
 *
Jon Griffiths's avatar
Jon Griffiths committed
797 798 799 800
 * NOTES
 *  olorin@fandra.org:
 *  Would be nice to subtract the cpu time used by Wine at startup.
 *  Also, there is a need to separate times used by different applications.
Andrew Johnston's avatar
Andrew Johnston committed
801 802
 *
 * BUGS
803
 *  KernelTime and UserTime are always for the current process
804
 */
805 806
BOOL WINAPI GetProcessTimes( HANDLE hprocess, LPFILETIME lpCreationTime,
    LPFILETIME lpExitTime, LPFILETIME lpKernelTime, LPFILETIME lpUserTime )
807 808
{
    struct tms tms;
809
    KERNEL_USER_TIMES pti;
810 811 812 813

    times(&tms);
    TIME_ClockTimeToFileTime(tms.tms_utime,lpUserTime);
    TIME_ClockTimeToFileTime(tms.tms_stime,lpKernelTime);
814 815 816 817
    if (NtQueryInformationProcess( hprocess, ProcessTimes, &pti, sizeof(pti), NULL))
        return FALSE;
    LL2FILETIME( pti.CreateTime.QuadPart, lpCreationTime);
    LL2FILETIME( pti.ExitTime.QuadPart, lpExitTime);
818 819
    return TRUE;
}
820 821

/*********************************************************************
822
 *	GetCalendarInfoA				(KERNEL32.@)
823 824
 *
 */
825
int WINAPI GetCalendarInfoA(LCID lcid, CALID Calendar, CALTYPE CalType,
826 827
			    LPSTR lpCalData, int cchData, LPDWORD lpValue)
{
828
    int ret, cchDataW = cchData;
829 830
    LPWSTR lpCalDataW = NULL;

831 832 833 834 835 836
    if (NLS_IsUnicodeOnlyLcid(lcid))
    {
      SetLastError(ERROR_INVALID_PARAMETER);
      return 0;
    }

837 838 839 840
    if (!cchData && !(CalType & CAL_RETURN_NUMBER))
        cchDataW = GetCalendarInfoW(lcid, Calendar, CalType, NULL, 0, NULL);
    if (!(lpCalDataW = HeapAlloc(GetProcessHeap(), 0, cchDataW*sizeof(WCHAR))))
        return 0;
841

842
    ret = GetCalendarInfoW(lcid, Calendar, CalType, lpCalDataW, cchDataW, lpValue);
843
    if(ret && lpCalDataW && lpCalData)
844
        ret = WideCharToMultiByte(CP_ACP, 0, lpCalDataW, -1, lpCalData, cchData, NULL, NULL);
845 846
    else if (CalType & CAL_RETURN_NUMBER)
        ret *= sizeof(WCHAR);
847
    HeapFree(GetProcessHeap(), 0, lpCalDataW);
848 849

    return ret;
850 851 852
}

/*********************************************************************
853
 *	GetCalendarInfoW				(KERNEL32.@)
854 855 856 857
 *
 */
int WINAPI GetCalendarInfoW(LCID Locale, CALID Calendar, CALTYPE CalType,
			    LPWSTR lpCalData, int cchData, LPDWORD lpValue)
858
{
859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918
    static const LCTYPE caltype_lctype_map[] = {
        0, /* not used */
        0, /* CAL_ICALINTVALUE */
        0, /* CAL_SCALNAME */
        0, /* CAL_IYEAROFFSETRANGE */
        0, /* CAL_SERASTRING */
        LOCALE_SSHORTDATE,
        LOCALE_SLONGDATE,
        LOCALE_SDAYNAME1,
        LOCALE_SDAYNAME2,
        LOCALE_SDAYNAME3,
        LOCALE_SDAYNAME4,
        LOCALE_SDAYNAME5,
        LOCALE_SDAYNAME6,
        LOCALE_SDAYNAME7,
        LOCALE_SABBREVDAYNAME1,
        LOCALE_SABBREVDAYNAME2,
        LOCALE_SABBREVDAYNAME3,
        LOCALE_SABBREVDAYNAME4,
        LOCALE_SABBREVDAYNAME5,
        LOCALE_SABBREVDAYNAME6,
        LOCALE_SABBREVDAYNAME7,
        LOCALE_SMONTHNAME1,
        LOCALE_SMONTHNAME2,
        LOCALE_SMONTHNAME3,
        LOCALE_SMONTHNAME4,
        LOCALE_SMONTHNAME5,
        LOCALE_SMONTHNAME6,
        LOCALE_SMONTHNAME7,
        LOCALE_SMONTHNAME8,
        LOCALE_SMONTHNAME9,
        LOCALE_SMONTHNAME10,
        LOCALE_SMONTHNAME11,
        LOCALE_SMONTHNAME12,
        LOCALE_SMONTHNAME13,
        LOCALE_SABBREVMONTHNAME1,
        LOCALE_SABBREVMONTHNAME2,
        LOCALE_SABBREVMONTHNAME3,
        LOCALE_SABBREVMONTHNAME4,
        LOCALE_SABBREVMONTHNAME5,
        LOCALE_SABBREVMONTHNAME6,
        LOCALE_SABBREVMONTHNAME7,
        LOCALE_SABBREVMONTHNAME8,
        LOCALE_SABBREVMONTHNAME9,
        LOCALE_SABBREVMONTHNAME10,
        LOCALE_SABBREVMONTHNAME11,
        LOCALE_SABBREVMONTHNAME12,
        LOCALE_SABBREVMONTHNAME13,
        LOCALE_SYEARMONTH,
        0, /* CAL_ITWODIGITYEARMAX */
        LOCALE_SSHORTESTDAYNAME1,
        LOCALE_SSHORTESTDAYNAME2,
        LOCALE_SSHORTESTDAYNAME3,
        LOCALE_SSHORTESTDAYNAME4,
        LOCALE_SSHORTESTDAYNAME5,
        LOCALE_SSHORTESTDAYNAME6,
        LOCALE_SSHORTESTDAYNAME7,
        LOCALE_SMONTHDAY,
        0, /* CAL_SABBREVERASTRING */
    };
919
    DWORD localeflags = 0;
920 921
    CALTYPE calinfo;

922 923 924 925 926 927
    if (CalType & CAL_NOUSEROVERRIDE)
	FIXME("flag CAL_NOUSEROVERRIDE used, not fully implemented\n");
    if (CalType & CAL_USE_CP_ACP)
	FIXME("flag CAL_USE_CP_ACP used, not fully implemented\n");

    if (CalType & CAL_RETURN_NUMBER) {
928 929 930 931 932
        if (!lpValue)
        {
            SetLastError( ERROR_INVALID_PARAMETER );
            return 0;
        }
933 934 935 936 937 938 939 940 941 942 943
	if (lpCalData != NULL)
	    WARN("lpCalData not NULL (%p) when it should!\n", lpCalData);
	if (cchData != 0)
	    WARN("cchData not 0 (%d) when it should!\n", cchData);
    } else {
	if (lpValue != NULL)
	    WARN("lpValue not NULL (%p) when it should!\n", lpValue);
    }

    /* FIXME: No verification is made yet wrt Locale
     * for the CALTYPES not requiring GetLocaleInfoA */
944 945 946

    calinfo = CalType & 0xffff;

947 948 949
    if (CalType & CAL_RETURN_GENITIVE_NAMES)
        localeflags |= LOCALE_RETURN_GENITIVE_NAMES;

950
    switch (calinfo) {
951
	case CAL_ICALINTVALUE:
952 953 954 955
            if (CalType & CAL_RETURN_NUMBER)
                return GetLocaleInfoW(Locale, LOCALE_RETURN_NUMBER | LOCALE_ICALENDARTYPE,
                        (LPWSTR)lpValue, 2);
            return GetLocaleInfoW(Locale, LOCALE_ICALENDARTYPE, lpCalData, cchData);
956
	case CAL_SCALNAME:
957
            FIXME("Unimplemented caltype %d\n", calinfo);
958 959
            if (lpCalData) *lpCalData = 0;
	    return 1;
960
	case CAL_IYEAROFFSETRANGE:
961
            FIXME("Unimplemented caltype %d\n", calinfo);
962
	    return 0;
963
	case CAL_SERASTRING:
964
            FIXME("Unimplemented caltype %d\n", calinfo);
965
	    return 0;
966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
	case CAL_SSHORTDATE:
	case CAL_SLONGDATE:
	case CAL_SDAYNAME1:
	case CAL_SDAYNAME2:
	case CAL_SDAYNAME3:
	case CAL_SDAYNAME4:
	case CAL_SDAYNAME5:
	case CAL_SDAYNAME6:
	case CAL_SDAYNAME7:
	case CAL_SABBREVDAYNAME1:
	case CAL_SABBREVDAYNAME2:
	case CAL_SABBREVDAYNAME3:
	case CAL_SABBREVDAYNAME4:
	case CAL_SABBREVDAYNAME5:
	case CAL_SABBREVDAYNAME6:
	case CAL_SABBREVDAYNAME7:
	case CAL_SMONTHNAME1:
	case CAL_SMONTHNAME2:
	case CAL_SMONTHNAME3:
	case CAL_SMONTHNAME4:
	case CAL_SMONTHNAME5:
	case CAL_SMONTHNAME6:
	case CAL_SMONTHNAME7:
	case CAL_SMONTHNAME8:
	case CAL_SMONTHNAME9:
	case CAL_SMONTHNAME10:
	case CAL_SMONTHNAME11:
	case CAL_SMONTHNAME12:
	case CAL_SMONTHNAME13:
	case CAL_SABBREVMONTHNAME1:
	case CAL_SABBREVMONTHNAME2:
	case CAL_SABBREVMONTHNAME3:
	case CAL_SABBREVMONTHNAME4:
	case CAL_SABBREVMONTHNAME5:
	case CAL_SABBREVMONTHNAME6:
	case CAL_SABBREVMONTHNAME7:
	case CAL_SABBREVMONTHNAME8:
	case CAL_SABBREVMONTHNAME9:
	case CAL_SABBREVMONTHNAME10:
	case CAL_SABBREVMONTHNAME11:
	case CAL_SABBREVMONTHNAME12:
	case CAL_SABBREVMONTHNAME13:
	case CAL_SYEARMONTH:
1009
            return GetLocaleInfoW(Locale, caltype_lctype_map[calinfo] | localeflags, lpCalData, cchData);
1010
	case CAL_ITWODIGITYEARMAX:
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
            if (CalType & CAL_RETURN_NUMBER)
            {
                *lpValue = CALINFO_MAX_YEAR;
                return sizeof(DWORD) / sizeof(WCHAR);
            }
            else
            {
                static const WCHAR fmtW[] = {'%','u',0};
                WCHAR buffer[10];
                int ret = snprintfW( buffer, 10, fmtW, CALINFO_MAX_YEAR  ) + 1;
                if (!lpCalData) return ret;
                if (ret <= cchData)
                {
                    strcpyW( lpCalData, buffer );
                    return ret;
                }
                SetLastError( ERROR_INSUFFICIENT_BUFFER );
                return 0;
            }
1030
	    break;
1031
	default:
1032
            FIXME("Unknown caltype %d\n", calinfo);
1033 1034
            SetLastError(ERROR_INVALID_FLAGS);
            return 0;
1035
    }
1036 1037 1038
    return 0;
}

1039 1040 1041 1042 1043 1044
/*********************************************************************
 *	GetCalendarInfoEx				(KERNEL32.@)
 */
int WINAPI GetCalendarInfoEx(LPCWSTR locale, CALID calendar, LPCWSTR lpReserved, CALTYPE caltype,
    LPWSTR data, int len, DWORD *value)
{
1045 1046
    static int once;

1047
    LCID lcid = LocaleNameToLCID(locale, 0);
1048 1049
    if (!once++)
        FIXME("(%s, %d, %p, 0x%08x, %p, %d, %p): semi-stub\n", debugstr_w(locale), calendar, lpReserved, caltype,
1050 1051 1052 1053
        data, len, value);
    return GetCalendarInfoW(lcid, calendar, caltype, data, len, value);
}

1054
/*********************************************************************
1055
 *	SetCalendarInfoA				(KERNEL32.@)
1056 1057 1058 1059
 *
 */
int WINAPI	SetCalendarInfoA(LCID Locale, CALID Calendar, CALTYPE CalType, LPCSTR lpCalData)
{
1060
    FIXME("(%08x,%08x,%08x,%s): stub\n",
1061 1062 1063 1064 1065
	  Locale, Calendar, CalType, debugstr_a(lpCalData));
    return 0;
}

/*********************************************************************
1066
 *	SetCalendarInfoW				(KERNEL32.@)
1067
 *
1068
 *
1069 1070 1071
 */
int WINAPI	SetCalendarInfoW(LCID Locale, CALID Calendar, CALTYPE CalType, LPCWSTR lpCalData)
{
1072
    FIXME("(%08x,%08x,%08x,%s): stub\n",
1073 1074 1075
	  Locale, Calendar, CalType, debugstr_w(lpCalData));
    return 0;
}
1076 1077 1078 1079

/*********************************************************************
 *      LocalFileTimeToFileTime                         (KERNEL32.@)
 */
1080
BOOL WINAPI LocalFileTimeToFileTime( const FILETIME *localft, LPFILETIME utcft )
1081 1082
{
    NTSTATUS status;
1083 1084
    LARGE_INTEGER local, utc;

1085 1086
    local.u.LowPart = localft->dwLowDateTime;
    local.u.HighPart = localft->dwHighDateTime;
1087 1088
    if (!(status = RtlLocalTimeToSystemTime( &local, &utc )))
    {
1089 1090
        utcft->dwLowDateTime = utc.u.LowPart;
        utcft->dwHighDateTime = utc.u.HighPart;
1091 1092 1093
    }
    else SetLastError( RtlNtStatusToDosError(status) );

1094 1095 1096 1097 1098 1099
    return !status;
}

/*********************************************************************
 *      FileTimeToLocalFileTime                         (KERNEL32.@)
 */
1100
BOOL WINAPI FileTimeToLocalFileTime( const FILETIME *utcft, LPFILETIME localft )
1101 1102
{
    NTSTATUS status;
1103 1104
    LARGE_INTEGER local, utc;

1105 1106
    utc.u.LowPart = utcft->dwLowDateTime;
    utc.u.HighPart = utcft->dwHighDateTime;
1107 1108
    if (!(status = RtlSystemTimeToLocalTime( &utc, &local )))
    {
1109 1110
        localft->dwLowDateTime = local.u.LowPart;
        localft->dwHighDateTime = local.u.HighPart;
1111 1112 1113
    }
    else SetLastError( RtlNtStatusToDosError(status) );

1114 1115
    return !status;
}
1116 1117 1118 1119 1120 1121 1122

/*********************************************************************
 *      FileTimeToSystemTime                            (KERNEL32.@)
 */
BOOL WINAPI FileTimeToSystemTime( const FILETIME *ft, LPSYSTEMTIME syst )
{
    TIME_FIELDS tf;
1123
    LARGE_INTEGER t;
1124

1125 1126
    t.u.LowPart = ft->dwLowDateTime;
    t.u.HighPart = ft->dwHighDateTime;
1127
    RtlTimeToTimeFields(&t, &tf);
1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145

    syst->wYear = tf.Year;
    syst->wMonth = tf.Month;
    syst->wDay = tf.Day;
    syst->wHour = tf.Hour;
    syst->wMinute = tf.Minute;
    syst->wSecond = tf.Second;
    syst->wMilliseconds = tf.Milliseconds;
    syst->wDayOfWeek = tf.Weekday;
    return TRUE;
}

/*********************************************************************
 *      SystemTimeToFileTime                            (KERNEL32.@)
 */
BOOL WINAPI SystemTimeToFileTime( const SYSTEMTIME *syst, LPFILETIME ft )
{
    TIME_FIELDS tf;
1146
    LARGE_INTEGER t;
1147 1148 1149 1150 1151 1152 1153 1154 1155

    tf.Year = syst->wYear;
    tf.Month = syst->wMonth;
    tf.Day = syst->wDay;
    tf.Hour = syst->wHour;
    tf.Minute = syst->wMinute;
    tf.Second = syst->wSecond;
    tf.Milliseconds = syst->wMilliseconds;

1156 1157 1158 1159
    if( !RtlTimeFieldsToTime(&tf, &t)) {
        SetLastError( ERROR_INVALID_PARAMETER);
        return FALSE;
    }
1160 1161
    ft->dwLowDateTime = t.u.LowPart;
    ft->dwHighDateTime = t.u.HighPart;
1162 1163 1164 1165 1166
    return TRUE;
}

/*********************************************************************
 *      CompareFileTime                                 (KERNEL32.@)
Jon Griffiths's avatar
Jon Griffiths committed
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176
 *
 * Compare two FILETIME's to each other.
 *
 * PARAMS
 *  x [I] First time
 *  y [I] time to compare to x
 *
 * RETURNS
 *  -1, 0, or 1 indicating that x is less than, equal to, or greater
 *  than y respectively.
1177
 */
1178
INT WINAPI CompareFileTime( const FILETIME *x, const FILETIME *y )
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
{
    if (!x || !y) return -1;

    if (x->dwHighDateTime > y->dwHighDateTime)
        return 1;
    if (x->dwHighDateTime < y->dwHighDateTime)
        return -1;
    if (x->dwLowDateTime > y->dwLowDateTime)
        return 1;
    if (x->dwLowDateTime < y->dwLowDateTime)
        return -1;
    return 0;
}

/*********************************************************************
 *      GetLocalTime                                    (KERNEL32.@)
Jon Griffiths's avatar
Jon Griffiths committed
1195 1196 1197
 *
 * Get the current local time.
 *
1198 1199 1200
 * PARAMS
 *  systime [O] Destination for current time.
 *
Jon Griffiths's avatar
Jon Griffiths committed
1201 1202
 * RETURNS
 *  Nothing.
1203
 */
1204
VOID WINAPI GetLocalTime(LPSYSTEMTIME systime)
1205 1206
{
    FILETIME lft;
1207
    LARGE_INTEGER ft, ft2;
1208 1209

    NtQuerySystemTime(&ft);
1210
    RtlSystemTimeToLocalTime(&ft, &ft2);
1211 1212
    lft.dwLowDateTime = ft2.u.LowPart;
    lft.dwHighDateTime = ft2.u.HighPart;
1213 1214 1215 1216 1217
    FileTimeToSystemTime(&lft, systime);
}

/*********************************************************************
 *      GetSystemTime                                   (KERNEL32.@)
Jon Griffiths's avatar
Jon Griffiths committed
1218 1219 1220
 *
 * Get the current system time.
 *
1221 1222 1223
 * PARAMS
 *  systime [O] Destination for current time.
 *
Jon Griffiths's avatar
Jon Griffiths committed
1224 1225
 * RETURNS
 *  Nothing.
1226
 */
1227
VOID WINAPI GetSystemTime(LPSYSTEMTIME systime)
1228 1229
{
    FILETIME ft;
1230
    LARGE_INTEGER t;
1231

1232
    NtQuerySystemTime(&t);
1233 1234
    ft.dwLowDateTime = t.u.LowPart;
    ft.dwHighDateTime = t.u.HighPart;
1235 1236
    FileTimeToSystemTime(&ft, systime);
}
1237 1238 1239 1240

/*********************************************************************
 *      GetDaylightFlag                                   (KERNEL32.@)
 *
1241
 *  Specifies if daylight savings time is in operation.
1242 1243 1244
 *
 * NOTES
 *  This function is called from the Win98's control applet timedate.cpl.
1245
 *
1246
 * RETURNS
1247
 *  TRUE if daylight savings time is in operation.
1248
 *  FALSE otherwise.
1249 1250 1251
 */
BOOL WINAPI GetDaylightFlag(void)
{
1252 1253
    TIME_ZONE_INFORMATION tzinfo;
    return GetTimeZoneInformation( &tzinfo) == TIME_ZONE_ID_DAYLIGHT;
1254
}
1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272

/***********************************************************************
 *           DosDateTimeToFileTime   (KERNEL32.@)
 */
BOOL WINAPI DosDateTimeToFileTime( WORD fatdate, WORD fattime, LPFILETIME ft)
{
    struct tm newtm;
#ifndef HAVE_TIMEGM
    struct tm *gtm;
    time_t time1, time2;
#endif

    newtm.tm_sec  = (fattime & 0x1f) * 2;
    newtm.tm_min  = (fattime >> 5) & 0x3f;
    newtm.tm_hour = (fattime >> 11);
    newtm.tm_mday = (fatdate & 0x1f);
    newtm.tm_mon  = ((fatdate >> 5) & 0x0f) - 1;
    newtm.tm_year = (fatdate >> 9) + 80;
1273
    newtm.tm_isdst = -1;
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
#ifdef HAVE_TIMEGM
    RtlSecondsSince1970ToTime( timegm(&newtm), (LARGE_INTEGER *)ft );
#else
    time1 = mktime(&newtm);
    gtm = gmtime(&time1);
    time2 = mktime(gtm);
    RtlSecondsSince1970ToTime( 2*time1-time2, (LARGE_INTEGER *)ft );
#endif
    return TRUE;
}


/***********************************************************************
 *           FileTimeToDosDateTime   (KERNEL32.@)
 */
BOOL WINAPI FileTimeToDosDateTime( const FILETIME *ft, LPWORD fatdate,
                                     LPWORD fattime )
{
    LARGE_INTEGER       li;
    ULONG               t;
    time_t              unixtime;
    struct tm*          tm;

1297 1298 1299 1300 1301
    if (!fatdate || !fattime)
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }
1302 1303
    li.u.LowPart = ft->dwLowDateTime;
    li.u.HighPart = ft->dwHighDateTime;
1304 1305 1306 1307 1308
    if (!RtlTimeToSecondsSince1970( &li, &t ))
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }
1309 1310
    unixtime = t;
    tm = gmtime( &unixtime );
1311 1312
    *fattime = (tm->tm_hour << 11) + (tm->tm_min << 5) + (tm->tm_sec / 2);
    *fatdate = ((tm->tm_year - 80) << 9) + ((tm->tm_mon + 1) << 5) + tm->tm_mday;
1313 1314
    return TRUE;
}
1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330

/*********************************************************************
 *      GetSystemTimes                                  (KERNEL32.@)
 *
 * Retrieves system timing information
 *
 * PARAMS
 *  lpIdleTime [O] Destination for idle time.
 *  lpKernelTime [O] Destination for kernel time.
 *  lpUserTime [O] Destination for user time.
 *
 * RETURNS
 *  TRUE if success, FALSE otherwise.
 */
BOOL WINAPI GetSystemTimes(LPFILETIME lpIdleTime, LPFILETIME lpKernelTime, LPFILETIME lpUserTime)
{
1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345
    LARGE_INTEGER idle_time, kernel_time, user_time;
    SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION *sppi;
    SYSTEM_BASIC_INFORMATION sbi;
    NTSTATUS status;
    ULONG ret_size;
    int i;

    TRACE("(%p,%p,%p)\n", lpIdleTime, lpKernelTime, lpUserTime);

    status = NtQuerySystemInformation( SystemBasicInformation, &sbi, sizeof(sbi), &ret_size );
    if (status != STATUS_SUCCESS)
    {
        SetLastError( RtlNtStatusToDosError(status) );
        return FALSE;
    }
1346

1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391
    sppi = HeapAlloc( GetProcessHeap(), 0,
                      sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION) * sbi.NumberOfProcessors);
    if (!sppi)
    {
        SetLastError( ERROR_OUTOFMEMORY );
        return FALSE;
    }

    status = NtQuerySystemInformation( SystemProcessorPerformanceInformation, sppi, sizeof(*sppi) * sbi.NumberOfProcessors,
                                       &ret_size );
    if (status != STATUS_SUCCESS)
    {
        HeapFree( GetProcessHeap(), 0, sppi );
        SetLastError( RtlNtStatusToDosError(status) );
        return FALSE;
    }

    idle_time.QuadPart = 0;
    kernel_time.QuadPart = 0;
    user_time.QuadPart = 0;
    for (i = 0; i < sbi.NumberOfProcessors; i++)
    {
        idle_time.QuadPart += sppi[i].IdleTime.QuadPart;
        kernel_time.QuadPart += sppi[i].KernelTime.QuadPart;
        user_time.QuadPart += sppi[i].UserTime.QuadPart;
    }

    if (lpIdleTime)
    {
        lpIdleTime->dwLowDateTime = idle_time.u.LowPart;
        lpIdleTime->dwHighDateTime = idle_time.u.HighPart;
    }
    if (lpKernelTime)
    {
        lpKernelTime->dwLowDateTime = kernel_time.u.LowPart;
        lpKernelTime->dwHighDateTime = kernel_time.u.HighPart;
    }
    if (lpUserTime)
    {
        lpUserTime->dwLowDateTime = user_time.u.LowPart;
        lpUserTime->dwHighDateTime = user_time.u.HighPart;
    }

    HeapFree( GetProcessHeap(), 0, sppi );
    return TRUE;
1392
}
1393 1394 1395 1396

/***********************************************************************
 *           GetDynamicTimeZoneInformation   (KERNEL32.@)
 */
1397
DWORD WINAPI GetDynamicTimeZoneInformation(DYNAMIC_TIME_ZONE_INFORMATION *tzinfo)
1398
{
1399 1400 1401 1402 1403 1404 1405 1406 1407
    NTSTATUS status;

    status = RtlQueryDynamicTimeZoneInformation( (RTL_DYNAMIC_TIME_ZONE_INFORMATION*)tzinfo );
    if ( status != STATUS_SUCCESS )
    {
        SetLastError( RtlNtStatusToDosError(status) );
        return TIME_ZONE_ID_INVALID;
    }
    return TIME_ZoneID( (TIME_ZONE_INFORMATION*)tzinfo );
1408
}
1409

1410 1411 1412 1413 1414 1415 1416
/***********************************************************************
 *           QueryThreadCycleTime   (KERNEL32.@)
 */
BOOL WINAPI QueryThreadCycleTime(HANDLE thread, PULONG64 cycle)
{
    static int once;
    if (!once++)
1417
        FIXME("(%p,%p): stub!\n", thread, cycle);
1418 1419 1420 1421
    SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
    return FALSE;
}

1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
/***********************************************************************
 *           QueryUnbiasedInterruptTime   (KERNEL32.@)
 */
BOOL WINAPI QueryUnbiasedInterruptTime(ULONGLONG *time)
{
    TRACE("(%p)\n", time);
    if (!time) return FALSE;
    RtlQueryUnbiasedInterruptTime(time);
    return TRUE;
}