ntdll: Add a helper to validate attributes in open calls, and use a common pattern...
[wine.git] / dlls / ntdll / sync.c
blobaa58442700d2bf837e37c9295531365cedc8c2b8
1 /*
2 * Process synchronisation
4 * Copyright 1996, 1997, 1998 Marcus Meissner
5 * Copyright 1997, 1999 Alexandre Julliard
6 * Copyright 1999, 2000 Juergen Schmied
7 * Copyright 2003 Eric Pouech
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
24 #include "config.h"
25 #include "wine/port.h"
27 #include <assert.h>
28 #include <errno.h>
29 #include <signal.h>
30 #ifdef HAVE_SYS_TIME_H
31 # include <sys/time.h>
32 #endif
33 #ifdef HAVE_POLL_H
34 #include <poll.h>
35 #endif
36 #ifdef HAVE_SYS_POLL_H
37 # include <sys/poll.h>
38 #endif
39 #ifdef HAVE_UNISTD_H
40 # include <unistd.h>
41 #endif
42 #ifdef HAVE_SCHED_H
43 # include <sched.h>
44 #endif
45 #include <string.h>
46 #include <stdarg.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <time.h>
51 #include "ntstatus.h"
52 #define WIN32_NO_STATUS
53 #define NONAMELESSUNION
54 #include "windef.h"
55 #include "winternl.h"
56 #include "wine/server.h"
57 #include "wine/debug.h"
58 #include "ntdll_misc.h"
60 WINE_DEFAULT_DEBUG_CHANNEL(ntdll);
62 HANDLE keyed_event = NULL;
64 static inline int interlocked_dec_if_nonzero( int *dest )
66 int val, tmp;
67 for (val = *dest;; val = tmp)
69 if (!val || (tmp = interlocked_cmpxchg( dest, val - 1, val )) == val)
70 break;
72 return val;
75 /* creates a struct security_descriptor and contained information in one contiguous piece of memory */
76 NTSTATUS alloc_object_attributes( const OBJECT_ATTRIBUTES *attr, struct object_attributes **ret,
77 data_size_t *ret_len )
79 unsigned int len = sizeof(**ret);
80 PSID owner, group;
81 ACL *dacl, *sacl;
82 BOOLEAN owner_present, group_present, dacl_present, sacl_present, defaulted;
83 PSECURITY_DESCRIPTOR sd;
84 NTSTATUS status;
86 *ret = NULL;
87 *ret_len = 0;
89 if (!attr) return STATUS_SUCCESS;
91 if ((sd = attr->SecurityDescriptor))
93 len += sizeof(struct security_descriptor);
95 if ((status = RtlGetOwnerSecurityDescriptor( sd, &owner, &owner_present ))) return status;
96 if ((status = RtlGetGroupSecurityDescriptor( sd, &group, &group_present ))) return status;
97 if ((status = RtlGetSaclSecurityDescriptor( sd, &sacl_present, &sacl, &defaulted ))) return status;
98 if ((status = RtlGetDaclSecurityDescriptor( sd, &dacl_present, &dacl, &defaulted ))) return status;
99 if (owner_present) len += RtlLengthSid( owner );
100 if (group_present) len += RtlLengthSid( group );
101 if (sacl_present && sacl) len += sacl->AclSize;
102 if (dacl_present && dacl) len += dacl->AclSize;
104 /* fix alignment for the Unicode name that follows the structure */
105 len = (len + sizeof(WCHAR) - 1) & ~(sizeof(WCHAR) - 1);
108 if (attr->ObjectName)
110 if (attr->ObjectName->Length & (sizeof(WCHAR) - 1)) return STATUS_OBJECT_NAME_INVALID;
111 len += attr->ObjectName->Length;
113 else if (attr->RootDirectory) return STATUS_OBJECT_NAME_INVALID;
115 *ret = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, len );
116 if (!*ret) return STATUS_NO_MEMORY;
118 (*ret)->rootdir = wine_server_obj_handle( attr->RootDirectory );
119 (*ret)->attributes = attr->Attributes;
121 if (attr->SecurityDescriptor)
123 struct security_descriptor *descr = (struct security_descriptor *)(*ret + 1);
124 unsigned char *ptr = (unsigned char *)(descr + 1);
126 descr->control = ((SECURITY_DESCRIPTOR *)sd)->Control & ~SE_SELF_RELATIVE;
127 if (owner_present) descr->owner_len = RtlLengthSid( owner );
128 if (group_present) descr->group_len = RtlLengthSid( group );
129 if (sacl_present && sacl) descr->sacl_len = sacl->AclSize;
130 if (dacl_present && dacl) descr->dacl_len = dacl->AclSize;
132 memcpy( ptr, owner, descr->owner_len );
133 ptr += descr->owner_len;
134 memcpy( ptr, group, descr->group_len );
135 ptr += descr->group_len;
136 memcpy( ptr, sacl, descr->sacl_len );
137 ptr += descr->sacl_len;
138 memcpy( ptr, dacl, descr->dacl_len );
139 (*ret)->sd_len = (sizeof(*descr) + descr->owner_len + descr->group_len + descr->sacl_len +
140 descr->dacl_len + sizeof(WCHAR) - 1) & ~(sizeof(WCHAR) - 1);
143 if (attr->ObjectName)
145 unsigned char *ptr = (unsigned char *)(*ret + 1) + (*ret)->sd_len;
146 (*ret)->name_len = attr->ObjectName->Length;
147 memcpy( ptr, attr->ObjectName->Buffer, (*ret)->name_len );
150 *ret_len = len;
151 return STATUS_SUCCESS;
154 NTSTATUS validate_open_object_attributes( const OBJECT_ATTRIBUTES *attr )
156 if (!attr) return STATUS_INVALID_PARAMETER;
158 if (attr->ObjectName)
160 if (attr->ObjectName->Length & (sizeof(WCHAR) - 1)) return STATUS_OBJECT_NAME_INVALID;
162 else if (attr->RootDirectory) return STATUS_OBJECT_NAME_INVALID;
164 return STATUS_SUCCESS;
168 * Semaphores
171 /******************************************************************************
172 * NtCreateSemaphore (NTDLL.@)
174 NTSTATUS WINAPI NtCreateSemaphore( OUT PHANDLE SemaphoreHandle,
175 IN ACCESS_MASK access,
176 IN const OBJECT_ATTRIBUTES *attr OPTIONAL,
177 IN LONG InitialCount,
178 IN LONG MaximumCount )
180 NTSTATUS ret;
181 data_size_t len;
182 struct object_attributes *objattr;
184 if (MaximumCount <= 0 || InitialCount < 0 || InitialCount > MaximumCount)
185 return STATUS_INVALID_PARAMETER;
187 if ((ret = alloc_object_attributes( attr, &objattr, &len ))) return ret;
189 SERVER_START_REQ( create_semaphore )
191 req->access = access;
192 req->initial = InitialCount;
193 req->max = MaximumCount;
194 wine_server_add_data( req, objattr, len );
195 ret = wine_server_call( req );
196 *SemaphoreHandle = wine_server_ptr_handle( reply->handle );
198 SERVER_END_REQ;
200 RtlFreeHeap( GetProcessHeap(), 0, objattr );
201 return ret;
204 /******************************************************************************
205 * NtOpenSemaphore (NTDLL.@)
207 NTSTATUS WINAPI NtOpenSemaphore( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr )
209 NTSTATUS ret;
211 if ((ret = validate_open_object_attributes( attr ))) return ret;
213 SERVER_START_REQ( open_semaphore )
215 req->access = access;
216 req->attributes = attr->Attributes;
217 req->rootdir = wine_server_obj_handle( attr->RootDirectory );
218 if (attr->ObjectName)
219 wine_server_add_data( req, attr->ObjectName->Buffer, attr->ObjectName->Length );
220 ret = wine_server_call( req );
221 *handle = wine_server_ptr_handle( reply->handle );
223 SERVER_END_REQ;
224 return ret;
227 /******************************************************************************
228 * NtQuerySemaphore (NTDLL.@)
230 NTSTATUS WINAPI NtQuerySemaphore( HANDLE handle, SEMAPHORE_INFORMATION_CLASS class,
231 void *info, ULONG len, ULONG *ret_len )
233 NTSTATUS ret;
234 SEMAPHORE_BASIC_INFORMATION *out = info;
236 if (class != SemaphoreBasicInformation)
238 FIXME("(%p,%d,%u) Unknown class\n", handle, class, len);
239 return STATUS_INVALID_INFO_CLASS;
242 if (len != sizeof(SEMAPHORE_BASIC_INFORMATION)) return STATUS_INFO_LENGTH_MISMATCH;
244 SERVER_START_REQ( query_semaphore )
246 req->handle = wine_server_obj_handle( handle );
247 if (!(ret = wine_server_call( req )))
249 out->CurrentCount = reply->current;
250 out->MaximumCount = reply->max;
251 if (ret_len) *ret_len = sizeof(SEMAPHORE_BASIC_INFORMATION);
254 SERVER_END_REQ;
256 return ret;
259 /******************************************************************************
260 * NtReleaseSemaphore (NTDLL.@)
262 NTSTATUS WINAPI NtReleaseSemaphore( HANDLE handle, ULONG count, PULONG previous )
264 NTSTATUS ret;
265 SERVER_START_REQ( release_semaphore )
267 req->handle = wine_server_obj_handle( handle );
268 req->count = count;
269 if (!(ret = wine_server_call( req )))
271 if (previous) *previous = reply->prev_count;
274 SERVER_END_REQ;
275 return ret;
279 * Events
282 /**************************************************************************
283 * NtCreateEvent (NTDLL.@)
284 * ZwCreateEvent (NTDLL.@)
286 NTSTATUS WINAPI NtCreateEvent( PHANDLE EventHandle, ACCESS_MASK DesiredAccess,
287 const OBJECT_ATTRIBUTES *attr, EVENT_TYPE type, BOOLEAN InitialState)
289 NTSTATUS ret;
290 data_size_t len;
291 struct object_attributes *objattr;
293 if ((ret = alloc_object_attributes( attr, &objattr, &len ))) return ret;
295 SERVER_START_REQ( create_event )
297 req->access = DesiredAccess;
298 req->manual_reset = (type == NotificationEvent);
299 req->initial_state = InitialState;
300 wine_server_add_data( req, objattr, len );
301 ret = wine_server_call( req );
302 *EventHandle = wine_server_ptr_handle( reply->handle );
304 SERVER_END_REQ;
306 RtlFreeHeap( GetProcessHeap(), 0, objattr );
307 return ret;
310 /******************************************************************************
311 * NtOpenEvent (NTDLL.@)
312 * ZwOpenEvent (NTDLL.@)
314 NTSTATUS WINAPI NtOpenEvent( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr )
316 NTSTATUS ret;
318 if ((ret = validate_open_object_attributes( attr ))) return ret;
320 SERVER_START_REQ( open_event )
322 req->access = access;
323 req->attributes = attr->Attributes;
324 req->rootdir = wine_server_obj_handle( attr->RootDirectory );
325 if (attr->ObjectName)
326 wine_server_add_data( req, attr->ObjectName->Buffer, attr->ObjectName->Length );
327 ret = wine_server_call( req );
328 *handle = wine_server_ptr_handle( reply->handle );
330 SERVER_END_REQ;
331 return ret;
335 /******************************************************************************
336 * NtSetEvent (NTDLL.@)
337 * ZwSetEvent (NTDLL.@)
339 NTSTATUS WINAPI NtSetEvent( HANDLE handle, PULONG NumberOfThreadsReleased )
341 NTSTATUS ret;
343 /* FIXME: set NumberOfThreadsReleased */
345 SERVER_START_REQ( event_op )
347 req->handle = wine_server_obj_handle( handle );
348 req->op = SET_EVENT;
349 ret = wine_server_call( req );
351 SERVER_END_REQ;
352 return ret;
355 /******************************************************************************
356 * NtResetEvent (NTDLL.@)
358 NTSTATUS WINAPI NtResetEvent( HANDLE handle, PULONG NumberOfThreadsReleased )
360 NTSTATUS ret;
362 /* resetting an event can't release any thread... */
363 if (NumberOfThreadsReleased) *NumberOfThreadsReleased = 0;
365 SERVER_START_REQ( event_op )
367 req->handle = wine_server_obj_handle( handle );
368 req->op = RESET_EVENT;
369 ret = wine_server_call( req );
371 SERVER_END_REQ;
372 return ret;
375 /******************************************************************************
376 * NtClearEvent (NTDLL.@)
378 * FIXME
379 * same as NtResetEvent ???
381 NTSTATUS WINAPI NtClearEvent ( HANDLE handle )
383 return NtResetEvent( handle, NULL );
386 /******************************************************************************
387 * NtPulseEvent (NTDLL.@)
389 * FIXME
390 * PulseCount
392 NTSTATUS WINAPI NtPulseEvent( HANDLE handle, PULONG PulseCount )
394 NTSTATUS ret;
396 if (PulseCount)
397 FIXME("(%p,%d)\n", handle, *PulseCount);
399 SERVER_START_REQ( event_op )
401 req->handle = wine_server_obj_handle( handle );
402 req->op = PULSE_EVENT;
403 ret = wine_server_call( req );
405 SERVER_END_REQ;
406 return ret;
409 /******************************************************************************
410 * NtQueryEvent (NTDLL.@)
412 NTSTATUS WINAPI NtQueryEvent( HANDLE handle, EVENT_INFORMATION_CLASS class,
413 void *info, ULONG len, ULONG *ret_len )
415 NTSTATUS ret;
416 EVENT_BASIC_INFORMATION *out = info;
418 if (class != EventBasicInformation)
420 FIXME("(%p, %d, %d) Unknown class\n",
421 handle, class, len);
422 return STATUS_INVALID_INFO_CLASS;
425 if (len != sizeof(EVENT_BASIC_INFORMATION)) return STATUS_INFO_LENGTH_MISMATCH;
427 SERVER_START_REQ( query_event )
429 req->handle = wine_server_obj_handle( handle );
430 if (!(ret = wine_server_call( req )))
432 out->EventType = reply->manual_reset ? NotificationEvent : SynchronizationEvent;
433 out->EventState = reply->state;
434 if (ret_len) *ret_len = sizeof(EVENT_BASIC_INFORMATION);
437 SERVER_END_REQ;
439 return ret;
443 * Mutants (known as Mutexes in Kernel32)
446 /******************************************************************************
447 * NtCreateMutant [NTDLL.@]
448 * ZwCreateMutant [NTDLL.@]
450 NTSTATUS WINAPI NtCreateMutant(OUT HANDLE* MutantHandle,
451 IN ACCESS_MASK access,
452 IN const OBJECT_ATTRIBUTES* attr OPTIONAL,
453 IN BOOLEAN InitialOwner)
455 NTSTATUS status;
456 data_size_t len;
457 struct object_attributes *objattr;
459 if ((status = alloc_object_attributes( attr, &objattr, &len ))) return status;
461 SERVER_START_REQ( create_mutex )
463 req->access = access;
464 req->owned = InitialOwner;
465 wine_server_add_data( req, objattr, len );
466 status = wine_server_call( req );
467 *MutantHandle = wine_server_ptr_handle( reply->handle );
469 SERVER_END_REQ;
471 RtlFreeHeap( GetProcessHeap(), 0, objattr );
472 return status;
475 /**************************************************************************
476 * NtOpenMutant [NTDLL.@]
477 * ZwOpenMutant [NTDLL.@]
479 NTSTATUS WINAPI NtOpenMutant( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr )
481 NTSTATUS status;
483 if ((status = validate_open_object_attributes( attr ))) return status;
485 SERVER_START_REQ( open_mutex )
487 req->access = access;
488 req->attributes = attr->Attributes;
489 req->rootdir = wine_server_obj_handle( attr->RootDirectory );
490 if (attr->ObjectName)
491 wine_server_add_data( req, attr->ObjectName->Buffer, attr->ObjectName->Length );
492 status = wine_server_call( req );
493 *handle = wine_server_ptr_handle( reply->handle );
495 SERVER_END_REQ;
496 return status;
499 /**************************************************************************
500 * NtReleaseMutant [NTDLL.@]
501 * ZwReleaseMutant [NTDLL.@]
503 NTSTATUS WINAPI NtReleaseMutant( IN HANDLE handle, OUT PLONG prev_count OPTIONAL)
505 NTSTATUS status;
507 SERVER_START_REQ( release_mutex )
509 req->handle = wine_server_obj_handle( handle );
510 status = wine_server_call( req );
511 if (prev_count) *prev_count = reply->prev_count;
513 SERVER_END_REQ;
514 return status;
517 /******************************************************************
518 * NtQueryMutant [NTDLL.@]
519 * ZwQueryMutant [NTDLL.@]
521 NTSTATUS WINAPI NtQueryMutant(IN HANDLE handle,
522 IN MUTANT_INFORMATION_CLASS MutantInformationClass,
523 OUT PVOID MutantInformation,
524 IN ULONG MutantInformationLength,
525 OUT PULONG ResultLength OPTIONAL )
527 FIXME("(%p %u %p %u %p): stub!\n",
528 handle, MutantInformationClass, MutantInformation, MutantInformationLength, ResultLength);
529 return STATUS_NOT_IMPLEMENTED;
533 * Jobs
536 /******************************************************************************
537 * NtCreateJobObject [NTDLL.@]
538 * ZwCreateJobObject [NTDLL.@]
540 NTSTATUS WINAPI NtCreateJobObject( PHANDLE handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr )
542 NTSTATUS ret;
543 data_size_t len;
544 struct object_attributes *objattr;
546 if ((ret = alloc_object_attributes( attr, &objattr, &len ))) return ret;
548 SERVER_START_REQ( create_job )
550 req->access = access;
551 wine_server_add_data( req, objattr, len );
552 ret = wine_server_call( req );
553 *handle = wine_server_ptr_handle( reply->handle );
555 SERVER_END_REQ;
557 RtlFreeHeap( GetProcessHeap(), 0, objattr );
558 return ret;
561 /******************************************************************************
562 * NtOpenJobObject [NTDLL.@]
563 * ZwOpenJobObject [NTDLL.@]
565 NTSTATUS WINAPI NtOpenJobObject( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr )
567 NTSTATUS ret;
569 if ((ret = validate_open_object_attributes( attr ))) return ret;
571 SERVER_START_REQ( open_job )
573 req->access = access;
574 req->attributes = attr->Attributes;
575 req->rootdir = wine_server_obj_handle( attr->RootDirectory );
576 if (attr->ObjectName)
577 wine_server_add_data( req, attr->ObjectName->Buffer, attr->ObjectName->Length );
578 ret = wine_server_call( req );
579 *handle = wine_server_ptr_handle( reply->handle );
581 SERVER_END_REQ;
582 return ret;
585 /******************************************************************************
586 * NtTerminateJobObject [NTDLL.@]
587 * ZwTerminateJobObject [NTDLL.@]
589 NTSTATUS WINAPI NtTerminateJobObject( HANDLE handle, NTSTATUS status )
591 NTSTATUS ret;
593 TRACE( "(%p, %d)\n", handle, status );
595 SERVER_START_REQ( terminate_job )
597 req->handle = wine_server_obj_handle( handle );
598 req->status = status;
599 ret = wine_server_call( req );
601 SERVER_END_REQ;
603 return ret;
606 /******************************************************************************
607 * NtQueryInformationJobObject [NTDLL.@]
608 * ZwQueryInformationJobObject [NTDLL.@]
610 NTSTATUS WINAPI NtQueryInformationJobObject( HANDLE handle, JOBOBJECTINFOCLASS class, PVOID info,
611 ULONG len, PULONG ret_len )
613 FIXME( "stub: %p %u %p %u %p\n", handle, class, info, len, ret_len );
615 if (class >= MaxJobObjectInfoClass)
616 return STATUS_INVALID_PARAMETER;
618 switch (class)
620 case JobObjectExtendedLimitInformation:
622 JOBOBJECT_EXTENDED_LIMIT_INFORMATION *extended_limit;
623 if (len < sizeof(*extended_limit))
624 return STATUS_INFO_LENGTH_MISMATCH;
626 extended_limit = (JOBOBJECT_EXTENDED_LIMIT_INFORMATION *)info;
627 memset(extended_limit, 0, sizeof(*extended_limit));
628 if (ret_len) *ret_len = sizeof(*extended_limit);
629 return STATUS_SUCCESS;
632 case JobObjectBasicLimitInformation:
634 JOBOBJECT_BASIC_LIMIT_INFORMATION *basic_limit;
635 if (len < sizeof(*basic_limit))
636 return STATUS_INFO_LENGTH_MISMATCH;
638 basic_limit = (JOBOBJECT_BASIC_LIMIT_INFORMATION *)info;
639 memset(basic_limit, 0, sizeof(*basic_limit));
640 if (ret_len) *ret_len = sizeof(*basic_limit);
641 return STATUS_SUCCESS;
644 default:
645 return STATUS_NOT_IMPLEMENTED;
649 /******************************************************************************
650 * NtSetInformationJobObject [NTDLL.@]
651 * ZwSetInformationJobObject [NTDLL.@]
653 NTSTATUS WINAPI NtSetInformationJobObject( HANDLE handle, JOBOBJECTINFOCLASS class, PVOID info, ULONG len )
655 NTSTATUS status = STATUS_NOT_IMPLEMENTED;
656 JOBOBJECT_BASIC_LIMIT_INFORMATION *basic_limit;
657 ULONG info_size = sizeof(JOBOBJECT_BASIC_LIMIT_INFORMATION);
658 DWORD limit_flags = JOB_OBJECT_BASIC_LIMIT_VALID_FLAGS;
660 TRACE( "(%p, %u, %p, %u)\n", handle, class, info, len );
662 if (class >= MaxJobObjectInfoClass)
663 return STATUS_INVALID_PARAMETER;
665 switch (class)
668 case JobObjectExtendedLimitInformation:
669 info_size = sizeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION);
670 limit_flags = JOB_OBJECT_EXTENDED_LIMIT_VALID_FLAGS;
671 /* fallthrough */
672 case JobObjectBasicLimitInformation:
673 if (len != info_size)
674 return STATUS_INVALID_PARAMETER;
676 basic_limit = info;
677 if (basic_limit->LimitFlags & ~limit_flags)
678 return STATUS_INVALID_PARAMETER;
680 SERVER_START_REQ( set_job_limits )
682 req->handle = wine_server_obj_handle( handle );
683 req->limit_flags = basic_limit->LimitFlags;
684 status = wine_server_call( req );
686 SERVER_END_REQ;
687 break;
689 case JobObjectAssociateCompletionPortInformation:
690 if (len != sizeof(JOBOBJECT_ASSOCIATE_COMPLETION_PORT))
691 return STATUS_INVALID_PARAMETER;
693 SERVER_START_REQ( set_job_completion_port )
695 JOBOBJECT_ASSOCIATE_COMPLETION_PORT *port_info = info;
696 req->job = wine_server_obj_handle( handle );
697 req->port = wine_server_obj_handle( port_info->CompletionPort );
698 req->key = wine_server_client_ptr( port_info->CompletionKey );
699 status = wine_server_call(req);
701 SERVER_END_REQ;
702 break;
704 case JobObjectBasicUIRestrictions:
705 status = STATUS_SUCCESS;
706 /* fallthrough */
707 default:
708 FIXME( "stub: %p %u %p %u\n", handle, class, info, len );
711 return status;
714 /******************************************************************************
715 * NtIsProcessInJob [NTDLL.@]
716 * ZwIsProcessInJob [NTDLL.@]
718 NTSTATUS WINAPI NtIsProcessInJob( HANDLE process, HANDLE job )
720 NTSTATUS status;
722 TRACE( "(%p %p)\n", job, process );
724 SERVER_START_REQ( process_in_job )
726 req->job = wine_server_obj_handle( job );
727 req->process = wine_server_obj_handle( process );
728 status = wine_server_call( req );
730 SERVER_END_REQ;
732 return status;
735 /******************************************************************************
736 * NtAssignProcessToJobObject [NTDLL.@]
737 * ZwAssignProcessToJobObject [NTDLL.@]
739 NTSTATUS WINAPI NtAssignProcessToJobObject( HANDLE job, HANDLE process )
741 NTSTATUS status;
743 TRACE( "(%p %p)\n", job, process );
745 SERVER_START_REQ( assign_job )
747 req->job = wine_server_obj_handle( job );
748 req->process = wine_server_obj_handle( process );
749 status = wine_server_call( req );
751 SERVER_END_REQ;
753 return status;
757 * Timers
760 /**************************************************************************
761 * NtCreateTimer [NTDLL.@]
762 * ZwCreateTimer [NTDLL.@]
764 NTSTATUS WINAPI NtCreateTimer(OUT HANDLE *handle,
765 IN ACCESS_MASK access,
766 IN const OBJECT_ATTRIBUTES *attr OPTIONAL,
767 IN TIMER_TYPE timer_type)
769 NTSTATUS status;
770 data_size_t len;
771 struct object_attributes *objattr;
773 if (timer_type != NotificationTimer && timer_type != SynchronizationTimer)
774 return STATUS_INVALID_PARAMETER;
776 if ((status = alloc_object_attributes( attr, &objattr, &len ))) return status;
778 SERVER_START_REQ( create_timer )
780 req->access = access;
781 req->manual = (timer_type == NotificationTimer);
782 wine_server_add_data( req, objattr, len );
783 status = wine_server_call( req );
784 *handle = wine_server_ptr_handle( reply->handle );
786 SERVER_END_REQ;
788 RtlFreeHeap( GetProcessHeap(), 0, objattr );
789 return status;
793 /**************************************************************************
794 * NtOpenTimer [NTDLL.@]
795 * ZwOpenTimer [NTDLL.@]
797 NTSTATUS WINAPI NtOpenTimer( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr )
799 NTSTATUS status;
801 if ((status = validate_open_object_attributes( attr ))) return status;
803 SERVER_START_REQ( open_timer )
805 req->access = access;
806 req->attributes = attr->Attributes;
807 req->rootdir = wine_server_obj_handle( attr ? attr->RootDirectory : 0 );
808 if (attr->ObjectName)
809 wine_server_add_data( req, attr->ObjectName->Buffer, attr->ObjectName->Length );
810 status = wine_server_call( req );
811 *handle = wine_server_ptr_handle( reply->handle );
813 SERVER_END_REQ;
814 return status;
817 /**************************************************************************
818 * NtSetTimer [NTDLL.@]
819 * ZwSetTimer [NTDLL.@]
821 NTSTATUS WINAPI NtSetTimer(IN HANDLE handle,
822 IN const LARGE_INTEGER* when,
823 IN PTIMER_APC_ROUTINE callback,
824 IN PVOID callback_arg,
825 IN BOOLEAN resume,
826 IN ULONG period OPTIONAL,
827 OUT PBOOLEAN state OPTIONAL)
829 NTSTATUS status = STATUS_SUCCESS;
831 TRACE("(%p,%p,%p,%p,%08x,0x%08x,%p) stub\n",
832 handle, when, callback, callback_arg, resume, period, state);
834 SERVER_START_REQ( set_timer )
836 req->handle = wine_server_obj_handle( handle );
837 req->period = period;
838 req->expire = when->QuadPart;
839 req->callback = wine_server_client_ptr( callback );
840 req->arg = wine_server_client_ptr( callback_arg );
841 status = wine_server_call( req );
842 if (state) *state = reply->signaled;
844 SERVER_END_REQ;
846 /* set error but can still succeed */
847 if (resume && status == STATUS_SUCCESS) return STATUS_TIMER_RESUME_IGNORED;
848 return status;
851 /**************************************************************************
852 * NtCancelTimer [NTDLL.@]
853 * ZwCancelTimer [NTDLL.@]
855 NTSTATUS WINAPI NtCancelTimer(IN HANDLE handle, OUT BOOLEAN* state)
857 NTSTATUS status;
859 SERVER_START_REQ( cancel_timer )
861 req->handle = wine_server_obj_handle( handle );
862 status = wine_server_call( req );
863 if (state) *state = reply->signaled;
865 SERVER_END_REQ;
866 return status;
869 /******************************************************************************
870 * NtQueryTimer (NTDLL.@)
872 * Retrieves information about a timer.
874 * PARAMS
875 * TimerHandle [I] The timer to retrieve information about.
876 * TimerInformationClass [I] The type of information to retrieve.
877 * TimerInformation [O] Pointer to buffer to store information in.
878 * Length [I] The length of the buffer pointed to by TimerInformation.
879 * ReturnLength [O] Optional. The size of buffer actually used.
881 * RETURNS
882 * Success: STATUS_SUCCESS
883 * Failure: STATUS_INFO_LENGTH_MISMATCH, if Length doesn't match the required data
884 * size for the class specified.
885 * STATUS_INVALID_INFO_CLASS, if an invalid TimerInformationClass was specified.
886 * STATUS_ACCESS_DENIED, if TimerHandle does not have TIMER_QUERY_STATE access
887 * to the timer.
889 NTSTATUS WINAPI NtQueryTimer(
890 HANDLE TimerHandle,
891 TIMER_INFORMATION_CLASS TimerInformationClass,
892 PVOID TimerInformation,
893 ULONG Length,
894 PULONG ReturnLength)
896 TIMER_BASIC_INFORMATION * basic_info = TimerInformation;
897 NTSTATUS status;
898 LARGE_INTEGER now;
900 TRACE("(%p,%d,%p,0x%08x,%p)\n", TimerHandle, TimerInformationClass,
901 TimerInformation, Length, ReturnLength);
903 switch (TimerInformationClass)
905 case TimerBasicInformation:
906 if (Length < sizeof(TIMER_BASIC_INFORMATION))
907 return STATUS_INFO_LENGTH_MISMATCH;
909 SERVER_START_REQ(get_timer_info)
911 req->handle = wine_server_obj_handle( TimerHandle );
912 status = wine_server_call(req);
914 /* convert server time to absolute NTDLL time */
915 basic_info->RemainingTime.QuadPart = reply->when;
916 basic_info->TimerState = reply->signaled;
918 SERVER_END_REQ;
920 /* convert from absolute into relative time */
921 NtQuerySystemTime(&now);
922 if (now.QuadPart > basic_info->RemainingTime.QuadPart)
923 basic_info->RemainingTime.QuadPart = 0;
924 else
925 basic_info->RemainingTime.QuadPart -= now.QuadPart;
927 if (ReturnLength) *ReturnLength = sizeof(TIMER_BASIC_INFORMATION);
929 return status;
932 FIXME("Unhandled class %d\n", TimerInformationClass);
933 return STATUS_INVALID_INFO_CLASS;
937 /******************************************************************************
938 * NtQueryTimerResolution [NTDLL.@]
940 NTSTATUS WINAPI NtQueryTimerResolution(OUT ULONG* min_resolution,
941 OUT ULONG* max_resolution,
942 OUT ULONG* current_resolution)
944 FIXME("(%p,%p,%p), stub!\n",
945 min_resolution, max_resolution, current_resolution);
947 return STATUS_NOT_IMPLEMENTED;
950 /******************************************************************************
951 * NtSetTimerResolution [NTDLL.@]
953 NTSTATUS WINAPI NtSetTimerResolution(IN ULONG resolution,
954 IN BOOLEAN set_resolution,
955 OUT ULONG* current_resolution )
957 FIXME("(%u,%u,%p), stub!\n",
958 resolution, set_resolution, current_resolution);
960 return STATUS_NOT_IMPLEMENTED;
965 /* wait operations */
967 static NTSTATUS wait_objects( DWORD count, const HANDLE *handles,
968 BOOLEAN wait_any, BOOLEAN alertable,
969 const LARGE_INTEGER *timeout )
971 select_op_t select_op;
972 UINT i, flags = SELECT_INTERRUPTIBLE;
974 if (!count || count > MAXIMUM_WAIT_OBJECTS) return STATUS_INVALID_PARAMETER_1;
976 if (alertable) flags |= SELECT_ALERTABLE;
977 select_op.wait.op = wait_any ? SELECT_WAIT : SELECT_WAIT_ALL;
978 for (i = 0; i < count; i++) select_op.wait.handles[i] = wine_server_obj_handle( handles[i] );
979 return server_select( &select_op, offsetof( select_op_t, wait.handles[count] ), flags, timeout );
983 /******************************************************************
984 * NtWaitForMultipleObjects (NTDLL.@)
986 NTSTATUS WINAPI NtWaitForMultipleObjects( DWORD count, const HANDLE *handles,
987 BOOLEAN wait_any, BOOLEAN alertable,
988 const LARGE_INTEGER *timeout )
990 return wait_objects( count, handles, wait_any, alertable, timeout );
994 /******************************************************************
995 * NtWaitForSingleObject (NTDLL.@)
997 NTSTATUS WINAPI NtWaitForSingleObject(HANDLE handle, BOOLEAN alertable, const LARGE_INTEGER *timeout )
999 return wait_objects( 1, &handle, FALSE, alertable, timeout );
1003 /******************************************************************
1004 * NtSignalAndWaitForSingleObject (NTDLL.@)
1006 NTSTATUS WINAPI NtSignalAndWaitForSingleObject( HANDLE hSignalObject, HANDLE hWaitObject,
1007 BOOLEAN alertable, const LARGE_INTEGER *timeout )
1009 select_op_t select_op;
1010 UINT flags = SELECT_INTERRUPTIBLE;
1012 if (!hSignalObject) return STATUS_INVALID_HANDLE;
1014 if (alertable) flags |= SELECT_ALERTABLE;
1015 select_op.signal_and_wait.op = SELECT_SIGNAL_AND_WAIT;
1016 select_op.signal_and_wait.wait = wine_server_obj_handle( hWaitObject );
1017 select_op.signal_and_wait.signal = wine_server_obj_handle( hSignalObject );
1018 return server_select( &select_op, sizeof(select_op.signal_and_wait), flags, timeout );
1022 /******************************************************************
1023 * NtYieldExecution (NTDLL.@)
1025 NTSTATUS WINAPI NtYieldExecution(void)
1027 #ifdef HAVE_SCHED_YIELD
1028 sched_yield();
1029 return STATUS_SUCCESS;
1030 #else
1031 return STATUS_NO_YIELD_PERFORMED;
1032 #endif
1036 /******************************************************************
1037 * NtDelayExecution (NTDLL.@)
1039 NTSTATUS WINAPI NtDelayExecution( BOOLEAN alertable, const LARGE_INTEGER *timeout )
1041 /* if alertable, we need to query the server */
1042 if (alertable)
1043 return server_select( NULL, 0, SELECT_INTERRUPTIBLE | SELECT_ALERTABLE, timeout );
1045 if (!timeout || timeout->QuadPart == TIMEOUT_INFINITE) /* sleep forever */
1047 for (;;) select( 0, NULL, NULL, NULL, NULL );
1049 else
1051 LARGE_INTEGER now;
1052 timeout_t when, diff;
1054 if ((when = timeout->QuadPart) < 0)
1056 NtQuerySystemTime( &now );
1057 when = now.QuadPart - when;
1060 /* Note that we yield after establishing the desired timeout */
1061 NtYieldExecution();
1062 if (!when) return STATUS_SUCCESS;
1064 for (;;)
1066 struct timeval tv;
1067 NtQuerySystemTime( &now );
1068 diff = (when - now.QuadPart + 9) / 10;
1069 if (diff <= 0) break;
1070 tv.tv_sec = diff / 1000000;
1071 tv.tv_usec = diff % 1000000;
1072 if (select( 0, NULL, NULL, NULL, &tv ) != -1) break;
1075 return STATUS_SUCCESS;
1079 /******************************************************************************
1080 * NtCreateKeyedEvent (NTDLL.@)
1082 NTSTATUS WINAPI NtCreateKeyedEvent( HANDLE *handle, ACCESS_MASK access,
1083 const OBJECT_ATTRIBUTES *attr, ULONG flags )
1085 NTSTATUS ret;
1086 data_size_t len;
1087 struct object_attributes *objattr;
1089 if ((ret = alloc_object_attributes( attr, &objattr, &len ))) return ret;
1091 SERVER_START_REQ( create_keyed_event )
1093 req->access = access;
1094 wine_server_add_data( req, objattr, len );
1095 ret = wine_server_call( req );
1096 *handle = wine_server_ptr_handle( reply->handle );
1098 SERVER_END_REQ;
1100 RtlFreeHeap( GetProcessHeap(), 0, objattr );
1101 return ret;
1104 /******************************************************************************
1105 * NtOpenKeyedEvent (NTDLL.@)
1107 NTSTATUS WINAPI NtOpenKeyedEvent( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr )
1109 NTSTATUS ret;
1111 if ((ret = validate_open_object_attributes( attr ))) return ret;
1113 SERVER_START_REQ( open_keyed_event )
1115 req->access = access;
1116 req->attributes = attr->Attributes;
1117 req->rootdir = wine_server_obj_handle( attr->RootDirectory );
1118 if (attr->ObjectName)
1119 wine_server_add_data( req, attr->ObjectName->Buffer, attr->ObjectName->Length );
1120 ret = wine_server_call( req );
1121 *handle = wine_server_ptr_handle( reply->handle );
1123 SERVER_END_REQ;
1124 return ret;
1127 /******************************************************************************
1128 * NtWaitForKeyedEvent (NTDLL.@)
1130 NTSTATUS WINAPI NtWaitForKeyedEvent( HANDLE handle, const void *key,
1131 BOOLEAN alertable, const LARGE_INTEGER *timeout )
1133 select_op_t select_op;
1134 UINT flags = SELECT_INTERRUPTIBLE;
1136 if ((ULONG_PTR)key & 1) return STATUS_INVALID_PARAMETER_1;
1137 if (alertable) flags |= SELECT_ALERTABLE;
1138 select_op.keyed_event.op = SELECT_KEYED_EVENT_WAIT;
1139 select_op.keyed_event.handle = wine_server_obj_handle( handle );
1140 select_op.keyed_event.key = wine_server_client_ptr( key );
1141 return server_select( &select_op, sizeof(select_op.keyed_event), flags, timeout );
1144 /******************************************************************************
1145 * NtReleaseKeyedEvent (NTDLL.@)
1147 NTSTATUS WINAPI NtReleaseKeyedEvent( HANDLE handle, const void *key,
1148 BOOLEAN alertable, const LARGE_INTEGER *timeout )
1150 select_op_t select_op;
1151 UINT flags = SELECT_INTERRUPTIBLE;
1153 if ((ULONG_PTR)key & 1) return STATUS_INVALID_PARAMETER_1;
1154 if (alertable) flags |= SELECT_ALERTABLE;
1155 select_op.keyed_event.op = SELECT_KEYED_EVENT_RELEASE;
1156 select_op.keyed_event.handle = wine_server_obj_handle( handle );
1157 select_op.keyed_event.key = wine_server_client_ptr( key );
1158 return server_select( &select_op, sizeof(select_op.keyed_event), flags, timeout );
1161 /******************************************************************
1162 * NtCreateIoCompletion (NTDLL.@)
1163 * ZwCreateIoCompletion (NTDLL.@)
1165 * Creates I/O completion object.
1167 * PARAMS
1168 * CompletionPort [O] created completion object handle will be placed there
1169 * DesiredAccess [I] desired access to a handle (combination of IO_COMPLETION_*)
1170 * ObjectAttributes [I] completion object attributes
1171 * NumberOfConcurrentThreads [I] desired number of concurrent active worker threads
1174 NTSTATUS WINAPI NtCreateIoCompletion( PHANDLE CompletionPort, ACCESS_MASK DesiredAccess,
1175 POBJECT_ATTRIBUTES attr, ULONG NumberOfConcurrentThreads )
1177 NTSTATUS status;
1178 data_size_t len;
1179 struct object_attributes *objattr;
1181 TRACE("(%p, %x, %p, %d)\n", CompletionPort, DesiredAccess, attr, NumberOfConcurrentThreads);
1183 if (!CompletionPort)
1184 return STATUS_INVALID_PARAMETER;
1186 if ((status = alloc_object_attributes( attr, &objattr, &len ))) return status;
1188 SERVER_START_REQ( create_completion )
1190 req->access = DesiredAccess;
1191 req->concurrent = NumberOfConcurrentThreads;
1192 wine_server_add_data( req, objattr, len );
1193 if (!(status = wine_server_call( req )))
1194 *CompletionPort = wine_server_ptr_handle( reply->handle );
1196 SERVER_END_REQ;
1198 RtlFreeHeap( GetProcessHeap(), 0, objattr );
1199 return status;
1202 /******************************************************************
1203 * NtSetIoCompletion (NTDLL.@)
1204 * ZwSetIoCompletion (NTDLL.@)
1206 * Inserts completion message into queue
1208 * PARAMS
1209 * CompletionPort [I] HANDLE to completion object
1210 * CompletionKey [I] completion key
1211 * CompletionValue [I] completion value (usually pointer to OVERLAPPED)
1212 * Status [I] operation status
1213 * NumberOfBytesTransferred [I] number of bytes transferred
1215 NTSTATUS WINAPI NtSetIoCompletion( HANDLE CompletionPort, ULONG_PTR CompletionKey,
1216 ULONG_PTR CompletionValue, NTSTATUS Status,
1217 SIZE_T NumberOfBytesTransferred )
1219 NTSTATUS status;
1221 TRACE("(%p, %lx, %lx, %x, %lx)\n", CompletionPort, CompletionKey,
1222 CompletionValue, Status, NumberOfBytesTransferred);
1224 SERVER_START_REQ( add_completion )
1226 req->handle = wine_server_obj_handle( CompletionPort );
1227 req->ckey = CompletionKey;
1228 req->cvalue = CompletionValue;
1229 req->status = Status;
1230 req->information = NumberOfBytesTransferred;
1231 status = wine_server_call( req );
1233 SERVER_END_REQ;
1234 return status;
1237 /******************************************************************
1238 * NtRemoveIoCompletion (NTDLL.@)
1239 * ZwRemoveIoCompletion (NTDLL.@)
1241 * (Wait for and) retrieve first completion message from completion object's queue
1243 * PARAMS
1244 * CompletionPort [I] HANDLE to I/O completion object
1245 * CompletionKey [O] completion key
1246 * CompletionValue [O] Completion value given in NtSetIoCompletion or in async operation
1247 * iosb [O] IO_STATUS_BLOCK of completed asynchronous operation
1248 * WaitTime [I] optional wait time in NTDLL format
1251 NTSTATUS WINAPI NtRemoveIoCompletion( HANDLE CompletionPort, PULONG_PTR CompletionKey,
1252 PULONG_PTR CompletionValue, PIO_STATUS_BLOCK iosb,
1253 PLARGE_INTEGER WaitTime )
1255 NTSTATUS status;
1257 TRACE("(%p, %p, %p, %p, %p)\n", CompletionPort, CompletionKey,
1258 CompletionValue, iosb, WaitTime);
1260 for(;;)
1262 SERVER_START_REQ( remove_completion )
1264 req->handle = wine_server_obj_handle( CompletionPort );
1265 if (!(status = wine_server_call( req )))
1267 *CompletionKey = reply->ckey;
1268 *CompletionValue = reply->cvalue;
1269 iosb->Information = reply->information;
1270 iosb->u.Status = reply->status;
1273 SERVER_END_REQ;
1274 if (status != STATUS_PENDING) break;
1276 status = NtWaitForSingleObject( CompletionPort, FALSE, WaitTime );
1277 if (status != WAIT_OBJECT_0) break;
1279 return status;
1282 /******************************************************************
1283 * NtOpenIoCompletion (NTDLL.@)
1284 * ZwOpenIoCompletion (NTDLL.@)
1286 * Opens I/O completion object
1288 * PARAMS
1289 * CompletionPort [O] completion object handle will be placed there
1290 * DesiredAccess [I] desired access to a handle (combination of IO_COMPLETION_*)
1291 * ObjectAttributes [I] completion object name
1294 NTSTATUS WINAPI NtOpenIoCompletion( HANDLE *handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr )
1296 NTSTATUS status;
1298 if (!handle) return STATUS_INVALID_PARAMETER;
1299 if ((status = validate_open_object_attributes( attr ))) return status;
1301 SERVER_START_REQ( open_completion )
1303 req->access = access;
1304 req->attributes = attr->Attributes;
1305 req->rootdir = wine_server_obj_handle( attr->RootDirectory );
1306 if (attr->ObjectName)
1307 wine_server_add_data( req, attr->ObjectName->Buffer, attr->ObjectName->Length );
1308 status = wine_server_call( req );
1309 *handle = wine_server_ptr_handle( reply->handle );
1311 SERVER_END_REQ;
1312 return status;
1315 /******************************************************************
1316 * NtQueryIoCompletion (NTDLL.@)
1317 * ZwQueryIoCompletion (NTDLL.@)
1319 * Requests information about given I/O completion object
1321 * PARAMS
1322 * CompletionPort [I] HANDLE to completion port to request
1323 * InformationClass [I] information class
1324 * CompletionInformation [O] user-provided buffer for data
1325 * BufferLength [I] buffer length
1326 * RequiredLength [O] required buffer length
1329 NTSTATUS WINAPI NtQueryIoCompletion( HANDLE CompletionPort, IO_COMPLETION_INFORMATION_CLASS InformationClass,
1330 PVOID CompletionInformation, ULONG BufferLength, PULONG RequiredLength )
1332 NTSTATUS status;
1334 TRACE("(%p, %d, %p, 0x%x, %p)\n", CompletionPort, InformationClass, CompletionInformation,
1335 BufferLength, RequiredLength);
1337 if (!CompletionInformation) return STATUS_INVALID_PARAMETER;
1338 switch( InformationClass )
1340 case IoCompletionBasicInformation:
1342 ULONG *info = CompletionInformation;
1344 if (RequiredLength) *RequiredLength = sizeof(*info);
1345 if (BufferLength != sizeof(*info))
1346 status = STATUS_INFO_LENGTH_MISMATCH;
1347 else
1349 SERVER_START_REQ( query_completion )
1351 req->handle = wine_server_obj_handle( CompletionPort );
1352 if (!(status = wine_server_call( req )))
1353 *info = reply->depth;
1355 SERVER_END_REQ;
1358 break;
1359 default:
1360 status = STATUS_INVALID_PARAMETER;
1361 break;
1363 return status;
1366 NTSTATUS NTDLL_AddCompletion( HANDLE hFile, ULONG_PTR CompletionValue,
1367 NTSTATUS CompletionStatus, ULONG Information )
1369 NTSTATUS status;
1371 SERVER_START_REQ( add_fd_completion )
1373 req->handle = wine_server_obj_handle( hFile );
1374 req->cvalue = CompletionValue;
1375 req->status = CompletionStatus;
1376 req->information = Information;
1377 status = wine_server_call( req );
1379 SERVER_END_REQ;
1380 return status;
1383 /******************************************************************
1384 * RtlRunOnceInitialize (NTDLL.@)
1386 void WINAPI RtlRunOnceInitialize( RTL_RUN_ONCE *once )
1388 once->Ptr = NULL;
1391 /******************************************************************
1392 * RtlRunOnceBeginInitialize (NTDLL.@)
1394 DWORD WINAPI RtlRunOnceBeginInitialize( RTL_RUN_ONCE *once, ULONG flags, void **context )
1396 if (flags & RTL_RUN_ONCE_CHECK_ONLY)
1398 ULONG_PTR val = (ULONG_PTR)once->Ptr;
1400 if (flags & RTL_RUN_ONCE_ASYNC) return STATUS_INVALID_PARAMETER;
1401 if ((val & 3) != 2) return STATUS_UNSUCCESSFUL;
1402 if (context) *context = (void *)(val & ~3);
1403 return STATUS_SUCCESS;
1406 for (;;)
1408 ULONG_PTR next, val = (ULONG_PTR)once->Ptr;
1410 switch (val & 3)
1412 case 0: /* first time */
1413 if (!interlocked_cmpxchg_ptr( &once->Ptr,
1414 (flags & RTL_RUN_ONCE_ASYNC) ? (void *)3 : (void *)1, 0 ))
1415 return STATUS_PENDING;
1416 break;
1418 case 1: /* in progress, wait */
1419 if (flags & RTL_RUN_ONCE_ASYNC) return STATUS_INVALID_PARAMETER;
1420 next = val & ~3;
1421 if (interlocked_cmpxchg_ptr( &once->Ptr, (void *)((ULONG_PTR)&next | 1),
1422 (void *)val ) == (void *)val)
1423 NtWaitForKeyedEvent( keyed_event, &next, FALSE, NULL );
1424 break;
1426 case 2: /* done */
1427 if (context) *context = (void *)(val & ~3);
1428 return STATUS_SUCCESS;
1430 case 3: /* in progress, async */
1431 if (!(flags & RTL_RUN_ONCE_ASYNC)) return STATUS_INVALID_PARAMETER;
1432 return STATUS_PENDING;
1437 /******************************************************************
1438 * RtlRunOnceComplete (NTDLL.@)
1440 DWORD WINAPI RtlRunOnceComplete( RTL_RUN_ONCE *once, ULONG flags, void *context )
1442 if ((ULONG_PTR)context & 3) return STATUS_INVALID_PARAMETER;
1444 if (flags & RTL_RUN_ONCE_INIT_FAILED)
1446 if (context) return STATUS_INVALID_PARAMETER;
1447 if (flags & RTL_RUN_ONCE_ASYNC) return STATUS_INVALID_PARAMETER;
1449 else context = (void *)((ULONG_PTR)context | 2);
1451 for (;;)
1453 ULONG_PTR val = (ULONG_PTR)once->Ptr;
1455 switch (val & 3)
1457 case 1: /* in progress */
1458 if (interlocked_cmpxchg_ptr( &once->Ptr, context, (void *)val ) != (void *)val) break;
1459 val &= ~3;
1460 while (val)
1462 ULONG_PTR next = *(ULONG_PTR *)val;
1463 NtReleaseKeyedEvent( keyed_event, (void *)val, FALSE, NULL );
1464 val = next;
1466 return STATUS_SUCCESS;
1468 case 3: /* in progress, async */
1469 if (!(flags & RTL_RUN_ONCE_ASYNC)) return STATUS_INVALID_PARAMETER;
1470 if (interlocked_cmpxchg_ptr( &once->Ptr, context, (void *)val ) != (void *)val) break;
1471 return STATUS_SUCCESS;
1473 default:
1474 return STATUS_UNSUCCESSFUL;
1479 /******************************************************************
1480 * RtlRunOnceExecuteOnce (NTDLL.@)
1482 DWORD WINAPI RtlRunOnceExecuteOnce( RTL_RUN_ONCE *once, PRTL_RUN_ONCE_INIT_FN func,
1483 void *param, void **context )
1485 DWORD ret = RtlRunOnceBeginInitialize( once, 0, context );
1487 if (ret != STATUS_PENDING) return ret;
1489 if (!func( once, param, context ))
1491 RtlRunOnceComplete( once, RTL_RUN_ONCE_INIT_FAILED, NULL );
1492 return STATUS_UNSUCCESSFUL;
1495 return RtlRunOnceComplete( once, 0, context ? *context : NULL );
1499 /* SRW locks implementation
1501 * The memory layout used by the lock is:
1503 * 32 31 16 0
1504 * ________________ ________________
1505 * | X| #exclusive | #shared |
1506 * ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯
1507 * Since there is no space left for a separate counter of shared access
1508 * threads inside the locked section the #shared field is used for multiple
1509 * purposes. The following table lists all possible states the lock can be
1510 * in, notation: [X, #exclusive, #shared]:
1512 * [0, 0, N] -> locked by N shared access threads, if N=0 its unlocked
1513 * [0, >=1, >=1] -> threads are requesting exclusive locks, but there are
1514 * still shared access threads inside. #shared should not be incremented
1515 * anymore!
1516 * [1, >=1, >=0] -> lock is owned by an exclusive thread and the #shared
1517 * counter can be used again to count the number of threads waiting in the
1518 * queue for shared access.
1520 * the following states are invalid and will never occur:
1521 * [0, >=1, 0], [1, 0, >=0]
1523 * The main problem arising from the fact that we have no separate counter
1524 * of shared access threads inside the locked section is that in the state
1525 * [0, >=1, >=1] above we cannot add additional waiting threads to the
1526 * shared access queue - it wouldn't be possible to distinguish waiting
1527 * threads and those that are still inside. To solve this problem the lock
1528 * uses the following approach: a thread that isn't able to allocate a
1529 * shared lock just uses the exclusive queue instead. As soon as the thread
1530 * is woken up it is in the state [1, >=1, >=0]. In this state it's again
1531 * possible to use the shared access queue. The thread atomically moves
1532 * itself to the shared access queue and releases the exclusive lock, so
1533 * that the "real" exclusive access threads have a chance. As soon as they
1534 * are all ready the shared access threads are processed.
1537 #define SRWLOCK_MASK_IN_EXCLUSIVE 0x80000000
1538 #define SRWLOCK_MASK_EXCLUSIVE_QUEUE 0x7fff0000
1539 #define SRWLOCK_MASK_SHARED_QUEUE 0x0000ffff
1540 #define SRWLOCK_RES_EXCLUSIVE 0x00010000
1541 #define SRWLOCK_RES_SHARED 0x00000001
1543 #ifdef WORDS_BIGENDIAN
1544 #define srwlock_key_exclusive(lock) (&lock->Ptr)
1545 #define srwlock_key_shared(lock) ((void *)((char *)&lock->Ptr + 2))
1546 #else
1547 #define srwlock_key_exclusive(lock) ((void *)((char *)&lock->Ptr + 2))
1548 #define srwlock_key_shared(lock) (&lock->Ptr)
1549 #endif
1551 static inline void srwlock_check_invalid( unsigned int val )
1553 /* Throw exception if it's impossible to acquire/release this lock. */
1554 if ((val & SRWLOCK_MASK_EXCLUSIVE_QUEUE) == SRWLOCK_MASK_EXCLUSIVE_QUEUE ||
1555 (val & SRWLOCK_MASK_SHARED_QUEUE) == SRWLOCK_MASK_SHARED_QUEUE)
1556 RtlRaiseStatus(STATUS_RESOURCE_NOT_OWNED);
1559 static inline unsigned int srwlock_lock_exclusive( unsigned int *dest, int incr )
1561 unsigned int val, tmp;
1562 /* Atomically modifies the value of *dest by adding incr. If the shared
1563 * queue is empty and there are threads waiting for exclusive access, then
1564 * sets the mark SRWLOCK_MASK_IN_EXCLUSIVE to signal other threads that
1565 * they are allowed again to use the shared queue counter. */
1566 for (val = *dest;; val = tmp)
1568 tmp = val + incr;
1569 srwlock_check_invalid( tmp );
1570 if ((tmp & SRWLOCK_MASK_EXCLUSIVE_QUEUE) && !(tmp & SRWLOCK_MASK_SHARED_QUEUE))
1571 tmp |= SRWLOCK_MASK_IN_EXCLUSIVE;
1572 if ((tmp = interlocked_cmpxchg( (int *)dest, tmp, val )) == val)
1573 break;
1575 return val;
1578 static inline unsigned int srwlock_unlock_exclusive( unsigned int *dest, int incr )
1580 unsigned int val, tmp;
1581 /* Atomically modifies the value of *dest by adding incr. If the queue of
1582 * threads waiting for exclusive access is empty, then remove the
1583 * SRWLOCK_MASK_IN_EXCLUSIVE flag (only the shared queue counter will
1584 * remain). */
1585 for (val = *dest;; val = tmp)
1587 tmp = val + incr;
1588 srwlock_check_invalid( tmp );
1589 if (!(tmp & SRWLOCK_MASK_EXCLUSIVE_QUEUE))
1590 tmp &= SRWLOCK_MASK_SHARED_QUEUE;
1591 if ((tmp = interlocked_cmpxchg( (int *)dest, tmp, val )) == val)
1592 break;
1594 return val;
1597 static inline void srwlock_leave_exclusive( RTL_SRWLOCK *lock, unsigned int val )
1599 /* Used when a thread leaves an exclusive section. If there are other
1600 * exclusive access threads they are processed first, followed by
1601 * the shared waiters. */
1602 if (val & SRWLOCK_MASK_EXCLUSIVE_QUEUE)
1603 NtReleaseKeyedEvent( keyed_event, srwlock_key_exclusive(lock), FALSE, NULL );
1604 else
1606 val &= SRWLOCK_MASK_SHARED_QUEUE; /* remove SRWLOCK_MASK_IN_EXCLUSIVE */
1607 while (val--)
1608 NtReleaseKeyedEvent( keyed_event, srwlock_key_shared(lock), FALSE, NULL );
1612 static inline void srwlock_leave_shared( RTL_SRWLOCK *lock, unsigned int val )
1614 /* Wake up one exclusive thread as soon as the last shared access thread
1615 * has left. */
1616 if ((val & SRWLOCK_MASK_EXCLUSIVE_QUEUE) && !(val & SRWLOCK_MASK_SHARED_QUEUE))
1617 NtReleaseKeyedEvent( keyed_event, srwlock_key_exclusive(lock), FALSE, NULL );
1620 /***********************************************************************
1621 * RtlInitializeSRWLock (NTDLL.@)
1623 * NOTES
1624 * Please note that SRWLocks do not keep track of the owner of a lock.
1625 * It doesn't make any difference which thread for example unlocks an
1626 * SRWLock (see corresponding tests). This implementation uses two
1627 * keyed events (one for the exclusive waiters and one for the shared
1628 * waiters) and is limited to 2^15-1 waiting threads.
1630 void WINAPI RtlInitializeSRWLock( RTL_SRWLOCK *lock )
1632 lock->Ptr = NULL;
1635 /***********************************************************************
1636 * RtlAcquireSRWLockExclusive (NTDLL.@)
1638 * NOTES
1639 * Unlike RtlAcquireResourceExclusive this function doesn't allow
1640 * nested calls from the same thread. "Upgrading" a shared access lock
1641 * to an exclusive access lock also doesn't seem to be supported.
1643 void WINAPI RtlAcquireSRWLockExclusive( RTL_SRWLOCK *lock )
1645 if (srwlock_lock_exclusive( (unsigned int *)&lock->Ptr, SRWLOCK_RES_EXCLUSIVE ))
1646 NtWaitForKeyedEvent( keyed_event, srwlock_key_exclusive(lock), FALSE, NULL );
1649 /***********************************************************************
1650 * RtlAcquireSRWLockShared (NTDLL.@)
1652 * NOTES
1653 * Do not call this function recursively - it will only succeed when
1654 * there are no threads waiting for an exclusive lock!
1656 void WINAPI RtlAcquireSRWLockShared( RTL_SRWLOCK *lock )
1658 unsigned int val, tmp;
1659 /* Acquires a shared lock. If it's currently not possible to add elements to
1660 * the shared queue, then request exclusive access instead. */
1661 for (val = *(unsigned int *)&lock->Ptr;; val = tmp)
1663 if ((val & SRWLOCK_MASK_EXCLUSIVE_QUEUE) && !(val & SRWLOCK_MASK_IN_EXCLUSIVE))
1664 tmp = val + SRWLOCK_RES_EXCLUSIVE;
1665 else
1666 tmp = val + SRWLOCK_RES_SHARED;
1667 if ((tmp = interlocked_cmpxchg( (int *)&lock->Ptr, tmp, val )) == val)
1668 break;
1671 /* Drop exclusive access again and instead requeue for shared access. */
1672 if ((val & SRWLOCK_MASK_EXCLUSIVE_QUEUE) && !(val & SRWLOCK_MASK_IN_EXCLUSIVE))
1674 NtWaitForKeyedEvent( keyed_event, srwlock_key_exclusive(lock), FALSE, NULL );
1675 val = srwlock_unlock_exclusive( (unsigned int *)&lock->Ptr, (SRWLOCK_RES_SHARED
1676 - SRWLOCK_RES_EXCLUSIVE) ) - SRWLOCK_RES_EXCLUSIVE;
1677 srwlock_leave_exclusive( lock, val );
1680 if (val & SRWLOCK_MASK_EXCLUSIVE_QUEUE)
1681 NtWaitForKeyedEvent( keyed_event, srwlock_key_shared(lock), FALSE, NULL );
1684 /***********************************************************************
1685 * RtlReleaseSRWLockExclusive (NTDLL.@)
1687 void WINAPI RtlReleaseSRWLockExclusive( RTL_SRWLOCK *lock )
1689 srwlock_leave_exclusive( lock, srwlock_unlock_exclusive( (unsigned int *)&lock->Ptr,
1690 - SRWLOCK_RES_EXCLUSIVE ) - SRWLOCK_RES_EXCLUSIVE );
1693 /***********************************************************************
1694 * RtlReleaseSRWLockShared (NTDLL.@)
1696 void WINAPI RtlReleaseSRWLockShared( RTL_SRWLOCK *lock )
1698 srwlock_leave_shared( lock, srwlock_lock_exclusive( (unsigned int *)&lock->Ptr,
1699 - SRWLOCK_RES_SHARED ) - SRWLOCK_RES_SHARED );
1702 /***********************************************************************
1703 * RtlTryAcquireSRWLockExclusive (NTDLL.@)
1705 * NOTES
1706 * Similar to AcquireSRWLockExclusive recusive calls are not allowed
1707 * and will fail with return value FALSE.
1709 BOOLEAN WINAPI RtlTryAcquireSRWLockExclusive( RTL_SRWLOCK *lock )
1711 return interlocked_cmpxchg( (int *)&lock->Ptr, SRWLOCK_MASK_IN_EXCLUSIVE |
1712 SRWLOCK_RES_EXCLUSIVE, 0 ) == 0;
1715 /***********************************************************************
1716 * RtlTryAcquireSRWLockShared (NTDLL.@)
1718 BOOLEAN WINAPI RtlTryAcquireSRWLockShared( RTL_SRWLOCK *lock )
1720 unsigned int val, tmp;
1721 for (val = *(unsigned int *)&lock->Ptr;; val = tmp)
1723 if (val & SRWLOCK_MASK_EXCLUSIVE_QUEUE)
1724 return FALSE;
1725 if ((tmp = interlocked_cmpxchg( (int *)&lock->Ptr, val + SRWLOCK_RES_SHARED, val )) == val)
1726 break;
1728 return TRUE;
1731 /***********************************************************************
1732 * RtlInitializeConditionVariable (NTDLL.@)
1734 * Initializes the condition variable with NULL.
1736 * PARAMS
1737 * variable [O] condition variable
1739 * RETURNS
1740 * Nothing.
1742 void WINAPI RtlInitializeConditionVariable( RTL_CONDITION_VARIABLE *variable )
1744 variable->Ptr = NULL;
1747 /***********************************************************************
1748 * RtlWakeConditionVariable (NTDLL.@)
1750 * Wakes up one thread waiting on the condition variable.
1752 * PARAMS
1753 * variable [I/O] condition variable to wake up.
1755 * RETURNS
1756 * Nothing.
1758 * NOTES
1759 * The calling thread does not have to own any lock in order to call
1760 * this function.
1762 void WINAPI RtlWakeConditionVariable( RTL_CONDITION_VARIABLE *variable )
1764 if (interlocked_dec_if_nonzero( (int *)&variable->Ptr ))
1765 NtReleaseKeyedEvent( keyed_event, &variable->Ptr, FALSE, NULL );
1768 /***********************************************************************
1769 * RtlWakeAllConditionVariable (NTDLL.@)
1771 * See WakeConditionVariable, wakes up all waiting threads.
1773 void WINAPI RtlWakeAllConditionVariable( RTL_CONDITION_VARIABLE *variable )
1775 int val = interlocked_xchg( (int *)&variable->Ptr, 0 );
1776 while (val-- > 0)
1777 NtReleaseKeyedEvent( keyed_event, &variable->Ptr, FALSE, NULL );
1780 /***********************************************************************
1781 * RtlSleepConditionVariableCS (NTDLL.@)
1783 * Atomically releases the critical section and suspends the thread,
1784 * waiting for a Wake(All)ConditionVariable event. Afterwards it enters
1785 * the critical section again and returns.
1787 * PARAMS
1788 * variable [I/O] condition variable
1789 * crit [I/O] critical section to leave temporarily
1790 * timeout [I] timeout
1792 * RETURNS
1793 * see NtWaitForKeyedEvent for all possible return values.
1795 NTSTATUS WINAPI RtlSleepConditionVariableCS( RTL_CONDITION_VARIABLE *variable, RTL_CRITICAL_SECTION *crit,
1796 const LARGE_INTEGER *timeout )
1798 NTSTATUS status;
1799 interlocked_xchg_add( (int *)&variable->Ptr, 1 );
1800 RtlLeaveCriticalSection( crit );
1802 status = NtWaitForKeyedEvent( keyed_event, &variable->Ptr, FALSE, timeout );
1803 if (status != STATUS_SUCCESS)
1805 if (!interlocked_dec_if_nonzero( (int *)&variable->Ptr ))
1806 status = NtWaitForKeyedEvent( keyed_event, &variable->Ptr, FALSE, NULL );
1809 RtlEnterCriticalSection( crit );
1810 return status;
1813 /***********************************************************************
1814 * RtlSleepConditionVariableSRW (NTDLL.@)
1816 * Atomically releases the SRWLock and suspends the thread,
1817 * waiting for a Wake(All)ConditionVariable event. Afterwards it enters
1818 * the SRWLock again with the same access rights and returns.
1820 * PARAMS
1821 * variable [I/O] condition variable
1822 * lock [I/O] SRWLock to leave temporarily
1823 * timeout [I] timeout
1824 * flags [I] type of the current lock (exclusive / shared)
1826 * RETURNS
1827 * see NtWaitForKeyedEvent for all possible return values.
1829 * NOTES
1830 * the behaviour is undefined if the thread doesn't own the lock.
1832 NTSTATUS WINAPI RtlSleepConditionVariableSRW( RTL_CONDITION_VARIABLE *variable, RTL_SRWLOCK *lock,
1833 const LARGE_INTEGER *timeout, ULONG flags )
1835 NTSTATUS status;
1836 interlocked_xchg_add( (int *)&variable->Ptr, 1 );
1838 if (flags & RTL_CONDITION_VARIABLE_LOCKMODE_SHARED)
1839 RtlReleaseSRWLockShared( lock );
1840 else
1841 RtlReleaseSRWLockExclusive( lock );
1843 status = NtWaitForKeyedEvent( keyed_event, &variable->Ptr, FALSE, timeout );
1844 if (status != STATUS_SUCCESS)
1846 if (!interlocked_dec_if_nonzero( (int *)&variable->Ptr ))
1847 status = NtWaitForKeyedEvent( keyed_event, &variable->Ptr, FALSE, NULL );
1850 if (flags & RTL_CONDITION_VARIABLE_LOCKMODE_SHARED)
1851 RtlAcquireSRWLockShared( lock );
1852 else
1853 RtlAcquireSRWLockExclusive( lock );
1854 return status;