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