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