server: Add ARM64 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(__powerpc__)
61 static const unsigned int supported_cpus = CPU_FLAG(CPU_POWERPC);
62 #elif defined(__sparc__)
63 static const unsigned int supported_cpus = CPU_FLAG(CPU_SPARC);
64 #elif defined(__arm__)
65 static const unsigned int supported_cpus = CPU_FLAG(CPU_ARM);
66 #elif defined(__aarch64__)
67 static const unsigned int supported_cpus = CPU_FLAG(CPU_ARM64);
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 /* stop a thread if it's supposed to be suspended */
497 void stop_thread_if_suspended( struct thread *thread )
498 {
499     if (thread->suspend + thread->process->suspend > 0) stop_thread( thread );
500 }
501
502 /* suspend a thread */
503 static int suspend_thread( struct thread *thread )
504 {
505     int old_count = thread->suspend;
506     if (thread->suspend < MAXIMUM_SUSPEND_COUNT)
507     {
508         if (!(thread->process->suspend + thread->suspend++)) stop_thread( thread );
509     }
510     else set_error( STATUS_SUSPEND_COUNT_EXCEEDED );
511     return old_count;
512 }
513
514 /* resume a thread */
515 static int resume_thread( struct thread *thread )
516 {
517     int old_count = thread->suspend;
518     if (thread->suspend > 0)
519     {
520         if (!(--thread->suspend + thread->process->suspend)) wake_thread( thread );
521     }
522     return old_count;
523 }
524
525 /* add a thread to an object wait queue; return 1 if OK, 0 on error */
526 int add_queue( struct object *obj, struct wait_queue_entry *entry )
527 {
528     grab_object( obj );
529     entry->obj = obj;
530     list_add_tail( &obj->wait_queue, &entry->entry );
531     return 1;
532 }
533
534 /* remove a thread from an object wait queue */
535 void remove_queue( struct object *obj, struct wait_queue_entry *entry )
536 {
537     list_remove( &entry->entry );
538     release_object( obj );
539 }
540
541 /* finish waiting */
542 static void end_wait( struct thread *thread )
543 {
544     struct thread_wait *wait = thread->wait;
545     struct wait_queue_entry *entry;
546     int i;
547
548     assert( wait );
549     thread->wait = wait->next;
550     for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
551         entry->obj->ops->remove_queue( entry->obj, entry );
552     if (wait->user) remove_timeout_user( wait->user );
553     free( wait );
554 }
555
556 /* build the thread wait structure */
557 static int wait_on( unsigned int count, struct object *objects[], int flags, timeout_t timeout )
558 {
559     struct thread_wait *wait;
560     struct wait_queue_entry *entry;
561     unsigned int i;
562
563     if (!(wait = mem_alloc( FIELD_OFFSET(struct thread_wait, queues[count]) ))) return 0;
564     wait->next    = current->wait;
565     wait->thread  = current;
566     wait->count   = count;
567     wait->flags   = flags;
568     wait->user    = NULL;
569     wait->timeout = timeout;
570     current->wait = wait;
571
572     for (i = 0, entry = wait->queues; i < count; i++, entry++)
573     {
574         struct object *obj = objects[i];
575         entry->thread = current;
576         if (!obj->ops->add_queue( obj, entry ))
577         {
578             wait->count = i;
579             end_wait( current );
580             return 0;
581         }
582     }
583     return 1;
584 }
585
586 /* check if the thread waiting condition is satisfied */
587 static int check_wait( struct thread *thread )
588 {
589     int i, signaled;
590     struct thread_wait *wait = thread->wait;
591     struct wait_queue_entry *entry;
592
593     assert( wait );
594
595     if ((wait->flags & SELECT_INTERRUPTIBLE) && !list_empty( &thread->system_apc ))
596         return STATUS_USER_APC;
597
598     /* Suspended threads may not acquire locks, but they can run system APCs */
599     if (thread->process->suspend + thread->suspend > 0) return -1;
600
601     if (wait->flags & SELECT_ALL)
602     {
603         int not_ok = 0;
604         /* Note: we must check them all anyway, as some objects may
605          * want to do something when signaled, even if others are not */
606         for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
607             not_ok |= !entry->obj->ops->signaled( entry->obj, thread );
608         if (not_ok) goto other_checks;
609         /* Wait satisfied: tell it to all objects */
610         signaled = 0;
611         for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
612             if (entry->obj->ops->satisfied( entry->obj, thread ))
613                 signaled = STATUS_ABANDONED_WAIT_0;
614         return signaled;
615     }
616     else
617     {
618         for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
619         {
620             if (!entry->obj->ops->signaled( entry->obj, thread )) continue;
621             /* Wait satisfied: tell it to the object */
622             signaled = i;
623             if (entry->obj->ops->satisfied( entry->obj, thread ))
624                 signaled = i + STATUS_ABANDONED_WAIT_0;
625             return signaled;
626         }
627     }
628
629  other_checks:
630     if ((wait->flags & SELECT_ALERTABLE) && !list_empty(&thread->user_apc)) return STATUS_USER_APC;
631     if (wait->timeout <= current_time) return STATUS_TIMEOUT;
632     return -1;
633 }
634
635 /* send the wakeup signal to a thread */
636 static int send_thread_wakeup( struct thread *thread, client_ptr_t cookie, int signaled )
637 {
638     struct wake_up_reply reply;
639     int ret;
640
641     memset( &reply, 0, sizeof(reply) );
642     reply.cookie   = cookie;
643     reply.signaled = signaled;
644     if ((ret = write( get_unix_fd( thread->wait_fd ), &reply, sizeof(reply) )) == sizeof(reply))
645         return 0;
646     if (ret >= 0)
647         fatal_protocol_error( thread, "partial wakeup write %d\n", ret );
648     else if (errno == EPIPE)
649         kill_thread( thread, 0 );  /* normal death */
650     else
651         fatal_protocol_perror( thread, "write" );
652     return -1;
653 }
654
655 /* attempt to wake up a thread */
656 /* return >0 if OK, 0 if the wait condition is still not satisfied */
657 int wake_thread( struct thread *thread )
658 {
659     int signaled, count;
660     client_ptr_t cookie;
661
662     for (count = 0; thread->wait; count++)
663     {
664         if ((signaled = check_wait( thread )) == -1) break;
665
666         cookie = thread->wait->cookie;
667         if (debug_level) fprintf( stderr, "%04x: *wakeup* signaled=%d\n", thread->id, signaled );
668         end_wait( thread );
669         if (send_thread_wakeup( thread, cookie, signaled ) == -1) /* error */
670             break;
671     }
672     return count;
673 }
674
675 /* thread wait timeout */
676 static void thread_timeout( void *ptr )
677 {
678     struct thread_wait *wait = ptr;
679     struct thread *thread = wait->thread;
680     client_ptr_t cookie = wait->cookie;
681
682     wait->user = NULL;
683     if (thread->wait != wait) return; /* not the top-level wait, ignore it */
684     if (thread->suspend + thread->process->suspend > 0) return;  /* suspended, ignore it */
685
686     if (debug_level) fprintf( stderr, "%04x: *wakeup* signaled=TIMEOUT\n", thread->id );
687     end_wait( thread );
688     if (send_thread_wakeup( thread, cookie, STATUS_TIMEOUT ) == -1) return;
689     /* check if other objects have become signaled in the meantime */
690     wake_thread( thread );
691 }
692
693 /* try signaling an event flag, a semaphore or a mutex */
694 static int signal_object( obj_handle_t handle )
695 {
696     struct object *obj;
697     int ret = 0;
698
699     obj = get_handle_obj( current->process, handle, 0, NULL );
700     if (obj)
701     {
702         ret = obj->ops->signal( obj, get_handle_access( current->process, handle ));
703         release_object( obj );
704     }
705     return ret;
706 }
707
708 /* select on a list of handles */
709 static timeout_t select_on( unsigned int count, client_ptr_t cookie, const obj_handle_t *handles,
710                             int flags, timeout_t timeout, obj_handle_t signal_obj )
711 {
712     int ret;
713     unsigned int i;
714     struct object *objects[MAXIMUM_WAIT_OBJECTS];
715
716     if (timeout <= 0) timeout = current_time - timeout;
717
718     if (count > MAXIMUM_WAIT_OBJECTS)
719     {
720         set_error( STATUS_INVALID_PARAMETER );
721         return 0;
722     }
723     for (i = 0; i < count; i++)
724     {
725         if (!(objects[i] = get_handle_obj( current->process, handles[i], SYNCHRONIZE, NULL )))
726             break;
727     }
728
729     if (i < count) goto done;
730     if (!wait_on( count, objects, flags, timeout )) goto done;
731
732     /* signal the object */
733     if (signal_obj)
734     {
735         if (!signal_object( signal_obj ))
736         {
737             end_wait( current );
738             goto done;
739         }
740         /* check if we woke ourselves up */
741         if (!current->wait) goto done;
742     }
743
744     if ((ret = check_wait( current )) != -1)
745     {
746         /* condition is already satisfied */
747         end_wait( current );
748         set_error( ret );
749         goto done;
750     }
751
752     /* now we need to wait */
753     if (current->wait->timeout != TIMEOUT_INFINITE)
754     {
755         if (!(current->wait->user = add_timeout_user( current->wait->timeout,
756                                                       thread_timeout, current->wait )))
757         {
758             end_wait( current );
759             goto done;
760         }
761     }
762     current->wait->cookie = cookie;
763     set_error( STATUS_PENDING );
764
765 done:
766     while (i > 0) release_object( objects[--i] );
767     return timeout;
768 }
769
770 /* attempt to wake threads sleeping on the object wait queue */
771 void wake_up( struct object *obj, int max )
772 {
773     struct list *ptr;
774
775     LIST_FOR_EACH( ptr, &obj->wait_queue )
776     {
777         struct wait_queue_entry *entry = LIST_ENTRY( ptr, struct wait_queue_entry, entry );
778         if (!wake_thread( entry->thread )) continue;
779         if (max && !--max) break;
780         /* restart at the head of the list since a wake up can change the object wait queue */
781         ptr = &obj->wait_queue;
782     }
783 }
784
785 /* return the apc queue to use for a given apc type */
786 static inline struct list *get_apc_queue( struct thread *thread, enum apc_type type )
787 {
788     switch(type)
789     {
790     case APC_NONE:
791     case APC_USER:
792     case APC_TIMER:
793         return &thread->user_apc;
794     default:
795         return &thread->system_apc;
796     }
797 }
798
799 /* check if thread is currently waiting for a (system) apc */
800 static inline int is_in_apc_wait( struct thread *thread )
801 {
802     return (thread->process->suspend || thread->suspend ||
803             (thread->wait && (thread->wait->flags & SELECT_INTERRUPTIBLE)));
804 }
805
806 /* queue an existing APC to a given thread */
807 static int queue_apc( struct process *process, struct thread *thread, struct thread_apc *apc )
808 {
809     struct list *queue;
810
811     if (!thread)  /* find a suitable thread inside the process */
812     {
813         struct thread *candidate;
814
815         /* first try to find a waiting thread */
816         LIST_FOR_EACH_ENTRY( candidate, &process->thread_list, struct thread, proc_entry )
817         {
818             if (candidate->state == TERMINATED) continue;
819             if (is_in_apc_wait( candidate ))
820             {
821                 thread = candidate;
822                 break;
823             }
824         }
825         if (!thread)
826         {
827             /* then use the first one that accepts a signal */
828             LIST_FOR_EACH_ENTRY( candidate, &process->thread_list, struct thread, proc_entry )
829             {
830                 if (send_thread_signal( candidate, SIGUSR1 ))
831                 {
832                     thread = candidate;
833                     break;
834                 }
835             }
836         }
837         if (!thread) return 0;  /* nothing found */
838         queue = get_apc_queue( thread, apc->call.type );
839     }
840     else
841     {
842         if (thread->state == TERMINATED) return 0;
843         queue = get_apc_queue( thread, apc->call.type );
844         /* send signal for system APCs if needed */
845         if (queue == &thread->system_apc && list_empty( queue ) && !is_in_apc_wait( thread ))
846         {
847             if (!send_thread_signal( thread, SIGUSR1 )) return 0;
848         }
849         /* cancel a possible previous APC with the same owner */
850         if (apc->owner) thread_cancel_apc( thread, apc->owner, apc->call.type );
851     }
852
853     grab_object( apc );
854     list_add_tail( queue, &apc->entry );
855     if (!list_prev( queue, &apc->entry ))  /* first one */
856         wake_thread( thread );
857
858     return 1;
859 }
860
861 /* queue an async procedure call */
862 int thread_queue_apc( struct thread *thread, struct object *owner, const apc_call_t *call_data )
863 {
864     struct thread_apc *apc;
865     int ret = 0;
866
867     if ((apc = create_apc( owner, call_data )))
868     {
869         ret = queue_apc( NULL, thread, apc );
870         release_object( apc );
871     }
872     return ret;
873 }
874
875 /* cancel the async procedure call owned by a specific object */
876 void thread_cancel_apc( struct thread *thread, struct object *owner, enum apc_type type )
877 {
878     struct thread_apc *apc;
879     struct list *queue = get_apc_queue( thread, type );
880
881     LIST_FOR_EACH_ENTRY( apc, queue, struct thread_apc, entry )
882     {
883         if (apc->owner != owner) continue;
884         list_remove( &apc->entry );
885         apc->executed = 1;
886         wake_up( &apc->obj, 0 );
887         release_object( apc );
888         return;
889     }
890 }
891
892 /* remove the head apc from the queue; the returned object must be released by the caller */
893 static struct thread_apc *thread_dequeue_apc( struct thread *thread, int system_only )
894 {
895     struct thread_apc *apc = NULL;
896     struct list *ptr = list_head( &thread->system_apc );
897
898     if (!ptr && !system_only) ptr = list_head( &thread->user_apc );
899     if (ptr)
900     {
901         apc = LIST_ENTRY( ptr, struct thread_apc, entry );
902         list_remove( ptr );
903     }
904     return apc;
905 }
906
907 /* clear an APC queue, cancelling all the APCs on it */
908 static void clear_apc_queue( struct list *queue )
909 {
910     struct list *ptr;
911
912     while ((ptr = list_head( queue )))
913     {
914         struct thread_apc *apc = LIST_ENTRY( ptr, struct thread_apc, entry );
915         list_remove( &apc->entry );
916         apc->executed = 1;
917         wake_up( &apc->obj, 0 );
918         release_object( apc );
919     }
920 }
921
922 /* add an fd to the inflight list */
923 /* return list index, or -1 on error */
924 int thread_add_inflight_fd( struct thread *thread, int client, int server )
925 {
926     int i;
927
928     if (server == -1) return -1;
929     if (client == -1)
930     {
931         close( server );
932         return -1;
933     }
934
935     /* first check if we already have an entry for this fd */
936     for (i = 0; i < MAX_INFLIGHT_FDS; i++)
937         if (thread->inflight[i].client == client)
938         {
939             close( thread->inflight[i].server );
940             thread->inflight[i].server = server;
941             return i;
942         }
943
944     /* now find a free spot to store it */
945     for (i = 0; i < MAX_INFLIGHT_FDS; i++)
946         if (thread->inflight[i].client == -1)
947         {
948             thread->inflight[i].client = client;
949             thread->inflight[i].server = server;
950             return i;
951         }
952     return -1;
953 }
954
955 /* get an inflight fd and purge it from the list */
956 /* the fd must be closed when no longer used */
957 int thread_get_inflight_fd( struct thread *thread, int client )
958 {
959     int i, ret;
960
961     if (client == -1) return -1;
962
963     do
964     {
965         for (i = 0; i < MAX_INFLIGHT_FDS; i++)
966         {
967             if (thread->inflight[i].client == client)
968             {
969                 ret = thread->inflight[i].server;
970                 thread->inflight[i].server = thread->inflight[i].client = -1;
971                 return ret;
972             }
973         }
974     } while (!receive_fd( thread->process ));  /* in case it is still in the socket buffer */
975     return -1;
976 }
977
978 /* kill a thread on the spot */
979 void kill_thread( struct thread *thread, int violent_death )
980 {
981     if (thread->state == TERMINATED) return;  /* already killed */
982     thread->state = TERMINATED;
983     thread->exit_time = current_time;
984     if (current == thread) current = NULL;
985     if (debug_level)
986         fprintf( stderr,"%04x: *killed* exit_code=%d\n",
987                  thread->id, thread->exit_code );
988     if (thread->wait)
989     {
990         while (thread->wait) end_wait( thread );
991         send_thread_wakeup( thread, 0, thread->exit_code );
992         /* if it is waiting on the socket, we don't need to send a SIGQUIT */
993         violent_death = 0;
994     }
995     kill_console_processes( thread, 0 );
996     debug_exit_thread( thread );
997     abandon_mutexes( thread );
998     wake_up( &thread->obj, 0 );
999     if (violent_death) send_thread_signal( thread, SIGQUIT );
1000     cleanup_thread( thread );
1001     remove_process_thread( thread->process, thread );
1002     release_object( thread );
1003 }
1004
1005 /* copy parts of a context structure */
1006 static void copy_context( context_t *to, const context_t *from, unsigned int flags )
1007 {
1008     assert( to->cpu == from->cpu );
1009     to->flags |= flags;
1010     if (flags & SERVER_CTX_CONTROL) to->ctl = from->ctl;
1011     if (flags & SERVER_CTX_INTEGER) to->integer = from->integer;
1012     if (flags & SERVER_CTX_SEGMENTS) to->seg = from->seg;
1013     if (flags & SERVER_CTX_FLOATING_POINT) to->fp = from->fp;
1014     if (flags & SERVER_CTX_DEBUG_REGISTERS) to->debug = from->debug;
1015     if (flags & SERVER_CTX_EXTENDED_REGISTERS) to->ext = from->ext;
1016 }
1017
1018 /* return the context flags that correspond to system regs */
1019 /* (system regs are the ones we can't access on the client side) */
1020 static unsigned int get_context_system_regs( enum cpu_type cpu )
1021 {
1022     switch (cpu)
1023     {
1024     case CPU_x86:     return SERVER_CTX_DEBUG_REGISTERS;
1025     case CPU_x86_64:  return SERVER_CTX_DEBUG_REGISTERS;
1026     case CPU_POWERPC: return 0;
1027     case CPU_ARM:     return 0;
1028     case CPU_ARM64:   return 0;
1029     case CPU_SPARC:   return 0;
1030     }
1031     return 0;
1032 }
1033
1034 /* trigger a breakpoint event in a given thread */
1035 void break_thread( struct thread *thread )
1036 {
1037     debug_event_t data;
1038
1039     assert( thread->context );
1040
1041     memset( &data, 0, sizeof(data) );
1042     data.exception.first     = 1;
1043     data.exception.exc_code  = STATUS_BREAKPOINT;
1044     data.exception.flags     = EXCEPTION_CONTINUABLE;
1045     switch (thread->context->cpu)
1046     {
1047     case CPU_x86:
1048         data.exception.address = thread->context->ctl.i386_regs.eip;
1049         break;
1050     case CPU_x86_64:
1051         data.exception.address = thread->context->ctl.x86_64_regs.rip;
1052         break;
1053     case CPU_POWERPC:
1054         data.exception.address = thread->context->ctl.powerpc_regs.iar;
1055         break;
1056     case CPU_SPARC:
1057         data.exception.address = thread->context->ctl.sparc_regs.pc;
1058         break;
1059     case CPU_ARM:
1060         data.exception.address = thread->context->ctl.arm_regs.pc;
1061         break;
1062     case CPU_ARM64:
1063         data.exception.address = thread->context->ctl.arm64_regs.pc;
1064         break;
1065     }
1066     generate_debug_event( thread, EXCEPTION_DEBUG_EVENT, &data );
1067     thread->debug_break = 0;
1068 }
1069
1070 /* take a snapshot of currently running threads */
1071 struct thread_snapshot *thread_snap( int *count )
1072 {
1073     struct thread_snapshot *snapshot, *ptr;
1074     struct thread *thread;
1075     int total = 0;
1076
1077     LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
1078         if (thread->state != TERMINATED) total++;
1079     if (!total || !(snapshot = mem_alloc( sizeof(*snapshot) * total ))) return NULL;
1080     ptr = snapshot;
1081     LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
1082     {
1083         if (thread->state == TERMINATED) continue;
1084         ptr->thread   = thread;
1085         ptr->count    = thread->obj.refcount;
1086         ptr->priority = thread->priority;
1087         grab_object( thread );
1088         ptr++;
1089     }
1090     *count = total;
1091     return snapshot;
1092 }
1093
1094 /* gets the current impersonation token */
1095 struct token *thread_get_impersonation_token( struct thread *thread )
1096 {
1097     if (thread->token)
1098         return thread->token;
1099     else
1100         return thread->process->token;
1101 }
1102
1103 /* create a new thread */
1104 DECL_HANDLER(new_thread)
1105 {
1106     struct thread *thread;
1107     int request_fd = thread_get_inflight_fd( current, req->request_fd );
1108
1109     if (request_fd == -1 || fcntl( request_fd, F_SETFL, O_NONBLOCK ) == -1)
1110     {
1111         if (request_fd != -1) close( request_fd );
1112         set_error( STATUS_INVALID_HANDLE );
1113         return;
1114     }
1115
1116     if ((thread = create_thread( request_fd, current->process )))
1117     {
1118         if (req->suspend) thread->suspend++;
1119         reply->tid = get_thread_id( thread );
1120         if ((reply->handle = alloc_handle( current->process, thread, req->access, req->attributes )))
1121         {
1122             /* thread object will be released when the thread gets killed */
1123             return;
1124         }
1125         kill_thread( thread, 1 );
1126     }
1127 }
1128
1129 /* initialize a new thread */
1130 DECL_HANDLER(init_thread)
1131 {
1132     unsigned int prefix_cpu_mask = get_prefix_cpu_mask();
1133     struct process *process = current->process;
1134     int wait_fd, reply_fd;
1135
1136     if ((reply_fd = thread_get_inflight_fd( current, req->reply_fd )) == -1)
1137     {
1138         set_error( STATUS_TOO_MANY_OPENED_FILES );
1139         return;
1140     }
1141     if ((wait_fd = thread_get_inflight_fd( current, req->wait_fd )) == -1)
1142     {
1143         set_error( STATUS_TOO_MANY_OPENED_FILES );
1144         goto error;
1145     }
1146
1147     if (current->reply_fd)  /* already initialised */
1148     {
1149         set_error( STATUS_INVALID_PARAMETER );
1150         goto error;
1151     }
1152
1153     if (fcntl( reply_fd, F_SETFL, O_NONBLOCK ) == -1) goto error;
1154
1155     current->reply_fd = create_anonymous_fd( &thread_fd_ops, reply_fd, &current->obj, 0 );
1156     current->wait_fd  = create_anonymous_fd( &thread_fd_ops, wait_fd, &current->obj, 0 );
1157     if (!current->reply_fd || !current->wait_fd) return;
1158
1159     if (!is_valid_address(req->teb))
1160     {
1161         set_error( STATUS_INVALID_PARAMETER );
1162         return;
1163     }
1164
1165     current->unix_pid = req->unix_pid;
1166     current->unix_tid = req->unix_tid;
1167     current->teb      = req->teb;
1168
1169     if (!process->peb)  /* first thread, initialize the process too */
1170     {
1171         if (!CPU_FLAG(req->cpu) || !(supported_cpus & prefix_cpu_mask & CPU_FLAG(req->cpu)))
1172         {
1173             if (!(supported_cpus & CPU_64BIT_MASK))
1174                 set_error( STATUS_NOT_SUPPORTED );
1175             else
1176                 set_error( STATUS_NOT_REGISTRY_FILE );  /* server supports it but not the prefix */
1177             return;
1178         }
1179         process->unix_pid = current->unix_pid;
1180         process->peb      = req->entry;
1181         process->cpu      = req->cpu;
1182         reply->info_size  = init_process( current );
1183         if (!process->parent)
1184             process->affinity = current->affinity = get_thread_affinity( current );
1185         else
1186             set_thread_affinity( current, current->affinity );
1187     }
1188     else
1189     {
1190         if (req->cpu != process->cpu)
1191         {
1192             set_error( STATUS_INVALID_PARAMETER );
1193             return;
1194         }
1195         if (process->unix_pid != current->unix_pid)
1196             process->unix_pid = -1;  /* can happen with linuxthreads */
1197         stop_thread_if_suspended( current );
1198         generate_debug_event( current, CREATE_THREAD_DEBUG_EVENT, &req->entry );
1199         set_thread_affinity( current, current->affinity );
1200     }
1201     debug_level = max( debug_level, req->debug_level );
1202
1203     reply->pid     = get_process_id( process );
1204     reply->tid     = get_thread_id( current );
1205     reply->version = SERVER_PROTOCOL_VERSION;
1206     reply->server_start = server_start_time;
1207     reply->all_cpus     = supported_cpus & prefix_cpu_mask;
1208     return;
1209
1210  error:
1211     if (reply_fd != -1) close( reply_fd );
1212     if (wait_fd != -1) close( wait_fd );
1213 }
1214
1215 /* terminate a thread */
1216 DECL_HANDLER(terminate_thread)
1217 {
1218     struct thread *thread;
1219
1220     reply->self = 0;
1221     reply->last = 0;
1222     if ((thread = get_thread_from_handle( req->handle, THREAD_TERMINATE )))
1223     {
1224         thread->exit_code = req->exit_code;
1225         if (thread != current) kill_thread( thread, 1 );
1226         else
1227         {
1228             reply->self = 1;
1229             reply->last = (thread->process->running_threads == 1);
1230         }
1231         release_object( thread );
1232     }
1233 }
1234
1235 /* open a handle to a thread */
1236 DECL_HANDLER(open_thread)
1237 {
1238     struct thread *thread = get_thread_from_id( req->tid );
1239
1240     reply->handle = 0;
1241     if (thread)
1242     {
1243         reply->handle = alloc_handle( current->process, thread, req->access, req->attributes );
1244         release_object( thread );
1245     }
1246 }
1247
1248 /* fetch information about a thread */
1249 DECL_HANDLER(get_thread_info)
1250 {
1251     struct thread *thread;
1252     obj_handle_t handle = req->handle;
1253
1254     if (!handle) thread = get_thread_from_id( req->tid_in );
1255     else thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION );
1256
1257     if (thread)
1258     {
1259         reply->pid            = get_process_id( thread->process );
1260         reply->tid            = get_thread_id( thread );
1261         reply->teb            = thread->teb;
1262         reply->exit_code      = (thread->state == TERMINATED) ? thread->exit_code : STATUS_PENDING;
1263         reply->priority       = thread->priority;
1264         reply->affinity       = thread->affinity;
1265         reply->creation_time  = thread->creation_time;
1266         reply->exit_time      = thread->exit_time;
1267         reply->last           = thread->process->running_threads == 1;
1268
1269         release_object( thread );
1270     }
1271 }
1272
1273 /* set information about a thread */
1274 DECL_HANDLER(set_thread_info)
1275 {
1276     struct thread *thread;
1277
1278     if ((thread = get_thread_from_handle( req->handle, THREAD_SET_INFORMATION )))
1279     {
1280         set_thread_info( thread, req );
1281         release_object( thread );
1282     }
1283 }
1284
1285 /* suspend a thread */
1286 DECL_HANDLER(suspend_thread)
1287 {
1288     struct thread *thread;
1289
1290     if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
1291     {
1292         if (thread->state == TERMINATED) set_error( STATUS_ACCESS_DENIED );
1293         else reply->count = suspend_thread( thread );
1294         release_object( thread );
1295     }
1296 }
1297
1298 /* resume a thread */
1299 DECL_HANDLER(resume_thread)
1300 {
1301     struct thread *thread;
1302
1303     if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
1304     {
1305         reply->count = resume_thread( thread );
1306         release_object( thread );
1307     }
1308 }
1309
1310 /* select on a handle list */
1311 DECL_HANDLER(select)
1312 {
1313     struct thread_apc *apc;
1314     unsigned int count;
1315     const apc_result_t *result = get_req_data();
1316     const obj_handle_t *handles = (const obj_handle_t *)(result + 1);
1317
1318     if (get_req_data_size() < sizeof(*result))
1319     {
1320         set_error( STATUS_INVALID_PARAMETER );
1321         return;
1322     }
1323     count = (get_req_data_size() - sizeof(*result)) / sizeof(obj_handle_t);
1324
1325     /* first store results of previous apc */
1326     if (req->prev_apc)
1327     {
1328         if (!(apc = (struct thread_apc *)get_handle_obj( current->process, req->prev_apc,
1329                                                          0, &thread_apc_ops ))) return;
1330         apc->result = *result;
1331         apc->executed = 1;
1332         if (apc->result.type == APC_CREATE_THREAD)  /* transfer the handle to the caller process */
1333         {
1334             obj_handle_t handle = duplicate_handle( current->process, apc->result.create_thread.handle,
1335                                                     apc->caller->process, 0, 0, DUP_HANDLE_SAME_ACCESS );
1336             close_handle( current->process, apc->result.create_thread.handle );
1337             apc->result.create_thread.handle = handle;
1338             clear_error();  /* ignore errors from the above calls */
1339         }
1340         else if (apc->result.type == APC_ASYNC_IO)
1341         {
1342             if (apc->owner)
1343                 async_set_result( apc->owner, apc->result.async_io.status,
1344                                   apc->result.async_io.total, apc->result.async_io.apc );
1345         }
1346         wake_up( &apc->obj, 0 );
1347         close_handle( current->process, req->prev_apc );
1348         release_object( apc );
1349     }
1350
1351     reply->timeout = select_on( count, req->cookie, handles, req->flags, req->timeout, req->signal );
1352
1353     if (get_error() == STATUS_USER_APC)
1354     {
1355         for (;;)
1356         {
1357             if (!(apc = thread_dequeue_apc( current, !(req->flags & SELECT_ALERTABLE) )))
1358                 break;
1359             /* Optimization: ignore APC_NONE calls, they are only used to
1360              * wake up a thread, but since we got here the thread woke up already.
1361              */
1362             if (apc->call.type != APC_NONE)
1363             {
1364                 if ((reply->apc_handle = alloc_handle( current->process, apc, SYNCHRONIZE, 0 )))
1365                     reply->call = apc->call;
1366                 release_object( apc );
1367                 break;
1368             }
1369             apc->executed = 1;
1370             wake_up( &apc->obj, 0 );
1371             release_object( apc );
1372         }
1373     }
1374 }
1375
1376 /* queue an APC for a thread or process */
1377 DECL_HANDLER(queue_apc)
1378 {
1379     struct thread *thread = NULL;
1380     struct process *process = NULL;
1381     struct thread_apc *apc;
1382
1383     if (!(apc = create_apc( NULL, &req->call ))) return;
1384
1385     switch (apc->call.type)
1386     {
1387     case APC_NONE:
1388     case APC_USER:
1389         thread = get_thread_from_handle( req->handle, THREAD_SET_CONTEXT );
1390         break;
1391     case APC_VIRTUAL_ALLOC:
1392     case APC_VIRTUAL_FREE:
1393     case APC_VIRTUAL_PROTECT:
1394     case APC_VIRTUAL_FLUSH:
1395     case APC_VIRTUAL_LOCK:
1396     case APC_VIRTUAL_UNLOCK:
1397     case APC_UNMAP_VIEW:
1398         process = get_process_from_handle( req->handle, PROCESS_VM_OPERATION );
1399         break;
1400     case APC_VIRTUAL_QUERY:
1401         process = get_process_from_handle( req->handle, PROCESS_QUERY_INFORMATION );
1402         break;
1403     case APC_MAP_VIEW:
1404         process = get_process_from_handle( req->handle, PROCESS_VM_OPERATION );
1405         if (process && process != current->process)
1406         {
1407             /* duplicate the handle into the target process */
1408             obj_handle_t handle = duplicate_handle( current->process, apc->call.map_view.handle,
1409                                                     process, 0, 0, DUP_HANDLE_SAME_ACCESS );
1410             if (handle) apc->call.map_view.handle = handle;
1411             else
1412             {
1413                 release_object( process );
1414                 process = NULL;
1415             }
1416         }
1417         break;
1418     case APC_CREATE_THREAD:
1419         process = get_process_from_handle( req->handle, PROCESS_CREATE_THREAD );
1420         break;
1421     default:
1422         set_error( STATUS_INVALID_PARAMETER );
1423         break;
1424     }
1425
1426     if (thread)
1427     {
1428         if (!queue_apc( NULL, thread, apc )) set_error( STATUS_THREAD_IS_TERMINATING );
1429         release_object( thread );
1430     }
1431     else if (process)
1432     {
1433         reply->self = (process == current->process);
1434         if (!reply->self)
1435         {
1436             obj_handle_t handle = alloc_handle( current->process, apc, SYNCHRONIZE, 0 );
1437             if (handle)
1438             {
1439                 if (queue_apc( process, NULL, apc ))
1440                 {
1441                     apc->caller = (struct thread *)grab_object( current );
1442                     reply->handle = handle;
1443                 }
1444                 else
1445                 {
1446                     close_handle( current->process, handle );
1447                     set_error( STATUS_PROCESS_IS_TERMINATING );
1448                 }
1449             }
1450         }
1451         release_object( process );
1452     }
1453
1454     release_object( apc );
1455 }
1456
1457 /* Get the result of an APC call */
1458 DECL_HANDLER(get_apc_result)
1459 {
1460     struct thread_apc *apc;
1461
1462     if (!(apc = (struct thread_apc *)get_handle_obj( current->process, req->handle,
1463                                                      0, &thread_apc_ops ))) return;
1464     if (!apc->executed) set_error( STATUS_PENDING );
1465     else
1466     {
1467         reply->result = apc->result;
1468         /* close the handle directly to avoid an extra round-trip */
1469         close_handle( current->process, req->handle );
1470     }
1471     release_object( apc );
1472 }
1473
1474 /* retrieve the current context of a thread */
1475 DECL_HANDLER(get_thread_context)
1476 {
1477     struct thread *thread;
1478     context_t *context;
1479
1480     if (get_reply_max_size() < sizeof(context_t))
1481     {
1482         set_error( STATUS_INVALID_PARAMETER );
1483         return;
1484     }
1485     if (!(thread = get_thread_from_handle( req->handle, THREAD_GET_CONTEXT ))) return;
1486     reply->self = (thread == current);
1487
1488     if (thread != current && !thread->context)
1489     {
1490         /* thread is not suspended, retry (if it's still running) */
1491         if (thread->state == RUNNING)
1492         {
1493             set_error( STATUS_PENDING );
1494             if (req->suspend)
1495             {
1496                 release_object( thread );
1497                 /* make sure we have suspend access */
1498                 if (!(thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME ))) return;
1499                 suspend_thread( thread );
1500             }
1501         }
1502         else set_error( STATUS_UNSUCCESSFUL );
1503     }
1504     else if ((context = set_reply_data_size( sizeof(context_t) )))
1505     {
1506         unsigned int flags = get_context_system_regs( thread->process->cpu );
1507
1508         memset( context, 0, sizeof(context_t) );
1509         context->cpu = thread->process->cpu;
1510         if (thread->context) copy_context( context, thread->context, req->flags & ~flags );
1511         if (flags) get_thread_context( thread, context, flags );
1512     }
1513     release_object( thread );
1514 }
1515
1516 /* set the current context of a thread */
1517 DECL_HANDLER(set_thread_context)
1518 {
1519     struct thread *thread;
1520     const context_t *context = get_req_data();
1521
1522     if (get_req_data_size() < sizeof(context_t))
1523     {
1524         set_error( STATUS_INVALID_PARAMETER );
1525         return;
1526     }
1527     if (!(thread = get_thread_from_handle( req->handle, THREAD_SET_CONTEXT ))) return;
1528     reply->self = (thread == current);
1529
1530     if (thread != current && !thread->context)
1531     {
1532         /* thread is not suspended, retry (if it's still running) */
1533         if (thread->state == RUNNING)
1534         {
1535             set_error( STATUS_PENDING );
1536             if (req->suspend)
1537             {
1538                 release_object( thread );
1539                 /* make sure we have suspend access */
1540                 if (!(thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME ))) return;
1541                 suspend_thread( thread );
1542             }
1543         }
1544         else set_error( STATUS_UNSUCCESSFUL );
1545     }
1546     else if (context->cpu == thread->process->cpu)
1547     {
1548         unsigned int system_flags = get_context_system_regs(context->cpu) & context->flags;
1549         unsigned int client_flags = context->flags & ~system_flags;
1550
1551         if (system_flags) set_thread_context( thread, context, system_flags );
1552         if (thread->context && !get_error()) copy_context( thread->context, context, client_flags );
1553     }
1554     else set_error( STATUS_INVALID_PARAMETER );
1555
1556     release_object( thread );
1557 }
1558
1559 /* retrieve the suspended context of a thread */
1560 DECL_HANDLER(get_suspend_context)
1561 {
1562     if (get_reply_max_size() < sizeof(context_t))
1563     {
1564         set_error( STATUS_INVALID_PARAMETER );
1565         return;
1566     }
1567
1568     if (current->suspend_context)
1569     {
1570         set_reply_data_ptr( current->suspend_context, sizeof(context_t) );
1571         if (current->context == current->suspend_context)
1572         {
1573             current->context = NULL;
1574             stop_thread_if_suspended( current );
1575         }
1576         current->suspend_context = NULL;
1577     }
1578     else set_error( STATUS_INVALID_PARAMETER );  /* not suspended, shouldn't happen */
1579 }
1580
1581 /* store the suspended context of a thread */
1582 DECL_HANDLER(set_suspend_context)
1583 {
1584     const context_t *context = get_req_data();
1585
1586     if (get_req_data_size() < sizeof(context_t))
1587     {
1588         set_error( STATUS_INVALID_PARAMETER );
1589         return;
1590     }
1591
1592     if (current->context || context->cpu != current->process->cpu)
1593     {
1594         /* nested suspend or exception, shouldn't happen */
1595         set_error( STATUS_INVALID_PARAMETER );
1596     }
1597     else if ((current->suspend_context = mem_alloc( sizeof(context_t) )))
1598     {
1599         memcpy( current->suspend_context, get_req_data(), sizeof(context_t) );
1600         current->context = current->suspend_context;
1601         if (current->debug_break) break_thread( current );
1602     }
1603 }
1604
1605 /* fetch a selector entry for a thread */
1606 DECL_HANDLER(get_selector_entry)
1607 {
1608     struct thread *thread;
1609     if ((thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION )))
1610     {
1611         get_selector_entry( thread, req->entry, &reply->base, &reply->limit, &reply->flags );
1612         release_object( thread );
1613     }
1614 }