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