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