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