Reimplemented DebugBreakProcess.
[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     else apc->prev->next = apc;
566
567     return 1;
568 }
569
570 /* cancel the async procedure call owned by a specific object */
571 void thread_cancel_apc( struct thread *thread, struct object *owner, int system )
572 {
573     struct thread_apc *apc;
574     struct apc_queue *queue = system ? &thread->system_apc : &thread->user_apc;
575     for (apc = queue->head; apc; apc = apc->next)
576     {
577         if (apc->owner != owner) continue;
578         if (apc->next) apc->next->prev = apc->prev;
579         else queue->tail = apc->prev;
580         if (apc->prev) apc->prev->next = apc->next;
581         else queue->head = apc->next;
582         free( apc );
583         return;
584     }
585 }
586
587 /* remove the head apc from the queue; the returned pointer must be freed by the caller */
588 static struct thread_apc *thread_dequeue_apc( struct thread *thread, int system_only )
589 {
590     struct thread_apc *apc;
591     struct apc_queue *queue = &thread->system_apc;
592
593     if (!queue->head && !system_only) queue = &thread->user_apc;
594     if ((apc = queue->head))
595     {
596         if (apc->next) apc->next->prev = NULL;
597         else queue->tail = NULL;
598         queue->head = apc->next;
599     }
600     return apc;
601 }
602
603 /* add an fd to the inflight list */
604 /* return list index, or -1 on error */
605 int thread_add_inflight_fd( struct thread *thread, int client, int server )
606 {
607     int i;
608
609     if (server == -1) return -1;
610     if (client == -1)
611     {
612         close( server );
613         return -1;
614     }
615
616     /* first check if we already have an entry for this fd */
617     for (i = 0; i < MAX_INFLIGHT_FDS; i++)
618         if (thread->inflight[i].client == client)
619         {
620             close( thread->inflight[i].server );
621             thread->inflight[i].server = server;
622             return i;
623         }
624
625     /* now find a free spot to store it */
626     for (i = 0; i < MAX_INFLIGHT_FDS; i++)
627         if (thread->inflight[i].client == -1)
628         {
629             thread->inflight[i].client = client;
630             thread->inflight[i].server = server;
631             return i;
632         }
633     return -1;
634 }
635
636 /* get an inflight fd and purge it from the list */
637 /* the fd must be closed when no longer used */
638 int thread_get_inflight_fd( struct thread *thread, int client )
639 {
640     int i, ret;
641
642     if (client == -1) return -1;
643
644     do
645     {
646         for (i = 0; i < MAX_INFLIGHT_FDS; i++)
647         {
648             if (thread->inflight[i].client == client)
649             {
650                 ret = thread->inflight[i].server;
651                 thread->inflight[i].server = thread->inflight[i].client = -1;
652                 return ret;
653             }
654         }
655     } while (!receive_fd( thread->process ));  /* in case it is still in the socket buffer */
656     return -1;
657 }
658
659 /* retrieve an LDT selector entry */
660 static void get_selector_entry( struct thread *thread, int entry,
661                                 unsigned int *base, unsigned int *limit,
662                                 unsigned char *flags )
663 {
664     if (!thread->process->ldt_copy)
665     {
666         set_error( STATUS_ACCESS_DENIED );
667         return;
668     }
669     if (entry >= 8192)
670     {
671         set_error( STATUS_INVALID_PARAMETER );  /* FIXME */
672         return;
673     }
674     if (suspend_for_ptrace( thread ))
675     {
676         unsigned char flags_buf[4];
677         int *addr = (int *)thread->process->ldt_copy + entry;
678         if (read_thread_int( thread, addr, base ) == -1) goto done;
679         if (read_thread_int( thread, addr + 8192, limit ) == -1) goto done;
680         addr = (int *)thread->process->ldt_copy + 2*8192 + (entry >> 2);
681         if (read_thread_int( thread, addr, (int *)flags_buf ) == -1) goto done;
682         *flags = flags_buf[entry & 3];
683     done:
684         resume_thread( thread );
685     }
686 }
687
688 /* kill a thread on the spot */
689 void kill_thread( struct thread *thread, int violent_death )
690 {
691     if (thread->state == TERMINATED) return;  /* already killed */
692     thread->state = TERMINATED;
693     if (current == thread) current = NULL;
694     if (debug_level)
695         fprintf( stderr,"%08x: *killed* exit_code=%d\n",
696                  (unsigned int)thread, thread->exit_code );
697     if (thread->wait)
698     {
699         while (thread->wait) end_wait( thread );
700         send_thread_wakeup( thread, NULL, STATUS_PENDING );
701         /* if it is waiting on the socket, we don't need to send a SIGTERM */
702         violent_death = 0;
703     }
704     kill_console_processes( thread, 0 );
705     debug_exit_thread( thread );
706     abandon_mutexes( thread );
707     remove_process_thread( thread->process, thread );
708     wake_up( &thread->obj, 0 );
709     detach_thread( thread, violent_death ? SIGTERM : 0 );
710     if (thread->request_fd == thread->obj.fd) thread->request_fd = -1;
711     if (thread->reply_fd == thread->obj.fd) thread->reply_fd = -1;
712     remove_select_user( &thread->obj );
713     cleanup_thread( thread );
714     release_object( thread );
715 }
716
717 /* take a snapshot of currently running threads */
718 struct thread_snapshot *thread_snap( int *count )
719 {
720     struct thread_snapshot *snapshot, *ptr;
721     struct thread *thread;
722     int total = 0;
723
724     for (thread = first_thread; thread; thread = thread->next)
725         if (thread->state != TERMINATED) total++;
726     if (!total || !(snapshot = mem_alloc( sizeof(*snapshot) * total ))) return NULL;
727     ptr = snapshot;
728     for (thread = first_thread; thread; thread = thread->next)
729     {
730         if (thread->state == TERMINATED) continue;
731         ptr->thread   = thread;
732         ptr->count    = thread->obj.refcount;
733         ptr->priority = thread->priority;
734         grab_object( thread );
735         ptr++;
736     }
737     *count = total;
738     return snapshot;
739 }
740
741 /* signal that we are finished booting on the client side */
742 DECL_HANDLER(boot_done)
743 {
744     debug_level = max( debug_level, req->debug_level );
745     if (current == booting_thread)
746     {
747         booting_thread = (struct thread *)~0UL;  /* make sure it doesn't match other threads */
748         lock_master_socket(0);  /* allow other clients now */
749     }
750 }
751
752 /* create a new thread */
753 DECL_HANDLER(new_thread)
754 {
755     struct thread *thread;
756     int request_fd = thread_get_inflight_fd( current, req->request_fd );
757
758     if (request_fd == -1 || fcntl( request_fd, F_SETFL, O_NONBLOCK ) == -1)
759     {
760         if (request_fd != -1) close( request_fd );
761         set_error( STATUS_INVALID_HANDLE );
762         return;
763     }
764
765     if ((thread = create_thread( request_fd, current->process )))
766     {
767         if (req->suspend) thread->suspend++;
768         reply->tid = thread;
769         if ((reply->handle = alloc_handle( current->process, thread,
770                                            THREAD_ALL_ACCESS, req->inherit )))
771         {
772             /* thread object will be released when the thread gets killed */
773             return;
774         }
775         kill_thread( thread, 1 );
776         request_fd = -1;
777     }
778 }
779
780 /* initialize a new thread */
781 DECL_HANDLER(init_thread)
782 {
783     int reply_fd = thread_get_inflight_fd( current, req->reply_fd );
784     int wait_fd = thread_get_inflight_fd( current, req->wait_fd );
785
786     if (current->unix_pid)
787     {
788         fatal_protocol_error( current, "init_thread: already running\n" );
789         goto error;
790     }
791     if (reply_fd == -1 || fcntl( reply_fd, F_SETFL, O_NONBLOCK ) == -1)
792     {
793         fatal_protocol_error( current, "bad reply fd\n" );
794         goto error;
795     }
796     if (wait_fd == -1)
797     {
798         fatal_protocol_error( current, "bad wait fd\n" );
799         goto error;
800     }
801
802     current->unix_pid = req->unix_pid;
803     current->teb      = req->teb;
804     current->reply_fd = reply_fd;
805     current->wait_fd  = wait_fd;
806
807     if (current->suspend + current->process->suspend > 0) stop_thread( current );
808     if (current->process->running_threads > 1)
809         generate_debug_event( current, CREATE_THREAD_DEBUG_EVENT, req->entry );
810
811     reply->pid     = get_process_id( current->process );
812     reply->tid     = get_thread_id( current );
813     reply->boot    = (current == booting_thread);
814     reply->version = SERVER_PROTOCOL_VERSION;
815     return;
816
817  error:
818     if (reply_fd != -1) close( reply_fd );
819     if (wait_fd != -1) close( wait_fd );
820 }
821
822 /* terminate a thread */
823 DECL_HANDLER(terminate_thread)
824 {
825     struct thread *thread;
826
827     reply->self = 0;
828     reply->last = 0;
829     if ((thread = get_thread_from_handle( req->handle, THREAD_TERMINATE )))
830     {
831         thread->exit_code = req->exit_code;
832         if (thread != current) kill_thread( thread, 1 );
833         else
834         {
835             reply->self = 1;
836             reply->last = (thread->process->running_threads == 1);
837         }
838         release_object( thread );
839     }
840 }
841
842 /* fetch information about a thread */
843 DECL_HANDLER(get_thread_info)
844 {
845     struct thread *thread;
846     handle_t handle = req->handle;
847
848     if (!handle) thread = get_thread_from_id( req->tid_in );
849     else thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION );
850
851     if (thread)
852     {
853         reply->tid       = get_thread_id( thread );
854         reply->teb       = thread->teb;
855         reply->exit_code = (thread->state == TERMINATED) ? thread->exit_code : STILL_ACTIVE;
856         reply->priority  = thread->priority;
857         release_object( thread );
858     }
859 }
860
861 /* set information about a thread */
862 DECL_HANDLER(set_thread_info)
863 {
864     struct thread *thread;
865
866     if ((thread = get_thread_from_handle( req->handle, THREAD_SET_INFORMATION )))
867     {
868         set_thread_info( thread, req );
869         release_object( thread );
870     }
871 }
872
873 /* suspend a thread */
874 DECL_HANDLER(suspend_thread)
875 {
876     struct thread *thread;
877
878     if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
879     {
880         reply->count = suspend_thread( thread, 1 );
881         release_object( thread );
882     }
883 }
884
885 /* resume a thread */
886 DECL_HANDLER(resume_thread)
887 {
888     struct thread *thread;
889
890     if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
891     {
892         reply->count = resume_thread( thread );
893         release_object( thread );
894     }
895 }
896
897 /* select on a handle list */
898 DECL_HANDLER(select)
899 {
900     int count = get_req_data_size() / sizeof(int);
901     select_on( count, req->cookie, get_req_data(), req->flags, req->sec, req->usec );
902 }
903
904 /* queue an APC for a thread */
905 DECL_HANDLER(queue_apc)
906 {
907     struct thread *thread;
908     if ((thread = get_thread_from_handle( req->handle, THREAD_SET_CONTEXT )))
909     {
910         thread_queue_apc( thread, NULL, req->func, APC_USER, !req->user, 1, req->param );
911         release_object( thread );
912     }
913 }
914
915 /* get next APC to call */
916 DECL_HANDLER(get_apc)
917 {
918     struct thread_apc *apc;
919     size_t size;
920
921     for (;;)
922     {
923         if (!(apc = thread_dequeue_apc( current, !req->alertable )))
924         {
925             /* no more APCs */
926             reply->func = NULL;
927             reply->type = APC_NONE;
928             return;
929         }
930         /* Optimization: ignore APCs that have a NULL func; they are only used
931          * to wake up a thread, but since we got here the thread woke up already.
932          */
933         if (apc->func) break;
934         free( apc );
935     }
936     size = apc->nb_args * sizeof(apc->args[0]);
937     if (size > get_reply_max_size()) size = get_reply_max_size();
938     reply->func = apc->func;
939     reply->type = apc->type;
940     set_reply_data( apc->args, size );
941     free( apc );
942 }
943
944 /* fetch a selector entry for a thread */
945 DECL_HANDLER(get_selector_entry)
946 {
947     struct thread *thread;
948     if ((thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION )))
949     {
950         get_selector_entry( thread, req->entry, &reply->base, &reply->limit, &reply->flags );
951         release_object( thread );
952     }
953 }