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