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