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