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