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