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