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