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