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