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