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