Add name_lookup function in object_ops.
[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_lookup_name,             /* lookup_name */
98     no_close_handle,            /* close_handle */
99     destroy_thread              /* destroy */
100 };
101
102 static const struct fd_ops thread_fd_ops =
103 {
104     NULL,                       /* get_poll_events */
105     thread_poll_event,          /* poll_event */
106     no_flush,                   /* flush */
107     no_get_file_info,           /* get_file_info */
108     no_queue_async,             /* queue_async */
109     no_cancel_async             /* cancel_async */
110 };
111
112 static struct list thread_list = LIST_INIT(thread_list);
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->suspend_context = NULL;
123     thread->teb             = NULL;
124     thread->debug_ctx       = NULL;
125     thread->debug_event     = NULL;
126     thread->queue           = NULL;
127     thread->wait            = NULL;
128     thread->error           = 0;
129     thread->req_data        = NULL;
130     thread->req_toread      = 0;
131     thread->reply_data      = NULL;
132     thread->reply_towrite   = 0;
133     thread->request_fd      = NULL;
134     thread->reply_fd        = NULL;
135     thread->wait_fd         = NULL;
136     thread->state           = RUNNING;
137     thread->attached        = 0;
138     thread->exit_code       = 0;
139     thread->priority        = THREAD_PRIORITY_NORMAL;
140     thread->affinity        = 1;
141     thread->suspend         = 0;
142     thread->creation_time   = time(NULL);
143     thread->exit_time       = 0;
144     thread->desktop_users   = 0;
145
146     list_init( &thread->mutex_list );
147     list_init( &thread->system_apc );
148     list_init( &thread->user_apc );
149
150     for (i = 0; i < MAX_INFLIGHT_FDS; i++)
151         thread->inflight[i].server = thread->inflight[i].client = -1;
152 }
153
154 /* check if address looks valid for a client-side data structure (TEB etc.) */
155 static inline int is_valid_address( void *addr )
156 {
157     return addr && !((unsigned int)addr % sizeof(int));
158 }
159
160 /* create a new thread */
161 struct thread *create_thread( int fd, struct process *process )
162 {
163     struct thread *thread;
164
165     if (!(thread = alloc_object( &thread_ops ))) return NULL;
166
167     init_thread_structure( thread );
168
169     thread->process = (struct process *)grab_object( process );
170     thread->desktop = process->desktop;
171     if (!current) current = thread;
172
173     list_add_head( &thread_list, &thread->entry );
174
175     if (!(thread->id = alloc_ptid( thread )))
176     {
177         release_object( thread );
178         return NULL;
179     }
180     if (!(thread->request_fd = create_anonymous_fd( &thread_fd_ops, fd, &thread->obj )))
181     {
182         release_object( thread );
183         return NULL;
184     }
185
186     thread->token = (struct token *) grab_object( process->token );
187
188     set_fd_events( thread->request_fd, POLLIN );  /* start listening to events */
189     add_process_thread( thread->process, thread );
190     return thread;
191 }
192
193 /* handle a client event */
194 static void thread_poll_event( struct fd *fd, int event )
195 {
196     struct thread *thread = get_fd_user( fd );
197     assert( thread->obj.ops == &thread_ops );
198
199     if (event & (POLLERR | POLLHUP)) kill_thread( thread, 0 );
200     else if (event & POLLIN) read_request( thread );
201     else if (event & POLLOUT) write_reply( thread );
202 }
203
204 /* cleanup everything that is no longer needed by a dead thread */
205 /* used by destroy_thread and kill_thread */
206 static void cleanup_thread( struct thread *thread )
207 {
208     int i;
209     struct thread_apc *apc;
210
211     while ((apc = thread_dequeue_apc( thread, 0 ))) free( apc );
212     if (thread->req_data) free( thread->req_data );
213     if (thread->reply_data) free( thread->reply_data );
214     if (thread->request_fd) release_object( thread->request_fd );
215     if (thread->reply_fd) release_object( thread->reply_fd );
216     if (thread->wait_fd) release_object( thread->wait_fd );
217     if (thread->suspend_context) free( thread->suspend_context );
218     free_msg_queue( thread );
219     cleanup_clipboard_thread(thread);
220     destroy_thread_windows( thread );
221     close_thread_desktop( thread );
222     for (i = 0; i < MAX_INFLIGHT_FDS; i++)
223     {
224         if (thread->inflight[i].client != -1)
225         {
226             close( thread->inflight[i].server );
227             thread->inflight[i].client = thread->inflight[i].server = -1;
228         }
229     }
230     thread->req_data = NULL;
231     thread->reply_data = NULL;
232     thread->request_fd = NULL;
233     thread->reply_fd = NULL;
234     thread->wait_fd = NULL;
235     thread->context = NULL;
236     thread->suspend_context = NULL;
237     thread->desktop = 0;
238 }
239
240 /* destroy a thread when its refcount is 0 */
241 static void destroy_thread( struct object *obj )
242 {
243     struct thread *thread = (struct thread *)obj;
244     assert( obj->ops == &thread_ops );
245
246     assert( !thread->debug_ctx );  /* cannot still be debugging something */
247     list_remove( &thread->entry );
248     cleanup_thread( thread );
249     release_object( thread->process );
250     if (thread->id) free_ptid( thread->id );
251     if (thread->token) release_object( thread->token );
252 }
253
254 /* dump a thread on stdout for debugging purposes */
255 static void dump_thread( struct object *obj, int verbose )
256 {
257     struct thread *thread = (struct thread *)obj;
258     assert( obj->ops == &thread_ops );
259
260     fprintf( stderr, "Thread id=%04x unix pid=%d unix tid=%d teb=%p state=%d\n",
261              thread->id, thread->unix_pid, thread->unix_tid, thread->teb, thread->state );
262 }
263
264 static int thread_signaled( struct object *obj, struct thread *thread )
265 {
266     struct thread *mythread = (struct thread *)obj;
267     return (mythread->state == TERMINATED);
268 }
269
270 /* get a thread pointer from a thread id (and increment the refcount) */
271 struct thread *get_thread_from_id( thread_id_t id )
272 {
273     struct object *obj = get_ptid_entry( id );
274
275     if (obj && obj->ops == &thread_ops) return (struct thread *)grab_object( obj );
276     set_error( STATUS_INVALID_CID );
277     return NULL;
278 }
279
280 /* get a thread from a handle (and increment the refcount) */
281 struct thread *get_thread_from_handle( obj_handle_t handle, unsigned int access )
282 {
283     return (struct thread *)get_handle_obj( current->process, handle,
284                                             access, &thread_ops );
285 }
286
287 /* find a thread from a Unix pid */
288 struct thread *get_thread_from_pid( int pid )
289 {
290     struct thread *thread;
291
292     LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
293     {
294         if (thread->unix_tid == pid) return thread;
295     }
296     LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
297     {
298         if (thread->unix_pid == pid) return thread;
299     }
300     return NULL;
301 }
302
303 /* set all information about a thread */
304 static void set_thread_info( struct thread *thread,
305                              const struct set_thread_info_request *req )
306 {
307     if (req->mask & SET_THREAD_INFO_PRIORITY)
308         thread->priority = req->priority;
309     if (req->mask & SET_THREAD_INFO_AFFINITY)
310     {
311         if (req->affinity != 1) set_error( STATUS_INVALID_PARAMETER );
312         else thread->affinity = req->affinity;
313     }
314     if (req->mask & SET_THREAD_INFO_TOKEN)
315         security_set_thread_token( thread, req->token );
316 }
317
318 /* stop a thread (at the Unix level) */
319 void stop_thread( struct thread *thread )
320 {
321     if (thread->context) return;  /* already inside a debug event, no need for a signal */
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, (int *)base ) == -1) goto done;
742         if (read_thread_int( thread, addr + 8192, (int *)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     wake_up( &thread->obj, 0 );
772     if (violent_death) send_thread_signal( thread, SIGTERM );
773     cleanup_thread( thread );
774     remove_process_thread( thread->process, 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 /* create a new thread */
812 DECL_HANDLER(new_thread)
813 {
814     struct thread *thread;
815     int request_fd = thread_get_inflight_fd( current, req->request_fd );
816
817     if (request_fd == -1 || fcntl( request_fd, F_SETFL, O_NONBLOCK ) == -1)
818     {
819         if (request_fd != -1) close( request_fd );
820         set_error( STATUS_INVALID_HANDLE );
821         return;
822     }
823
824     if ((thread = create_thread( request_fd, current->process )))
825     {
826         if (req->suspend) thread->suspend++;
827         reply->tid = get_thread_id( thread );
828         if ((reply->handle = alloc_handle( current->process, thread,
829                                            THREAD_ALL_ACCESS, req->inherit )))
830         {
831             /* thread object will be released when the thread gets killed */
832             return;
833         }
834         kill_thread( thread, 1 );
835     }
836 }
837
838 /* initialize a new thread */
839 DECL_HANDLER(init_thread)
840 {
841     struct process *process = current->process;
842     int reply_fd = thread_get_inflight_fd( current, req->reply_fd );
843     int wait_fd = thread_get_inflight_fd( current, req->wait_fd );
844
845     if (current->unix_pid != -1)
846     {
847         fatal_protocol_error( current, "init_thread: already running\n" );
848         goto error;
849     }
850     if (reply_fd == -1 || fcntl( reply_fd, F_SETFL, O_NONBLOCK ) == -1)
851     {
852         fatal_protocol_error( current, "bad reply fd\n" );
853         goto error;
854     }
855     if (wait_fd == -1)
856     {
857         fatal_protocol_error( current, "bad wait fd\n" );
858         goto error;
859     }
860     if (!(current->reply_fd = create_anonymous_fd( &thread_fd_ops, reply_fd, &current->obj )))
861     {
862         reply_fd = -1;
863         fatal_protocol_error( current, "could not allocate reply fd\n" );
864         goto error;
865     }
866     if (!(current->wait_fd  = create_anonymous_fd( &thread_fd_ops, wait_fd, &current->obj )))
867         return;
868
869     if (!is_valid_address(req->teb) || !is_valid_address(req->peb) || !is_valid_address(req->ldt_copy))
870     {
871         set_error( STATUS_INVALID_PARAMETER );
872         return;
873     }
874
875     current->unix_pid = req->unix_pid;
876     current->unix_tid = req->unix_tid;
877     current->teb      = req->teb;
878
879     if (!process->peb)  /* first thread, initialize the process too */
880     {
881         process->peb      = req->peb;
882         process->ldt_copy = req->ldt_copy;
883         reply->info_size  = init_process( current );
884     }
885     else
886     {
887         if (current->suspend + process->suspend > 0) stop_thread( current );
888         generate_debug_event( current, CREATE_THREAD_DEBUG_EVENT, req->entry );
889     }
890     debug_level = max( debug_level, req->debug_level );
891
892     reply->pid     = get_process_id( process );
893     reply->tid     = get_thread_id( current );
894     reply->version = SERVER_PROTOCOL_VERSION;
895     reply->server_start = server_start_time;
896     return;
897
898  error:
899     if (reply_fd != -1) close( reply_fd );
900     if (wait_fd != -1) close( wait_fd );
901 }
902
903 /* terminate a thread */
904 DECL_HANDLER(terminate_thread)
905 {
906     struct thread *thread;
907
908     reply->self = 0;
909     reply->last = 0;
910     if ((thread = get_thread_from_handle( req->handle, THREAD_TERMINATE )))
911     {
912         thread->exit_code = req->exit_code;
913         if (thread != current) kill_thread( thread, 1 );
914         else
915         {
916             reply->self = 1;
917             reply->last = (thread->process->running_threads == 1);
918         }
919         release_object( thread );
920     }
921 }
922
923 /* open a handle to a thread */
924 DECL_HANDLER(open_thread)
925 {
926     struct thread *thread = get_thread_from_id( req->tid );
927
928     reply->handle = 0;
929     if (thread)
930     {
931         reply->handle = alloc_handle( current->process, thread, req->access, req->inherit );
932         release_object( thread );
933     }
934 }
935
936 /* fetch information about a thread */
937 DECL_HANDLER(get_thread_info)
938 {
939     struct thread *thread;
940     obj_handle_t handle = req->handle;
941
942     if (!handle) thread = get_thread_from_id( req->tid_in );
943     else thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION );
944
945     if (thread)
946     {
947         reply->pid            = get_process_id( thread->process );
948         reply->tid            = get_thread_id( thread );
949         reply->teb            = thread->teb;
950         reply->exit_code      = (thread->state == TERMINATED) ? thread->exit_code : STILL_ACTIVE;
951         reply->priority       = thread->priority;
952         reply->affinity       = thread->affinity;
953         reply->creation_time  = thread->creation_time;
954         reply->exit_time      = thread->exit_time;
955
956         release_object( thread );
957     }
958 }
959
960 /* set information about a thread */
961 DECL_HANDLER(set_thread_info)
962 {
963     struct thread *thread;
964
965     if ((thread = get_thread_from_handle( req->handle, THREAD_SET_INFORMATION )))
966     {
967         set_thread_info( thread, req );
968         release_object( thread );
969     }
970 }
971
972 /* suspend a thread */
973 DECL_HANDLER(suspend_thread)
974 {
975     struct thread *thread;
976
977     if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
978     {
979         if (thread->state == TERMINATED) set_error( STATUS_ACCESS_DENIED );
980         else reply->count = suspend_thread( thread );
981         release_object( thread );
982     }
983 }
984
985 /* resume a thread */
986 DECL_HANDLER(resume_thread)
987 {
988     struct thread *thread;
989
990     if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
991     {
992         if (thread->state == TERMINATED) set_error( STATUS_ACCESS_DENIED );
993         else reply->count = resume_thread( thread );
994         release_object( thread );
995     }
996 }
997
998 /* select on a handle list */
999 DECL_HANDLER(select)
1000 {
1001     int count = get_req_data_size() / sizeof(int);
1002     select_on( count, req->cookie, get_req_data(), req->flags, &req->timeout, req->signal );
1003 }
1004
1005 /* queue an APC for a thread */
1006 DECL_HANDLER(queue_apc)
1007 {
1008     struct thread *thread;
1009     if ((thread = get_thread_from_handle( req->handle, THREAD_SET_CONTEXT )))
1010     {
1011         thread_queue_apc( thread, NULL, req->func, APC_USER, !req->user,
1012                           req->arg1, req->arg2, req->arg3 );
1013         release_object( thread );
1014     }
1015 }
1016
1017 /* get next APC to call */
1018 DECL_HANDLER(get_apc)
1019 {
1020     struct thread_apc *apc;
1021
1022     for (;;)
1023     {
1024         if (!(apc = thread_dequeue_apc( current, !req->alertable )))
1025         {
1026             /* no more APCs */
1027             reply->func = NULL;
1028             reply->type = APC_NONE;
1029             return;
1030         }
1031         /* Optimization: ignore APCs that have a NULL func; they are only used
1032          * to wake up a thread, but since we got here the thread woke up already.
1033          * Exception: for APC_ASYNC_IO, func == NULL is legal.
1034          */
1035         if (apc->func || apc->type == APC_ASYNC_IO) break;
1036         free( apc );
1037     }
1038     reply->func = apc->func;
1039     reply->type = apc->type;
1040     reply->arg1 = apc->arg1;
1041     reply->arg2 = apc->arg2;
1042     reply->arg3 = apc->arg3;
1043     free( apc );
1044 }
1045
1046 /* retrieve the current context of a thread */
1047 DECL_HANDLER(get_thread_context)
1048 {
1049     struct thread *thread;
1050     void *data;
1051
1052     if (get_reply_max_size() < sizeof(CONTEXT))
1053     {
1054         set_error( STATUS_INVALID_PARAMETER );
1055         return;
1056     }
1057     if (!(thread = get_thread_from_handle( req->handle, THREAD_GET_CONTEXT ))) return;
1058
1059     if (req->suspend)
1060     {
1061         if (thread != current || !thread->suspend_context)
1062         {
1063             /* not suspended, shouldn't happen */
1064             set_error( STATUS_INVALID_PARAMETER );
1065         }
1066         else
1067         {
1068             if (thread->context == thread->suspend_context) thread->context = NULL;
1069             set_reply_data_ptr( thread->suspend_context, sizeof(CONTEXT) );
1070             thread->suspend_context = NULL;
1071         }
1072     }
1073     else if (thread != current && !thread->context)
1074     {
1075         /* thread is not suspended, retry (if it's still running) */
1076         if (thread->state != RUNNING) set_error( STATUS_ACCESS_DENIED );
1077         else set_error( STATUS_PENDING );
1078     }
1079     else if ((data = set_reply_data_size( sizeof(CONTEXT) )))
1080     {
1081         memset( data, 0, sizeof(CONTEXT) );
1082         get_thread_context( thread, data, req->flags );
1083     }
1084     release_object( thread );
1085 }
1086
1087 /* set the current context of a thread */
1088 DECL_HANDLER(set_thread_context)
1089 {
1090     struct thread *thread;
1091
1092     if (get_req_data_size() < sizeof(CONTEXT))
1093     {
1094         set_error( STATUS_INVALID_PARAMETER );
1095         return;
1096     }
1097     if (!(thread = get_thread_from_handle( req->handle, THREAD_SET_CONTEXT ))) return;
1098
1099     if (req->suspend)
1100     {
1101         if (thread != current || thread->context)
1102         {
1103             /* nested suspend or exception, shouldn't happen */
1104             set_error( STATUS_INVALID_PARAMETER );
1105         }
1106         else if ((thread->suspend_context = mem_alloc( sizeof(CONTEXT) )))
1107         {
1108             memcpy( thread->suspend_context, get_req_data(), sizeof(CONTEXT) );
1109             thread->context = thread->suspend_context;
1110         }
1111     }
1112     else if (thread != current && !thread->context)
1113     {
1114         /* thread is not suspended, retry (if it's still running) */
1115         if (thread->state != RUNNING) set_error( STATUS_ACCESS_DENIED );
1116         else set_error( STATUS_PENDING );
1117     }
1118     else
1119     {
1120         set_thread_context( thread, get_req_data(), req->flags );
1121     }
1122     release_object( thread );
1123 }
1124
1125 /* fetch a selector entry for a thread */
1126 DECL_HANDLER(get_selector_entry)
1127 {
1128     struct thread *thread;
1129     if ((thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION )))
1130     {
1131         get_selector_entry( thread, req->entry, &reply->base, &reply->limit, &reply->flags );
1132         release_object( thread );
1133     }
1134 }