d3dx9: Use all 32 bits as mask.
[wine] / dlls / ntdll / sync.c
1 /*
2  *      Process synchronisation
3  *
4  * Copyright 1996, 1997, 1998 Marcus Meissner
5  * Copyright 1997, 1999 Alexandre Julliard
6  * Copyright 1999, 2000 Juergen Schmied
7  * Copyright 2003 Eric Pouech
8  *
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.
13  *
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.
18  *
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
22  */
23
24 #include "config.h"
25
26 #include <assert.h>
27 #include <errno.h>
28 #include <signal.h>
29 #ifdef HAVE_SYS_TIME_H
30 # include <sys/time.h>
31 #endif
32 #ifdef HAVE_POLL_H
33 #include <poll.h>
34 #endif
35 #ifdef HAVE_SYS_POLL_H
36 # include <sys/poll.h>
37 #endif
38 #ifdef HAVE_UNISTD_H
39 # include <unistd.h>
40 #endif
41 #ifdef HAVE_SCHED_H
42 # include <sched.h>
43 #endif
44 #include <string.h>
45 #include <stdarg.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <time.h>
49
50 #define NONAMELESSUNION
51 #define NONAMELESSSTRUCT
52
53 #include "ntstatus.h"
54 #define WIN32_NO_STATUS
55 #include "windef.h"
56 #include "winternl.h"
57 #include "wine/server.h"
58 #include "wine/debug.h"
59 #include "ntdll_misc.h"
60
61 WINE_DEFAULT_DEBUG_CHANNEL(ntdll);
62
63 /* creates a struct security_descriptor and contained information in one contiguous piece of memory */
64 NTSTATUS NTDLL_create_struct_sd(PSECURITY_DESCRIPTOR nt_sd, struct security_descriptor **server_sd,
65                                 data_size_t *server_sd_len)
66 {
67     unsigned int len;
68     PSID owner, group;
69     ACL *dacl, *sacl;
70     BOOLEAN owner_present, group_present, dacl_present, sacl_present;
71     BOOLEAN defaulted;
72     NTSTATUS status;
73     unsigned char *ptr;
74
75     if (!nt_sd)
76     {
77         *server_sd = NULL;
78         *server_sd_len = 0;
79         return STATUS_SUCCESS;
80     }
81
82     len = sizeof(struct security_descriptor);
83
84     status = RtlGetOwnerSecurityDescriptor(nt_sd, &owner, &owner_present);
85     if (status != STATUS_SUCCESS) return status;
86     status = RtlGetGroupSecurityDescriptor(nt_sd, &group, &group_present);
87     if (status != STATUS_SUCCESS) return status;
88     status = RtlGetSaclSecurityDescriptor(nt_sd, &sacl_present, &sacl, &defaulted);
89     if (status != STATUS_SUCCESS) return status;
90     status = RtlGetDaclSecurityDescriptor(nt_sd, &dacl_present, &dacl, &defaulted);
91     if (status != STATUS_SUCCESS) return status;
92
93     if (owner_present)
94         len += RtlLengthSid(owner);
95     if (group_present)
96         len += RtlLengthSid(group);
97     if (sacl_present && sacl)
98         len += sacl->AclSize;
99     if (dacl_present && dacl)
100         len += dacl->AclSize;
101
102     /* fix alignment for the Unicode name that follows the structure */
103     len = (len + sizeof(WCHAR) - 1) & ~(sizeof(WCHAR) - 1);
104     *server_sd = RtlAllocateHeap(GetProcessHeap(), 0, len);
105     if (!*server_sd) return STATUS_NO_MEMORY;
106
107     (*server_sd)->control = ((SECURITY_DESCRIPTOR *)nt_sd)->Control & ~SE_SELF_RELATIVE;
108     (*server_sd)->owner_len = owner_present ? RtlLengthSid(owner) : 0;
109     (*server_sd)->group_len = group_present ? RtlLengthSid(group) : 0;
110     (*server_sd)->sacl_len = (sacl_present && sacl) ? sacl->AclSize : 0;
111     (*server_sd)->dacl_len = (dacl_present && dacl) ? dacl->AclSize : 0;
112
113     ptr = (unsigned char *)(*server_sd + 1);
114     memcpy(ptr, owner, (*server_sd)->owner_len);
115     ptr += (*server_sd)->owner_len;
116     memcpy(ptr, group, (*server_sd)->group_len);
117     ptr += (*server_sd)->group_len;
118     memcpy(ptr, sacl, (*server_sd)->sacl_len);
119     ptr += (*server_sd)->sacl_len;
120     memcpy(ptr, dacl, (*server_sd)->dacl_len);
121
122     *server_sd_len = len;
123
124     return STATUS_SUCCESS;
125 }
126
127 /* frees a struct security_descriptor allocated by NTDLL_create_struct_sd */
128 void NTDLL_free_struct_sd(struct security_descriptor *server_sd)
129 {
130     RtlFreeHeap(GetProcessHeap(), 0, server_sd);
131 }
132
133 /*
134  *      Semaphores
135  */
136
137 /******************************************************************************
138  *  NtCreateSemaphore (NTDLL.@)
139  */
140 NTSTATUS WINAPI NtCreateSemaphore( OUT PHANDLE SemaphoreHandle,
141                                    IN ACCESS_MASK access,
142                                    IN const OBJECT_ATTRIBUTES *attr OPTIONAL,
143                                    IN LONG InitialCount,
144                                    IN LONG MaximumCount )
145 {
146     DWORD len = attr && attr->ObjectName ? attr->ObjectName->Length : 0;
147     NTSTATUS ret;
148     struct object_attributes objattr;
149     struct security_descriptor *sd = NULL;
150
151     if (MaximumCount <= 0 || InitialCount < 0 || InitialCount > MaximumCount)
152         return STATUS_INVALID_PARAMETER;
153     if (len >= MAX_PATH * sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
154
155     objattr.rootdir = wine_server_obj_handle( attr ? attr->RootDirectory : 0 );
156     objattr.sd_len = 0;
157     objattr.name_len = len;
158     if (attr)
159     {
160         ret = NTDLL_create_struct_sd( attr->SecurityDescriptor, &sd, &objattr.sd_len );
161         if (ret != STATUS_SUCCESS) return ret;
162     }
163
164     SERVER_START_REQ( create_semaphore )
165     {
166         req->access  = access;
167         req->attributes = (attr) ? attr->Attributes : 0;
168         req->initial = InitialCount;
169         req->max     = MaximumCount;
170         wine_server_add_data( req, &objattr, sizeof(objattr) );
171         if (objattr.sd_len) wine_server_add_data( req, sd, objattr.sd_len );
172         if (len) wine_server_add_data( req, attr->ObjectName->Buffer, len );
173         ret = wine_server_call( req );
174         *SemaphoreHandle = wine_server_ptr_handle( reply->handle );
175     }
176     SERVER_END_REQ;
177
178     NTDLL_free_struct_sd( sd );
179
180     return ret;
181 }
182
183 /******************************************************************************
184  *  NtOpenSemaphore (NTDLL.@)
185  */
186 NTSTATUS WINAPI NtOpenSemaphore( OUT PHANDLE SemaphoreHandle,
187                                  IN ACCESS_MASK access,
188                                  IN const OBJECT_ATTRIBUTES *attr )
189 {
190     DWORD len = attr && attr->ObjectName ? attr->ObjectName->Length : 0;
191     NTSTATUS ret;
192
193     if (len >= MAX_PATH * sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
194
195     SERVER_START_REQ( open_semaphore )
196     {
197         req->access  = access;
198         req->attributes = (attr) ? attr->Attributes : 0;
199         req->rootdir = wine_server_obj_handle( attr ? attr->RootDirectory : 0 );
200         if (len) wine_server_add_data( req, attr->ObjectName->Buffer, len );
201         ret = wine_server_call( req );
202         *SemaphoreHandle = wine_server_ptr_handle( reply->handle );
203     }
204     SERVER_END_REQ;
205     return ret;
206 }
207
208 /******************************************************************************
209  *  NtQuerySemaphore (NTDLL.@)
210  */
211 NTSTATUS WINAPI NtQuerySemaphore(
212         HANDLE SemaphoreHandle,
213         SEMAPHORE_INFORMATION_CLASS SemaphoreInformationClass,
214         PVOID SemaphoreInformation,
215         ULONG Length,
216         PULONG ReturnLength)
217 {
218         FIXME("(%p,%d,%p,0x%08x,%p) stub!\n",
219         SemaphoreHandle, SemaphoreInformationClass, SemaphoreInformation, Length, ReturnLength);
220         return STATUS_SUCCESS;
221 }
222
223 /******************************************************************************
224  *  NtReleaseSemaphore (NTDLL.@)
225  */
226 NTSTATUS WINAPI NtReleaseSemaphore( HANDLE handle, ULONG count, PULONG previous )
227 {
228     NTSTATUS ret;
229     SERVER_START_REQ( release_semaphore )
230     {
231         req->handle = wine_server_obj_handle( handle );
232         req->count  = count;
233         if (!(ret = wine_server_call( req )))
234         {
235             if (previous) *previous = reply->prev_count;
236         }
237     }
238     SERVER_END_REQ;
239     return ret;
240 }
241
242 /*
243  *      Events
244  */
245
246 /**************************************************************************
247  * NtCreateEvent (NTDLL.@)
248  * ZwCreateEvent (NTDLL.@)
249  */
250 NTSTATUS WINAPI NtCreateEvent( PHANDLE EventHandle, ACCESS_MASK DesiredAccess,
251                                const OBJECT_ATTRIBUTES *attr, EVENT_TYPE type, BOOLEAN InitialState)
252 {
253     DWORD len = attr && attr->ObjectName ? attr->ObjectName->Length : 0;
254     NTSTATUS ret;
255     struct security_descriptor *sd = NULL;
256     struct object_attributes objattr;
257
258     if (len >= MAX_PATH * sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
259
260     objattr.rootdir = wine_server_obj_handle( attr ? attr->RootDirectory : 0 );
261     objattr.sd_len = 0;
262     objattr.name_len = len;
263     if (attr)
264     {
265         ret = NTDLL_create_struct_sd( attr->SecurityDescriptor, &sd, &objattr.sd_len );
266         if (ret != STATUS_SUCCESS) return ret;
267     }
268
269     SERVER_START_REQ( create_event )
270     {
271         req->access = DesiredAccess;
272         req->attributes = (attr) ? attr->Attributes : 0;
273         req->manual_reset = (type == NotificationEvent);
274         req->initial_state = InitialState;
275         wine_server_add_data( req, &objattr, sizeof(objattr) );
276         if (objattr.sd_len) wine_server_add_data( req, sd, objattr.sd_len );
277         if (len) wine_server_add_data( req, attr->ObjectName->Buffer, len );
278         ret = wine_server_call( req );
279         *EventHandle = wine_server_ptr_handle( reply->handle );
280     }
281     SERVER_END_REQ;
282
283     NTDLL_free_struct_sd( sd );
284
285     return ret;
286 }
287
288 /******************************************************************************
289  *  NtOpenEvent (NTDLL.@)
290  *  ZwOpenEvent (NTDLL.@)
291  */
292 NTSTATUS WINAPI NtOpenEvent(
293         OUT PHANDLE EventHandle,
294         IN ACCESS_MASK DesiredAccess,
295         IN const OBJECT_ATTRIBUTES *attr )
296 {
297     DWORD len = attr && attr->ObjectName ? attr->ObjectName->Length : 0;
298     NTSTATUS ret;
299
300     if (len >= MAX_PATH * sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
301
302     SERVER_START_REQ( open_event )
303     {
304         req->access  = DesiredAccess;
305         req->attributes = (attr) ? attr->Attributes : 0;
306         req->rootdir = wine_server_obj_handle( attr ? attr->RootDirectory : 0 );
307         if (len) wine_server_add_data( req, attr->ObjectName->Buffer, len );
308         ret = wine_server_call( req );
309         *EventHandle = wine_server_ptr_handle( reply->handle );
310     }
311     SERVER_END_REQ;
312     return ret;
313 }
314
315
316 /******************************************************************************
317  *  NtSetEvent (NTDLL.@)
318  *  ZwSetEvent (NTDLL.@)
319  */
320 NTSTATUS WINAPI NtSetEvent( HANDLE handle, PULONG NumberOfThreadsReleased )
321 {
322     NTSTATUS ret;
323
324     /* FIXME: set NumberOfThreadsReleased */
325
326     SERVER_START_REQ( event_op )
327     {
328         req->handle = wine_server_obj_handle( handle );
329         req->op     = SET_EVENT;
330         ret = wine_server_call( req );
331     }
332     SERVER_END_REQ;
333     return ret;
334 }
335
336 /******************************************************************************
337  *  NtResetEvent (NTDLL.@)
338  */
339 NTSTATUS WINAPI NtResetEvent( HANDLE handle, PULONG NumberOfThreadsReleased )
340 {
341     NTSTATUS ret;
342
343     /* resetting an event can't release any thread... */
344     if (NumberOfThreadsReleased) *NumberOfThreadsReleased = 0;
345
346     SERVER_START_REQ( event_op )
347     {
348         req->handle = wine_server_obj_handle( handle );
349         req->op     = RESET_EVENT;
350         ret = wine_server_call( req );
351     }
352     SERVER_END_REQ;
353     return ret;
354 }
355
356 /******************************************************************************
357  *  NtClearEvent (NTDLL.@)
358  *
359  * FIXME
360  *   same as NtResetEvent ???
361  */
362 NTSTATUS WINAPI NtClearEvent ( HANDLE handle )
363 {
364     return NtResetEvent( handle, NULL );
365 }
366
367 /******************************************************************************
368  *  NtPulseEvent (NTDLL.@)
369  *
370  * FIXME
371  *   PulseCount
372  */
373 NTSTATUS WINAPI NtPulseEvent( HANDLE handle, PULONG PulseCount )
374 {
375     NTSTATUS ret;
376
377     if (PulseCount)
378       FIXME("(%p,%d)\n", handle, *PulseCount);
379
380     SERVER_START_REQ( event_op )
381     {
382         req->handle = wine_server_obj_handle( handle );
383         req->op     = PULSE_EVENT;
384         ret = wine_server_call( req );
385     }
386     SERVER_END_REQ;
387     return ret;
388 }
389
390 /******************************************************************************
391  *  NtQueryEvent (NTDLL.@)
392  */
393 NTSTATUS WINAPI NtQueryEvent (
394         IN  HANDLE EventHandle,
395         IN  EVENT_INFORMATION_CLASS EventInformationClass,
396         OUT PVOID EventInformation,
397         IN  ULONG EventInformationLength,
398         OUT PULONG  ReturnLength)
399 {
400         FIXME("(%p)\n", EventHandle);
401         return STATUS_NOT_IMPLEMENTED;
402 }
403
404 /*
405  *      Mutants (known as Mutexes in Kernel32)
406  */
407
408 /******************************************************************************
409  *              NtCreateMutant                          [NTDLL.@]
410  *              ZwCreateMutant                          [NTDLL.@]
411  */
412 NTSTATUS WINAPI NtCreateMutant(OUT HANDLE* MutantHandle,
413                                IN ACCESS_MASK access,
414                                IN const OBJECT_ATTRIBUTES* attr OPTIONAL,
415                                IN BOOLEAN InitialOwner)
416 {
417     NTSTATUS status;
418     DWORD len = attr && attr->ObjectName ? attr->ObjectName->Length : 0;
419     struct security_descriptor *sd = NULL;
420     struct object_attributes objattr;
421
422     if (len >= MAX_PATH * sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
423
424     objattr.rootdir = wine_server_obj_handle( attr ? attr->RootDirectory : 0 );
425     objattr.sd_len = 0;
426     objattr.name_len = len;
427     if (attr)
428     {
429         status = NTDLL_create_struct_sd( attr->SecurityDescriptor, &sd, &objattr.sd_len );
430         if (status != STATUS_SUCCESS) return status;
431     }
432
433     SERVER_START_REQ( create_mutex )
434     {
435         req->access  = access;
436         req->attributes = (attr) ? attr->Attributes : 0;
437         req->owned   = InitialOwner;
438         wine_server_add_data( req, &objattr, sizeof(objattr) );
439         if (objattr.sd_len) wine_server_add_data( req, sd, objattr.sd_len );
440         if (len) wine_server_add_data( req, attr->ObjectName->Buffer, len );
441         status = wine_server_call( req );
442         *MutantHandle = wine_server_ptr_handle( reply->handle );
443     }
444     SERVER_END_REQ;
445
446     NTDLL_free_struct_sd( sd );
447
448     return status;
449 }
450
451 /**************************************************************************
452  *              NtOpenMutant                            [NTDLL.@]
453  *              ZwOpenMutant                            [NTDLL.@]
454  */
455 NTSTATUS WINAPI NtOpenMutant(OUT HANDLE* MutantHandle, 
456                              IN ACCESS_MASK access, 
457                              IN const OBJECT_ATTRIBUTES* attr )
458 {
459     NTSTATUS    status;
460     DWORD       len = attr && attr->ObjectName ? attr->ObjectName->Length : 0;
461
462     if (len >= MAX_PATH * sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
463
464     SERVER_START_REQ( open_mutex )
465     {
466         req->access  = access;
467         req->attributes = (attr) ? attr->Attributes : 0;
468         req->rootdir = wine_server_obj_handle( attr ? attr->RootDirectory : 0 );
469         if (len) wine_server_add_data( req, attr->ObjectName->Buffer, len );
470         status = wine_server_call( req );
471         *MutantHandle = wine_server_ptr_handle( reply->handle );
472     }
473     SERVER_END_REQ;
474     return status;
475 }
476
477 /**************************************************************************
478  *              NtReleaseMutant                         [NTDLL.@]
479  *              ZwReleaseMutant                         [NTDLL.@]
480  */
481 NTSTATUS WINAPI NtReleaseMutant( IN HANDLE handle, OUT PLONG prev_count OPTIONAL)
482 {
483     NTSTATUS    status;
484
485     SERVER_START_REQ( release_mutex )
486     {
487         req->handle = wine_server_obj_handle( handle );
488         status = wine_server_call( req );
489         if (prev_count) *prev_count = reply->prev_count;
490     }
491     SERVER_END_REQ;
492     return status;
493 }
494
495 /******************************************************************
496  *              NtQueryMutant                   [NTDLL.@]
497  *              ZwQueryMutant                   [NTDLL.@]
498  */
499 NTSTATUS WINAPI NtQueryMutant(IN HANDLE handle, 
500                               IN MUTANT_INFORMATION_CLASS MutantInformationClass, 
501                               OUT PVOID MutantInformation, 
502                               IN ULONG MutantInformationLength, 
503                               OUT PULONG ResultLength OPTIONAL )
504 {
505     FIXME("(%p %u %p %u %p): stub!\n", 
506           handle, MutantInformationClass, MutantInformation, MutantInformationLength, ResultLength);
507     return STATUS_NOT_IMPLEMENTED;
508 }
509
510 /*
511  *      Jobs
512  */
513
514 /******************************************************************************
515  *              NtCreateJobObject   [NTDLL.@]
516  *              ZwCreateJobObject   [NTDLL.@]
517  */
518 NTSTATUS WINAPI NtCreateJobObject( PHANDLE handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr )
519 {
520     FIXME( "stub: %p %x %s\n", handle, access, attr ? debugstr_us(attr->ObjectName) : "" );
521     *handle = (HANDLE)0xdead;
522     return STATUS_SUCCESS;
523 }
524
525 /******************************************************************************
526  *              NtOpenJobObject   [NTDLL.@]
527  *              ZwOpenJobObject   [NTDLL.@]
528  */
529 NTSTATUS WINAPI NtOpenJobObject( PHANDLE handle, ACCESS_MASK access, const OBJECT_ATTRIBUTES *attr )
530 {
531     FIXME( "stub: %p %x %s\n", handle, access, attr ? debugstr_us(attr->ObjectName) : "" );
532     return STATUS_NOT_IMPLEMENTED;
533 }
534
535 /******************************************************************************
536  *              NtTerminateJobObject   [NTDLL.@]
537  *              ZwTerminateJobObject   [NTDLL.@]
538  */
539 NTSTATUS WINAPI NtTerminateJobObject( HANDLE handle, NTSTATUS status )
540 {
541     FIXME( "stub: %p %x\n", handle, status );
542     return STATUS_SUCCESS;
543 }
544
545 /******************************************************************************
546  *              NtQueryInformationJobObject   [NTDLL.@]
547  *              ZwQueryInformationJobObject   [NTDLL.@]
548  */
549 NTSTATUS WINAPI NtQueryInformationJobObject( HANDLE handle, JOBOBJECTINFOCLASS class, PVOID info,
550                                              ULONG len, PULONG ret_len )
551 {
552     FIXME( "stub: %p %u %p %u %p\n", handle, class, info, len, ret_len );
553     return STATUS_NOT_IMPLEMENTED;
554 }
555
556 /******************************************************************************
557  *              NtSetInformationJobObject   [NTDLL.@]
558  *              ZwSetInformationJobObject   [NTDLL.@]
559  */
560 NTSTATUS WINAPI NtSetInformationJobObject( HANDLE handle, JOBOBJECTINFOCLASS class, PVOID info, ULONG len )
561 {
562     FIXME( "stub: %p %u %p %u\n", handle, class, info, len );
563     return STATUS_SUCCESS;
564 }
565
566 /******************************************************************************
567  *              NtIsProcessInJob   [NTDLL.@]
568  *              ZwIsProcessInJob   [NTDLL.@]
569  */
570 NTSTATUS WINAPI NtIsProcessInJob( HANDLE process, HANDLE job )
571 {
572     FIXME( "stub: %p %p\n", process, job );
573     return STATUS_PROCESS_NOT_IN_JOB;
574 }
575
576 /******************************************************************************
577  *              NtAssignProcessToJobObject   [NTDLL.@]
578  *              ZwAssignProcessToJobObject   [NTDLL.@]
579  */
580 NTSTATUS WINAPI NtAssignProcessToJobObject( HANDLE job, HANDLE process )
581 {
582     FIXME( "stub: %p %p\n", job, process );
583     return STATUS_SUCCESS;
584 }
585
586 /*
587  *      Timers
588  */
589
590 /**************************************************************************
591  *              NtCreateTimer                           [NTDLL.@]
592  *              ZwCreateTimer                           [NTDLL.@]
593  */
594 NTSTATUS WINAPI NtCreateTimer(OUT HANDLE *handle,
595                               IN ACCESS_MASK access,
596                               IN const OBJECT_ATTRIBUTES *attr OPTIONAL,
597                               IN TIMER_TYPE timer_type)
598 {
599     DWORD       len = (attr && attr->ObjectName) ? attr->ObjectName->Length : 0;
600     NTSTATUS    status;
601
602     if (len >= MAX_PATH * sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
603
604     if (timer_type != NotificationTimer && timer_type != SynchronizationTimer)
605         return STATUS_INVALID_PARAMETER;
606
607     SERVER_START_REQ( create_timer )
608     {
609         req->access  = access;
610         req->attributes = (attr) ? attr->Attributes : 0;
611         req->rootdir = wine_server_obj_handle( attr ? attr->RootDirectory : 0 );
612         req->manual  = (timer_type == NotificationTimer) ? TRUE : FALSE;
613         if (len) wine_server_add_data( req, attr->ObjectName->Buffer, len );
614         status = wine_server_call( req );
615         *handle = wine_server_ptr_handle( reply->handle );
616     }
617     SERVER_END_REQ;
618     return status;
619
620 }
621
622 /**************************************************************************
623  *              NtOpenTimer                             [NTDLL.@]
624  *              ZwOpenTimer                             [NTDLL.@]
625  */
626 NTSTATUS WINAPI NtOpenTimer(OUT PHANDLE handle,
627                             IN ACCESS_MASK access,
628                             IN const OBJECT_ATTRIBUTES* attr )
629 {
630     DWORD       len = (attr && attr->ObjectName) ? attr->ObjectName->Length : 0;
631     NTSTATUS    status;
632
633     if (len >= MAX_PATH * sizeof(WCHAR)) return STATUS_NAME_TOO_LONG;
634
635     SERVER_START_REQ( open_timer )
636     {
637         req->access  = access;
638         req->attributes = (attr) ? attr->Attributes : 0;
639         req->rootdir = wine_server_obj_handle( attr ? attr->RootDirectory : 0 );
640         if (len) wine_server_add_data( req, attr->ObjectName->Buffer, len );
641         status = wine_server_call( req );
642         *handle = wine_server_ptr_handle( reply->handle );
643     }
644     SERVER_END_REQ;
645     return status;
646 }
647
648 /**************************************************************************
649  *              NtSetTimer                              [NTDLL.@]
650  *              ZwSetTimer                              [NTDLL.@]
651  */
652 NTSTATUS WINAPI NtSetTimer(IN HANDLE handle,
653                            IN const LARGE_INTEGER* when,
654                            IN PTIMER_APC_ROUTINE callback,
655                            IN PVOID callback_arg,
656                            IN BOOLEAN resume,
657                            IN ULONG period OPTIONAL,
658                            OUT PBOOLEAN state OPTIONAL)
659 {
660     NTSTATUS    status = STATUS_SUCCESS;
661
662     TRACE("(%p,%p,%p,%p,%08x,0x%08x,%p) stub\n",
663           handle, when, callback, callback_arg, resume, period, state);
664
665     SERVER_START_REQ( set_timer )
666     {
667         req->handle   = wine_server_obj_handle( handle );
668         req->period   = period;
669         req->expire   = when->QuadPart;
670         req->callback = wine_server_client_ptr( callback );
671         req->arg      = wine_server_client_ptr( callback_arg );
672         status = wine_server_call( req );
673         if (state) *state = reply->signaled;
674     }
675     SERVER_END_REQ;
676
677     /* set error but can still succeed */
678     if (resume && status == STATUS_SUCCESS) return STATUS_TIMER_RESUME_IGNORED;
679     return status;
680 }
681
682 /**************************************************************************
683  *              NtCancelTimer                           [NTDLL.@]
684  *              ZwCancelTimer                           [NTDLL.@]
685  */
686 NTSTATUS WINAPI NtCancelTimer(IN HANDLE handle, OUT BOOLEAN* state)
687 {
688     NTSTATUS    status;
689
690     SERVER_START_REQ( cancel_timer )
691     {
692         req->handle = wine_server_obj_handle( handle );
693         status = wine_server_call( req );
694         if (state) *state = reply->signaled;
695     }
696     SERVER_END_REQ;
697     return status;
698 }
699
700 /******************************************************************************
701  *  NtQueryTimer (NTDLL.@)
702  *
703  * Retrieves information about a timer.
704  *
705  * PARAMS
706  *  TimerHandle           [I] The timer to retrieve information about.
707  *  TimerInformationClass [I] The type of information to retrieve.
708  *  TimerInformation      [O] Pointer to buffer to store information in.
709  *  Length                [I] The length of the buffer pointed to by TimerInformation.
710  *  ReturnLength          [O] Optional. The size of buffer actually used.
711  *
712  * RETURNS
713  *  Success: STATUS_SUCCESS
714  *  Failure: STATUS_INFO_LENGTH_MISMATCH, if Length doesn't match the required data
715  *           size for the class specified.
716  *           STATUS_INVALID_INFO_CLASS, if an invalid TimerInformationClass was specified.
717  *           STATUS_ACCESS_DENIED, if TimerHandle does not have TIMER_QUERY_STATE access
718  *           to the timer.
719  */
720 NTSTATUS WINAPI NtQueryTimer(
721     HANDLE TimerHandle,
722     TIMER_INFORMATION_CLASS TimerInformationClass,
723     PVOID TimerInformation,
724     ULONG Length,
725     PULONG ReturnLength)
726 {
727     TIMER_BASIC_INFORMATION * basic_info = TimerInformation;
728     NTSTATUS status;
729     LARGE_INTEGER now;
730
731     TRACE("(%p,%d,%p,0x%08x,%p)\n", TimerHandle, TimerInformationClass,
732        TimerInformation, Length, ReturnLength);
733
734     switch (TimerInformationClass)
735     {
736     case TimerBasicInformation:
737         if (Length < sizeof(TIMER_BASIC_INFORMATION))
738             return STATUS_INFO_LENGTH_MISMATCH;
739
740         SERVER_START_REQ(get_timer_info)
741         {
742             req->handle = wine_server_obj_handle( TimerHandle );
743             status = wine_server_call(req);
744
745             /* convert server time to absolute NTDLL time */
746             basic_info->RemainingTime.QuadPart = reply->when;
747             basic_info->TimerState = reply->signaled;
748         }
749         SERVER_END_REQ;
750
751         /* convert from absolute into relative time */
752         NtQuerySystemTime(&now);
753         if (now.QuadPart > basic_info->RemainingTime.QuadPart)
754             basic_info->RemainingTime.QuadPart = 0;
755         else
756             basic_info->RemainingTime.QuadPart -= now.QuadPart;
757
758         if (ReturnLength) *ReturnLength = sizeof(TIMER_BASIC_INFORMATION);
759
760         return status;
761     }
762
763     FIXME("Unhandled class %d\n", TimerInformationClass);
764     return STATUS_INVALID_INFO_CLASS;
765 }
766
767
768 /******************************************************************************
769  * NtQueryTimerResolution [NTDLL.@]
770  */
771 NTSTATUS WINAPI NtQueryTimerResolution(OUT ULONG* min_resolution,
772                                        OUT ULONG* max_resolution,
773                                        OUT ULONG* current_resolution)
774 {
775     FIXME("(%p,%p,%p), stub!\n",
776           min_resolution, max_resolution, current_resolution);
777
778     return STATUS_NOT_IMPLEMENTED;
779 }
780
781 /******************************************************************************
782  * NtSetTimerResolution [NTDLL.@]
783  */
784 NTSTATUS WINAPI NtSetTimerResolution(IN ULONG resolution,
785                                      IN BOOLEAN set_resolution,
786                                      OUT ULONG* current_resolution )
787 {
788     FIXME("(%u,%u,%p), stub!\n",
789           resolution, set_resolution, current_resolution);
790
791     return STATUS_NOT_IMPLEMENTED;
792 }
793
794
795 /***********************************************************************
796  *              wait_reply
797  *
798  * Wait for a reply on the waiting pipe of the current thread.
799  */
800 static int wait_reply( void *cookie )
801 {
802     int signaled;
803     struct wake_up_reply reply;
804     for (;;)
805     {
806         int ret;
807         ret = read( ntdll_get_thread_data()->wait_fd[0], &reply, sizeof(reply) );
808         if (ret == sizeof(reply))
809         {
810             if (!reply.cookie) abort_thread( reply.signaled );  /* thread got killed */
811             if (wine_server_get_ptr(reply.cookie) == cookie) return reply.signaled;
812             /* we stole another reply, wait for the real one */
813             signaled = wait_reply( cookie );
814             /* and now put the wrong one back in the pipe */
815             for (;;)
816             {
817                 ret = write( ntdll_get_thread_data()->wait_fd[1], &reply, sizeof(reply) );
818                 if (ret == sizeof(reply)) break;
819                 if (ret >= 0) server_protocol_error( "partial wakeup write %d\n", ret );
820                 if (errno == EINTR) continue;
821                 server_protocol_perror("wakeup write");
822             }
823             return signaled;
824         }
825         if (ret >= 0) server_protocol_error( "partial wakeup read %d\n", ret );
826         if (errno == EINTR) continue;
827         server_protocol_perror("wakeup read");
828     }
829 }
830
831
832 /***********************************************************************
833  *              invoke_apc
834  *
835  * Invoke a single APC. Return TRUE if a user APC has been run.
836  */
837 static BOOL invoke_apc( const apc_call_t *call, apc_result_t *result )
838 {
839     BOOL user_apc = FALSE;
840     SIZE_T size;
841     void *addr;
842
843     memset( result, 0, sizeof(*result) );
844
845     switch (call->type)
846     {
847     case APC_NONE:
848         break;
849     case APC_USER:
850     {
851         void (WINAPI *func)(ULONG_PTR,ULONG_PTR,ULONG_PTR) = wine_server_get_ptr( call->user.func );
852         func( call->user.args[0], call->user.args[1], call->user.args[2] );
853         user_apc = TRUE;
854         break;
855     }
856     case APC_TIMER:
857     {
858         void (WINAPI *func)(void*, unsigned int, unsigned int) = wine_server_get_ptr( call->timer.func );
859         func( wine_server_get_ptr( call->timer.arg ),
860               (DWORD)call->timer.time, (DWORD)(call->timer.time >> 32) );
861         user_apc = TRUE;
862         break;
863     }
864     case APC_ASYNC_IO:
865     {
866         void *apc = NULL;
867         IO_STATUS_BLOCK *iosb = wine_server_get_ptr( call->async_io.sb );
868         NTSTATUS (*func)(void *, IO_STATUS_BLOCK *, NTSTATUS, void **) = wine_server_get_ptr( call->async_io.func );
869         result->type = call->type;
870         result->async_io.status = func( wine_server_get_ptr( call->async_io.user ),
871                                         iosb, call->async_io.status, &apc );
872         if (result->async_io.status != STATUS_PENDING)
873         {
874             result->async_io.total = iosb->Information;
875             result->async_io.apc   = wine_server_client_ptr( apc );
876         }
877         break;
878     }
879     case APC_VIRTUAL_ALLOC:
880         result->type = call->type;
881         addr = wine_server_get_ptr( call->virtual_alloc.addr );
882         size = call->virtual_alloc.size;
883         if ((ULONG_PTR)addr == call->virtual_alloc.addr && size == call->virtual_alloc.size)
884         {
885             result->virtual_alloc.status = NtAllocateVirtualMemory( NtCurrentProcess(), &addr,
886                                                                     call->virtual_alloc.zero_bits, &size,
887                                                                     call->virtual_alloc.op_type,
888                                                                     call->virtual_alloc.prot );
889             result->virtual_alloc.addr = wine_server_client_ptr( addr );
890             result->virtual_alloc.size = size;
891         }
892         else result->virtual_alloc.status = STATUS_WORKING_SET_LIMIT_RANGE;
893         break;
894     case APC_VIRTUAL_FREE:
895         result->type = call->type;
896         addr = wine_server_get_ptr( call->virtual_free.addr );
897         size = call->virtual_free.size;
898         if ((ULONG_PTR)addr == call->virtual_free.addr && size == call->virtual_free.size)
899         {
900             result->virtual_free.status = NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size,
901                                                                call->virtual_free.op_type );
902             result->virtual_free.addr = wine_server_client_ptr( addr );
903             result->virtual_free.size = size;
904         }
905         else result->virtual_free.status = STATUS_INVALID_PARAMETER;
906         break;
907     case APC_VIRTUAL_QUERY:
908     {
909         MEMORY_BASIC_INFORMATION info;
910         result->type = call->type;
911         addr = wine_server_get_ptr( call->virtual_query.addr );
912         if ((ULONG_PTR)addr == call->virtual_query.addr)
913             result->virtual_query.status = NtQueryVirtualMemory( NtCurrentProcess(),
914                                                                  addr, MemoryBasicInformation, &info,
915                                                                  sizeof(info), NULL );
916         else
917             result->virtual_query.status = STATUS_WORKING_SET_LIMIT_RANGE;
918
919         if (result->virtual_query.status == STATUS_SUCCESS)
920         {
921             result->virtual_query.base       = wine_server_client_ptr( info.BaseAddress );
922             result->virtual_query.alloc_base = wine_server_client_ptr( info.AllocationBase );
923             result->virtual_query.size       = info.RegionSize;
924             result->virtual_query.prot       = info.Protect;
925             result->virtual_query.alloc_prot = info.AllocationProtect;
926             result->virtual_query.state      = info.State >> 12;
927             result->virtual_query.alloc_type = info.Type >> 16;
928         }
929         break;
930     }
931     case APC_VIRTUAL_PROTECT:
932         result->type = call->type;
933         addr = wine_server_get_ptr( call->virtual_protect.addr );
934         size = call->virtual_protect.size;
935         if ((ULONG_PTR)addr == call->virtual_protect.addr && size == call->virtual_protect.size)
936         {
937             result->virtual_protect.status = NtProtectVirtualMemory( NtCurrentProcess(), &addr, &size,
938                                                                      call->virtual_protect.prot,
939                                                                      &result->virtual_protect.prot );
940             result->virtual_protect.addr = wine_server_client_ptr( addr );
941             result->virtual_protect.size = size;
942         }
943         else result->virtual_protect.status = STATUS_INVALID_PARAMETER;
944         break;
945     case APC_VIRTUAL_FLUSH:
946         result->type = call->type;
947         addr = wine_server_get_ptr( call->virtual_flush.addr );
948         size = call->virtual_flush.size;
949         if ((ULONG_PTR)addr == call->virtual_flush.addr && size == call->virtual_flush.size)
950         {
951             result->virtual_flush.status = NtFlushVirtualMemory( NtCurrentProcess(),
952                                                                  (const void **)&addr, &size, 0 );
953             result->virtual_flush.addr = wine_server_client_ptr( addr );
954             result->virtual_flush.size = size;
955         }
956         else result->virtual_flush.status = STATUS_INVALID_PARAMETER;
957         break;
958     case APC_VIRTUAL_LOCK:
959         result->type = call->type;
960         addr = wine_server_get_ptr( call->virtual_lock.addr );
961         size = call->virtual_lock.size;
962         if ((ULONG_PTR)addr == call->virtual_lock.addr && size == call->virtual_lock.size)
963         {
964             result->virtual_lock.status = NtLockVirtualMemory( NtCurrentProcess(), &addr, &size, 0 );
965             result->virtual_lock.addr = wine_server_client_ptr( addr );
966             result->virtual_lock.size = size;
967         }
968         else result->virtual_lock.status = STATUS_INVALID_PARAMETER;
969         break;
970     case APC_VIRTUAL_UNLOCK:
971         result->type = call->type;
972         addr = wine_server_get_ptr( call->virtual_unlock.addr );
973         size = call->virtual_unlock.size;
974         if ((ULONG_PTR)addr == call->virtual_unlock.addr && size == call->virtual_unlock.size)
975         {
976             result->virtual_unlock.status = NtUnlockVirtualMemory( NtCurrentProcess(), &addr, &size, 0 );
977             result->virtual_unlock.addr = wine_server_client_ptr( addr );
978             result->virtual_unlock.size = size;
979         }
980         else result->virtual_unlock.status = STATUS_INVALID_PARAMETER;
981         break;
982     case APC_MAP_VIEW:
983         result->type = call->type;
984         addr = wine_server_get_ptr( call->map_view.addr );
985         size = call->map_view.size;
986         if ((ULONG_PTR)addr == call->map_view.addr && size == call->map_view.size)
987         {
988             LARGE_INTEGER offset;
989             offset.QuadPart = call->map_view.offset;
990             result->map_view.status = NtMapViewOfSection( wine_server_ptr_handle(call->map_view.handle),
991                                                           NtCurrentProcess(), &addr,
992                                                           call->map_view.zero_bits, 0,
993                                                           &offset, &size, ViewShare,
994                                                           call->map_view.alloc_type, call->map_view.prot );
995             result->map_view.addr = wine_server_client_ptr( addr );
996             result->map_view.size = size;
997         }
998         else result->map_view.status = STATUS_INVALID_PARAMETER;
999         NtClose( wine_server_ptr_handle(call->map_view.handle) );
1000         break;
1001     case APC_UNMAP_VIEW:
1002         result->type = call->type;
1003         addr = wine_server_get_ptr( call->unmap_view.addr );
1004         if ((ULONG_PTR)addr == call->unmap_view.addr)
1005             result->unmap_view.status = NtUnmapViewOfSection( NtCurrentProcess(), addr );
1006         else
1007             result->unmap_view.status = STATUS_INVALID_PARAMETER;
1008         break;
1009     case APC_CREATE_THREAD:
1010     {
1011         CLIENT_ID id;
1012         HANDLE handle;
1013         SIZE_T reserve = call->create_thread.reserve;
1014         SIZE_T commit = call->create_thread.commit;
1015         void *func = wine_server_get_ptr( call->create_thread.func );
1016         void *arg  = wine_server_get_ptr( call->create_thread.arg );
1017
1018         result->type = call->type;
1019         if (reserve == call->create_thread.reserve && commit == call->create_thread.commit &&
1020             (ULONG_PTR)func == call->create_thread.func && (ULONG_PTR)arg == call->create_thread.arg)
1021         {
1022             result->create_thread.status = RtlCreateUserThread( NtCurrentProcess(), NULL,
1023                                                                 call->create_thread.suspend, NULL,
1024                                                                 reserve, commit, func, arg, &handle, &id );
1025             result->create_thread.handle = wine_server_obj_handle( handle );
1026             result->create_thread.tid = HandleToULong(id.UniqueThread);
1027         }
1028         else result->create_thread.status = STATUS_INVALID_PARAMETER;
1029         break;
1030     }
1031     default:
1032         server_protocol_error( "get_apc_request: bad type %d\n", call->type );
1033         break;
1034     }
1035     return user_apc;
1036 }
1037
1038 /***********************************************************************
1039  *           NTDLL_queue_process_apc
1040  */
1041 NTSTATUS NTDLL_queue_process_apc( HANDLE process, const apc_call_t *call, apc_result_t *result )
1042 {
1043     for (;;)
1044     {
1045         NTSTATUS ret;
1046         HANDLE handle = 0;
1047         BOOL self = FALSE;
1048
1049         SERVER_START_REQ( queue_apc )
1050         {
1051             req->handle = wine_server_obj_handle( process );
1052             req->call = *call;
1053             if (!(ret = wine_server_call( req )))
1054             {
1055                 handle = wine_server_ptr_handle( reply->handle );
1056                 self = reply->self;
1057             }
1058         }
1059         SERVER_END_REQ;
1060         if (ret != STATUS_SUCCESS) return ret;
1061
1062         if (self)
1063         {
1064             invoke_apc( call, result );
1065         }
1066         else
1067         {
1068             NtWaitForSingleObject( handle, FALSE, NULL );
1069
1070             SERVER_START_REQ( get_apc_result )
1071             {
1072                 req->handle = wine_server_obj_handle( handle );
1073                 if (!(ret = wine_server_call( req ))) *result = reply->result;
1074             }
1075             SERVER_END_REQ;
1076
1077             if (!ret && result->type == APC_NONE) continue;  /* APC didn't run, try again */
1078             if (ret) NtClose( handle );
1079         }
1080         return ret;
1081     }
1082 }
1083
1084
1085 /***********************************************************************
1086  *              NTDLL_wait_for_multiple_objects
1087  *
1088  * Implementation of NtWaitForMultipleObjects
1089  */
1090 NTSTATUS NTDLL_wait_for_multiple_objects( UINT count, const HANDLE *handles, UINT flags,
1091                                           const LARGE_INTEGER *timeout, HANDLE signal_object )
1092 {
1093     NTSTATUS ret;
1094     int i, cookie;
1095     BOOL user_apc = FALSE;
1096     obj_handle_t obj_handles[MAXIMUM_WAIT_OBJECTS];
1097     obj_handle_t apc_handle = 0;
1098     apc_call_t call;
1099     apc_result_t result;
1100     timeout_t abs_timeout = timeout ? timeout->QuadPart : TIMEOUT_INFINITE;
1101
1102     memset( &result, 0, sizeof(result) );
1103     for (i = 0; i < count; i++) obj_handles[i] = wine_server_obj_handle( handles[i] );
1104
1105     for (;;)
1106     {
1107         SERVER_START_REQ( select )
1108         {
1109             req->flags    = flags;
1110             req->cookie   = wine_server_client_ptr( &cookie );
1111             req->signal   = wine_server_obj_handle( signal_object );
1112             req->prev_apc = apc_handle;
1113             req->timeout  = abs_timeout;
1114             wine_server_add_data( req, &result, sizeof(result) );
1115             wine_server_add_data( req, obj_handles, count * sizeof(*obj_handles) );
1116             ret = wine_server_call( req );
1117             abs_timeout = reply->timeout;
1118             apc_handle  = reply->apc_handle;
1119             call        = reply->call;
1120         }
1121         SERVER_END_REQ;
1122         if (ret == STATUS_PENDING) ret = wait_reply( &cookie );
1123         if (ret != STATUS_USER_APC) break;
1124         if (invoke_apc( &call, &result ))
1125         {
1126             /* if we ran a user apc we have to check once more if an object got signaled,
1127              * but we don't want to wait */
1128             abs_timeout = 0;
1129             user_apc = TRUE;
1130         }
1131         signal_object = 0;  /* don't signal it multiple times */
1132     }
1133
1134     if (ret == STATUS_TIMEOUT && user_apc) ret = STATUS_USER_APC;
1135
1136     /* A test on Windows 2000 shows that Windows always yields during
1137        a wait, but a wait that is hit by an event gets a priority
1138        boost as well.  This seems to model that behavior the closest.  */
1139     if (ret == STATUS_TIMEOUT) NtYieldExecution();
1140
1141     return ret;
1142 }
1143
1144
1145 /* wait operations */
1146
1147 /******************************************************************
1148  *              NtWaitForMultipleObjects (NTDLL.@)
1149  */
1150 NTSTATUS WINAPI NtWaitForMultipleObjects( DWORD count, const HANDLE *handles,
1151                                           BOOLEAN wait_all, BOOLEAN alertable,
1152                                           const LARGE_INTEGER *timeout )
1153 {
1154     UINT flags = SELECT_INTERRUPTIBLE;
1155
1156     if (!count || count > MAXIMUM_WAIT_OBJECTS) return STATUS_INVALID_PARAMETER_1;
1157
1158     if (wait_all) flags |= SELECT_ALL;
1159     if (alertable) flags |= SELECT_ALERTABLE;
1160     return NTDLL_wait_for_multiple_objects( count, handles, flags, timeout, 0 );
1161 }
1162
1163
1164 /******************************************************************
1165  *              NtWaitForSingleObject (NTDLL.@)
1166  */
1167 NTSTATUS WINAPI NtWaitForSingleObject(HANDLE handle, BOOLEAN alertable, const LARGE_INTEGER *timeout )
1168 {
1169     return NtWaitForMultipleObjects( 1, &handle, FALSE, alertable, timeout );
1170 }
1171
1172
1173 /******************************************************************
1174  *              NtSignalAndWaitForSingleObject (NTDLL.@)
1175  */
1176 NTSTATUS WINAPI NtSignalAndWaitForSingleObject( HANDLE hSignalObject, HANDLE hWaitObject,
1177                                                 BOOLEAN alertable, const LARGE_INTEGER *timeout )
1178 {
1179     UINT flags = SELECT_INTERRUPTIBLE;
1180
1181     if (!hSignalObject) return STATUS_INVALID_HANDLE;
1182     if (alertable) flags |= SELECT_ALERTABLE;
1183     return NTDLL_wait_for_multiple_objects( 1, &hWaitObject, flags, timeout, hSignalObject );
1184 }
1185
1186
1187 /******************************************************************
1188  *              NtYieldExecution (NTDLL.@)
1189  */
1190 NTSTATUS WINAPI NtYieldExecution(void)
1191 {
1192 #ifdef HAVE_SCHED_YIELD
1193     sched_yield();
1194     return STATUS_SUCCESS;
1195 #else
1196     return STATUS_NO_YIELD_PERFORMED;
1197 #endif
1198 }
1199
1200
1201 /******************************************************************
1202  *              NtDelayExecution (NTDLL.@)
1203  */
1204 NTSTATUS WINAPI NtDelayExecution( BOOLEAN alertable, const LARGE_INTEGER *timeout )
1205 {
1206     /* if alertable, we need to query the server */
1207     if (alertable)
1208         return NTDLL_wait_for_multiple_objects( 0, NULL, SELECT_INTERRUPTIBLE | SELECT_ALERTABLE,
1209                                                 timeout, 0 );
1210
1211     if (!timeout || timeout->QuadPart == TIMEOUT_INFINITE)  /* sleep forever */
1212     {
1213         for (;;) select( 0, NULL, NULL, NULL, NULL );
1214     }
1215     else
1216     {
1217         LARGE_INTEGER now;
1218         timeout_t when, diff;
1219
1220         if ((when = timeout->QuadPart) < 0)
1221         {
1222             NtQuerySystemTime( &now );
1223             when = now.QuadPart - when;
1224         }
1225
1226         /* Note that we yield after establishing the desired timeout */
1227         NtYieldExecution();
1228         if (!when) return STATUS_SUCCESS;
1229
1230         for (;;)
1231         {
1232             struct timeval tv;
1233             NtQuerySystemTime( &now );
1234             diff = (when - now.QuadPart + 9) / 10;
1235             if (diff <= 0) break;
1236             tv.tv_sec  = diff / 1000000;
1237             tv.tv_usec = diff % 1000000;
1238             if (select( 0, NULL, NULL, NULL, &tv ) != -1) break;
1239         }
1240     }
1241     return STATUS_SUCCESS;
1242 }
1243
1244 /******************************************************************
1245  *              NtCreateIoCompletion (NTDLL.@)
1246  *              ZwCreateIoCompletion (NTDLL.@)
1247  *
1248  * Creates I/O completion object.
1249  *
1250  * PARAMS
1251  *      CompletionPort            [O] created completion object handle will be placed there
1252  *      DesiredAccess             [I] desired access to a handle (combination of IO_COMPLETION_*)
1253  *      ObjectAttributes          [I] completion object attributes
1254  *      NumberOfConcurrentThreads [I] desired number of concurrent active worker threads
1255  *
1256  */
1257 NTSTATUS WINAPI NtCreateIoCompletion( PHANDLE CompletionPort, ACCESS_MASK DesiredAccess,
1258                                       POBJECT_ATTRIBUTES ObjectAttributes, ULONG NumberOfConcurrentThreads )
1259 {
1260     NTSTATUS status;
1261
1262     TRACE("(%p, %x, %p, %d)\n", CompletionPort, DesiredAccess,
1263           ObjectAttributes, NumberOfConcurrentThreads);
1264
1265     if (!CompletionPort)
1266         return STATUS_INVALID_PARAMETER;
1267
1268     SERVER_START_REQ( create_completion )
1269     {
1270         req->access     = DesiredAccess;
1271         req->attributes = ObjectAttributes ? ObjectAttributes->Attributes : 0;
1272         req->rootdir    = wine_server_obj_handle( ObjectAttributes ? ObjectAttributes->RootDirectory : 0 );
1273         req->concurrent = NumberOfConcurrentThreads;
1274         if (ObjectAttributes && ObjectAttributes->ObjectName)
1275             wine_server_add_data( req, ObjectAttributes->ObjectName->Buffer,
1276                                        ObjectAttributes->ObjectName->Length );
1277         if (!(status = wine_server_call( req )))
1278             *CompletionPort = wine_server_ptr_handle( reply->handle );
1279     }
1280     SERVER_END_REQ;
1281     return status;
1282 }
1283
1284 /******************************************************************
1285  *              NtSetIoCompletion (NTDLL.@)
1286  *              ZwSetIoCompletion (NTDLL.@)
1287  *
1288  * Inserts completion message into queue
1289  *
1290  * PARAMS
1291  *      CompletionPort           [I] HANDLE to completion object
1292  *      CompletionKey            [I] completion key
1293  *      CompletionValue          [I] completion value (usually pointer to OVERLAPPED)
1294  *      Status                   [I] operation status
1295  *      NumberOfBytesTransferred [I] number of bytes transferred
1296  */
1297 NTSTATUS WINAPI NtSetIoCompletion( HANDLE CompletionPort, ULONG_PTR CompletionKey,
1298                                    ULONG_PTR CompletionValue, NTSTATUS Status,
1299                                    ULONG NumberOfBytesTransferred )
1300 {
1301     NTSTATUS status;
1302
1303     TRACE("(%p, %lx, %lx, %x, %d)\n", CompletionPort, CompletionKey,
1304           CompletionValue, Status, NumberOfBytesTransferred);
1305
1306     SERVER_START_REQ( add_completion )
1307     {
1308         req->handle      = wine_server_obj_handle( CompletionPort );
1309         req->ckey        = CompletionKey;
1310         req->cvalue      = CompletionValue;
1311         req->status      = Status;
1312         req->information = NumberOfBytesTransferred;
1313         status = wine_server_call( req );
1314     }
1315     SERVER_END_REQ;
1316     return status;
1317 }
1318
1319 /******************************************************************
1320  *              NtRemoveIoCompletion (NTDLL.@)
1321  *              ZwRemoveIoCompletion (NTDLL.@)
1322  *
1323  * (Wait for and) retrieve first completion message from completion object's queue
1324  *
1325  * PARAMS
1326  *      CompletionPort  [I] HANDLE to I/O completion object
1327  *      CompletionKey   [O] completion key
1328  *      CompletionValue [O] Completion value given in NtSetIoCompletion or in async operation
1329  *      iosb            [O] IO_STATUS_BLOCK of completed asynchronous operation
1330  *      WaitTime        [I] optional wait time in NTDLL format
1331  *
1332  */
1333 NTSTATUS WINAPI NtRemoveIoCompletion( HANDLE CompletionPort, PULONG_PTR CompletionKey,
1334                                       PULONG_PTR CompletionValue, PIO_STATUS_BLOCK iosb,
1335                                       PLARGE_INTEGER WaitTime )
1336 {
1337     NTSTATUS status;
1338
1339     TRACE("(%p, %p, %p, %p, %p)\n", CompletionPort, CompletionKey,
1340           CompletionValue, iosb, WaitTime);
1341
1342     for(;;)
1343     {
1344         SERVER_START_REQ( remove_completion )
1345         {
1346             req->handle = wine_server_obj_handle( CompletionPort );
1347             if (!(status = wine_server_call( req )))
1348             {
1349                 *CompletionKey    = reply->ckey;
1350                 *CompletionValue  = reply->cvalue;
1351                 iosb->Information = reply->information;
1352                 iosb->u.Status    = reply->status;
1353             }
1354         }
1355         SERVER_END_REQ;
1356         if (status != STATUS_PENDING) break;
1357
1358         status = NtWaitForSingleObject( CompletionPort, FALSE, WaitTime );
1359         if (status != WAIT_OBJECT_0) break;
1360     }
1361     return status;
1362 }
1363
1364 /******************************************************************
1365  *              NtOpenIoCompletion (NTDLL.@)
1366  *              ZwOpenIoCompletion (NTDLL.@)
1367  *
1368  * Opens I/O completion object
1369  *
1370  * PARAMS
1371  *      CompletionPort     [O] completion object handle will be placed there
1372  *      DesiredAccess      [I] desired access to a handle (combination of IO_COMPLETION_*)
1373  *      ObjectAttributes   [I] completion object name
1374  *
1375  */
1376 NTSTATUS WINAPI NtOpenIoCompletion( PHANDLE CompletionPort, ACCESS_MASK DesiredAccess,
1377                                     POBJECT_ATTRIBUTES ObjectAttributes )
1378 {
1379     NTSTATUS status;
1380
1381     TRACE("(%p, 0x%x, %p)\n", CompletionPort, DesiredAccess, ObjectAttributes);
1382
1383     if (!CompletionPort || !ObjectAttributes || !ObjectAttributes->ObjectName)
1384         return STATUS_INVALID_PARAMETER;
1385
1386     SERVER_START_REQ( open_completion )
1387     {
1388         req->access     = DesiredAccess;
1389         req->rootdir    = wine_server_obj_handle( ObjectAttributes->RootDirectory );
1390         wine_server_add_data( req, ObjectAttributes->ObjectName->Buffer,
1391                                    ObjectAttributes->ObjectName->Length );
1392         if (!(status = wine_server_call( req )))
1393             *CompletionPort = wine_server_ptr_handle( reply->handle );
1394     }
1395     SERVER_END_REQ;
1396     return status;
1397 }
1398
1399 /******************************************************************
1400  *              NtQueryIoCompletion (NTDLL.@)
1401  *              ZwQueryIoCompletion (NTDLL.@)
1402  *
1403  * Requests information about given I/O completion object
1404  *
1405  * PARAMS
1406  *      CompletionPort        [I] HANDLE to completion port to request
1407  *      InformationClass      [I] information class
1408  *      CompletionInformation [O] user-provided buffer for data
1409  *      BufferLength          [I] buffer length
1410  *      RequiredLength        [O] required buffer length
1411  *
1412  */
1413 NTSTATUS WINAPI NtQueryIoCompletion( HANDLE CompletionPort, IO_COMPLETION_INFORMATION_CLASS InformationClass,
1414                                      PVOID CompletionInformation, ULONG BufferLength, PULONG RequiredLength )
1415 {
1416     NTSTATUS status;
1417
1418     TRACE("(%p, %d, %p, 0x%x, %p)\n", CompletionPort, InformationClass, CompletionInformation,
1419           BufferLength, RequiredLength);
1420
1421     if (!CompletionInformation) return STATUS_INVALID_PARAMETER;
1422     switch( InformationClass )
1423     {
1424         case IoCompletionBasicInformation:
1425             {
1426                 ULONG *info = CompletionInformation;
1427
1428                 if (RequiredLength) *RequiredLength = sizeof(*info);
1429                 if (BufferLength != sizeof(*info))
1430                     status = STATUS_INFO_LENGTH_MISMATCH;
1431                 else
1432                 {
1433                     SERVER_START_REQ( query_completion )
1434                     {
1435                         req->handle = wine_server_obj_handle( CompletionPort );
1436                         if (!(status = wine_server_call( req )))
1437                             *info = reply->depth;
1438                     }
1439                     SERVER_END_REQ;
1440                 }
1441             }
1442             break;
1443         default:
1444             status = STATUS_INVALID_PARAMETER;
1445             break;
1446     }
1447     return status;
1448 }
1449
1450 NTSTATUS NTDLL_AddCompletion( HANDLE hFile, ULONG_PTR CompletionValue,
1451                               NTSTATUS CompletionStatus, ULONG Information )
1452 {
1453     NTSTATUS status;
1454
1455     SERVER_START_REQ( add_fd_completion )
1456     {
1457         req->handle      = wine_server_obj_handle( hFile );
1458         req->cvalue      = CompletionValue;
1459         req->status      = CompletionStatus;
1460         req->information = Information;
1461         status = wine_server_call( req );
1462     }
1463     SERVER_END_REQ;
1464     return status;
1465 }
1466
1467 VOID NTAPI RtlRunOnceInitialize(PRTL_RUN_ONCE initonce)
1468 {
1469     initonce->Ptr = NULL;
1470 }