sync.c 75.8 KB
Newer Older
1 2 3 4
/*
 * Kernel synchronization objects
 *
 * Copyright 1998 Alexandre Julliard
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
#include "config.h"
22
#include "wine/port.h"
23

24
#include <string.h>
25 26 27
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
28
#include <errno.h>
29
#include <stdarg.h>
30
#include <stdio.h>
31

32
#include "ntstatus.h"
33
#define WIN32_NO_STATUS
34
#define NONAMELESSUNION
35
#include "windef.h"
36
#include "winbase.h"
37 38
#include "winerror.h"
#include "winnls.h"
39
#include "winternl.h"
40
#include "winioctl.h"
41
#include "ddk/wdm.h"
42 43

#include "wine/unicode.h"
44
#include "kernel_private.h"
45

46
#include "wine/debug.h"
47

48
WINE_DEFAULT_DEBUG_CHANNEL(sync);
49

50
/* check if current version is NT or Win95 */
51
static inline BOOL is_version_nt(void)
52 53 54
{
    return !(GetVersion() & 0x80000000);
}
55

56 57 58 59
/* returns directory handle to \\BaseNamedObjects */
HANDLE get_BaseNamedObjects_handle(void)
{
    static HANDLE handle = NULL;
60 61 62
    static const WCHAR basenameW[] = {'\\','S','e','s','s','i','o','n','s','\\','%','u',
                                      '\\','B','a','s','e','N','a','m','e','d','O','b','j','e','c','t','s',0};
    WCHAR buffer[64];
63 64 65 66 67 68 69
    UNICODE_STRING str;
    OBJECT_ATTRIBUTES attr;

    if (!handle)
    {
        HANDLE dir;

70 71
        sprintfW( buffer, basenameW, NtCurrentTeb()->Peb->SessionId );
        RtlInitUnicodeString( &str, buffer );
72 73 74
        InitializeObjectAttributes(&attr, &str, 0, 0, NULL);
        NtOpenDirectoryObject(&dir, DIRECTORY_CREATE_OBJECT|DIRECTORY_TRAVERSE,
                              &attr);
75
        if (InterlockedCompareExchangePointer( &handle, dir, 0 ) != 0)
76 77 78 79 80 81 82
        {
            /* someone beat us here... */
            CloseHandle( dir );
        }
    }
    return handle;
}
83

84 85 86 87 88 89 90 91
/* helper for kernel32->ntdll timeout format conversion */
static inline PLARGE_INTEGER get_nt_timeout( PLARGE_INTEGER pTime, DWORD timeout )
{
    if (timeout == INFINITE) return NULL;
    pTime->QuadPart = (ULONGLONG)timeout * -10000;
    return pTime;
}

92 93 94
/***********************************************************************
 *              Sleep  (KERNEL32.@)
 */
95
VOID WINAPI DECLSPEC_HOTPATCH Sleep( DWORD timeout )
96 97 98 99 100 101 102 103 104 105
{
    SleepEx( timeout, FALSE );
}

/******************************************************************************
 *              SleepEx   (KERNEL32.@)
 */
DWORD WINAPI SleepEx( DWORD timeout, BOOL alertable )
{
    NTSTATUS status;
106
    LARGE_INTEGER time;
107

108 109 110
    status = NtDelayExecution( alertable, get_nt_timeout( &time, timeout ) );
    if (status == STATUS_USER_APC) return WAIT_IO_COMPLETION;
    return 0;
111 112 113
}


114 115 116 117 118 119 120 121 122
/***********************************************************************
 *		SwitchToThread (KERNEL32.@)
 */
BOOL WINAPI SwitchToThread(void)
{
    return (NtYieldExecution() != STATUS_NO_YIELD_PERFORMED);
}


123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
/***********************************************************************
 *           WaitForSingleObject   (KERNEL32.@)
 */
DWORD WINAPI WaitForSingleObject( HANDLE handle, DWORD timeout )
{
    return WaitForMultipleObjectsEx( 1, &handle, FALSE, timeout, FALSE );
}


/***********************************************************************
 *           WaitForSingleObjectEx   (KERNEL32.@)
 */
DWORD WINAPI WaitForSingleObjectEx( HANDLE handle, DWORD timeout,
                                    BOOL alertable )
{
    return WaitForMultipleObjectsEx( 1, &handle, FALSE, timeout, alertable );
}


/***********************************************************************
 *           WaitForMultipleObjects   (KERNEL32.@)
 */
DWORD WINAPI WaitForMultipleObjects( DWORD count, const HANDLE *handles,
                                     BOOL wait_all, DWORD timeout )
{
    return WaitForMultipleObjectsEx( count, handles, wait_all, timeout, FALSE );
}

151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
static HANDLE normalize_handle_if_console(HANDLE handle)
{
    if ((handle == (HANDLE)STD_INPUT_HANDLE) ||
        (handle == (HANDLE)STD_OUTPUT_HANDLE) ||
        (handle == (HANDLE)STD_ERROR_HANDLE))
        handle = GetStdHandle( HandleToULong(handle) );

    /* yes, even screen buffer console handles are waitable, and are
     * handled as a handle to the console itself !!
     */
    if (is_console_handle(handle))
    {
        if (VerifyConsoleIoHandle(handle))
            handle = GetConsoleInputWaitHandle();
    }
    return handle;
}
168 169 170 171 172 173 174 175 176 177

/***********************************************************************
 *           WaitForMultipleObjectsEx   (KERNEL32.@)
 */
DWORD WINAPI WaitForMultipleObjectsEx( DWORD count, const HANDLE *handles,
                                       BOOL wait_all, DWORD timeout,
                                       BOOL alertable )
{
    NTSTATUS status;
    HANDLE hloc[MAXIMUM_WAIT_OBJECTS];
178
    LARGE_INTEGER time;
179
    unsigned int i;
180

181
    if (count > MAXIMUM_WAIT_OBJECTS)
182 183 184 185 186
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return WAIT_FAILED;
    }
    for (i = 0; i < count; i++)
187
        hloc[i] = normalize_handle_if_console(handles[i]);
188

189
    status = NtWaitForMultipleObjects( count, hloc, !wait_all, alertable,
190
                                       get_nt_timeout( &time, timeout ) );
191 192 193 194 195 196 197 198 199 200

    if (HIWORD(status))  /* is it an error code? */
    {
        SetLastError( RtlNtStatusToDosError(status) );
        status = WAIT_FAILED;
    }
    return status;
}


201 202 203 204 205 206 207
/***********************************************************************
 *           RegisterWaitForSingleObject   (KERNEL32.@)
 */
BOOL WINAPI RegisterWaitForSingleObject(PHANDLE phNewWaitObject, HANDLE hObject,
                WAITORTIMERCALLBACK Callback, PVOID Context,
                ULONG dwMilliseconds, ULONG dwFlags)
{
208 209 210
    NTSTATUS status;

    TRACE("%p %p %p %p %d %d\n",
211
          phNewWaitObject,hObject,Callback,Context,dwMilliseconds,dwFlags);
212

213
    hObject = normalize_handle_if_console(hObject);
214 215 216 217 218 219 220
    status = RtlRegisterWait( phNewWaitObject, hObject, Callback, Context, dwMilliseconds, dwFlags );
    if (status != STATUS_SUCCESS)
    {
        SetLastError( RtlNtStatusToDosError(status) );
        return FALSE;
    }
    return TRUE;
221 222 223 224 225
}

/***********************************************************************
 *           RegisterWaitForSingleObjectEx   (KERNEL32.@)
 */
226
HANDLE WINAPI RegisterWaitForSingleObjectEx( HANDLE hObject, 
227 228 229
                WAITORTIMERCALLBACK Callback, PVOID Context,
                ULONG dwMilliseconds, ULONG dwFlags ) 
{
230 231 232 233
    NTSTATUS status;
    HANDLE hNewWaitObject;

    TRACE("%p %p %p %d %d\n",
234
          hObject,Callback,Context,dwMilliseconds,dwFlags);
235

236
    hObject = normalize_handle_if_console(hObject);
237 238 239 240 241 242 243
    status = RtlRegisterWait( &hNewWaitObject, hObject, Callback, Context, dwMilliseconds, dwFlags );
    if (status != STATUS_SUCCESS)
    {
        SetLastError( RtlNtStatusToDosError(status) );
        return NULL;
    }
    return hNewWaitObject;
244 245 246 247 248 249 250
}

/***********************************************************************
 *           UnregisterWait   (KERNEL32.@)
 */
BOOL WINAPI UnregisterWait( HANDLE WaitHandle ) 
{
251 252 253 254 255 256 257 258 259 260 261
    NTSTATUS status;

    TRACE("%p\n",WaitHandle);

    status = RtlDeregisterWait( WaitHandle );
    if (status != STATUS_SUCCESS)
    {
        SetLastError( RtlNtStatusToDosError(status) );
        return FALSE;
    }
    return TRUE;
262 263 264 265 266 267 268
}

/***********************************************************************
 *           UnregisterWaitEx   (KERNEL32.@)
 */
BOOL WINAPI UnregisterWaitEx( HANDLE WaitHandle, HANDLE CompletionEvent ) 
{
269 270 271 272 273 274 275
    NTSTATUS status;

    TRACE("%p %p\n",WaitHandle, CompletionEvent);

    status = RtlDeregisterWaitEx( WaitHandle, CompletionEvent );
    if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
    return !status;
276 277
}

278 279 280
/***********************************************************************
 *           SignalObjectAndWait  (KERNEL32.@)
 *
281 282
 * Makes it possible to atomically signal any of the synchronization
 * objects (semaphore, mutex, event) and wait on another.
283
 */
284 285
DWORD WINAPI SignalObjectAndWait( HANDLE hObjectToSignal, HANDLE hObjectToWaitOn,
                                  DWORD dwMilliseconds, BOOL bAlertable )
286
{
287
    NTSTATUS status;
288
    LARGE_INTEGER timeout;
289

290
    TRACE("%p %p %d %d\n", hObjectToSignal,
291 292
          hObjectToWaitOn, dwMilliseconds, bAlertable);

293 294
    status = NtSignalAndWaitForSingleObject( hObjectToSignal, hObjectToWaitOn, bAlertable,
                                             get_nt_timeout( &timeout, dwMilliseconds ) );
295 296 297 298 299 300 301
    if (HIWORD(status))
    {
        SetLastError( RtlNtStatusToDosError(status) );
        status = WAIT_FAILED;
    }
    return status;
}
302

303 304
/***********************************************************************
 *           InitializeCriticalSection   (KERNEL32.@)
Jon Griffiths's avatar
Jon Griffiths committed
305 306 307 308 309 310 311 312
 *
 * Initialise a critical section before use.
 *
 * PARAMS
 *  crit [O] Critical section to initialise.
 *
 * RETURNS
 *  Nothing. If the function fails an exception is raised.
313 314 315
 */
void WINAPI InitializeCriticalSection( CRITICAL_SECTION *crit )
{
316
    InitializeCriticalSectionEx( crit, 0, 0 );
317 318 319 320
}

/***********************************************************************
 *           InitializeCriticalSectionAndSpinCount   (KERNEL32.@)
Jon Griffiths's avatar
Jon Griffiths committed
321 322 323 324 325 326 327 328 329 330 331 332 333
 *
 * Initialise a critical section with a spin count.
 *
 * PARAMS
 *  crit      [O] Critical section to initialise.
 *  spincount [I] Number of times to spin upon contention.
 *
 * RETURNS
 *  Success: TRUE.
 *  Failure: Nothing. If the function fails an exception is raised.
 *
 * NOTES
 *  spincount is ignored on uni-processor systems.
334 335 336
 */
BOOL WINAPI InitializeCriticalSectionAndSpinCount( CRITICAL_SECTION *crit, DWORD spincount )
{
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
    return InitializeCriticalSectionEx( crit, spincount, 0 );
}

/***********************************************************************
 *           InitializeCriticalSectionEx   (KERNEL32.@)
 *
 * Initialise a critical section with a spin count and flags.
 *
 * PARAMS
 *  crit      [O] Critical section to initialise.
 *  spincount [I] Number of times to spin upon contention.
 *  flags     [I] CRITICAL_SECTION_ flags from winbase.h.
 *
 * RETURNS
 *  Success: TRUE.
 *  Failure: Nothing. If the function fails an exception is raised.
 *
 * NOTES
 *  spincount is ignored on uni-processor systems.
 */
BOOL WINAPI InitializeCriticalSectionEx( CRITICAL_SECTION *crit, DWORD spincount, DWORD flags )
{
    NTSTATUS ret = RtlInitializeCriticalSectionEx( crit, spincount, flags );
360 361 362 363 364 365 366 367 368 369 370 371 372
    if (ret) RtlRaiseStatus( ret );
    return !ret;
}

