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