server: Added mechanism for returning results of APC calls.
[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
39 #include "ntstatus.h"
40 #define WIN32_NO_STATUS
41 #include "windef.h"
42 #include "winternl.h"
43
44 #include "file.h"
45 #include "handle.h"
46 #include "process.h"
47 #include "thread.h"
48 #include "request.h"
49 #include "user.h"
50 #include "security.h"
51
52
53 /* thread queues */
54
55 struct thread_wait
56 {
57     struct thread_wait     *next;       /* next wait structure for this thread */
58     struct thread          *thread;     /* owner thread */
59     int                     count;      /* count of objects */
60     int                     flags;
61     void                   *cookie;     /* magic cookie to return to client */
62     struct timeval          timeout;
63     struct timeout_user    *user;
64     struct wait_queue_entry queues[1];
65 };
66
67 /* asynchronous procedure calls */
68
69 struct thread_apc
70 {
71     struct object       obj;      /* object header */
72     struct list         entry;    /* queue linked list */
73     struct object      *owner;    /* object that queued this apc */
74     int                 executed; /* has it been executed by the client? */
75     apc_call_t          call;     /* call arguments */
76     apc_result_t        result;   /* call results once executed */
77 };
78
79 static void dump_thread_apc( struct object *obj, int verbose );
80 static int thread_apc_signaled( struct object *obj, struct thread *thread );
81 static void clear_apc_queue( struct list *queue );
82
83 static const struct object_ops thread_apc_ops =
84 {
85     sizeof(struct thread_apc),  /* size */
86     dump_thread_apc,            /* dump */
87     add_queue,                  /* add_queue */
88     remove_queue,               /* remove_queue */
89     thread_apc_signaled,        /* signaled */
90     no_satisfied,               /* satisfied */
91     no_signal,                  /* signal */
92     no_get_fd,                  /* get_fd */
93     no_map_access,              /* map_access */
94     no_lookup_name,             /* lookup_name */
95     no_close_handle,            /* close_handle */
96     no_destroy                  /* destroy */
97 };
98
99
100 /* thread operations */
101
102 static void dump_thread( struct object *obj, int verbose );
103 static int thread_signaled( struct object *obj, struct thread *thread );
104 static unsigned int thread_map_access( struct object *obj, unsigned int access );
105 static void thread_poll_event( struct fd *fd, int event );
106 static void destroy_thread( struct object *obj );
107
108 static const struct object_ops thread_ops =
109 {
110     sizeof(struct thread),      /* size */
111     dump_thread,                /* dump */
112     add_queue,                  /* add_queue */
113     remove_queue,               /* remove_queue */
114     thread_signaled,            /* signaled */
115     no_satisfied,               /* satisfied */
116     no_signal,                  /* signal */
117     no_get_fd,                  /* get_fd */
118     thread_map_access,          /* map_access */
119     no_lookup_name,             /* lookup_name */
120     no_close_handle,            /* close_handle */
121     destroy_thread              /* destroy */
122 };
123
124 static const struct fd_ops thread_fd_ops =
125 {
126     NULL,                       /* get_poll_events */
127     thread_poll_event,          /* poll_event */
128     no_flush,                   /* flush */
129     no_get_file_info,           /* get_file_info */
130     no_queue_async,             /* queue_async */
131     no_cancel_async             /* cancel_async */
132 };
133
134 static struct list thread_list = LIST_INIT(thread_list);
135
136 /* initialize the structure for a newly allocated thread */
137 inline static void init_thread_structure( struct thread *thread )
138 {
139     int i;
140
141     thread->unix_pid        = -1;  /* not known yet */
142     thread->unix_tid        = -1;  /* not known yet */
143     thread->context         = NULL;
144     thread->suspend_context = NULL;
145     thread->teb             = NULL;
146     thread->debug_ctx       = NULL;
147     thread->debug_event     = NULL;
148     thread->debug_break     = 0;
149     thread->queue           = NULL;
150     thread->wait            = NULL;
151     thread->error           = 0;
152     thread->req_data        = NULL;
153     thread->req_toread      = 0;
154     thread->reply_data      = NULL;
155     thread->reply_towrite   = 0;
156     thread->request_fd      = NULL;
157     thread->reply_fd        = NULL;
158     thread->wait_fd         = NULL;
159     thread->state           = RUNNING;
160     thread->exit_code       = 0;
161     thread->priority        = 0;
162     thread->affinity        = 1;
163     thread->suspend         = 0;
164     thread->desktop_users   = 0;
165     thread->token           = NULL;
166
167     thread->creation_time = current_time;
168     thread->exit_time.tv_sec = thread->exit_time.tv_usec = 0;
169
170     list_init( &thread->mutex_list );
171     list_init( &thread->system_apc );
172     list_init( &thread->user_apc );
173
174     for (i = 0; i < MAX_INFLIGHT_FDS; i++)
175         thread->inflight[i].server = thread->inflight[i].client = -1;
176 }
177
178 /* check if address looks valid for a client-side data structure (TEB etc.) */
179 static inline int is_valid_address( void *addr )
180 {
181     return addr && !((unsigned long)addr % sizeof(int));
182 }
183
184 /* create a new thread */
185 struct thread *create_thread( int fd, struct process *process )
186 {
187     struct thread *thread;
188
189     if (!(thread = alloc_object( &thread_ops ))) return NULL;
190
191     init_thread_structure( thread );
192
193     thread->process = (struct process *)grab_object( process );
194     thread->desktop = process->desktop;
195     if (!current) current = thread;
196
197     list_add_head( &thread_list, &thread->entry );
198
199     if (!(thread->id = alloc_ptid( thread )))
200     {
201         release_object( thread );
202         return NULL;
203     }
204     if (!(thread->request_fd = create_anonymous_fd( &thread_fd_ops, fd, &thread->obj )))
205     {
206         release_object( thread );
207         return NULL;
208     }
209
210     set_fd_events( thread->request_fd, POLLIN );  /* start listening to events */
211     add_process_thread( thread->process, thread );
212     return thread;
213 }
214
215 /* handle a client event */
216 static void thread_poll_event( struct fd *fd, int event )
217 {
218     struct thread *thread = get_fd_user( fd );
219     assert( thread->obj.ops == &thread_ops );
220
221     if (event & (POLLERR | POLLHUP)) kill_thread( thread, 0 );
222     else if (event & POLLIN) read_request( thread );
223     else if (event & POLLOUT) write_reply( thread );
224 }
225
226 /* cleanup everything that is no longer needed by a dead thread */
227 /* used by destroy_thread and kill_thread */
228 static void cleanup_thread( struct thread *thread )
229 {
230     int i;
231
232     clear_apc_queue( &thread->system_apc );
233     clear_apc_queue( &thread->user_apc );
234     free( thread->req_data );
235     free( thread->reply_data );
236     if (thread->request_fd) release_object( thread->request_fd );
237     if (thread->reply_fd) release_object( thread->reply_fd );
238     if (thread->wait_fd) release_object( thread->wait_fd );
239     free( thread->suspend_context );
240     free_msg_queue( thread );
241     cleanup_clipboard_thread(thread);
242     destroy_thread_windows( thread );
243     close_thread_desktop( thread );
244     for (i = 0; i < MAX_INFLIGHT_FDS; i++)
245     {
246         if (thread->inflight[i].client != -1)
247         {
248             close( thread->inflight[i].server );
249             thread->inflight[i].client = thread->inflight[i].server = -1;
250         }
251     }
252     thread->req_data = NULL;
253     thread->reply_data = NULL;
254     thread->request_fd = NULL;
255     thread->reply_fd = NULL;
256     thread->wait_fd = NULL;
257     thread->context = NULL;
258     thread->suspend_context = NULL;
259     thread->desktop = 0;
260 }
261
262 /* destroy a thread when its refcount is 0 */
263 static void destroy_thread( struct object *obj )
264 {
265     struct thread *thread = (struct thread *)obj;
266     assert( obj->ops == &thread_ops );
267
268     assert( !thread->debug_ctx );  /* cannot still be debugging something */
269     list_remove( &thread->entry );
270     cleanup_thread( thread );
271     release_object( thread->process );
272     if (thread->id) free_ptid( thread->id );
273     if (thread->token) release_object( thread->token );
274 }
275
276 /* dump a thread on stdout for debugging purposes */
277 static void dump_thread( struct object *obj, int verbose )
278 {
279     struct thread *thread = (struct thread *)obj;
280     assert( obj->ops == &thread_ops );
281
282     fprintf( stderr, "Thread id=%04x unix pid=%d unix tid=%d teb=%p state=%d\n",
283              thread->id, thread->unix_pid, thread->unix_tid, thread->teb, thread->state );
284 }
285
286 static int thread_signaled( struct object *obj, struct thread *thread )
287 {
288     struct thread *mythread = (struct thread *)obj;
289     return (mythread->state == TERMINATED);
290 }
291
292 static unsigned int thread_map_access( struct object *obj, unsigned int access )
293 {
294     if (access & GENERIC_READ)    access |= STANDARD_RIGHTS_READ | SYNCHRONIZE;
295     if (access & GENERIC_WRITE)   access |= STANDARD_RIGHTS_WRITE | SYNCHRONIZE;
296     if (access & GENERIC_EXECUTE) access |= STANDARD_RIGHTS_EXECUTE;
297     if (access & GENERIC_ALL)     access |= THREAD_ALL_ACCESS;
298     return access & ~(GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE | GENERIC_ALL);
299 }
300
301 static void dump_thread_apc( struct object *obj, int verbose )
302 {
303     struct thread_apc *apc = (struct thread_apc *)obj;
304     assert( obj->ops == &thread_apc_ops );
305
306     fprintf( stderr, "APC owner=%p type=%u\n", apc->owner, apc->call.type );
307 }
308
309 static int thread_apc_signaled( struct object *obj, struct thread *thread )
310 {
311     struct thread_apc *apc = (struct thread_apc *)obj;
312     return apc->executed;
313 }
314
315 /* get a thread pointer from a thread id (and increment the refcount) */
316 struct thread *get_thread_from_id( thread_id_t id )
317 {
318     struct object *obj = get_ptid_entry( id );
319
320     if (obj && obj->ops == &thread_ops) return (struct thread *)grab_object( obj );
321     set_error( STATUS_INVALID_CID );
322     return NULL;
323 }
324
325 /* get a thread from a handle (and increment the refcount) */
326 struct thread *get_thread_from_handle( obj_handle_t handle, unsigned int access )
327 {
328     return (struct thread *)get_handle_obj( current->process, handle,
329                                             access, &thread_ops );
330 }
331
332 /* find a thread from a Unix tid */
333 struct thread *get_thread_from_tid( int tid )
334 {
335     struct thread *thread;
336
337     LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
338     {
339         if (thread->unix_tid == tid) return thread;
340     }
341     return NULL;
342 }
343
344 /* find a thread from a Unix pid */
345 struct thread *get_thread_from_pid( int pid )
346 {
347     struct thread *thread;
348
349     LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
350     {
351         if (thread->unix_pid == pid) return thread;
352     }
353     return NULL;
354 }
355
356 /* set all information about a thread */
357 static void set_thread_info( struct thread *thread,
358                              const struct set_thread_info_request *req )
359 {
360     if (req->mask & SET_THREAD_INFO_PRIORITY)
361         thread->priority = req->priority;
362     if (req->mask & SET_THREAD_INFO_AFFINITY)
363     {
364         if (req->affinity != 1) set_error( STATUS_INVALID_PARAMETER );
365         else thread->affinity = req->affinity;
366     }
367     if (req->mask & SET_THREAD_INFO_TOKEN)
368         security_set_thread_token( thread, req->token );
369 }
370
371 /* stop a thread (at the Unix level) */
372 void stop_thread( struct thread *thread )
373 {
374     if (thread->context) return;  /* already inside a debug event, no need for a signal */
375     /* can't stop a thread while initialisation is in progress */
376     if (is_process_init_done(thread->process)) send_thread_signal( thread, SIGUSR1 );
377 }
378
379 /* suspend a thread */
380 static int suspend_thread( struct thread *thread )
381 {
382     int old_count = thread->suspend;
383     if (thread->suspend < MAXIMUM_SUSPEND_COUNT)
384     {
385         if (!(thread->process->suspend + thread->suspend++)) stop_thread( thread );
386     }
387     else set_error( STATUS_SUSPEND_COUNT_EXCEEDED );
388     return old_count;
389 }
390
391 /* resume a thread */
392 static int resume_thread( struct thread *thread )
393 {
394     int old_count = thread->suspend;
395     if (thread->suspend > 0)
396     {
397         if (!(--thread->suspend + thread->process->suspend)) wake_thread( thread );
398     }
399     return old_count;
400 }
401
402 /* add a thread to an object wait queue; return 1 if OK, 0 on error */
403 int add_queue( struct object *obj, struct wait_queue_entry *entry )
404 {
405     grab_object( obj );
406     entry->obj = obj;
407     list_add_tail( &obj->wait_queue, &entry->entry );
408     return 1;
409 }
410
411 /* remove a thread from an object wait queue */
412 void remove_queue( struct object *obj, struct wait_queue_entry *entry )
413 {
414     list_remove( &entry->entry );
415     release_object( obj );
416 }
417
418 /* finish waiting */
419 static void end_wait( struct thread *thread )
420 {
421     struct thread_wait *wait = thread->wait;
422     struct wait_queue_entry *entry;
423     int i;
424
425     assert( wait );
426     for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
427         entry->obj->ops->remove_queue( entry->obj, entry );
428     if (wait->user) remove_timeout_user( wait->user );
429     thread->wait = wait->next;
430     free( wait );
431 }
432
433 /* build the thread wait structure */
434 static int wait_on( int count, struct object *objects[], int flags, const abs_time_t *timeout )
435 {
436     struct thread_wait *wait;
437     struct wait_queue_entry *entry;
438     int i;
439
440     if (!(wait = mem_alloc( sizeof(*wait) + (count-1) * sizeof(*entry) ))) return 0;
441     wait->next    = current->wait;
442     wait->thread  = current;
443     wait->count   = count;
444     wait->flags   = flags;
445     wait->user    = NULL;
446     current->wait = wait;
447     if (flags & SELECT_TIMEOUT)
448     {
449         wait->timeout.tv_sec  = timeout->sec;
450         wait->timeout.tv_usec = timeout->usec;
451     }
452
453     for (i = 0, entry = wait->queues; i < count; i++, entry++)
454     {
455         struct object *obj = objects[i];
456         entry->thread = current;
457         if (!obj->ops->add_queue( obj, entry ))
458         {
459             wait->count = i;
460             end_wait( current );
461             return 0;
462         }
463     }
464     return 1;
465 }
466
467 /* check if the thread waiting condition is satisfied */
468 static int check_wait( struct thread *thread )
469 {
470     int i, signaled;
471     struct thread_wait *wait = thread->wait;
472     struct wait_queue_entry *entry = wait->queues;
473
474     /* Suspended threads may not acquire locks, but they can run system APCs */
475     if (thread->process->suspend + thread->suspend > 0)
476     {
477         if ((wait->flags & SELECT_INTERRUPTIBLE) && !list_empty( &thread->system_apc ))
478             return STATUS_USER_APC;
479         return -1;
480     }
481
482     assert( wait );
483     if (wait->flags & SELECT_ALL)
484     {
485         int not_ok = 0;
486         /* Note: we must check them all anyway, as some objects may
487          * want to do something when signaled, even if others are not */
488         for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
489             not_ok |= !entry->obj->ops->signaled( entry->obj, thread );
490         if (not_ok) goto other_checks;
491         /* Wait satisfied: tell it to all objects */
492         signaled = 0;
493         for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
494             if (entry->obj->ops->satisfied( entry->obj, thread ))
495                 signaled = STATUS_ABANDONED_WAIT_0;
496         return signaled;
497     }
498     else
499     {
500         for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
501         {
502             if (!entry->obj->ops->signaled( entry->obj, thread )) continue;
503             /* Wait satisfied: tell it to the object */
504             signaled = i;
505             if (entry->obj->ops->satisfied( entry->obj, thread ))
506                 signaled = i + STATUS_ABANDONED_WAIT_0;
507             return signaled;
508         }
509     }
510
511  other_checks:
512     if ((wait->flags & SELECT_INTERRUPTIBLE) && !list_empty(&thread->system_apc)) return STATUS_USER_APC;
513     if ((wait->flags & SELECT_ALERTABLE) && !list_empty(&thread->user_apc)) return STATUS_USER_APC;
514     if (wait->flags & SELECT_TIMEOUT)
515     {
516         if (!time_before( &current_time, &wait->timeout )) return STATUS_TIMEOUT;
517     }
518     return -1;
519 }
520
521 /* send the wakeup signal to a thread */
522 static int send_thread_wakeup( struct thread *thread, void *cookie, int signaled )
523 {
524     struct wake_up_reply reply;
525     int ret;
526
527     reply.cookie   = cookie;
528     reply.signaled = signaled;
529     if ((ret = write( get_unix_fd( thread->wait_fd ), &reply, sizeof(reply) )) == sizeof(reply))
530         return 0;
531     if (ret >= 0)
532         fatal_protocol_error( thread, "partial wakeup write %d\n", ret );
533     else if (errno == EPIPE)
534         kill_thread( thread, 0 );  /* normal death */
535     else
536         fatal_protocol_perror( thread, "write" );
537     return -1;
538 }
539
540 /* attempt to wake up a thread */
541 /* return >0 if OK, 0 if the wait condition is still not satisfied */
542 int wake_thread( struct thread *thread )
543 {
544     int signaled, count;
545     void *cookie;
546
547     for (count = 0; thread->wait; count++)
548     {
549         if ((signaled = check_wait( thread )) == -1) break;
550
551         cookie = thread->wait->cookie;
552         if (debug_level) fprintf( stderr, "%04x: *wakeup* signaled=%d cookie=%p\n",
553                                   thread->id, signaled, cookie );
554         end_wait( thread );
555         if (send_thread_wakeup( thread, cookie, signaled ) == -1) /* error */
556             break;
557     }
558     return count;
559 }
560
561 /* thread wait timeout */
562 static void thread_timeout( void *ptr )
563 {
564     struct thread_wait *wait = ptr;
565     struct thread *thread = wait->thread;
566     void *cookie = wait->cookie;
567
568     wait->user = NULL;
569     if (thread->wait != wait) return; /* not the top-level wait, ignore it */
570     if (thread->suspend + thread->process->suspend > 0) return;  /* suspended, ignore it */
571
572     if (debug_level) fprintf( stderr, "%04x: *wakeup* signaled=%d cookie=%p\n",
573                               thread->id, (int)STATUS_TIMEOUT, cookie );
574     end_wait( thread );
575     if (send_thread_wakeup( thread, cookie, STATUS_TIMEOUT ) == -1) return;
576     /* check if other objects have become signaled in the meantime */
577     wake_thread( thread );
578 }
579
580 /* try signaling an event flag, a semaphore or a mutex */
581 static int signal_object( obj_handle_t handle )
582 {
583     struct object *obj;
584     int ret = 0;
585
586     obj = get_handle_obj( current->process, handle, 0, NULL );
587     if (obj)
588     {
589         ret = obj->ops->signal( obj, get_handle_access( current->process, handle ));
590         release_object( obj );
591     }
592     return ret;
593 }
594
595 /* select on a list of handles */
596 static void select_on( int count, void *cookie, const obj_handle_t *handles,
597                        int flags, const abs_time_t *timeout, obj_handle_t signal_obj )
598 {
599     int ret, i;
600     struct object *objects[MAXIMUM_WAIT_OBJECTS];
601
602     if ((count < 0) || (count > MAXIMUM_WAIT_OBJECTS))
603     {
604         set_error( STATUS_INVALID_PARAMETER );
605         return;
606     }
607     for (i = 0; i < count; i++)
608     {
609         if (!(objects[i] = get_handle_obj( current->process, handles[i], SYNCHRONIZE, NULL )))
610             break;
611     }
612
613     if (i < count) goto done;
614     if (!wait_on( count, objects, flags, timeout )) goto done;
615
616     /* signal the object */
617     if (signal_obj)
618     {
619         if (!signal_object( signal_obj ))
620         {
621             end_wait( current );
622             goto done;
623         }
624         /* check if we woke ourselves up */
625         if (!current->wait) goto done;
626     }
627
628     if ((ret = check_wait( current )) != -1)
629     {
630         /* condition is already satisfied */
631         end_wait( current );
632         set_error( ret );
633         goto done;
634     }
635
636     /* now we need to wait */
637     if (flags & SELECT_TIMEOUT)
638     {
639         if (!(current->wait->user = add_timeout_user( &current->wait->timeout,
640                                                       thread_timeout, current->wait )))
641         {
642             end_wait( current );
643             goto done;
644         }
645     }
646     current->wait->cookie = cookie;
647     set_error( STATUS_PENDING );
648
649 done:
650     while (--i >= 0) release_object( objects[i] );
651 }
652
653 /* attempt to wake threads sleeping on the object wait queue */
654 void wake_up( struct object *obj, int max )
655 {
656     struct list *ptr, *next;
657
658     LIST_FOR_EACH_SAFE( ptr, next, &obj->wait_queue )
659     {
660         struct wait_queue_entry *entry = LIST_ENTRY( ptr, struct wait_queue_entry, entry );
661         if (wake_thread( entry->thread ))
662         {
663             if (max && !--max) break;
664         }
665     }
666 }
667
668 /* return the apc queue to use for a given apc type */
669 static inline struct list *get_apc_queue( struct thread *thread, enum apc_type type )
670 {
671     switch(type)
672     {
673     case APC_NONE:
674     case APC_USER:
675     case APC_TIMER:
676         return &thread->user_apc;
677     default:
678         return &thread->system_apc;
679     }
680 }
681
682 /* queue an async procedure call */
683 int thread_queue_apc( struct thread *thread, struct object *owner, const apc_call_t *call_data )
684 {
685     struct thread_apc *apc;
686     struct list *queue = get_apc_queue( thread, call_data->type );
687
688     /* cancel a possible previous APC with the same owner */
689     if (owner) thread_cancel_apc( thread, owner, call_data->type );
690     if (thread->state == TERMINATED) return 0;
691
692     if (!(apc = alloc_object( &thread_apc_ops ))) return 0;
693     apc->call     = *call_data;
694     apc->owner    = owner;
695     apc->executed = 0;
696     list_add_tail( queue, &apc->entry );
697     if (!list_prev( queue, &apc->entry ))  /* first one */
698         wake_thread( thread );
699
700     return 1;
701 }
702
703 /* cancel the async procedure call owned by a specific object */
704 void thread_cancel_apc( struct thread *thread, struct object *owner, enum apc_type type )
705 {
706     struct thread_apc *apc;
707     struct list *queue = get_apc_queue( thread, type );
708
709     LIST_FOR_EACH_ENTRY( apc, queue, struct thread_apc, entry )
710     {
711         if (apc->owner != owner) continue;
712         list_remove( &apc->entry );
713         apc->executed = 1;
714         wake_up( &apc->obj, 0 );
715         release_object( apc );
716         return;
717     }
718 }
719
720 /* remove the head apc from the queue; the returned object must be released by the caller */
721 static struct thread_apc *thread_dequeue_apc( struct thread *thread, int system_only )
722 {
723     struct thread_apc *apc = NULL;
724     struct list *ptr = list_head( &thread->system_apc );
725
726     if (!ptr && !system_only) ptr = list_head( &thread->user_apc );
727     if (ptr)
728     {
729         apc = LIST_ENTRY( ptr, struct thread_apc, entry );
730         list_remove( ptr );
731     }
732     return apc;
733 }
734
735 /* clear an APC queue, cancelling all the APCs on it */
736 static void clear_apc_queue( struct list *queue )
737 {
738     struct list *ptr;
739
740     while ((ptr = list_head( queue )))
741     {
742         struct thread_apc *apc = LIST_ENTRY( ptr, struct thread_apc, entry );
743         list_remove( &apc->entry );
744         apc->executed = 1;
745         wake_up( &apc->obj, 0 );
746         release_object( apc );
747     }
748 }
749
750 /* add an fd to the inflight list */
751 /* return list index, or -1 on error */
752 int thread_add_inflight_fd( struct thread *thread, int client, int server )
753 {
754     int i;
755
756     if (server == -1) return -1;
757     if (client == -1)
758     {
759         close( server );
760         return -1;
761     }
762
763     /* first check if we already have an entry for this fd */
764     for (i = 0; i < MAX_INFLIGHT_FDS; i++)
765         if (thread->inflight[i].client == client)
766         {
767             close( thread->inflight[i].server );
768             thread->inflight[i].server = server;
769             return i;
770         }
771
772     /* now find a free spot to store it */
773     for (i = 0; i < MAX_INFLIGHT_FDS; i++)
774         if (thread->inflight[i].client == -1)
775         {
776             thread->inflight[i].client = client;
777             thread->inflight[i].server = server;
778             return i;
779         }
780     return -1;
781 }
782
783 /* get an inflight fd and purge it from the list */
784 /* the fd must be closed when no longer used */
785 int thread_get_inflight_fd( struct thread *thread, int client )
786 {
787     int i, ret;
788
789     if (client == -1) return -1;
790
791     do
792     {
793         for (i = 0; i < MAX_INFLIGHT_FDS; i++)
794         {
795             if (thread->inflight[i].client == client)
796             {
797                 ret = thread->inflight[i].server;
798                 thread->inflight[i].server = thread->inflight[i].client = -1;
799                 return ret;
800             }
801         }
802     } while (!receive_fd( thread->process ));  /* in case it is still in the socket buffer */
803     return -1;
804 }
805
806 /* kill a thread on the spot */
807 void kill_thread( struct thread *thread, int violent_death )
808 {
809     if (thread->state == TERMINATED) return;  /* already killed */
810     thread->state = TERMINATED;
811     thread->exit_time = current_time;
812     if (current == thread) current = NULL;
813     if (debug_level)
814         fprintf( stderr,"%04x: *killed* exit_code=%d\n",
815                  thread->id, thread->exit_code );
816     if (thread->wait)
817     {
818         while (thread->wait) end_wait( thread );
819         send_thread_wakeup( thread, NULL, STATUS_PENDING );
820         /* if it is waiting on the socket, we don't need to send a SIGTERM */
821         violent_death = 0;
822     }
823     kill_console_processes( thread, 0 );
824     debug_exit_thread( thread );
825     abandon_mutexes( thread );
826     wake_up( &thread->obj, 0 );
827     if (violent_death) send_thread_signal( thread, SIGTERM );
828     cleanup_thread( thread );
829     remove_process_thread( thread->process, thread );
830     release_object( thread );
831 }
832
833 /* trigger a breakpoint event in a given thread */
834 void break_thread( struct thread *thread )
835 {
836     struct debug_event_exception data;
837
838     assert( thread->context );
839
840     data.record.ExceptionCode    = STATUS_BREAKPOINT;
841     data.record.ExceptionFlags   = EXCEPTION_CONTINUABLE;
842     data.record.ExceptionRecord  = NULL;
843     data.record.ExceptionAddress = get_context_ip( thread->context );
844     data.record.NumberParameters = 0;
845     data.first = 1;
846     generate_debug_event( thread, EXCEPTION_DEBUG_EVENT, &data );
847     thread->debug_break = 0;
848 }
849
850 /* take a snapshot of currently running threads */
851 struct thread_snapshot *thread_snap( int *count )
852 {
853     struct thread_snapshot *snapshot, *ptr;
854     struct thread *thread;
855     int total = 0;
856
857     LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
858         if (thread->state != TERMINATED) total++;
859     if (!total || !(snapshot = mem_alloc( sizeof(*snapshot) * total ))) return NULL;
860     ptr = snapshot;
861     LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
862     {
863         if (thread->state == TERMINATED) continue;
864         ptr->thread   = thread;
865         ptr->count    = thread->obj.refcount;
866         ptr->priority = thread->priority;
867         grab_object( thread );
868         ptr++;
869     }
870     *count = total;
871     return snapshot;
872 }
873
874 /* gets the current impersonation token */
875 struct token *thread_get_impersonation_token( struct thread *thread )
876 {
877     if (thread->token)
878         return thread->token;
879     else
880         return thread->process->token;
881 }
882
883 /* create a new thread */
884 DECL_HANDLER(new_thread)
885 {
886     struct thread *thread;
887     int request_fd = thread_get_inflight_fd( current, req->request_fd );
888
889     if (request_fd == -1 || fcntl( request_fd, F_SETFL, O_NONBLOCK ) == -1)
890     {
891         if (request_fd != -1) close( request_fd );
892         set_error( STATUS_INVALID_HANDLE );
893         return;
894     }
895
896     if ((thread = create_thread( request_fd, current->process )))
897     {
898         if (req->suspend) thread->suspend++;
899         reply->tid = get_thread_id( thread );
900         if ((reply->handle = alloc_handle( current->process, thread, req->access, req->attributes )))
901         {
902             /* thread object will be released when the thread gets killed */
903             return;
904         }
905         kill_thread( thread, 1 );
906     }
907 }
908
909 /* initialize a new thread */
910 DECL_HANDLER(init_thread)
911 {
912     struct process *process = current->process;
913     int reply_fd = thread_get_inflight_fd( current, req->reply_fd );
914     int wait_fd = thread_get_inflight_fd( current, req->wait_fd );
915
916     if (current->reply_fd)  /* already initialised */
917     {
918         set_error( STATUS_INVALID_PARAMETER );
919         goto error;
920     }
921
922     if (reply_fd == -1 || fcntl( reply_fd, F_SETFL, O_NONBLOCK ) == -1) goto error;
923
924     current->reply_fd = create_anonymous_fd( &thread_fd_ops, reply_fd, &current->obj );
925     reply_fd = -1;
926     if (!current->reply_fd) goto error;
927
928     if (wait_fd == -1)
929     {
930         set_error( STATUS_TOO_MANY_OPENED_FILES );  /* most likely reason */
931         return;
932     }
933     if (!(current->wait_fd  = create_anonymous_fd( &thread_fd_ops, wait_fd, &current->obj )))
934         return;
935
936     if (!is_valid_address(req->teb) || !is_valid_address(req->peb) || !is_valid_address(req->ldt_copy))
937     {
938         set_error( STATUS_INVALID_PARAMETER );
939         return;
940     }
941
942     current->unix_pid = req->unix_pid;
943     current->unix_tid = req->unix_tid;
944     current->teb      = req->teb;
945
946     if (!process->peb)  /* first thread, initialize the process too */
947     {
948         process->unix_pid = current->unix_pid;
949         process->peb      = req->peb;
950         process->ldt_copy = req->ldt_copy;
951         reply->info_size  = init_process( current );
952     }
953     else
954     {
955         if (process->unix_pid != current->unix_pid)
956             process->unix_pid = -1;  /* can happen with linuxthreads */
957         if (current->suspend + process->suspend > 0) stop_thread( current );
958         generate_debug_event( current, CREATE_THREAD_DEBUG_EVENT, req->entry );
959     }
960     debug_level = max( debug_level, req->debug_level );
961
962     reply->pid     = get_process_id( process );
963     reply->tid     = get_thread_id( current );
964     reply->version = SERVER_PROTOCOL_VERSION;
965     reply->server_start.sec  = server_start_time.tv_sec;
966     reply->server_start.usec = server_start_time.tv_usec;
967     return;
968
969  error:
970     if (reply_fd != -1) close( reply_fd );
971     if (wait_fd != -1) close( wait_fd );
972 }
973
974 /* terminate a thread */
975 DECL_HANDLER(terminate_thread)
976 {
977     struct thread *thread;
978
979     reply->self = 0;
980     reply->last = 0;
981     if ((thread = get_thread_from_handle( req->handle, THREAD_TERMINATE )))
982     {
983         thread->exit_code = req->exit_code;
984         if (thread != current) kill_thread( thread, 1 );
985         else
986         {
987             reply->self = 1;
988             reply->last = (thread->process->running_threads == 1);
989         }
990         release_object( thread );
991     }
992 }
993
994 /* open a handle to a thread */
995 DECL_HANDLER(open_thread)
996 {
997     struct thread *thread = get_thread_from_id( req->tid );
998
999     reply->handle = 0;
1000     if (thread)
1001     {
1002         reply->handle = alloc_handle( current->process, thread, req->access, req->attributes );
1003         release_object( thread );
1004     }
1005 }
1006
1007 /* fetch information about a thread */
1008 DECL_HANDLER(get_thread_info)
1009 {
1010     struct thread *thread;
1011     obj_handle_t handle = req->handle;
1012
1013     if (!handle) thread = get_thread_from_id( req->tid_in );
1014     else thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION );
1015
1016     if (thread)
1017     {
1018         reply->pid            = get_process_id( thread->process );
1019         reply->tid            = get_thread_id( thread );
1020         reply->teb            = thread->teb;
1021         reply->exit_code      = (thread->state == TERMINATED) ? thread->exit_code : STATUS_PENDING;
1022         reply->priority       = thread->priority;
1023         reply->affinity       = thread->affinity;
1024         reply->creation_time.sec  = thread->creation_time.tv_sec;
1025         reply->creation_time.usec = thread->creation_time.tv_usec;
1026         reply->exit_time.sec  = thread->exit_time.tv_sec;
1027         reply->exit_time.usec = thread->exit_time.tv_usec;
1028         reply->last           = thread->process->running_threads == 1;
1029
1030         release_object( thread );
1031     }
1032 }
1033
1034 /* set information about a thread */
1035 DECL_HANDLER(set_thread_info)
1036 {
1037     struct thread *thread;
1038
1039     if ((thread = get_thread_from_handle( req->handle, THREAD_SET_INFORMATION )))
1040     {
1041         set_thread_info( thread, req );
1042         release_object( thread );
1043     }
1044 }
1045
1046 /* suspend a thread */
1047 DECL_HANDLER(suspend_thread)
1048 {
1049     struct thread *thread;
1050
1051     if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
1052     {
1053         if (thread->state == TERMINATED) set_error( STATUS_ACCESS_DENIED );
1054         else reply->count = suspend_thread( thread );
1055         release_object( thread );
1056     }
1057 }
1058
1059 /* resume a thread */
1060 DECL_HANDLER(resume_thread)
1061 {
1062     struct thread *thread;
1063
1064     if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
1065     {
1066         if (thread->state == TERMINATED) set_error( STATUS_ACCESS_DENIED );
1067         else reply->count = resume_thread( thread );
1068         release_object( thread );
1069     }
1070 }
1071
1072 /* select on a handle list */
1073 DECL_HANDLER(select)
1074 {
1075     int count = get_req_data_size() / sizeof(obj_handle_t);
1076     select_on( count, req->cookie, get_req_data(), req->flags, &req->timeout, req->signal );
1077 }
1078
1079 /* queue an APC for a thread */
1080 DECL_HANDLER(queue_apc)
1081 {
1082     struct thread *thread;
1083     if ((thread = get_thread_from_handle( req->handle, THREAD_SET_CONTEXT )))
1084     {
1085         switch( req->call.type )
1086         {
1087         case APC_NONE:
1088         case APC_USER:
1089             thread_queue_apc( thread, NULL, &req->call );
1090             break;
1091         default:
1092             set_error( STATUS_INVALID_PARAMETER );
1093             break;
1094         }
1095         release_object( thread );
1096     }
1097 }
1098
1099 /* get next APC to call */
1100 DECL_HANDLER(get_apc)
1101 {
1102     struct thread_apc *apc;
1103     int system_only = !req->alertable;
1104
1105     if (req->prev)
1106     {
1107         if (!(apc = (struct thread_apc *)get_handle_obj( current->process, req->prev,
1108                                                          0, &thread_apc_ops ))) return;
1109         apc->result = req->result;
1110         apc->executed = 1;
1111         wake_up( &apc->obj, 0 );
1112         close_handle( current->process, req->prev );
1113         release_object( apc );
1114     }
1115
1116     if (current->suspend + current->process->suspend > 0) system_only = 1;
1117
1118     for (;;)
1119     {
1120         if (!(apc = thread_dequeue_apc( current, system_only )))
1121         {
1122             /* no more APCs */
1123             set_error( STATUS_PENDING );
1124             return;
1125         }
1126         /* Optimization: ignore APC_NONE calls, they are only used to
1127          * wake up a thread, but since we got here the thread woke up already.
1128          */
1129         if (apc->call.type != APC_NONE) break;
1130         apc->executed = 1;
1131         wake_up( &apc->obj, 0 );
1132         release_object( apc );
1133     }
1134
1135     if ((reply->handle = alloc_handle( current->process, apc, SYNCHRONIZE, 0 )))
1136         reply->call = apc->call;
1137     release_object( apc );
1138 }
1139
1140 /* Get the result of an APC call */
1141 DECL_HANDLER(get_apc_result)
1142 {
1143     struct thread_apc *apc;
1144
1145     if (!(apc = (struct thread_apc *)get_handle_obj( current->process, req->handle,
1146                                                      0, &thread_apc_ops ))) return;
1147     if (!apc->executed) set_error( STATUS_PENDING );
1148     else
1149     {
1150         reply->result = apc->result;
1151         /* close the handle directly to avoid an extra round-trip */
1152         close_handle( current->process, req->handle );
1153     }
1154     release_object( apc );
1155 }
1156
1157 /* retrieve the current context of a thread */
1158 DECL_HANDLER(get_thread_context)
1159 {
1160     struct thread *thread;
1161     CONTEXT *context;
1162
1163     if (get_reply_max_size() < sizeof(CONTEXT))
1164     {
1165         set_error( STATUS_INVALID_PARAMETER );
1166         return;
1167     }
1168     if (!(thread = get_thread_from_handle( req->handle, THREAD_GET_CONTEXT ))) return;
1169
1170     if (req->suspend)
1171     {
1172         if (thread != current || !thread->suspend_context)
1173         {
1174             /* not suspended, shouldn't happen */
1175             set_error( STATUS_INVALID_PARAMETER );
1176         }
1177         else
1178         {
1179             if (thread->context == thread->suspend_context) thread->context = NULL;
1180             set_reply_data_ptr( thread->suspend_context, sizeof(CONTEXT) );
1181             thread->suspend_context = NULL;
1182         }
1183     }
1184     else if (thread != current && !thread->context)
1185     {
1186         /* thread is not suspended, retry (if it's still running) */
1187         if (thread->state != RUNNING) set_error( STATUS_ACCESS_DENIED );
1188         else set_error( STATUS_PENDING );
1189     }
1190     else if ((context = set_reply_data_size( sizeof(CONTEXT) )))
1191     {
1192         unsigned int flags = get_context_system_regs( req->flags );
1193
1194         memset( context, 0, sizeof(CONTEXT) );
1195         context->ContextFlags = get_context_cpu_flag();
1196         if (thread->context) copy_context( context, thread->context, req->flags & ~flags );
1197         if (flags) get_thread_context( thread, context, flags );
1198     }
1199     reply->self = (thread == current);
1200     release_object( thread );
1201 }
1202
1203 /* set the current context of a thread */
1204 DECL_HANDLER(set_thread_context)
1205 {
1206     struct thread *thread;
1207
1208     if (get_req_data_size() < sizeof(CONTEXT))
1209     {
1210         set_error( STATUS_INVALID_PARAMETER );
1211         return;
1212     }
1213     if (!(thread = get_thread_from_handle( req->handle, THREAD_SET_CONTEXT ))) return;
1214
1215     if (req->suspend)
1216     {
1217         if (thread != current || thread->context)
1218         {
1219             /* nested suspend or exception, shouldn't happen */
1220             set_error( STATUS_INVALID_PARAMETER );
1221         }
1222         else if ((thread->suspend_context = mem_alloc( sizeof(CONTEXT) )))
1223         {
1224             memcpy( thread->suspend_context, get_req_data(), sizeof(CONTEXT) );
1225             thread->context = thread->suspend_context;
1226             if (thread->debug_break) break_thread( thread );
1227         }
1228     }
1229     else if (thread != current && !thread->context)
1230     {
1231         /* thread is not suspended, retry (if it's still running) */
1232         if (thread->state != RUNNING) set_error( STATUS_ACCESS_DENIED );
1233         else set_error( STATUS_PENDING );
1234     }
1235     else
1236     {
1237         const CONTEXT *context = get_req_data();
1238         unsigned int flags = get_context_system_regs( req->flags );
1239
1240         if (flags) set_thread_context( thread, context, flags );
1241         if (thread->context && !get_error())
1242             copy_context( thread->context, context, req->flags & ~flags );
1243     }
1244     reply->self = (thread == current);
1245     release_object( thread );
1246 }
1247
1248 /* fetch a selector entry for a thread */
1249 DECL_HANDLER(get_selector_entry)
1250 {
1251     struct thread *thread;
1252     if ((thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION )))
1253     {
1254         get_selector_entry( thread, req->entry, &reply->base, &reply->limit, &reply->flags );
1255         release_object( thread );
1256     }
1257 }