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