/***********************************************************************
 *           MakeCriticalSectionGlobal   (KERNEL32.@)
 */
void WINAPI MakeCriticalSectionGlobal( CRITICAL_SECTION *crit )
{
    /* let's assume that only one thread at a time will try to do this */
    HANDLE sem = crit->LockSemaphore;
    if (!sem) NtCreateSemaphore( &sem, SEMAPHORE_ALL_ACCESS, NULL, 0, 1 );
    crit->LockSemaphore = ConvertToGlobalHandle( sem );
373 374
    RtlFreeHeap( GetProcessHeap(), 0, crit->DebugInfo );
    crit->DebugInfo = NULL;
375 376 377 378 379
}


/***********************************************************************
 *           ReinitializeCriticalSection   (KERNEL32.@)
Jon Griffiths's avatar
Jon Griffiths committed
380 381 382 383 384 385 386 387
 *
 * Initialise an already used critical section.
 *
 * PARAMS
 *  crit [O] Critical section to initialise.
 *
 * RETURNS
 *  Nothing.
388 389 390 391 392 393 394 395 396 397
 */
void WINAPI ReinitializeCriticalSection( CRITICAL_SECTION *crit )
{
    if ( !crit->LockSemaphore )
        RtlInitializeCriticalSection( crit );
}


/***********************************************************************
 *           UninitializeCriticalSection   (KERNEL32.@)
Jon Griffiths's avatar
Jon Griffiths committed
398 399 400 401 402 403 404 405
 *
 * UnInitialise a critical section after use.
 *
 * PARAMS
 *  crit [O] Critical section to uninitialise (destroy).
 *
 * RETURNS
 *  Nothing.
406 407 408 409 410 411 412
 */
void WINAPI UninitializeCriticalSection( CRITICAL_SECTION *crit )
{
    RtlDeleteCriticalSection( crit );
}


413
/***********************************************************************
414
 *           CreateEventA    (KERNEL32.@)
415
 */
416 417
HANDLE WINAPI DECLSPEC_HOTPATCH CreateEventA( SECURITY_ATTRIBUTES *sa, BOOL manual_reset,
                                              BOOL initial_state, LPCSTR name )
418 419 420 421 422 423 424 425 426 427 428 429
{
    DWORD flags = 0;

    if (manual_reset) flags |= CREATE_EVENT_MANUAL_RESET;
    if (initial_state) flags |= CREATE_EVENT_INITIAL_SET;
    return CreateEventExA( sa, name, flags, EVENT_ALL_ACCESS );
}


/***********************************************************************
 *           CreateEventW    (KERNEL32.@)
 */
430 431
HANDLE WINAPI DECLSPEC_HOTPATCH CreateEventW( SECURITY_ATTRIBUTES *sa, BOOL manual_reset,
                                              BOOL initial_state, LPCWSTR name )
432 433 434 435 436 437 438 439 440 441 442 443
{
    DWORD flags = 0;

    if (manual_reset) flags |= CREATE_EVENT_MANUAL_RESET;
    if (initial_state) flags |= CREATE_EVENT_INITIAL_SET;
    return CreateEventExW( sa, name, flags, EVENT_ALL_ACCESS );
}


/***********************************************************************
 *           CreateEventExA    (KERNEL32.@)
 */
444
HANDLE WINAPI DECLSPEC_HOTPATCH CreateEventExA( SECURITY_ATTRIBUTES *sa, LPCSTR name, DWORD flags, DWORD access )
445
{
446 447
    WCHAR buffer[MAX_PATH];

448
    if (!name) return CreateEventExW( sa, NULL, flags, access );
449 450

    if (!MultiByteToWideChar( CP_ACP, 0, name, -1, buffer, MAX_PATH ))
451 452 453 454
    {
        SetLastError( ERROR_FILENAME_EXCED_RANGE );
        return 0;
    }
455
    return CreateEventExW( sa, buffer, flags, access );
456 457 458 459
}


/***********************************************************************
460
 *           CreateEventExW    (KERNEL32.@)
461
 */
462
HANDLE WINAPI DECLSPEC_HOTPATCH CreateEventExW( SECURITY_ATTRIBUTES *sa, LPCWSTR name, DWORD flags, DWORD access )
463
{
464
    HANDLE ret = 0;
465 466 467 468
    UNICODE_STRING nameW;
    OBJECT_ATTRIBUTES attr;
    NTSTATUS status;

469 470 471 472 473 474 475 476 477
    /* one buggy program needs this
     * ("Van Dale Groot woordenboek der Nederlandse taal")
     */
    if (sa && IsBadReadPtr(sa,sizeof(SECURITY_ATTRIBUTES)))
    {
        ERR("Bad security attributes pointer %p\n",sa);
        SetLastError( ERROR_INVALID_PARAMETER);
        return 0;
    }
478 479 480 481

    attr.Length                   = sizeof(attr);
    attr.RootDirectory            = 0;
    attr.ObjectName               = NULL;
482
    attr.Attributes               = OBJ_OPENIF | ((sa && sa->bInheritHandle) ? OBJ_INHERIT : 0);
483 484 485
    attr.SecurityDescriptor       = sa ? sa->lpSecurityDescriptor : NULL;
    attr.SecurityQualityOfService = NULL;
    if (name)
486
    {
487 488
        RtlInitUnicodeString( &nameW, name );
        attr.ObjectName = &nameW;
489
        attr.RootDirectory = get_BaseNamedObjects_handle();
490
    }
491

492 493
    status = NtCreateEvent( &ret, access, &attr,
                            (flags & CREATE_EVENT_MANUAL_RESET) ? NotificationEvent : SynchronizationEvent,
494
                            (flags & CREATE_EVENT_INITIAL_SET) != 0 );
495 496 497 498
    if (status == STATUS_OBJECT_NAME_EXISTS)
        SetLastError( ERROR_ALREADY_EXISTS );
    else
        SetLastError( RtlNtStatusToDosError(status) );
499 500 501 502 503
    return ret;
}


/***********************************************************************
504
 *           OpenEventA    (KERNEL32.@)
505
 */
506
HANDLE WINAPI DECLSPEC_HOTPATCH OpenEventA( DWORD access, BOOL inherit, LPCSTR name )
507
{
508 509 510 511 512
    WCHAR buffer[MAX_PATH];

    if (!name) return OpenEventW( access, inherit, NULL );

    if (!MultiByteToWideChar( CP_ACP, 0, name, -1, buffer, MAX_PATH ))
513 514 515 516
    {
        SetLastError( ERROR_FILENAME_EXCED_RANGE );
        return 0;
    }
517
    return OpenEventW( access, inherit, buffer );
518 519 520 521
}


/***********************************************************************
522
 *           OpenEventW    (KERNEL32.@)
523
 */
524
HANDLE WINAPI DECLSPEC_HOTPATCH OpenEventW( DWORD access, BOOL inherit, LPCWSTR name )
525 526
{
    HANDLE ret;
527 528 529 530 531 532 533 534 535
    UNICODE_STRING nameW;
    OBJECT_ATTRIBUTES attr;
    NTSTATUS status;

    if (!is_version_nt()) access = EVENT_ALL_ACCESS;

    attr.Length                   = sizeof(attr);
    attr.RootDirectory            = 0;
    attr.ObjectName               = NULL;
536
    attr.Attributes               = inherit ? OBJ_INHERIT : 0;
537 538 539
    attr.SecurityDescriptor       = NULL;
    attr.SecurityQualityOfService = NULL;
    if (name)
540
    {
541 542
        RtlInitUnicodeString( &nameW, name );
        attr.ObjectName = &nameW;
543
        attr.RootDirectory = get_BaseNamedObjects_handle();
544
    }
545

546 547
    status = NtOpenEvent( &ret, access, &attr );
    if (status != STATUS_SUCCESS)
548
    {
549 550
        SetLastError( RtlNtStatusToDosError(status) );
        return 0;
551 552 553 554 555
    }
    return ret;
}

/***********************************************************************
556
 *           PulseEvent    (KERNEL32.@)
557
 */
558
BOOL WINAPI DECLSPEC_HOTPATCH PulseEvent( HANDLE handle )
559
{
560 561 562 563 564
    NTSTATUS status;

    if ((status = NtPulseEvent( handle, NULL )))
        SetLastError( RtlNtStatusToDosError(status) );
    return !status;
565 566 567 568
}


/***********************************************************************
569
 *           SetEvent    (KERNEL32.@)
570
 */
571
BOOL WINAPI DECLSPEC_HOTPATCH SetEvent( HANDLE handle )
572
{
573 574 575 576 577
    NTSTATUS status;

    if ((status = NtSetEvent( handle, NULL )))
        SetLastError( RtlNtStatusToDosError(status) );
    return !status;
578 579 580 581
}


/***********************************************************************
582
 *           ResetEvent    (KERNEL32.@)
583
 */
584
BOOL WINAPI DECLSPEC_HOTPATCH ResetEvent( HANDLE handle )
585
{
586 587 588 589 590
    NTSTATUS status;

    if ((status = NtResetEvent( handle, NULL )))
        SetLastError( RtlNtStatusToDosError(status) );
    return !status;
591 592 593 594
}


/***********************************************************************
595
 *           CreateMutexA   (KERNEL32.@)
596
 */
597
HANDLE WINAPI DECLSPEC_HOTPATCH CreateMutexA( SECURITY_ATTRIBUTES *sa, BOOL owner, LPCSTR name )
598 599 600 601 602 603 604 605
{
    return CreateMutexExA( sa, name, owner ? CREATE_MUTEX_INITIAL_OWNER : 0, MUTEX_ALL_ACCESS );
}


/***********************************************************************
 *           CreateMutexW   (KERNEL32.@)
 */
606
HANDLE WINAPI DECLSPEC_HOTPATCH CreateMutexW( SECURITY_ATTRIBUTES *sa, BOOL owner, LPCWSTR name )
607 608 609 610 611 612 613 614
{
    return CreateMutexExW( sa, name, owner ? CREATE_MUTEX_INITIAL_OWNER : 0, MUTEX_ALL_ACCESS );
}


/***********************************************************************
 *           CreateMutexExA   (KERNEL32.@)
 */
615
HANDLE WINAPI DECLSPEC_HOTPATCH CreateMutexExA( SECURITY_ATTRIBUTES *sa, LPCSTR name, DWORD flags, DWORD access )
616
{
617 618
    ANSI_STRING nameA;
    NTSTATUS status;
619

620
    if (!name) return CreateMutexExW( sa, NULL, flags, access );
621

622 623 624
    RtlInitAnsiString( &nameA, name );
    status = RtlAnsiStringToUnicodeString( &NtCurrentTeb()->StaticUnicodeString, &nameA, FALSE );
    if (status != STATUS_SUCCESS)
625 626 627 628
    {
        SetLastError( ERROR_FILENAME_EXCED_RANGE );
        return 0;
    }
629
    return CreateMutexExW( sa, NtCurrentTeb()->StaticUnicodeString.Buffer, flags, access );
630 631 632 633
}


/***********************************************************************
634
 *           CreateMutexExW   (KERNEL32.@)
635
 */
636
HANDLE WINAPI DECLSPEC_HOTPATCH CreateMutexExW( SECURITY_ATTRIBUTES *sa, LPCWSTR name, DWORD flags, DWORD access )
637
{
638
    HANDLE ret = 0;
639 640 641 642 643 644 645
    UNICODE_STRING nameW;
    OBJECT_ATTRIBUTES attr;
    NTSTATUS status;

    attr.Length                   = sizeof(attr);
    attr.RootDirectory            = 0;
    attr.ObjectName               = NULL;
646
    attr.Attributes               = OBJ_OPENIF | ((sa && sa->bInheritHandle) ? OBJ_INHERIT : 0);
647 648 649
    attr.SecurityDescriptor       = sa ? sa->lpSecurityDescriptor : NULL;
    attr.SecurityQualityOfService = NULL;
    if (name)
650
    {
651 652
        RtlInitUnicodeString( &nameW, name );
        attr.ObjectName = &nameW;
653
        attr.RootDirectory = get_BaseNamedObjects_handle();
654
    }
655

656
    status = NtCreateMutant( &ret, access, &attr, (flags & CREATE_MUTEX_INITIAL_OWNER) != 0 );
657 658 659 660
    if (status == STATUS_OBJECT_NAME_EXISTS)
        SetLastError( ERROR_ALREADY_EXISTS );
    else
        SetLastError( RtlNtStatusToDosError(status) );
661 662 663 664 665
    return ret;
}


/***********************************************************************
666
 *           OpenMutexA   (KERNEL32.@)
667
 */
