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