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