668
HANDLE WINAPI DECLSPEC_HOTPATCH OpenMutexA( DWORD access, BOOL inherit, LPCSTR name )
669
{
670 671 672 673 674
    WCHAR buffer[MAX_PATH];

    if (!name) return OpenMutexW( access, inherit, NULL );

    if (!MultiByteToWideChar( CP_ACP, 0, name, -1, buffer, MAX_PATH ))
675 676 677 678
    {
        SetLastError( ERROR_FILENAME_EXCED_RANGE );
        return 0;
    }
679
    return OpenMutexW( access, inherit, buffer );
680 681 682 683
}


/***********************************************************************
684
 *           OpenMutexW   (KERNEL32.@)
685
 */
686
HANDLE WINAPI DECLSPEC_HOTPATCH OpenMutexW( DWORD access, BOOL inherit, LPCWSTR name )
687 688
{
    HANDLE ret;
689 690 691 692 693 694 695 696 697
    UNICODE_STRING nameW;
    OBJECT_ATTRIBUTES attr;
    NTSTATUS status;

    if (!is_version_nt()) access = MUTEX_ALL_ACCESS;

    attr.Length                   = sizeof(attr);
    attr.RootDirectory            = 0;
    attr.ObjectName               = NULL;
698
    attr.Attributes               = inherit ? OBJ_INHERIT : 0;
699 700 701
    attr.SecurityDescriptor       = NULL;
    attr.SecurityQualityOfService = NULL;
    if (name)
702
    {
703 704
        RtlInitUnicodeString( &nameW, name );
        attr.ObjectName = &nameW;
705
        attr.RootDirectory = get_BaseNamedObjects_handle();
706
    }
707

708 709
    status = NtOpenMutant( &ret, access, &attr );
    if (status != STATUS_SUCCESS)
710
    {
711 712
        SetLastError( RtlNtStatusToDosError(status) );
        return 0;
713 714 715 716 717 718
    }
    return ret;
}


/***********************************************************************
719
 *           ReleaseMutex   (KERNEL32.@)
720
 */
721
BOOL WINAPI DECLSPEC_HOTPATCH ReleaseMutex( HANDLE handle )
722
{
723 724 725 726
    NTSTATUS    status;

    status = NtReleaseMutant(handle, NULL);
    if (status != STATUS_SUCCESS)
727
    {
728 729
        SetLastError( RtlNtStatusToDosError(status) );
        return FALSE;
730
    }
731
    return TRUE;
732 733 734 735 736 737 738 739 740
}


/*
 * Semaphores
 */


/***********************************************************************
741
 *           CreateSemaphoreA   (KERNEL32.@)
742
 */
743
HANDLE WINAPI DECLSPEC_HOTPATCH CreateSemaphoreA( SECURITY_ATTRIBUTES *sa, LONG initial, LONG max, LPCSTR name )
744 745 746 747 748 749 750 751
{
    return CreateSemaphoreExA( sa, initial, max, name, 0, SEMAPHORE_ALL_ACCESS );
}


/***********************************************************************
 *           CreateSemaphoreW   (KERNEL32.@)
 */
752
HANDLE WINAPI DECLSPEC_HOTPATCH CreateSemaphoreW( SECURITY_ATTRIBUTES *sa, LONG initial, LONG max, LPCWSTR name )
753 754 755 756 757 758 759 760
{
    return CreateSemaphoreExW( sa, initial, max, name, 0, SEMAPHORE_ALL_ACCESS );
}


/***********************************************************************
 *           CreateSemaphoreExA   (KERNEL32.@)
 */
761 762
HANDLE WINAPI DECLSPEC_HOTPATCH CreateSemaphoreExA( SECURITY_ATTRIBUTES *sa, LONG initial, LONG max,
                                                    LPCSTR name, DWORD flags, DWORD access )
763
{
764
    WCHAR buffer[MAX_PATH];
765

766
    if (!name) return CreateSemaphoreExW( sa, initial, max, NULL, flags, access );
767

768
    if (!MultiByteToWideChar( CP_ACP, 0, name, -1, buffer, MAX_PATH ))
769 770 771 772
    {
        SetLastError( ERROR_FILENAME_EXCED_RANGE );
        return 0;
    }
773
    return CreateSemaphoreExW( sa, initial, max, buffer, flags, access );
774 775 776 777
}


/***********************************************************************
778
 *           CreateSemaphoreExW   (KERNEL32.@)
779
 */
780 781
HANDLE WINAPI DECLSPEC_HOTPATCH CreateSemaphoreExW( SECURITY_ATTRIBUTES *sa, LONG initial, LONG max,
                                                    LPCWSTR name, DWORD flags, DWORD access )
782
{
783
    HANDLE ret = 0;
784 785 786
    UNICODE_STRING nameW;
    OBJECT_ATTRIBUTES attr;
    NTSTATUS status;
787

788 789 790
    attr.Length                   = sizeof(attr);
    attr.RootDirectory            = 0;
    attr.ObjectName               = NULL;
791
    attr.Attributes               = OBJ_OPENIF | ((sa && sa->bInheritHandle) ? OBJ_INHERIT : 0);
792 793 794
    attr.SecurityDescriptor       = sa ? sa->lpSecurityDescriptor : NULL;
    attr.SecurityQualityOfService = NULL;
    if (name)
795
    {
796 797
        RtlInitUnicodeString( &nameW, name );
        attr.ObjectName = &nameW;
798
        attr.RootDirectory = get_BaseNamedObjects_handle();
799 800
    }

801
    status = NtCreateSemaphore( &ret, access, &attr, initial, max );
802 803 804 805
    if (status == STATUS_OBJECT_NAME_EXISTS)
        SetLastError( ERROR_ALREADY_EXISTS );
    else
        SetLastError( RtlNtStatusToDosError(status) );
806 807 808 809 810
    return ret;
}


/***********************************************************************
811
 *           OpenSemaphoreA   (KERNEL32.@)
812
 */
813
HANDLE WINAPI DECLSPEC_HOTPATCH OpenSemaphoreA( DWORD access, BOOL inherit, LPCSTR name )
814
{
815 816 817 818 819
    WCHAR buffer[MAX_PATH];

    if (!name) return OpenSemaphoreW( access, inherit, NULL );

    if (!MultiByteToWideChar( CP_ACP, 0, name, -1, buffer, MAX_PATH ))
820 821 822 823
    {
        SetLastError( ERROR_FILENAME_EXCED_RANGE );
        return 0;
    }
824
    return OpenSemaphoreW( access, inherit, buffer );
825 826 827 828
}


/***********************************************************************
829
 *           OpenSemaphoreW   (KERNEL32.@)
830
 */
831
HANDLE WINAPI DECLSPEC_HOTPATCH OpenSemaphoreW( DWORD access, BOOL inherit, LPCWSTR name )
832 833
{
    HANDLE ret;
834 835 836 837 838 839 840 841 842
    UNICODE_STRING nameW;
    OBJECT_ATTRIBUTES attr;
    NTSTATUS status;

    if (!is_version_nt()) access = SEMAPHORE_ALL_ACCESS;

    attr.Length                   = sizeof(attr);
    attr.RootDirectory            = 0;
    attr.ObjectName               = NULL;
843
    attr.Attributes               = inherit ? OBJ_INHERIT : 0;
844 845 846
    attr.SecurityDescriptor       = NULL;
    attr.SecurityQualityOfService = NULL;
    if (name)
847
    {
848 849
        RtlInitUnicodeString( &nameW, name );
        attr.ObjectName = &nameW;
850
        attr.RootDirectory = get_BaseNamedObjects_handle();
851
    }
852

853 854
    status = NtOpenSemaphore( &ret, access, &attr );
    if (status != STATUS_SUCCESS)
855
    {
856 857
        SetLastError( RtlNtStatusToDosError(status) );
        return 0;
858 859 860 861 862 863
    }
    return ret;
}


/***********************************************************************
864
 *           ReleaseSemaphore   (KERNEL32.@)
865
 */
866
BOOL WINAPI DECLSPEC_HOTPATCH ReleaseSemaphore( HANDLE handle, LONG count, LONG *previous )
867
{
Mike McCormack's avatar
Mike McCormack committed
868
    NTSTATUS status = NtReleaseSemaphore( handle, count, (PULONG)previous );
869 870 871 872 873
    if (status) SetLastError( RtlNtStatusToDosError(status) );
    return !status;
}


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 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 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 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
/*
 * Jobs
 */

/******************************************************************************
 *		CreateJobObjectW (KERNEL32.@)
 */
HANDLE WINAPI CreateJobObjectW( LPSECURITY_ATTRIBUTES sa, LPCWSTR name )
{
    HANDLE ret = 0;
    UNICODE_STRING nameW;
    OBJECT_ATTRIBUTES attr;
    NTSTATUS status;

    attr.Length                   = sizeof(attr);
    attr.RootDirectory            = 0;
    attr.ObjectName               = NULL;
    attr.Attributes               = OBJ_OPENIF | ((sa && sa->bInheritHandle) ? OBJ_INHERIT : 0);
    attr.SecurityDescriptor       = sa ? sa->lpSecurityDescriptor : NULL;
    attr.SecurityQualityOfService = NULL;
    if (name)
    {
        RtlInitUnicodeString( &nameW, name );
        attr.ObjectName = &nameW;
        attr.RootDirectory = get_BaseNamedObjects_handle();
    }

    status = NtCreateJobObject( &ret, JOB_OBJECT_ALL_ACCESS, &attr );
    if (status == STATUS_OBJECT_NAME_EXISTS)
        SetLastError( ERROR_ALREADY_EXISTS );
    else
        SetLastError( RtlNtStatusToDosError(status) );
    return ret;
}

/******************************************************************************
 *		CreateJobObjectA (KERNEL32.@)
 */
HANDLE WINAPI CreateJobObjectA( LPSECURITY_ATTRIBUTES attr, LPCSTR name )
{
    WCHAR buffer[MAX_PATH];

    if (!name) return CreateJobObjectW( attr, NULL );

    if (!MultiByteToWideChar( CP_ACP, 0, name, -1, buffer, MAX_PATH ))
    {
        SetLastError( ERROR_FILENAME_EXCED_RANGE );
        return 0;
    }
    return CreateJobObjectW( attr, buffer );
}

/******************************************************************************
 *		OpenJobObjectW (KERNEL32.@)
 */
HANDLE WINAPI OpenJobObjectW( DWORD access, BOOL inherit, LPCWSTR name )
{
    HANDLE ret;
    UNICODE_STRING nameW;
    OBJECT_ATTRIBUTES attr;
    NTSTATUS status;

    attr.Length                   = sizeof(attr);
    attr.RootDirectory            = 0;
    attr.ObjectName               = NULL;
    attr.Attributes               = inherit ? OBJ_INHERIT : 0;
    attr.SecurityDescriptor       = NULL;
    attr.SecurityQualityOfService = NULL;
    if (name)
    {
        RtlInitUnicodeString( &nameW, name );
        attr.ObjectName = &nameW;
        attr.RootDirectory = get_BaseNamedObjects_handle();
    }

    status = NtOpenJobObject( &ret, access, &attr );
    if (status != STATUS_SUCCESS)
    {
        SetLastError( RtlNtStatusToDosError(status) );
        return 0;
    }
    return ret;
}

/******************************************************************************
 *		OpenJobObjectA (KERNEL32.@)
 */
HANDLE WINAPI OpenJobObjectA( DWORD access, BOOL inherit, LPCSTR name )
{
    WCHAR buffer[MAX_PATH];

    if (!name) return OpenJobObjectW( access, inherit, NULL );

    if (!MultiByteToWideChar( CP_ACP, 0, name, -1, buffer, MAX_PATH ))
    {
        SetLastError( ERROR_FILENAME_EXCED_RANGE );
        return 0;
    }
    return OpenJobObjectW( access, inherit, buffer );
}

/******************************************************************************
 *		TerminateJobObject (KERNEL32.@)
 */
BOOL WINAPI TerminateJobObject( HANDLE job, UINT exit_code )
{
    NTSTATUS status = NtTerminateJobObject( job, exit_code );
    if (status) SetLastError( RtlNtStatusToDosError(status) );
    return !status;
}

/******************************************************************************
 *		QueryInformationJobObject (KERNEL32.@)
 */
BOOL WINAPI QueryInformationJobObject( HANDLE job, JOBOBJECTINFOCLASS class, LPVOID info,
                                       DWORD len, DWORD *ret_len )
{
    NTSTATUS status = NtQueryInformationJobObject( job, class, info, len, ret_len );
    if (status) SetLastError( RtlNtStatusToDosError(status) );
    return !status;
}

/******************************************************************************
 *		SetInformationJobObject (KERNEL32.@)
 */
