shell32/tests: Use FAILED instead of !SUCCEEDED.
[wine/multimedia.git] / dlls / kernel32 / sync.c
blobe92679aafef4e3b1a0ef8f15a92f99f72eff8f9f
1 /*
2 * Kernel synchronization objects
4 * Copyright 1998 Alexandre Julliard
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.
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.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 #include "config.h"
22 #include "wine/port.h"
24 #include <string.h>
25 #ifdef HAVE_UNISTD_H
26 # include <unistd.h>
27 #endif
28 #include <errno.h>
29 #include <stdarg.h>
30 #include <stdio.h>
32 #define NONAMELESSUNION
33 #define NONAMELESSSTRUCT
35 #include "ntstatus.h"
36 #define WIN32_NO_STATUS
37 #include "windef.h"
38 #include "winbase.h"
39 #include "winerror.h"
40 #include "winnls.h"
41 #include "winternl.h"
42 #include "winioctl.h"
43 #include "ddk/wdm.h"
45 #include "wine/unicode.h"
46 #include "wine/winbase16.h"
47 #include "kernel_private.h"
49 #include "wine/debug.h"
51 WINE_DEFAULT_DEBUG_CHANNEL(sync);
53 /* check if current version is NT or Win95 */
54 static inline int is_version_nt(void)
56 return !(GetVersion() & 0x80000000);
59 /* returns directory handle to \\BaseNamedObjects */
60 HANDLE get_BaseNamedObjects_handle(void)
62 static HANDLE handle = NULL;
63 static const WCHAR basenameW[] =
64 {'\\','B','a','s','e','N','a','m','e','d','O','b','j','e','c','t','s',0};
65 UNICODE_STRING str;
66 OBJECT_ATTRIBUTES attr;
68 if (!handle)
70 HANDLE dir;
72 RtlInitUnicodeString(&str, basenameW);
73 InitializeObjectAttributes(&attr, &str, 0, 0, NULL);
74 NtOpenDirectoryObject(&dir, DIRECTORY_CREATE_OBJECT|DIRECTORY_TRAVERSE,
75 &attr);
76 if (InterlockedCompareExchangePointer( (PVOID)&handle, dir, 0 ) != 0)
78 /* someone beat us here... */
79 CloseHandle( dir );
82 return handle;
85 /* helper for kernel32->ntdll timeout format conversion */
86 static inline PLARGE_INTEGER get_nt_timeout( PLARGE_INTEGER pTime, DWORD timeout )
88 if (timeout == INFINITE) return NULL;
89 pTime->QuadPart = (ULONGLONG)timeout * -10000;
90 return pTime;
93 /***********************************************************************
94 * Sleep (KERNEL32.@)
96 VOID WINAPI Sleep( DWORD timeout )
98 SleepEx( timeout, FALSE );
101 /******************************************************************************
102 * SleepEx (KERNEL32.@)
104 DWORD WINAPI SleepEx( DWORD timeout, BOOL alertable )
106 NTSTATUS status;
107 LARGE_INTEGER time;
109 status = NtDelayExecution( alertable, get_nt_timeout( &time, timeout ) );
110 if (status == STATUS_USER_APC) return WAIT_IO_COMPLETION;
111 return 0;
115 /***********************************************************************
116 * SwitchToThread (KERNEL32.@)
118 BOOL WINAPI SwitchToThread(void)
120 return (NtYieldExecution() != STATUS_NO_YIELD_PERFORMED);
124 /***********************************************************************
125 * WaitForSingleObject (KERNEL32.@)
127 DWORD WINAPI WaitForSingleObject( HANDLE handle, DWORD timeout )
129 return WaitForMultipleObjectsEx( 1, &handle, FALSE, timeout, FALSE );
133 /***********************************************************************
134 * WaitForSingleObjectEx (KERNEL32.@)
136 DWORD WINAPI WaitForSingleObjectEx( HANDLE handle, DWORD timeout,
137 BOOL alertable )
139 return WaitForMultipleObjectsEx( 1, &handle, FALSE, timeout, alertable );
143 /***********************************************************************
144 * WaitForMultipleObjects (KERNEL32.@)
146 DWORD WINAPI WaitForMultipleObjects( DWORD count, const HANDLE *handles,
147 BOOL wait_all, DWORD timeout )
149 return WaitForMultipleObjectsEx( count, handles, wait_all, timeout, FALSE );
153 /***********************************************************************
154 * WaitForMultipleObjectsEx (KERNEL32.@)
156 DWORD WINAPI WaitForMultipleObjectsEx( DWORD count, const HANDLE *handles,
157 BOOL wait_all, DWORD timeout,
158 BOOL alertable )
160 NTSTATUS status;
161 HANDLE hloc[MAXIMUM_WAIT_OBJECTS];
162 LARGE_INTEGER time;
163 unsigned int i;
165 if (count > MAXIMUM_WAIT_OBJECTS)
167 SetLastError(ERROR_INVALID_PARAMETER);
168 return WAIT_FAILED;
170 for (i = 0; i < count; i++)
172 if ((handles[i] == (HANDLE)STD_INPUT_HANDLE) ||
173 (handles[i] == (HANDLE)STD_OUTPUT_HANDLE) ||
174 (handles[i] == (HANDLE)STD_ERROR_HANDLE))
175 hloc[i] = GetStdHandle( HandleToULong(handles[i]) );
176 else
177 hloc[i] = handles[i];
179 /* yes, even screen buffer console handles are waitable, and are
180 * handled as a handle to the console itself !!
182 if (is_console_handle(hloc[i]))
184 if (!VerifyConsoleIoHandle(hloc[i]))
186 return FALSE;
188 hloc[i] = GetConsoleInputWaitHandle();
192 status = NtWaitForMultipleObjects( count, hloc, wait_all, alertable,
193 get_nt_timeout( &time, timeout ) );
195 if (HIWORD(status)) /* is it an error code? */
197 SetLastError( RtlNtStatusToDosError(status) );
198 status = WAIT_FAILED;
200 return status;
204 /***********************************************************************
205 * WaitForSingleObject (KERNEL.460)
207 DWORD WINAPI WaitForSingleObject16( HANDLE handle, DWORD timeout )
209 DWORD retval, mutex_count;
211 ReleaseThunkLock( &mutex_count );
212 retval = WaitForSingleObject( handle, timeout );
213 RestoreThunkLock( mutex_count );
214 return retval;
217 /***********************************************************************
218 * WaitForMultipleObjects (KERNEL.461)
220 DWORD WINAPI WaitForMultipleObjects16( DWORD count, const HANDLE *handles,
221 BOOL wait_all, DWORD timeout )
223 DWORD retval, mutex_count;
225 ReleaseThunkLock( &mutex_count );
226 retval = WaitForMultipleObjectsEx( count, handles, wait_all, timeout, FALSE );
227 RestoreThunkLock( mutex_count );
228 return retval;
231 /***********************************************************************
232 * WaitForMultipleObjectsEx (KERNEL.495)
234 DWORD WINAPI WaitForMultipleObjectsEx16( DWORD count, const HANDLE *handles,
235 BOOL wait_all, DWORD timeout, BOOL alertable )
237 DWORD retval, mutex_count;
239 ReleaseThunkLock( &mutex_count );
240 retval = WaitForMultipleObjectsEx( count, handles, wait_all, timeout, alertable );
241 RestoreThunkLock( mutex_count );
242 return retval;
245 /***********************************************************************
246 * RegisterWaitForSingleObject (KERNEL32.@)
248 BOOL WINAPI RegisterWaitForSingleObject(PHANDLE phNewWaitObject, HANDLE hObject,
249 WAITORTIMERCALLBACK Callback, PVOID Context,
250 ULONG dwMilliseconds, ULONG dwFlags)
252 NTSTATUS status;
254 TRACE("%p %p %p %p %d %d\n",
255 phNewWaitObject,hObject,Callback,Context,dwMilliseconds,dwFlags);
257 status = RtlRegisterWait( phNewWaitObject, hObject, Callback, Context, dwMilliseconds, dwFlags );
258 if (status != STATUS_SUCCESS)
260 SetLastError( RtlNtStatusToDosError(status) );
261 return FALSE;
263 return TRUE;
266 /***********************************************************************
267 * RegisterWaitForSingleObjectEx (KERNEL32.@)
269 HANDLE WINAPI RegisterWaitForSingleObjectEx( HANDLE hObject,
270 WAITORTIMERCALLBACK Callback, PVOID Context,
271 ULONG dwMilliseconds, ULONG dwFlags )
273 NTSTATUS status;
274 HANDLE hNewWaitObject;
276 TRACE("%p %p %p %d %d\n",
277 hObject,Callback,Context,dwMilliseconds,dwFlags);
279 status = RtlRegisterWait( &hNewWaitObject, hObject, Callback, Context, dwMilliseconds, dwFlags );
280 if (status != STATUS_SUCCESS)
282 SetLastError( RtlNtStatusToDosError(status) );
283 return NULL;
285 return hNewWaitObject;
288 /***********************************************************************
289 * UnregisterWait (KERNEL32.@)
291 BOOL WINAPI UnregisterWait( HANDLE WaitHandle )
293 NTSTATUS status;
295 TRACE("%p\n",WaitHandle);
297 status = RtlDeregisterWait( WaitHandle );
298 if (status != STATUS_SUCCESS)
300 SetLastError( RtlNtStatusToDosError(status) );
301 return FALSE;
303 return TRUE;
306 /***********************************************************************
307 * UnregisterWaitEx (KERNEL32.@)
309 BOOL WINAPI UnregisterWaitEx( HANDLE WaitHandle, HANDLE CompletionEvent )
311 NTSTATUS status;
313 TRACE("%p %p\n",WaitHandle, CompletionEvent);
315 status = RtlDeregisterWaitEx( WaitHandle, CompletionEvent );
316 if (status != STATUS_SUCCESS) SetLastError( RtlNtStatusToDosError(status) );
317 return !status;
320 /***********************************************************************
321 * SignalObjectAndWait (KERNEL32.@)
323 * Allows to atomically signal any of the synchro objects (semaphore,
324 * mutex, event) and wait on another.
326 DWORD WINAPI SignalObjectAndWait( HANDLE hObjectToSignal, HANDLE hObjectToWaitOn,
327 DWORD dwMilliseconds, BOOL bAlertable )
329 NTSTATUS status;
330 LARGE_INTEGER timeout;
332 TRACE("%p %p %d %d\n", hObjectToSignal,
333 hObjectToWaitOn, dwMilliseconds, bAlertable);
335 status = NtSignalAndWaitForSingleObject( hObjectToSignal, hObjectToWaitOn, bAlertable,
336 get_nt_timeout( &timeout, dwMilliseconds ) );
337 if (HIWORD(status))
339 SetLastError( RtlNtStatusToDosError(status) );
340 status = WAIT_FAILED;
342 return status;
345 /***********************************************************************
346 * InitializeCriticalSection (KERNEL32.@)
348 * Initialise a critical section before use.
350 * PARAMS
351 * crit [O] Critical section to initialise.
353 * RETURNS
354 * Nothing. If the function fails an exception is raised.
356 void WINAPI InitializeCriticalSection( CRITICAL_SECTION *crit )
358 InitializeCriticalSectionEx( crit, 0, 0 );
361 /***********************************************************************
362 * InitializeCriticalSectionAndSpinCount (KERNEL32.@)
364 * Initialise a critical section with a spin count.
366 * PARAMS
367 * crit [O] Critical section to initialise.
368 * spincount [I] Number of times to spin upon contention.
370 * RETURNS
371 * Success: TRUE.
372 * Failure: Nothing. If the function fails an exception is raised.
374 * NOTES
375 * spincount is ignored on uni-processor systems.
377 BOOL WINAPI InitializeCriticalSectionAndSpinCount( CRITICAL_SECTION *crit, DWORD spincount )
379 return InitializeCriticalSectionEx( crit, spincount, 0 );
382 /***********************************************************************
383 * InitializeCriticalSectionEx (KERNEL32.@)
385 * Initialise a critical section with a spin count and flags.
387 * PARAMS
388 * crit [O] Critical section to initialise.
389 * spincount [I] Number of times to spin upon contention.
390 * flags [I] CRITICAL_SECTION_ flags from winbase.h.
392 * RETURNS
393 * Success: TRUE.
394 * Failure: Nothing. If the function fails an exception is raised.
396 * NOTES
397 * spincount is ignored on uni-processor systems.
399 BOOL WINAPI InitializeCriticalSectionEx( CRITICAL_SECTION *crit, DWORD spincount, DWORD flags )
401 NTSTATUS ret = RtlInitializeCriticalSectionEx( crit, spincount, flags );
402 if (ret) RtlRaiseStatus( ret );
403 return !ret;
406 /***********************************************************************
407 * MakeCriticalSectionGlobal (KERNEL32.@)
409 void WINAPI MakeCriticalSectionGlobal( CRITICAL_SECTION *crit )
411 /* let's assume that only one thread at a time will try to do this */
412 HANDLE sem = crit->LockSemaphore;
413 if (!sem) NtCreateSemaphore( &sem, SEMAPHORE_ALL_ACCESS, NULL, 0, 1 );
414 crit->LockSemaphore = ConvertToGlobalHandle( sem );
415 RtlFreeHeap( GetProcessHeap(), 0, crit->DebugInfo );
416 crit->DebugInfo = NULL;
420 /***********************************************************************
421 * ReinitializeCriticalSection (KERNEL32.@)
423 * Initialise an already used critical section.
425 * PARAMS
426 * crit [O] Critical section to initialise.
428 * RETURNS
429 * Nothing.
431 void WINAPI ReinitializeCriticalSection( CRITICAL_SECTION *crit )
433 if ( !crit->LockSemaphore )
434 RtlInitializeCriticalSection( crit );
438 /***********************************************************************
439 * UninitializeCriticalSection (KERNEL32.@)
441 * UnInitialise a critical section after use.
443 * PARAMS
444 * crit [O] Critical section to uninitialise (destroy).
446 * RETURNS
447 * Nothing.
449 void WINAPI UninitializeCriticalSection( CRITICAL_SECTION *crit )
451 RtlDeleteCriticalSection( crit );
455 /***********************************************************************
456 * CreateEventA (KERNEL32.@)
458 HANDLE WINAPI CreateEventA( SECURITY_ATTRIBUTES *sa, BOOL manual_reset,
459 BOOL initial_state, LPCSTR name )
461 WCHAR buffer[MAX_PATH];
463 if (!name) return CreateEventW( sa, manual_reset, initial_state, NULL );
465 if (!MultiByteToWideChar( CP_ACP, 0, name, -1, buffer, MAX_PATH ))
467 SetLastError( ERROR_FILENAME_EXCED_RANGE );
468 return 0;
470 return CreateEventW( sa, manual_reset, initial_state, buffer );
474 /***********************************************************************
475 * CreateEventW (KERNEL32.@)
477 HANDLE WINAPI CreateEventW( SECURITY_ATTRIBUTES *sa, BOOL manual_reset,
478 BOOL initial_state, LPCWSTR name )
480 HANDLE ret;
481 UNICODE_STRING nameW;
482 OBJECT_ATTRIBUTES attr;
483 NTSTATUS status;
485 /* one buggy program needs this
486 * ("Van Dale Groot woordenboek der Nederlandse taal")
488 if (sa && IsBadReadPtr(sa,sizeof(SECURITY_ATTRIBUTES)))
490 ERR("Bad security attributes pointer %p\n",sa);
491 SetLastError( ERROR_INVALID_PARAMETER);
492 return 0;
495 attr.Length = sizeof(attr);
496 attr.RootDirectory = 0;
497 attr.ObjectName = NULL;
498 attr.Attributes = OBJ_OPENIF | ((sa && sa->bInheritHandle) ? OBJ_INHERIT : 0);
499 attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
500 attr.SecurityQualityOfService = NULL;
501 if (name)
503 RtlInitUnicodeString( &nameW, name );
504 attr.ObjectName = &nameW;
505 attr.RootDirectory = get_BaseNamedObjects_handle();
508 status = NtCreateEvent( &ret, EVENT_ALL_ACCESS, &attr, manual_reset, initial_state );
509 if (status == STATUS_OBJECT_NAME_EXISTS)
510 SetLastError( ERROR_ALREADY_EXISTS );
511 else
512 SetLastError( RtlNtStatusToDosError(status) );
513 return ret;
517 /***********************************************************************
518 * CreateW32Event (KERNEL.457)
520 HANDLE WINAPI WIN16_CreateEvent( BOOL manual_reset, BOOL initial_state )
522 return CreateEventW( NULL, manual_reset, initial_state, NULL );
526 /***********************************************************************
527 * OpenEventA (KERNEL32.@)
529 HANDLE WINAPI OpenEventA( DWORD access, BOOL inherit, LPCSTR name )
531 WCHAR buffer[MAX_PATH];
533 if (!name) return OpenEventW( access, inherit, NULL );
535 if (!MultiByteToWideChar( CP_ACP, 0, name, -1, buffer, MAX_PATH ))
537 SetLastError( ERROR_FILENAME_EXCED_RANGE );
538 return 0;
540 return OpenEventW( access, inherit, buffer );
544 /***********************************************************************
545 * OpenEventW (KERNEL32.@)
547 HANDLE WINAPI OpenEventW( DWORD access, BOOL inherit, LPCWSTR name )
549 HANDLE ret;
550 UNICODE_STRING nameW;
551 OBJECT_ATTRIBUTES attr;
552 NTSTATUS status;
554 if (!is_version_nt()) access = EVENT_ALL_ACCESS;
556 attr.Length = sizeof(attr);
557 attr.RootDirectory = 0;
558 attr.ObjectName = NULL;
559 attr.Attributes = inherit ? OBJ_INHERIT : 0;
560 attr.SecurityDescriptor = NULL;
561 attr.SecurityQualityOfService = NULL;
562 if (name)
564 RtlInitUnicodeString( &nameW, name );
565 attr.ObjectName = &nameW;
566 attr.RootDirectory = get_BaseNamedObjects_handle();
569 status = NtOpenEvent( &ret, access, &attr );
570 if (status != STATUS_SUCCESS)
572 SetLastError( RtlNtStatusToDosError(status) );
573 return 0;
575 return ret;
578 /***********************************************************************
579 * PulseEvent (KERNEL32.@)
581 BOOL WINAPI PulseEvent( HANDLE handle )
583 NTSTATUS status;
585 if ((status = NtPulseEvent( handle, NULL )))
586 SetLastError( RtlNtStatusToDosError(status) );
587 return !status;
591 /***********************************************************************
592 * SetW32Event (KERNEL.458)
593 * SetEvent (KERNEL32.@)
595 BOOL WINAPI SetEvent( HANDLE handle )
597 NTSTATUS status;
599 if ((status = NtSetEvent( handle, NULL )))
600 SetLastError( RtlNtStatusToDosError(status) );
601 return !status;
605 /***********************************************************************
606 * ResetW32Event (KERNEL.459)
607 * ResetEvent (KERNEL32.@)
609 BOOL WINAPI ResetEvent( HANDLE handle )
611 NTSTATUS status;
613 if ((status = NtResetEvent( handle, NULL )))
614 SetLastError( RtlNtStatusToDosError(status) );
615 return !status;
619 /***********************************************************************
620 * NOTE: The Win95 VWin32_Event routines given below are really low-level
621 * routines implemented directly by VWin32. The user-mode libraries
622 * implement Win32 synchronisation routines on top of these low-level
623 * primitives. We do it the other way around here :-)
626 /***********************************************************************
627 * VWin32_EventCreate (KERNEL.442)
629 HANDLE WINAPI VWin32_EventCreate(VOID)
631 HANDLE hEvent = CreateEventW( NULL, FALSE, 0, NULL );
632 return ConvertToGlobalHandle( hEvent );
635 /***********************************************************************
636 * VWin32_EventDestroy (KERNEL.443)
638 VOID WINAPI VWin32_EventDestroy(HANDLE event)
640 CloseHandle( event );
643 /***********************************************************************
644 * VWin32_EventWait (KERNEL.450)
646 VOID WINAPI VWin32_EventWait(HANDLE event)
648 DWORD mutex_count;
650 ReleaseThunkLock( &mutex_count );
651 WaitForSingleObject( event, INFINITE );
652 RestoreThunkLock( mutex_count );
655 /***********************************************************************
656 * VWin32_EventSet (KERNEL.451)
657 * KERNEL_479 (KERNEL.479)
659 VOID WINAPI VWin32_EventSet(HANDLE event)
661 SetEvent( event );
666 /***********************************************************************
667 * CreateMutexA (KERNEL32.@)
669 HANDLE WINAPI CreateMutexA( SECURITY_ATTRIBUTES *sa, BOOL owner, LPCSTR name )
671 WCHAR buffer[MAX_PATH];
673 if (!name) return CreateMutexW( sa, owner, NULL );
675 if (!MultiByteToWideChar( CP_ACP, 0, name, -1, buffer, MAX_PATH ))
677 SetLastError( ERROR_FILENAME_EXCED_RANGE );
678 return 0;
680 return CreateMutexW( sa, owner, buffer );
684 /***********************************************************************
685 * CreateMutexW (KERNEL32.@)
687 HANDLE WINAPI CreateMutexW( SECURITY_ATTRIBUTES *sa, BOOL owner, LPCWSTR name )
689 HANDLE ret;
690 UNICODE_STRING nameW;
691 OBJECT_ATTRIBUTES attr;
692 NTSTATUS status;
694 attr.Length = sizeof(attr);
695 attr.RootDirectory = 0;
696 attr.ObjectName = NULL;
697 attr.Attributes = OBJ_OPENIF | ((sa && sa->bInheritHandle) ? OBJ_INHERIT : 0);
698 attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
699 attr.SecurityQualityOfService = NULL;
700 if (name)
702 RtlInitUnicodeString( &nameW, name );
703 attr.ObjectName = &nameW;
704 attr.RootDirectory = get_BaseNamedObjects_handle();
707 status = NtCreateMutant( &ret, MUTEX_ALL_ACCESS, &attr, owner );
708 if (status == STATUS_OBJECT_NAME_EXISTS)
709 SetLastError( ERROR_ALREADY_EXISTS );
710 else
711 SetLastError( RtlNtStatusToDosError(status) );
712 return ret;
716 /***********************************************************************
717 * OpenMutexA (KERNEL32.@)
719 HANDLE WINAPI OpenMutexA( DWORD access, BOOL inherit, LPCSTR name )
721 WCHAR buffer[MAX_PATH];
723 if (!name) return OpenMutexW( access, inherit, NULL );
725 if (!MultiByteToWideChar( CP_ACP, 0, name, -1, buffer, MAX_PATH ))
727 SetLastError( ERROR_FILENAME_EXCED_RANGE );
728 return 0;
730 return OpenMutexW( access, inherit, buffer );
734 /***********************************************************************
735 * OpenMutexW (KERNEL32.@)
737 HANDLE WINAPI OpenMutexW( DWORD access, BOOL inherit, LPCWSTR name )
739 HANDLE ret;
740 UNICODE_STRING nameW;
741 OBJECT_ATTRIBUTES attr;
742 NTSTATUS status;
744 if (!is_version_nt()) access = MUTEX_ALL_ACCESS;
746 attr.Length = sizeof(attr);
747 attr.RootDirectory = 0;
748 attr.ObjectName = NULL;
749 attr.Attributes = inherit ? OBJ_INHERIT : 0;
750 attr.SecurityDescriptor = NULL;
751 attr.SecurityQualityOfService = NULL;
752 if (name)
754 RtlInitUnicodeString( &nameW, name );
755 attr.ObjectName = &nameW;
756 attr.RootDirectory = get_BaseNamedObjects_handle();
759 status = NtOpenMutant( &ret, access, &attr );
760 if (status != STATUS_SUCCESS)
762 SetLastError( RtlNtStatusToDosError(status) );
763 return 0;
765 return ret;
769 /***********************************************************************
770 * ReleaseMutex (KERNEL32.@)
772 BOOL WINAPI ReleaseMutex( HANDLE handle )
774 NTSTATUS status;
776 status = NtReleaseMutant(handle, NULL);
777 if (status != STATUS_SUCCESS)
779 SetLastError( RtlNtStatusToDosError(status) );
780 return FALSE;
782 return TRUE;
787 * Semaphores
791 /***********************************************************************
792 * CreateSemaphoreA (KERNEL32.@)
794 HANDLE WINAPI CreateSemaphoreA( SECURITY_ATTRIBUTES *sa, LONG initial, LONG max, LPCSTR name )
796 WCHAR buffer[MAX_PATH];
798 if (!name) return CreateSemaphoreW( sa, initial, max, NULL );
800 if (!MultiByteToWideChar( CP_ACP, 0, name, -1, buffer, MAX_PATH ))
802 SetLastError( ERROR_FILENAME_EXCED_RANGE );
803 return 0;
805 return CreateSemaphoreW( sa, initial, max, buffer );
809 /***********************************************************************
810 * CreateSemaphoreW (KERNEL32.@)
812 HANDLE WINAPI CreateSemaphoreW( SECURITY_ATTRIBUTES *sa, LONG initial,
813 LONG max, LPCWSTR name )
815 HANDLE ret;
816 UNICODE_STRING nameW;
817 OBJECT_ATTRIBUTES attr;
818 NTSTATUS status;
820 attr.Length = sizeof(attr);
821 attr.RootDirectory = 0;
822 attr.ObjectName = NULL;
823 attr.Attributes = OBJ_OPENIF | ((sa && sa->bInheritHandle) ? OBJ_INHERIT : 0);
824 attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
825 attr.SecurityQualityOfService = NULL;
826 if (name)
828 RtlInitUnicodeString( &nameW, name );
829 attr.ObjectName = &nameW;
830 attr.RootDirectory = get_BaseNamedObjects_handle();
833 status = NtCreateSemaphore( &ret, SEMAPHORE_ALL_ACCESS, &attr, initial, max );
834 if (status == STATUS_OBJECT_NAME_EXISTS)
835 SetLastError( ERROR_ALREADY_EXISTS );
836 else
837 SetLastError( RtlNtStatusToDosError(status) );
838 return ret;
842 /***********************************************************************
843 * OpenSemaphoreA (KERNEL32.@)
845 HANDLE WINAPI OpenSemaphoreA( DWORD access, BOOL inherit, LPCSTR name )
847 WCHAR buffer[MAX_PATH];
849 if (!name) return OpenSemaphoreW( access, inherit, NULL );
851 if (!MultiByteToWideChar( CP_ACP, 0, name, -1, buffer, MAX_PATH ))
853 SetLastError( ERROR_FILENAME_EXCED_RANGE );
854 return 0;
856 return OpenSemaphoreW( access, inherit, buffer );
860 /***********************************************************************
861 * OpenSemaphoreW (KERNEL32.@)
863 HANDLE WINAPI OpenSemaphoreW( DWORD access, BOOL inherit, LPCWSTR name )
865 HANDLE ret;
866 UNICODE_STRING nameW;
867 OBJECT_ATTRIBUTES attr;
868 NTSTATUS status;
870 if (!is_version_nt()) access = SEMAPHORE_ALL_ACCESS;
872 attr.Length = sizeof(attr);
873 attr.RootDirectory = 0;
874 attr.ObjectName = NULL;
875 attr.Attributes = inherit ? OBJ_INHERIT : 0;
876 attr.SecurityDescriptor = NULL;
877 attr.SecurityQualityOfService = NULL;
878 if (name)
880 RtlInitUnicodeString( &nameW, name );
881 attr.ObjectName = &nameW;
882 attr.RootDirectory = get_BaseNamedObjects_handle();
885 status = NtOpenSemaphore( &ret, access, &attr );
886 if (status != STATUS_SUCCESS)
888 SetLastError( RtlNtStatusToDosError(status) );
889 return 0;
891 return ret;
895 /***********************************************************************
896 * ReleaseSemaphore (KERNEL32.@)
898 BOOL WINAPI ReleaseSemaphore( HANDLE handle, LONG count, LONG *previous )
900 NTSTATUS status = NtReleaseSemaphore( handle, count, (PULONG)previous );
901 if (status) SetLastError( RtlNtStatusToDosError(status) );
902 return !status;
907 * Jobs
910 /******************************************************************************
911 * CreateJobObjectW (KERNEL32.@)
913 HANDLE WINAPI CreateJobObjectW( LPSECURITY_ATTRIBUTES sa, LPCWSTR name )
915 HANDLE ret = 0;
916 UNICODE_STRING nameW;
917 OBJECT_ATTRIBUTES attr;
918 NTSTATUS status;
920 attr.Length = sizeof(attr);
921 attr.RootDirectory = 0;
922 attr.ObjectName = NULL;
923 attr.Attributes = OBJ_OPENIF | ((sa && sa->bInheritHandle) ? OBJ_INHERIT : 0);
924 attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
925 attr.SecurityQualityOfService = NULL;
926 if (name)
928 RtlInitUnicodeString( &nameW, name );
929 attr.ObjectName = &nameW;
930 attr.RootDirectory = get_BaseNamedObjects_handle();
933 status = NtCreateJobObject( &ret, JOB_OBJECT_ALL_ACCESS, &attr );
934 if (status == STATUS_OBJECT_NAME_EXISTS)
935 SetLastError( ERROR_ALREADY_EXISTS );
936 else
937 SetLastError( RtlNtStatusToDosError(status) );
938 return ret;
941 /******************************************************************************
942 * CreateJobObjectA (KERNEL32.@)
944 HANDLE WINAPI CreateJobObjectA( LPSECURITY_ATTRIBUTES attr, LPCSTR name )
946 WCHAR buffer[MAX_PATH];
948 if (!name) return CreateJobObjectW( attr, NULL );
950 if (!MultiByteToWideChar( CP_ACP, 0, name, -1, buffer, MAX_PATH ))
952 SetLastError( ERROR_FILENAME_EXCED_RANGE );
953 return 0;
955 return CreateJobObjectW( attr, buffer );
958 /******************************************************************************
959 * OpenJobObjectW (KERNEL32.@)
961 HANDLE WINAPI OpenJobObjectW( DWORD access, BOOL inherit, LPCWSTR name )
963 HANDLE ret;
964 UNICODE_STRING nameW;
965 OBJECT_ATTRIBUTES attr;
966 NTSTATUS status;
968 attr.Length = sizeof(attr);
969 attr.RootDirectory = 0;
970 attr.ObjectName = NULL;
971 attr.Attributes = inherit ? OBJ_INHERIT : 0;
972 attr.SecurityDescriptor = NULL;
973 attr.SecurityQualityOfService = NULL;
974 if (name)
976 RtlInitUnicodeString( &nameW, name );
977 attr.ObjectName = &nameW;
978 attr.RootDirectory = get_BaseNamedObjects_handle();
981 status = NtOpenJobObject( &ret, access, &attr );
982 if (status != STATUS_SUCCESS)
984 SetLastError( RtlNtStatusToDosError(status) );
985 return 0;
987 return ret;
990 /******************************************************************************
991 * OpenJobObjectA (KERNEL32.@)
993 HANDLE WINAPI OpenJobObjectA( DWORD access, BOOL inherit, LPCSTR name )
995 WCHAR buffer[MAX_PATH];
997 if (!name) return OpenJobObjectW( access, inherit, NULL );
999 if (!MultiByteToWideChar( CP_ACP, 0, name, -1, buffer, MAX_PATH ))
1001 SetLastError( ERROR_FILENAME_EXCED_RANGE );
1002 return 0;
1004 return OpenJobObjectW( access, inherit, buffer );
1007 /******************************************************************************
1008 * TerminateJobObject (KERNEL32.@)
1010 BOOL WINAPI TerminateJobObject( HANDLE job, UINT exit_code )
1012 NTSTATUS status = NtTerminateJobObject( job, exit_code );
1013 if (status) SetLastError( RtlNtStatusToDosError(status) );
1014 return !status;
1017 /******************************************************************************
1018 * QueryInformationJobObject (KERNEL32.@)
1020 BOOL WINAPI QueryInformationJobObject( HANDLE job, JOBOBJECTINFOCLASS class, LPVOID info,
1021 DWORD len, DWORD *ret_len )
1023 NTSTATUS status = NtQueryInformationJobObject( job, class, info, len, ret_len );
1024 if (status) SetLastError( RtlNtStatusToDosError(status) );
1025 return !status;
1028 /******************************************************************************
1029 * SetInformationJobObject (KERNEL32.@)
1031 BOOL WINAPI SetInformationJobObject( HANDLE job, JOBOBJECTINFOCLASS class, LPVOID info, DWORD len )
1033 NTSTATUS status = NtSetInformationJobObject( job, class, info, len );
1034 if (status) SetLastError( RtlNtStatusToDosError(status) );
1035 return !status;
1038 /******************************************************************************
1039 * AssignProcessToJobObject (KERNEL32.@)
1041 BOOL WINAPI AssignProcessToJobObject( HANDLE job, HANDLE process )
1043 NTSTATUS status = NtAssignProcessToJobObject( job, process );
1044 if (status) SetLastError( RtlNtStatusToDosError(status) );
1045 return !status;
1048 /******************************************************************************
1049 * IsProcessInJob (KERNEL32.@)
1051 BOOL WINAPI IsProcessInJob( HANDLE process, HANDLE job, PBOOL result )
1053 NTSTATUS status = NtIsProcessInJob( job, process );
1054 switch(status)
1056 case STATUS_PROCESS_IN_JOB:
1057 *result = TRUE;
1058 return TRUE;
1059 case STATUS_PROCESS_NOT_IN_JOB:
1060 *result = FALSE;
1061 return TRUE;
1062 default:
1063 SetLastError( RtlNtStatusToDosError(status) );
1064 return FALSE;
1070 * Timers
1074 /***********************************************************************
1075 * CreateWaitableTimerA (KERNEL32.@)
1077 HANDLE WINAPI CreateWaitableTimerA( SECURITY_ATTRIBUTES *sa, BOOL manual, LPCSTR name )
1079 WCHAR buffer[MAX_PATH];
1081 if (!name) return CreateWaitableTimerW( sa, manual, NULL );
1083 if (!MultiByteToWideChar( CP_ACP, 0, name, -1, buffer, MAX_PATH ))
1085 SetLastError( ERROR_FILENAME_EXCED_RANGE );
1086 return 0;
1088 return CreateWaitableTimerW( sa, manual, buffer );
1092 /***********************************************************************
1093 * CreateWaitableTimerW (KERNEL32.@)
1095 HANDLE WINAPI CreateWaitableTimerW( SECURITY_ATTRIBUTES *sa, BOOL manual, LPCWSTR name )
1097 HANDLE handle;
1098 NTSTATUS status;
1099 UNICODE_STRING nameW;
1100 OBJECT_ATTRIBUTES attr;
1102 attr.Length = sizeof(attr);
1103 attr.RootDirectory = 0;
1104 attr.ObjectName = NULL;
1105 attr.Attributes = OBJ_OPENIF | ((sa && sa->bInheritHandle) ? OBJ_INHERIT : 0);
1106 attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
1107 attr.SecurityQualityOfService = NULL;
1108 if (name)
1110 RtlInitUnicodeString( &nameW, name );
1111 attr.ObjectName = &nameW;
1112 attr.RootDirectory = get_BaseNamedObjects_handle();
1115 status = NtCreateTimer(&handle, TIMER_ALL_ACCESS, &attr,
1116 manual ? NotificationTimer : SynchronizationTimer);
1117 if (status == STATUS_OBJECT_NAME_EXISTS)
1118 SetLastError( ERROR_ALREADY_EXISTS );
1119 else
1120 SetLastError( RtlNtStatusToDosError(status) );
1121 return handle;
1125 /***********************************************************************
1126 * OpenWaitableTimerA (KERNEL32.@)
1128 HANDLE WINAPI OpenWaitableTimerA( DWORD access, BOOL inherit, LPCSTR name )
1130 WCHAR buffer[MAX_PATH];
1132 if (!name) return OpenWaitableTimerW( access, inherit, NULL );
1134 if (!MultiByteToWideChar( CP_ACP, 0, name, -1, buffer, MAX_PATH ))
1136 SetLastError( ERROR_FILENAME_EXCED_RANGE );
1137 return 0;
1139 return OpenWaitableTimerW( access, inherit, buffer );
1143 /***********************************************************************
1144 * OpenWaitableTimerW (KERNEL32.@)
1146 HANDLE WINAPI OpenWaitableTimerW( DWORD access, BOOL inherit, LPCWSTR name )
1148 HANDLE handle;
1149 UNICODE_STRING nameW;
1150 OBJECT_ATTRIBUTES attr;
1151 NTSTATUS status;
1153 if (!is_version_nt()) access = TIMER_ALL_ACCESS;
1155 attr.Length = sizeof(attr);
1156 attr.RootDirectory = 0;
1157 attr.ObjectName = NULL;
1158 attr.Attributes = inherit ? OBJ_INHERIT : 0;
1159 attr.SecurityDescriptor = NULL;
1160 attr.SecurityQualityOfService = NULL;
1161 if (name)
1163 RtlInitUnicodeString( &nameW, name );
1164 attr.ObjectName = &nameW;
1165 attr.RootDirectory = get_BaseNamedObjects_handle();
1168 status = NtOpenTimer(&handle, access, &attr);
1169 if (status != STATUS_SUCCESS)
1171 SetLastError( RtlNtStatusToDosError(status) );
1172 return 0;
1174 return handle;
1178 /***********************************************************************
1179 * SetWaitableTimer (KERNEL32.@)
1181 BOOL WINAPI SetWaitableTimer( HANDLE handle, const LARGE_INTEGER *when, LONG period,
1182 PTIMERAPCROUTINE callback, LPVOID arg, BOOL resume )
1184 NTSTATUS status = NtSetTimer(handle, when, (PTIMER_APC_ROUTINE)callback,
1185 arg, resume, period, NULL);
1187 if (status != STATUS_SUCCESS)
1189 SetLastError( RtlNtStatusToDosError(status) );
1190 if (status != STATUS_TIMER_RESUME_IGNORED) return FALSE;
1192 return TRUE;
1196 /***********************************************************************
1197 * CancelWaitableTimer (KERNEL32.@)
1199 BOOL WINAPI CancelWaitableTimer( HANDLE handle )
1201 NTSTATUS status;
1203 status = NtCancelTimer(handle, NULL);
1204 if (status != STATUS_SUCCESS)
1206 SetLastError( RtlNtStatusToDosError(status) );
1207 return FALSE;
1209 return TRUE;
1213 /***********************************************************************
1214 * CreateTimerQueue (KERNEL32.@)
1216 HANDLE WINAPI CreateTimerQueue(void)
1218 HANDLE q;
1219 NTSTATUS status = RtlCreateTimerQueue(&q);
1221 if (status != STATUS_SUCCESS)
1223 SetLastError( RtlNtStatusToDosError(status) );
1224 return NULL;
1227 return q;
1231 /***********************************************************************
1232 * DeleteTimerQueueEx (KERNEL32.@)
1234 BOOL WINAPI DeleteTimerQueueEx(HANDLE TimerQueue, HANDLE CompletionEvent)
1236 NTSTATUS status = RtlDeleteTimerQueueEx(TimerQueue, CompletionEvent);
1238 if (status != STATUS_SUCCESS)
1240 SetLastError( RtlNtStatusToDosError(status) );
1241 return FALSE;
1244 return TRUE;
1247 /***********************************************************************
1248 * CreateTimerQueueTimer (KERNEL32.@)
1250 * Creates a timer-queue timer. This timer expires at the specified due
1251 * time (in ms), then after every specified period (in ms). When the timer
1252 * expires, the callback function is called.
1254 * RETURNS
1255 * nonzero on success or zero on failure
1257 BOOL WINAPI CreateTimerQueueTimer( PHANDLE phNewTimer, HANDLE TimerQueue,
1258 WAITORTIMERCALLBACK Callback, PVOID Parameter,
1259 DWORD DueTime, DWORD Period, ULONG Flags )
1261 NTSTATUS status = RtlCreateTimer(phNewTimer, TimerQueue, Callback,
1262 Parameter, DueTime, Period, Flags);
1264 if (status != STATUS_SUCCESS)
1266 SetLastError( RtlNtStatusToDosError(status) );
1267 return FALSE;
1270 return TRUE;
1273 /***********************************************************************
1274 * ChangeTimerQueueTimer (KERNEL32.@)
1276 * Changes the times at which the timer expires.
1278 * RETURNS
1279 * nonzero on success or zero on failure
1281 BOOL WINAPI ChangeTimerQueueTimer( HANDLE TimerQueue, HANDLE Timer,
1282 ULONG DueTime, ULONG Period )
1284 NTSTATUS status = RtlUpdateTimer(TimerQueue, Timer, DueTime, Period);
1286 if (status != STATUS_SUCCESS)
1288 SetLastError( RtlNtStatusToDosError(status) );
1289 return FALSE;
1292 return TRUE;
1295 /***********************************************************************
1296 * DeleteTimerQueueTimer (KERNEL32.@)
1298 * Cancels a timer-queue timer.
1300 * RETURNS
1301 * nonzero on success or zero on failure
1303 BOOL WINAPI DeleteTimerQueueTimer( HANDLE TimerQueue, HANDLE Timer,
1304 HANDLE CompletionEvent )
1306 NTSTATUS status = RtlDeleteTimer(TimerQueue, Timer, CompletionEvent);
1307 if (status != STATUS_SUCCESS)
1309 SetLastError( RtlNtStatusToDosError(status) );
1310 return FALSE;
1312 return TRUE;
1317 * Pipes
1321 /***********************************************************************
1322 * CreateNamedPipeA (KERNEL32.@)
1324 HANDLE WINAPI CreateNamedPipeA( LPCSTR name, DWORD dwOpenMode,
1325 DWORD dwPipeMode, DWORD nMaxInstances,
1326 DWORD nOutBufferSize, DWORD nInBufferSize,
1327 DWORD nDefaultTimeOut, LPSECURITY_ATTRIBUTES attr )
1329 WCHAR buffer[MAX_PATH];
1331 if (!name) return CreateNamedPipeW( NULL, dwOpenMode, dwPipeMode, nMaxInstances,
1332 nOutBufferSize, nInBufferSize, nDefaultTimeOut, attr );
1334 if (!MultiByteToWideChar( CP_ACP, 0, name, -1, buffer, MAX_PATH ))
1336 SetLastError( ERROR_FILENAME_EXCED_RANGE );
1337 return INVALID_HANDLE_VALUE;
1339 return CreateNamedPipeW( buffer, dwOpenMode, dwPipeMode, nMaxInstances,
1340 nOutBufferSize, nInBufferSize, nDefaultTimeOut, attr );
1344 /***********************************************************************
1345 * CreateNamedPipeW (KERNEL32.@)
1347 HANDLE WINAPI CreateNamedPipeW( LPCWSTR name, DWORD dwOpenMode,
1348 DWORD dwPipeMode, DWORD nMaxInstances,
1349 DWORD nOutBufferSize, DWORD nInBufferSize,
1350 DWORD nDefaultTimeOut, LPSECURITY_ATTRIBUTES sa )
1352 HANDLE handle;
1353 UNICODE_STRING nt_name;
1354 OBJECT_ATTRIBUTES attr;
1355 DWORD access, options;
1356 BOOLEAN pipe_type, read_mode, non_block;
1357 NTSTATUS status;
1358 IO_STATUS_BLOCK iosb;
1359 LARGE_INTEGER timeout;
1361 TRACE("(%s, %#08x, %#08x, %d, %d, %d, %d, %p)\n",
1362 debugstr_w(name), dwOpenMode, dwPipeMode, nMaxInstances,
1363 nOutBufferSize, nInBufferSize, nDefaultTimeOut, sa );
1365 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
1367 SetLastError( ERROR_PATH_NOT_FOUND );
1368 return INVALID_HANDLE_VALUE;
1370 if (nt_name.Length >= MAX_PATH * sizeof(WCHAR) )
1372 SetLastError( ERROR_FILENAME_EXCED_RANGE );
1373 RtlFreeUnicodeString( &nt_name );
1374 return INVALID_HANDLE_VALUE;
1377 attr.Length = sizeof(attr);
1378 attr.RootDirectory = 0;
1379 attr.ObjectName = &nt_name;
1380 attr.Attributes = OBJ_CASE_INSENSITIVE |
1381 ((sa && sa->bInheritHandle) ? OBJ_INHERIT : 0);
1382 attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
1383 attr.SecurityQualityOfService = NULL;
1385 switch(dwOpenMode & 3)
1387 case PIPE_ACCESS_INBOUND:
1388 options = FILE_PIPE_INBOUND;
1389 access = GENERIC_READ;
1390 break;
1391 case PIPE_ACCESS_OUTBOUND:
1392 options = FILE_PIPE_OUTBOUND;
1393 access = GENERIC_WRITE;
1394 break;
1395 case PIPE_ACCESS_DUPLEX:
1396 options = FILE_PIPE_FULL_DUPLEX;
1397 access = GENERIC_READ | GENERIC_WRITE;
1398 break;
1399 default:
1400 SetLastError( ERROR_INVALID_PARAMETER );
1401 return INVALID_HANDLE_VALUE;
1403 access |= SYNCHRONIZE;
1404 if (dwOpenMode & FILE_FLAG_WRITE_THROUGH) options |= FILE_WRITE_THROUGH;
1405 if (!(dwOpenMode & FILE_FLAG_OVERLAPPED)) options |= FILE_SYNCHRONOUS_IO_ALERT;
1406 pipe_type = (dwPipeMode & PIPE_TYPE_MESSAGE) ? TRUE : FALSE;
1407 read_mode = (dwPipeMode & PIPE_READMODE_MESSAGE) ? TRUE : FALSE;
1408 non_block = (dwPipeMode & PIPE_NOWAIT) ? TRUE : FALSE;
1409 if (nMaxInstances >= PIPE_UNLIMITED_INSTANCES) nMaxInstances = ~0U;
1411 timeout.QuadPart = (ULONGLONG)nDefaultTimeOut * -10000;
1413 SetLastError(0);
1415 status = NtCreateNamedPipeFile(&handle, access, &attr, &iosb, 0,
1416 FILE_OVERWRITE_IF, options, pipe_type,
1417 read_mode, non_block, nMaxInstances,
1418 nInBufferSize, nOutBufferSize, &timeout);
1420 RtlFreeUnicodeString( &nt_name );
1421 if (status)
1423 handle = INVALID_HANDLE_VALUE;
1424 SetLastError( RtlNtStatusToDosError(status) );
1426 return handle;
1430 /***********************************************************************
1431 * PeekNamedPipe (KERNEL32.@)
1433 BOOL WINAPI PeekNamedPipe( HANDLE hPipe, LPVOID lpvBuffer, DWORD cbBuffer,
1434 LPDWORD lpcbRead, LPDWORD lpcbAvail, LPDWORD lpcbMessage )
1436 FILE_PIPE_PEEK_BUFFER local_buffer;
1437 FILE_PIPE_PEEK_BUFFER *buffer = &local_buffer;
1438 IO_STATUS_BLOCK io;
1439 NTSTATUS status;
1441 if (cbBuffer && !(buffer = HeapAlloc( GetProcessHeap(), 0,
1442 FIELD_OFFSET( FILE_PIPE_PEEK_BUFFER, Data[cbBuffer] ))))
1444 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1445 return FALSE;
1448 status = NtFsControlFile( hPipe, 0, NULL, NULL, &io, FSCTL_PIPE_PEEK, NULL, 0,
1449 buffer, FIELD_OFFSET( FILE_PIPE_PEEK_BUFFER, Data[cbBuffer] ) );
1450 if (!status)
1452 ULONG read_size = io.Information - FIELD_OFFSET( FILE_PIPE_PEEK_BUFFER, Data );
1453 if (lpcbAvail) *lpcbAvail = buffer->ReadDataAvailable;
1454 if (lpcbRead) *lpcbRead = read_size;
1455 if (lpcbMessage) *lpcbMessage = 0; /* FIXME */
1456 if (lpvBuffer) memcpy( lpvBuffer, buffer->Data, read_size );
1458 else SetLastError( RtlNtStatusToDosError(status) );
1460 if (buffer != &local_buffer) HeapFree( GetProcessHeap(), 0, buffer );
1461 return !status;
1464 /***********************************************************************
1465 * WaitNamedPipeA (KERNEL32.@)
1467 BOOL WINAPI WaitNamedPipeA (LPCSTR name, DWORD nTimeOut)
1469 WCHAR buffer[MAX_PATH];
1471 if (!name) return WaitNamedPipeW( NULL, nTimeOut );
1473 if (!MultiByteToWideChar( CP_ACP, 0, name, -1, buffer, MAX_PATH ))
1475 SetLastError( ERROR_FILENAME_EXCED_RANGE );
1476 return 0;
1478 return WaitNamedPipeW( buffer, nTimeOut );
1482 /***********************************************************************
1483 * WaitNamedPipeW (KERNEL32.@)
1485 * Waits for a named pipe instance to become available
1487 * PARAMS
1488 * name [I] Pointer to a named pipe name to wait for
1489 * nTimeOut [I] How long to wait in ms
1491 * RETURNS
1492 * TRUE: Success, named pipe can be opened with CreateFile
1493 * FALSE: Failure, GetLastError can be called for further details
1495 BOOL WINAPI WaitNamedPipeW (LPCWSTR name, DWORD nTimeOut)
1497 static const WCHAR leadin[] = {'\\','?','?','\\','P','I','P','E','\\'};
1498 NTSTATUS status;
1499 UNICODE_STRING nt_name, pipe_dev_name;
1500 FILE_PIPE_WAIT_FOR_BUFFER *pipe_wait;
1501 IO_STATUS_BLOCK iosb;
1502 OBJECT_ATTRIBUTES attr;
1503 ULONG sz_pipe_wait;
1504 HANDLE pipe_dev;
1506 TRACE("%s 0x%08x\n",debugstr_w(name),nTimeOut);
1508 if (!RtlDosPathNameToNtPathName_U( name, &nt_name, NULL, NULL ))
1509 return FALSE;
1511 if (nt_name.Length >= MAX_PATH * sizeof(WCHAR) ||
1512 nt_name.Length < sizeof(leadin) ||
1513 strncmpiW( nt_name.Buffer, leadin, sizeof(leadin)/sizeof(WCHAR)) != 0)
1515 RtlFreeUnicodeString( &nt_name );
1516 SetLastError( ERROR_PATH_NOT_FOUND );
1517 return FALSE;
1520 sz_pipe_wait = sizeof(*pipe_wait) + nt_name.Length - sizeof(leadin) - sizeof(WCHAR);
1521 if (!(pipe_wait = HeapAlloc( GetProcessHeap(), 0, sz_pipe_wait)))
1523 RtlFreeUnicodeString( &nt_name );
1524 SetLastError( ERROR_OUTOFMEMORY );
1525 return FALSE;
1528 pipe_dev_name.Buffer = nt_name.Buffer;
1529 pipe_dev_name.Length = sizeof(leadin);
1530 pipe_dev_name.MaximumLength = sizeof(leadin);
1531 InitializeObjectAttributes(&attr,&pipe_dev_name, OBJ_CASE_INSENSITIVE, NULL, NULL);
1532 status = NtOpenFile( &pipe_dev, FILE_READ_ATTRIBUTES, &attr,
1533 &iosb, FILE_SHARE_READ | FILE_SHARE_WRITE,
1534 FILE_SYNCHRONOUS_IO_NONALERT);
1535 if (status != ERROR_SUCCESS)
1537 SetLastError( ERROR_PATH_NOT_FOUND );
1538 return FALSE;
1541 pipe_wait->TimeoutSpecified = !(nTimeOut == NMPWAIT_USE_DEFAULT_WAIT);
1542 if (nTimeOut == NMPWAIT_WAIT_FOREVER)
1543 pipe_wait->Timeout.QuadPart = ((ULONGLONG)0x7fffffff << 32) | 0xffffffff;
1544 else
1545 pipe_wait->Timeout.QuadPart = (ULONGLONG)nTimeOut * -10000;
1546 pipe_wait->NameLength = nt_name.Length - sizeof(leadin);
1547 memcpy(pipe_wait->Name, nt_name.Buffer + sizeof(leadin)/sizeof(WCHAR),
1548 pipe_wait->NameLength);
1549 RtlFreeUnicodeString( &nt_name );
1551 status = NtFsControlFile( pipe_dev, NULL, NULL, NULL, &iosb, FSCTL_PIPE_WAIT,
1552 pipe_wait, sz_pipe_wait, NULL, 0 );
1554 HeapFree( GetProcessHeap(), 0, pipe_wait );
1555 NtClose( pipe_dev );
1557 if(status != STATUS_SUCCESS)
1559 SetLastError(RtlNtStatusToDosError(status));
1560 return FALSE;
1562 else
1563 return TRUE;
1567 /***********************************************************************
1568 * ConnectNamedPipe (KERNEL32.@)
1570 * Connects to a named pipe
1572 * Parameters
1573 * hPipe: A handle to a named pipe returned by CreateNamedPipe
1574 * overlapped: Optional OVERLAPPED struct
1576 * Return values
1577 * TRUE: Success
1578 * FALSE: Failure, GetLastError can be called for further details
1580 BOOL WINAPI ConnectNamedPipe(HANDLE hPipe, LPOVERLAPPED overlapped)
1582 NTSTATUS status;
1583 IO_STATUS_BLOCK status_block;
1584 LPVOID cvalue = NULL;
1586 TRACE("(%p,%p)\n", hPipe, overlapped);
1588 if(overlapped)
1590 overlapped->Internal = STATUS_PENDING;
1591 overlapped->InternalHigh = 0;
1592 if (((ULONG_PTR)overlapped->hEvent & 1) == 0) cvalue = overlapped;
1595 status = NtFsControlFile(hPipe, overlapped ? overlapped->hEvent : NULL, NULL, cvalue,
1596 overlapped ? (IO_STATUS_BLOCK *)overlapped : &status_block,
1597 FSCTL_PIPE_LISTEN, NULL, 0, NULL, 0);
1599 if (status == STATUS_SUCCESS) return TRUE;
1600 SetLastError( RtlNtStatusToDosError(status) );
1601 return FALSE;
1604 /***********************************************************************
1605 * DisconnectNamedPipe (KERNEL32.@)
1607 * Disconnects from a named pipe
1609 * Parameters
1610 * hPipe: A handle to a named pipe returned by CreateNamedPipe
1612 * Return values
1613 * TRUE: Success
1614 * FALSE: Failure, GetLastError can be called for further details
1616 BOOL WINAPI DisconnectNamedPipe(HANDLE hPipe)
1618 NTSTATUS status;
1619 IO_STATUS_BLOCK io_block;
1621 TRACE("(%p)\n",hPipe);
1623 status = NtFsControlFile(hPipe, 0, NULL, NULL, &io_block, FSCTL_PIPE_DISCONNECT,
1624 NULL, 0, NULL, 0);
1625 if (status == STATUS_SUCCESS) return TRUE;
1626 SetLastError( RtlNtStatusToDosError(status) );
1627 return FALSE;
1630 /***********************************************************************
1631 * TransactNamedPipe (KERNEL32.@)
1633 * BUGS
1634 * should be done as a single operation in the wineserver or kernel
1636 BOOL WINAPI TransactNamedPipe(
1637 HANDLE handle, LPVOID write_buf, DWORD write_size, LPVOID read_buf,
1638 DWORD read_size, LPDWORD bytes_read, LPOVERLAPPED overlapped)
1640 BOOL r;
1641 DWORD count;
1643 TRACE("%p %p %d %p %d %p %p\n",
1644 handle, write_buf, write_size, read_buf,
1645 read_size, bytes_read, overlapped);
1647 if (overlapped)
1649 FIXME("Doesn't support overlapped operation as yet\n");
1650 return FALSE;
1653 r = WriteFile(handle, write_buf, write_size, &count, NULL);
1654 if (r)
1655 r = ReadFile(handle, read_buf, read_size, bytes_read, NULL);
1657 return r;
1660 /***********************************************************************
1661 * GetNamedPipeInfo (KERNEL32.@)
1663 BOOL WINAPI GetNamedPipeInfo(
1664 HANDLE hNamedPipe, LPDWORD lpFlags, LPDWORD lpOutputBufferSize,
1665 LPDWORD lpInputBufferSize, LPDWORD lpMaxInstances)
1667 FILE_PIPE_LOCAL_INFORMATION fpli;
1668 IO_STATUS_BLOCK iosb;
1669 NTSTATUS status;
1671 status = NtQueryInformationFile(hNamedPipe, &iosb, &fpli, sizeof(fpli),
1672 FilePipeLocalInformation);
1673 if (status)
1675 SetLastError( RtlNtStatusToDosError(status) );
1676 return FALSE;
1679 if (lpFlags)
1681 *lpFlags = (fpli.NamedPipeEnd & FILE_PIPE_SERVER_END) ?
1682 PIPE_SERVER_END : PIPE_CLIENT_END;
1683 *lpFlags |= (fpli.NamedPipeType & FILE_PIPE_TYPE_MESSAGE) ?
1684 PIPE_TYPE_MESSAGE : PIPE_TYPE_BYTE;
1687 if (lpOutputBufferSize) *lpOutputBufferSize = fpli.OutboundQuota;
1688 if (lpInputBufferSize) *lpInputBufferSize = fpli.InboundQuota;
1689 if (lpMaxInstances) *lpMaxInstances = fpli.MaximumInstances;
1691 return TRUE;
1694 /***********************************************************************
1695 * GetNamedPipeHandleStateA (KERNEL32.@)
1697 BOOL WINAPI GetNamedPipeHandleStateA(
1698 HANDLE hNamedPipe, LPDWORD lpState, LPDWORD lpCurInstances,
1699 LPDWORD lpMaxCollectionCount, LPDWORD lpCollectDataTimeout,
1700 LPSTR lpUsername, DWORD nUsernameMaxSize)
1702 FIXME("%p %p %p %p %p %p %d\n",
1703 hNamedPipe, lpState, lpCurInstances,
1704 lpMaxCollectionCount, lpCollectDataTimeout,
1705 lpUsername, nUsernameMaxSize);
1707 return FALSE;
1710 /***********************************************************************
1711 * GetNamedPipeHandleStateW (KERNEL32.@)
1713 BOOL WINAPI GetNamedPipeHandleStateW(
1714 HANDLE hNamedPipe, LPDWORD lpState, LPDWORD lpCurInstances,
1715 LPDWORD lpMaxCollectionCount, LPDWORD lpCollectDataTimeout,
1716 LPWSTR lpUsername, DWORD nUsernameMaxSize)
1718 FIXME("%p %p %p %p %p %p %d\n",
1719 hNamedPipe, lpState, lpCurInstances,
1720 lpMaxCollectionCount, lpCollectDataTimeout,
1721 lpUsername, nUsernameMaxSize);
1723 return FALSE;
1726 /***********************************************************************
1727 * SetNamedPipeHandleState (KERNEL32.@)
1729 BOOL WINAPI SetNamedPipeHandleState(
1730 HANDLE hNamedPipe, LPDWORD lpMode, LPDWORD lpMaxCollectionCount,
1731 LPDWORD lpCollectDataTimeout)
1733 /* should be a fixme, but this function is called a lot by the RPC
1734 * runtime, and it slows down InstallShield a fair bit. */
1735 WARN("stub: %p %p/%d %p %p\n",
1736 hNamedPipe, lpMode, lpMode ? *lpMode : 0, lpMaxCollectionCount, lpCollectDataTimeout);
1737 return FALSE;
1740 /***********************************************************************
1741 * CallNamedPipeA (KERNEL32.@)
1743 BOOL WINAPI CallNamedPipeA(
1744 LPCSTR lpNamedPipeName, LPVOID lpInput, DWORD dwInputSize,
1745 LPVOID lpOutput, DWORD dwOutputSize,
1746 LPDWORD lpBytesRead, DWORD nTimeout)
1748 DWORD len;
1749 LPWSTR str = NULL;
1750 BOOL ret;
1752 TRACE("%s %p %d %p %d %p %d\n",
1753 debugstr_a(lpNamedPipeName), lpInput, dwInputSize,
1754 lpOutput, dwOutputSize, lpBytesRead, nTimeout);
1756 if( lpNamedPipeName )
1758 len = MultiByteToWideChar( CP_ACP, 0, lpNamedPipeName, -1, NULL, 0 );
1759 str = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
1760 MultiByteToWideChar( CP_ACP, 0, lpNamedPipeName, -1, str, len );
1762 ret = CallNamedPipeW( str, lpInput, dwInputSize, lpOutput,
1763 dwOutputSize, lpBytesRead, nTimeout );
1764 if( lpNamedPipeName )
1765 HeapFree( GetProcessHeap(), 0, str );
1767 return ret;
1770 /***********************************************************************
1771 * CallNamedPipeW (KERNEL32.@)
1773 BOOL WINAPI CallNamedPipeW(
1774 LPCWSTR lpNamedPipeName, LPVOID lpInput, DWORD lpInputSize,
1775 LPVOID lpOutput, DWORD lpOutputSize,
1776 LPDWORD lpBytesRead, DWORD nTimeout)
1778 HANDLE pipe;
1779 BOOL ret;
1780 DWORD mode;
1782 TRACE("%s %p %d %p %d %p %d\n",
1783 debugstr_w(lpNamedPipeName), lpInput, lpInputSize,
1784 lpOutput, lpOutputSize, lpBytesRead, nTimeout);
1786 pipe = CreateFileW(lpNamedPipeName, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
1787 if (pipe == INVALID_HANDLE_VALUE)
1789 ret = WaitNamedPipeW(lpNamedPipeName, nTimeout);
1790 if (!ret)
1791 return FALSE;
1792 pipe = CreateFileW(lpNamedPipeName, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
1793 if (pipe == INVALID_HANDLE_VALUE)
1794 return FALSE;
1797 mode = PIPE_READMODE_MESSAGE;
1798 ret = SetNamedPipeHandleState(pipe, &mode, NULL, NULL);
1800 /* Currently SetNamedPipeHandleState() is a stub returning FALSE */
1801 if (ret) FIXME("Now that SetNamedPipeHandleState() is more than a stub, please update CallNamedPipeW\n");
1803 if (!ret)
1805 CloseHandle(pipe);
1806 return FALSE;
1809 ret = TransactNamedPipe(pipe, lpInput, lpInputSize, lpOutput, lpOutputSize, lpBytesRead, NULL);
1810 CloseHandle(pipe);
1811 if (!ret)
1812 return FALSE;
1814 return TRUE;
1817 /******************************************************************
1818 * CreatePipe (KERNEL32.@)
1821 BOOL WINAPI CreatePipe( PHANDLE hReadPipe, PHANDLE hWritePipe,
1822 LPSECURITY_ATTRIBUTES sa, DWORD size )
1824 static unsigned index /* = 0 */;
1825 WCHAR name[64];
1826 HANDLE hr, hw;
1827 unsigned in_index = index;
1828 UNICODE_STRING nt_name;
1829 OBJECT_ATTRIBUTES attr;
1830 NTSTATUS status;
1831 IO_STATUS_BLOCK iosb;
1832 LARGE_INTEGER timeout;
1834 *hReadPipe = *hWritePipe = INVALID_HANDLE_VALUE;
1836 attr.Length = sizeof(attr);
1837 attr.RootDirectory = 0;
1838 attr.ObjectName = &nt_name;
1839 attr.Attributes = OBJ_CASE_INSENSITIVE |
1840 ((sa && sa->bInheritHandle) ? OBJ_INHERIT : 0);
1841 attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
1842 attr.SecurityQualityOfService = NULL;
1844 timeout.QuadPart = (ULONGLONG)NMPWAIT_USE_DEFAULT_WAIT * -10000;
1845 /* generate a unique pipe name (system wide) */
1848 static const WCHAR nameFmt[] = { '\\','?','?','\\','p','i','p','e',
1849 '\\','W','i','n','3','2','.','P','i','p','e','s','.','%','0','8','l',
1850 'u','.','%','0','8','u','\0' };
1852 snprintfW(name, sizeof(name) / sizeof(name[0]), nameFmt,
1853 GetCurrentProcessId(), ++index);
1854 RtlInitUnicodeString(&nt_name, name);
1855 status = NtCreateNamedPipeFile(&hr, GENERIC_READ | SYNCHRONIZE, &attr, &iosb,
1856 0, FILE_OVERWRITE_IF,
1857 FILE_SYNCHRONOUS_IO_ALERT | FILE_PIPE_INBOUND,
1858 FALSE, FALSE, FALSE,
1859 1, size, size, &timeout);
1860 if (status)
1862 SetLastError( RtlNtStatusToDosError(status) );
1863 hr = INVALID_HANDLE_VALUE;
1865 } while (hr == INVALID_HANDLE_VALUE && index != in_index);
1866 /* from completion sakeness, I think system resources might be exhausted before this happens !! */
1867 if (hr == INVALID_HANDLE_VALUE) return FALSE;
1869 status = NtOpenFile(&hw, GENERIC_WRITE | SYNCHRONIZE, &attr, &iosb, 0,
1870 FILE_SYNCHRONOUS_IO_ALERT | FILE_NON_DIRECTORY_FILE);
1872 if (status)
1874 SetLastError( RtlNtStatusToDosError(status) );
1875 NtClose(hr);
1876 return FALSE;
1879 *hReadPipe = hr;
1880 *hWritePipe = hw;
1881 return TRUE;
1885 /******************************************************************************
1886 * CreateMailslotA [KERNEL32.@]
1888 * See CreateMailslotW.
1890 HANDLE WINAPI CreateMailslotA( LPCSTR lpName, DWORD nMaxMessageSize,
1891 DWORD lReadTimeout, LPSECURITY_ATTRIBUTES sa )
1893 DWORD len;
1894 HANDLE handle;
1895 LPWSTR name = NULL;
1897 TRACE("%s %d %d %p\n", debugstr_a(lpName),
1898 nMaxMessageSize, lReadTimeout, sa);
1900 if( lpName )
1902 len = MultiByteToWideChar( CP_ACP, 0, lpName, -1, NULL, 0 );
1903 name = HeapAlloc( GetProcessHeap(), 0, len*sizeof(WCHAR) );
1904 MultiByteToWideChar( CP_ACP, 0, lpName, -1, name, len );
1907 handle = CreateMailslotW( name, nMaxMessageSize, lReadTimeout, sa );
1909 HeapFree( GetProcessHeap(), 0, name );
1911 return handle;
1915 /******************************************************************************
1916 * CreateMailslotW [KERNEL32.@]
1918 * Create a mailslot with specified name.
1920 * PARAMS
1921 * lpName [I] Pointer to string for mailslot name
1922 * nMaxMessageSize [I] Maximum message size
1923 * lReadTimeout [I] Milliseconds before read time-out
1924 * sa [I] Pointer to security structure
1926 * RETURNS
1927 * Success: Handle to mailslot
1928 * Failure: INVALID_HANDLE_VALUE
1930 HANDLE WINAPI CreateMailslotW( LPCWSTR lpName, DWORD nMaxMessageSize,
1931 DWORD lReadTimeout, LPSECURITY_ATTRIBUTES sa )
1933 HANDLE handle = INVALID_HANDLE_VALUE;
1934 OBJECT_ATTRIBUTES attr;
1935 UNICODE_STRING nameW;
1936 LARGE_INTEGER timeout;
1937 IO_STATUS_BLOCK iosb;
1938 NTSTATUS status;
1940 TRACE("%s %d %d %p\n", debugstr_w(lpName),
1941 nMaxMessageSize, lReadTimeout, sa);
1943 if (!RtlDosPathNameToNtPathName_U( lpName, &nameW, NULL, NULL ))
1945 SetLastError( ERROR_PATH_NOT_FOUND );
1946 return INVALID_HANDLE_VALUE;
1949 if (nameW.Length >= MAX_PATH * sizeof(WCHAR) )
1951 SetLastError( ERROR_FILENAME_EXCED_RANGE );
1952 RtlFreeUnicodeString( &nameW );
1953 return INVALID_HANDLE_VALUE;
1956 attr.Length = sizeof(attr);
1957 attr.RootDirectory = 0;
1958 attr.Attributes = OBJ_CASE_INSENSITIVE;
1959 attr.ObjectName = &nameW;
1960 attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
1961 attr.SecurityQualityOfService = NULL;
1963 if (lReadTimeout != MAILSLOT_WAIT_FOREVER)
1964 timeout.QuadPart = (ULONGLONG) lReadTimeout * -10000;
1965 else
1966 timeout.QuadPart = ((LONGLONG)0x7fffffff << 32) | 0xffffffff;
1968 status = NtCreateMailslotFile( &handle, GENERIC_READ | SYNCHRONIZE, &attr,
1969 &iosb, 0, 0, nMaxMessageSize, &timeout );
1970 if (status)
1972 SetLastError( RtlNtStatusToDosError(status) );
1973 handle = INVALID_HANDLE_VALUE;
1976 RtlFreeUnicodeString( &nameW );
1977 return handle;
1981 /******************************************************************************
1982 * GetMailslotInfo [KERNEL32.@]
1984 * Retrieve information about a mailslot.
1986 * PARAMS
1987 * hMailslot [I] Mailslot handle
1988 * lpMaxMessageSize [O] Address of maximum message size
1989 * lpNextSize [O] Address of size of next message
1990 * lpMessageCount [O] Address of number of messages
1991 * lpReadTimeout [O] Address of read time-out
1993 * RETURNS
1994 * Success: TRUE
1995 * Failure: FALSE
1997 BOOL WINAPI GetMailslotInfo( HANDLE hMailslot, LPDWORD lpMaxMessageSize,
1998 LPDWORD lpNextSize, LPDWORD lpMessageCount,
1999 LPDWORD lpReadTimeout )
2001 FILE_MAILSLOT_QUERY_INFORMATION info;
2002 IO_STATUS_BLOCK iosb;
2003 NTSTATUS status;
2005 TRACE("%p %p %p %p %p\n",hMailslot, lpMaxMessageSize,
2006 lpNextSize, lpMessageCount, lpReadTimeout);
2008 status = NtQueryInformationFile( hMailslot, &iosb, &info, sizeof info,
2009 FileMailslotQueryInformation );
2011 if( status != STATUS_SUCCESS )
2013 SetLastError( RtlNtStatusToDosError(status) );
2014 return FALSE;
2017 if( lpMaxMessageSize )
2018 *lpMaxMessageSize = info.MaximumMessageSize;
2019 if( lpNextSize )
2020 *lpNextSize = info.NextMessageSize;
2021 if( lpMessageCount )
2022 *lpMessageCount = info.MessagesAvailable;
2023 if( lpReadTimeout )
2025 if (info.ReadTimeout.QuadPart == (((LONGLONG)0x7fffffff << 32) | 0xffffffff))
2026 *lpReadTimeout = MAILSLOT_WAIT_FOREVER;
2027 else
2028 *lpReadTimeout = info.ReadTimeout.QuadPart / -10000;
2030 return TRUE;
2034 /******************************************************************************
2035 * SetMailslotInfo [KERNEL32.@]
2037 * Set the read timeout of a mailslot.
2039 * PARAMS
2040 * hMailslot [I] Mailslot handle
2041 * dwReadTimeout [I] Timeout in milliseconds.
2043 * RETURNS
2044 * Success: TRUE
2045 * Failure: FALSE
2047 BOOL WINAPI SetMailslotInfo( HANDLE hMailslot, DWORD dwReadTimeout)
2049 FILE_MAILSLOT_SET_INFORMATION info;
2050 IO_STATUS_BLOCK iosb;
2051 NTSTATUS status;
2053 TRACE("%p %d\n", hMailslot, dwReadTimeout);
2055 if (dwReadTimeout != MAILSLOT_WAIT_FOREVER)
2056 info.ReadTimeout.QuadPart = (ULONGLONG)dwReadTimeout * -10000;
2057 else
2058 info.ReadTimeout.QuadPart = ((LONGLONG)0x7fffffff << 32) | 0xffffffff;
2059 status = NtSetInformationFile( hMailslot, &iosb, &info, sizeof info,
2060 FileMailslotSetInformation );
2061 if( status != STATUS_SUCCESS )
2063 SetLastError( RtlNtStatusToDosError(status) );
2064 return FALSE;
2066 return TRUE;
2070 /******************************************************************************
2071 * CreateIoCompletionPort (KERNEL32.@)
2073 HANDLE WINAPI CreateIoCompletionPort(HANDLE hFileHandle, HANDLE hExistingCompletionPort,
2074 ULONG_PTR CompletionKey, DWORD dwNumberOfConcurrentThreads)
2076 NTSTATUS status;
2077 HANDLE ret = 0;
2079 TRACE("(%p, %p, %08lx, %08x)\n",
2080 hFileHandle, hExistingCompletionPort, CompletionKey, dwNumberOfConcurrentThreads);
2082 if (hExistingCompletionPort && hFileHandle == INVALID_HANDLE_VALUE)
2084 SetLastError( ERROR_INVALID_PARAMETER);
2085 return NULL;
2088 if (hExistingCompletionPort)
2089 ret = hExistingCompletionPort;
2090 else
2092 status = NtCreateIoCompletion( &ret, IO_COMPLETION_ALL_ACCESS, NULL, dwNumberOfConcurrentThreads );
2093 if (status != STATUS_SUCCESS) goto fail;
2096 if (hFileHandle != INVALID_HANDLE_VALUE)
2098 FILE_COMPLETION_INFORMATION info;
2099 IO_STATUS_BLOCK iosb;
2101 info.CompletionPort = ret;
2102 info.CompletionKey = CompletionKey;
2103 status = NtSetInformationFile( hFileHandle, &iosb, &info, sizeof(info), FileCompletionInformation );
2104 if (status != STATUS_SUCCESS) goto fail;
2107 return ret;
2109 fail:
2110 if (ret && !hExistingCompletionPort)
2111 CloseHandle( ret );
2112 SetLastError( RtlNtStatusToDosError(status) );
2113 return 0;
2116 /******************************************************************************
2117 * GetQueuedCompletionStatus (KERNEL32.@)
2119 BOOL WINAPI GetQueuedCompletionStatus( HANDLE CompletionPort, LPDWORD lpNumberOfBytesTransferred,
2120 PULONG_PTR pCompletionKey, LPOVERLAPPED *lpOverlapped,
2121 DWORD dwMilliseconds )
2123 NTSTATUS status;
2124 IO_STATUS_BLOCK iosb;
2125 LARGE_INTEGER wait_time;
2127 TRACE("(%p,%p,%p,%p,%d)\n",
2128 CompletionPort,lpNumberOfBytesTransferred,pCompletionKey,lpOverlapped,dwMilliseconds);
2130 *lpOverlapped = NULL;
2132 status = NtRemoveIoCompletion( CompletionPort, pCompletionKey, (PULONG_PTR)lpOverlapped,
2133 &iosb, get_nt_timeout( &wait_time, dwMilliseconds ) );
2134 if (status == STATUS_SUCCESS)
2136 *lpNumberOfBytesTransferred = iosb.Information;
2137 return TRUE;
2140 SetLastError( RtlNtStatusToDosError(status) );
2141 return FALSE;
2145 /******************************************************************************
2146 * PostQueuedCompletionStatus (KERNEL32.@)
2148 BOOL WINAPI PostQueuedCompletionStatus( HANDLE CompletionPort, DWORD dwNumberOfBytes,
2149 ULONG_PTR dwCompletionKey, LPOVERLAPPED lpOverlapped)
2151 NTSTATUS status;
2153 TRACE("%p %d %08lx %p\n", CompletionPort, dwNumberOfBytes, dwCompletionKey, lpOverlapped );
2155 status = NtSetIoCompletion( CompletionPort, dwCompletionKey, (ULONG_PTR)lpOverlapped,
2156 STATUS_SUCCESS, dwNumberOfBytes );
2158 if (status == STATUS_SUCCESS) return TRUE;
2159 SetLastError( RtlNtStatusToDosError(status) );
2160 return FALSE;
2163 /******************************************************************************
2164 * BindIoCompletionCallback (KERNEL32.@)
2166 BOOL WINAPI BindIoCompletionCallback( HANDLE FileHandle, LPOVERLAPPED_COMPLETION_ROUTINE Function, ULONG Flags)
2168 NTSTATUS status;
2170 TRACE("(%p, %p, %d)\n", FileHandle, Function, Flags);
2172 status = RtlSetIoCompletionCallback( FileHandle, (PRTL_OVERLAPPED_COMPLETION_ROUTINE)Function, Flags );
2173 if (status == STATUS_SUCCESS) return TRUE;
2174 SetLastError( RtlNtStatusToDosError(status) );
2175 return FALSE;
2178 #ifdef __i386__
2180 /***********************************************************************
2181 * InterlockedCompareExchange (KERNEL32.@)
2183 /* LONG WINAPI InterlockedCompareExchange( PLONG dest, LONG xchg, LONG compare ); */
2184 __ASM_GLOBAL_FUNC(InterlockedCompareExchange,
2185 "movl 12(%esp),%eax\n\t"
2186 "movl 8(%esp),%ecx\n\t"
2187 "movl 4(%esp),%edx\n\t"
2188 "lock; cmpxchgl %ecx,(%edx)\n\t"
2189 "ret $12")
2191 /***********************************************************************
2192 * InterlockedExchange (KERNEL32.@)
2194 /* LONG WINAPI InterlockedExchange( PLONG dest, LONG val ); */
2195 __ASM_GLOBAL_FUNC(InterlockedExchange,
2196 "movl 8(%esp),%eax\n\t"
2197 "movl 4(%esp),%edx\n\t"
2198 "lock; xchgl %eax,(%edx)\n\t"
2199 "ret $8")
2201 /***********************************************************************
2202 * InterlockedExchangeAdd (KERNEL32.@)
2204 /* LONG WINAPI InterlockedExchangeAdd( PLONG dest, LONG incr ); */
2205 __ASM_GLOBAL_FUNC(InterlockedExchangeAdd,
2206 "movl 8(%esp),%eax\n\t"
2207 "movl 4(%esp),%edx\n\t"
2208 "lock; xaddl %eax,(%edx)\n\t"
2209 "ret $8")
2211 /***********************************************************************
2212 * InterlockedIncrement (KERNEL32.@)
2214 /* LONG WINAPI InterlockedIncrement( PLONG dest ); */
2215 __ASM_GLOBAL_FUNC(InterlockedIncrement,
2216 "movl 4(%esp),%edx\n\t"
2217 "movl $1,%eax\n\t"
2218 "lock; xaddl %eax,(%edx)\n\t"
2219 "incl %eax\n\t"
2220 "ret $4")
2222 /***********************************************************************
2223 * InterlockedDecrement (KERNEL32.@)
2225 __ASM_GLOBAL_FUNC(InterlockedDecrement,
2226 "movl 4(%esp),%edx\n\t"
2227 "movl $-1,%eax\n\t"
2228 "lock; xaddl %eax,(%edx)\n\t"
2229 "decl %eax\n\t"
2230 "ret $4")
2232 #else /* __i386__ */
2234 /***********************************************************************
2235 * InterlockedCompareExchange (KERNEL32.@)
2237 * Atomically swap one value with another.
2239 * PARAMS
2240 * dest [I/O] The value to replace
2241 * xchq [I] The value to be swapped
2242 * compare [I] The value to compare to dest
2244 * RETURNS
2245 * The resulting value of dest.
2247 * NOTES
2248 * dest is updated only if it is equal to compare, otherwise no swap is done.
2250 LONG WINAPI InterlockedCompareExchange( LONG volatile *dest, LONG xchg, LONG compare )
2252 return interlocked_cmpxchg( (int *)dest, xchg, compare );
2255 /***********************************************************************
2256 * InterlockedExchange (KERNEL32.@)
2258 * Atomically swap one value with another.
2260 * PARAMS
2261 * dest [I/O] The value to replace
2262 * val [I] The value to be swapped
2264 * RETURNS
2265 * The resulting value of dest.
2267 LONG WINAPI InterlockedExchange( LONG volatile *dest, LONG val )
2269 return interlocked_xchg( (int *)dest, val );
2272 /***********************************************************************
2273 * InterlockedExchangeAdd (KERNEL32.@)
2275 * Atomically add one value to another.
2277 * PARAMS
2278 * dest [I/O] The value to add to
2279 * incr [I] The value to be added
2281 * RETURNS
2282 * The resulting value of dest.
2284 LONG WINAPI InterlockedExchangeAdd( LONG volatile *dest, LONG incr )
2286 return interlocked_xchg_add( (int *)dest, incr );
2289 /***********************************************************************
2290 * InterlockedIncrement (KERNEL32.@)
2292 * Atomically increment a value.
2294 * PARAMS
2295 * dest [I/O] The value to increment
2297 * RETURNS
2298 * The resulting value of dest.
2300 LONG WINAPI InterlockedIncrement( LONG volatile *dest )
2302 return interlocked_xchg_add( (int *)dest, 1 ) + 1;
2305 /***********************************************************************
2306 * InterlockedDecrement (KERNEL32.@)
2308 * Atomically decrement a value.
2310 * PARAMS
2311 * dest [I/O] The value to decrement
2313 * RETURNS
2314 * The resulting value of dest.
2316 LONG WINAPI InterlockedDecrement( LONG volatile *dest )
2318 return interlocked_xchg_add( (int *)dest, -1 ) - 1;
2321 #endif /* __i386__ */