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