BOOL WINAPI SetInformationJobObject( HANDLE job, JOBOBJECTINFOCLASS class, LPVOID info, DWORD len )
{
    NTSTATUS status = NtSetInformationJobObject( job, class, info, len );
    if (status) SetLastError( RtlNtStatusToDosError(status) );
    return !status;
}

/******************************************************************************
 *		AssignProcessToJobObject (KERNEL32.@)
 */
BOOL WINAPI AssignProcessToJobObject( HANDLE job, HANDLE process )
{
    NTSTATUS status = NtAssignProcessToJobObject( job, process );
    if (status) SetLastError( RtlNtStatusToDosError(status) );
    return !status;
}

/******************************************************************************
 *		IsProcessInJob (KERNEL32.@)
 */
BOOL WINAPI IsProcessInJob( HANDLE process, HANDLE job, PBOOL result )
{
1021
    NTSTATUS status = NtIsProcessInJob( process, job );
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
    switch(status)
    {
    case STATUS_PROCESS_IN_JOB:
        *result = TRUE;
        return TRUE;
    case STATUS_PROCESS_NOT_IN_JOB:
        *result = FALSE;
        return TRUE;
    default:
        SetLastError( RtlNtStatusToDosError(status) );
        return FALSE;
    }
}


1037 1038 1039 1040 1041 1042 1043 1044 1045
/*
 * Timers
 */


/***********************************************************************
 *           CreateWaitableTimerA    (KERNEL32.@)
 */
HANDLE WINAPI CreateWaitableTimerA( SECURITY_ATTRIBUTES *sa, BOOL manual, LPCSTR name )
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
{
    return CreateWaitableTimerExA( sa, name, manual ? CREATE_WAITABLE_TIMER_MANUAL_RESET : 0,
                                   TIMER_ALL_ACCESS );
}


/***********************************************************************
 *           CreateWaitableTimerW    (KERNEL32.@)
 */
HANDLE WINAPI CreateWaitableTimerW( SECURITY_ATTRIBUTES *sa, BOOL manual, LPCWSTR name )
{
    return CreateWaitableTimerExW( sa, name, manual ? CREATE_WAITABLE_TIMER_MANUAL_RESET : 0,
                                   TIMER_ALL_ACCESS );
}


/***********************************************************************
 *           CreateWaitableTimerExA    (KERNEL32.@)
 */
HANDLE WINAPI CreateWaitableTimerExA( SECURITY_ATTRIBUTES *sa, LPCSTR name, DWORD flags, DWORD access )
1066 1067 1068
{
    WCHAR buffer[MAX_PATH];

1069
    if (!name) return CreateWaitableTimerExW( sa, NULL, flags, access );
1070 1071 1072 1073 1074 1075

    if (!MultiByteToWideChar( CP_ACP, 0, name, -1, buffer, MAX_PATH ))
    {
        SetLastError( ERROR_FILENAME_EXCED_RANGE );
        return 0;
    }
1076
    return CreateWaitableTimerExW( sa, buffer, flags, access );
1077 1078 1079 1080
}


/***********************************************************************
1081
 *           CreateWaitableTimerExW    (KERNEL32.@)
1082
 */
1083
HANDLE WINAPI CreateWaitableTimerExW( SECURITY_ATTRIBUTES *sa, LPCWSTR name, DWORD flags, DWORD access )
1084
{
1085 1086 1087 1088
    HANDLE handle;
    NTSTATUS status;
    UNICODE_STRING nameW;
    OBJECT_ATTRIBUTES attr;
1089

1090 1091 1092
    attr.Length                   = sizeof(attr);
    attr.RootDirectory            = 0;
    attr.ObjectName               = NULL;
1093
    attr.Attributes               = OBJ_OPENIF | ((sa && sa->bInheritHandle) ? OBJ_INHERIT : 0);
1094 1095 1096
    attr.SecurityDescriptor       = sa ? sa->lpSecurityDescriptor : NULL;
    attr.SecurityQualityOfService = NULL;
    if (name)
1097
    {
1098 1099
        RtlInitUnicodeString( &nameW, name );
        attr.ObjectName = &nameW;
1100
        attr.RootDirectory = get_BaseNamedObjects_handle();
1101
    }
1102

1103 1104
    status = NtCreateTimer( &handle, access, &attr,
                 (flags & CREATE_WAITABLE_TIMER_MANUAL_RESET) ? NotificationTimer : SynchronizationTimer );
1105 1106 1107 1108
    if (status == STATUS_OBJECT_NAME_EXISTS)
        SetLastError( ERROR_ALREADY_EXISTS );
    else
        SetLastError( RtlNtStatusToDosError(status) );
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
    return handle;
}


/***********************************************************************
 *           OpenWaitableTimerA    (KERNEL32.@)
 */
HANDLE WINAPI OpenWaitableTimerA( DWORD access, BOOL inherit, LPCSTR name )
{
    WCHAR buffer[MAX_PATH];

    if (!name) return OpenWaitableTimerW( access, inherit, NULL );

    if (!MultiByteToWideChar( CP_ACP, 0, name, -1, buffer, MAX_PATH ))
    {
        SetLastError( ERROR_FILENAME_EXCED_RANGE );
        return 0;
    }
    return OpenWaitableTimerW( access, inherit, buffer );
}


/***********************************************************************
 *           OpenWaitableTimerW    (KERNEL32.@)
 */
HANDLE WINAPI OpenWaitableTimerW( DWORD access, BOOL inherit, LPCWSTR name )
{
1136 1137 1138 1139
    HANDLE handle;
    UNICODE_STRING nameW;
    OBJECT_ATTRIBUTES attr;
    NTSTATUS status;
1140

1141
    if (!is_version_nt()) access = TIMER_ALL_ACCESS;
1142 1143 1144 1145

    attr.Length                   = sizeof(attr);
    attr.RootDirectory            = 0;
    attr.ObjectName               = NULL;
1146
    attr.Attributes               = inherit ? OBJ_INHERIT : 0;
1147 1148 1149 1150 1151 1152
    attr.SecurityDescriptor       = NULL;
    attr.SecurityQualityOfService = NULL;
    if (name)
    {
        RtlInitUnicodeString( &nameW, name );
        attr.ObjectName = &nameW;
1153
        attr.RootDirectory = get_BaseNamedObjects_handle();
1154
    }
1155

1156
    status = NtOpenTimer(&handle, access, &attr);
1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171
    if (status != STATUS_SUCCESS)
    {
        SetLastError( RtlNtStatusToDosError(status) );
        return 0;
    }
    return handle;
}


/***********************************************************************
 *           SetWaitableTimer    (KERNEL32.@)
 */
BOOL WINAPI SetWaitableTimer( HANDLE handle, const LARGE_INTEGER *when, LONG period,
                              PTIMERAPCROUTINE callback, LPVOID arg, BOOL resume )
{
1172 1173
    NTSTATUS status = NtSetTimer(handle, when, (PTIMER_APC_ROUTINE)callback,
                                 arg, resume, period, NULL);
1174 1175 1176 1177 1178 1179 1180 1181 1182

    if (status != STATUS_SUCCESS)
    {
        SetLastError( RtlNtStatusToDosError(status) );
        if (status != STATUS_TIMER_RESUME_IGNORED) return FALSE;
    }
    return TRUE;
}

1183 1184 1185 1186 1187 1188
/***********************************************************************
 *           SetWaitableTimerEx    (KERNEL32.@)
 */
BOOL WINAPI SetWaitableTimerEx( HANDLE handle, const LARGE_INTEGER *when, LONG period,
                              PTIMERAPCROUTINE callback, LPVOID arg, REASON_CONTEXT *context, ULONG tolerabledelay )
{
1189 1190 1191 1192 1193 1194
    static int once;
    if (!once++)
    {
        FIXME("(%p, %p, %d, %p, %p, %p, %d) semi-stub\n",
              handle, when, period, callback, arg, context, tolerabledelay);
    }
1195 1196
    return SetWaitableTimer(handle, when, period, callback, arg, FALSE);
}
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219

/***********************************************************************
 *           CancelWaitableTimer    (KERNEL32.@)
 */
BOOL WINAPI CancelWaitableTimer( HANDLE handle )
{
    NTSTATUS status;

    status = NtCancelTimer(handle, NULL);
    if (status != STATUS_SUCCESS)
    {
        SetLastError( RtlNtStatusToDosError(status) );
        return FALSE;
    }
    return TRUE;
}


/***********************************************************************
 *           CreateTimerQueue  (KERNEL32.@)
 */
HANDLE WINAPI CreateTimerQueue(void)
{
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
    HANDLE q;
    NTSTATUS status = RtlCreateTimerQueue(&q);

    if (status != STATUS_SUCCESS)
    {
        SetLastError( RtlNtStatusToDosError(status) );
        return NULL;
    }

    return q;
1230 1231 1232 1233 1234 1235 1236 1237
}


/***********************************************************************
 *           DeleteTimerQueueEx  (KERNEL32.@)
 */
BOOL WINAPI DeleteTimerQueueEx(HANDLE TimerQueue, HANDLE CompletionEvent)
{
1238 1239 1240 1241 1242 1243 1244 1245 1246
    NTSTATUS status = RtlDeleteTimerQueueEx(TimerQueue, CompletionEvent);

    if (status != STATUS_SUCCESS)
    {
        SetLastError( RtlNtStatusToDosError(status) );
        return FALSE;
    }

    return TRUE;
1247 1248
}

1249 1250 1251 1252 1253 1254 1255 1256
/***********************************************************************
 *           DeleteTimerQueue  (KERNEL32.@)
 */
BOOL WINAPI DeleteTimerQueue(HANDLE TimerQueue)
{
    return DeleteTimerQueueEx(TimerQueue, NULL);
}

1257 1258 1259 1260 1261 1262 1263 1264
/***********************************************************************
 *           CreateTimerQueueTimer  (KERNEL32.@)
 *
 * Creates a timer-queue timer. This timer expires at the specified due
 * time (in ms), then after every specified period (in ms). When the timer
 * expires, the callback function is called.
 *
 * RETURNS
1265
 *   nonzero on success or zero on failure
1266 1267 1268 1269 1270
 */
BOOL WINAPI CreateTimerQueueTimer( PHANDLE phNewTimer, HANDLE TimerQueue,
                                   WAITORTIMERCALLBACK Callback, PVOID Parameter,
                                   DWORD DueTime, DWORD Period, ULONG Flags )
{
1271 1272 1273 1274 1275 1276 1277 1278 1279
    NTSTATUS status = RtlCreateTimer(phNewTimer, TimerQueue, Callback,
                                     Parameter, DueTime, Period, Flags);

    if (status != STATUS_SUCCESS)
    {
        SetLastError( RtlNtStatusToDosError(status) );
        return FALSE;
    }

1280 1281 1282
    return TRUE;
}

1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293
/***********************************************************************
 *           ChangeTimerQueueTimer  (KERNEL32.@)
 *
 * Changes the times at which the timer expires.
 *
 * RETURNS
 *   nonzero on success or zero on failure
 */
BOOL WINAPI ChangeTimerQueueTimer( HANDLE TimerQueue, HANDLE Timer,
                                   ULONG DueTime, ULONG Period )
{
1294 1295 1296 1297 1298 1299 1300 1301 1302
    NTSTATUS status = RtlUpdateTimer(TimerQueue, Timer, DueTime, Period);

    if (status != STATUS_SUCCESS)
    {
        SetLastError( RtlNtStatusToDosError(status) );
        return FALSE;
    }

    return TRUE;
1303 1304
}

1305 1306 1307 1308 1309 1310 1311 1312 1313
/***********************************************************************
 *           CancelTimerQueueTimer    (KERNEL32.@)
 */
BOOL WINAPI CancelTimerQueueTimer(HANDLE queue, HANDLE timer)
{
    FIXME("stub: %p %p\n", queue, timer);
    return FALSE;
}

1314 1315 1316 1317 1318 1319
/***********************************************************************
 *           DeleteTimerQueueTimer  (KERNEL32.@)
 *
 * Cancels a timer-queue timer.
 *
 * RETURNS
1320
 *   nonzero on success or zero on failure
1321 1322 1323 1324
 */
BOOL WINAPI DeleteTimerQueueTimer( HANDLE TimerQueue, HANDLE Timer,
                                   HANDLE CompletionEvent )
{
1325 1326 1327 1328 1329 1330
    NTSTATUS status = RtlDeleteTimer(TimerQueue, Timer, CompletionEvent);
    if (status != STATUS_SUCCESS)
    {
        SetLastError( RtlNtStatusToDosError(status) );
        return FALSE;
    }
1331 1332 1333 1334
    return TRUE;
}


