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