Return correct attributes in ParseDisplayName.
[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 static struct thread *booting_thread;
113
114 /* initialize the structure for a newly allocated thread */
115 inline static void init_thread_structure( struct thread *thread )
116 {
117     int i;
118
119     thread->unix_pid        = -1;  /* not known yet */
120     thread->unix_tid        = -1;  /* not known yet */
121     thread->context         = NULL;
122     thread->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 /* create a new thread */
154 struct thread *create_thread( int fd, struct process *process )
155 {
156     struct thread *thread;
157
158     if (!(thread = alloc_object( &thread_ops ))) return NULL;
159
160     init_thread_structure( thread );
161
162     thread->process = (struct process *)grab_object( process );
163     thread->desktop = process->desktop;
164     if (!current) current = thread;
165
166     if (!booting_thread)  /* first thread ever */
167     {
168         booting_thread = thread;
169         lock_master_socket(1);
170     }
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     free_msg_queue( thread );
217     cleanup_clipboard_thread(thread);
218     destroy_thread_windows( thread );
219     close_thread_desktop( thread );
220     for (i = 0; i < MAX_INFLIGHT_FDS; i++)
221     {
222         if (thread->inflight[i].client != -1)
223         {
224             close( thread->inflight[i].server );
225             thread->inflight[i].client = thread->inflight[i].server = -1;
226         }
227     }
228     thread->req_data = NULL;
229     thread->reply_data = NULL;
230     thread->request_fd = NULL;
231     thread->reply_fd = NULL;
232     thread->wait_fd = NULL;
233     thread->desktop = 0;
234
235     if (thread == booting_thread)  /* killing booting thread */
236     {
237         booting_thread = NULL;
238         lock_master_socket(0);
239     }
240 }
241
242 /* destroy a thread when its refcount is 0 */
243 static void destroy_thread( struct object *obj )
244 {
245     struct thread_apc *apc;
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     while ((apc = thread_dequeue_apc( thread, 0 ))) free( apc );
252     cleanup_thread( thread );
253     release_object( thread->process );
254     if (thread->id) free_ptid( thread->id );
255     if (thread->token) release_object( thread->token );
256 }
257
258 /* dump a thread on stdout for debugging purposes */
259 static void dump_thread( struct object *obj, int verbose )
260 {
261     struct thread *thread = (struct thread *)obj;
262     assert( obj->ops == &thread_ops );
263
264     fprintf( stderr, "Thread id=%04x unix pid=%d unix tid=%d teb=%p state=%d\n",
265              thread->id, thread->unix_pid, thread->unix_tid, thread->teb, thread->state );
266 }
267
268 static int thread_signaled( struct object *obj, struct thread *thread )
269 {
270     struct thread *mythread = (struct thread *)obj;
271     return (mythread->state == TERMINATED);
272 }
273
274 /* get a thread pointer from a thread id (and increment the refcount) */
275 struct thread *get_thread_from_id( thread_id_t id )
276 {
277     struct object *obj = get_ptid_entry( id );
278
279     if (obj && obj->ops == &thread_ops) return (struct thread *)grab_object( obj );
280     set_win32_error( ERROR_INVALID_THREAD_ID );
281     return NULL;
282 }
283
284 /* get a thread from a handle (and increment the refcount) */
285 struct thread *get_thread_from_handle( obj_handle_t handle, unsigned int access )
286 {
287     return (struct thread *)get_handle_obj( current->process, handle,
288                                             access, &thread_ops );
289 }
290
291 /* find a thread from a Unix pid */
292 struct thread *get_thread_from_pid( int pid )
293 {
294     struct thread *thread;
295
296     LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
297     {
298         if (thread->unix_tid == pid) return thread;
299     }
300     LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
301     {
302         if (thread->unix_pid == pid) return thread;
303     }
304     return NULL;
305 }
306
307 /* set all information about a thread */
308 static void set_thread_info( struct thread *thread,
309                              const struct set_thread_info_request *req )
310 {
311     if (req->mask & SET_THREAD_INFO_PRIORITY)
312         thread->priority = req->priority;
313     if (req->mask & SET_THREAD_INFO_AFFINITY)
314     {
315         if (req->affinity != 1) set_error( STATUS_INVALID_PARAMETER );
316         else thread->affinity = req->affinity;
317     }
318     if (req->mask & SET_THREAD_INFO_TOKEN)
319         security_set_thread_token( thread, req->token );
320 }
321
322 /* stop a thread (at the Unix level) */
323 void stop_thread( struct thread *thread )
324 {
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, 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, base ) == -1) goto done;
745         if (read_thread_int( thread, addr + 8192, 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     remove_process_thread( thread->process, thread );
775     wake_up( &thread->obj, 0 );
776     detach_thread( thread, violent_death ? SIGTERM : 0 );
777     cleanup_thread( 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 /* signal that we are finished booting on the client side */
815 DECL_HANDLER(boot_done)
816 {
817     debug_level = max( debug_level, req->debug_level );
818     if (current == booting_thread)
819     {
820         booting_thread = (struct thread *)~0UL;  /* make sure it doesn't match other threads */
821         lock_master_socket(0);  /* allow other clients now */
822     }
823 }
824
825 /* create a new thread */
826 DECL_HANDLER(new_thread)
827 {
828     struct thread *thread;
829     int request_fd = thread_get_inflight_fd( current, req->request_fd );
830
831     if (request_fd == -1 || fcntl( request_fd, F_SETFL, O_NONBLOCK ) == -1)
832     {
833         if (request_fd != -1) close( request_fd );
834         set_error( STATUS_INVALID_HANDLE );
835         return;
836     }
837
838     if ((thread = create_thread( request_fd, current->process )))
839     {
840         if (req->suspend) thread->suspend++;
841         reply->tid = get_thread_id( thread );
842         if ((reply->handle = alloc_handle( current->process, thread,
843                                            THREAD_ALL_ACCESS, req->inherit )))
844         {
845             /* thread object will be released when the thread gets killed */
846             return;
847         }
848         kill_thread( thread, 1 );
849     }
850 }
851
852 /* initialize a new thread */
853 DECL_HANDLER(init_thread)
854 {
855     int reply_fd = thread_get_inflight_fd( current, req->reply_fd );
856     int wait_fd = thread_get_inflight_fd( current, req->wait_fd );
857
858     if (current->unix_pid != -1)
859     {
860         fatal_protocol_error( current, "init_thread: already running\n" );
861         goto error;
862     }
863     if (reply_fd == -1 || fcntl( reply_fd, F_SETFL, O_NONBLOCK ) == -1)
864     {
865         fatal_protocol_error( current, "bad reply fd\n" );
866         goto error;
867     }
868     if (wait_fd == -1)
869     {
870         fatal_protocol_error( current, "bad wait fd\n" );
871         goto error;
872     }
873     if (!(current->reply_fd = create_anonymous_fd( &thread_fd_ops, reply_fd, &current->obj )))
874     {
875         reply_fd = -1;
876         fatal_protocol_error( current, "could not allocate reply fd\n" );
877         goto error;
878     }
879     if (!(current->wait_fd  = create_anonymous_fd( &thread_fd_ops, wait_fd, &current->obj )))
880         return;
881
882     current->unix_pid = req->unix_pid;
883     current->unix_tid = req->unix_tid;
884     current->teb      = req->teb;
885
886     if (current->suspend + current->process->suspend > 0) stop_thread( current );
887     if (current->process->running_threads > 1)
888         generate_debug_event( current, CREATE_THREAD_DEBUG_EVENT, req->entry );
889
890     reply->pid     = get_process_id( current->process );
891     reply->tid     = get_thread_id( current );
892     reply->boot    = (current == booting_thread);
893     reply->version = SERVER_PROTOCOL_VERSION;
894     return;
895
896  error:
897     if (reply_fd != -1) close( reply_fd );
898     if (wait_fd != -1) close( wait_fd );
899 }
900
901 /* terminate a thread */
902 DECL_HANDLER(terminate_thread)
903 {
904     struct thread *thread;
905
906     reply->self = 0;
907     reply->last = 0;
908     if ((thread = get_thread_from_handle( req->handle, THREAD_TERMINATE )))
909     {
910         thread->exit_code = req->exit_code;
911         if (thread != current) kill_thread( thread, 1 );
912         else
913         {
914             reply->self = 1;
915             reply->last = (thread->process->running_threads == 1);
916         }
917         release_object( thread );
918     }
919 }
920
921 /* open a handle to a thread */
922 DECL_HANDLER(open_thread)
923 {
924     struct thread *thread = get_thread_from_id( req->tid );
925
926     reply->handle = 0;
927     if (thread)
928     {
929         reply->handle = alloc_handle( current->process, thread, req->access, req->inherit );
930         release_object( thread );
931     }
932 }
933
934 /* fetch information about a thread */
935 DECL_HANDLER(get_thread_info)
936 {
937     struct thread *thread;
938     obj_handle_t handle = req->handle;
939
940     if (!handle) thread = get_thread_from_id( req->tid_in );
941     else thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION );
942
943     if (thread)
944     {
945         reply->pid            = get_process_id( thread->process );
946         reply->tid            = get_thread_id( thread );
947         reply->teb            = thread->teb;
948         reply->exit_code      = (thread->state == TERMINATED) ? thread->exit_code : STILL_ACTIVE;
949         reply->priority       = thread->priority;
950         reply->affinity       = thread->affinity;
951         reply->creation_time  = thread->creation_time;
952         reply->exit_time      = thread->exit_time;
953
954         release_object( thread );
955     }
956 }
957
958 /* set information about a thread */
959 DECL_HANDLER(set_thread_info)
960 {
961     struct thread *thread;
962
963     if ((thread = get_thread_from_handle( req->handle, THREAD_SET_INFORMATION )))
964     {
965         set_thread_info( thread, req );
966         release_object( thread );
967     }
968 }
969
970 /* suspend a thread */
971 DECL_HANDLER(suspend_thread)
972 {
973     struct thread *thread;
974
975     if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
976     {
977         if (thread->state == TERMINATED) set_error( STATUS_ACCESS_DENIED );
978         else reply->count = suspend_thread( thread );
979         release_object( thread );
980     }
981 }
982
983 /* resume a thread */
984 DECL_HANDLER(resume_thread)
985 {
986     struct thread *thread;
987
988     if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
989     {
990         if (thread->state == TERMINATED) set_error( STATUS_ACCESS_DENIED );
991         else reply->count = resume_thread( thread );
992         release_object( thread );
993     }
994 }
995
996 /* select on a handle list */
997 DECL_HANDLER(select)
998 {
999     int count = get_req_data_size() / sizeof(int);
1000     select_on( count, req->cookie, get_req_data(), req->flags, &req->timeout, req->signal );
1001 }
1002
1003 /* queue an APC for a thread */
1004 DECL_HANDLER(queue_apc)
1005 {
1006     struct thread *thread;
1007     if ((thread = get_thread_from_handle( req->handle, THREAD_SET_CONTEXT )))
1008     {
1009         thread_queue_apc( thread, NULL, req->func, APC_USER, !req->user,
1010                           req->arg1, req->arg2, req->arg3 );
1011         release_object( thread );
1012     }
1013 }
1014
1015 /* get next APC to call */
1016 DECL_HANDLER(get_apc)
1017 {
1018     struct thread_apc *apc;
1019
1020     for (;;)
1021     {
1022         if (!(apc = thread_dequeue_apc( current, !req->alertable )))
1023         {
1024             /* no more APCs */
1025             reply->func = NULL;
1026             reply->type = APC_NONE;
1027             return;
1028         }
1029         /* Optimization: ignore APCs that have a NULL func; they are only used
1030          * to wake up a thread, but since we got here the thread woke up already.
1031          * Exception: for APC_ASYNC_IO, func == NULL is legal.
1032          */
1033         if (apc->func || apc->type == APC_ASYNC_IO) break;
1034         free( apc );
1035     }
1036     reply->func = apc->func;
1037     reply->type = apc->type;
1038     reply->arg1 = apc->arg1;
1039     reply->arg2 = apc->arg2;
1040     reply->arg3 = apc->arg3;
1041     free( apc );
1042 }
1043
1044 /* fetch a selector entry for a thread */
1045 DECL_HANDLER(get_selector_entry)
1046 {
1047     struct thread *thread;
1048     if ((thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION )))
1049     {
1050         get_selector_entry( thread, req->entry, &reply->base, &reply->limit, &reply->flags );
1051         release_object( thread );
1052     }
1053 }