1335 1336 1337 1338 1339 1340
/*
 * Pipes
 */


/***********************************************************************
1341
 *           CreateNamedPipeA   (KERNEL32.@)
1342 1343 1344 1345 1346 1347
 */
HANDLE WINAPI CreateNamedPipeA( LPCSTR name, DWORD dwOpenMode,
                                DWORD dwPipeMode, DWORD nMaxInstances,
                                DWORD nOutBufferSize, DWORD nInBufferSize,
                                DWORD nDefaultTimeOut, LPSECURITY_ATTRIBUTES attr )
{
1348
    WCHAR buffer[MAX_PATH];
1349

1350 1351
    if (!name) return CreateNamedPipeW( NULL, dwOpenMode, dwPipeMode, nMaxInstances,
                                        nOutBufferSize, nInBufferSize, nDefaultTimeOut, attr );
1352

1353
    if (!MultiByteToWideChar( CP_ACP, 0, name, -1, buffer, MAX_PATH ))
1354 1355
    {
        SetLastError( ERROR_FILENAME_EXCED_RANGE );
1356
        return INVALID_HANDLE_VALUE;
1357
    }
1358 1359
    return CreateNamedPipeW( buffer, dwOpenMode, dwPipeMode, nMaxInstances,
                             nOutBufferSize, nInBufferSize, nDefaultTimeOut, attr );
1360 1361 1362 1363
}


/***********************************************************************
1364
 *           CreateNamedPipeW   (KERNEL32.@)
1365 1366 1367 1368
 */
HANDLE WINAPI CreateNamedPipeW( LPCWSTR name, DWORD dwOpenMode,
                                DWORD dwPipeMode, DWORD nMaxInstances,
                                DWORD nOutBufferSize, DWORD nInBufferSize,
1369
                                DWORD nDefaultTimeOut, LPSECURITY_ATTRIBUTES sa )
1370
{
1371
    HANDLE handle;
1372
    UNICODE_STRING nt_name;
1373
    OBJECT_ATTRIBUTES attr;
1374
    DWORD access, options, sharing;
1375 1376 1377 1378
    BOOLEAN pipe_type, read_mode, non_block;
    NTSTATUS status;
    IO_STATUS_BLOCK iosb;
    LARGE_INTEGER timeout;
1379

1380
    TRACE("(%s, %#08x, %#08x, %d, %d, %d, %d, %p)\n",
1381
          debugstr_w(name), dwOpenMode, dwPipeMode, nMaxInstances,
1382
          nOutBufferSize, nInBufferSize, nDefaultTimeOut, sa );
1383

1384
    if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
1385 1386 1387 1388
    {
        SetLastError( ERROR_PATH_NOT_FOUND );
        return INVALID_HANDLE_VALUE;
    }
1389
    if (nt_name.Length >= MAX_PATH * sizeof(WCHAR) )
1390 1391
    {
        SetLastError( ERROR_FILENAME_EXCED_RANGE );
1392
        RtlFreeUnicodeString( &nt_name );
1393 1394
        return INVALID_HANDLE_VALUE;
    }
1395 1396 1397 1398

    attr.Length                   = sizeof(attr);
    attr.RootDirectory            = 0;
    attr.ObjectName               = &nt_name;
1399
    attr.Attributes               = OBJ_CASE_INSENSITIVE |
1400
                                    ((sa && sa->bInheritHandle) ? OBJ_INHERIT : 0);
1401 1402 1403
    attr.SecurityDescriptor       = sa ? sa->lpSecurityDescriptor : NULL;
    attr.SecurityQualityOfService = NULL;

1404 1405 1406
    switch(dwOpenMode & 3)
    {
    case PIPE_ACCESS_INBOUND:
1407
        sharing = FILE_SHARE_WRITE;
1408 1409 1410
        access  = GENERIC_READ;
        break;
    case PIPE_ACCESS_OUTBOUND:
1411
        sharing = FILE_SHARE_READ;
1412 1413 1414
        access  = GENERIC_WRITE;
        break;
    case PIPE_ACCESS_DUPLEX:
1415
        sharing = FILE_SHARE_READ | FILE_SHARE_WRITE;
1416 1417 1418 1419 1420 1421 1422
        access  = GENERIC_READ | GENERIC_WRITE;
        break;
    default:
        SetLastError( ERROR_INVALID_PARAMETER );
        return INVALID_HANDLE_VALUE;
    }
    access |= SYNCHRONIZE;
1423
    options = 0;
1424 1425 1426
    if (dwOpenMode & WRITE_DAC) access |= WRITE_DAC;
    if (dwOpenMode & WRITE_OWNER) access |= WRITE_OWNER;
    if (dwOpenMode & ACCESS_SYSTEM_SECURITY) access |= ACCESS_SYSTEM_SECURITY;
1427
    if (dwOpenMode & FILE_FLAG_WRITE_THROUGH) options |= FILE_WRITE_THROUGH;
1428
    if (!(dwOpenMode & FILE_FLAG_OVERLAPPED)) options |= FILE_SYNCHRONOUS_IO_NONALERT;
1429 1430 1431
    pipe_type = (dwPipeMode & PIPE_TYPE_MESSAGE) != 0;
    read_mode = (dwPipeMode & PIPE_READMODE_MESSAGE) != 0;
    non_block = (dwPipeMode & PIPE_NOWAIT) != 0;
1432
    if (nMaxInstances >= PIPE_UNLIMITED_INSTANCES) nMaxInstances = ~0U;
1433 1434 1435 1436

    timeout.QuadPart = (ULONGLONG)nDefaultTimeOut * -10000;

    SetLastError(0);
1437

1438
    status = NtCreateNamedPipeFile(&handle, access, &attr, &iosb, sharing,
1439
                                   FILE_OVERWRITE_IF, options, pipe_type,
1440 1441
                                   read_mode, non_block, nMaxInstances,
                                   nInBufferSize, nOutBufferSize, &timeout);
1442 1443 1444

    RtlFreeUnicodeString( &nt_name );
    if (status)
1445
    {
1446 1447
        handle = INVALID_HANDLE_VALUE;
        SetLastError( RtlNtStatusToDosError(status) );
1448
    }
1449
    return handle;
1450 1451 1452 1453
}


/***********************************************************************
1454
 *           PeekNamedPipe   (KERNEL32.@)
1455 1456 1457 1458
 */
BOOL WINAPI PeekNamedPipe( HANDLE hPipe, LPVOID lpvBuffer, DWORD cbBuffer,
                           LPDWORD lpcbRead, LPDWORD lpcbAvail, LPDWORD lpcbMessage )
{
1459 1460 1461 1462
    FILE_PIPE_PEEK_BUFFER local_buffer;
    FILE_PIPE_PEEK_BUFFER *buffer = &local_buffer;
    IO_STATUS_BLOCK io;
    NTSTATUS status;
1463

1464 1465
    if (cbBuffer && !(buffer = HeapAlloc( GetProcessHeap(), 0,
                                          FIELD_OFFSET( FILE_PIPE_PEEK_BUFFER, Data[cbBuffer] ))))
1466
    {
1467
        SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1468 1469
        return FALSE;
    }
1470

1471 1472 1473
    status = NtFsControlFile( hPipe, 0, NULL, NULL, &io, FSCTL_PIPE_PEEK, NULL, 0,
                              buffer, FIELD_OFFSET( FILE_PIPE_PEEK_BUFFER, Data[cbBuffer] ) );
    if (!status)
1474
    {
1475 1476 1477 1478 1479
        ULONG read_size = io.Information - FIELD_OFFSET( FILE_PIPE_PEEK_BUFFER, Data );
        if (lpcbAvail) *lpcbAvail = buffer->ReadDataAvailable;
        if (lpcbRead) *lpcbRead = read_size;
        if (lpcbMessage) *lpcbMessage = 0;  /* FIXME */
        if (lpvBuffer) memcpy( lpvBuffer, buffer->Data, read_size );
1480
    }
1481
    else SetLastError( RtlNtStatusToDosError(status) );
1482

1483 1484
    if (buffer != &local_buffer) HeapFree( GetProcessHeap(), 0, buffer );
    return !status;
1485 1486
}

1487 1488 1489 1490 1491
/***********************************************************************
 *           WaitNamedPipeA   (KERNEL32.@)
 */
BOOL WINAPI WaitNamedPipeA (LPCSTR name, DWORD nTimeOut)
{
1492
    WCHAR buffer[MAX_PATH];
1493

1494
    if (!name) return WaitNamedPipeW( NULL, nTimeOut );
1495

1496
    if (!MultiByteToWideChar( CP_ACP, 0, name, -1, buffer, MAX_PATH ))
1497
    {
1498
        SetLastError( ERROR_FILENAME_EXCED_RANGE );
1499
        return FALSE;
1500
    }
1501
    return WaitNamedPipeW( buffer, nTimeOut );
1502 1503 1504 1505
}


/***********************************************************************
1506
 *           WaitNamedPipeW   (KERNEL32.@)
1507 1508 1509 1510 1511 1512 1513 1514
 *
 *  Waits for a named pipe instance to become available
 *
 *  PARAMS
 *   name     [I] Pointer to a named pipe name to wait for
 *   nTimeOut [I] How long to wait in ms
 *
 *  RETURNS
1515
 *   TRUE: Success, named pipe can be opened with CreateFile
1516
 *   FALSE: Failure, GetLastError can be called for further details
1517
 */
1518
BOOL WINAPI WaitNamedPipeW (LPCWSTR name, DWORD nTimeOut)
1519
{
1520
    static const WCHAR leadin[] = {'\\','?','?','\\','P','I','P','E','\\'};
1521 1522 1523 1524 1525 1526 1527
    NTSTATUS status;
    UNICODE_STRING nt_name, pipe_dev_name;
    FILE_PIPE_WAIT_FOR_BUFFER *pipe_wait;
    IO_STATUS_BLOCK iosb;
    OBJECT_ATTRIBUTES attr;
    ULONG sz_pipe_wait;
    HANDLE pipe_dev;
1528

1529
    TRACE("%s 0x%08x\n",debugstr_w(name),nTimeOut);
1530 1531 1532 1533

    if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
        return FALSE;

1534 1535
    if (nt_name.Length >= MAX_PATH * sizeof(WCHAR) ||
        nt_name.Length < sizeof(leadin) ||
1536
        strncmpiW( nt_name.Buffer, leadin, sizeof(leadin)/sizeof(WCHAR)) != 0)
1537
    {
1538
        RtlFreeUnicodeString( &nt_name );
1539
        SetLastError( ERROR_PATH_NOT_FOUND );
1540 1541
        return FALSE;
    }
1542 1543 1544

    sz_pipe_wait = sizeof(*pipe_wait) + nt_name.Length - sizeof(leadin) - sizeof(WCHAR);
    if (!(pipe_wait = HeapAlloc( GetProcessHeap(), 0,  sz_pipe_wait)))
1545 1546
    {
        RtlFreeUnicodeString( &nt_name );
1547
        SetLastError( ERROR_OUTOFMEMORY );
1548 1549
        return FALSE;
    }
1550

1551 1552 1553 1554
    pipe_dev_name.Buffer = nt_name.Buffer;
    pipe_dev_name.Length = sizeof(leadin);
    pipe_dev_name.MaximumLength = sizeof(leadin);
    InitializeObjectAttributes(&attr,&pipe_dev_name, OBJ_CASE_INSENSITIVE, NULL, NULL);
1555
    status = NtOpenFile( &pipe_dev, FILE_READ_ATTRIBUTES | SYNCHRONIZE, &attr,
1556 1557
                         &iosb, FILE_SHARE_READ | FILE_SHARE_WRITE,
                         FILE_SYNCHRONOUS_IO_NONALERT);
1558
    if (status != STATUS_SUCCESS)
1559
    {
1560 1561
        HeapFree( GetProcessHeap(), 0, pipe_wait);
        RtlFreeUnicodeString( &nt_name );
1562 1563
        SetLastError( ERROR_PATH_NOT_FOUND );
        return FALSE;
1564 1565
    }

1566
    pipe_wait->TimeoutSpecified = !(nTimeOut == NMPWAIT_USE_DEFAULT_WAIT);
1567 1568 1569 1570
    if (nTimeOut == NMPWAIT_WAIT_FOREVER)
        pipe_wait->Timeout.QuadPart = ((ULONGLONG)0x7fffffff << 32) | 0xffffffff;
    else
        pipe_wait->Timeout.QuadPart = (ULONGLONG)nTimeOut * -10000;
1571 1572 1573
    pipe_wait->NameLength = nt_name.Length - sizeof(leadin);
    memcpy(pipe_wait->Name, nt_name.Buffer + sizeof(leadin)/sizeof(WCHAR),
           pipe_wait->NameLength);
1574 1575
    RtlFreeUnicodeString( &nt_name );

1576 1577 1578 1579 1580 1581 1582
    status = NtFsControlFile( pipe_dev, NULL, NULL, NULL, &iosb, FSCTL_PIPE_WAIT,
                              pipe_wait, sz_pipe_wait, NULL, 0 );

    HeapFree( GetProcessHeap(), 0, pipe_wait );
    NtClose( pipe_dev );

    if(status != STATUS_SUCCESS)
1583
    {
1584 1585
        SetLastError(RtlNtStatusToDosError(status));
        return FALSE;
1586
    }
1587 1588
    else
        return TRUE;
1589 1590 1591 1592
}


