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