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