Release 1.5.29.
[wine] / dlls / kernel32 / sync.c
1 /*
2  * Kernel synchronization objects
3  *
4  * Copyright 1998 Alexandre Julliard
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * 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 #ifdef HAVE_UNISTD_H
26 # include <unistd.h>
27 #endif
28 #include <errno.h>
29 #include <stdarg.h>
30 #include <stdio.h>
31
32 #define NONAMELESSUNION
33 #define NONAMELESSSTRUCT
34
35 #include "ntstatus.h"
36 #define WIN32_NO_STATUS
37 #include "windef.h"
38 #include "winbase.h"
39 #include "winerror.h"
40 #include "winnls.h"
41 #include "winternl.h"
42 #include "winioctl.h"
43 #include "ddk/wdm.h"
44
45 #include "wine/unicode.h"
46 #include "kernel_private.h"
47
48 #include "wine/debug.h"
49
50 WINE_DEFAULT_DEBUG_CHANNEL(sync);
51
52 /* check if current version is NT or Win95 */
53 static inline int is_version_nt(void)
54 {
55     return !(GetVersion() & 0x80000000);
56 }
57
58 /* returns directory handle to \\BaseNamedObjects */
59 HANDLE get_BaseNamedObjects_handle(void)
60 {
61     static HANDLE handle = NULL;
62     static const WCHAR basenameW[] =
63         {'\\','B','a','s','e','N','a','m','e','d','O','b','j','e','c','t','s',0};
64     UNICODE_STRING str;
65     OBJECT_ATTRIBUTES attr;
66
67     if (!handle)
68     {
69         HANDLE dir;
70
71         RtlInitUnicodeString(&str, basenameW);
72         InitializeObjectAttributes(&attr, &str, 0, 0, NULL);
73         NtOpenDirectoryObject(&dir, DIRECTORY_CREATE_OBJECT|DIRECTORY_TRAVERSE,
74                               &attr);
75         if (InterlockedCompareExchangePointer( &handle, dir, 0 ) != 0)
76         {
77             /* someone beat us here... */
78             CloseHandle( dir );
79         }
80     }
81     return handle;
82 }
83
84 /* helper for kernel32->ntdll timeout format conversion */
85 static inline PLARGE_INTEGER get_nt_timeout( PLARGE_INTEGER pTime, DWORD timeout )
86 {
87     if (timeout == INFINITE) return NULL;
88     pTime->QuadPart = (ULONGLONG)timeout * -10000;
89     return pTime;
90 }
91
92 /***********************************************************************
93  *              Sleep  (KERNEL32.@)
94  */
95 VOID WINAPI DECLSPEC_HOTPATCH Sleep( DWORD timeout )
96 {
97     SleepEx( timeout, FALSE );
98 }
99
100 /******************************************************************************
101  *              SleepEx   (KERNEL32.@)
102  */
103 DWORD WINAPI SleepEx( DWORD timeout, BOOL alertable )
104 {
105     NTSTATUS status;
106     LARGE_INTEGER time;
107
108     status = NtDelayExecution( alertable, get_nt_timeout( &time, timeout ) );
109     if (status == STATUS_USER_APC) return WAIT_IO_COMPLETION;
110     return 0;
111 }
112
113
114 /***********************************************************************
115  *              SwitchToThread (KERNEL32.@)
116  */
117 BOOL WINAPI SwitchToThread(void)
118 {
119     return (NtYieldExecution() != STATUS_NO_YIELD_PERFORMED);
120 }
121
122
123 /***********************************************************************
124  *           WaitForSingleObject   (KERNEL32.@)
125  */
126 DWORD WINAPI WaitForSingleObject( HANDLE handle, DWORD timeout )
127 {
128     return WaitForMultipleObjectsEx( 1, &handle, FALSE, timeout, FALSE );
129 }
130
131
132 /***********************************************************************
133  *           WaitForSingleObjectEx   (KERNEL32.@)
134  */
135 DWORD WINAPI WaitForSingleObjectEx( HANDLE handle, DWORD timeout,
136                                     BOOL alertable )
137 {
138     return WaitForMultipleObjectsEx( 1, &handle, FALSE, timeout, alertable );
139 }
140
141
142 /***********************************************************************
143  *           WaitForMultipleObjects   (KERNEL32.@)
144  */
145 DWORD WINAPI WaitForMultipleObjects( DWORD count, const HANDLE *handles,
146                                      BOOL wait_all, DWORD timeout )
147 {
148     return WaitForMultipleObjectsEx( count, handles, wait_all, timeout, FALSE );
149 }
150
151
152 /***********************************************************************
153  *           WaitForMultipleObjectsEx   (KERNEL32.@)
154  */
155 DWORD WINAPI WaitForMultipleObjectsEx( DWORD count, const HANDLE *handles,
156                                        BOOL wait_all, DWORD timeout,
157                                        BOOL alertable )
158 {
159     NTSTATUS status;
160     HANDLE hloc[MAXIMUM_WAIT_OBJECTS];
161     LARGE_INTEGER time;
162     unsigned int i;
163
164     if (count > MAXIMUM_WAIT_OBJECTS)
165     {
166         SetLastError(ERROR_INVALID_PARAMETER);
167         return WAIT_FAILED;
168     }
169     for (i = 0; i < count; i++)
170     {
171         if ((handles[i] == (HANDLE)STD_INPUT_HANDLE) ||
172             (handles[i] == (HANDLE)STD_OUTPUT_HANDLE) ||
173             (handles[i] == (HANDLE)STD_ERROR_HANDLE))
174             hloc[i] = GetStdHandle( HandleToULong(handles[i]) );
175         else
176             hloc[i] = handles[i];
177
178         /* yes, even screen buffer console handles are waitable, and are
179          * handled as a handle to the console itself !!
180          */
181         if (is_console_handle(hloc[i]))
182         {
183             if (VerifyConsoleIoHandle(hloc[i]))
184                 hloc[i] = GetConsoleInputWaitHandle();
185         }
186     }
187
188     status = NtWaitForMultipleObjects( count, hloc, wait_all, alertable,
189                                        get_nt_timeout( &time, timeout ) );
190
191     if (HIWORD(status))  /* is it an error code? */
192     {
193         SetLastError( RtlNtStatusToDosError(status) );
194         status = WAIT_FAILED;
195     }
196     return status;
197 }
198
199
200 /***********************************************************************
201  *           RegisterWaitForSingleObject   (KERNEL32.@)
202  */
203 BOOL WINAPI RegisterWaitForSingleObject(PHANDLE phNewWaitObject, HANDLE hObject,
204                 WAITORTIMERCALLBACK Callback, PVOID Context,
205                 ULONG dwMilliseconds, ULONG dwFlags)
206 {
207     NTSTATUS status;
208
209     TRACE("%p %p %p %p %d %d\n",
210           phNewWaitObject,hObject,Callback,Context,dwMilliseconds,dwFlags);
211
212     status = RtlRegisterWait( phNewWaitObject, hObject, Callback, Context, dwMilliseconds, dwFlags );
213     if (status != STATUS_SUCCESS)
214     {
215         SetLastError( RtlNtStatusToDosError(status) );
216         return FALSE;
217     }
218     return TRUE;
219 }
220
221 /***********************************************************************
222  *           RegisterWaitForSingleObjectEx   (KERNEL32.@)
223  */
224 HANDLE WINAPI RegisterWaitForSingleObjectEx( HANDLE hObject, 
225                 WAITORTIMERCALLBACK Callback, PVOID Context,
226                 ULONG dwMilliseconds, ULONG dwFlags ) 
227 {
228     NTSTATUS status;
229     HANDLE hNewWaitObject;
230
231     TRACE("%p %p %p %d %d\n",
232           hObject,Callback,Context,dwMilliseconds,dwFlags);
233
234     status = RtlRegisterWait( &hNewWaitObject, hObject, Callback, Context, dwMilliseconds, dwFlags );
235     if (status != STATUS_SUCCESS)
236     {
237         SetLastError( RtlNtStatusToDosError(status) );
238         return NULL;
239     }
240     return hNewWaitObject;
241 }
242
243 /***********************************************************************
244  *           UnregisterWait   (KERNEL32.@)
245  */
246 BOOL WINAPI UnregisterWait( HANDLE WaitHandle ) 
247 {
248     NTSTATUS status;
249
250     TRACE("%p\n",WaitHandle);
251
252     status = RtlDeregisterWait( WaitHandle );
253     if (status != STATUS_SUCCESS)
254     {
255         SetLastError( RtlNtStatusToDosError(status) );
256         return FALSE;
257     }
258     return TRUE;
259 }
260
261 /***********************************************************************
262  *           UnregisterWaitEx   (KERNEL32.@)
263  */
264 BOOL WINAPI UnregisterWaitEx( HANDLE WaitHandle, HANDLE CompletionEvent ) 
265 {
266     NTSTATUS status;
267
268     TRACE("%p %p\n",WaitHandle, CompletionEvent);
269
270     status = RtlDeregisterWaitEx( WaitHandle, CompletionEvent );
271     if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
272     return !status;
273 }
274
275 /***********************************************************************
276  *           SignalObjectAndWait  (KERNEL32.@)
277  *
278  * Makes it possible to atomically signal any of the synchronization
279  * objects (semaphore, mutex, event) and wait on another.
280  */
281 DWORD WINAPI SignalObjectAndWait( HANDLE hObjectToSignal, HANDLE hObjectToWaitOn,
282                                   DWORD dwMilliseconds, BOOL bAlertable )
283 {
284     NTSTATUS status;
285     LARGE_INTEGER timeout;
286
287     TRACE("%p %p %d %d\n", hObjectToSignal,
288           hObjectToWaitOn, dwMilliseconds, bAlertable);
289
290     status = NtSignalAndWaitForSingleObject( hObjectToSignal, hObjectToWaitOn, bAlertable,
291                                              get_nt_timeout( &timeout, dwMilliseconds ) );
292     if (HIWORD(status))
293     {
294         SetLastError( RtlNtStatusToDosError(status) );
295         status = WAIT_FAILED;
296     }
297     return status;
298 }
299
300 /***********************************************************************
301  *           InitializeCriticalSection   (KERNEL32.@)
302  *
303  * Initialise a critical section before use.
304  *
305  * PARAMS
306  *  crit [O] Critical section to initialise.
307  *
308  * RETURNS
309  *  Nothing. If the function fails an exception is raised.
310  */
311 void WINAPI InitializeCriticalSection( CRITICAL_SECTION *crit )
312 {
313     InitializeCriticalSectionEx( crit, 0, 0 );
314 }
315
316 /***********************************************************************
317  *           InitializeCriticalSectionAndSpinCount   (KERNEL32.@)
318  *
319  * Initialise a critical section with a spin count.
320  *
321  * PARAMS
322  *  crit      [O] Critical section to initialise.
323  *  spincount [I] Number of times to spin upon contention.
324  *
325  * RETURNS
326  *  Success: TRUE.
327  *  Failure: Nothing. If the function fails an exception is raised.
328  *
329  * NOTES
330  *  spincount is ignored on uni-processor systems.
331  */
332 BOOL WINAPI InitializeCriticalSectionAndSpinCount( CRITICAL_SECTION *crit, DWORD spincount )
333 {
334     return InitializeCriticalSectionEx( crit, spincount, 0 );
335 }
336
337 /***********************************************************************
338  *           InitializeCriticalSectionEx   (KERNEL32.@)
339  *
340  * Initialise a critical section with a spin count and flags.
341  *
342  * PARAMS
343  *  crit      [O] Critical section to initialise.
344  *  spincount [I] Number of times to spin upon contention.
345  *  flags     [I] CRITICAL_SECTION_ flags from winbase.h.
346  *
347  * RETURNS
348  *  Success: TRUE.
349  *  Failure: Nothing. If the function fails an exception is raised.
350  *
351  * NOTES
352  *  spincount is ignored on uni-processor systems.
353  */
354 BOOL WINAPI InitializeCriticalSectionEx( CRITICAL_SECTION *crit, DWORD spincount, DWORD flags )
355 {
356     NTSTATUS ret = RtlInitializeCriticalSectionEx( crit, spincount, flags );
357     if (ret) RtlRaiseStatus( ret );
358     return !ret;
359 }
360
361 /***********************************************************************
362  *           MakeCriticalSectionGlobal   (KERNEL32.@)
363  */
364 void WINAPI MakeCriticalSectionGlobal( CRITICAL_SECTION *crit )
365 {
366     /* let's assume that only one thread at a time will try to do this */
367     HANDLE sem = crit->LockSemaphore;
368     if (!sem) NtCreateSemaphore( &sem, SEMAPHORE_ALL_ACCESS, NULL, 0, 1 );
369     crit->LockSemaphore = ConvertToGlobalHandle( sem );
370     RtlFreeHeap( GetProcessHeap(), 0, crit->DebugInfo );
371     crit->DebugInfo = NULL;
372 }
373
374
375 /***********************************************************************
376  *           ReinitializeCriticalSection   (KERNEL32.@)
377  *
378  * Initialise an already used critical section.
379  *
380  * PARAMS
381  *  crit [O] Critical section to initialise.
382  *
383  * RETURNS
384  *  Nothing.
385  */
386 void WINAPI ReinitializeCriticalSection( CRITICAL_SECTION *crit )
387 {
388     if ( !crit->LockSemaphore )
389         RtlInitializeCriticalSection( crit );
390 }
391
392
393 /***********************************************************************
394  *           UninitializeCriticalSection   (KERNEL32.@)
395  *
396  * UnInitialise a critical section after use.
397  *
398  * PARAMS
399  *  crit [O] Critical section to uninitialise (destroy).
400  *
401  * RETURNS
402  *  Nothing.
403  */
404 void WINAPI UninitializeCriticalSection( CRITICAL_SECTION *crit )
405 {
406     RtlDeleteCriticalSection( crit );
407 }
408
409
410 /***********************************************************************
411  *           CreateEventA    (KERNEL32.@)
412  */
413 HANDLE WINAPI DECLSPEC_HOTPATCH CreateEventA( SECURITY_ATTRIBUTES *sa, BOOL manual_reset,
414                                               BOOL initial_state, LPCSTR name )
415 {
416     DWORD flags = 0;
417
418     if (manual_reset) flags |= CREATE_EVENT_MANUAL_RESET;
419     if (initial_state) flags |= CREATE_EVENT_INITIAL_SET;
420     return CreateEventExA( sa, name, flags, EVENT_ALL_ACCESS );
421 }
422
423
424 /***********************************************************************
425  *           CreateEventW    (KERNEL32.@)
426  */
427 HANDLE WINAPI DECLSPEC_HOTPATCH CreateEventW( SECURITY_ATTRIBUTES *sa, BOOL manual_reset,
428                                               BOOL initial_state, LPCWSTR name )
429 {
430     DWORD flags = 0;
431
432     if (manual_reset) flags |= CREATE_EVENT_MANUAL_RESET;
433     if (initial_state) flags |= CREATE_EVENT_INITIAL_SET;
434     return CreateEventExW( sa, name, flags, EVENT_ALL_ACCESS );
435 }
436
437
438 /***********************************************************************
439  *           CreateEventExA    (KERNEL32.@)
440  */
441 HANDLE WINAPI DECLSPEC_HOTPATCH CreateEventExA( SECURITY_ATTRIBUTES *sa, LPCSTR name, DWORD flags, DWORD access )
442 {
443     WCHAR buffer[MAX_PATH];
444
445     if (!name) return CreateEventExW( sa, NULL, flags, access );
446
447     if (!MultiByteToWideChar( CP_ACP, 0, name, -1, buffer, MAX_PATH ))
448     {
449         SetLastError( ERROR_FILENAME_EXCED_RANGE );
450         return 0;
451     }
452     return CreateEventExW( sa, buffer, flags, access );
453 }
454
455
456 /***********************************************************************
457  *           CreateEventExW    (KERNEL32.@)
458  */
459 HANDLE WINAPI DECLSPEC_HOTPATCH CreateEventExW( SECURITY_ATTRIBUTES *sa, LPCWSTR name, DWORD flags, DWORD access )
460 {
461     HANDLE ret;
462     UNICODE_STRING nameW;
463     OBJECT_ATTRIBUTES attr;
464     NTSTATUS status;
465
466     /* one buggy program needs this
467      * ("Van Dale Groot woordenboek der Nederlandse taal")
468      */
469     if (sa && IsBadReadPtr(sa,sizeof(SECURITY_ATTRIBUTES)))
470     {
471         ERR("Bad security attributes pointer %p\n",sa);
472         SetLastError( ERROR_INVALID_PARAMETER);
473         return 0;
474     }
475
476     attr.Length                   = sizeof(attr);
477     attr.RootDirectory            = 0;
478     attr.ObjectName               = NULL;
479     attr.Attributes               = OBJ_OPENIF | ((sa && sa->bInheritHandle) ? OBJ_INHERIT : 0);
480     attr.SecurityDescriptor       = sa ? sa->lpSecurityDescriptor : NULL;
481     attr.SecurityQualityOfService = NULL;
482     if (name)
483     {
484         RtlInitUnicodeString( &nameW, name );
485         attr.ObjectName = &nameW;
486         attr.RootDirectory = get_BaseNamedObjects_handle();
487     }
488
489     status = NtCreateEvent( &ret, access, &attr,
490                             (flags & CREATE_EVENT_MANUAL_RESET) ? NotificationEvent : SynchronizationEvent,
491                             (flags & CREATE_EVENT_INITIAL_SET) != 0 );
492     if (status == STATUS_OBJECT_NAME_EXISTS)
493         SetLastError( ERROR_ALREADY_EXISTS );
494     else
495         SetLastError( RtlNtStatusToDosError(status) );
496     return ret;
497 }
498
499
500 /***********************************************************************
501  *           OpenEventA    (KERNEL32.@)
502  */
503 HANDLE WINAPI DECLSPEC_HOTPATCH OpenEventA( DWORD access, BOOL inherit, LPCSTR name )
504 {
505     WCHAR buffer[MAX_PATH];
506
507     if (!name) return OpenEventW( access, inherit, NULL );
508
509     if (!MultiByteToWideChar( CP_ACP, 0, name, -1, buffer, MAX_PATH ))
510     {
511         SetLastError( ERROR_FILENAME_EXCED_RANGE );
512         return 0;
513     }
514     return OpenEventW( access, inherit, buffer );
515 }
516
517
518 /***********************************************************************
519  *           OpenEventW    (KERNEL32.@)
520  */
521 HANDLE WINAPI DECLSPEC_HOTPATCH OpenEventW( DWORD access, BOOL inherit, LPCWSTR name )
522 {
523     HANDLE ret;
524     UNICODE_STRING nameW;
525     OBJECT_ATTRIBUTES attr;
526     NTSTATUS status;
527
528     if (!is_version_nt()) access = EVENT_ALL_ACCESS;
529
530     attr.Length                   = sizeof(attr);
531     attr.RootDirectory            = 0;
532     attr.ObjectName               = NULL;
533     attr.Attributes               = inherit ? OBJ_INHERIT : 0;
534     attr.SecurityDescriptor       = NULL;
535     attr.SecurityQualityOfService = NULL;
536     if (name)
537     {
538         RtlInitUnicodeString( &nameW, name );
539         attr.ObjectName = &nameW;
540         attr.RootDirectory = get_BaseNamedObjects_handle();
541     }
542
543     status = NtOpenEvent( &ret, access, &attr );
544     if (status != STATUS_SUCCESS)
545     {
546         SetLastError( RtlNtStatusToDosError(status) );
547         return 0;
548     }
549     return ret;
550 }
551
552 /***********************************************************************
553  *           PulseEvent    (KERNEL32.@)
554  */
555 BOOL WINAPI DECLSPEC_HOTPATCH PulseEvent( HANDLE handle )
556 {
557     NTSTATUS status;
558
559     if ((status = NtPulseEvent( handle, NULL )))
560         SetLastError( RtlNtStatusToDosError(status) );
561     return !status;
562 }
563
564
565 /***********************************************************************
566  *           SetEvent    (KERNEL32.@)
567  */
568 BOOL WINAPI DECLSPEC_HOTPATCH SetEvent( HANDLE handle )
569 {
570     NTSTATUS status;
571
572     if ((status = NtSetEvent( handle, NULL )))
573         SetLastError( RtlNtStatusToDosError(status) );
574     return !status;
575 }
576
577
578 /***********************************************************************
579  *           ResetEvent    (KERNEL32.@)
580  */
581 BOOL WINAPI DECLSPEC_HOTPATCH ResetEvent( HANDLE handle )
582 {
583     NTSTATUS status;
584
585     if ((status = NtResetEvent( handle, NULL )))
586         SetLastError( RtlNtStatusToDosError(status) );
587     return !status;
588 }
589
590
591 /***********************************************************************
592  *           CreateMutexA   (KERNEL32.@)
593  */
594 HANDLE WINAPI DECLSPEC_HOTPATCH CreateMutexA( SECURITY_ATTRIBUTES *sa, BOOL owner, LPCSTR name )
595 {
596     return CreateMutexExA( sa, name, owner ? CREATE_MUTEX_INITIAL_OWNER : 0, MUTEX_ALL_ACCESS );
597 }
598
599
600 /***********************************************************************
601  *           CreateMutexW   (KERNEL32.@)
602  */
603 HANDLE WINAPI DECLSPEC_HOTPATCH CreateMutexW( SECURITY_ATTRIBUTES *sa, BOOL owner, LPCWSTR name )
604 {
605     return CreateMutexExW( sa, name, owner ? CREATE_MUTEX_INITIAL_OWNER : 0, MUTEX_ALL_ACCESS );
606 }
607
608
609 /***********************************************************************
610  *           CreateMutexExA   (KERNEL32.@)
611  */
612 HANDLE WINAPI DECLSPEC_HOTPATCH CreateMutexExA( SECURITY_ATTRIBUTES *sa, LPCSTR name, DWORD flags, DWORD access )
613 {
614     ANSI_STRING nameA;
615     NTSTATUS status;
616
617     if (!name) return CreateMutexExW( sa, NULL, flags, access );
618
619     RtlInitAnsiString( &nameA, name );
620     status = RtlAnsiStringToUnicodeString( &NtCurrentTeb()->StaticUnicodeString, &nameA, FALSE );
621     if (status != STATUS_SUCCESS)
622     {
623         SetLastError( ERROR_FILENAME_EXCED_RANGE );
624         return 0;
625     }
626     return CreateMutexExW( sa, NtCurrentTeb()->StaticUnicodeString.Buffer, flags, access );
627 }
628
629
630 /***********************************************************************
631  *           CreateMutexExW   (KERNEL32.@)
632  */
633 HANDLE WINAPI DECLSPEC_HOTPATCH CreateMutexExW( SECURITY_ATTRIBUTES *sa, LPCWSTR name, DWORD flags, DWORD access )
634 {
635     HANDLE ret;
636     UNICODE_STRING nameW;
637     OBJECT_ATTRIBUTES attr;
638     NTSTATUS status;
639
640     attr.Length                   = sizeof(attr);
641     attr.RootDirectory            = 0;
642     attr.ObjectName               = NULL;
643     attr.Attributes               = OBJ_OPENIF | ((sa && sa->bInheritHandle) ? OBJ_INHERIT : 0);
644     attr.SecurityDescriptor       = sa ? sa->lpSecurityDescriptor : NULL;
645     attr.SecurityQualityOfService = NULL;
646     if (name)
647     {
648         RtlInitUnicodeString( &nameW, name );
649         attr.ObjectName = &nameW;
650         attr.RootDirectory = get_BaseNamedObjects_handle();
651     }
652
653     status = NtCreateMutant( &ret, access, &attr, (flags & CREATE_MUTEX_INITIAL_OWNER) != 0 );
654     if (status == STATUS_OBJECT_NAME_EXISTS)
655         SetLastError( ERROR_ALREADY_EXISTS );
656     else
657         SetLastError( RtlNtStatusToDosError(status) );
658     return ret;
659 }
660
661
662 /***********************************************************************
663  *           OpenMutexA   (KERNEL32.@)
664  */
665 HANDLE WINAPI DECLSPEC_HOTPATCH OpenMutexA( DWORD access, BOOL inherit, LPCSTR name )
666 {
667     WCHAR buffer[MAX_PATH];
668
669     if (!name) return OpenMutexW( access, inherit, NULL );
670
671     if (!MultiByteToWideChar( CP_ACP, 0, name, -1, buffer, MAX_PATH ))
672     {
673         SetLastError( ERROR_FILENAME_EXCED_RANGE );
674         return 0;
675     }
676     return OpenMutexW( access, inherit, buffer );
677 }
678
679
680 /***********************************************************************
681  *           OpenMutexW   (KERNEL32.@)
682  */
683 HANDLE WINAPI DECLSPEC_HOTPATCH OpenMutexW( DWORD access, BOOL inherit, LPCWSTR name )
684 {
685     HANDLE ret;
686     UNICODE_STRING nameW;
687     OBJECT_ATTRIBUTES attr;
688     NTSTATUS status;
689
690     if (!is_version_nt()) access = MUTEX_ALL_ACCESS;
691
692     attr.Length                   = sizeof(attr);
693     attr.RootDirectory            = 0;
694     attr.ObjectName               = NULL;
695     attr.Attributes               = inherit ? OBJ_INHERIT : 0;
696     attr.SecurityDescriptor       = NULL;
697     attr.SecurityQualityOfService = NULL;
698     if (name)
699     {
700         RtlInitUnicodeString( &nameW, name );
701         attr.ObjectName = &nameW;
702         attr.RootDirectory = get_BaseNamedObjects_handle();
703     }
704
705     status = NtOpenMutant( &ret, access, &attr );
706     if (status != STATUS_SUCCESS)
707     {
708         SetLastError( RtlNtStatusToDosError(status) );
709         return 0;
710     }
711     return ret;
712 }
713
714
715 /***********************************************************************
716  *           ReleaseMutex   (KERNEL32.@)
717  */
718 BOOL WINAPI DECLSPEC_HOTPATCH ReleaseMutex( HANDLE handle )
719 {
720     NTSTATUS    status;
721
722     status = NtReleaseMutant(handle, NULL);
723     if (status != STATUS_SUCCESS)
724     {
725         SetLastError( RtlNtStatusToDosError(status) );
726         return FALSE;
727     }
728     return TRUE;
729 }
730
731
732 /*
733  * Semaphores
734  */
735
736
737 /***********************************************************************
738  *           CreateSemaphoreA   (KERNEL32.@)
739  */
740 HANDLE WINAPI DECLSPEC_HOTPATCH CreateSemaphoreA( SECURITY_ATTRIBUTES *sa, LONG initial, LONG max, LPCSTR name )
741 {
742     return CreateSemaphoreExA( sa, initial, max, name, 0, SEMAPHORE_ALL_ACCESS );
743 }
744
745
746 /***********************************************************************
747  *           CreateSemaphoreW   (KERNEL32.@)
748  */
749 HANDLE WINAPI DECLSPEC_HOTPATCH CreateSemaphoreW( SECURITY_ATTRIBUTES *sa, LONG initial, LONG max, LPCWSTR name )
750 {
751     return CreateSemaphoreExW( sa, initial, max, name, 0, SEMAPHORE_ALL_ACCESS );
752 }
753
754
755 /***********************************************************************
756  *           CreateSemaphoreExA   (KERNEL32.@)
757  */
758 HANDLE WINAPI DECLSPEC_HOTPATCH CreateSemaphoreExA( SECURITY_ATTRIBUTES *sa, LONG initial, LONG max,
759                                                     LPCSTR name, DWORD flags, DWORD access )
760 {
761     WCHAR buffer[MAX_PATH];
762
763     if (!name) return CreateSemaphoreExW( sa, initial, max, NULL, flags, access );
764
765     if (!MultiByteToWideChar( CP_ACP, 0, name, -1, buffer, MAX_PATH ))
766     {
767         SetLastError( ERROR_FILENAME_EXCED_RANGE );
768         return 0;
769     }
770     return CreateSemaphoreExW( sa, initial, max, buffer, flags, access );
771 }
772
773
774 /***********************************************************************
775  *           CreateSemaphoreExW   (KERNEL32.@)
776  */
777 HANDLE WINAPI DECLSPEC_HOTPATCH CreateSemaphoreExW( SECURITY_ATTRIBUTES *sa, LONG initial, LONG max,
778                                                     LPCWSTR name, DWORD flags, DWORD access )
779 {
780     HANDLE ret;
781     UNICODE_STRING nameW;
782     OBJECT_ATTRIBUTES attr;
783     NTSTATUS status;
784
785     attr.Length                   = sizeof(attr);
786     attr.RootDirectory            = 0;
787     attr.ObjectName               = NULL;
788     attr.Attributes               = OBJ_OPENIF | ((sa && sa->bInheritHandle) ? OBJ_INHERIT : 0);
789     attr.SecurityDescriptor       = sa ? sa->lpSecurityDescriptor : NULL;
790     attr.SecurityQualityOfService = NULL;
791     if (name)
792     {
793         RtlInitUnicodeString( &nameW, name );
794         attr.ObjectName = &nameW;
795         attr.RootDirectory = get_BaseNamedObjects_handle();
796     }
797
798     status = NtCreateSemaphore( &ret, access, &attr, initial, max );
799     if (status == STATUS_OBJECT_NAME_EXISTS)
800         SetLastError( ERROR_ALREADY_EXISTS );
801     else
802         SetLastError( RtlNtStatusToDosError(status) );
803     return ret;
804 }
805
806
807 /***********************************************************************
808  *           OpenSemaphoreA   (KERNEL32.@)
809  */
810 HANDLE WINAPI DECLSPEC_HOTPATCH OpenSemaphoreA( DWORD access, BOOL inherit, LPCSTR name )
811 {
812     WCHAR buffer[MAX_PATH];
813
814     if (!name) return OpenSemaphoreW( access, inherit, NULL );
815
816     if (!MultiByteToWideChar( CP_ACP, 0, name, -1, buffer, MAX_PATH ))
817     {
818         SetLastError( ERROR_FILENAME_EXCED_RANGE );
819         return 0;
820     }
821     return OpenSemaphoreW( access, inherit, buffer );
822 }
823
824
825 /***********************************************************************
826  *           OpenSemaphoreW   (KERNEL32.@)
827  */
828 HANDLE WINAPI DECLSPEC_HOTPATCH OpenSemaphoreW( DWORD access, BOOL inherit, LPCWSTR name )
829 {
830     HANDLE ret;
831     UNICODE_STRING nameW;
832     OBJECT_ATTRIBUTES attr;
833     NTSTATUS status;
834
835     if (!is_version_nt()) access = SEMAPHORE_ALL_ACCESS;
836
837     attr.Length                   = sizeof(attr);
838     attr.RootDirectory            = 0;
839     attr.ObjectName               = NULL;
840     attr.Attributes               = inherit ? OBJ_INHERIT : 0;
841     attr.SecurityDescriptor       = NULL;
842     attr.SecurityQualityOfService = NULL;
843     if (name)
844     {
845         RtlInitUnicodeString( &nameW, name );
846         attr.ObjectName = &nameW;
847         attr.RootDirectory = get_BaseNamedObjects_handle();
848     }
849
850     status = NtOpenSemaphore( &ret, access, &attr );
851     if (status != STATUS_SUCCESS)
852     {
853         SetLastError( RtlNtStatusToDosError(status) );
854         return 0;
855     }
856     return ret;
857 }
858
859
860 /***********************************************************************
861  *           ReleaseSemaphore   (KERNEL32.@)
862  */
863 BOOL WINAPI DECLSPEC_HOTPATCH ReleaseSemaphore( HANDLE handle, LONG count, LONG *previous )
864 {
865     NTSTATUS status = NtReleaseSemaphore( handle, count, (PULONG)previous );
866     if (status) SetLastError( RtlNtStatusToDosError(status) );
867     return !status;
868 }
869
870
871 /*
872  * Jobs
873  */
874
875 /******************************************************************************
876  *              CreateJobObjectW (KERNEL32.@)
877  */
878 HANDLE WINAPI CreateJobObjectW( LPSECURITY_ATTRIBUTES sa, LPCWSTR name )
879 {
880     HANDLE ret = 0;
881     UNICODE_STRING nameW;
882     OBJECT_ATTRIBUTES attr;
883     NTSTATUS status;
884
885     attr.Length                   = sizeof(attr);
886     attr.RootDirectory            = 0;
887     attr.ObjectName               = NULL;
888     attr.Attributes               = OBJ_OPENIF | ((sa && sa->bInheritHandle) ? OBJ_INHERIT : 0);
889     attr.SecurityDescriptor       = sa ? sa->lpSecurityDescriptor : NULL;
890     attr.SecurityQualityOfService = NULL;
891     if (name)
892     {
893         RtlInitUnicodeString( &nameW, name );
894         attr.ObjectName = &nameW;
895         attr.RootDirectory = get_BaseNamedObjects_handle();
896     }
897
898     status = NtCreateJobObject( &ret, JOB_OBJECT_ALL_ACCESS, &attr );
899     if (status == STATUS_OBJECT_NAME_EXISTS)
900         SetLastError( ERROR_ALREADY_EXISTS );
901     else
902         SetLastError( RtlNtStatusToDosError(status) );
903     return ret;
904 }
905
906 /******************************************************************************
907  *              CreateJobObjectA (KERNEL32.@)
908  */
909 HANDLE WINAPI CreateJobObjectA( LPSECURITY_ATTRIBUTES attr, LPCSTR name )
910 {
911     WCHAR buffer[MAX_PATH];
912
913     if (!name) return CreateJobObjectW( attr, NULL );
914
915     if (!MultiByteToWideChar( CP_ACP, 0, name, -1, buffer, MAX_PATH ))
916     {
917         SetLastError( ERROR_FILENAME_EXCED_RANGE );
918         return 0;
919     }
920     return CreateJobObjectW( attr, buffer );
921 }
922
923 /******************************************************************************
924  *              OpenJobObjectW (KERNEL32.@)
925  */
926 HANDLE WINAPI OpenJobObjectW( DWORD access, BOOL inherit, LPCWSTR name )
927 {
928     HANDLE ret;
929     UNICODE_STRING nameW;
930     OBJECT_ATTRIBUTES attr;
931     NTSTATUS status;
932
933     attr.Length                   = sizeof(attr);
934     attr.RootDirectory            = 0;
935     attr.ObjectName               = NULL;
936     attr.Attributes               = inherit ? OBJ_INHERIT : 0;
937     attr.SecurityDescriptor       = NULL;
938     attr.SecurityQualityOfService = NULL;
939     if (name)
940     {
941         RtlInitUnicodeString( &nameW, name );
942         attr.ObjectName = &nameW;
943         attr.RootDirectory = get_BaseNamedObjects_handle();
944     }
945
946     status = NtOpenJobObject( &ret, access, &attr );
947     if (status != STATUS_SUCCESS)
948     {
949         SetLastError( RtlNtStatusToDosError(status) );
950         return 0;
951     }
952     return ret;
953 }
954
955 /******************************************************************************
956  *              OpenJobObjectA (KERNEL32.@)
957  */
958 HANDLE WINAPI OpenJobObjectA( DWORD access, BOOL inherit, LPCSTR name )
959 {
960     WCHAR buffer[MAX_PATH];
961
962     if (!name) return OpenJobObjectW( access, inherit, NULL );
963
964     if (!MultiByteToWideChar( CP_ACP, 0, name, -1, buffer, MAX_PATH ))
965     {
966         SetLastError( ERROR_FILENAME_EXCED_RANGE );
967         return 0;
968     }
969     return OpenJobObjectW( access, inherit, buffer );
970 }
971
972 /******************************************************************************
973  *              TerminateJobObject (KERNEL32.@)
974  */
975 BOOL WINAPI TerminateJobObject( HANDLE job, UINT exit_code )
976 {
977     NTSTATUS status = NtTerminateJobObject( job, exit_code );
978     if (status) SetLastError( RtlNtStatusToDosError(status) );
979     return !status;
980 }
981
982 /******************************************************************************
983  *              QueryInformationJobObject (KERNEL32.@)
984  */
985 BOOL WINAPI QueryInformationJobObject( HANDLE job, JOBOBJECTINFOCLASS class, LPVOID info,
986                                        DWORD len, DWORD *ret_len )
987 {
988     NTSTATUS status = NtQueryInformationJobObject( job, class, info, len, ret_len );
989     if (status) SetLastError( RtlNtStatusToDosError(status) );
990     return !status;
991 }
992
993 /******************************************************************************
994  *              SetInformationJobObject (KERNEL32.@)
995  */
996 BOOL WINAPI SetInformationJobObject( HANDLE job, JOBOBJECTINFOCLASS class, LPVOID info, DWORD len )
997 {
998     NTSTATUS status = NtSetInformationJobObject( job, class, info, len );
999     if (status) SetLastError( RtlNtStatusToDosError(status) );
1000     return !status;
1001 }
1002
1003 /******************************************************************************
1004  *              AssignProcessToJobObject (KERNEL32.@)
1005  */
1006 BOOL WINAPI AssignProcessToJobObject( HANDLE job, HANDLE process )
1007 {
1008     NTSTATUS status = NtAssignProcessToJobObject( job, process );
1009     if (status) SetLastError( RtlNtStatusToDosError(status) );
1010     return !status;
1011 }
1012
1013 /******************************************************************************
1014  *              IsProcessInJob (KERNEL32.@)
1015  */
1016 BOOL WINAPI IsProcessInJob( HANDLE process, HANDLE job, PBOOL result )
1017 {
1018     NTSTATUS status = NtIsProcessInJob( job, process );
1019     switch(status)
1020     {
1021     case STATUS_PROCESS_IN_JOB:
1022         *result = TRUE;
1023         return TRUE;
1024     case STATUS_PROCESS_NOT_IN_JOB:
1025         *result = FALSE;
1026         return TRUE;
1027     default:
1028         SetLastError( RtlNtStatusToDosError(status) );
1029         return FALSE;
1030     }
1031 }
1032
1033
1034 /*
1035  * Timers
1036  */
1037
1038
1039 /***********************************************************************
1040  *           CreateWaitableTimerA    (KERNEL32.@)
1041  */
1042 HANDLE WINAPI CreateWaitableTimerA( SECURITY_ATTRIBUTES *sa, BOOL manual, LPCSTR name )
1043 {
1044     return CreateWaitableTimerExA( sa, name, manual ? CREATE_WAITABLE_TIMER_MANUAL_RESET : 0,
1045                                    TIMER_ALL_ACCESS );
1046 }
1047
1048
1049 /***********************************************************************
1050  *           CreateWaitableTimerW    (KERNEL32.@)
1051  */
1052 HANDLE WINAPI CreateWaitableTimerW( SECURITY_ATTRIBUTES *sa, BOOL manual, LPCWSTR name )
1053 {
1054     return CreateWaitableTimerExW( sa, name, manual ? CREATE_WAITABLE_TIMER_MANUAL_RESET : 0,
1055                                    TIMER_ALL_ACCESS );
1056 }
1057
1058
1059 /***********************************************************************
1060  *           CreateWaitableTimerExA    (KERNEL32.@)
1061  */
1062 HANDLE WINAPI CreateWaitableTimerExA( SECURITY_ATTRIBUTES *sa, LPCSTR name, DWORD flags, DWORD access )
1063 {
1064     WCHAR buffer[MAX_PATH];
1065
1066     if (!name) return CreateWaitableTimerExW( sa, NULL, flags, access );
1067
1068     if (!MultiByteToWideChar( CP_ACP, 0, name, -1, buffer, MAX_PATH ))
1069     {
1070         SetLastError( ERROR_FILENAME_EXCED_RANGE );
1071         return 0;
1072     }
1073     return CreateWaitableTimerExW( sa, buffer, flags, access );
1074 }
1075
1076
1077 /***********************************************************************
1078  *           CreateWaitableTimerExW    (KERNEL32.@)
1079  */
1080 HANDLE WINAPI CreateWaitableTimerExW( SECURITY_ATTRIBUTES *sa, LPCWSTR name, DWORD flags, DWORD access )
1081 {
1082     HANDLE handle;
1083     NTSTATUS status;
1084     UNICODE_STRING nameW;
1085     OBJECT_ATTRIBUTES attr;
1086
1087     attr.Length                   = sizeof(attr);
1088     attr.RootDirectory            = 0;
1089     attr.ObjectName               = NULL;
1090     attr.Attributes               = OBJ_OPENIF | ((sa && sa->bInheritHandle) ? OBJ_INHERIT : 0);
1091     attr.SecurityDescriptor       = sa ? sa->lpSecurityDescriptor : NULL;
1092     attr.SecurityQualityOfService = NULL;
1093     if (name)
1094     {
1095         RtlInitUnicodeString( &nameW, name );
1096         attr.ObjectName = &nameW;
1097         attr.RootDirectory = get_BaseNamedObjects_handle();
1098     }
1099
1100     status = NtCreateTimer( &handle, access, &attr,
1101                  (flags & CREATE_WAITABLE_TIMER_MANUAL_RESET) ? NotificationTimer : SynchronizationTimer );
1102     if (status == STATUS_OBJECT_NAME_EXISTS)
1103         SetLastError( ERROR_ALREADY_EXISTS );
1104     else
1105         SetLastError( RtlNtStatusToDosError(status) );
1106     return handle;
1107 }
1108
1109
1110 /***********************************************************************
1111  *           OpenWaitableTimerA    (KERNEL32.@)
1112  */
1113 HANDLE WINAPI OpenWaitableTimerA( DWORD access, BOOL inherit, LPCSTR name )
1114 {
1115     WCHAR buffer[MAX_PATH];
1116
1117     if (!name) return OpenWaitableTimerW( access, inherit, NULL );
1118
1119     if (!MultiByteToWideChar( CP_ACP, 0, name, -1, buffer, MAX_PATH ))
1120     {
1121         SetLastError( ERROR_FILENAME_EXCED_RANGE );
1122         return 0;
1123     }
1124     return OpenWaitableTimerW( access, inherit, buffer );
1125 }
1126
1127
1128 /***********************************************************************
1129  *           OpenWaitableTimerW    (KERNEL32.@)
1130  */
1131 HANDLE WINAPI OpenWaitableTimerW( DWORD access, BOOL inherit, LPCWSTR name )
1132 {
1133     HANDLE handle;
1134     UNICODE_STRING nameW;
1135     OBJECT_ATTRIBUTES attr;
1136     NTSTATUS status;
1137
1138     if (!is_version_nt()) access = TIMER_ALL_ACCESS;
1139
1140     attr.Length                   = sizeof(attr);
1141     attr.RootDirectory            = 0;
1142     attr.ObjectName               = NULL;
1143     attr.Attributes               = inherit ? OBJ_INHERIT : 0;
1144     attr.SecurityDescriptor       = NULL;
1145     attr.SecurityQualityOfService = NULL;
1146     if (name)
1147     {
1148         RtlInitUnicodeString( &nameW, name );
1149         attr.ObjectName = &nameW;
1150         attr.RootDirectory = get_BaseNamedObjects_handle();
1151     }
1152
1153     status = NtOpenTimer(&handle, access, &attr);
1154     if (status != STATUS_SUCCESS)
1155     {
1156         SetLastError( RtlNtStatusToDosError(status) );
1157         return 0;
1158     }
1159     return handle;
1160 }
1161
1162
1163 /***********************************************************************
1164  *           SetWaitableTimer    (KERNEL32.@)
1165  */
1166 BOOL WINAPI SetWaitableTimer( HANDLE handle, const LARGE_INTEGER *when, LONG period,
1167                               PTIMERAPCROUTINE callback, LPVOID arg, BOOL resume )
1168 {
1169     NTSTATUS status = NtSetTimer(handle, when, (PTIMER_APC_ROUTINE)callback,
1170                                  arg, resume, period, NULL);
1171
1172     if (status != STATUS_SUCCESS)
1173     {
1174         SetLastError( RtlNtStatusToDosError(status) );
1175         if (status != STATUS_TIMER_RESUME_IGNORED) return FALSE;
1176     }
1177     return TRUE;
1178 }
1179
1180
1181 /***********************************************************************
1182  *           CancelWaitableTimer    (KERNEL32.@)
1183  */
1184 BOOL WINAPI CancelWaitableTimer( HANDLE handle )
1185 {
1186     NTSTATUS status;
1187
1188     status = NtCancelTimer(handle, NULL);
1189     if (status != STATUS_SUCCESS)
1190     {
1191         SetLastError( RtlNtStatusToDosError(status) );
1192         return FALSE;
1193     }
1194     return TRUE;
1195 }
1196
1197
1198 /***********************************************************************
1199  *           CreateTimerQueue  (KERNEL32.@)
1200  */
1201 HANDLE WINAPI CreateTimerQueue(void)
1202 {
1203     HANDLE q;
1204     NTSTATUS status = RtlCreateTimerQueue(&q);
1205
1206     if (status != STATUS_SUCCESS)
1207     {
1208         SetLastError( RtlNtStatusToDosError(status) );
1209         return NULL;
1210     }
1211
1212     return q;
1213 }
1214
1215
1216 /***********************************************************************
1217  *           DeleteTimerQueueEx  (KERNEL32.@)
1218  */
1219 BOOL WINAPI DeleteTimerQueueEx(HANDLE TimerQueue, HANDLE CompletionEvent)
1220 {
1221     NTSTATUS status = RtlDeleteTimerQueueEx(TimerQueue, CompletionEvent);
1222
1223     if (status != STATUS_SUCCESS)
1224     {
1225         SetLastError( RtlNtStatusToDosError(status) );
1226         return FALSE;
1227     }
1228
1229     return TRUE;
1230 }
1231
1232 /***********************************************************************
1233  *           DeleteTimerQueue  (KERNEL32.@)
1234  */
1235 BOOL WINAPI DeleteTimerQueue(HANDLE TimerQueue)
1236 {
1237     return DeleteTimerQueueEx(TimerQueue, NULL);
1238 }
1239
1240 /***********************************************************************
1241  *           CreateTimerQueueTimer  (KERNEL32.@)
1242  *
1243  * Creates a timer-queue timer. This timer expires at the specified due
1244  * time (in ms), then after every specified period (in ms). When the timer
1245  * expires, the callback function is called.
1246  *
1247  * RETURNS
1248  *   nonzero on success or zero on failure
1249  */
1250 BOOL WINAPI CreateTimerQueueTimer( PHANDLE phNewTimer, HANDLE TimerQueue,
1251                                    WAITORTIMERCALLBACK Callback, PVOID Parameter,
1252                                    DWORD DueTime, DWORD Period, ULONG Flags )
1253 {
1254     NTSTATUS status = RtlCreateTimer(phNewTimer, TimerQueue, Callback,
1255                                      Parameter, DueTime, Period, Flags);
1256
1257     if (status != STATUS_SUCCESS)
1258     {
1259         SetLastError( RtlNtStatusToDosError(status) );
1260         return FALSE;
1261     }
1262
1263     return TRUE;
1264 }
1265
1266 /***********************************************************************
1267  *           ChangeTimerQueueTimer  (KERNEL32.@)
1268  *
1269  * Changes the times at which the timer expires.
1270  *
1271  * RETURNS
1272  *   nonzero on success or zero on failure
1273  */
1274 BOOL WINAPI ChangeTimerQueueTimer( HANDLE TimerQueue, HANDLE Timer,
1275                                    ULONG DueTime, ULONG Period )
1276 {
1277     NTSTATUS status = RtlUpdateTimer(TimerQueue, Timer, DueTime, Period);
1278
1279     if (status != STATUS_SUCCESS)
1280     {
1281         SetLastError( RtlNtStatusToDosError(status) );
1282         return FALSE;
1283     }
1284
1285     return TRUE;
1286 }
1287
1288 /***********************************************************************
1289  *           DeleteTimerQueueTimer  (KERNEL32.@)
1290  *
1291  * Cancels a timer-queue timer.
1292  *
1293  * RETURNS
1294  *   nonzero on success or zero on failure
1295  */
1296 BOOL WINAPI DeleteTimerQueueTimer( HANDLE TimerQueue, HANDLE Timer,
1297                                    HANDLE CompletionEvent )
1298 {
1299     NTSTATUS status = RtlDeleteTimer(TimerQueue, Timer, CompletionEvent);
1300     if (status != STATUS_SUCCESS)
1301     {
1302         SetLastError( RtlNtStatusToDosError(status) );
1303         return FALSE;
1304     }
1305     return TRUE;
1306 }
1307
1308
1309 /*
1310  * Pipes
1311  */
1312
1313
1314 /***********************************************************************
1315  *           CreateNamedPipeA   (KERNEL32.@)
1316  */
1317 HANDLE WINAPI CreateNamedPipeA( LPCSTR name, DWORD dwOpenMode,
1318                                 DWORD dwPipeMode, DWORD nMaxInstances,
1319                                 DWORD nOutBufferSize, DWORD nInBufferSize,
1320                                 DWORD nDefaultTimeOut, LPSECURITY_ATTRIBUTES attr )
1321 {
1322     WCHAR buffer[MAX_PATH];
1323
1324     if (!name) return CreateNamedPipeW( NULL, dwOpenMode, dwPipeMode, nMaxInstances,
1325                                         nOutBufferSize, nInBufferSize, nDefaultTimeOut, attr );
1326
1327     if (!MultiByteToWideChar( CP_ACP, 0, name, -1, buffer, MAX_PATH ))
1328     {
1329         SetLastError( ERROR_FILENAME_EXCED_RANGE );
1330         return INVALID_HANDLE_VALUE;
1331     }
1332     return CreateNamedPipeW( buffer, dwOpenMode, dwPipeMode, nMaxInstances,
1333                              nOutBufferSize, nInBufferSize, nDefaultTimeOut, attr );
1334 }
1335
1336
1337 /***********************************************************************
1338  *           CreateNamedPipeW   (KERNEL32.@)
1339  */
1340 HANDLE WINAPI CreateNamedPipeW( LPCWSTR name, DWORD dwOpenMode,
1341                                 DWORD dwPipeMode, DWORD nMaxInstances,
1342                                 DWORD nOutBufferSize, DWORD nInBufferSize,
1343                                 DWORD nDefaultTimeOut, LPSECURITY_ATTRIBUTES sa )
1344 {
1345     HANDLE handle;
1346     UNICODE_STRING nt_name;
1347     OBJECT_ATTRIBUTES attr;
1348     DWORD access, options, sharing;
1349     BOOLEAN pipe_type, read_mode, non_block;
1350     NTSTATUS status;
1351     IO_STATUS_BLOCK iosb;
1352     LARGE_INTEGER timeout;
1353
1354     TRACE("(%s, %#08x, %#08x, %d, %d, %d, %d, %p)\n",
1355           debugstr_w(name), dwOpenMode, dwPipeMode, nMaxInstances,
1356           nOutBufferSize, nInBufferSize, nDefaultTimeOut, sa );
1357
1358     if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
1359     {
1360         SetLastError( ERROR_PATH_NOT_FOUND );
1361         return INVALID_HANDLE_VALUE;
1362     }
1363     if (nt_name.Length >= MAX_PATH * sizeof(WCHAR) )
1364     {
1365         SetLastError( ERROR_FILENAME_EXCED_RANGE );
1366         RtlFreeUnicodeString( &nt_name );
1367         return INVALID_HANDLE_VALUE;
1368     }
1369
1370     attr.Length                   = sizeof(attr);
1371     attr.RootDirectory            = 0;
1372     attr.ObjectName               = &nt_name;
1373     attr.Attributes               = OBJ_CASE_INSENSITIVE |
1374                                     ((sa && sa->bInheritHandle) ? OBJ_INHERIT : 0);
1375     attr.SecurityDescriptor       = sa ? sa->lpSecurityDescriptor : NULL;
1376     attr.SecurityQualityOfService = NULL;
1377
1378     switch(dwOpenMode & 3)
1379     {
1380     case PIPE_ACCESS_INBOUND:
1381         sharing = FILE_SHARE_WRITE;
1382         access  = GENERIC_READ;
1383         break;
1384     case PIPE_ACCESS_OUTBOUND:
1385         sharing = FILE_SHARE_READ;
1386         access  = GENERIC_WRITE;
1387         break;
1388     case PIPE_ACCESS_DUPLEX:
1389         sharing = FILE_SHARE_READ | FILE_SHARE_WRITE;
1390         access  = GENERIC_READ | GENERIC_WRITE;
1391         break;
1392     default:
1393         SetLastError( ERROR_INVALID_PARAMETER );
1394         return INVALID_HANDLE_VALUE;
1395     }
1396     access |= SYNCHRONIZE;
1397     options = 0;
1398     if (dwOpenMode & FILE_FLAG_WRITE_THROUGH) options |= FILE_WRITE_THROUGH;
1399     if (!(dwOpenMode & FILE_FLAG_OVERLAPPED)) options |= FILE_SYNCHRONOUS_IO_NONALERT;
1400     pipe_type = (dwPipeMode & PIPE_TYPE_MESSAGE) != 0;
1401     read_mode = (dwPipeMode & PIPE_READMODE_MESSAGE) != 0;
1402     non_block = (dwPipeMode & PIPE_NOWAIT) != 0;
1403     if (nMaxInstances >= PIPE_UNLIMITED_INSTANCES) nMaxInstances = ~0U;
1404
1405     timeout.QuadPart = (ULONGLONG)nDefaultTimeOut * -10000;
1406
1407     SetLastError(0);
1408
1409     status = NtCreateNamedPipeFile(&handle, access, &attr, &iosb, sharing,
1410                                    FILE_OVERWRITE_IF, options, pipe_type,
1411                                    read_mode, non_block, nMaxInstances,
1412                                    nInBufferSize, nOutBufferSize, &timeout);
1413
1414     RtlFreeUnicodeString( &nt_name );
1415     if (status)
1416     {
1417         handle = INVALID_HANDLE_VALUE;
1418         SetLastError( RtlNtStatusToDosError(status) );
1419     }
1420     return handle;
1421 }
1422
1423
1424 /***********************************************************************
1425  *           PeekNamedPipe   (KERNEL32.@)
1426  */
1427 BOOL WINAPI PeekNamedPipe( HANDLE hPipe, LPVOID lpvBuffer, DWORD cbBuffer,
1428                            LPDWORD lpcbRead, LPDWORD lpcbAvail, LPDWORD lpcbMessage )
1429 {
1430     FILE_PIPE_PEEK_BUFFER local_buffer;
1431     FILE_PIPE_PEEK_BUFFER *buffer = &local_buffer;
1432     IO_STATUS_BLOCK io;
1433     NTSTATUS status;
1434
1435     if (cbBuffer && !(buffer = HeapAlloc( GetProcessHeap(), 0,
1436                                           FIELD_OFFSET( FILE_PIPE_PEEK_BUFFER, Data[cbBuffer] ))))
1437     {
1438         SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1439         return FALSE;
1440     }
1441
1442     status = NtFsControlFile( hPipe, 0, NULL, NULL, &io, FSCTL_PIPE_PEEK, NULL, 0,
1443                               buffer, FIELD_OFFSET( FILE_PIPE_PEEK_BUFFER, Data[cbBuffer] ) );
1444     if (!status)
1445     {
1446         ULONG read_size = io.Information - FIELD_OFFSET( FILE_PIPE_PEEK_BUFFER, Data );
1447         if (lpcbAvail) *lpcbAvail = buffer->ReadDataAvailable;
1448         if (lpcbRead) *lpcbRead = read_size;
1449         if (lpcbMessage) *lpcbMessage = 0;  /* FIXME */
1450         if (lpvBuffer) memcpy( lpvBuffer, buffer->Data, read_size );
1451     }
1452     else SetLastError( RtlNtStatusToDosError(status) );
1453
1454     if (buffer != &local_buffer) HeapFree( GetProcessHeap(), 0, buffer );
1455     return !status;
1456 }
1457
1458 /***********************************************************************
1459  *           WaitNamedPipeA   (KERNEL32.@)
1460  */
1461 BOOL WINAPI WaitNamedPipeA (LPCSTR name, DWORD nTimeOut)
1462 {
1463     WCHAR buffer[MAX_PATH];
1464
1465     if (!name) return WaitNamedPipeW( NULL, nTimeOut );
1466
1467     if (!MultiByteToWideChar( CP_ACP, 0, name, -1, buffer, MAX_PATH ))
1468     {
1469         SetLastError( ERROR_FILENAME_EXCED_RANGE );
1470         return 0;
1471     }
1472     return WaitNamedPipeW( buffer, nTimeOut );
1473 }
1474
1475
1476 /***********************************************************************
1477  *           WaitNamedPipeW   (KERNEL32.@)
1478  *
1479  *  Waits for a named pipe instance to become available
1480  *
1481  *  PARAMS
1482  *   name     [I] Pointer to a named pipe name to wait for
1483  *   nTimeOut [I] How long to wait in ms
1484  *
1485  *  RETURNS
1486  *   TRUE: Success, named pipe can be opened with CreateFile
1487  *   FALSE: Failure, GetLastError can be called for further details
1488  */
1489 BOOL WINAPI WaitNamedPipeW (LPCWSTR name, DWORD nTimeOut)
1490 {
1491     static const WCHAR leadin[] = {'\\','?','?','\\','P','I','P','E','\\'};
1492     NTSTATUS status;
1493     UNICODE_STRING nt_name, pipe_dev_name;
1494     FILE_PIPE_WAIT_FOR_BUFFER *pipe_wait;
1495     IO_STATUS_BLOCK iosb;
1496     OBJECT_ATTRIBUTES attr;
1497     ULONG sz_pipe_wait;
1498     HANDLE pipe_dev;
1499
1500     TRACE("%s 0x%08x\n",debugstr_w(name),nTimeOut);
1501
1502     if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
1503         return FALSE;
1504
1505     if (nt_name.Length >= MAX_PATH * sizeof(WCHAR) ||
1506         nt_name.Length < sizeof(leadin) ||
1507         strncmpiW( nt_name.Buffer, leadin, sizeof(leadin)/sizeof(WCHAR)) != 0)
1508     {
1509         RtlFreeUnicodeString( &nt_name );
1510         SetLastError( ERROR_PATH_NOT_FOUND );
1511         return FALSE;
1512     }
1513
1514     sz_pipe_wait = sizeof(*pipe_wait) + nt_name.Length - sizeof(leadin) - sizeof(WCHAR);
1515     if (!(pipe_wait = HeapAlloc( GetProcessHeap(), 0,  sz_pipe_wait)))
1516     {
1517         RtlFreeUnicodeString( &nt_name );
1518         SetLastError( ERROR_OUTOFMEMORY );
1519         return FALSE;
1520     }
1521
1522     pipe_dev_name.Buffer = nt_name.Buffer;
1523     pipe_dev_name.Length = sizeof(leadin);
1524     pipe_dev_name.MaximumLength = sizeof(leadin);
1525     InitializeObjectAttributes(&attr,&pipe_dev_name, OBJ_CASE_INSENSITIVE, NULL, NULL);
1526     status = NtOpenFile( &pipe_dev, FILE_READ_ATTRIBUTES, &attr,
1527                          &iosb, FILE_SHARE_READ | FILE_SHARE_WRITE,
1528                          FILE_SYNCHRONOUS_IO_NONALERT);
1529     if (status != ERROR_SUCCESS)
1530     {
1531         HeapFree( GetProcessHeap(), 0, pipe_wait);
1532         RtlFreeUnicodeString( &nt_name );
1533         SetLastError( ERROR_PATH_NOT_FOUND );
1534         return FALSE;
1535     }
1536
1537     pipe_wait->TimeoutSpecified = !(nTimeOut == NMPWAIT_USE_DEFAULT_WAIT);
1538     if (nTimeOut == NMPWAIT_WAIT_FOREVER)
1539         pipe_wait->Timeout.QuadPart = ((ULONGLONG)0x7fffffff << 32) | 0xffffffff;
1540     else
1541         pipe_wait->Timeout.QuadPart = (ULONGLONG)nTimeOut * -10000;
1542     pipe_wait->NameLength = nt_name.Length - sizeof(leadin);
1543     memcpy(pipe_wait->Name, nt_name.Buffer + sizeof(leadin)/sizeof(WCHAR),
1544            pipe_wait->NameLength);
1545     RtlFreeUnicodeString( &nt_name );
1546
1547     status = NtFsControlFile( pipe_dev, NULL, NULL, NULL, &iosb, FSCTL_PIPE_WAIT,
1548                               pipe_wait, sz_pipe_wait, NULL, 0 );
1549
1550     HeapFree( GetProcessHeap(), 0, pipe_wait );
1551     NtClose( pipe_dev );
1552
1553     if(status != STATUS_SUCCESS)
1554     {
1555         SetLastError(RtlNtStatusToDosError(status));
1556         return FALSE;
1557     }
1558     else
1559         return TRUE;
1560 }
1561
1562
1563 /***********************************************************************
1564  *           ConnectNamedPipe   (KERNEL32.@)
1565  *
1566  *  Connects to a named pipe
1567  *
1568  *  Parameters
1569  *  hPipe: A handle to a named pipe returned by CreateNamedPipe
1570  *  overlapped: Optional OVERLAPPED struct
1571  *
1572  *  Return values
1573  *  TRUE: Success
1574  *  FALSE: Failure, GetLastError can be called for further details
1575  */
1576 BOOL WINAPI ConnectNamedPipe(HANDLE hPipe, LPOVERLAPPED overlapped)
1577 {
1578     NTSTATUS status;
1579     IO_STATUS_BLOCK status_block;
1580     LPVOID   cvalue = NULL;
1581
1582     TRACE("(%p,%p)\n", hPipe, overlapped);
1583
1584     if(overlapped)
1585     {
1586         overlapped->Internal = STATUS_PENDING;
1587         overlapped->InternalHigh = 0;
1588         if (((ULONG_PTR)overlapped->hEvent & 1) == 0) cvalue = overlapped;
1589     }
1590
1591     status = NtFsControlFile(hPipe, overlapped ? overlapped->hEvent : NULL, NULL, cvalue,
1592                              overlapped ? (IO_STATUS_BLOCK *)overlapped : &status_block,
1593                              FSCTL_PIPE_LISTEN, NULL, 0, NULL, 0);
1594
1595     if (status == STATUS_SUCCESS) return TRUE;
1596     SetLastError( RtlNtStatusToDosError(status) );
1597     return FALSE;
1598 }
1599
1600 /***********************************************************************
1601  *           DisconnectNamedPipe   (KERNEL32.@)
1602  *
1603  *  Disconnects from a named pipe
1604  *
1605  *  Parameters
1606  *  hPipe: A handle to a named pipe returned by CreateNamedPipe
1607  *
1608  *  Return values
1609  *  TRUE: Success
1610  *  FALSE: Failure, GetLastError can be called for further details
1611  */
1612 BOOL WINAPI DisconnectNamedPipe(HANDLE hPipe)
1613 {
1614     NTSTATUS status;
1615     IO_STATUS_BLOCK io_block;
1616
1617     TRACE("(%p)\n",hPipe);
1618
1619     status = NtFsControlFile(hPipe, 0, NULL, NULL, &io_block, FSCTL_PIPE_DISCONNECT,
1620                              NULL, 0, NULL, 0);
1621     if (status == STATUS_SUCCESS) return TRUE;
1622     SetLastError( RtlNtStatusToDosError(status) );
1623     return FALSE;
1624 }
1625
1626 /***********************************************************************
1627  *           TransactNamedPipe   (KERNEL32.@)
1628  *
1629  * BUGS
1630  *  should be done as a single operation in the wineserver or kernel
1631  */
1632 BOOL WINAPI TransactNamedPipe(
1633     HANDLE handle, LPVOID write_buf, DWORD write_size, LPVOID read_buf,
1634     DWORD read_size, LPDWORD bytes_read, LPOVERLAPPED overlapped)
1635 {
1636     BOOL r;
1637     DWORD count;
1638
1639     TRACE("%p %p %d %p %d %p %p\n",
1640           handle, write_buf, write_size, read_buf,
1641           read_size, bytes_read, overlapped);
1642
1643     if (overlapped)
1644     {
1645         FIXME("Doesn't support overlapped operation as yet\n");
1646         return FALSE;
1647     }
1648
1649     r = WriteFile(handle, write_buf, write_size, &count, NULL);
1650     if (r)
1651         r = ReadFile(handle, read_buf, read_size, bytes_read, NULL);
1652
1653     return r;
1654 }
1655
1656 /***********************************************************************
1657  *           GetNamedPipeInfo   (KERNEL32.@)
1658  */
1659 BOOL WINAPI GetNamedPipeInfo(
1660     HANDLE hNamedPipe, LPDWORD lpFlags, LPDWORD lpOutputBufferSize,
1661     LPDWORD lpInputBufferSize, LPDWORD lpMaxInstances)
1662 {
1663     FILE_PIPE_LOCAL_INFORMATION fpli;
1664     IO_STATUS_BLOCK iosb;
1665     NTSTATUS status;
1666
1667     status = NtQueryInformationFile(hNamedPipe, &iosb, &fpli, sizeof(fpli),
1668                                     FilePipeLocalInformation);
1669     if (status)
1670     {
1671         SetLastError( RtlNtStatusToDosError(status) );
1672         return FALSE;
1673     }
1674
1675     if (lpFlags)
1676     {
1677         *lpFlags = (fpli.NamedPipeEnd & FILE_PIPE_SERVER_END) ?
1678             PIPE_SERVER_END : PIPE_CLIENT_END;
1679         *lpFlags |= (fpli.NamedPipeType & FILE_PIPE_TYPE_MESSAGE) ?
1680             PIPE_TYPE_MESSAGE : PIPE_TYPE_BYTE;
1681     }
1682
1683     if (lpOutputBufferSize) *lpOutputBufferSize = fpli.OutboundQuota;
1684     if (lpInputBufferSize) *lpInputBufferSize = fpli.InboundQuota;
1685     if (lpMaxInstances) *lpMaxInstances = fpli.MaximumInstances;
1686
1687     return TRUE;
1688 }
1689
1690 /***********************************************************************
1691  *           GetNamedPipeHandleStateA  (KERNEL32.@)
1692  */
1693 BOOL WINAPI GetNamedPipeHandleStateA(
1694     HANDLE hNamedPipe, LPDWORD lpState, LPDWORD lpCurInstances,
1695     LPDWORD lpMaxCollectionCount, LPDWORD lpCollectDataTimeout,
1696     LPSTR lpUsername, DWORD nUsernameMaxSize)
1697 {
1698     FIXME("%p %p %p %p %p %p %d\n",
1699           hNamedPipe, lpState, lpCurInstances,
1700           lpMaxCollectionCount, lpCollectDataTimeout,
1701           lpUsername, nUsernameMaxSize);
1702
1703     return FALSE;
1704 }
1705
1706 /***********************************************************************
1707  *           GetNamedPipeHandleStateW  (KERNEL32.@)
1708  */
1709 BOOL WINAPI GetNamedPipeHandleStateW(
1710     HANDLE hNamedPipe, LPDWORD lpState, LPDWORD lpCurInstances,
1711     LPDWORD lpMaxCollectionCount, LPDWORD lpCollectDataTimeout,
1712     LPWSTR lpUsername, DWORD nUsernameMaxSize)
1713 {
1714     FIXME("%p %p %p %p %p %p %d\n",
1715           hNamedPipe, lpState, lpCurInstances,
1716           lpMaxCollectionCount, lpCollectDataTimeout,
1717           lpUsername, nUsernameMaxSize);
1718
1719     return FALSE;
1720 }
1721
1722 /***********************************************************************
1723  *           SetNamedPipeHandleState  (KERNEL32.@)
1724  */
1725 BOOL WINAPI SetNamedPipeHandleState(
1726     HANDLE hNamedPipe, LPDWORD lpMode, LPDWORD lpMaxCollectionCount,
1727     LPDWORD lpCollectDataTimeout)
1728 {
1729     /* should be a fixme, but this function is called a lot by the RPC
1730      * runtime, and it slows down InstallShield a fair bit. */
1731     WARN("stub: %p %p/%d %p %p\n",
1732           hNamedPipe, lpMode, lpMode ? *lpMode : 0, lpMaxCollectionCount, lpCollectDataTimeout);
1733     return FALSE;
1734 }
1735
1736 /***********************************************************************
1737  *           CallNamedPipeA  (KERNEL32.@)
1738  */
1739 BOOL WINAPI CallNamedPipeA(
1740     LPCSTR lpNamedPipeName, LPVOID lpInput, DWORD dwInputSize,
1741     LPVOID lpOutput, DWORD dwOutputSize,
1742     LPDWORD lpBytesRead, DWORD nTimeout)
1743 {
1744     DWORD len;
1745     LPWSTR str = NULL;
1746     BOOL ret;
1747
1748     TRACE("%s %p %d %p %d %p %d\n",
1749            debugstr_a(lpNamedPipeName), lpInput, dwInputSize,
1750            lpOutput, dwOutputSize, lpBytesRead, nTimeout);
1751
1752     if( lpNamedPipeName )
1753     {
1754         len = MultiByteToWideChar( CP_ACP, 0, lpNamedPipeName, -1, NULL, 0 );
1755         str = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
1756         MultiByteToWideChar( CP_ACP, 0, lpNamedPipeName, -1, str, len );
1757     }
1758     ret = CallNamedPipeW( str, lpInput, dwInputSize, lpOutput,
1759                           dwOutputSize, lpBytesRead, nTimeout );
1760     if( lpNamedPipeName )
1761         HeapFree( GetProcessHeap(), 0, str );
1762
1763     return ret;
1764 }
1765
1766 /***********************************************************************
1767  *           CallNamedPipeW  (KERNEL32.@)
1768  */
1769 BOOL WINAPI CallNamedPipeW(
1770     LPCWSTR lpNamedPipeName, LPVOID lpInput, DWORD lpInputSize,
1771     LPVOID lpOutput, DWORD lpOutputSize,
1772     LPDWORD lpBytesRead, DWORD nTimeout)
1773 {
1774     HANDLE pipe;
1775     BOOL ret;
1776     DWORD mode;
1777
1778     TRACE("%s %p %d %p %d %p %d\n",
1779           debugstr_w(lpNamedPipeName), lpInput, lpInputSize,
1780           lpOutput, lpOutputSize, lpBytesRead, nTimeout);
1781
1782     pipe = CreateFileW(lpNamedPipeName, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
1783     if (pipe == INVALID_HANDLE_VALUE)
1784     {
1785         ret = WaitNamedPipeW(lpNamedPipeName, nTimeout);
1786         if (!ret)
1787             return FALSE;
1788         pipe = CreateFileW(lpNamedPipeName, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
1789         if (pipe == INVALID_HANDLE_VALUE)
1790             return FALSE;
1791     }
1792
1793     mode = PIPE_READMODE_MESSAGE;
1794     ret = SetNamedPipeHandleState(pipe, &mode, NULL, NULL);
1795
1796     /* Currently SetNamedPipeHandleState() is a stub returning FALSE */
1797     if (ret) FIXME("Now that SetNamedPipeHandleState() is more than a stub, please update CallNamedPipeW\n");
1798     /*
1799     if (!ret)
1800     {
1801         CloseHandle(pipe);
1802         return FALSE;
1803     }*/
1804
1805     ret = TransactNamedPipe(pipe, lpInput, lpInputSize, lpOutput, lpOutputSize, lpBytesRead, NULL);
1806     CloseHandle(pipe);
1807     if (!ret)
1808         return FALSE;
1809
1810     return TRUE;
1811 }
1812
1813 /******************************************************************
1814  *              CreatePipe (KERNEL32.@)
1815  *
1816  */
1817 BOOL WINAPI CreatePipe( PHANDLE hReadPipe, PHANDLE hWritePipe,
1818                         LPSECURITY_ATTRIBUTES sa, DWORD size )
1819 {
1820     static unsigned     index /* = 0 */;
1821     WCHAR               name[64];
1822     HANDLE              hr, hw;
1823     unsigned            in_index = index;
1824     UNICODE_STRING      nt_name;
1825     OBJECT_ATTRIBUTES   attr;
1826     NTSTATUS            status;
1827     IO_STATUS_BLOCK     iosb;
1828     LARGE_INTEGER       timeout;
1829
1830     *hReadPipe = *hWritePipe = INVALID_HANDLE_VALUE;
1831
1832     attr.Length                   = sizeof(attr);
1833     attr.RootDirectory            = 0;
1834     attr.ObjectName               = &nt_name;
1835     attr.Attributes               = OBJ_CASE_INSENSITIVE |
1836                                     ((sa && sa->bInheritHandle) ? OBJ_INHERIT : 0);
1837     attr.SecurityDescriptor       = sa ? sa->lpSecurityDescriptor : NULL;
1838     attr.SecurityQualityOfService = NULL;
1839
1840     timeout.QuadPart = (ULONGLONG)NMPWAIT_USE_DEFAULT_WAIT * -10000;
1841     /* generate a unique pipe name (system wide) */
1842     do
1843     {
1844         static const WCHAR nameFmt[] = { '\\','?','?','\\','p','i','p','e',
1845          '\\','W','i','n','3','2','.','P','i','p','e','s','.','%','0','8','l',
1846          'u','.','%','0','8','u','\0' };
1847
1848         snprintfW(name, sizeof(name) / sizeof(name[0]), nameFmt,
1849                   GetCurrentProcessId(), ++index);
1850         RtlInitUnicodeString(&nt_name, name);
1851         status = NtCreateNamedPipeFile(&hr, GENERIC_READ | SYNCHRONIZE, &attr, &iosb,
1852                                        FILE_SHARE_WRITE, FILE_OVERWRITE_IF,
1853                                        FILE_SYNCHRONOUS_IO_NONALERT,
1854                                        FALSE, FALSE, FALSE, 
1855                                        1, size, size, &timeout);
1856         if (status)
1857         {
1858             SetLastError( RtlNtStatusToDosError(status) );
1859             hr = INVALID_HANDLE_VALUE;
1860         }
1861     } while (hr == INVALID_HANDLE_VALUE && index != in_index);
1862     /* from completion sakeness, I think system resources might be exhausted before this happens !! */
1863     if (hr == INVALID_HANDLE_VALUE) return FALSE;
1864
1865     status = NtOpenFile(&hw, GENERIC_WRITE | SYNCHRONIZE, &attr, &iosb, 0,
1866                         FILE_SYNCHRONOUS_IO_NONALERT | FILE_NON_DIRECTORY_FILE);
1867
1868     if (status) 
1869     {
1870         SetLastError( RtlNtStatusToDosError(status) );
1871         NtClose(hr);
1872         return FALSE;
1873     }
1874
1875     *hReadPipe = hr;
1876     *hWritePipe = hw;
1877     return TRUE;
1878 }
1879
1880
1881 /******************************************************************************
1882  * CreateMailslotA [KERNEL32.@]
1883  *
1884  * See CreateMailslotW.
1885  */
1886 HANDLE WINAPI CreateMailslotA( LPCSTR lpName, DWORD nMaxMessageSize,
1887                                DWORD lReadTimeout, LPSECURITY_ATTRIBUTES sa )
1888 {
1889     DWORD len;
1890     HANDLE handle;
1891     LPWSTR name = NULL;
1892
1893     TRACE("%s %d %d %p\n", debugstr_a(lpName),
1894           nMaxMessageSize, lReadTimeout, sa);
1895
1896     if( lpName )
1897     {
1898         len = MultiByteToWideChar( CP_ACP, 0, lpName, -1, NULL, 0 );
1899         name = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
1900         MultiByteToWideChar( CP_ACP, 0, lpName, -1, name, len );
1901     }
1902
1903     handle = CreateMailslotW( name, nMaxMessageSize, lReadTimeout, sa );
1904
1905     HeapFree( GetProcessHeap(), 0, name );
1906
1907     return handle;
1908 }
1909
1910
1911 /******************************************************************************
1912  * CreateMailslotW [KERNEL32.@]
1913  *
1914  * Create a mailslot with specified name.
1915  *
1916  * PARAMS
1917  *    lpName          [I] Pointer to string for mailslot name
1918  *    nMaxMessageSize [I] Maximum message size
1919  *    lReadTimeout    [I] Milliseconds before read time-out
1920  *    sa              [I] Pointer to security structure
1921  *
1922  * RETURNS
1923  *    Success: Handle to mailslot
1924  *    Failure: INVALID_HANDLE_VALUE
1925  */
1926 HANDLE WINAPI CreateMailslotW( LPCWSTR lpName, DWORD nMaxMessageSize,
1927                                DWORD lReadTimeout, LPSECURITY_ATTRIBUTES sa )
1928 {
1929     HANDLE handle = INVALID_HANDLE_VALUE;
1930     OBJECT_ATTRIBUTES attr;
1931     UNICODE_STRING nameW;
1932     LARGE_INTEGER timeout;
1933     IO_STATUS_BLOCK iosb;
1934     NTSTATUS status;
1935
1936     TRACE("%s %d %d %p\n", debugstr_w(lpName),
1937           nMaxMessageSize, lReadTimeout, sa);
1938
1939     if (!RtlDosPathNameToNtPathName_U( lpName, &nameW, NULL, NULL ))
1940     {
1941         SetLastError( ERROR_PATH_NOT_FOUND );
1942         return INVALID_HANDLE_VALUE;
1943     }
1944
1945     if (nameW.Length >= MAX_PATH * sizeof(WCHAR) )
1946     {
1947         SetLastError( ERROR_FILENAME_EXCED_RANGE );
1948         RtlFreeUnicodeString( &nameW );
1949         return INVALID_HANDLE_VALUE;
1950     }
1951
1952     attr.Length = sizeof(attr);
1953     attr.RootDirectory = 0;
1954     attr.Attributes = OBJ_CASE_INSENSITIVE;
1955     attr.ObjectName = &nameW;
1956     attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
1957     attr.SecurityQualityOfService = NULL;
1958
1959     if (lReadTimeout != MAILSLOT_WAIT_FOREVER)
1960         timeout.QuadPart = (ULONGLONG) lReadTimeout * -10000;
1961     else
1962         timeout.QuadPart = ((LONGLONG)0x7fffffff << 32) | 0xffffffff;
1963
1964     status = NtCreateMailslotFile( &handle, GENERIC_READ | SYNCHRONIZE, &attr,
1965                                    &iosb, 0, 0, nMaxMessageSize, &timeout );
1966     if (status)
1967     {
1968         SetLastError( RtlNtStatusToDosError(status) );
1969         handle = INVALID_HANDLE_VALUE;
1970     }
1971
1972     RtlFreeUnicodeString( &nameW );
1973     return handle;
1974 }
1975
1976
1977 /******************************************************************************
1978  * GetMailslotInfo [KERNEL32.@]
1979  *
1980  * Retrieve information about a mailslot.
1981  *
1982  * PARAMS
1983  *    hMailslot        [I] Mailslot handle
1984  *    lpMaxMessageSize [O] Address of maximum message size
1985  *    lpNextSize       [O] Address of size of next message
1986  *    lpMessageCount   [O] Address of number of messages
1987  *    lpReadTimeout    [O] Address of read time-out
1988  *
1989  * RETURNS
1990  *    Success: TRUE
1991  *    Failure: FALSE
1992  */
1993 BOOL WINAPI GetMailslotInfo( HANDLE hMailslot, LPDWORD lpMaxMessageSize,
1994                                LPDWORD lpNextSize, LPDWORD lpMessageCount,
1995                                LPDWORD lpReadTimeout )
1996 {
1997     FILE_MAILSLOT_QUERY_INFORMATION info;
1998     IO_STATUS_BLOCK iosb;
1999     NTSTATUS status;
2000
2001     TRACE("%p %p %p %p %p\n",hMailslot, lpMaxMessageSize,
2002           lpNextSize, lpMessageCount, lpReadTimeout);
2003
2004     status = NtQueryInformationFile( hMailslot, &iosb, &info, sizeof info,
2005                                      FileMailslotQueryInformation );
2006
2007     if( status != STATUS_SUCCESS )
2008     {
2009         SetLastError( RtlNtStatusToDosError(status) );
2010         return FALSE;
2011     }
2012
2013     if( lpMaxMessageSize )
2014         *lpMaxMessageSize = info.MaximumMessageSize;
2015     if( lpNextSize )
2016         *lpNextSize = info.NextMessageSize;
2017     if( lpMessageCount )
2018         *lpMessageCount = info.MessagesAvailable;
2019     if( lpReadTimeout )
2020     {
2021         if (info.ReadTimeout.QuadPart == (((LONGLONG)0x7fffffff << 32) | 0xffffffff))
2022             *lpReadTimeout = MAILSLOT_WAIT_FOREVER;
2023         else
2024             *lpReadTimeout = info.ReadTimeout.QuadPart / -10000;
2025     }
2026     return TRUE;
2027 }
2028
2029
2030 /******************************************************************************
2031  * SetMailslotInfo [KERNEL32.@]
2032  *
2033  * Set the read timeout of a mailslot.
2034  *
2035  * PARAMS
2036  *  hMailslot     [I] Mailslot handle
2037  *  dwReadTimeout [I] Timeout in milliseconds.
2038  *
2039  * RETURNS
2040  *    Success: TRUE
2041  *    Failure: FALSE
2042  */
2043 BOOL WINAPI SetMailslotInfo( HANDLE hMailslot, DWORD dwReadTimeout)
2044 {
2045     FILE_MAILSLOT_SET_INFORMATION info;
2046     IO_STATUS_BLOCK iosb;
2047     NTSTATUS status;
2048
2049     TRACE("%p %d\n", hMailslot, dwReadTimeout);
2050
2051     if (dwReadTimeout != MAILSLOT_WAIT_FOREVER)
2052         info.ReadTimeout.QuadPart = (ULONGLONG)dwReadTimeout * -10000;
2053     else
2054         info.ReadTimeout.QuadPart = ((LONGLONG)0x7fffffff << 32) | 0xffffffff;
2055     status = NtSetInformationFile( hMailslot, &iosb, &info, sizeof info,
2056                                    FileMailslotSetInformation );
2057     if( status != STATUS_SUCCESS )
2058     {
2059         SetLastError( RtlNtStatusToDosError(status) );
2060         return FALSE;
2061     }
2062     return TRUE;
2063 }
2064
2065
2066 /******************************************************************************
2067  *              CreateIoCompletionPort (KERNEL32.@)
2068  */
2069 HANDLE WINAPI CreateIoCompletionPort(HANDLE hFileHandle, HANDLE hExistingCompletionPort,
2070                                      ULONG_PTR CompletionKey, DWORD dwNumberOfConcurrentThreads)
2071 {
2072     NTSTATUS status;
2073     HANDLE ret = 0;
2074
2075     TRACE("(%p, %p, %08lx, %08x)\n",
2076           hFileHandle, hExistingCompletionPort, CompletionKey, dwNumberOfConcurrentThreads);
2077
2078     if (hExistingCompletionPort && hFileHandle == INVALID_HANDLE_VALUE)
2079     {
2080         SetLastError( ERROR_INVALID_PARAMETER);
2081         return NULL;
2082     }
2083
2084     if (hExistingCompletionPort)
2085         ret = hExistingCompletionPort;
2086     else
2087     {
2088         status = NtCreateIoCompletion( &ret, IO_COMPLETION_ALL_ACCESS, NULL, dwNumberOfConcurrentThreads );
2089         if (status != STATUS_SUCCESS) goto fail;
2090     }
2091
2092     if (hFileHandle != INVALID_HANDLE_VALUE)
2093     {
2094         FILE_COMPLETION_INFORMATION info;
2095         IO_STATUS_BLOCK iosb;
2096
2097         info.CompletionPort = ret;
2098         info.CompletionKey = CompletionKey;
2099         status = NtSetInformationFile( hFileHandle, &iosb, &info, sizeof(info), FileCompletionInformation );
2100         if (status != STATUS_SUCCESS) goto fail;
2101     }
2102
2103     return ret;
2104
2105 fail:
2106     if (ret && !hExistingCompletionPort)
2107         CloseHandle( ret );
2108     SetLastError( RtlNtStatusToDosError(status) );
2109     return 0;
2110 }
2111
2112 /******************************************************************************
2113  *              GetQueuedCompletionStatus (KERNEL32.@)
2114  */
2115 BOOL WINAPI GetQueuedCompletionStatus( HANDLE CompletionPort, LPDWORD lpNumberOfBytesTransferred,
2116                                        PULONG_PTR pCompletionKey, LPOVERLAPPED *lpOverlapped,
2117                                        DWORD dwMilliseconds )
2118 {
2119     NTSTATUS status;
2120     IO_STATUS_BLOCK iosb;
2121     LARGE_INTEGER wait_time;
2122
2123     TRACE("(%p,%p,%p,%p,%d)\n",
2124           CompletionPort,lpNumberOfBytesTransferred,pCompletionKey,lpOverlapped,dwMilliseconds);
2125
2126     *lpOverlapped = NULL;
2127
2128     status = NtRemoveIoCompletion( CompletionPort, pCompletionKey, (PULONG_PTR)lpOverlapped,
2129                                    &iosb, get_nt_timeout( &wait_time, dwMilliseconds ) );
2130     if (status == STATUS_SUCCESS)
2131     {
2132         *lpNumberOfBytesTransferred = iosb.Information;
2133         if (iosb.u.Status >= 0) return TRUE;
2134         SetLastError( RtlNtStatusToDosError(iosb.u.Status) );
2135         return FALSE;
2136     }
2137
2138     if (status == STATUS_TIMEOUT) SetLastError( WAIT_TIMEOUT );
2139     else SetLastError( RtlNtStatusToDosError(status) );
2140     return FALSE;
2141 }
2142
2143
2144 /******************************************************************************
2145  *              PostQueuedCompletionStatus (KERNEL32.@)
2146  */
2147 BOOL WINAPI PostQueuedCompletionStatus( HANDLE CompletionPort, DWORD dwNumberOfBytes,
2148                                         ULONG_PTR dwCompletionKey, LPOVERLAPPED lpOverlapped)
2149 {
2150     NTSTATUS status;
2151
2152     TRACE("%p %d %08lx %p\n", CompletionPort, dwNumberOfBytes, dwCompletionKey, lpOverlapped );
2153
2154     status = NtSetIoCompletion( CompletionPort, dwCompletionKey, (ULONG_PTR)lpOverlapped,
2155                                 STATUS_SUCCESS, dwNumberOfBytes );
2156
2157     if (status == STATUS_SUCCESS) return TRUE;
2158     SetLastError( RtlNtStatusToDosError(status) );
2159     return FALSE;
2160 }
2161
2162 /******************************************************************************
2163  *              BindIoCompletionCallback (KERNEL32.@)
2164  */
2165 BOOL WINAPI BindIoCompletionCallback( HANDLE FileHandle, LPOVERLAPPED_COMPLETION_ROUTINE Function, ULONG Flags)
2166 {
2167     NTSTATUS status;
2168
2169     TRACE("(%p, %p, %d)\n", FileHandle, Function, Flags);
2170
2171     status = RtlSetIoCompletionCallback( FileHandle, (PRTL_OVERLAPPED_COMPLETION_ROUTINE)Function, Flags );
2172     if (status == STATUS_SUCCESS) return TRUE;
2173     SetLastError( RtlNtStatusToDosError(status) );
2174     return FALSE;
2175 }
2176
2177
2178 /***********************************************************************
2179  *           CreateMemoryResourceNotification   (KERNEL32.@)
2180  */
2181 HANDLE WINAPI CreateMemoryResourceNotification(MEMORY_RESOURCE_NOTIFICATION_TYPE type)
2182 {
2183     static const WCHAR lowmemW[] =
2184         {'\\','K','e','r','n','e','l','O','b','j','e','c','t','s',
2185          '\\','L','o','w','M','e','m','o','r','y','C','o','n','d','i','t','i','o','n',0};
2186     static const WCHAR highmemW[] =
2187         {'\\','K','e','r','n','e','l','O','b','j','e','c','t','s',
2188          '\\','H','i','g','h','M','e','m','o','r','y','C','o','n','d','i','t','i','o','n',0};
2189     HANDLE ret;
2190     UNICODE_STRING nameW;
2191     OBJECT_ATTRIBUTES attr;
2192     NTSTATUS status;
2193
2194     switch (type)
2195     {
2196     case LowMemoryResourceNotification:
2197         RtlInitUnicodeString( &nameW, lowmemW );
2198         break;
2199     case HighMemoryResourceNotification:
2200         RtlInitUnicodeString( &nameW, highmemW );
2201         break;
2202     default:
2203         SetLastError( ERROR_INVALID_PARAMETER );
2204         return 0;
2205     }
2206
2207     attr.Length                   = sizeof(attr);
2208     attr.RootDirectory            = 0;
2209     attr.ObjectName               = &nameW;
2210     attr.Attributes               = 0;
2211     attr.SecurityDescriptor       = NULL;
2212     attr.SecurityQualityOfService = NULL;
2213     status = NtOpenEvent( &ret, EVENT_ALL_ACCESS, &attr );
2214     if (status != STATUS_SUCCESS)
2215     {
2216         SetLastError( RtlNtStatusToDosError(status) );
2217         return 0;
2218     }
2219     return ret;
2220 }
2221
2222 /***********************************************************************
2223  *          QueryMemoryResourceNotification   (KERNEL32.@)
2224  */
2225 BOOL WINAPI QueryMemoryResourceNotification(HANDLE handle, PBOOL state)
2226 {
2227     switch (WaitForSingleObject( handle, 0 ))
2228     {
2229     case WAIT_OBJECT_0:
2230         *state = TRUE;
2231         return TRUE;
2232     case WAIT_TIMEOUT:
2233         *state = FALSE;
2234         return TRUE;
2235     }
2236     SetLastError( ERROR_INVALID_PARAMETER );
2237     return FALSE;
2238 }
2239
2240 #ifdef __i386__
2241
2242 /***********************************************************************
2243  *              InterlockedCompareExchange (KERNEL32.@)
2244  */
2245 /* LONG WINAPI InterlockedCompareExchange( PLONG dest, LONG xchg, LONG compare ); */
2246 __ASM_STDCALL_FUNC(InterlockedCompareExchange, 12,
2247                   "movl 12(%esp),%eax\n\t"
2248                   "movl 8(%esp),%ecx\n\t"
2249                   "movl 4(%esp),%edx\n\t"
2250                   "lock; cmpxchgl %ecx,(%edx)\n\t"
2251                   "ret $12")
2252
2253 /***********************************************************************
2254  *              InterlockedExchange (KERNEL32.@)
2255  */
2256 /* LONG WINAPI InterlockedExchange( PLONG dest, LONG val ); */
2257 __ASM_STDCALL_FUNC(InterlockedExchange, 8,
2258                   "movl 8(%esp),%eax\n\t"
2259                   "movl 4(%esp),%edx\n\t"
2260                   "lock; xchgl %eax,(%edx)\n\t"
2261                   "ret $8")
2262
2263 /***********************************************************************
2264  *              InterlockedExchangeAdd (KERNEL32.@)
2265  */
2266 /* LONG WINAPI InterlockedExchangeAdd( PLONG dest, LONG incr ); */
2267 __ASM_STDCALL_FUNC(InterlockedExchangeAdd, 8,
2268                   "movl 8(%esp),%eax\n\t"
2269                   "movl 4(%esp),%edx\n\t"
2270                   "lock; xaddl %eax,(%edx)\n\t"
2271                   "ret $8")
2272
2273 /***********************************************************************
2274  *              InterlockedIncrement (KERNEL32.@)
2275  */
2276 /* LONG WINAPI InterlockedIncrement( PLONG dest ); */
2277 __ASM_STDCALL_FUNC(InterlockedIncrement, 4,
2278                   "movl 4(%esp),%edx\n\t"
2279                   "movl $1,%eax\n\t"
2280                   "lock; xaddl %eax,(%edx)\n\t"
2281                   "incl %eax\n\t"
2282                   "ret $4")
2283
2284 /***********************************************************************
2285  *              InterlockedDecrement (KERNEL32.@)
2286  */
2287 __ASM_STDCALL_FUNC(InterlockedDecrement, 4,
2288                   "movl 4(%esp),%edx\n\t"
2289                   "movl $-1,%eax\n\t"
2290                   "lock; xaddl %eax,(%edx)\n\t"
2291                   "decl %eax\n\t"
2292                   "ret $4")
2293
2294 #endif  /* __i386__ */