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