/***********************************************************************
1593
 *           ConnectNamedPipe   (KERNEL32.@)
1594 1595 1596 1597 1598 1599 1600 1601 1602 1603
 *
 *  Connects to a named pipe
 *
 *  Parameters
 *  hPipe: A handle to a named pipe returned by CreateNamedPipe
 *  overlapped: Optional OVERLAPPED struct
 *
 *  Return values
 *  TRUE: Success
 *  FALSE: Failure, GetLastError can be called for further details
1604
 */
1605
BOOL WINAPI ConnectNamedPipe(HANDLE hPipe, LPOVERLAPPED overlapped)
1606
{
1607 1608
    NTSTATUS status;
    IO_STATUS_BLOCK status_block;
1609
    LPVOID   cvalue = NULL;
1610

1611
    TRACE("(%p,%p)\n", hPipe, overlapped);
1612

1613
    if(overlapped)
1614
    {
1615
        overlapped->Internal = STATUS_PENDING;
1616
        overlapped->InternalHigh = 0;
1617
        if (((ULONG_PTR)overlapped->hEvent & 1) == 0) cvalue = overlapped;
1618
    }
1619

1620
    status = NtFsControlFile(hPipe, overlapped ? overlapped->hEvent : NULL, NULL, cvalue,
1621 1622
                             overlapped ? (IO_STATUS_BLOCK *)overlapped : &status_block,
                             FSCTL_PIPE_LISTEN, NULL, 0, NULL, 0);
1623

1624 1625 1626
    if (status == STATUS_SUCCESS) return TRUE;
    SetLastError( RtlNtStatusToDosError(status) );
    return FALSE;
1627 1628 1629 1630
}

/***********************************************************************
 *           DisconnectNamedPipe   (KERNEL32.@)
1631 1632 1633 1634 1635 1636 1637 1638 1639
 *
 *  Disconnects from a named pipe
 *
 *  Parameters
 *  hPipe: A handle to a named pipe returned by CreateNamedPipe
 *
 *  Return values
 *  TRUE: Success
 *  FALSE: Failure, GetLastError can be called for further details
1640 1641 1642
 */
BOOL WINAPI DisconnectNamedPipe(HANDLE hPipe)
{
1643 1644
    NTSTATUS status;
    IO_STATUS_BLOCK io_block;
1645

1646
    TRACE("(%p)\n",hPipe);
1647

1648 1649 1650 1651 1652
    status = NtFsControlFile(hPipe, 0, NULL, NULL, &io_block, FSCTL_PIPE_DISCONNECT,
                             NULL, 0, NULL, 0);
    if (status == STATUS_SUCCESS) return TRUE;
    SetLastError( RtlNtStatusToDosError(status) );
    return FALSE;
1653 1654
}

1655 1656
/***********************************************************************
 *           TransactNamedPipe   (KERNEL32.@)
1657 1658 1659
 *
 * BUGS
 *  should be done as a single operation in the wineserver or kernel
1660 1661
 */
BOOL WINAPI TransactNamedPipe(
1662 1663
    HANDLE handle, LPVOID write_buf, DWORD write_size, LPVOID read_buf,
    DWORD read_size, LPDWORD bytes_read, LPOVERLAPPED overlapped)
1664
{
1665 1666 1667
    BOOL r;
    DWORD count;

1668
    TRACE("%p %p %d %p %d %p %p\n",
1669 1670
          handle, write_buf, write_size, read_buf,
          read_size, bytes_read, overlapped);
1671

1672
    if (overlapped)
1673 1674 1675 1676 1677
    {
        FIXME("Doesn't support overlapped operation as yet\n");
        return FALSE;
    }

1678
    r = WriteFile(handle, write_buf, write_size, &count, NULL);
1679
    if (r)
1680
        r = ReadFile(handle, read_buf, read_size, bytes_read, NULL);
1681 1682

    return r;
1683 1684 1685 1686 1687 1688 1689 1690 1691
}

/***********************************************************************
 *           GetNamedPipeInfo   (KERNEL32.@)
 */
BOOL WINAPI GetNamedPipeInfo(
    HANDLE hNamedPipe, LPDWORD lpFlags, LPDWORD lpOutputBufferSize,
    LPDWORD lpInputBufferSize, LPDWORD lpMaxInstances)
{
1692 1693 1694
    FILE_PIPE_LOCAL_INFORMATION fpli;
    IO_STATUS_BLOCK iosb;
    NTSTATUS status;
1695

1696 1697 1698 1699 1700 1701 1702
    status = NtQueryInformationFile(hNamedPipe, &iosb, &fpli, sizeof(fpli),
                                    FilePipeLocalInformation);
    if (status)
    {
        SetLastError( RtlNtStatusToDosError(status) );
        return FALSE;
    }
1703

1704
    if (lpFlags)
1705
    {
1706 1707 1708 1709
        *lpFlags = (fpli.NamedPipeEnd & FILE_PIPE_SERVER_END) ?
            PIPE_SERVER_END : PIPE_CLIENT_END;
        *lpFlags |= (fpli.NamedPipeType & FILE_PIPE_TYPE_MESSAGE) ?
            PIPE_TYPE_MESSAGE : PIPE_TYPE_BYTE;
1710 1711
    }

1712 1713 1714 1715 1716
    if (lpOutputBufferSize) *lpOutputBufferSize = fpli.OutboundQuota;
    if (lpInputBufferSize) *lpInputBufferSize = fpli.InboundQuota;
    if (lpMaxInstances) *lpMaxInstances = fpli.MaximumInstances;

    return TRUE;
1717 1718 1719 1720 1721 1722 1723 1724 1725 1726
}

/***********************************************************************
 *           GetNamedPipeHandleStateA  (KERNEL32.@)
 */
BOOL WINAPI GetNamedPipeHandleStateA(
    HANDLE hNamedPipe, LPDWORD lpState, LPDWORD lpCurInstances,
    LPDWORD lpMaxCollectionCount, LPDWORD lpCollectDataTimeout,
    LPSTR lpUsername, DWORD nUsernameMaxSize)
{
1727 1728 1729 1730
    WARN("%p %p %p %p %p %p %d: semi-stub\n",
         hNamedPipe, lpState, lpCurInstances,
         lpMaxCollectionCount, lpCollectDataTimeout,
         lpUsername, nUsernameMaxSize);
1731

1732 1733 1734 1735 1736
    if (lpUsername && nUsernameMaxSize)
        *lpUsername = 0;

    return GetNamedPipeHandleStateW(hNamedPipe, lpState, lpCurInstances,
                                    lpMaxCollectionCount, lpCollectDataTimeout, NULL, 0);
1737 1738 1739 1740 1741 1742 1743 1744 1745 1746
}

/***********************************************************************
 *           GetNamedPipeHandleStateW  (KERNEL32.@)
 */
BOOL WINAPI GetNamedPipeHandleStateW(
    HANDLE hNamedPipe, LPDWORD lpState, LPDWORD lpCurInstances,
    LPDWORD lpMaxCollectionCount, LPDWORD lpCollectDataTimeout,
    LPWSTR lpUsername, DWORD nUsernameMaxSize)
{
1747 1748 1749 1750
    IO_STATUS_BLOCK iosb;
    NTSTATUS status;

    FIXME("%p %p %p %p %p %p %d: semi-stub\n",
1751 1752 1753
          hNamedPipe, lpState, lpCurInstances,
          lpMaxCollectionCount, lpCollectDataTimeout,
          lpUsername, nUsernameMaxSize);
1754

1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793
    if (lpMaxCollectionCount)
        *lpMaxCollectionCount = 0;

    if (lpCollectDataTimeout)
        *lpCollectDataTimeout = 0;

    if (lpUsername && nUsernameMaxSize)
        *lpUsername = 0;

    if (lpState)
    {
        FILE_PIPE_INFORMATION fpi;
        status = NtQueryInformationFile(hNamedPipe, &iosb, &fpi, sizeof(fpi),
                                        FilePipeInformation);
        if (status)
        {
            SetLastError( RtlNtStatusToDosError(status) );
            return FALSE;
        }

        *lpState = (fpi.ReadMode ? PIPE_READMODE_MESSAGE : PIPE_READMODE_BYTE) |
                   (fpi.CompletionMode ? PIPE_NOWAIT : PIPE_WAIT);
    }

    if (lpCurInstances)
    {
        FILE_PIPE_LOCAL_INFORMATION fpli;
        status = NtQueryInformationFile(hNamedPipe, &iosb, &fpli, sizeof(fpli),
                                        FilePipeLocalInformation);
        if (status)
        {
            SetLastError( RtlNtStatusToDosError(status) );
            return FALSE;
        }

        *lpCurInstances = fpli.CurrentInstances;
    }

    return TRUE;
1794 1795 1796 1797 1798 1799 1800 1801 1802
}

/***********************************************************************
 *           SetNamedPipeHandleState  (KERNEL32.@)
 */
