jscript: Add the Romanian translation.
[wine] / server / thread.c
1 /*
2  * Server-side thread management
3  *
4  * Copyright (C) 1998 Alexandre Julliard
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21 #include "config.h"
22 #include "wine/port.h"
23
24 #include <assert.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <signal.h>
28 #include <stdarg.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <sys/types.h>
33 #include <unistd.h>
34 #include <time.h>
35 #ifdef HAVE_POLL_H
36 #include <poll.h>
37 #endif
38 #ifdef HAVE_SCHED_H
39 #include <sched.h>
40 #endif
41
42 #include "ntstatus.h"
43 #define WIN32_NO_STATUS
44 #include "windef.h"
45 #include "winternl.h"
46
47 #include "file.h"
48 #include "handle.h"
49 #include "process.h"
50 #include "thread.h"
51 #include "request.h"
52 #include "user.h"
53 #include "security.h"
54
55
56 #ifdef __i386__
57 static const unsigned int supported_cpus = CPU_FLAG(CPU_x86);
58 #elif defined(__x86_64__)
59 static const unsigned int supported_cpus = CPU_FLAG(CPU_x86_64) | CPU_FLAG(CPU_x86);
60 #elif defined(__ALPHA__)
61 static const unsigned int supported_cpus = CPU_FLAG(CPU_ALPHA);
62 #elif defined(__powerpc__)
63 static const unsigned int supported_cpus = CPU_FLAG(CPU_POWERPC);
64 #elif defined(__sparc__)
65 static const unsigned int supported_cpus = CPU_FLAG(CPU_SPARC);
66 #else
67 #error Unsupported CPU
68 #endif
69
70 /* thread queues */
71
72 struct thread_wait
73 {
74     struct thread_wait     *next;       /* next wait structure for this thread */
75     struct thread          *thread;     /* owner thread */
76     int                     count;      /* count of objects */
77     int                     flags;
78     client_ptr_t            cookie;     /* magic cookie to return to client */
79     timeout_t               timeout;
80     struct timeout_user    *user;
81     struct wait_queue_entry queues[1];
82 };
83
84 /* asynchronous procedure calls */
85
86 struct thread_apc
87 {
88     struct object       obj;      /* object header */
89     struct list         entry;    /* queue linked list */
90     struct thread      *caller;   /* thread that queued this apc */
91     struct object      *owner;    /* object that queued this apc */
92     int                 executed; /* has it been executed by the client? */
93     apc_call_t          call;     /* call arguments */
94     apc_result_t        result;   /* call results once executed */
95 };
96
97 static void dump_thread_apc( struct object *obj, int verbose );
98 static int thread_apc_signaled( struct object *obj, struct thread *thread );
99 static void thread_apc_destroy( struct object *obj );
100 static void clear_apc_queue( struct list *queue );
101
102 static const struct object_ops thread_apc_ops =
103 {
104     sizeof(struct thread_apc),  /* size */
105     dump_thread_apc,            /* dump */
106     no_get_type,                /* get_type */
107     add_queue,                  /* add_queue */
108     remove_queue,               /* remove_queue */
109     thread_apc_signaled,        /* signaled */
110     no_satisfied,               /* satisfied */
111     no_signal,                  /* signal */
112     no_get_fd,                  /* get_fd */
113     no_map_access,              /* map_access */
114     default_get_sd,             /* get_sd */
115     default_set_sd,             /* set_sd */
116     no_lookup_name,             /* lookup_name */
117     no_open_file,               /* open_file */
118     no_close_handle,            /* close_handle */
119     thread_apc_destroy          /* destroy */
120 };
121
122
123 /* thread operations */
124
125 static void dump_thread( struct object *obj, int verbose );
126 static int thread_signaled( struct object *obj, struct thread *thread );
127 static unsigned int thread_map_access( struct object *obj, unsigned int access );
128 static void thread_poll_event( struct fd *fd, int event );
129 static void destroy_thread( struct object *obj );
130
131 static const struct object_ops thread_ops =
132 {
133     sizeof(struct thread),      /* size */
134     dump_thread,                /* dump */
135     no_get_type,                /* get_type */
136     add_queue,                  /* add_queue */
137     remove_queue,               /* remove_queue */
138     thread_signaled,            /* signaled */
139     no_satisfied,               /* satisfied */
140     no_signal,                  /* signal */
141     no_get_fd,                  /* get_fd */
142     thread_map_access,          /* map_access */
143     default_get_sd,             /* get_sd */
144     default_set_sd,             /* set_sd */
145     no_lookup_name,             /* lookup_name */
146     no_open_file,               /* open_file */
147     no_close_handle,            /* close_handle */
148     destroy_thread              /* destroy */
149 };
150
151 static const struct fd_ops thread_fd_ops =
152 {
153     NULL,                       /* get_poll_events */
154     thread_poll_event,          /* poll_event */
155     NULL,                       /* flush */
156     NULL,                       /* get_fd_type */
157     NULL,                       /* ioctl */
158     NULL,                       /* queue_async */
159     NULL,                       /* reselect_async */
160     NULL                        /* cancel_async */
161 };
162
163 static struct list thread_list = LIST_INIT(thread_list);
164
165 /* initialize the structure for a newly allocated thread */
166 static inline void init_thread_structure( struct thread *thread )
167 {
168     int i;
169
170     thread->unix_pid        = -1;  /* not known yet */
171     thread->unix_tid        = -1;  /* not known yet */
172     thread->context         = NULL;
173     thread->suspend_context = NULL;
174     thread->teb             = 0;
175     thread->debug_ctx       = NULL;
176     thread->debug_event     = NULL;
177     thread->debug_break     = 0;
178     thread->queue           = NULL;
179     thread->wait            = NULL;
180     thread->error           = 0;
181     thread->req_data        = NULL;
182     thread->req_toread      = 0;
183     thread->reply_data      = NULL;
184     thread->reply_towrite   = 0;
185     thread->request_fd      = NULL;
186     thread->reply_fd        = NULL;
187     thread->wait_fd         = NULL;
188     thread->state           = RUNNING;
189     thread->exit_code       = 0;
190     thread->priority        = 0;
191     thread->affinity        = ~0;
192     thread->suspend         = 0;
193     thread->desktop_users   = 0;
194     thread->token           = NULL;
195
196     thread->creation_time = current_time;
197     thread->exit_time     = 0;
198
199     list_init( &thread->mutex_list );
200     list_init( &thread->system_apc );
201     list_init( &thread->user_apc );
202
203     for (i = 0; i < MAX_INFLIGHT_FDS; i++)
204         thread->inflight[i].server = thread->inflight[i].client = -1;
205 }
206
207 /* check if address looks valid for a client-side data structure (TEB etc.) */
208 static inline int is_valid_address( client_ptr_t addr )
209 {
210     return addr && !(addr % sizeof(int));
211 }
212
213 /* create a new thread */
214 struct thread *create_thread( int fd, struct process *process )
215 {
216     struct thread *thread;
217
218     if (!(thread = alloc_object( &thread_ops ))) return NULL;
219
220     init_thread_structure( thread );
221
222     thread->process = (struct process *)grab_object( process );
223     thread->desktop = process->desktop;
224     thread->affinity = process->affinity;
225     if (!current) current = thread;
226
227     list_add_head( &thread_list, &thread->entry );
228
229     if (!(thread->id = alloc_ptid( thread )))
230     {
231         release_object( thread );
232         return NULL;
233     }
234     if (!(thread->request_fd = create_anonymous_fd( &thread_fd_ops, fd, &thread->obj, 0 )))
235     {
236         release_object( thread );
237         return NULL;
238     }
239
240     set_fd_events( thread->request_fd, POLLIN );  /* start listening to events */
241     add_process_thread( thread->process, thread );
242     return thread;
243 }
244
245 /* handle a client event */
246 static void thread_poll_event( struct fd *fd, int event )
247 {
248     struct thread *thread = get_fd_user( fd );
249     assert( thread->obj.ops == &thread_ops );
250
251     grab_object( thread );
252     if (event & (POLLERR | POLLHUP)) kill_thread( thread, 0 );
253     else if (event & POLLIN) read_request( thread );
254     else if (event & POLLOUT) write_reply( thread );
255     release_object( thread );
256 }
257
258 /* cleanup everything that is no longer needed by a dead thread */
259 /* used by destroy_thread and kill_thread */
260 static void cleanup_thread( struct thread *thread )
261 {
262     int i;
263
264     clear_apc_queue( &thread->system_apc );
265     clear_apc_queue( &thread->user_apc );
266     free( thread->req_data );
267     free( thread->reply_data );
268     if (thread->request_fd) release_object( thread->request_fd );
269     if (thread->reply_fd) release_object( thread->reply_fd );
270     if (thread->wait_fd) release_object( thread->wait_fd );
271     free( thread->suspend_context );
272     cleanup_clipboard_thread(thread);
273     destroy_thread_windows( thread );
274     free_msg_queue( thread );
275     close_thread_desktop( thread );
276     for (i = 0; i < MAX_INFLIGHT_FDS; i++)
277     {
278         if (thread->inflight[i].client != -1)
279         {
280             close( thread->inflight[i].server );
281             thread->inflight[i].client = thread->inflight[i].server = -1;
282         }
283     }
284     thread->req_data = NULL;
285     thread->reply_data = NULL;
286     thread->request_fd = NULL;
287     thread->reply_fd = NULL;
288     thread->wait_fd = NULL;
289     thread->context = NULL;
290     thread->suspend_context = NULL;
291     thread->desktop = 0;
292 }
293
294 /* destroy a thread when its refcount is 0 */
295 static void destroy_thread( struct object *obj )
296 {
297     struct thread *thread = (struct thread *)obj;
298     assert( obj->ops == &thread_ops );
299
300     assert( !thread->debug_ctx );  /* cannot still be debugging something */
301     list_remove( &thread->entry );
302     cleanup_thread( thread );
303     release_object( thread->process );
304     if (thread->id) free_ptid( thread->id );
305     if (thread->token) release_object( thread->token );
306 }
307
308 /* dump a thread on stdout for debugging purposes */
309 static void dump_thread( struct object *obj, int verbose )
310 {
311     struct thread *thread = (struct thread *)obj;
312     assert( obj->ops == &thread_ops );
313
314     fprintf( stderr, "Thread id=%04x unix pid=%d unix tid=%d state=%d\n",
315              thread->id, thread->unix_pid, thread->unix_tid, thread->state );
316 }
317
318 static int thread_signaled( struct object *obj, struct thread *thread )
319 {
320     struct thread *mythread = (struct thread *)obj;
321     return (mythread->state == TERMINATED);
322 }
323
324 static unsigned int thread_map_access( struct object *obj, unsigned int access )
325 {
326     if (access & GENERIC_READ)    access |= STANDARD_RIGHTS_READ | SYNCHRONIZE;
327     if (access & GENERIC_WRITE)   access |= STANDARD_RIGHTS_WRITE | SYNCHRONIZE;
328     if (access & GENERIC_EXECUTE) access |= STANDARD_RIGHTS_EXECUTE;
329     if (access & GENERIC_ALL)     access |= THREAD_ALL_ACCESS;
330     return access & ~(GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE | GENERIC_ALL);
331 }
332
333 static void dump_thread_apc( struct object *obj, int verbose )
334 {
335     struct thread_apc *apc = (struct thread_apc *)obj;
336     assert( obj->ops == &thread_apc_ops );
337
338     fprintf( stderr, "APC owner=%p type=%u\n", apc->owner, apc->call.type );
339 }
340
341 static int thread_apc_signaled( struct object *obj, struct thread *thread )
342 {
343     struct thread_apc *apc = (struct thread_apc *)obj;
344     return apc->executed;
345 }
346
347 static void thread_apc_destroy( struct object *obj )
348 {
349     struct thread_apc *apc = (struct thread_apc *)obj;
350     if (apc->caller) release_object( apc->caller );
351     if (apc->owner) release_object( apc->owner );
352 }
353
354 /* queue an async procedure call */
355 static struct thread_apc *create_apc( struct object *owner, const apc_call_t *call_data )
356 {
357     struct thread_apc *apc;
358
359     if ((apc = alloc_object( &thread_apc_ops )))
360     {
361         apc->call        = *call_data;
362         apc->caller      = NULL;
363         apc->owner       = owner;
364         apc->executed    = 0;
365         apc->result.type = APC_NONE;
366         if (owner) grab_object( owner );
367     }
368     return apc;
369 }
370
371 /* get a thread pointer from a thread id (and increment the refcount) */
372 struct thread *get_thread_from_id( thread_id_t id )
373 {
374     struct object *obj = get_ptid_entry( id );
375
376     if (obj && obj->ops == &thread_ops) return (struct thread *)grab_object( obj );
377     set_error( STATUS_INVALID_CID );
378     return NULL;
379 }
380
381 /* get a thread from a handle (and increment the refcount) */
382 struct thread *get_thread_from_handle( obj_handle_t handle, unsigned int access )
383 {
384     return (struct thread *)get_handle_obj( current->process, handle,
385                                             access, &thread_ops );
386 }
387
388 /* find a thread from a Unix tid */
389 struct thread *get_thread_from_tid( int tid )
390 {
391     struct thread *thread;
392
393     LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
394     {
395         if (thread->unix_tid == tid) return thread;
396     }
397     return NULL;
398 }
399
400 /* find a thread from a Unix pid */
401 struct thread *get_thread_from_pid( int pid )
402 {
403     struct thread *thread;
404
405     LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
406     {
407         if (thread->unix_pid == pid) return thread;
408     }
409     return NULL;
410 }
411
412 int set_thread_affinity( struct thread *thread, affinity_t affinity )
413 {
414     int ret = 0;
415 #ifdef HAVE_SCHED_SETAFFINITY
416     if (thread->unix_tid != -1)
417     {
418         cpu_set_t set;
419         int i;
420         affinity_t mask;
421
422         CPU_ZERO( &set );
423         for (i = 0, mask = 1; mask; i++, mask <<= 1)
424             if (affinity & mask) CPU_SET( i, &set );
425
426         ret = sched_setaffinity( thread->unix_tid, sizeof(set), &set );
427     }
428 #endif
429     if (!ret) thread->affinity = affinity;
430     return ret;
431 }
432
433 #define THREAD_PRIORITY_REALTIME_HIGHEST 6
434 #define THREAD_PRIORITY_REALTIME_LOWEST -7
435
436 /* set all information about a thread */
437 static void set_thread_info( struct thread *thread,
438                              const struct set_thread_info_request *req )
439 {
440     if (req->mask & SET_THREAD_INFO_PRIORITY)
441     {
442         int max = THREAD_PRIORITY_HIGHEST;
443         int min = THREAD_PRIORITY_LOWEST;
444         if (thread->process->priority == PROCESS_PRIOCLASS_REALTIME)
445         {
446             max = THREAD_PRIORITY_REALTIME_HIGHEST;
447             min = THREAD_PRIORITY_REALTIME_LOWEST;
448         }
449         if ((req->priority >= min && req->priority <= max) ||
450             req->priority == THREAD_PRIORITY_IDLE ||
451             req->priority == THREAD_PRIORITY_TIME_CRITICAL)
452             thread->priority = req->priority;
453         else
454             set_error( STATUS_INVALID_PARAMETER );
455     }
456     if (req->mask & SET_THREAD_INFO_AFFINITY)
457     {
458         if ((req->affinity & thread->process->affinity) != req->affinity)
459             set_error( STATUS_INVALID_PARAMETER );
460         else if (thread->state == TERMINATED)
461             set_error( STATUS_ACCESS_DENIED );
462         else if (set_thread_affinity( thread, req->affinity ))
463             file_set_error();
464     }
465     if (req->mask & SET_THREAD_INFO_TOKEN)
466         security_set_thread_token( thread, req->token );
467 }
468
469 /* stop a thread (at the Unix level) */
470 void stop_thread( struct thread *thread )
471 {
472     if (thread->context) return;  /* already inside a debug event, no need for a signal */
473     /* can't stop a thread while initialisation is in progress */
474     if (is_process_init_done(thread->process)) send_thread_signal( thread, SIGUSR1 );
475 }
476
477 /* suspend a thread */
478 static int suspend_thread( struct thread *thread )
479 {
480     int old_count = thread->suspend;
481     if (thread->suspend < MAXIMUM_SUSPEND_COUNT)
482     {
483         if (!(thread->process->suspend + thread->suspend++)) stop_thread( thread );
484     }
485     else set_error( STATUS_SUSPEND_COUNT_EXCEEDED );
486     return old_count;
487 }
488
489 /* resume a thread */
490 static int resume_thread( struct thread *thread )
491 {
492     int old_count = thread->suspend;
493     if (thread->suspend > 0)
494     {
495         if (!(--thread->suspend + thread->process->suspend)) wake_thread( thread );
496     }
497     return old_count;
498 }
499
500 /* add a thread to an object wait queue; return 1 if OK, 0 on error */
501 int add_queue( struct object *obj, struct wait_queue_entry *entry )
502 {
503     grab_object( obj );
504     entry->obj = obj;
505     list_add_tail( &obj->wait_queue, &entry->entry );
506     return 1;
507 }
508
509 /* remove a thread from an object wait queue */
510 void remove_queue( struct object *obj, struct wait_queue_entry *entry )
511 {
512     list_remove( &entry->entry );
513     release_object( obj );
514 }
515
516 /* finish waiting */
517 static void end_wait( struct thread *thread )
518 {
519     struct thread_wait *wait = thread->wait;
520     struct wait_queue_entry *entry;
521     int i;
522
523     assert( wait );
524     thread->wait = wait->next;
525     for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
526         entry->obj->ops->remove_queue( entry->obj, entry );
527     if (wait->user) remove_timeout_user( wait->user );
528     free( wait );
529 }
530
531 /* build the thread wait structure */
532 static int wait_on( unsigned int count, struct object *objects[], int flags, timeout_t timeout )
533 {
534     struct thread_wait *wait;
535     struct wait_queue_entry *entry;
536     unsigned int i;
537
538     if (!(wait = mem_alloc( FIELD_OFFSET(struct thread_wait, queues[count]) ))) return 0;
539     wait->next    = current->wait;
540     wait->thread  = current;
541     wait->count   = count;
542     wait->flags   = flags;
543     wait->user    = NULL;
544     wait->timeout = timeout;
545     current->wait = wait;
546
547     for (i = 0, entry = wait->queues; i < count; i++, entry++)
548     {
549         struct object *obj = objects[i];
550         entry->thread = current;
551         if (!obj->ops->add_queue( obj, entry ))
552         {
553             wait->count = i;
554             end_wait( current );
555             return 0;
556         }
557     }
558     return 1;
559 }
560
561 /* check if the thread waiting condition is satisfied */
562 static int check_wait( struct thread *thread )
563 {
564     int i, signaled;
565     struct thread_wait *wait = thread->wait;
566     struct wait_queue_entry *entry = wait->queues;
567
568     assert( wait );
569
570     if ((wait->flags & SELECT_INTERRUPTIBLE) && !list_empty( &thread->system_apc ))
571         return STATUS_USER_APC;
572
573     /* Suspended threads may not acquire locks, but they can run system APCs */
574     if (thread->process->suspend + thread->suspend > 0) return -1;
575
576     if (wait->flags & SELECT_ALL)
577     {
578         int not_ok = 0;
579         /* Note: we must check them all anyway, as some objects may
580          * want to do something when signaled, even if others are not */
581         for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
582             not_ok |= !entry->obj->ops->signaled( entry->obj, thread );
583         if (not_ok) goto other_checks;
584         /* Wait satisfied: tell it to all objects */
585         signaled = 0;
586         for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
587             if (entry->obj->ops->satisfied( entry->obj, thread ))
588                 signaled = STATUS_ABANDONED_WAIT_0;
589         return signaled;
590     }
591     else
592     {
593         for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
594         {
595             if (!entry->obj->ops->signaled( entry->obj, thread )) continue;
596             /* Wait satisfied: tell it to the object */
597             signaled = i;
598             if (entry->obj->ops->satisfied( entry->obj, thread ))
599                 signaled = i + STATUS_ABANDONED_WAIT_0;
600             return signaled;
601         }
602     }
603
604  other_checks:
605     if ((wait->flags & SELECT_ALERTABLE) && !list_empty(&thread->user_apc)) return STATUS_USER_APC;
606     if (wait->timeout <= current_time) return STATUS_TIMEOUT;
607     return -1;
608 }
609
610 /* send the wakeup signal to a thread */
611 static int send_thread_wakeup( struct thread *thread, client_ptr_t cookie, int signaled )
612 {
613     struct wake_up_reply reply;
614     int ret;
615
616     memset( &reply, 0, sizeof(reply) );
617     reply.cookie   = cookie;
618     reply.signaled = signaled;
619     if ((ret = write( get_unix_fd( thread->wait_fd ), &reply, sizeof(reply) )) == sizeof(reply))
620         return 0;
621     if (ret >= 0)
622         fatal_protocol_error( thread, "partial wakeup write %d\n", ret );
623     else if (errno == EPIPE)
624         kill_thread( thread, 0 );  /* normal death */
625     else
626         fatal_protocol_perror( thread, "write" );
627     return -1;
628 }
629
630 /* attempt to wake up a thread */
631 /* return >0 if OK, 0 if the wait condition is still not satisfied */
632 int wake_thread( struct thread *thread )
633 {
634     int signaled, count;
635     client_ptr_t cookie;
636
637     for (count = 0; thread->wait; count++)
638     {
639         if ((signaled = check_wait( thread )) == -1) break;
640
641         cookie = thread->wait->cookie;
642         if (debug_level) fprintf( stderr, "%04x: *wakeup* signaled=%d\n", thread->id, signaled );
643         end_wait( thread );
644         if (send_thread_wakeup( thread, cookie, signaled ) == -1) /* error */
645             break;
646     }
647     return count;
648 }
649
650 /* thread wait timeout */
651 static void thread_timeout( void *ptr )
652 {
653     struct thread_wait *wait = ptr;
654     struct thread *thread = wait->thread;
655     client_ptr_t cookie = wait->cookie;
656
657     wait->user = NULL;
658     if (thread->wait != wait) return; /* not the top-level wait, ignore it */
659     if (thread->suspend + thread->process->suspend > 0) return;  /* suspended, ignore it */
660
661     if (debug_level) fprintf( stderr, "%04x: *wakeup* signaled=TIMEOUT\n", thread->id );
662     end_wait( thread );
663     if (send_thread_wakeup( thread, cookie, STATUS_TIMEOUT ) == -1) return;
664     /* check if other objects have become signaled in the meantime */
665     wake_thread( thread );
666 }
667
668 /* try signaling an event flag, a semaphore or a mutex */
669 static int signal_object( obj_handle_t handle )
670 {
671     struct object *obj;
672     int ret = 0;
673
674     obj = get_handle_obj( current->process, handle, 0, NULL );
675     if (obj)
676     {
677         ret = obj->ops->signal( obj, get_handle_access( current->process, handle ));
678         release_object( obj );
679     }
680     return ret;
681 }
682
683 /* select on a list of handles */
684 static timeout_t select_on( unsigned int count, client_ptr_t cookie, const obj_handle_t *handles,
685                             int flags, timeout_t timeout, obj_handle_t signal_obj )
686 {
687     int ret;
688     unsigned int i;
689     struct object *objects[MAXIMUM_WAIT_OBJECTS];
690
691     if (timeout <= 0) timeout = current_time - timeout;
692
693     if (count > MAXIMUM_WAIT_OBJECTS)
694     {
695         set_error( STATUS_INVALID_PARAMETER );
696         return 0;
697     }
698     for (i = 0; i < count; i++)
699     {
700         if (!(objects[i] = get_handle_obj( current->process, handles[i], SYNCHRONIZE, NULL )))
701             break;
702     }
703
704     if (i < count) goto done;
705     if (!wait_on( count, objects, flags, timeout )) goto done;
706
707     /* signal the object */
708     if (signal_obj)
709     {
710         if (!signal_object( signal_obj ))
711         {
712             end_wait( current );
713             goto done;
714         }
715         /* check if we woke ourselves up */
716         if (!current->wait) goto done;
717     }
718
719     if ((ret = check_wait( current )) != -1)
720     {
721         /* condition is already satisfied */
722         end_wait( current );
723         set_error( ret );
724         goto done;
725     }
726
727     /* now we need to wait */
728     if (current->wait->timeout != TIMEOUT_INFINITE)
729     {
730         if (!(current->wait->user = add_timeout_user( current->wait->timeout,
731                                                       thread_timeout, current->wait )))
732         {
733             end_wait( current );
734             goto done;
735         }
736     }
737     current->wait->cookie = cookie;
738     set_error( STATUS_PENDING );
739
740 done:
741     while (i > 0) release_object( objects[--i] );
742     return timeout;
743 }
744
745 /* attempt to wake threads sleeping on the object wait queue */
746 void wake_up( struct object *obj, int max )
747 {
748     struct list *ptr;
749
750     LIST_FOR_EACH( ptr, &obj->wait_queue )
751     {
752         struct wait_queue_entry *entry = LIST_ENTRY( ptr, struct wait_queue_entry, entry );
753         if (!wake_thread( entry->thread )) continue;
754         if (max && !--max) break;
755         /* restart at the head of the list since a wake up can change the object wait queue */
756         ptr = &obj->wait_queue;
757     }
758 }
759
760 /* return the apc queue to use for a given apc type */
761 static inline struct list *get_apc_queue( struct thread *thread, enum apc_type type )
762 {
763     switch(type)
764     {
765     case APC_NONE:
766     case APC_USER:
767     case APC_TIMER:
768         return &thread->user_apc;
769     default:
770         return &thread->system_apc;
771     }
772 }
773
774 /* check if thread is currently waiting for a (system) apc */
775 static inline int is_in_apc_wait( struct thread *thread )
776 {
777     return (thread->process->suspend || thread->suspend ||
778             (thread->wait && (thread->wait->flags & SELECT_INTERRUPTIBLE)));
779 }
780
781 /* queue an existing APC to a given thread */
782 static int queue_apc( struct process *process, struct thread *thread, struct thread_apc *apc )
783 {
784     struct list *queue;
785
786     if (!thread)  /* find a suitable thread inside the process */
787     {
788         struct thread *candidate;
789
790         /* first try to find a waiting thread */
791         LIST_FOR_EACH_ENTRY( candidate, &process->thread_list, struct thread, proc_entry )
792         {
793             if (candidate->state == TERMINATED) continue;
794             if (is_in_apc_wait( candidate ))
795             {
796                 thread = candidate;
797                 break;
798             }
799         }
800         if (!thread)
801         {
802             /* then use the first one that accepts a signal */
803             LIST_FOR_EACH_ENTRY( candidate, &process->thread_list, struct thread, proc_entry )
804             {
805                 if (send_thread_signal( candidate, SIGUSR1 ))
806                 {
807                     thread = candidate;
808                     break;
809                 }
810             }
811         }
812         if (!thread) return 0;  /* nothing found */
813         queue = get_apc_queue( thread, apc->call.type );
814     }
815     else
816     {
817         if (thread->state == TERMINATED) return 0;
818         queue = get_apc_queue( thread, apc->call.type );
819         /* send signal for system APCs if needed */
820         if (queue == &thread->system_apc && list_empty( queue ) && !is_in_apc_wait( thread ))
821         {
822             if (!send_thread_signal( thread, SIGUSR1 )) return 0;
823         }
824         /* cancel a possible previous APC with the same owner */
825         if (apc->owner) thread_cancel_apc( thread, apc->owner, apc->call.type );
826     }
827
828     grab_object( apc );
829     list_add_tail( queue, &apc->entry );
830     if (!list_prev( queue, &apc->entry ))  /* first one */
831         wake_thread( thread );
832
833     return 1;
834 }
835
836 /* queue an async procedure call */
837 int thread_queue_apc( struct thread *thread, struct object *owner, const apc_call_t *call_data )
838 {
839     struct thread_apc *apc;
840     int ret = 0;
841
842     if ((apc = create_apc( owner, call_data )))
843     {
844         ret = queue_apc( NULL, thread, apc );
845         release_object( apc );
846     }
847     return ret;
848 }
849
850 /* cancel the async procedure call owned by a specific object */
851 void thread_cancel_apc( struct thread *thread, struct object *owner, enum apc_type type )
852 {
853     struct thread_apc *apc;
854     struct list *queue = get_apc_queue( thread, type );
855
856     LIST_FOR_EACH_ENTRY( apc, queue, struct thread_apc, entry )
857     {
858         if (apc->owner != owner) continue;
859         list_remove( &apc->entry );
860         apc->executed = 1;
861         wake_up( &apc->obj, 0 );
862         release_object( apc );
863         return;
864     }
865 }
866
867 /* remove the head apc from the queue; the returned object must be released by the caller */
868 static struct thread_apc *thread_dequeue_apc( struct thread *thread, int system_only )
869 {
870     struct thread_apc *apc = NULL;
871     struct list *ptr = list_head( &thread->system_apc );
872
873     if (!ptr && !system_only) ptr = list_head( &thread->user_apc );
874     if (ptr)
875     {
876         apc = LIST_ENTRY( ptr, struct thread_apc, entry );
877         list_remove( ptr );
878     }
879     return apc;
880 }
881
882 /* clear an APC queue, cancelling all the APCs on it */
883 static void clear_apc_queue( struct list *queue )
884 {
885     struct list *ptr;
886
887     while ((ptr = list_head( queue )))
888     {
889         struct thread_apc *apc = LIST_ENTRY( ptr, struct thread_apc, entry );
890         list_remove( &apc->entry );
891         apc->executed = 1;
892         wake_up( &apc->obj, 0 );
893         release_object( apc );
894     }
895 }
896
897 /* add an fd to the inflight list */
898 /* return list index, or -1 on error */
899 int thread_add_inflight_fd( struct thread *thread, int client, int server )
900 {
901     int i;
902
903     if (server == -1) return -1;
904     if (client == -1)
905     {
906         close( server );
907         return -1;
908     }
909
910     /* first check if we already have an entry for this fd */
911     for (i = 0; i < MAX_INFLIGHT_FDS; i++)
912         if (thread->inflight[i].client == client)
913         {
914             close( thread->inflight[i].server );
915             thread->inflight[i].server = server;
916             return i;
917         }
918
919     /* now find a free spot to store it */
920     for (i = 0; i < MAX_INFLIGHT_FDS; i++)
921         if (thread->inflight[i].client == -1)
922         {
923             thread->inflight[i].client = client;
924             thread->inflight[i].server = server;
925             return i;
926         }
927     return -1;
928 }
929
930 /* get an inflight fd and purge it from the list */
931 /* the fd must be closed when no longer used */
932 int thread_get_inflight_fd( struct thread *thread, int client )
933 {
934     int i, ret;
935
936     if (client == -1) return -1;
937
938     do
939     {
940         for (i = 0; i < MAX_INFLIGHT_FDS; i++)
941         {
942             if (thread->inflight[i].client == client)
943             {
944                 ret = thread->inflight[i].server;
945                 thread->inflight[i].server = thread->inflight[i].client = -1;
946                 return ret;
947             }
948         }
949     } while (!receive_fd( thread->process ));  /* in case it is still in the socket buffer */
950     return -1;
951 }
952
953 /* kill a thread on the spot */
954 void kill_thread( struct thread *thread, int violent_death )
955 {
956     if (thread->state == TERMINATED) return;  /* already killed */
957     thread->state = TERMINATED;
958     thread->exit_time = current_time;
959     if (current == thread) current = NULL;
960     if (debug_level)
961         fprintf( stderr,"%04x: *killed* exit_code=%d\n",
962                  thread->id, thread->exit_code );
963     if (thread->wait)
964     {
965         while (thread->wait) end_wait( thread );
966         send_thread_wakeup( thread, 0, STATUS_PENDING );
967         /* if it is waiting on the socket, we don't need to send a SIGQUIT */
968         violent_death = 0;
969     }
970     kill_console_processes( thread, 0 );
971     debug_exit_thread( thread );
972     abandon_mutexes( thread );
973     wake_up( &thread->obj, 0 );
974     if (violent_death) send_thread_signal( thread, SIGQUIT );
975     cleanup_thread( thread );
976     remove_process_thread( thread->process, thread );
977     release_object( thread );
978 }
979
980 /* copy parts of a context structure */
981 static void copy_context( context_t *to, const context_t *from, unsigned int flags )
982 {
983     assert( to->cpu == from->cpu );
984     to->flags |= flags;
985     if (flags & SERVER_CTX_CONTROL) to->ctl = from->ctl;
986     if (flags & SERVER_CTX_INTEGER) to->integer = from->integer;
987     if (flags & SERVER_CTX_SEGMENTS) to->seg = from->seg;
988     if (flags & SERVER_CTX_FLOATING_POINT) to->fp = from->fp;
989     if (flags & SERVER_CTX_DEBUG_REGISTERS) to->debug = from->debug;
990     if (flags & SERVER_CTX_EXTENDED_REGISTERS) to->ext = from->ext;
991 }
992
993 /* return the context flags that correspond to system regs */
994 /* (system regs are the ones we can't access on the client side) */
995 static unsigned int get_context_system_regs( enum cpu_type cpu )
996 {
997     switch (cpu)
998     {
999     case CPU_x86:     return SERVER_CTX_DEBUG_REGISTERS;
1000     case CPU_x86_64:  return SERVER_CTX_DEBUG_REGISTERS;
1001     case CPU_ALPHA:   return 0;
1002     case CPU_POWERPC: return 0;
1003     case CPU_SPARC:   return 0;
1004     }
1005     return 0;
1006 }
1007
1008 /* trigger a breakpoint event in a given thread */
1009 void break_thread( struct thread *thread )
1010 {
1011     debug_event_t data;
1012
1013     assert( thread->context );
1014
1015     memset( &data, 0, sizeof(data) );
1016     data.exception.first     = 1;
1017     data.exception.exc_code  = STATUS_BREAKPOINT;
1018     data.exception.flags     = EXCEPTION_CONTINUABLE;
1019     switch (thread->context->cpu)
1020     {
1021     case CPU_x86:
1022         data.exception.address = thread->context->ctl.i386_regs.eip;
1023         break;
1024     case CPU_x86_64:
1025         data.exception.address = thread->context->ctl.x86_64_regs.rip;
1026         break;
1027     case CPU_ALPHA:
1028         data.exception.address = thread->context->ctl.alpha_regs.fir;
1029         break;
1030     case CPU_POWERPC:
1031         data.exception.address = thread->context->ctl.powerpc_regs.iar;
1032         break;
1033     case CPU_SPARC:
1034         data.exception.address = thread->context->ctl.sparc_regs.pc;
1035         break;
1036     }
1037     generate_debug_event( thread, EXCEPTION_DEBUG_EVENT, &data );
1038     thread->debug_break = 0;
1039 }
1040
1041 /* take a snapshot of currently running threads */
1042 struct thread_snapshot *thread_snap( int *count )
1043 {
1044     struct thread_snapshot *snapshot, *ptr;
1045     struct thread *thread;
1046     int total = 0;
1047
1048     LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
1049         if (thread->state != TERMINATED) total++;
1050     if (!total || !(snapshot = mem_alloc( sizeof(*snapshot) * total ))) return NULL;
1051     ptr = snapshot;
1052     LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
1053     {
1054         if (thread->state == TERMINATED) continue;
1055         ptr->thread   = thread;
1056         ptr->count    = thread->obj.refcount;
1057         ptr->priority = thread->priority;
1058         grab_object( thread );
1059         ptr++;
1060     }
1061     *count = total;
1062     return snapshot;
1063 }
1064
1065 /* gets the current impersonation token */
1066 struct token *thread_get_impersonation_token( struct thread *thread )
1067 {
1068     if (thread->token)
1069         return thread->token;
1070     else
1071         return thread->process->token;
1072 }
1073
1074 /* create a new thread */
1075 DECL_HANDLER(new_thread)
1076 {
1077     struct thread *thread;
1078     int request_fd = thread_get_inflight_fd( current, req->request_fd );
1079
1080     if (request_fd == -1 || fcntl( request_fd, F_SETFL, O_NONBLOCK ) == -1)
1081     {
1082         if (request_fd != -1) close( request_fd );
1083         set_error( STATUS_INVALID_HANDLE );
1084         return;
1085     }
1086
1087     if ((thread = create_thread( request_fd, current->process )))
1088     {
1089         if (req->suspend) thread->suspend++;
1090         reply->tid = get_thread_id( thread );
1091         if ((reply->handle = alloc_handle( current->process, thread, req->access, req->attributes )))
1092         {
1093             /* thread object will be released when the thread gets killed */
1094             return;
1095         }
1096         kill_thread( thread, 1 );
1097     }
1098 }
1099
1100 /* initialize a new thread */
1101 DECL_HANDLER(init_thread)
1102 {
1103     unsigned int prefix_cpu_mask = get_prefix_cpu_mask();
1104     struct process *process = current->process;
1105     int reply_fd = thread_get_inflight_fd( current, req->reply_fd );
1106     int wait_fd = thread_get_inflight_fd( current, req->wait_fd );
1107
1108     if (current->reply_fd)  /* already initialised */
1109     {
1110         set_error( STATUS_INVALID_PARAMETER );
1111         goto error;
1112     }
1113
1114     if (reply_fd == -1 || fcntl( reply_fd, F_SETFL, O_NONBLOCK ) == -1) goto error;
1115
1116     current->reply_fd = create_anonymous_fd( &thread_fd_ops, reply_fd, &current->obj, 0 );
1117     reply_fd = -1;
1118     if (!current->reply_fd) goto error;
1119
1120     if (wait_fd == -1)
1121     {
1122         set_error( STATUS_TOO_MANY_OPENED_FILES );  /* most likely reason */
1123         return;
1124     }
1125     if (!(current->wait_fd  = create_anonymous_fd( &thread_fd_ops, wait_fd, &current->obj, 0 )))
1126         return;
1127
1128     if (!is_valid_address(req->teb))
1129     {
1130         set_error( STATUS_INVALID_PARAMETER );
1131         return;
1132     }
1133
1134     current->unix_pid = req->unix_pid;
1135     current->unix_tid = req->unix_tid;
1136     current->teb      = req->teb;
1137
1138     if (!process->peb)  /* first thread, initialize the process too */
1139     {
1140         if (!CPU_FLAG(req->cpu) || !(supported_cpus & prefix_cpu_mask & CPU_FLAG(req->cpu)))
1141         {
1142             if (!(supported_cpus & CPU_64BIT_MASK))
1143                 set_error( STATUS_NOT_SUPPORTED );
1144             else
1145                 set_error( STATUS_NOT_REGISTRY_FILE );  /* server supports it but not the prefix */
1146             return;
1147         }
1148         process->unix_pid = current->unix_pid;
1149         process->peb      = req->entry;
1150         process->cpu      = req->cpu;
1151         reply->info_size  = init_process( current );
1152     }
1153     else
1154     {
1155         if (req->cpu != process->cpu)
1156         {
1157             set_error( STATUS_INVALID_PARAMETER );
1158             return;
1159         }
1160         if (process->unix_pid != current->unix_pid)
1161             process->unix_pid = -1;  /* can happen with linuxthreads */
1162         if (current->suspend + process->suspend > 0) stop_thread( current );
1163         generate_debug_event( current, CREATE_THREAD_DEBUG_EVENT, &req->entry );
1164     }
1165     debug_level = max( debug_level, req->debug_level );
1166     set_thread_affinity( current, current->affinity );
1167
1168     reply->pid     = get_process_id( process );
1169     reply->tid     = get_thread_id( current );
1170     reply->version = SERVER_PROTOCOL_VERSION;
1171     reply->server_start = server_start_time;
1172     reply->all_cpus     = supported_cpus & prefix_cpu_mask;
1173     return;
1174
1175  error:
1176     if (reply_fd != -1) close( reply_fd );
1177     if (wait_fd != -1) close( wait_fd );
1178 }
1179
1180 /* terminate a thread */
1181 DECL_HANDLER(terminate_thread)
1182 {
1183     struct thread *thread;
1184
1185     reply->self = 0;
1186     reply->last = 0;
1187     if ((thread = get_thread_from_handle( req->handle, THREAD_TERMINATE )))
1188     {
1189         thread->exit_code = req->exit_code;
1190         if (thread != current) kill_thread( thread, 1 );
1191         else
1192         {
1193             reply->self = 1;
1194             reply->last = (thread->process->running_threads == 1);
1195         }
1196         release_object( thread );
1197     }
1198 }
1199
1200 /* open a handle to a thread */
1201 DECL_HANDLER(open_thread)
1202 {
1203     struct thread *thread = get_thread_from_id( req->tid );
1204
1205     reply->handle = 0;
1206     if (thread)
1207     {
1208         reply->handle = alloc_handle( current->process, thread, req->access, req->attributes );
1209         release_object( thread );
1210     }
1211 }
1212
1213 /* fetch information about a thread */
1214 DECL_HANDLER(get_thread_info)
1215 {
1216     struct thread *thread;
1217     obj_handle_t handle = req->handle;
1218
1219     if (!handle) thread = get_thread_from_id( req->tid_in );
1220     else thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION );
1221
1222     if (thread)
1223     {
1224         reply->pid            = get_process_id( thread->process );
1225         reply->tid            = get_thread_id( thread );
1226         reply->teb            = thread->teb;
1227         reply->exit_code      = (thread->state == TERMINATED) ? thread->exit_code : STATUS_PENDING;
1228         reply->priority       = thread->priority;
1229         reply->affinity       = thread->affinity;
1230         reply->creation_time  = thread->creation_time;
1231         reply->exit_time      = thread->exit_time;
1232         reply->last           = thread->process->running_threads == 1;
1233
1234         release_object( thread );
1235     }
1236 }
1237
1238 /* set information about a thread */
1239 DECL_HANDLER(set_thread_info)
1240 {
1241     struct thread *thread;
1242
1243     if ((thread = get_thread_from_handle( req->handle, THREAD_SET_INFORMATION )))
1244     {
1245         set_thread_info( thread, req );
1246         release_object( thread );
1247     }
1248 }
1249
1250 /* suspend a thread */
1251 DECL_HANDLER(suspend_thread)
1252 {
1253     struct thread *thread;
1254
1255     if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
1256     {
1257         if (thread->state == TERMINATED) set_error( STATUS_ACCESS_DENIED );
1258         else reply->count = suspend_thread( thread );
1259         release_object( thread );
1260     }
1261 }
1262
1263 /* resume a thread */
1264 DECL_HANDLER(resume_thread)
1265 {
1266     struct thread *thread;
1267
1268     if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
1269     {
1270         reply->count = resume_thread( thread );
1271         release_object( thread );
1272     }
1273 }
1274
1275 /* select on a handle list */
1276 DECL_HANDLER(select)
1277 {
1278     struct thread_apc *apc;
1279     unsigned int count;
1280     const apc_result_t *result = get_req_data();
1281     const obj_handle_t *handles = (const obj_handle_t *)(result + 1);
1282
1283     if (get_req_data_size() < sizeof(*result))
1284     {
1285         set_error( STATUS_INVALID_PARAMETER );
1286         return;
1287     }
1288     count = (get_req_data_size() - sizeof(*result)) / sizeof(obj_handle_t);
1289
1290     /* first store results of previous apc */
1291     if (req->prev_apc)
1292     {
1293         if (!(apc = (struct thread_apc *)get_handle_obj( current->process, req->prev_apc,
1294                                                          0, &thread_apc_ops ))) return;
1295         apc->result = *result;
1296         apc->executed = 1;
1297         if (apc->result.type == APC_CREATE_THREAD)  /* transfer the handle to the caller process */
1298         {
1299             obj_handle_t handle = duplicate_handle( current->process, apc->result.create_thread.handle,
1300                                                     apc->caller->process, 0, 0, DUP_HANDLE_SAME_ACCESS );
1301             close_handle( current->process, apc->result.create_thread.handle );
1302             apc->result.create_thread.handle = handle;
1303             clear_error();  /* ignore errors from the above calls */
1304         }
1305         else if (apc->result.type == APC_ASYNC_IO)
1306         {
1307             if (apc->owner)
1308                 async_set_result( apc->owner, apc->result.async_io.status,
1309                                   apc->result.async_io.total, apc->result.async_io.apc );
1310         }
1311         wake_up( &apc->obj, 0 );
1312         close_handle( current->process, req->prev_apc );
1313         release_object( apc );
1314     }
1315
1316     reply->timeout = select_on( count, req->cookie, handles, req->flags, req->timeout, req->signal );
1317
1318     if (get_error() == STATUS_USER_APC)
1319     {
1320         for (;;)
1321         {
1322             if (!(apc = thread_dequeue_apc( current, !(req->flags & SELECT_ALERTABLE) )))
1323                 break;
1324             /* Optimization: ignore APC_NONE calls, they are only used to
1325              * wake up a thread, but since we got here the thread woke up already.
1326              */
1327             if (apc->call.type != APC_NONE)
1328             {
1329                 if ((reply->apc_handle = alloc_handle( current->process, apc, SYNCHRONIZE, 0 )))
1330                     reply->call = apc->call;
1331                 release_object( apc );
1332                 break;
1333             }
1334             apc->executed = 1;
1335             wake_up( &apc->obj, 0 );
1336             release_object( apc );
1337         }
1338     }
1339 }
1340
1341 /* queue an APC for a thread or process */
1342 DECL_HANDLER(queue_apc)
1343 {
1344     struct thread *thread = NULL;
1345     struct process *process = NULL;
1346     struct thread_apc *apc;
1347
1348     if (!(apc = create_apc( NULL, &req->call ))) return;
1349
1350     switch (apc->call.type)
1351     {
1352     case APC_NONE:
1353     case APC_USER:
1354         thread = get_thread_from_handle( req->handle, THREAD_SET_CONTEXT );
1355         break;
1356     case APC_VIRTUAL_ALLOC:
1357     case APC_VIRTUAL_FREE:
1358     case APC_VIRTUAL_PROTECT:
1359     case APC_VIRTUAL_FLUSH:
1360     case APC_VIRTUAL_LOCK:
1361     case APC_VIRTUAL_UNLOCK:
1362     case APC_UNMAP_VIEW:
1363         process = get_process_from_handle( req->handle, PROCESS_VM_OPERATION );
1364         break;
1365     case APC_VIRTUAL_QUERY:
1366         process = get_process_from_handle( req->handle, PROCESS_QUERY_INFORMATION );
1367         break;
1368     case APC_MAP_VIEW:
1369         process = get_process_from_handle( req->handle, PROCESS_VM_OPERATION );
1370         if (process && process != current->process)
1371         {
1372             /* duplicate the handle into the target process */
1373             obj_handle_t handle = duplicate_handle( current->process, apc->call.map_view.handle,
1374                                                     process, 0, 0, DUP_HANDLE_SAME_ACCESS );
1375             if (handle) apc->call.map_view.handle = handle;
1376             else
1377             {
1378                 release_object( process );
1379                 process = NULL;
1380             }
1381         }
1382         break;
1383     case APC_CREATE_THREAD:
1384         process = get_process_from_handle( req->handle, PROCESS_CREATE_THREAD );
1385         break;
1386     default:
1387         set_error( STATUS_INVALID_PARAMETER );
1388         break;
1389     }
1390
1391     if (thread)
1392     {
1393         if (!queue_apc( NULL, thread, apc )) set_error( STATUS_THREAD_IS_TERMINATING );
1394         release_object( thread );
1395     }
1396     else if (process)
1397     {
1398         reply->self = (process == current->process);
1399         if (!reply->self)
1400         {
1401             obj_handle_t handle = alloc_handle( current->process, apc, SYNCHRONIZE, 0 );
1402             if (handle)
1403             {
1404                 if (queue_apc( process, NULL, apc ))
1405                 {
1406                     apc->caller = (struct thread *)grab_object( current );
1407                     reply->handle = handle;
1408                 }
1409                 else
1410                 {
1411                     close_handle( current->process, handle );
1412                     set_error( STATUS_PROCESS_IS_TERMINATING );
1413                 }
1414             }
1415         }
1416         release_object( process );
1417     }
1418
1419     release_object( apc );
1420 }
1421
1422 /* Get the result of an APC call */
1423 DECL_HANDLER(get_apc_result)
1424 {
1425     struct thread_apc *apc;
1426
1427     if (!(apc = (struct thread_apc *)get_handle_obj( current->process, req->handle,
1428                                                      0, &thread_apc_ops ))) return;
1429     if (!apc->executed) set_error( STATUS_PENDING );
1430     else
1431     {
1432         reply->result = apc->result;
1433         /* close the handle directly to avoid an extra round-trip */
1434         close_handle( current->process, req->handle );
1435     }
1436     release_object( apc );
1437 }
1438
1439 /* retrieve the current context of a thread */
1440 DECL_HANDLER(get_thread_context)
1441 {
1442     struct thread *thread;
1443     context_t *context;
1444
1445     if (get_reply_max_size() < sizeof(context_t))
1446     {
1447         set_error( STATUS_INVALID_PARAMETER );
1448         return;
1449     }
1450     if (!(thread = get_thread_from_handle( req->handle, THREAD_GET_CONTEXT ))) return;
1451
1452     if (req->suspend)
1453     {
1454         if (thread != current || !thread->suspend_context)
1455         {
1456             /* not suspended, shouldn't happen */
1457             set_error( STATUS_INVALID_PARAMETER );
1458         }
1459         else
1460         {
1461             if (thread->context == thread->suspend_context) thread->context = NULL;
1462             set_reply_data_ptr( thread->suspend_context, sizeof(context_t) );
1463             thread->suspend_context = NULL;
1464         }
1465     }
1466     else if (thread != current && !thread->context)
1467     {
1468         /* thread is not suspended, retry (if it's still running) */
1469         if (thread->state != RUNNING) set_error( STATUS_ACCESS_DENIED );
1470         else set_error( STATUS_PENDING );
1471     }
1472     else if ((context = set_reply_data_size( sizeof(context_t) )))
1473     {
1474         unsigned int flags = get_context_system_regs( thread->process->cpu );
1475
1476         memset( context, 0, sizeof(context_t) );
1477         context->cpu = thread->process->cpu;
1478         if (thread->context) copy_context( context, thread->context, req->flags & ~flags );
1479         if (flags) get_thread_context( thread, context, flags );
1480     }
1481     reply->self = (thread == current);
1482     release_object( thread );
1483 }
1484
1485 /* set the current context of a thread */
1486 DECL_HANDLER(set_thread_context)
1487 {
1488     struct thread *thread;
1489     const context_t *context = get_req_data();
1490
1491     if (get_req_data_size() < sizeof(context_t))
1492     {
1493         set_error( STATUS_INVALID_PARAMETER );
1494         return;
1495     }
1496     if (!(thread = get_thread_from_handle( req->handle, THREAD_SET_CONTEXT ))) return;
1497
1498     if (req->suspend)
1499     {
1500         if (thread != current || thread->context || context->cpu != thread->process->cpu)
1501         {
1502             /* nested suspend or exception, shouldn't happen */
1503             set_error( STATUS_INVALID_PARAMETER );
1504         }
1505         else if ((thread->suspend_context = mem_alloc( sizeof(context_t) )))
1506         {
1507             memcpy( thread->suspend_context, get_req_data(), sizeof(context_t) );
1508             thread->context = thread->suspend_context;
1509             if (thread->debug_break) break_thread( thread );
1510         }
1511     }
1512     else if (thread != current && !thread->context)
1513     {
1514         /* thread is not suspended, retry (if it's still running) */
1515         if (thread->state != RUNNING) set_error( STATUS_ACCESS_DENIED );
1516         else set_error( STATUS_PENDING );
1517     }
1518     else if (context->cpu == thread->process->cpu)
1519     {
1520         unsigned int system_flags = get_context_system_regs(context->cpu) & context->flags;
1521         unsigned int client_flags = context->flags & ~system_flags;
1522
1523         if (system_flags) set_thread_context( thread, context, system_flags );
1524         if (thread->context && !get_error()) copy_context( thread->context, context, client_flags );
1525     }
1526     else set_error( STATUS_INVALID_PARAMETER );
1527
1528     reply->self = (thread == current);
1529     release_object( thread );
1530 }
1531
1532 /* fetch a selector entry for a thread */
1533 DECL_HANDLER(get_selector_entry)
1534 {
1535     struct thread *thread;
1536     if ((thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION )))
1537     {
1538         get_selector_entry( thread, req->entry, &reply->base, &reply->limit, &reply->flags );
1539         release_object( thread );
1540     }
1541 }