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