BOOL WINAPI SetNamedPipeHandleState(
    HANDLE hNamedPipe, LPDWORD lpMode, LPDWORD lpMaxCollectionCount,
    LPDWORD lpCollectDataTimeout)
{
1803 1804
    /* should be a fixme, but this function is called a lot by the RPC
     * runtime, and it slows down InstallShield a fair bit. */
1805
    WARN("semi-stub: %p %p/%d %p %p\n",
1806
          hNamedPipe, lpMode, lpMode ? *lpMode : 0, lpMaxCollectionCount, lpCollectDataTimeout);
1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832

    if (lpMode)
    {
        FILE_PIPE_INFORMATION fpi;
        IO_STATUS_BLOCK iosb;
        NTSTATUS status;

        if (*lpMode & ~(PIPE_READMODE_MESSAGE | PIPE_NOWAIT))
            status = STATUS_INVALID_PARAMETER;
        else
        {
            fpi.CompletionMode = (*lpMode & PIPE_NOWAIT) ?
                FILE_PIPE_COMPLETE_OPERATION : FILE_PIPE_QUEUE_OPERATION;
            fpi.ReadMode = (*lpMode & PIPE_READMODE_MESSAGE) ?
                FILE_PIPE_MESSAGE_MODE : FILE_PIPE_BYTE_STREAM_MODE;
            status = NtSetInformationFile(hNamedPipe, &iosb, &fpi, sizeof(fpi), FilePipeInformation);
        }

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

    return TRUE;
1833 1834 1835 1836 1837 1838
}

/***********************************************************************
 *           CallNamedPipeA  (KERNEL32.@)
 */
BOOL WINAPI CallNamedPipeA(
1839 1840
    LPCSTR lpNamedPipeName, LPVOID lpInput, DWORD dwInputSize,
    LPVOID lpOutput, DWORD dwOutputSize,
1841 1842
    LPDWORD lpBytesRead, DWORD nTimeout)
{
1843 1844 1845 1846
    DWORD len;
    LPWSTR str = NULL;
    BOOL ret;

1847
    TRACE("%s %p %d %p %d %p %d\n",
1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862
           debugstr_a(lpNamedPipeName), lpInput, dwInputSize,
           lpOutput, dwOutputSize, lpBytesRead, nTimeout);

    if( lpNamedPipeName )
    {
        len = MultiByteToWideChar( CP_ACP, 0, lpNamedPipeName, -1, NULL, 0 );
        str = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
        MultiByteToWideChar( CP_ACP, 0, lpNamedPipeName, -1, str, len );
    }
    ret = CallNamedPipeW( str, lpInput, dwInputSize, lpOutput,
                          dwOutputSize, lpBytesRead, nTimeout );
    if( lpNamedPipeName )
        HeapFree( GetProcessHeap(), 0, str );

    return ret;
1863 1864 1865 1866 1867 1868 1869 1870 1871 1872
}

/***********************************************************************
 *           CallNamedPipeW  (KERNEL32.@)
 */
BOOL WINAPI CallNamedPipeW(
    LPCWSTR lpNamedPipeName, LPVOID lpInput, DWORD lpInputSize,
    LPVOID lpOutput, DWORD lpOutputSize,
    LPDWORD lpBytesRead, DWORD nTimeout)
{
1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897
    HANDLE pipe;
    BOOL ret;
    DWORD mode;

    TRACE("%s %p %d %p %d %p %d\n",
          debugstr_w(lpNamedPipeName), lpInput, lpInputSize,
          lpOutput, lpOutputSize, lpBytesRead, nTimeout);

    pipe = CreateFileW(lpNamedPipeName, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
    if (pipe == INVALID_HANDLE_VALUE)
    {
        ret = WaitNamedPipeW(lpNamedPipeName, nTimeout);
        if (!ret)
            return FALSE;
        pipe = CreateFileW(lpNamedPipeName, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
        if (pipe == INVALID_HANDLE_VALUE)
            return FALSE;
    }

    mode = PIPE_READMODE_MESSAGE;
    ret = SetNamedPipeHandleState(pipe, &mode, NULL, NULL);
    if (!ret)
    {
        CloseHandle(pipe);
        return FALSE;
1898
    }
1899 1900 1901 1902 1903 1904 1905

    ret = TransactNamedPipe(pipe, lpInput, lpInputSize, lpOutput, lpOutputSize, lpBytesRead, NULL);
    CloseHandle(pipe);
    if (!ret)
        return FALSE;

    return TRUE;
1906
}
1907 1908 1909 1910 1911 1912 1913 1914

/******************************************************************
 *		CreatePipe (KERNEL32.@)
 *
 */
BOOL WINAPI CreatePipe( PHANDLE hReadPipe, PHANDLE hWritePipe,
                        LPSECURITY_ATTRIBUTES sa, DWORD size )
{
1915 1916 1917 1918 1919 1920 1921 1922 1923
    static unsigned     index /* = 0 */;
    WCHAR               name[64];
    HANDLE              hr, hw;
    unsigned            in_index = index;
    UNICODE_STRING      nt_name;
    OBJECT_ATTRIBUTES   attr;
    NTSTATUS            status;
    IO_STATUS_BLOCK     iosb;
    LARGE_INTEGER       timeout;
1924 1925

    *hReadPipe = *hWritePipe = INVALID_HANDLE_VALUE;
1926 1927 1928 1929 1930

    attr.Length                   = sizeof(attr);
    attr.RootDirectory            = 0;
    attr.ObjectName               = &nt_name;
    attr.Attributes               = OBJ_CASE_INSENSITIVE |
1931
                                    ((sa && sa->bInheritHandle) ? OBJ_INHERIT : 0);
1932 1933 1934
    attr.SecurityDescriptor       = sa ? sa->lpSecurityDescriptor : NULL;
    attr.SecurityQualityOfService = NULL;

1935 1936
    if (!size) size = 4096;

1937
    timeout.QuadPart = (ULONGLONG)NMPWAIT_USE_DEFAULT_WAIT * -10000;
1938 1939 1940
    /* generate a unique pipe name (system wide) */
    do
    {
1941
        static const WCHAR nameFmt[] = { '\\','?','?','\\','p','i','p','e',
1942 1943
         '\\','W','i','n','3','2','.','P','i','p','e','s','.','%','0','8','l',
         'u','.','%','0','8','u','\0' };
1944

1945 1946
        snprintfW(name, sizeof(name) / sizeof(name[0]), nameFmt,
                  GetCurrentProcessId(), ++index);
1947 1948
        RtlInitUnicodeString(&nt_name, name);
        status = NtCreateNamedPipeFile(&hr, GENERIC_READ | SYNCHRONIZE, &attr, &iosb,
1949 1950
                                       FILE_SHARE_WRITE, FILE_OVERWRITE_IF,
                                       FILE_SYNCHRONOUS_IO_NONALERT,
1951 1952 1953 1954 1955 1956 1957
                                       FALSE, FALSE, FALSE, 
                                       1, size, size, &timeout);
        if (status)
        {
            SetLastError( RtlNtStatusToDosError(status) );
            hr = INVALID_HANDLE_VALUE;
        }
1958 1959 1960 1961
    } while (hr == INVALID_HANDLE_VALUE && index != in_index);
    /* from completion sakeness, I think system resources might be exhausted before this happens !! */
    if (hr == INVALID_HANDLE_VALUE) return FALSE;

1962
    status = NtOpenFile(&hw, GENERIC_WRITE | SYNCHRONIZE, &attr, &iosb, 0,
1963
                        FILE_SYNCHRONOUS_IO_NONALERT | FILE_NON_DIRECTORY_FILE);
1964 1965

    if (status) 
1966
    {
1967 1968
        SetLastError( RtlNtStatusToDosError(status) );
        NtClose(hr);
1969 1970 1971 1972 1973 1974 1975
        return FALSE;
    }

    *hReadPipe = hr;
    *hWritePipe = hw;
    return TRUE;
}
1976 1977


1978 1979
/******************************************************************************
 * CreateMailslotA [KERNEL32.@]
1980
 *
Rico Schüller's avatar
Rico Schüller committed
1981
 * See CreateMailslotW.
1982 1983 1984 1985 1986 1987 1988 1989
 */
HANDLE WINAPI CreateMailslotA( LPCSTR lpName, DWORD nMaxMessageSize,
                               DWORD lReadTimeout, LPSECURITY_ATTRIBUTES sa )
{
    DWORD len;
    HANDLE handle;
    LPWSTR name = NULL;

1990
    TRACE("%s %d %d %p\n", debugstr_a(lpName),
1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001
          nMaxMessageSize, lReadTimeout, sa);

    if( lpName )
    {
        len = MultiByteToWideChar( CP_ACP, 0, lpName, -1, NULL, 0 );
        name = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
        MultiByteToWideChar( CP_ACP, 0, lpName, -1, name, len );
    }

    handle = CreateMailslotW( name, nMaxMessageSize, lReadTimeout, sa );

2002
    HeapFree( GetProcessHeap(), 0, name );
2003 2004 2005 2006 2007 2008

    return handle;
}


/******************************************************************************
Jon Griffiths's avatar
Jon Griffiths committed
2009 2010 2011
 * CreateMailslotW [KERNEL32.@]
 *
 * Create a mailslot with specified name.
2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025
 *
 * PARAMS
 *    lpName          [I] Pointer to string for mailslot name
 *    nMaxMessageSize [I] Maximum message size
 *    lReadTimeout    [I] Milliseconds before read time-out
 *    sa              [I] Pointer to security structure
 *
 * RETURNS
 *    Success: Handle to mailslot
 *    Failure: INVALID_HANDLE_VALUE
 */
HANDLE WINAPI CreateMailslotW( LPCWSTR lpName, DWORD nMaxMessageSize,
                               DWORD lReadTimeout, LPSECURITY_ATTRIBUTES sa )
{
2026 2027 2028 2029 2030 2031 2032
    HANDLE handle = INVALID_HANDLE_VALUE;
    OBJECT_ATTRIBUTES attr;
    UNICODE_STRING nameW;
    LARGE_INTEGER timeout;
    IO_STATUS_BLOCK iosb;
    NTSTATUS status;

2033
    TRACE("%s %d %d %p\n", debugstr_w(lpName),
2034
          nMaxMessageSize, lReadTimeout, sa);
2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055

    if (!RtlDosPathNameToNtPathName_U( lpName, &nameW, NULL, NULL ))
    {
        SetLastError( ERROR_PATH_NOT_FOUND );
        return INVALID_HANDLE_VALUE;
    }

    if (nameW.Length >= MAX_PATH * sizeof(WCHAR) )
    {
        SetLastError( ERROR_FILENAME_EXCED_RANGE );
        RtlFreeUnicodeString( &nameW );
        return INVALID_HANDLE_VALUE;
    }

    attr.Length = sizeof(attr);
    attr.RootDirectory = 0;
    attr.Attributes = OBJ_CASE_INSENSITIVE;
    attr.ObjectName = &nameW;
    attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
    attr.SecurityQualityOfService = NULL;

2056 2057 2058 2059
    if (lReadTimeout != MAILSLOT_WAIT_FOREVER)
        timeout.QuadPart = (ULONGLONG) lReadTimeout * -10000;
    else
        timeout.QuadPart = ((LONGLONG)0x7fffffff << 32) | 0xffffffff;
2060

2061
    status = NtCreateMailslotFile( &handle, GENERIC_READ | SYNCHRONIZE, &attr,
2062 2063 2064 2065 2066 2067 2068 2069 2070
                                   &iosb, 0, 0, nMaxMessageSize, &timeout );
    if (status)
    {
        SetLastError( RtlNtStatusToDosError(status) );
        handle = INVALID_HANDLE_VALUE;
    }

    RtlFreeUnicodeString( &nameW );
    return handle;
2071 2072 2073 2074
}


/******************************************************************************
Jon Griffiths's avatar
Jon Griffiths committed
2075 2076 2077
 * GetMailslotInfo [KERNEL32.@]
 *
 * Retrieve information about a mailslot.
2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093
 *
 * PARAMS
 *    hMailslot        [I] Mailslot handle
 *    lpMaxMessageSize [O] Address of maximum message size
 *    lpNextSize       [O] Address of size of next message
 *    lpMessageCount   [O] Address of number of messages
 *    lpReadTimeout    [O] Address of read time-out
 *
 * RETURNS
 *    Success: TRUE
 *    Failure: FALSE
 */
BOOL WINAPI GetMailslotInfo( HANDLE hMailslot, LPDWORD lpMaxMessageSize,
                               LPDWORD lpNextSize, LPDWORD lpMessageCount,
                               LPDWORD lpReadTimeout )
{
2094 2095 2096
    FILE_MAILSLOT_QUERY_INFORMATION info;
    IO_STATUS_BLOCK iosb;
    NTSTATUS status;
Mike McCormack's avatar
Mike McCormack committed
2097

2098 2099
    TRACE("%p %p %p %p %p\n",hMailslot, lpMaxMessageSize,
          lpNextSize, lpMessageCount, lpReadTimeout);
Mike McCormack's avatar
Mike McCormack committed
2100

2101 2102 2103 2104
    status = NtQueryInformationFile( hMailslot, &iosb, &info, sizeof info,
                                     FileMailslotQueryInformation );

    if( status != STATUS_SUCCESS )
Mike McCormack's avatar
Mike McCormack committed
2105
    {
2106 2107
        SetLastError( RtlNtStatusToDosError(status) );
        return FALSE;
Mike McCormack's avatar
Mike McCormack committed
2108 2109
    }

2110 2111 2112 2113 2114 2115 2116
    if( lpMaxMessageSize )
        *lpMaxMessageSize = info.MaximumMessageSize;
    if( lpNextSize )
        *lpNextSize = info.NextMessageSize;
    if( lpMessageCount )
        *lpMessageCount = info.MessagesAvailable;
    if( lpReadTimeout )
2117 2118 2119 2120 2121 2122
    {
        if (info.ReadTimeout.QuadPart == (((LONGLONG)0x7fffffff << 32) | 0xffffffff))
            *lpReadTimeout = MAILSLOT_WAIT_FOREVER;
        else
            *lpReadTimeout = info.ReadTimeout.QuadPart / -10000;
    }
2123
    return TRUE;
2124 2125 2126 2127
}


/******************************************************************************
Jon Griffiths's avatar
Jon Griffiths committed
2128 2129 2130 2131 2132 2133 2134
 * SetMailslotInfo [KERNEL32.@]
 *
 * Set the read timeout of a mailslot.
 *
 * PARAMS
 *  hMailslot     [I] Mailslot handle
 *  dwReadTimeout [I] Timeout in milliseconds.
2135 2136 2137 2138 2139 2140 2141
 *
 * RETURNS
 *    Success: TRUE
 *    Failure: FALSE
 */
BOOL WINAPI SetMailslotInfo( HANDLE hMailslot, DWORD dwReadTimeout)
{
2142 2143 2144
    FILE_MAILSLOT_SET_INFORMATION info;
    IO_STATUS_BLOCK iosb;
    NTSTATUS status;
Mike McCormack's avatar
Mike McCormack committed
2145

2146
    TRACE("%p %d\n", hMailslot, dwReadTimeout);
Mike McCormack's avatar
Mike McCormack committed
2147

2148 2149 2150 2151
    if (dwReadTimeout != MAILSLOT_WAIT_FOREVER)
        info.ReadTimeout.QuadPart = (ULONGLONG)dwReadTimeout * -10000;
    else
        info.ReadTimeout.QuadPart = ((LONGLONG)0x7fffffff << 32) | 0xffffffff;
2152 2153 2154
    status = NtSetInformationFile( hMailslot, &iosb, &info, sizeof info,
                                   FileMailslotSetInformation );
    if( status != STATUS_SUCCESS )
Mike McCormack's avatar
Mike McCormack committed
2155
    {
2156 2157
        SetLastError( RtlNtStatusToDosError(status) );
        return FALSE;
Mike McCormack's avatar
Mike McCormack committed
2158
    }
2159
    return TRUE;
2160 2161 2162
}


2163 2164 2165 2166
/******************************************************************************
 *		CreateIoCompletionPort (KERNEL32.@)
 */
HANDLE WINAPI CreateIoCompletionPort(HANDLE hFileHandle, HANDLE hExistingCompletionPort,
2167
                                     ULONG_PTR CompletionKey, DWORD dwNumberOfConcurrentThreads)
2168
{
2169 2170 2171 2172
    NTSTATUS status;
    HANDLE ret = 0;

    TRACE("(%p, %p, %08lx, %08x)\n",
2173
          hFileHandle, hExistingCompletionPort, CompletionKey, dwNumberOfConcurrentThreads);
2174

2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207
    if (hExistingCompletionPort && hFileHandle == INVALID_HANDLE_VALUE)
    {
        SetLastError( ERROR_INVALID_PARAMETER);
        return NULL;
    }

    if (hExistingCompletionPort)
        ret = hExistingCompletionPort;
    else
    {
        status = NtCreateIoCompletion( &ret, IO_COMPLETION_ALL_ACCESS, NULL, dwNumberOfConcurrentThreads );
        if (status != STATUS_SUCCESS) goto fail;
    }

    if (hFileHandle != INVALID_HANDLE_VALUE)
    {
        FILE_COMPLETION_INFORMATION info;
        IO_STATUS_BLOCK iosb;

        info.CompletionPort = ret;
        info.CompletionKey = CompletionKey;
        status = NtSetInformationFile( hFileHandle, &iosb, &info, sizeof(info), FileCompletionInformation );
        if (status != STATUS_SUCCESS) goto fail;
    }

    return ret;

fail:
    if (ret && !hExistingCompletionPort)
        CloseHandle( ret );
    SetLastError( RtlNtStatusToDosError(status) );
    return 0;
}
2208 2209 2210 2211 2212

/******************************************************************************
 *		GetQueuedCompletionStatus (KERNEL32.@)
 */
BOOL WINAPI GetQueuedCompletionStatus( HANDLE CompletionPort, LPDWORD lpNumberOfBytesTransferred,
2213
                                       PULONG_PTR pCompletionKey, LPOVERLAPPED *lpOverlapped,
2214 2215
                                       DWORD dwMilliseconds )
{
2216 2217 2218 2219 2220
    NTSTATUS status;
    IO_STATUS_BLOCK iosb;
    LARGE_INTEGER wait_time;

    TRACE("(%p,%p,%p,%p,%d)\n",
2221
          CompletionPort,lpNumberOfBytesTransferred,pCompletionKey,lpOverlapped,dwMilliseconds);
2222 2223 2224 2225 2226 2227 2228 2229

    *lpOverlapped = NULL;

    status = NtRemoveIoCompletion( CompletionPort, pCompletionKey, (PULONG_PTR)lpOverlapped,
                                   &iosb, get_nt_timeout( &wait_time, dwMilliseconds ) );
    if (status == STATUS_SUCCESS)
    {
        *lpNumberOfBytesTransferred = iosb.Information;
2230 2231 2232
        if (iosb.u.Status >= 0) return TRUE;
        SetLastError( RtlNtStatusToDosError(iosb.u.Status) );
        return FALSE;
2233 2234
    }

2235 2236
    if (status == STATUS_TIMEOUT) SetLastError( WAIT_TIMEOUT );
    else SetLastError( RtlNtStatusToDosError(status) );
2237 2238 2239
    return FALSE;
}

2240 2241 2242 2243

/******************************************************************************
 *		PostQueuedCompletionStatus (KERNEL32.@)
 */
2244 2245 2246
BOOL WINAPI PostQueuedCompletionStatus( HANDLE CompletionPort, DWORD dwNumberOfBytes,
                                        ULONG_PTR dwCompletionKey, LPOVERLAPPED lpOverlapped)
{
2247 2248 2249 2250 2251 2252 2253 2254 2255
    NTSTATUS status;

    TRACE("%p %d %08lx %p\n", CompletionPort, dwNumberOfBytes, dwCompletionKey, lpOverlapped );

    status = NtSetIoCompletion( CompletionPort, dwCompletionKey, (ULONG_PTR)lpOverlapped,
                                STATUS_SUCCESS, dwNumberOfBytes );

    if (status == STATUS_SUCCESS) return TRUE;
    SetLastError( RtlNtStatusToDosError(status) );
2256 2257 2258
    return FALSE;
}

2259 2260 2261 2262 2263
/******************************************************************************
 *		BindIoCompletionCallback (KERNEL32.@)
 */
BOOL WINAPI BindIoCompletionCallback( HANDLE FileHandle, LPOVERLAPPED_COMPLETION_ROUTINE Function, ULONG Flags)
{
2264 2265 2266 2267 2268 2269 2270
    NTSTATUS status;

    TRACE("(%p, %p, %d)\n", FileHandle, Function, Flags);

    status = RtlSetIoCompletionCallback( FileHandle, (PRTL_OVERLAPPED_COMPLETION_ROUTINE)Function, Flags );
    if (status == STATUS_SUCCESS) return TRUE;
    SetLastError( RtlNtStatusToDosError(status) );
2271 2272 2273
    return FALSE;
}

2274 2275 2276 2277

/***********************************************************************
 *           CreateMemoryResourceNotification   (KERNEL32.@)
 */
2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316
HANDLE WINAPI CreateMemoryResourceNotification(MEMORY_RESOURCE_NOTIFICATION_TYPE type)
{
    static const WCHAR lowmemW[] =
        {'\\','K','e','r','n','e','l','O','b','j','e','c','t','s',
         '\\','L','o','w','M','e','m','o','r','y','C','o','n','d','i','t','i','o','n',0};
    static const WCHAR highmemW[] =
        {'\\','K','e','r','n','e','l','O','b','j','e','c','t','s',
         '\\','H','i','g','h','M','e','m','o','r','y','C','o','n','d','i','t','i','o','n',0};
    HANDLE ret;
    UNICODE_STRING nameW;
    OBJECT_ATTRIBUTES attr;
    NTSTATUS status;

    switch (type)
    {
    case LowMemoryResourceNotification:
        RtlInitUnicodeString( &nameW, lowmemW );
        break;
    case HighMemoryResourceNotification:
        RtlInitUnicodeString( &nameW, highmemW );
        break;
    default:
        SetLastError( ERROR_INVALID_PARAMETER );
        return 0;
    }

    attr.Length                   = sizeof(attr);
    attr.RootDirectory            = 0;
    attr.ObjectName               = &nameW;
    attr.Attributes               = 0;
    attr.SecurityDescriptor       = NULL;
    attr.SecurityQualityOfService = NULL;
    status = NtOpenEvent( &ret, EVENT_ALL_ACCESS, &attr );
    if (status != STATUS_SUCCESS)
    {
        SetLastError( RtlNtStatusToDosError(status) );
        return 0;
    }
    return ret;
2317 2318
}

2319 2320 2321
/***********************************************************************
 *          QueryMemoryResourceNotification   (KERNEL32.@)
 */
2322
BOOL WINAPI QueryMemoryResourceNotification(HANDLE handle, PBOOL state)
2323
{
2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334
    switch (WaitForSingleObject( handle, 0 ))
    {
    case WAIT_OBJECT_0:
        *state = TRUE;
        return TRUE;
    case WAIT_TIMEOUT:
        *state = FALSE;
        return TRUE;
    }
    SetLastError( ERROR_INVALID_PARAMETER );
    return FALSE;
2335
}
2336

2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365
/***********************************************************************
 *           InitOnceBeginInitialize    (KERNEL32.@)
 */
BOOL WINAPI InitOnceBeginInitialize( INIT_ONCE *once, DWORD flags, BOOL *pending, void **context )
{
    NTSTATUS status = RtlRunOnceBeginInitialize( once, flags, context );
    if (status >= 0) *pending = (status == STATUS_PENDING);
    else SetLastError( RtlNtStatusToDosError(status) );
    return status >= 0;
}

/***********************************************************************
 *           InitOnceComplete    (KERNEL32.@)
 */
BOOL WINAPI InitOnceComplete( INIT_ONCE *once, DWORD flags, void *context )
{
    NTSTATUS status = RtlRunOnceComplete( once, flags, context );
    if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
    return !status;
}

/***********************************************************************
 *           InitOnceExecuteOnce    (KERNEL32.@)
 */
BOOL WINAPI InitOnceExecuteOnce( INIT_ONCE *once, PINIT_ONCE_FN func, void *param, void **context )
{
    return !RtlRunOnceExecuteOnce( once, (PRTL_RUN_ONCE_INIT_FN)func, param, context );
}

2366 2367 2368 2369 2370 2371
#ifdef __i386__

/***********************************************************************
 *		InterlockedCompareExchange (KERNEL32.@)
 */
/* LONG WINAPI InterlockedCompareExchange( PLONG dest, LONG xchg, LONG compare ); */
2372
__ASM_STDCALL_FUNC(InterlockedCompareExchange, 12,
2373 2374 2375 2376
                  "movl 12(%esp),%eax\n\t"
                  "movl 8(%esp),%ecx\n\t"
                  "movl 4(%esp),%edx\n\t"
                  "lock; cmpxchgl %ecx,(%edx)\n\t"
2377
                  "ret $12")
2378 2379 2380 2381 2382

/***********************************************************************
 *		InterlockedExchange (KERNEL32.@)
 */
/* LONG WINAPI InterlockedExchange( PLONG dest, LONG val ); */
2383
__ASM_STDCALL_FUNC(InterlockedExchange, 8,
2384 2385 2386
                  "movl 8(%esp),%eax\n\t"
                  "movl 4(%esp),%edx\n\t"
                  "lock; xchgl %eax,(%edx)\n\t"
2387
                  "ret $8")
2388 2389 2390 2391 2392

/***********************************************************************
 *		InterlockedExchangeAdd (KERNEL32.@)
 */
/* LONG WINAPI InterlockedExchangeAdd( PLONG dest, LONG incr ); */
2393
__ASM_STDCALL_FUNC(InterlockedExchangeAdd, 8,
2394 2395 2396
                  "movl 8(%esp),%eax\n\t"
                  "movl 4(%esp),%edx\n\t"
                  "lock; xaddl %eax,(%edx)\n\t"
2397
                  "ret $8")
2398 2399 2400 2401 2402

/***********************************************************************
 *		InterlockedIncrement (KERNEL32.@)
 */
/* LONG WINAPI InterlockedIncrement( PLONG dest ); */
2403
__ASM_STDCALL_FUNC(InterlockedIncrement, 4,
2404 2405 2406 2407
                  "movl 4(%esp),%edx\n\t"
                  "movl $1,%eax\n\t"
                  "lock; xaddl %eax,(%edx)\n\t"
                  "incl %eax\n\t"
2408
                  "ret $4")
2409 2410 2411 2412

/***********************************************************************
 *		InterlockedDecrement (KERNEL32.@)
 */
2413
__ASM_STDCALL_FUNC(InterlockedDecrement, 4,
2414 2415 2416 2417
                  "movl 4(%esp),%edx\n\t"
                  "movl $-1,%eax\n\t"
                  "lock; xaddl %eax,(%edx)\n\t"
                  "decl %eax\n\t"
2418
                  "ret $4")
2419 2420

#endif  /* __i386__ */
2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438

/***********************************************************************
 *           SleepConditionVariableCS   (KERNEL32.@)
 */
BOOL WINAPI SleepConditionVariableCS( CONDITION_VARIABLE *variable, CRITICAL_SECTION *crit, DWORD timeout )
{
    NTSTATUS status;
    LARGE_INTEGER time;

    status = RtlSleepConditionVariableCS( variable, crit, get_nt_timeout( &time, timeout ) );

    if (status != STATUS_SUCCESS)
    {
        SetLastError( RtlNtStatusToDosError(status) );
        return FALSE;
    }
    return TRUE;
}
2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456

/***********************************************************************
 *           SleepConditionVariableSRW   (KERNEL32.@)
 */
BOOL WINAPI SleepConditionVariableSRW( RTL_CONDITION_VARIABLE *variable, RTL_SRWLOCK *lock, DWORD timeout, ULONG flags )
{
    NTSTATUS status;
    LARGE_INTEGER time;

    status = RtlSleepConditionVariableSRW( variable, lock, get_nt_timeout( &time, timeout ), flags );

    if (status != STATUS_SUCCESS)
    {
        SetLastError( RtlNtStatusToDosError(status) );
        return FALSE;
    }
    return TRUE;
}