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